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