move network tools
[reactos.git] / reactos / subsys / system / explorer / services / startup.c
1 /*
2 * Copyright (C) 2002 Andreas Mohr
3 * Copyright (C) 2002 Shachar Shemesh
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19
20 /* Based on the Wine "bootup" handler application
21 *
22 * This app handles the various "hooks" windows allows for applications to perform
23 * as part of the bootstrap process. Theses are roughly devided into three types.
24 * Knowledge base articles that explain this are 137367, 179365, 232487 and 232509.
25 * Also, 119941 has some info on grpconv.exe
26 * The operations performed are (by order of execution):
27 *
28 * Preboot (prior to fully loading the Windows kernel):
29 * - wininit.exe (rename operations left in wininit.ini - Win 9x only)
30 * - PendingRenameOperations (rename operations left in the registry - Win NT+ only)
31 *
32 * Startup (before the user logs in)
33 * - Services (NT, ?semi-synchronous?, not implemented yet)
34 * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce (9x, asynch)
35 * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices (9x, asynch)
36 *
37 * After log in
38 * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce (all, synch)
39 * - HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run (all, asynch)
40 * - HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run (all, asynch)
41 * - Startup folders (all, ?asynch?, no imp)
42 * - HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce (all, asynch)
43 *
44 * Somewhere in there is processing the RunOnceEx entries (also no imp)
45 *
46 * Bugs:
47 * - If a pending rename registry does not start with \??\ the entry is
48 * processed anyways. I'm not sure that is the Windows behaviour.
49 * - Need to check what is the windows behaviour when trying to delete files
50 * and directories that are read-only
51 * - In the pending rename registry processing - there are no traces of the files
52 * processed (requires translations from Unicode to Ansi).
53 */
54
55 #include <stdio.h>
56 #include <windows.h>
57 #include <ctype.h>
58
59 /**
60 * Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
61 * Returns FALSE if there was an error, or otherwise if all is ok.
62 */
63 static BOOL wininit()
64 {
65 return TRUE;
66 }
67
68 static BOOL pendingRename()
69 {
70 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
71 'F','i','l','e','R','e','n','a','m','e',
72 'O','p','e','r','a','t','i','o','n','s',0};
73 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
74 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
75 'C','o','n','t','r','o','l','\\',
76 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
77 WCHAR *buffer=NULL;
78 const WCHAR *src=NULL, *dst=NULL;
79 DWORD dataLength=0;
80 HKEY hSession=NULL;
81 DWORD res;
82
83 printf("Entered\n");
84
85 if ((res=RegOpenKeyExW(HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession))
86 !=ERROR_SUCCESS)
87 {
88 if (res==ERROR_FILE_NOT_FOUND)
89 {
90 printf("The key was not found - skipping\n");
91 res=TRUE;
92 }
93 else
94 {
95 printf("Couldn't open key, error %ld\n", res);
96 res=FALSE;
97 }
98
99 goto end;
100 }
101
102 res=RegQueryValueExW(hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
103 truely a REG_MULTI_SZ anyways */,
104 NULL, &dataLength);
105 if (res==ERROR_FILE_NOT_FOUND)
106 {
107 /* No value - nothing to do. Great! */
108 printf("Value not present - nothing to rename\n");
109 res=TRUE;
110 goto end;
111 }
112
113 if (res!=ERROR_SUCCESS)
114 {
115 printf("Couldn't query value's length (%ld)\n", res);
116 res=FALSE;
117 goto end;
118 }
119
120 buffer=malloc(dataLength);
121 if (buffer==NULL)
122 {
123 printf("Couldn't allocate %lu bytes for the value\n", dataLength);
124 res=FALSE;
125 goto end;
126 }
127
128 res=RegQueryValueExW(hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength);
129 if (res!=ERROR_SUCCESS)
130 {
131 printf("Couldn't query value after successfully querying before (%lu),\n"
132 "please report to wine-devel@winehq.org\n", res);
133 res=FALSE;
134 goto end;
135 }
136
137 /* Make sure that the data is long enough and ends with two NULLs. This
138 * simplifies the code later on.
139 */
140 if (dataLength<2*sizeof(buffer[0]) ||
141 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
142 buffer[dataLength/sizeof(buffer[0])-2]!='\0')
143 {
144 printf("Improper value format - doesn't end with NULL\n");
145 res=FALSE;
146 goto end;
147 }
148
149 for(src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
150 src=dst+lstrlenW(dst)+1)
151 {
152 DWORD dwFlags=0;
153
154 printf("processing next command\n");
155
156 dst=src+lstrlenW(src)+1;
157
158 /* We need to skip the \??\ header */
159 if (src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\')
160 src+=4;
161
162 if (dst[0]=='!')
163 {
164 dwFlags|=MOVEFILE_REPLACE_EXISTING;
165 dst++;
166 }
167
168 if (dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\')
169 dst+=4;
170
171 if (*dst!='\0')
172 {
173 /* Rename the file */
174 MoveFileExW(src, dst, dwFlags);
175 } else
176 {
177 /* Delete the file or directory */
178 res = GetFileAttributesW (src);
179 if (res != (DWORD)-1)
180 {
181 if ((res&FILE_ATTRIBUTE_DIRECTORY)==0)
182 {
183 /* It's a file */
184 DeleteFileW(src);
185 } else
186 {
187 /* It's a directory */
188 RemoveDirectoryW(src);
189 }
190 } else
191 {
192 printf("couldn't get file attributes (%ld)\n", GetLastError());
193 }
194 }
195 }
196
197 if ((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS)
198 {
199 printf("Error deleting the value (%lu)\n", GetLastError());
200 res=FALSE;
201 } else
202 res=TRUE;
203
204 end:
205 if (buffer!=NULL)
206 free(buffer);
207
208 if (hSession!=NULL)
209 RegCloseKey(hSession);
210
211 return res;
212 }
213
214 enum runkeys {
215 RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
216 };
217
218 const WCHAR runkeys_names[][30]=
219 {
220 {'R','u','n',0},
221 {'R','u','n','O','n','c','e',0},
222 {'R','u','n','S','e','r','v','i','c','e','s',0},
223 {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
224 };
225
226 #define INVALID_RUNCMD_RETURN -1
227 /**
228 * This function runs the specified command in the specified dir.
229 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
230 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
231 * [in] wait - whether to wait for the run program to finish before returning.
232 * [in] minimized - Whether to ask the program to run minimized.
233 *
234 * Returns:
235 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
236 * If wait is FALSE - returns 0 if successful.
237 * If wait is TRUE - returns the program's return value.
238 */
239 static int runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
240 {
241 STARTUPINFOW si;
242 PROCESS_INFORMATION info;
243 DWORD exit_code=0;
244
245 memset(&si, 0, sizeof(si));
246 si.cb=sizeof(si);
247 if (minimized)
248 {
249 si.dwFlags=STARTF_USESHOWWINDOW;
250 si.wShowWindow=SW_MINIMIZE;
251 }
252 memset(&info, 0, sizeof(info));
253
254 if (!CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info))
255 {
256 printf("Failed to run command (%ld)\n", GetLastError());
257
258 return INVALID_RUNCMD_RETURN;
259 }
260
261 printf("Successfully ran command\n"); //%s - Created process handle %p\n",
262 //wine_dbgstr_w(cmdline), info.hProcess);
263
264 if (wait)
265 { /* wait for the process to exit */
266 WaitForSingleObject(info.hProcess, INFINITE);
267 GetExitCodeProcess(info.hProcess, &exit_code);
268 }
269
270 CloseHandle(info.hProcess);
271
272 return exit_code;
273 }
274
275 /**
276 * Process a "Run" type registry key.
277 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
278 * opened.
279 * szKeyName is the key holding the actual entries.
280 * bDelete tells whether we should delete each value right before executing it.
281 * bSynchronous tells whether we should wait for the prog to complete before
282 * going on to the next prog.
283 */
284 static BOOL ProcessRunKeys(HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
285 BOOL bSynchronous)
286 {
287 static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
288 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
289 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
290 HKEY hkWin=NULL, hkRun=NULL;
291 LONG res=ERROR_SUCCESS;
292 DWORD i, nMaxCmdLine=0, nMaxValue=0;
293 WCHAR *szCmdLine=NULL;
294 WCHAR *szValue=NULL;
295
296 if (hkRoot==HKEY_LOCAL_MACHINE)
297 wprintf(L"processing %s entries under HKLM\n", szKeyName);
298 else
299 wprintf(L"processing %s entries under HKCU\n", szKeyName);
300
301 if ((res=RegOpenKeyExW(hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin))!=ERROR_SUCCESS)
302 {
303 printf("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%ld)\n",
304 res);
305
306 goto end;
307 }
308
309 if ((res=RegOpenKeyExW(hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun))!=
310 ERROR_SUCCESS)
311 {
312 if (res==ERROR_FILE_NOT_FOUND)
313 {
314 printf("Key doesn't exist - nothing to be done\n");
315
316 res=ERROR_SUCCESS;
317 }
318 else
319 printf("RegOpenKey failed on run key (%ld)\n", res);
320
321 goto end;
322 }
323
324 if ((res=RegQueryInfoKeyW(hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
325 &nMaxCmdLine, NULL, NULL))!=ERROR_SUCCESS)
326 {
327 printf("Couldn't query key info (%ld)\n", res);
328
329 goto end;
330 }
331
332 if (i==0)
333 {
334 printf("No commands to execute.\n");
335
336 res=ERROR_SUCCESS;
337 goto end;
338 }
339
340 if ((szCmdLine=malloc(nMaxCmdLine))==NULL)
341 {
342 printf("Couldn't allocate memory for the commands to be executed\n");
343
344 res=ERROR_NOT_ENOUGH_MEMORY;
345 goto end;
346 }
347
348 if ((szValue=malloc((++nMaxValue)*sizeof(*szValue)))==NULL)
349 {
350 printf("Couldn't allocate memory for the value names\n");
351
352 res=ERROR_NOT_ENOUGH_MEMORY;
353 goto end;
354 }
355
356 while(i>0)
357 {
358 DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
359 DWORD type;
360
361 --i;
362
363 if ((res=RegEnumValueW(hkRun, i, szValue, &nValLength, 0, &type,
364 (LPBYTE)szCmdLine, &nDataLength))!=ERROR_SUCCESS)
365 {
366 printf("Couldn't read in value %ld - %ld\n", i, res);
367
368 continue;
369 }
370
371 if (bDelete && (res=RegDeleteValueW(hkRun, szValue))!=ERROR_SUCCESS)
372 {
373 printf("Couldn't delete value - %ld, %ld. Running command anyways.\n", i, res);
374 }
375
376 if (type!=REG_SZ)
377 {
378 printf("Incorrect type of value #%ld (%ld)\n", i, type);
379
380 continue;
381 }
382
383 if ((res=runCmd(szCmdLine, NULL, bSynchronous, FALSE))==INVALID_RUNCMD_RETURN)
384 {
385 printf("Error running cmd #%ld (%ld)\n", i, GetLastError());
386 }
387
388 printf("Done processing cmd #%ld\n", i);
389 }
390
391 res=ERROR_SUCCESS;
392
393 end:
394 if (hkRun!=NULL)
395 RegCloseKey(hkRun);
396 if (hkWin!=NULL)
397 RegCloseKey(hkWin);
398
399 printf("done\n");
400
401 return res==ERROR_SUCCESS?TRUE:FALSE;
402 }
403
404 /// structure holding startup flags
405 struct op_mask {
406 BOOL w9xonly; /* Perform only operations done on Windows 9x */
407 BOOL ntonly; /* Perform only operations done on Windows NT */
408 BOOL startup; /* Perform the operations that are performed every boot */
409 BOOL preboot; /* Perform file renames typically done before the system starts */
410 BOOL prelogin; /* Perform the operations typically done before the user logs in */
411 BOOL postlogin; /* Operations done after login */
412 };
413
414 static const struct op_mask
415 SESSION_START = {FALSE, FALSE, TRUE, TRUE, TRUE, TRUE},
416 SETUP = {FALSE, FALSE, FALSE, TRUE, TRUE, TRUE};
417 #define DEFAULT SESSION_START
418
419 int startup(int argc, char *argv[])
420 {
421 struct op_mask ops; /* Which of the ops do we want to perform? */
422 /* First, set the current directory to SystemRoot */
423 TCHAR gen_path[MAX_PATH];
424 DWORD res;
425
426 res = GetWindowsDirectory(gen_path, sizeof(gen_path));
427
428 if (res==0)
429 {
430 printf("Couldn't get the windows directory - error %ld\n",
431 GetLastError());
432
433 return 100;
434 }
435
436 if (res>=sizeof(gen_path))
437 {
438 printf("Windows path too long (%ld)\n", res);
439
440 return 100;
441 }
442
443 if (!SetCurrentDirectory(gen_path))
444 {
445 wprintf(L"Cannot set the dir to %s (%ld)\n", gen_path, GetLastError());
446
447 return 100;
448 }
449
450 if (argc>1)
451 {
452 switch(argv[1][0])
453 {
454 case 'r': /* Restart */
455 ops=SETUP;
456 break;
457 case 's': /* Full start */
458 ops=SESSION_START;
459 break;
460 default:
461 ops=DEFAULT;
462 break;
463 }
464 } else
465 ops=DEFAULT;
466
467 /* Perform the ops by order, stopping if one fails, skipping if necessary */
468 /* Shachar: Sorry for the perl syntax */
469 res=(ops.ntonly || !ops.preboot || wininit()) &&
470 (ops.w9xonly || !ops.preboot || pendingRename()) &&
471 (ops.ntonly || !ops.prelogin ||
472 ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE)) &&
473 (ops.ntonly || !ops.prelogin || !ops.startup ||
474 ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE)) &&
475 (!ops.postlogin ||
476 ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE)) &&
477 (!ops.postlogin || !ops.startup ||
478 ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE)) &&
479 (!ops.postlogin || !ops.startup ||
480 ProcessRunKeys(HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE));
481
482 printf("Operation done\n");
483
484 return res?0:101;
485 }