Fix subclassing to support nested messages.
[wine] / programs / wineboot / wineboot.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 /* 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 #include <wine/debug.h>
57
58 WINE_DEFAULT_DEBUG_CHANNEL(wineboot);
59
60 #define MAX_LINE_LENGTH (2*MAX_PATH+2)
61
62 static BOOL GetLine( HANDLE hFile, char *buf, size_t buflen )
63 {
64     int i=0;
65     buf[0]='\0';
66
67     do
68     {
69         DWORD read;
70         if( !ReadFile( hFile, buf, 1, &read, NULL ) || read!=1 )
71         {
72             return FALSE;
73         }
74
75     } while( isspace( *buf ) );
76
77     while( buf[i]!='\n' && i<=buflen &&
78             ReadFile( hFile, buf+i+1, 1, NULL, NULL ) )
79     {
80         ++i;
81     }
82
83
84     if( buf[i]!='\n' )
85     {
86         return FALSE;
87     }
88
89     if( i>0 && buf[i-1]=='\r' )
90         --i;
91
92     buf[i]='\0';
93
94     return TRUE;
95 }
96
97 /* Performs the rename operations dictated in %SystemRoot%\Wininit.ini.
98  * Returns FALSE if there was an error, or otherwise if all is ok.
99  */
100 static BOOL wininit()
101 {
102     const char * const RENAME_FILE="wininit.ini";
103     const char * const RENAME_FILE_TO="wininit.bak";
104     const char * const RENAME_FILE_SECTION="[rename]";
105     char buffer[MAX_LINE_LENGTH];
106     HANDLE hFile;
107
108
109     hFile=CreateFileA(RENAME_FILE, GENERIC_READ,
110                     FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
111                     NULL );
112     
113     if( hFile==INVALID_HANDLE_VALUE )
114     {
115         DWORD err=GetLastError();
116         
117         if( err==ERROR_FILE_NOT_FOUND )
118         {
119             /* No file - nothing to do. Great! */
120             WINE_TRACE("Wininit.ini not present - no renaming to do\n");
121
122             return TRUE;
123         }
124
125         WINE_ERR("There was an error in reading wininit.ini file - %ld\n",
126                 GetLastError() );
127
128         return FALSE;
129     }
130
131     printf("Wine is finalizing your software installation. This may take a few minutes,\n");
132     printf("though it never actually does.\n");
133
134     while( GetLine( hFile, buffer, sizeof(buffer) ) &&
135             lstrcmpiA(buffer,RENAME_FILE_SECTION)!=0  )
136         ; /* Read the lines until we match the rename section */
137
138     while( GetLine( hFile, buffer, sizeof(buffer) ) && buffer[0]!='[' )
139     {
140         /* First, make sure this is not a comment */
141         if( buffer[0]!=';' && buffer[0]!='\0' )
142         {
143             char * value;
144
145             value=strchr(buffer, '=');
146
147             if( value==NULL )
148             {
149                 WINE_WARN("Line with no \"=\" in it in wininit.ini - %s\n",
150                         buffer);
151             } else
152             {
153                 /* split the line into key and value */
154                 *(value++)='\0';
155
156                 if( lstrcmpiA( "NUL", buffer )==0 )
157                 {
158                     WINE_TRACE("Deleting file \"%s\"\n", value );
159                     /* A file to delete */
160                     if( !DeleteFileA( value ) )
161                         WINE_WARN("Error deleting file \"%s\"\n", value);
162                 } else
163                 {
164                     WINE_TRACE("Renaming file \"%s\" to \"%s\"\n", value,
165                             buffer );
166
167                     if( !MoveFileExA(value, buffer, MOVEFILE_COPY_ALLOWED|
168                             MOVEFILE_REPLACE_EXISTING) )
169                     {
170                         WINE_WARN("Error renaming \"%s\" to \"%s\"\n", value,
171                                 buffer );
172                     }
173                 }
174             }
175         }
176     }
177
178     CloseHandle( hFile );
179
180     if( !MoveFileExA( RENAME_FILE, RENAME_FILE_TO, MOVEFILE_REPLACE_EXISTING) )
181     {
182         WINE_ERR("Couldn't rename wininit.ini, error %ld\n", GetLastError() );
183
184         return FALSE;
185     }
186
187     return TRUE;
188 }
189
190 static BOOL pendingRename()
191 {
192     static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
193                                       'F','i','l','e','R','e','n','a','m','e',
194                                       'O','p','e','r','a','t','i','o','n','s',0};
195     static const WCHAR SessionW[] = { 'S','y','s','t','e','m','\\',
196                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
197                                      'C','o','n','t','r','o','l','\\',
198                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
199     WCHAR *buffer=NULL;
200     const WCHAR *src=NULL, *dst=NULL;
201     DWORD dataLength=0;
202     HKEY hSession=NULL;
203     DWORD res;
204
205     WINE_TRACE("Entered\n");
206
207     if( (res=RegOpenKeyExW( HKEY_LOCAL_MACHINE, SessionW, 0, KEY_ALL_ACCESS, &hSession ))
208             !=ERROR_SUCCESS )
209     {
210         if( res==ERROR_FILE_NOT_FOUND )
211         {
212             WINE_TRACE("The key was not found - skipping\n");
213             res=TRUE;
214         }
215         else
216         {
217             WINE_ERR("Couldn't open key, error %ld\n", res );
218             res=FALSE;
219         }
220
221         goto end;
222     }
223
224     res=RegQueryValueExW( hSession, ValueName, NULL, NULL /* The value type does not really interest us, as it is not
225                                                              truely a REG_MULTI_SZ anyways */,
226             NULL, &dataLength );
227     if( res==ERROR_FILE_NOT_FOUND )
228     {
229         /* No value - nothing to do. Great! */
230         WINE_TRACE("Value not present - nothing to rename\n");
231         res=TRUE;
232         goto end;
233     }
234
235     if( res!=ERROR_SUCCESS )
236     {
237         WINE_ERR("Couldn't query value's length (%ld)\n", res );
238         res=FALSE;
239         goto end;
240     }
241
242     buffer=malloc( dataLength );
243     if( buffer==NULL )
244     {
245         WINE_ERR("Couldn't allocate %lu bytes for the value\n", dataLength );
246         res=FALSE;
247         goto end;
248     }
249
250     res=RegQueryValueExW( hSession, ValueName, NULL, NULL, (LPBYTE)buffer, &dataLength );
251     if( res!=ERROR_SUCCESS )
252     {
253         WINE_ERR("Couldn't query value after successfully querying before (%lu),\n"
254                 "please report to wine-devel@winehq.org\n", res);
255         res=FALSE;
256         goto end;
257     }
258
259     /* Make sure that the data is long enough and ends with two NULLs. This
260      * simplifies the code later on.
261      */
262     if( dataLength<2*sizeof(buffer[0]) ||
263             buffer[dataLength/sizeof(buffer[0])-1]!='\0' ||
264             buffer[dataLength/sizeof(buffer[0])-2]!='\0' )
265     {
266         WINE_ERR("Improper value format - doesn't end with NULL\n");
267         res=FALSE;
268         goto end;
269     }
270
271     for( src=buffer; (src-buffer)*sizeof(src[0])<dataLength && *src!='\0';
272             src=dst+lstrlenW(dst)+1 )
273     {
274         DWORD dwFlags=0;
275
276         WINE_TRACE("processing next command\n");
277
278         dst=src+lstrlenW(src)+1;
279
280         /* We need to skip the \??\ header */
281         if( src[0]=='\\' && src[1]=='?' && src[2]=='?' && src[3]=='\\' )
282             src+=4;
283
284         if( dst[0]=='!' )
285         {
286             dwFlags|=MOVEFILE_REPLACE_EXISTING;
287             dst++;
288         }
289
290         if( dst[0]=='\\' && dst[1]=='?' && dst[2]=='?' && dst[3]=='\\' )
291             dst+=4;
292
293         if( *dst!='\0' )
294         {
295             /* Rename the file */
296             MoveFileExW( src, dst, dwFlags );
297         } else
298         {
299             /* Delete the file or directory */
300             if( (res=GetFileAttributesW(src))!=INVALID_FILE_ATTRIBUTES )
301             {
302                 if( (res&FILE_ATTRIBUTE_DIRECTORY)==0 )
303                 {
304                     /* It's a file */
305                     DeleteFileW(src);
306                 } else
307                 {
308                     /* It's a directory */
309                     RemoveDirectoryW(src);
310                 }
311             } else
312             {
313                 WINE_ERR("couldn't get file attributes (%ld)\n", GetLastError() );
314             }
315         }
316     }
317
318     if((res=RegDeleteValueW(hSession, ValueName))!=ERROR_SUCCESS )
319     {
320         WINE_ERR("Error deleting the value (%lu)\n", GetLastError() );
321         res=FALSE;
322     } else
323         res=TRUE;
324     
325 end:
326     if( buffer!=NULL )
327         free(buffer);
328
329     if( hSession!=NULL )
330         RegCloseKey( hSession );
331
332     return res;
333 }
334
335 enum runkeys {
336     RUNKEY_RUN, RUNKEY_RUNONCE, RUNKEY_RUNSERVICES, RUNKEY_RUNSERVICESONCE
337 };
338
339 const WCHAR runkeys_names[][30]=
340 {
341     {'R','u','n',0},
342     {'R','u','n','O','n','c','e',0},
343     {'R','u','n','S','e','r','v','i','c','e','s',0},
344     {'R','u','n','S','e','r','v','i','c','e','s','O','n','c','e',0}
345 };
346
347 #define INVALID_RUNCMD_RETURN -1
348 /*
349  * This function runs the specified command in the specified dir.
350  * [in,out] cmdline - the command line to run. The function may change the passed buffer.
351  * [in] dir - the dir to run the command in. If it is NULL, then the current dir is used.
352  * [in] wait - whether to wait for the run program to finish before returning.
353  * [in] minimized - Whether to ask the program to run minimized.
354  *
355  * Returns:
356  * If running the process failed, returns INVALID_RUNCMD_RETURN. Use GetLastError to get the error code.
357  * If wait is FALSE - returns 0 if successful.
358  * If wait is TRUE - returns the program's return value.
359  */
360 static DWORD runCmd(LPWSTR cmdline, LPCWSTR dir, BOOL wait, BOOL minimized)
361 {
362     STARTUPINFOW si;
363     PROCESS_INFORMATION info;
364     DWORD exit_code=0;
365
366     memset(&si, 0, sizeof(si));
367     si.cb=sizeof(si);
368     if( minimized )
369     {
370         si.dwFlags=STARTF_USESHOWWINDOW;
371         si.wShowWindow=SW_MINIMIZE;
372     }
373     memset(&info, 0, sizeof(info));
374
375     if( !CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, dir, &si, &info) )
376     {
377         WINE_ERR("Failed to run command (%ld)\n", GetLastError() );
378
379         return INVALID_RUNCMD_RETURN;
380     }
381
382     WINE_TRACE("Successfully ran command %s - Created process handle %p\n",
383                wine_dbgstr_w(cmdline), info.hProcess );
384
385     if(wait)
386     {   /* wait for the process to exit */
387         WaitForSingleObject(info.hProcess, INFINITE);
388         GetExitCodeProcess(info.hProcess, &exit_code);
389     }
390
391     CloseHandle( info.hProcess );
392
393     return exit_code;
394 }
395
396 /*
397  * Process a "Run" type registry key.
398  * hkRoot is the HKEY from which "Software\Microsoft\Windows\CurrentVersion" is
399  *      opened.
400  * szKeyName is the key holding the actual entries.
401  * bDelete tells whether we should delete each value right before executing it.
402  * bSynchronous tells whether we should wait for the prog to complete before
403  *      going on to the next prog.
404  */
405 static BOOL ProcessRunKeys( HKEY hkRoot, LPCWSTR szKeyName, BOOL bDelete,
406         BOOL bSynchronous )
407 {
408     static const WCHAR WINKEY_NAME[]={'S','o','f','t','w','a','r','e','\\',
409         'M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s','\\',
410         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0};
411     HKEY hkWin=NULL, hkRun=NULL;
412     DWORD res=ERROR_SUCCESS;
413     DWORD i, nMaxCmdLine=0, nMaxValue=0;
414     WCHAR *szCmdLine=NULL;
415     WCHAR *szValue=NULL;
416
417     if (hkRoot==HKEY_LOCAL_MACHINE)
418         WINE_TRACE("processing %s entries under HKLM\n",wine_dbgstr_w(szKeyName) );
419     else
420         WINE_TRACE("processing %s entries under HKCU\n",wine_dbgstr_w(szKeyName) );
421
422     if( (res=RegOpenKeyExW( hkRoot, WINKEY_NAME, 0, KEY_READ, &hkWin ))!=ERROR_SUCCESS )
423     {
424         WINE_ERR("RegOpenKey failed on Software\\Microsoft\\Windows\\CurrentVersion (%ld)\n",
425                 res);
426
427         goto end;
428     }
429
430     if( (res=RegOpenKeyExW( hkWin, szKeyName, 0, bDelete?KEY_ALL_ACCESS:KEY_READ, &hkRun ))!=
431             ERROR_SUCCESS)
432     {
433         if( res==ERROR_FILE_NOT_FOUND )
434         {
435             WINE_TRACE("Key doesn't exist - nothing to be done\n");
436
437             res=ERROR_SUCCESS;
438         }
439         else
440             WINE_ERR("RegOpenKey failed on run key (%ld)\n", res);
441
442         goto end;
443     }
444     
445     if( (res=RegQueryInfoKeyW( hkRun, NULL, NULL, NULL, NULL, NULL, NULL, &i, &nMaxValue,
446                     &nMaxCmdLine, NULL, NULL ))!=ERROR_SUCCESS )
447     {
448         WINE_ERR("Couldn't query key info (%ld)\n", res );
449
450         goto end;
451     }
452
453     if( i==0 )
454     {
455         WINE_TRACE("No commands to execute.\n");
456
457         res=ERROR_SUCCESS;
458         goto end;
459     }
460     
461     if( (szCmdLine=malloc(nMaxCmdLine))==NULL )
462     {
463         WINE_ERR("Couldn't allocate memory for the commands to be executed\n");
464
465         res=ERROR_NOT_ENOUGH_MEMORY;
466         goto end;
467     }
468
469     if( (szValue=malloc((++nMaxValue)*sizeof(*szValue)))==NULL )
470     {
471         WINE_ERR("Couldn't allocate memory for the value names\n");
472
473         res=ERROR_NOT_ENOUGH_MEMORY;
474         goto end;
475     }
476     
477     while( i>0 )
478     {
479         DWORD nValLength=nMaxValue, nDataLength=nMaxCmdLine;
480         DWORD type;
481
482         --i;
483
484         if( (res=RegEnumValueW( hkRun, i, szValue, &nValLength, 0, &type,
485                         (LPBYTE)szCmdLine, &nDataLength ))!=ERROR_SUCCESS )
486         {
487             WINE_ERR("Couldn't read in value %ld - %ld\n", i, res );
488
489             continue;
490         }
491
492         if( bDelete && (res=RegDeleteValueW( hkRun, szValue ))!=ERROR_SUCCESS )
493         {
494             WINE_ERR("Couldn't delete value - %ld, %ld. Running command anyways.\n", i, res );
495         }
496         
497         if( type!=REG_SZ )
498         {
499             WINE_ERR("Incorrect type of value #%ld (%ld)\n", i, type );
500
501             continue;
502         }
503
504         if( (res=runCmd(szCmdLine, NULL, bSynchronous, FALSE ))==INVALID_RUNCMD_RETURN )
505         {
506             WINE_ERR("Error running cmd #%ld (%ld)\n", i, GetLastError() );
507         }
508
509         WINE_TRACE("Done processing cmd #%ld\n", i);
510     }
511
512     res=ERROR_SUCCESS;
513
514 end:
515     if( hkRun!=NULL )
516         RegCloseKey( hkRun );
517     if( hkWin!=NULL )
518         RegCloseKey( hkWin );
519
520     WINE_TRACE("done\n");
521
522     return res==ERROR_SUCCESS?TRUE:FALSE;
523 }
524
525 struct op_mask {
526     BOOL w9xonly; /* Perform only operations done on Windows 9x */
527     BOOL ntonly; /* Perform only operations done on Windows NT */
528     BOOL startup; /* Perform the operations that are performed every boot */
529     BOOL preboot; /* Perform file renames typically done before the system starts */
530     BOOL prelogin; /* Perform the operations typically done before the user logs in */
531     BOOL postlogin; /* Operations done after login */
532 };
533
534 static const struct op_mask SESSION_START={FALSE, FALSE, TRUE, TRUE, TRUE, TRUE},
535     SETUP={FALSE, FALSE, FALSE, TRUE, TRUE, TRUE};
536 #define DEFAULT SESSION_START
537
538 int main( int argc, char *argv[] )
539 {
540     struct op_mask ops; /* Which of the ops do we want to perform? */
541     /* First, set the current directory to SystemRoot */
542     TCHAR gen_path[MAX_PATH];
543     DWORD res;
544
545     res=GetWindowsDirectory( gen_path, sizeof(gen_path) );
546     
547     if( res==0 )
548     {
549         WINE_ERR("Couldn't get the windows directory - error %ld\n",
550                 GetLastError() );
551
552         return 100;
553     }
554
555     if( res>=sizeof(gen_path) )
556     {
557         WINE_ERR("Windows path too long (%ld)\n", res );
558
559         return 100;
560     }
561
562     if( !SetCurrentDirectory( gen_path ) )
563     {
564         WINE_ERR("Cannot set the dir to %s (%ld)\n", gen_path, GetLastError() );
565
566         return 100;
567     }
568
569     if( argc>1 )
570     {
571         switch( argv[1][0] )
572         {
573         case 'r': /* Restart */
574             ops=SETUP;
575             break;
576         case 's': /* Full start */
577             ops=SESSION_START;
578             break;
579         default:
580             ops=DEFAULT;
581             break;
582         }
583     } else
584         ops=DEFAULT;
585
586     /* Perform the ops by order, stopping if one fails, skipping if necessary */
587     /* Shachar: Sorry for the perl syntax */
588     res=(ops.ntonly || !ops.preboot || wininit())&&
589         (ops.w9xonly || !ops.preboot || pendingRename()) &&
590         (ops.ntonly || !ops.prelogin ||
591          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICESONCE],
592                 TRUE, FALSE )) &&
593         (ops.ntonly || !ops.prelogin || !ops.startup ||
594          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNSERVICES],
595                 FALSE, FALSE )) &&
596         (!ops.postlogin ||
597          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUNONCE],
598                 TRUE, TRUE )) &&
599         (!ops.postlogin || !ops.startup ||
600          ProcessRunKeys( HKEY_LOCAL_MACHINE, runkeys_names[RUNKEY_RUN],
601                 FALSE, FALSE )) &&
602         (!ops.postlogin || !ops.startup ||
603          ProcessRunKeys( HKEY_CURRENT_USER, runkeys_names[RUNKEY_RUN],
604                 FALSE, FALSE ));
605
606     WINE_TRACE("Operation done\n");
607
608     return res?0:101;
609 }