msi: Include run mode in fixmes.
[wine] / dlls / setupapi / install.c
1 /*
2  * Setupapi install routines
3  *
4  * Copyright 2002 Alexandre Julliard for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winreg.h"
28 #include "winternl.h"
29 #include "winerror.h"
30 #include "wingdi.h"
31 #include "winuser.h"
32 #include "winnls.h"
33 #include "winsvc.h"
34 #include "shlobj.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "setupapi.h"
38 #include "setupapi_private.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
43
44 /* info passed to callback functions dealing with files */
45 struct files_callback_info
46 {
47     HSPFILEQ queue;
48     PCWSTR   src_root;
49     UINT     copy_flags;
50     HINF     layout;
51 };
52
53 /* info passed to callback functions dealing with the registry */
54 struct registry_callback_info
55 {
56     HKEY default_root;
57     BOOL delete;
58 };
59
60 /* info passed to callback functions dealing with registering dlls */
61 struct register_dll_info
62 {
63     PSP_FILE_CALLBACK_W callback;
64     PVOID               callback_context;
65     BOOL                unregister;
66 };
67
68 typedef BOOL (*iterate_fields_func)( HINF hinf, PCWSTR field, void *arg );
69
70 /* Unicode constants */
71 static const WCHAR CopyFiles[]  = {'C','o','p','y','F','i','l','e','s',0};
72 static const WCHAR DelFiles[]   = {'D','e','l','F','i','l','e','s',0};
73 static const WCHAR RenFiles[]   = {'R','e','n','F','i','l','e','s',0};
74 static const WCHAR Ini2Reg[]    = {'I','n','i','2','R','e','g',0};
75 static const WCHAR LogConf[]    = {'L','o','g','C','o','n','f',0};
76 static const WCHAR AddReg[]     = {'A','d','d','R','e','g',0};
77 static const WCHAR DelReg[]     = {'D','e','l','R','e','g',0};
78 static const WCHAR BitReg[]     = {'B','i','t','R','e','g',0};
79 static const WCHAR UpdateInis[] = {'U','p','d','a','t','e','I','n','i','s',0};
80 static const WCHAR CopyINF[]    = {'C','o','p','y','I','N','F',0};
81 static const WCHAR AddService[] = {'A','d','d','S','e','r','v','i','c','e',0};
82 static const WCHAR DelService[] = {'D','e','l','S','e','r','v','i','c','e',0};
83 static const WCHAR UpdateIniFields[] = {'U','p','d','a','t','e','I','n','i','F','i','e','l','d','s',0};
84 static const WCHAR RegisterDlls[]    = {'R','e','g','i','s','t','e','r','D','l','l','s',0};
85 static const WCHAR UnregisterDlls[]  = {'U','n','r','e','g','i','s','t','e','r','D','l','l','s',0};
86 static const WCHAR ProfileItems[]    = {'P','r','o','f','i','l','e','I','t','e','m','s',0};
87 static const WCHAR Name[]            = {'N','a','m','e',0};
88 static const WCHAR CmdLine[]         = {'C','m','d','L','i','n','e',0};
89 static const WCHAR SubDir[]          = {'S','u','b','D','i','r',0};
90 static const WCHAR WineFakeDlls[]    = {'W','i','n','e','F','a','k','e','D','l','l','s',0};
91 static const WCHAR DisplayName[]     = {'D','i','s','p','l','a','y','N','a','m','e',0};
92 static const WCHAR Description[]     = {'D','e','s','c','r','i','p','t','i','o','n',0};
93 static const WCHAR ServiceBinary[]   = {'S','e','r','v','i','c','e','B','i','n','a','r','y',0};
94 static const WCHAR StartName[]       = {'S','t','a','r','t','N','a','m','e',0};
95 static const WCHAR LoadOrderGroup[]  = {'L','o','a','d','O','r','d','e','r','G','r','o','u','p',0};
96 static const WCHAR ServiceType[]     = {'S','e','r','v','i','c','e','T','y','p','e',0};
97 static const WCHAR StartType[]       = {'S','t','a','r','t','T','y','p','e',0};
98 static const WCHAR ErrorControl[]    = {'E','r','r','o','r','C','o','n','t','r','o','l',0};
99
100 static const WCHAR ServicesKey[] = {'S','y','s','t','e','m','\\',
101                         'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
102                         'S','e','r','v','i','c','e','s',0};
103
104 /***********************************************************************
105  *            get_field_string
106  *
107  * Retrieve the contents of a field, dynamically growing the buffer if necessary.
108  */
109 static WCHAR *get_field_string( INFCONTEXT *context, DWORD index, WCHAR *buffer,
110                                 WCHAR *static_buffer, DWORD *size )
111 {
112     DWORD required;
113
114     if (SetupGetStringFieldW( context, index, buffer, *size, &required )) return buffer;
115     if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
116     {
117         /* now grow the buffer */
118         if (buffer != static_buffer) HeapFree( GetProcessHeap(), 0, buffer );
119         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, required*sizeof(WCHAR) ))) return NULL;
120         *size = required;
121         if (SetupGetStringFieldW( context, index, buffer, *size, &required )) return buffer;
122     }
123     if (buffer != static_buffer) HeapFree( GetProcessHeap(), 0, buffer );
124     return NULL;
125 }
126
127
128 /***********************************************************************
129  *            dup_section_line_field
130  *
131  * Retrieve the contents of a field in a newly-allocated buffer.
132  */
133 static WCHAR *dup_section_line_field( HINF hinf, const WCHAR *section, const WCHAR *line, DWORD index )
134 {
135     INFCONTEXT context;
136     DWORD size;
137     WCHAR *buffer;
138
139     if (!SetupFindFirstLineW( hinf, section, line, &context )) return NULL;
140     if (!SetupGetStringFieldW( &context, index, NULL, 0, &size )) return NULL;
141     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return NULL;
142     if (!SetupGetStringFieldW( &context, index, buffer, size, NULL )) buffer[0] = 0;
143     return buffer;
144 }
145
146 /***********************************************************************
147  *            copy_files_callback
148  *
149  * Called once for each CopyFiles entry in a given section.
150  */
151 static BOOL copy_files_callback( HINF hinf, PCWSTR field, void *arg )
152 {
153     struct files_callback_info *info = arg;
154
155     if (field[0] == '@')  /* special case: copy single file */
156         SetupQueueDefaultCopyW( info->queue, info->layout ? info->layout : hinf, info->src_root, NULL, field+1, info->copy_flags );
157     else
158         SetupQueueCopySectionW( info->queue, info->src_root, info->layout ? info->layout : hinf, hinf, field, info->copy_flags );
159     return TRUE;
160 }
161
162
163 /***********************************************************************
164  *            delete_files_callback
165  *
166  * Called once for each DelFiles entry in a given section.
167  */
168 static BOOL delete_files_callback( HINF hinf, PCWSTR field, void *arg )
169 {
170     struct files_callback_info *info = arg;
171     SetupQueueDeleteSectionW( info->queue, hinf, 0, field );
172     return TRUE;
173 }
174
175
176 /***********************************************************************
177  *            rename_files_callback
178  *
179  * Called once for each RenFiles entry in a given section.
180  */
181 static BOOL rename_files_callback( HINF hinf, PCWSTR field, void *arg )
182 {
183     struct files_callback_info *info = arg;
184     SetupQueueRenameSectionW( info->queue, hinf, 0, field );
185     return TRUE;
186 }
187
188
189 /***********************************************************************
190  *            get_root_key
191  *
192  * Retrieve the registry root key from its name.
193  */
194 static HKEY get_root_key( const WCHAR *name, HKEY def_root )
195 {
196     static const WCHAR HKCR[] = {'H','K','C','R',0};
197     static const WCHAR HKCU[] = {'H','K','C','U',0};
198     static const WCHAR HKLM[] = {'H','K','L','M',0};
199     static const WCHAR HKU[]  = {'H','K','U',0};
200     static const WCHAR HKR[]  = {'H','K','R',0};
201
202     if (!strcmpiW( name, HKCR )) return HKEY_CLASSES_ROOT;
203     if (!strcmpiW( name, HKCU )) return HKEY_CURRENT_USER;
204     if (!strcmpiW( name, HKLM )) return HKEY_LOCAL_MACHINE;
205     if (!strcmpiW( name, HKU )) return HKEY_USERS;
206     if (!strcmpiW( name, HKR )) return def_root;
207     return 0;
208 }
209
210
211 /***********************************************************************
212  *            append_multi_sz_value
213  *
214  * Append a multisz string to a multisz registry value.
215  */
216 static void append_multi_sz_value( HKEY hkey, const WCHAR *value, const WCHAR *strings,
217                                    DWORD str_size )
218 {
219     DWORD size, type, total;
220     WCHAR *buffer, *p;
221
222     if (RegQueryValueExW( hkey, value, NULL, &type, NULL, &size )) return;
223     if (type != REG_MULTI_SZ) return;
224
225     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, (size + str_size) * sizeof(WCHAR) ))) return;
226     if (RegQueryValueExW( hkey, value, NULL, NULL, (BYTE *)buffer, &size )) goto done;
227
228     /* compare each string against all the existing ones */
229     total = size;
230     while (*strings)
231     {
232         int len = strlenW(strings) + 1;
233
234         for (p = buffer; *p; p += strlenW(p) + 1)
235             if (!strcmpiW( p, strings )) break;
236
237         if (!*p)  /* not found, need to append it */
238         {
239             memcpy( p, strings, len * sizeof(WCHAR) );
240             p[len] = 0;
241             total += len;
242         }
243         strings += len;
244     }
245     if (total != size)
246     {
247         TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(buffer) );
248         RegSetValueExW( hkey, value, 0, REG_MULTI_SZ, (BYTE *)buffer, total );
249     }
250  done:
251     HeapFree( GetProcessHeap(), 0, buffer );
252 }
253
254
255 /***********************************************************************
256  *            delete_multi_sz_value
257  *
258  * Remove a string from a multisz registry value.
259  */
260 static void delete_multi_sz_value( HKEY hkey, const WCHAR *value, const WCHAR *string )
261 {
262     DWORD size, type;
263     WCHAR *buffer, *src, *dst;
264
265     if (RegQueryValueExW( hkey, value, NULL, &type, NULL, &size )) return;
266     if (type != REG_MULTI_SZ) return;
267     /* allocate double the size, one for value before and one for after */
268     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size * 2 * sizeof(WCHAR) ))) return;
269     if (RegQueryValueExW( hkey, value, NULL, NULL, (BYTE *)buffer, &size )) goto done;
270     src = buffer;
271     dst = buffer + size;
272     while (*src)
273     {
274         int len = strlenW(src) + 1;
275         if (strcmpiW( src, string ))
276         {
277             memcpy( dst, src, len * sizeof(WCHAR) );
278             dst += len;
279         }
280         src += len;
281     }
282     *dst++ = 0;
283     if (dst != buffer + 2*size)  /* did we remove something? */
284     {
285         TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(buffer + size) );
286         RegSetValueExW( hkey, value, 0, REG_MULTI_SZ,
287                         (BYTE *)(buffer + size), dst - (buffer + size) );
288     }
289  done:
290     HeapFree( GetProcessHeap(), 0, buffer );
291 }
292
293
294 /***********************************************************************
295  *            do_reg_operation
296  *
297  * Perform an add/delete registry operation depending on the flags.
298  */
299 static BOOL do_reg_operation( HKEY hkey, const WCHAR *value, INFCONTEXT *context, INT flags )
300 {
301     DWORD type, size;
302
303     if (flags & (FLG_ADDREG_DELREG_BIT | FLG_ADDREG_DELVAL))  /* deletion */
304     {
305         if (*value && !(flags & FLG_DELREG_KEYONLY_COMMON))
306         {
307             if ((flags & FLG_DELREG_MULTI_SZ_DELSTRING) == FLG_DELREG_MULTI_SZ_DELSTRING)
308             {
309                 WCHAR *str;
310
311                 if (!SetupGetStringFieldW( context, 5, NULL, 0, &size ) || !size) return TRUE;
312                 if (!(str = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
313                 SetupGetStringFieldW( context, 5, str, size, NULL );
314                 delete_multi_sz_value( hkey, value, str );
315                 HeapFree( GetProcessHeap(), 0, str );
316             }
317             else RegDeleteValueW( hkey, value );
318         }
319         else NtDeleteKey( hkey );
320         return TRUE;
321     }
322
323     if (flags & (FLG_ADDREG_KEYONLY|FLG_ADDREG_KEYONLY_COMMON)) return TRUE;
324
325     if (flags & (FLG_ADDREG_NOCLOBBER|FLG_ADDREG_OVERWRITEONLY))
326     {
327         BOOL exists = !RegQueryValueExW( hkey, value, NULL, NULL, NULL, NULL );
328         if (exists && (flags & FLG_ADDREG_NOCLOBBER)) return TRUE;
329         if (!exists && (flags & FLG_ADDREG_OVERWRITEONLY)) return TRUE;
330     }
331
332     switch(flags & FLG_ADDREG_TYPE_MASK)
333     {
334     case FLG_ADDREG_TYPE_SZ:        type = REG_SZ; break;
335     case FLG_ADDREG_TYPE_MULTI_SZ:  type = REG_MULTI_SZ; break;
336     case FLG_ADDREG_TYPE_EXPAND_SZ: type = REG_EXPAND_SZ; break;
337     case FLG_ADDREG_TYPE_BINARY:    type = REG_BINARY; break;
338     case FLG_ADDREG_TYPE_DWORD:     type = REG_DWORD; break;
339     case FLG_ADDREG_TYPE_NONE:      type = REG_NONE; break;
340     default:                        type = flags >> 16; break;
341     }
342
343     if (!(flags & FLG_ADDREG_BINVALUETYPE) ||
344         (type == REG_DWORD && SetupGetFieldCount(context) == 5))
345     {
346         static const WCHAR empty;
347         WCHAR *str = NULL;
348
349         if (type == REG_MULTI_SZ)
350         {
351             if (!SetupGetMultiSzFieldW( context, 5, NULL, 0, &size )) size = 0;
352             if (size)
353             {
354                 if (!(str = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
355                 SetupGetMultiSzFieldW( context, 5, str, size, NULL );
356             }
357             if (flags & FLG_ADDREG_APPEND)
358             {
359                 if (!str) return TRUE;
360                 append_multi_sz_value( hkey, value, str, size );
361                 HeapFree( GetProcessHeap(), 0, str );
362                 return TRUE;
363             }
364             /* else fall through to normal string handling */
365         }
366         else
367         {
368             if (!SetupGetStringFieldW( context, 5, NULL, 0, &size )) size = 0;
369             if (size)
370             {
371                 if (!(str = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
372                 SetupGetStringFieldW( context, 5, str, size, NULL );
373                 if (type == REG_LINK) size--;  /* no terminating null for symlinks */
374             }
375         }
376
377         if (type == REG_DWORD)
378         {
379             DWORD dw = str ? strtoulW( str, NULL, 0 ) : 0;
380             TRACE( "setting dword %s to %x\n", debugstr_w(value), dw );
381             RegSetValueExW( hkey, value, 0, type, (BYTE *)&dw, sizeof(dw) );
382         }
383         else
384         {
385             TRACE( "setting value %s to %s\n", debugstr_w(value), debugstr_w(str) );
386             if (str) RegSetValueExW( hkey, value, 0, type, (BYTE *)str, size * sizeof(WCHAR) );
387             else RegSetValueExW( hkey, value, 0, type, (const BYTE *)&empty, sizeof(WCHAR) );
388         }
389         HeapFree( GetProcessHeap(), 0, str );
390         return TRUE;
391     }
392     else  /* get the binary data */
393     {
394         BYTE *data = NULL;
395
396         if (!SetupGetBinaryField( context, 5, NULL, 0, &size )) size = 0;
397         if (size)
398         {
399             if (!(data = HeapAlloc( GetProcessHeap(), 0, size ))) return FALSE;
400             TRACE( "setting binary data %s len %d\n", debugstr_w(value), size );
401             SetupGetBinaryField( context, 5, data, size, NULL );
402         }
403         RegSetValueExW( hkey, value, 0, type, data, size );
404         HeapFree( GetProcessHeap(), 0, data );
405         return TRUE;
406     }
407 }
408
409
410 /***********************************************************************
411  *            registry_callback
412  *
413  * Called once for each AddReg and DelReg entry in a given section.
414  */
415 static BOOL registry_callback( HINF hinf, PCWSTR field, void *arg )
416 {
417     struct registry_callback_info *info = arg;
418     INFCONTEXT context;
419     HKEY root_key, hkey;
420
421     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
422
423     for (; ok; ok = SetupFindNextLine( &context, &context ))
424     {
425         DWORD options = 0;
426         WCHAR buffer[MAX_INF_STRING_LENGTH];
427         INT flags;
428
429         /* get root */
430         if (!SetupGetStringFieldW( &context, 1, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
431             continue;
432         if (!(root_key = get_root_key( buffer, info->default_root )))
433             continue;
434
435         /* get key */
436         if (!SetupGetStringFieldW( &context, 2, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
437             *buffer = 0;
438
439         /* get flags */
440         if (!SetupGetIntField( &context, 4, &flags )) flags = 0;
441
442         if (!info->delete)
443         {
444             if (flags & FLG_ADDREG_DELREG_BIT) continue;  /* ignore this entry */
445         }
446         else
447         {
448             if (!flags) flags = FLG_ADDREG_DELREG_BIT;
449             else if (!(flags & FLG_ADDREG_DELREG_BIT)) continue;  /* ignore this entry */
450         }
451         /* Wine extension: magic support for symlinks */
452         if (flags >> 16 == REG_LINK) options = REG_OPTION_OPEN_LINK | REG_OPTION_CREATE_LINK;
453
454         if (info->delete || (flags & FLG_ADDREG_OVERWRITEONLY))
455         {
456             if (RegOpenKeyExW( root_key, buffer, options, MAXIMUM_ALLOWED, &hkey ))
457                 continue;  /* ignore if it doesn't exist */
458         }
459         else
460         {
461             DWORD res = RegCreateKeyExW( root_key, buffer, 0, NULL, options,
462                                          MAXIMUM_ALLOWED, NULL, &hkey, NULL );
463             if (res == ERROR_ALREADY_EXISTS && (options & REG_OPTION_CREATE_LINK))
464                 res = RegCreateKeyExW( root_key, buffer, 0, NULL, REG_OPTION_OPEN_LINK,
465                                        MAXIMUM_ALLOWED, NULL, &hkey, NULL );
466             if (res)
467             {
468                 ERR( "could not create key %p %s\n", root_key, debugstr_w(buffer) );
469                 continue;
470             }
471         }
472         TRACE( "key %p %s\n", root_key, debugstr_w(buffer) );
473
474         /* get value name */
475         if (!SetupGetStringFieldW( &context, 3, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
476             *buffer = 0;
477
478         /* and now do it */
479         if (!do_reg_operation( hkey, buffer, &context, flags ))
480         {
481             RegCloseKey( hkey );
482             return FALSE;
483         }
484         RegCloseKey( hkey );
485     }
486     return TRUE;
487 }
488
489
490 /***********************************************************************
491  *            do_register_dll
492  *
493  * Register or unregister a dll.
494  */
495 static BOOL do_register_dll( const struct register_dll_info *info, const WCHAR *path,
496                              INT flags, INT timeout, const WCHAR *args )
497 {
498     HMODULE module;
499     HRESULT res;
500     SP_REGISTER_CONTROL_STATUSW status;
501     IMAGE_NT_HEADERS *nt;
502
503     status.cbSize = sizeof(status);
504     status.FileName = path;
505     status.FailureCode = SPREG_SUCCESS;
506     status.Win32Error = ERROR_SUCCESS;
507
508     if (info->callback)
509     {
510         switch(info->callback( info->callback_context, SPFILENOTIFY_STARTREGISTRATION,
511                                (UINT_PTR)&status, !info->unregister ))
512         {
513         case FILEOP_ABORT:
514             SetLastError( ERROR_OPERATION_ABORTED );
515             return FALSE;
516         case FILEOP_SKIP:
517             return TRUE;
518         case FILEOP_DOIT:
519             break;
520         }
521     }
522
523     if (!(module = LoadLibraryExW( path, 0, LOAD_WITH_ALTERED_SEARCH_PATH )))
524     {
525         WARN( "could not load %s\n", debugstr_w(path) );
526         status.FailureCode = SPREG_LOADLIBRARY;
527         status.Win32Error = GetLastError();
528         goto done;
529     }
530
531     if ((nt = RtlImageNtHeader( module )) && !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
532     {
533         /* file is an executable, not a dll */
534         STARTUPINFOW startup;
535         PROCESS_INFORMATION info;
536         WCHAR *cmd_line;
537         BOOL res;
538         static const WCHAR format[] = {'"','%','s','"',' ','%','s',0};
539         static const WCHAR default_args[] = {'/','R','e','g','S','e','r','v','e','r',0};
540
541         FreeLibrary( module );
542         module = NULL;
543         if (!args) args = default_args;
544         cmd_line = HeapAlloc( GetProcessHeap(), 0, (strlenW(path) + strlenW(args) + 4) * sizeof(WCHAR) );
545         sprintfW( cmd_line, format, path, args );
546         memset( &startup, 0, sizeof(startup) );
547         startup.cb = sizeof(startup);
548         TRACE( "executing %s\n", debugstr_w(cmd_line) );
549         res = CreateProcessW( NULL, cmd_line, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &info );
550         HeapFree( GetProcessHeap(), 0, cmd_line );
551         if (!res)
552         {
553             status.FailureCode = SPREG_LOADLIBRARY;
554             status.Win32Error = GetLastError();
555             goto done;
556         }
557         CloseHandle( info.hThread );
558
559         if (WaitForSingleObject( info.hProcess, timeout*1000 ) == WAIT_TIMEOUT)
560         {
561             /* timed out, kill the process */
562             TerminateProcess( info.hProcess, 1 );
563             status.FailureCode = SPREG_TIMEOUT;
564             status.Win32Error = ERROR_TIMEOUT;
565         }
566         CloseHandle( info.hProcess );
567         goto done;
568     }
569
570     if (flags & FLG_REGSVR_DLLREGISTER)
571     {
572         const char *entry_point = info->unregister ? "DllUnregisterServer" : "DllRegisterServer";
573         HRESULT (WINAPI *func)(void) = (void *)GetProcAddress( module, entry_point );
574
575         if (!func)
576         {
577             status.FailureCode = SPREG_GETPROCADDR;
578             status.Win32Error = GetLastError();
579             goto done;
580         }
581
582         TRACE( "calling %s in %s\n", entry_point, debugstr_w(path) );
583         res = func();
584
585         if (FAILED(res))
586         {
587             WARN( "calling %s in %s returned error %x\n", entry_point, debugstr_w(path), res );
588             status.FailureCode = SPREG_REGSVR;
589             status.Win32Error = res;
590             goto done;
591         }
592     }
593
594     if (flags & FLG_REGSVR_DLLINSTALL)
595     {
596         HRESULT (WINAPI *func)(BOOL,LPCWSTR) = (void *)GetProcAddress( module, "DllInstall" );
597
598         if (!func)
599         {
600             status.FailureCode = SPREG_GETPROCADDR;
601             status.Win32Error = GetLastError();
602             goto done;
603         }
604
605         TRACE( "calling DllInstall(%d,%s) in %s\n",
606                !info->unregister, debugstr_w(args), debugstr_w(path) );
607         res = func( !info->unregister, args );
608
609         if (FAILED(res))
610         {
611             WARN( "calling DllInstall in %s returned error %x\n", debugstr_w(path), res );
612             status.FailureCode = SPREG_REGSVR;
613             status.Win32Error = res;
614             goto done;
615         }
616     }
617
618 done:
619     if (module) FreeLibrary( module );
620     if (info->callback) info->callback( info->callback_context, SPFILENOTIFY_ENDREGISTRATION,
621                                         (UINT_PTR)&status, !info->unregister );
622     return TRUE;
623 }
624
625
626 /***********************************************************************
627  *            register_dlls_callback
628  *
629  * Called once for each RegisterDlls entry in a given section.
630  */
631 static BOOL register_dlls_callback( HINF hinf, PCWSTR field, void *arg )
632 {
633     struct register_dll_info *info = arg;
634     INFCONTEXT context;
635     BOOL ret = TRUE;
636     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
637
638     for (; ok; ok = SetupFindNextLine( &context, &context ))
639     {
640         WCHAR *path, *args, *p;
641         WCHAR buffer[MAX_INF_STRING_LENGTH];
642         INT flags, timeout;
643
644         /* get directory */
645         if (!(path = PARSER_get_dest_dir( &context ))) continue;
646
647         /* get dll name */
648         if (!SetupGetStringFieldW( &context, 3, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
649             goto done;
650         if (!(p = HeapReAlloc( GetProcessHeap(), 0, path,
651                                (strlenW(path) + strlenW(buffer) + 2) * sizeof(WCHAR) ))) goto done;
652         path = p;
653         p += strlenW(p);
654         if (p == path || p[-1] != '\\') *p++ = '\\';
655         strcpyW( p, buffer );
656
657         /* get flags */
658         if (!SetupGetIntField( &context, 4, &flags )) flags = 0;
659
660         /* get timeout */
661         if (!SetupGetIntField( &context, 5, &timeout )) timeout = 60;
662
663         /* get command line */
664         args = NULL;
665         if (SetupGetStringFieldW( &context, 6, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
666             args = buffer;
667
668         ret = do_register_dll( info, path, flags, timeout, args );
669
670     done:
671         HeapFree( GetProcessHeap(), 0, path );
672         if (!ret) break;
673     }
674     return ret;
675 }
676
677 /***********************************************************************
678  *            fake_dlls_callback
679  *
680  * Called once for each WineFakeDlls entry in a given section.
681  */
682 static BOOL fake_dlls_callback( HINF hinf, PCWSTR field, void *arg )
683 {
684     INFCONTEXT context;
685     BOOL ret = TRUE;
686     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
687
688     for (; ok; ok = SetupFindNextLine( &context, &context ))
689     {
690         WCHAR *path, *p;
691         WCHAR buffer[MAX_INF_STRING_LENGTH];
692
693         /* get directory */
694         if (!(path = PARSER_get_dest_dir( &context ))) continue;
695
696         /* get dll name */
697         if (!SetupGetStringFieldW( &context, 3, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
698             goto done;
699         if (!(p = HeapReAlloc( GetProcessHeap(), 0, path,
700                                (strlenW(path) + strlenW(buffer) + 2) * sizeof(WCHAR) ))) goto done;
701         path = p;
702         p += strlenW(p);
703         if (p == path || p[-1] != '\\') *p++ = '\\';
704         strcpyW( p, buffer );
705
706         /* get source dll */
707         if (SetupGetStringFieldW( &context, 4, buffer, sizeof(buffer)/sizeof(WCHAR), NULL ))
708             p = buffer;  /* otherwise use target base name as default source */
709
710         create_fake_dll( path, p );  /* ignore errors */
711
712     done:
713         HeapFree( GetProcessHeap(), 0, path );
714         if (!ret) break;
715     }
716     cleanup_fake_dlls();
717     return ret;
718 }
719
720 /***********************************************************************
721  *            update_ini_callback
722  *
723  * Called once for each UpdateInis entry in a given section.
724  */
725 static BOOL update_ini_callback( HINF hinf, PCWSTR field, void *arg )
726 {
727     INFCONTEXT context;
728
729     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
730
731     for (; ok; ok = SetupFindNextLine( &context, &context ))
732     {
733         WCHAR buffer[MAX_INF_STRING_LENGTH];
734         WCHAR  filename[MAX_INF_STRING_LENGTH];
735         WCHAR  section[MAX_INF_STRING_LENGTH];
736         WCHAR  entry[MAX_INF_STRING_LENGTH];
737         WCHAR  string[MAX_INF_STRING_LENGTH];
738         LPWSTR divider;
739
740         if (!SetupGetStringFieldW( &context, 1, filename,
741                                    sizeof(filename)/sizeof(WCHAR), NULL ))
742             continue;
743
744         if (!SetupGetStringFieldW( &context, 2, section,
745                                    sizeof(section)/sizeof(WCHAR), NULL ))
746             continue;
747
748         if (!SetupGetStringFieldW( &context, 4, buffer,
749                                    sizeof(buffer)/sizeof(WCHAR), NULL ))
750             continue;
751
752         divider = strchrW(buffer,'=');
753         if (divider)
754         {
755             *divider = 0;
756             strcpyW(entry,buffer);
757             divider++;
758             strcpyW(string,divider);
759         }
760         else
761         {
762             strcpyW(entry,buffer);
763             string[0]=0;
764         }
765
766         TRACE("Writing %s = %s in %s of file %s\n",debugstr_w(entry),
767                debugstr_w(string),debugstr_w(section),debugstr_w(filename));
768         WritePrivateProfileStringW(section,entry,string,filename);
769
770     }
771     return TRUE;
772 }
773
774 static BOOL update_ini_fields_callback( HINF hinf, PCWSTR field, void *arg )
775 {
776     FIXME( "should update ini fields %s\n", debugstr_w(field) );
777     return TRUE;
778 }
779
780 static BOOL ini2reg_callback( HINF hinf, PCWSTR field, void *arg )
781 {
782     FIXME( "should do ini2reg %s\n", debugstr_w(field) );
783     return TRUE;
784 }
785
786 static BOOL logconf_callback( HINF hinf, PCWSTR field, void *arg )
787 {
788     FIXME( "should do logconf %s\n", debugstr_w(field) );
789     return TRUE;
790 }
791
792 static BOOL bitreg_callback( HINF hinf, PCWSTR field, void *arg )
793 {
794     FIXME( "should do bitreg %s\n", debugstr_w(field) );
795     return TRUE;
796 }
797
798 static BOOL profile_items_callback( HINF hinf, PCWSTR field, void *arg )
799 {
800     WCHAR lnkpath[MAX_PATH];
801     LPWSTR cmdline=NULL, lnkpath_end;
802     unsigned int name_size;
803     INFCONTEXT name_context, context;
804     int attrs=0;
805
806     static const WCHAR dotlnk[] = {'.','l','n','k',0};
807
808     TRACE( "(%s)\n", debugstr_w(field) );
809
810     if (SetupFindFirstLineW( hinf, field, Name, &name_context ))
811     {
812         SetupGetIntField( &name_context, 2, &attrs );
813         if (attrs & ~FLG_PROFITEM_GROUP) FIXME( "unhandled attributes: %x\n", attrs );
814     }
815     else return TRUE;
816
817     /* calculate filename */
818     SHGetFolderPathW( NULL, CSIDL_COMMON_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, lnkpath );
819     lnkpath_end = lnkpath + strlenW(lnkpath);
820     if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';
821
822     if (!(attrs & FLG_PROFITEM_GROUP) && SetupFindFirstLineW( hinf, field, SubDir, &context ))
823     {
824         unsigned int subdir_size;
825
826         if (!SetupGetStringFieldW( &context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &subdir_size ))
827             return TRUE;
828
829         lnkpath_end += subdir_size - 1;
830         if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';
831     }
832
833     if (!SetupGetStringFieldW( &name_context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &name_size ))
834         return TRUE;
835
836     lnkpath_end += name_size - 1;
837
838     if (attrs & FLG_PROFITEM_GROUP)
839     {
840         SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE );
841     }
842     else
843     {
844         IShellLinkW* shelllink=NULL;
845         IPersistFile* persistfile=NULL;
846         HRESULT initresult=E_FAIL;
847
848         if (lnkpath+MAX_PATH < lnkpath_end + 5) return TRUE;
849         strcpyW( lnkpath_end, dotlnk );
850
851         TRACE( "link path: %s\n", debugstr_w(lnkpath) );
852
853         /* calculate command line */
854         if (SetupFindFirstLineW( hinf, field, CmdLine, &context ))
855         {
856             unsigned int dir_len=0, subdir_size=0, filename_size=0;
857             int dirid=0;
858             LPCWSTR dir;
859             LPWSTR cmdline_end;
860
861             SetupGetIntField( &context, 1, &dirid );
862             dir = DIRID_get_string( dirid );
863
864             if (dir) dir_len = strlenW(dir);
865
866             SetupGetStringFieldW( &context, 2, NULL, 0, &subdir_size );
867             SetupGetStringFieldW( &context, 3, NULL, 0, &filename_size );
868
869             if (dir_len && filename_size)
870             {
871                 cmdline = cmdline_end = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR) * (dir_len+subdir_size+filename_size+1) );
872
873                 strcpyW( cmdline_end, dir );
874                 cmdline_end += dir_len;
875                 if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
876
877                 if (subdir_size)
878                 {
879                     SetupGetStringFieldW( &context, 2, cmdline_end, subdir_size, NULL );
880                     cmdline_end += subdir_size-1;
881                     if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
882                 }
883                 SetupGetStringFieldW( &context, 3, cmdline_end, filename_size, NULL );
884                 TRACE( "cmdline: %s\n", debugstr_w(cmdline));
885             }
886         }
887
888         if (!cmdline) return TRUE;
889
890         initresult = CoInitialize(NULL);
891
892         if (FAILED(CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
893                                      &IID_IShellLinkW, (LPVOID*)&shelllink )))
894             goto done;
895
896         IShellLinkW_SetPath( shelllink, cmdline );
897         SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE|SHPPFW_IGNOREFILENAME );
898         if (SUCCEEDED(IShellLinkW_QueryInterface( shelllink, &IID_IPersistFile, (LPVOID*)&persistfile)))
899         {
900             TRACE( "writing link: %s\n", debugstr_w(lnkpath) );
901             IPersistFile_Save( persistfile, lnkpath, FALSE );
902             IPersistFile_Release( persistfile );
903         }
904         IShellLinkW_Release( shelllink );
905
906     done:
907         if (SUCCEEDED(initresult)) CoUninitialize();
908         HeapFree( GetProcessHeap(), 0, cmdline );
909     }
910
911     return TRUE;
912 }
913
914 static BOOL copy_inf_callback( HINF hinf, PCWSTR field, void *arg )
915 {
916     FIXME( "should do copy inf %s\n", debugstr_w(field) );
917     return TRUE;
918 }
919
920
921 /***********************************************************************
922  *            iterate_section_fields
923  *
924  * Iterate over all fields of a certain key of a certain section
925  */
926 static BOOL iterate_section_fields( HINF hinf, PCWSTR section, PCWSTR key,
927                                     iterate_fields_func callback, void *arg )
928 {
929     WCHAR static_buffer[200];
930     WCHAR *buffer = static_buffer;
931     DWORD size = sizeof(static_buffer)/sizeof(WCHAR);
932     INFCONTEXT context;
933     BOOL ret = FALSE;
934
935     BOOL ok = SetupFindFirstLineW( hinf, section, key, &context );
936     while (ok)
937     {
938         UINT i, count = SetupGetFieldCount( &context );
939         for (i = 1; i <= count; i++)
940         {
941             if (!(buffer = get_field_string( &context, i, buffer, static_buffer, &size )))
942                 goto done;
943             if (!callback( hinf, buffer, arg ))
944             {
945                 WARN("callback failed for %s %s err %d\n",
946                      debugstr_w(section), debugstr_w(buffer), GetLastError() );
947                 goto done;
948             }
949         }
950         ok = SetupFindNextMatchLineW( &context, key, &context );
951     }
952     ret = TRUE;
953  done:
954     if (buffer != static_buffer) HeapFree( GetProcessHeap(), 0, buffer );
955     return ret;
956 }
957
958
959 /***********************************************************************
960  *            SetupInstallFilesFromInfSectionA   (SETUPAPI.@)
961  */
962 BOOL WINAPI SetupInstallFilesFromInfSectionA( HINF hinf, HINF hlayout, HSPFILEQ queue,
963                                               PCSTR section, PCSTR src_root, UINT flags )
964 {
965     UNICODE_STRING sectionW;
966     BOOL ret = FALSE;
967
968     if (!RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
969     {
970         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
971         return FALSE;
972     }
973     if (!src_root)
974         ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
975                                                 NULL, flags );
976     else
977     {
978         UNICODE_STRING srcW;
979         if (RtlCreateUnicodeStringFromAsciiz( &srcW, src_root ))
980         {
981             ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
982                                                     srcW.Buffer, flags );
983             RtlFreeUnicodeString( &srcW );
984         }
985         else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
986     }
987     RtlFreeUnicodeString( &sectionW );
988     return ret;
989 }
990
991
992 /***********************************************************************
993  *            SetupInstallFilesFromInfSectionW   (SETUPAPI.@)
994  */
995 BOOL WINAPI SetupInstallFilesFromInfSectionW( HINF hinf, HINF hlayout, HSPFILEQ queue,
996                                               PCWSTR section, PCWSTR src_root, UINT flags )
997 {
998     struct files_callback_info info;
999
1000     info.queue      = queue;
1001     info.src_root   = src_root;
1002     info.copy_flags = flags;
1003     info.layout     = hlayout;
1004     return iterate_section_fields( hinf, section, CopyFiles, copy_files_callback, &info );
1005 }
1006
1007
1008 /***********************************************************************
1009  *            SetupInstallFromInfSectionA   (SETUPAPI.@)
1010  */
1011 BOOL WINAPI SetupInstallFromInfSectionA( HWND owner, HINF hinf, PCSTR section, UINT flags,
1012                                          HKEY key_root, PCSTR src_root, UINT copy_flags,
1013                                          PSP_FILE_CALLBACK_A callback, PVOID context,
1014                                          HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
1015 {
1016     UNICODE_STRING sectionW, src_rootW;
1017     struct callback_WtoA_context ctx;
1018     BOOL ret = FALSE;
1019
1020     src_rootW.Buffer = NULL;
1021     if (src_root && !RtlCreateUnicodeStringFromAsciiz( &src_rootW, src_root ))
1022     {
1023         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1024         return FALSE;
1025     }
1026
1027     if (RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
1028     {
1029         ctx.orig_context = context;
1030         ctx.orig_handler = callback;
1031         ret = SetupInstallFromInfSectionW( owner, hinf, sectionW.Buffer, flags, key_root,
1032                                            src_rootW.Buffer, copy_flags, QUEUE_callback_WtoA,
1033                                            &ctx, devinfo, devinfo_data );
1034         RtlFreeUnicodeString( &sectionW );
1035     }
1036     else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1037
1038     RtlFreeUnicodeString( &src_rootW );
1039     return ret;
1040 }
1041
1042
1043 /***********************************************************************
1044  *            SetupInstallFromInfSectionW   (SETUPAPI.@)
1045  */
1046 BOOL WINAPI SetupInstallFromInfSectionW( HWND owner, HINF hinf, PCWSTR section, UINT flags,
1047                                          HKEY key_root, PCWSTR src_root, UINT copy_flags,
1048                                          PSP_FILE_CALLBACK_W callback, PVOID context,
1049                                          HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
1050 {
1051     if (flags & SPINST_FILES)
1052     {
1053         struct files_callback_info info;
1054         HSPFILEQ queue;
1055         BOOL ret;
1056
1057         if (!(queue = SetupOpenFileQueue())) return FALSE;
1058         info.queue      = queue;
1059         info.src_root   = src_root;
1060         info.copy_flags = copy_flags;
1061         info.layout     = hinf;
1062         ret = (iterate_section_fields( hinf, section, CopyFiles, copy_files_callback, &info ) &&
1063                iterate_section_fields( hinf, section, DelFiles, delete_files_callback, &info ) &&
1064                iterate_section_fields( hinf, section, RenFiles, rename_files_callback, &info ) &&
1065                SetupCommitFileQueueW( owner, queue, callback, context ));
1066         SetupCloseFileQueue( queue );
1067         if (!ret) return FALSE;
1068     }
1069     if (flags & SPINST_INIFILES)
1070     {
1071         if (!iterate_section_fields( hinf, section, UpdateInis, update_ini_callback, NULL ) ||
1072             !iterate_section_fields( hinf, section, UpdateIniFields,
1073                                      update_ini_fields_callback, NULL ))
1074             return FALSE;
1075     }
1076     if (flags & SPINST_INI2REG)
1077     {
1078         if (!iterate_section_fields( hinf, section, Ini2Reg, ini2reg_callback, NULL ))
1079             return FALSE;
1080     }
1081     if (flags & SPINST_LOGCONFIG)
1082     {
1083         if (!iterate_section_fields( hinf, section, LogConf, logconf_callback, NULL ))
1084             return FALSE;
1085     }
1086     if (flags & SPINST_REGSVR)
1087     {
1088         struct register_dll_info info;
1089
1090         info.unregister = FALSE;
1091         if (flags & SPINST_REGISTERCALLBACKAWARE)
1092         {
1093             info.callback         = callback;
1094             info.callback_context = context;
1095         }
1096         else info.callback = NULL;
1097
1098         if (!iterate_section_fields( hinf, section, WineFakeDlls, fake_dlls_callback, NULL ))
1099             return FALSE;
1100
1101         if (!iterate_section_fields( hinf, section, RegisterDlls, register_dlls_callback, &info ))
1102             return FALSE;
1103     }
1104     if (flags & SPINST_UNREGSVR)
1105     {
1106         struct register_dll_info info;
1107
1108         info.unregister = TRUE;
1109         if (flags & SPINST_REGISTERCALLBACKAWARE)
1110         {
1111             info.callback         = callback;
1112             info.callback_context = context;
1113         }
1114         else info.callback = NULL;
1115
1116         if (!iterate_section_fields( hinf, section, UnregisterDlls, register_dlls_callback, &info ))
1117             return FALSE;
1118     }
1119     if (flags & SPINST_REGISTRY)
1120     {
1121         struct registry_callback_info info;
1122
1123         info.default_root = key_root;
1124         info.delete = TRUE;
1125         if (!iterate_section_fields( hinf, section, DelReg, registry_callback, &info ))
1126             return FALSE;
1127         info.delete = FALSE;
1128         if (!iterate_section_fields( hinf, section, AddReg, registry_callback, &info ))
1129             return FALSE;
1130     }
1131     if (flags & SPINST_BITREG)
1132     {
1133         if (!iterate_section_fields( hinf, section, BitReg, bitreg_callback, NULL ))
1134             return FALSE;
1135     }
1136     if (flags & SPINST_PROFILEITEMS)
1137     {
1138         if (!iterate_section_fields( hinf, section, ProfileItems, profile_items_callback, NULL ))
1139             return FALSE;
1140     }
1141     if (flags & SPINST_COPYINF)
1142     {
1143         if (!iterate_section_fields( hinf, section, CopyINF, copy_inf_callback, NULL ))
1144             return FALSE;
1145     }
1146
1147     return TRUE;
1148 }
1149
1150
1151 /***********************************************************************
1152  *              InstallHinfSectionW  (SETUPAPI.@)
1153  *
1154  * NOTE: 'cmdline' is <section> <mode> <path> from
1155  *   RUNDLL32.EXE SETUPAPI.DLL,InstallHinfSection <section> <mode> <path>
1156  */
1157 void WINAPI InstallHinfSectionW( HWND hwnd, HINSTANCE handle, LPCWSTR cmdline, INT show )
1158 {
1159 #ifdef __i386__
1160     static const WCHAR nt_platformW[] = {'.','n','t','x','8','6',0};
1161 #elif defined(__x86_64)
1162     static const WCHAR nt_platformW[] = {'.','n','t','a','m','d','6','4',0};
1163 #else  /* FIXME: other platforms */
1164     static const WCHAR nt_platformW[] = {'.','n','t',0};
1165 #endif
1166     static const WCHAR nt_genericW[] = {'.','n','t',0};
1167     static const WCHAR servicesW[] = {'.','S','e','r','v','i','c','e','s',0};
1168
1169     WCHAR *s, *path, section[MAX_PATH + (sizeof(nt_platformW) + sizeof(servicesW)) / sizeof(WCHAR)];
1170     void *callback_context;
1171     UINT mode;
1172     HINF hinf;
1173
1174     TRACE("hwnd %p, handle %p, cmdline %s\n", hwnd, handle, debugstr_w(cmdline));
1175
1176     lstrcpynW( section, cmdline, MAX_PATH );
1177
1178     if (!(s = strchrW( section, ' ' ))) return;
1179     *s++ = 0;
1180     while (*s == ' ') s++;
1181     mode = atoiW( s );
1182
1183     /* quoted paths are not allowed on native, the rest of the command line is taken as the path */
1184     if (!(s = strchrW( s, ' ' ))) return;
1185     while (*s == ' ') s++;
1186     path = s;
1187
1188     hinf = SetupOpenInfFileW( path, NULL, INF_STYLE_WIN4, NULL );
1189     if (hinf == INVALID_HANDLE_VALUE) return;
1190
1191     if (!(GetVersion() & 0x80000000))
1192     {
1193         INFCONTEXT context;
1194
1195         /* check for <section>.ntx86 (or corresponding name for the current platform)
1196          * and then <section>.nt */
1197         s = section + strlenW(section);
1198         memcpy( s, nt_platformW, sizeof(nt_platformW) );
1199         if (!(SetupFindFirstLineW( hinf, section, NULL, &context )))
1200         {
1201             memcpy( s, nt_genericW, sizeof(nt_genericW) );
1202             if (!(SetupFindFirstLineW( hinf, section, NULL, &context ))) *s = 0;
1203         }
1204         if (*s) TRACE( "using section %s instead\n", debugstr_w(section) );
1205     }
1206
1207     callback_context = SetupInitDefaultQueueCallback( hwnd );
1208     SetupInstallFromInfSectionW( hwnd, hinf, section, SPINST_ALL, NULL, NULL, SP_COPY_NEWER,
1209                                  SetupDefaultQueueCallbackW, callback_context,
1210                                  NULL, NULL );
1211     SetupTermDefaultQueueCallback( callback_context );
1212     strcatW( section, servicesW );
1213     SetupInstallServicesFromInfSectionW( hinf, section, 0 );
1214     SetupCloseInfFile( hinf );
1215
1216     /* FIXME: should check the mode and maybe reboot */
1217     /* there isn't much point in doing that since we */
1218     /* don't yet handle deferred file copies anyway. */
1219 }
1220
1221
1222 /***********************************************************************
1223  *              InstallHinfSectionA  (SETUPAPI.@)
1224  */
1225 void WINAPI InstallHinfSectionA( HWND hwnd, HINSTANCE handle, LPCSTR cmdline, INT show )
1226 {
1227     UNICODE_STRING cmdlineW;
1228
1229     if (RtlCreateUnicodeStringFromAsciiz( &cmdlineW, cmdline ))
1230     {
1231         InstallHinfSectionW( hwnd, handle, cmdlineW.Buffer, show );
1232         RtlFreeUnicodeString( &cmdlineW );
1233     }
1234 }
1235
1236
1237 /***********************************************************************
1238  *            add_service
1239  *
1240  * Create a new service. Helper for SetupInstallServicesFromInfSectionW.
1241  */
1242 static BOOL add_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, const WCHAR *section, DWORD flags )
1243 {
1244     struct registry_callback_info info;
1245     SC_HANDLE service;
1246     INFCONTEXT context;
1247     SERVICE_DESCRIPTIONW descr;
1248     WCHAR *display_name, *start_name, *load_order, *binary_path;
1249     INT service_type = 0, start_type = 0, error_control = 0;
1250     DWORD size;
1251     HKEY hkey;
1252
1253     /* first the mandatory fields */
1254
1255     if (!SetupFindFirstLineW( hinf, section, ServiceType, &context ) ||
1256         !SetupGetIntField( &context, 1, &service_type ))
1257     {
1258         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1259         return FALSE;
1260     }
1261     if (!SetupFindFirstLineW( hinf, section, StartType, &context ) ||
1262         !SetupGetIntField( &context, 1, &start_type ))
1263     {
1264         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1265         return FALSE;
1266     }
1267     if (!SetupFindFirstLineW( hinf, section, ErrorControl, &context ) ||
1268         !SetupGetIntField( &context, 1, &error_control ))
1269     {
1270         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1271         return FALSE;
1272     }
1273     if (!(binary_path = dup_section_line_field( hinf, section, ServiceBinary, 1 )))
1274     {
1275         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1276         return FALSE;
1277     }
1278
1279     /* now the optional fields */
1280
1281     display_name = dup_section_line_field( hinf, section, DisplayName, 1 );
1282     start_name = dup_section_line_field( hinf, section, StartName, 1 );
1283     load_order = dup_section_line_field( hinf, section, LoadOrderGroup, 1 );
1284     descr.lpDescription = dup_section_line_field( hinf, section, Description, 1 );
1285
1286     /* FIXME: Dependencies field */
1287     /* FIXME: Security field */
1288
1289     TRACE( "service %s display %s type %x start %x error %x binary %s order %s startname %s flags %x\n",
1290            debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
1291            debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name), flags );
1292
1293     service = CreateServiceW( scm, name, display_name, SERVICE_ALL_ACCESS,
1294                               service_type, start_type, error_control, binary_path,
1295                               load_order, NULL, NULL, start_name, NULL );
1296     if (service)
1297     {
1298         if (descr.lpDescription) ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
1299     }
1300     else
1301     {
1302         if (GetLastError() != ERROR_SERVICE_EXISTS) goto done;
1303         service = OpenServiceW( scm, name, SERVICE_QUERY_CONFIG|SERVICE_CHANGE_CONFIG|SERVICE_START );
1304         if (!service) goto done;
1305
1306         if (flags & (SPSVCINST_NOCLOBBER_DISPLAYNAME | SPSVCINST_NOCLOBBER_STARTTYPE |
1307                      SPSVCINST_NOCLOBBER_ERRORCONTROL | SPSVCINST_NOCLOBBER_LOADORDERGROUP))
1308         {
1309             QUERY_SERVICE_CONFIGW *config = NULL;
1310
1311             if (!QueryServiceConfigW( service, NULL, 0, &size ) &&
1312                 GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1313                 config = HeapAlloc( GetProcessHeap(), 0, size );
1314             if (config && QueryServiceConfigW( service, config, size, &size ))
1315             {
1316                 if (flags & SPSVCINST_NOCLOBBER_STARTTYPE) start_type = config->dwStartType;
1317                 if (flags & SPSVCINST_NOCLOBBER_ERRORCONTROL) error_control = config->dwErrorControl;
1318                 if (flags & SPSVCINST_NOCLOBBER_DISPLAYNAME)
1319                 {
1320                     HeapFree( GetProcessHeap(), 0, display_name );
1321                     display_name = strdupW( config->lpDisplayName );
1322                 }
1323                 if (flags & SPSVCINST_NOCLOBBER_LOADORDERGROUP)
1324                 {
1325                     HeapFree( GetProcessHeap(), 0, load_order );
1326                     load_order = strdupW( config->lpLoadOrderGroup );
1327                 }
1328             }
1329             HeapFree( GetProcessHeap(), 0, config );
1330         }
1331         TRACE( "changing %s display %s type %x start %x error %x binary %s loadorder %s startname %s\n",
1332                debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
1333                debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name) );
1334
1335         ChangeServiceConfigW( service, service_type, start_type, error_control, binary_path,
1336                               load_order, NULL, NULL, start_name, NULL, display_name );
1337
1338         if (!(flags & SPSVCINST_NOCLOBBER_DESCRIPTION))
1339             ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
1340     }
1341
1342     /* execute the AddReg, DelReg and BitReg entries */
1343
1344     info.default_root = 0;
1345     if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, ServicesKey, &hkey ))
1346     {
1347         RegOpenKeyW( hkey, name, &info.default_root );
1348         RegCloseKey( hkey );
1349     }
1350     if (info.default_root)
1351     {
1352         info.delete = TRUE;
1353         iterate_section_fields( hinf, section, DelReg, registry_callback, &info );
1354         info.delete = FALSE;
1355         iterate_section_fields( hinf, section, AddReg, registry_callback, &info );
1356         RegCloseKey( info.default_root );
1357     }
1358     iterate_section_fields( hinf, section, BitReg, bitreg_callback, NULL );
1359
1360     if (flags & SPSVCINST_STARTSERVICE) StartServiceW( service, 0, NULL );
1361     CloseServiceHandle( service );
1362
1363 done:
1364     if (!service) WARN( "failed err %u\n", GetLastError() );
1365     HeapFree( GetProcessHeap(), 0, binary_path );
1366     HeapFree( GetProcessHeap(), 0, display_name );
1367     HeapFree( GetProcessHeap(), 0, start_name );
1368     HeapFree( GetProcessHeap(), 0, load_order );
1369     HeapFree( GetProcessHeap(), 0, descr.lpDescription );
1370     return service != 0;
1371 }
1372
1373
1374 /***********************************************************************
1375  *            del_service
1376  *
1377  * Delete service. Helper for SetupInstallServicesFromInfSectionW.
1378  */
1379 static BOOL del_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, DWORD flags )
1380 {
1381     BOOL ret;
1382     SC_HANDLE service;
1383     SERVICE_STATUS status;
1384
1385     if (!(service = OpenServiceW( scm, name, SERVICE_STOP | DELETE )))
1386     {
1387         if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) return TRUE;
1388         WARN( "cannot open %s err %u\n", debugstr_w(name), GetLastError() );
1389         return FALSE;
1390     }
1391     if (flags & SPSVCINST_STOPSERVICE) ControlService( service, SERVICE_CONTROL_STOP, &status );
1392     TRACE( "deleting %s\n", debugstr_w(name) );
1393     ret = DeleteService( service );
1394     CloseServiceHandle( service );
1395     return ret;
1396 }
1397
1398
1399 /***********************************************************************
1400  *              SetupInstallServicesFromInfSectionW  (SETUPAPI.@)
1401  */
1402 BOOL WINAPI SetupInstallServicesFromInfSectionW( HINF hinf, PCWSTR section, DWORD flags )
1403 {
1404     WCHAR service_name[MAX_INF_STRING_LENGTH];
1405     WCHAR service_section[MAX_INF_STRING_LENGTH];
1406     SC_HANDLE scm;
1407     INFCONTEXT context;
1408     INT section_flags;
1409     BOOL ok, ret = FALSE;
1410
1411     if (!(scm = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS ))) return FALSE;
1412
1413     if (!(ok = SetupFindFirstLineW( hinf, section, AddService, &context )))
1414         SetLastError( ERROR_SECTION_NOT_FOUND );
1415     while (ok)
1416     {
1417         if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
1418             continue;
1419         if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
1420         if (!SetupGetStringFieldW( &context, 3, service_section, MAX_INF_STRING_LENGTH, NULL ))
1421             continue;
1422         if (!(ret = add_service( scm, hinf, service_name, service_section, section_flags | flags )))
1423             goto done;
1424         ok = SetupFindNextMatchLineW( &context, AddService, &context );
1425     }
1426
1427     if (!(ok = SetupFindFirstLineW( hinf, section, DelService, &context )))
1428         SetLastError( ERROR_SECTION_NOT_FOUND );
1429     while (ok)
1430     {
1431         if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
1432             continue;
1433         if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
1434         if (!(ret = del_service( scm, hinf, service_name, section_flags | flags ))) goto done;
1435         ok = SetupFindNextMatchLineW( &context, AddService, &context );
1436     }
1437     if (ret) SetLastError( ERROR_SUCCESS );
1438  done:
1439     CloseServiceHandle( scm );
1440     return ret;
1441 }
1442
1443
1444 /***********************************************************************
1445  *              SetupInstallServicesFromInfSectionA  (SETUPAPI.@)
1446  */
1447 BOOL WINAPI SetupInstallServicesFromInfSectionA( HINF Inf, PCSTR SectionName, DWORD Flags)
1448 {
1449     UNICODE_STRING SectionNameW;
1450     BOOL ret = FALSE;
1451
1452     if (RtlCreateUnicodeStringFromAsciiz( &SectionNameW, SectionName ))
1453     {
1454         ret = SetupInstallServicesFromInfSectionW( Inf, SectionNameW.Buffer, Flags );
1455         RtlFreeUnicodeString( &SectionNameW );
1456     }
1457     else
1458         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1459
1460     return ret;
1461 }
1462
1463
1464 /***********************************************************************
1465  *              SetupGetInfFileListW  (SETUPAPI.@)
1466  */
1467 BOOL WINAPI SetupGetInfFileListW(PCWSTR dir, DWORD style, PWSTR buffer,
1468                                  DWORD insize, PDWORD outsize)
1469 {
1470     static WCHAR inf[] = {'\\','*','.','i','n','f',0 };
1471     WCHAR *filter, *fullname = NULL, *ptr = buffer;
1472     DWORD dir_len, name_len = 20, size ;
1473     WIN32_FIND_DATAW finddata;
1474     HANDLE hdl;
1475     if (style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
1476                    INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
1477     {
1478         FIXME( "unknown inf_style(s) 0x%x\n",
1479                style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
1480                          INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ));
1481         if( outsize ) *outsize = 1;
1482         return TRUE;
1483     }
1484     if ((style & ( INF_STYLE_OLDNT | INF_STYLE_WIN4 )) == INF_STYLE_NONE)
1485     {
1486         FIXME( "inf_style INF_STYLE_NONE not handled\n" );
1487         if( outsize ) *outsize = 1;
1488         return TRUE;
1489     }
1490     if (style & ( INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
1491         FIXME("ignored inf_style(s) %s %s\n",
1492               ( style & INF_STYLE_CACHE_ENABLE  ) ? "INF_STYLE_CACHE_ENABLE"  : "",
1493               ( style & INF_STYLE_CACHE_DISABLE ) ? "INF_STYLE_CACHE_DISABLE" : "");
1494     if( dir )
1495     {
1496         DWORD att;
1497         DWORD msize;
1498         dir_len = strlenW( dir );
1499         if ( !dir_len ) return FALSE;
1500         msize = ( 7 + dir_len )  * sizeof( WCHAR ); /* \\*.inf\0 */
1501         filter = HeapAlloc( GetProcessHeap(), 0, msize );
1502         if( !filter )
1503         {
1504             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1505             return FALSE;
1506         }
1507         strcpyW( filter, dir );
1508         if ( '\\' == filter[dir_len - 1] )
1509             filter[--dir_len] = 0;
1510
1511         att = GetFileAttributesW( filter );
1512         if (att != INVALID_FILE_ATTRIBUTES && !(att & FILE_ATTRIBUTE_DIRECTORY))
1513         {
1514             HeapFree( GetProcessHeap(), 0, filter );
1515             SetLastError( ERROR_DIRECTORY );
1516             return FALSE;
1517         }
1518     }
1519     else
1520     {
1521         WCHAR infdir[] = {'\\','i','n','f',0 };
1522         DWORD msize;
1523         dir_len = GetWindowsDirectoryW( NULL, 0 );
1524         msize = ( 7 + 4 + dir_len ) * sizeof( WCHAR );
1525         filter = HeapAlloc( GetProcessHeap(), 0, msize );
1526         if( !filter )
1527         {
1528             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1529             return FALSE;
1530         }
1531         GetWindowsDirectoryW( filter, msize );
1532         strcatW( filter, infdir );
1533     }
1534     strcatW( filter, inf );
1535
1536     hdl = FindFirstFileW( filter , &finddata );
1537     if ( hdl == INVALID_HANDLE_VALUE )
1538     {
1539         if( outsize ) *outsize = 1;
1540         HeapFree( GetProcessHeap(), 0, filter );
1541         return TRUE;
1542     }
1543     size = 1;
1544     do
1545     {
1546         static const WCHAR key[] =
1547                {'S','i','g','n','a','t','u','r','e',0 };
1548         static const WCHAR section[] =
1549                {'V','e','r','s','i','o','n',0 };
1550         static const WCHAR sig_win4_1[] =
1551                {'$','C','h','i','c','a','g','o','$',0 };
1552         static const WCHAR sig_win4_2[] =
1553                {'$','W','I','N','D','O','W','S',' ','N','T','$',0 };
1554         WCHAR signature[ MAX_PATH ];
1555         BOOL valid = FALSE;
1556         DWORD len = strlenW( finddata.cFileName );
1557         if (!fullname || ( name_len < len ))
1558         {
1559             name_len = ( name_len < len ) ? len : name_len;
1560             HeapFree( GetProcessHeap(), 0, fullname );
1561             fullname = HeapAlloc( GetProcessHeap(), 0,
1562                                   ( 2 + dir_len + name_len) * sizeof( WCHAR ));
1563             if( !fullname )
1564             {
1565                 HeapFree( GetProcessHeap(), 0, filter );
1566                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1567                 return FALSE;
1568             }
1569             strcpyW( fullname, filter );
1570         }
1571         fullname[ dir_len + 1] = 0; /* keep '\\' */
1572         strcatW( fullname, finddata.cFileName );
1573         if (!GetPrivateProfileStringW( section, key, NULL, signature, MAX_PATH, fullname ))
1574             signature[0] = 0;
1575         if( INF_STYLE_OLDNT & style )
1576             valid = strcmpiW( sig_win4_1, signature ) &&
1577                     strcmpiW( sig_win4_2, signature );
1578         if( INF_STYLE_WIN4 & style )
1579             valid = valid || !strcmpiW( sig_win4_1, signature ) ||
1580                     !strcmpiW( sig_win4_2, signature );
1581         if( valid )
1582         {
1583             size += 1 + strlenW( finddata.cFileName );
1584             if( ptr && insize >= size )
1585             {
1586                 strcpyW( ptr, finddata.cFileName );
1587                 ptr += 1 + strlenW( finddata.cFileName );
1588                 *ptr = 0;
1589             }
1590         }
1591     }
1592     while( FindNextFileW( hdl, &finddata ));
1593     FindClose( hdl );
1594
1595     HeapFree( GetProcessHeap(), 0, fullname );
1596     HeapFree( GetProcessHeap(), 0, filter );
1597     if( outsize ) *outsize = size;
1598     return TRUE;
1599 }