[EXPLORER][EXPLORER_NEW]
[reactos.git] / base / shell / 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
58 EXTERN_C HRESULT WINAPI SHCreateSessionKey(REGSAM samDesired, PHKEY phKey);
59
60 /**
61 * Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
62 * Returns FALSE if there was an error, or otherwise if all is ok.
63 */
64 static BOOL wininit()
65 {
66 return TRUE;
67 }
68
69 static BOOL pendingRename()
70 {
71 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
72 'F','i','l','e','R','e','n','a','m','e',
73 'O','p','e','r','a','t','i','o','n','s',0};
74 static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
75 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
76 'C','o','n','t','r','o','l','\\',
77 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
78 WCHAR *buffer=NULL;
79 const WCHAR *src=NULL, *dst=NULL;
80 DWORD dataLength=0;
81 HKEY hSession=NULL;
82 DWORD res;
83
84 printf("Entered\n");
85
86 if ((res=RegOpenKeyExW(HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession))
87 !=ERROR_SUCCESS)
88 {
89 if (res==ERROR_FILE_NOT_FOUND)
90 {
91 printf("The key was not found - skipping\n");
92 res=TRUE;
93 }
94 else
95 {
96 printf("Couldn't open key, error %lu\n", res);
97 res=FALSE;
98 }
99
100 goto end;
101 }
102
103 res=RegQueryValueExW(hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
104 truely a REG_MULTI_SZ anyways */,
105 NULL, &dataLength);
106 if (res==ERROR_FILE_NOT_FOUND)
107 {
108 /* No value - nothing to do. Great! */
109 printf("Value not present - nothing to rename\n");
110 res=TRUE;
111 goto end;
112 }
113
114 if (res!=ERROR_SUCCESS)
115 {
116 printf("Couldn't query value's length (%lu)\n", res);
117 res=FALSE;
118 goto end;
119 }
120
121 buffer=malloc(dataLength);
122 if (buffer==NULL)
123 {
124 printf("Couldn't allocate %lu bytes for the value\n", dataLength);
125 res=FALSE;
126 goto end;
127 }
128
129 res=RegQueryValueExW(hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength);
130 if (res!=ERROR_SUCCESS)
131 {
132 printf("Couldn't query value after successfully querying before (%lu),\n"
133 "please report to wine-devel@winehq.org\n", res);
134 res=FALSE;
135 goto end;
136 }
137
138 /* Make sure that the data is long enough and ends with two NULLs. This
139 * simplifies the code later on.
140 */
141 if (dataLength<2*sizeof(buffer[0]) ||
142 buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
143 buffer[dataLength/sizeof(buffer[0])-2]!='\0')
144 {
145 printf("Improper value format - doesn't end with NULL\n");
146 res=FALSE;
147 goto end;
148 }
149
150 for(src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
151 src=dst+lstrlenW(dst)+1)
152 {
153 DWORD dwFlags=0;
154
155 printf("processing next command\n");
156
157 dst=src+lstrlenW(src)+1;
158
159 /* We need to skip the \??\ header */
160 if (src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\')
161 src+=4;
162
163 if (dst[0]=='!')
164 {
165 dwFlags|=MOVEFILE_REPLACE_EXISTING;
166 dst++;
167 }
168
169 if (dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\')
170 dst+=4;
171
172 if (*dst!='\0')
173 {
174 /* Rename the file */
175 MoveFileExW(src, dst, dwFlags);
176 } else
177 {
178 /* Delete the file or directory */
179 res = GetFileAttributesW (src);
180 if (res != (DWORD)-1)
181 {
182 if ((res&FILE_ATTRIBUTE_DIRECTORY)==0)
183 {
184 /* It's a file */
185 DeleteFileW(src);
186 } else
187 {
188 /* It's a directory */
189 RemoveDirectoryW(src);
190 }
191 } else
192 {
193 printf("couldn't get file attributes (%ld)\n", GetLastError());
194 }
195 }
196 }
197
198 if ((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS)
199 {
200 printf("Error deleting the value (%lu)\n", GetLastError());
201 res=FALSE;
202 } else
203 res=TRUE;
204
205 end:
206 if (buffer!=NULL)
207 free(buffer);
208
209 if (hSession!=NULL)
210 RegCloseKey(hSession);
211
212 return res;
213 }
214
215 enum runkeys {
216 RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
217 };
218
219 const WCHAR runkeys_names[][30]=
220 {
221 {'R','u','n',0},
222 {'R','u','n','O','n','c','e',0},
223 {'R','u','n','S','e','r','v','i','c','e','s',0},
224 {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
225 };
226
227 #define INVALID_RUNCMD_RETURN -1
228 /**
229 * This function runs the specified command in the specified dir.
230 * [in,out] cmdline - the command line to run. The function may change the passed buffer.
231 * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
232 * [in] wait - whether to wait for the run program to finish before returning.
233 * [in] minimized - Whether to ask the program to run minimized.
234 *
235 * Returns:
236 * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
237 * If wait is FALSE - returns 0 if successful.
238 * If wait is TRUE - returns the program's return value.
239 */
240 static int runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
241 {
242 STARTUPINFOW si;
243 PROCESS_INFORMATION info;
244 DWORD exit_code=0;
245 WCHAR szCmdLineExp[MAX_PATH+1]= L"\0";
246
247 ExpandEnvironmentStringsW(cmdline, szCmdLineExp, sizeof(szCmdLineExp) / sizeof(WCHAR));
248
249 memset(&si, 0, sizeof(si));
250 si.cb=sizeof(si);
251 if (minimized)
252 {
253 si.dwFlags=STARTF_USESHOWWINDOW;
254 si.wShowWindow=SW_MINIMIZE;
255 }
256 memset(&info, 0, sizeof(info));
257
258 if (!CreateProcessW(NULL, szCmdLineExp, NULL, NULL, FALSE, 0, NULL, dir, &si, &info))
259 {
260 printf("Failed to run command (%ld)\n", GetLastError());
261
262 return INVALID_RUNCMD_RETURN;
263 }
264
265 printf("Successfully ran command\n"); //%s - Created process handle %p\n",
266 //wine_dbgstr_w(szCmdLineExp), info.hProcess);
267
268 if (wait)
269 { /* wait for the process to exit */
270 WaitForSingleObject(info.hProcess, INFINITE);
271 GetExitCodeProcess(info.hProcess, &exit_code);
272 }
273
274 CloseHandle(info.hThread);
275 CloseHandle(info.hProcess);
276
277 return exit_code;
278 }
279
280 /**
281 * Process a "Run" type registry key.
282 * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
283 * opened.
284 * szKeyName is the key holding the actual entries.
285 * bDelete tells whether we should delete each value right before executing it.
286 * bSynchronous tells whether we should wait for the prog to complete before
287 * going on to the next prog.
288 */
289 static BOOL ProcessRunKeys(HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
290 BOOL bSynchronous)
291 {
292 static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
293 'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
294 'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
295 HKEY hkWin=NULL, hkRun=NULL;
296 LONG res=ERROR_SUCCESS;
297 DWORD i, nMaxCmdLine=0, nMaxValue=0;
298 WCHAR *szCmdLine=NULL;
299 WCHAR *szValue=NULL;
300
301 if (hkRoot==HKEY_LOCAL_MACHINE)
302 wprintf(L"processing %s entries under HKLM\n", szKeyName);
303 else
304 wprintf(L"processing %s entries under HKCU\n", szKeyName);
305
306 if ((res=RegOpenKeyExW(hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin))!=ERROR_SUCCESS)
307 {
308 printf("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%ld)\n",
309 res);
310
311 goto end;
312 }
313
314 if ((res=RegOpenKeyExW(hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun))!=
315 ERROR_SUCCESS)
316 {
317 if (res==ERROR_FILE_NOT_FOUND)
318 {
319 printf("Key doesn't exist - nothing to be done\n");
320
321 res=ERROR_SUCCESS;
322 }
323 else
324 printf("RegOpenKey failed on run key (%ld)\n", res);
325
326 goto end;
327 }
328
329 if ((res=RegQueryInfoKeyW(hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
330 &nMaxCmdLine, NULL, NULL))!=ERROR_SUCCESS)
331 {
332 printf("Couldn't query key info (%ld)\n", res);
333
334 goto end;
335 }
336
337 if (i==0)
338 {
339 printf("No commands to execute.\n");
340
341 res=ERROR_SUCCESS;
342 goto end;
343 }
344
345 if ((szCmdLine=malloc(nMaxCmdLine))==NULL)
346 {
347 printf("Couldn't allocate memory for the commands to be executed\n");
348
349 res=ERROR_NOT_ENOUGH_MEMORY;
350 goto end;
351 }
352
353 if ((szValue=malloc((++nMaxValue)*sizeof(*szValue)))==NULL)
354 {
355 printf("Couldn't allocate memory for the value names\n");
356
357 free(szCmdLine);
358 res=ERROR_NOT_ENOUGH_MEMORY;
359 goto end;
360 }
361
362 while(i>0)
363 {
364 DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
365 DWORD type;
366
367 --i;
368
369 if ((res=RegEnumValueW(hkRun, i, szValue, &nValLength, 0, &type,
370 (LPBYTE)szCmdLine, &nDataLength))!=ERROR_SUCCESS)
371 {
372 printf("Couldn't read in value %lu - %ld\n", i, res);
373
374 continue;
375 }
376
377 /* safe mode - force to run if prefixed with asterisk */
378 if (GetSystemMetrics(SM_CLEANBOOT) && (szValue[0] != L'*')) continue;
379
380 if (bDelete && (res=RegDeleteValueW(hkRun, szValue))!=ERROR_SUCCESS)
381 {
382 printf("Couldn't delete value - %lu, %ld. Running command anyways.\n", i, res);
383 }
384
385 if (type!=REG_SZ)
386 {
387 printf("Incorrect type of value #%lu (%lu)\n", i, type);
388
389 continue;
390 }
391
392 if ((res=runCmd(szCmdLine, NULL, bSynchronous, FALSE))==INVALID_RUNCMD_RETURN)
393 {
394 printf("Error running cmd #%lu (%ld)\n", i, GetLastError());
395 }
396
397 printf("Done processing cmd #%lu\n", i);
398 }
399
400 free(szValue);
401 free(szCmdLine);
402 res=ERROR_SUCCESS;
403
404 end:
405 if (hkRun!=NULL)
406 RegCloseKey(hkRun);
407 if (hkWin!=NULL)
408 RegCloseKey(hkWin);
409
410 printf("done\n");
411
412 return res==ERROR_SUCCESS?TRUE:FALSE;
413 }
414
415 /// structure holding startup flags
416 struct op_mask {
417 BOOL w9xonly; /* Perform only operations done on Windows 9x */
418 BOOL ntonly; /* Perform only operations done on Windows NT */
419 BOOL startup; /* Perform the operations that are performed every boot */
420 BOOL preboot; /* Perform file renames typically done before the system starts */
421 BOOL prelogin; /* Perform the operations typically done before the user logs in */
422 BOOL postlogin; /* Operations done after login */
423 };
424
425 static const struct op_mask
426 SESSION_START = {FALSE, FALSE, TRUE, TRUE, TRUE, TRUE},
427 SETUP = {FALSE, FALSE, FALSE, TRUE, TRUE, TRUE};
428 #define DEFAULT SESSION_START
429
430 int startup(int argc, const char *argv[])
431 {
432 struct op_mask ops; /* Which of the ops do we want to perform? */
433 /* First, set the current directory to SystemRoot */
434 TCHAR gen_path[MAX_PATH];
435 DWORD res;
436 HKEY hSessionKey, hKey;
437 HRESULT hr;
438
439 res = GetWindowsDirectory(gen_path, sizeof(gen_path));
440
441 if (res==0)
442 {
443 printf("Couldn't get the windows directory - error %ld\n",
444 GetLastError());
445
446 return 100;
447 }
448
449 if (!SetCurrentDirectory(gen_path))
450 {
451 wprintf(L"Cannot set the dir to %s (%ld)\n", gen_path, GetLastError());
452
453 return 100;
454 }
455
456 hr = SHCreateSessionKey(KEY_WRITE, &hSessionKey);
457 if (SUCCEEDED(hr))
458 {
459 LONG Error;
460 DWORD dwDisp;
461
462 Error = RegCreateKeyEx(hSessionKey, L"StartupHasBeenRun", 0, NULL, REG_OPTION_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp);
463 RegCloseKey(hSessionKey);
464 if (Error == ERROR_SUCCESS)
465 {
466 RegCloseKey(hKey);
467 if (dwDisp == REG_OPENED_EXISTING_KEY)
468 {
469 /* Startup programs has already been run */
470 return 0;
471 }
472 }
473 }
474
475 if (argc > 1)
476 {
477 switch(argv[1][0])
478 {
479 case 'r': /* Restart */
480 ops = SETUP;
481 break;
482 case 's': /* Full start */
483 ops = SESSION_START;
484 break;
485 default:
486 ops = DEFAULT;
487 break;
488 }
489 } else
490 ops = DEFAULT;
491
492 /* do not run certain items in Safe Mode */
493 if(GetSystemMetrics(SM_CLEANBOOT)) ops.startup = FALSE;
494
495 /* Perform the ops by order, stopping if one fails, skipping if necessary */
496 /* Shachar: Sorry for the perl syntax */
497 res = TRUE;
498 if (res && !ops.ntonly && ops.preboot)
499 res = wininit();
500 if (res && !ops.w9xonly && ops.preboot)
501 res = pendingRename();
502 if (res && !ops.ntonly && ops.prelogin)
503 res = ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE], TRUE, FALSE);
504 if (res && !ops.ntonly && ops.prelogin && ops.startup)
505 res = ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES], FALSE, FALSE);
506 if (res && ops.postlogin)
507 res = ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE], TRUE, TRUE);
508 if (res && ops.postlogin && ops.startup)
509 res = ProcessRunKeys(HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN], FALSE, FALSE);
510 if (res && ops.postlogin && ops.startup)
511 res = ProcessRunKeys(HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN], FALSE, FALSE);
512 if (res && ops.postlogin && ops.startup)
513 res = ProcessRunKeys(HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUNONCE], TRUE, FALSE);
514
515 printf("Operation done\n");
516
517 return res ? 0 : 101;
518 }