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