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