d3dx9: Check register type in dcl input instruction.
[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     return ret;
717 }
718
719 /***********************************************************************
720  *            update_ini_callback
721  *
722  * Called once for each UpdateInis entry in a given section.
723  */
724 static BOOL update_ini_callback( HINF hinf, PCWSTR field, void *arg )
725 {
726     INFCONTEXT context;
727
728     BOOL ok = SetupFindFirstLineW( hinf, field, NULL, &context );
729
730     for (; ok; ok = SetupFindNextLine( &context, &context ))
731     {
732         WCHAR buffer[MAX_INF_STRING_LENGTH];
733         WCHAR  filename[MAX_INF_STRING_LENGTH];
734         WCHAR  section[MAX_INF_STRING_LENGTH];
735         WCHAR  entry[MAX_INF_STRING_LENGTH];
736         WCHAR  string[MAX_INF_STRING_LENGTH];
737         LPWSTR divider;
738
739         if (!SetupGetStringFieldW( &context, 1, filename,
740                                    sizeof(filename)/sizeof(WCHAR), NULL ))
741             continue;
742
743         if (!SetupGetStringFieldW( &context, 2, section,
744                                    sizeof(section)/sizeof(WCHAR), NULL ))
745             continue;
746
747         if (!SetupGetStringFieldW( &context, 4, buffer,
748                                    sizeof(buffer)/sizeof(WCHAR), NULL ))
749             continue;
750
751         divider = strchrW(buffer,'=');
752         if (divider)
753         {
754             *divider = 0;
755             strcpyW(entry,buffer);
756             divider++;
757             strcpyW(string,divider);
758         }
759         else
760         {
761             strcpyW(entry,buffer);
762             string[0]=0;
763         }
764
765         TRACE("Writing %s = %s in %s of file %s\n",debugstr_w(entry),
766                debugstr_w(string),debugstr_w(section),debugstr_w(filename));
767         WritePrivateProfileStringW(section,entry,string,filename);
768
769     }
770     return TRUE;
771 }
772
773 static BOOL update_ini_fields_callback( HINF hinf, PCWSTR field, void *arg )
774 {
775     FIXME( "should update ini fields %s\n", debugstr_w(field) );
776     return TRUE;
777 }
778
779 static BOOL ini2reg_callback( HINF hinf, PCWSTR field, void *arg )
780 {
781     FIXME( "should do ini2reg %s\n", debugstr_w(field) );
782     return TRUE;
783 }
784
785 static BOOL logconf_callback( HINF hinf, PCWSTR field, void *arg )
786 {
787     FIXME( "should do logconf %s\n", debugstr_w(field) );
788     return TRUE;
789 }
790
791 static BOOL bitreg_callback( HINF hinf, PCWSTR field, void *arg )
792 {
793     FIXME( "should do bitreg %s\n", debugstr_w(field) );
794     return TRUE;
795 }
796
797 static BOOL profile_items_callback( HINF hinf, PCWSTR field, void *arg )
798 {
799     WCHAR lnkpath[MAX_PATH];
800     LPWSTR cmdline=NULL, lnkpath_end;
801     unsigned int name_size;
802     INFCONTEXT name_context, context;
803     int attrs=0;
804
805     static const WCHAR dotlnk[] = {'.','l','n','k',0};
806
807     TRACE( "(%s)\n", debugstr_w(field) );
808
809     if (SetupFindFirstLineW( hinf, field, Name, &name_context ))
810     {
811         SetupGetIntField( &name_context, 2, &attrs );
812         if (attrs & ~FLG_PROFITEM_GROUP) FIXME( "unhandled attributes: %x\n", attrs );
813     }
814     else return TRUE;
815
816     /* calculate filename */
817     SHGetFolderPathW( NULL, CSIDL_COMMON_PROGRAMS, NULL, SHGFP_TYPE_CURRENT, lnkpath );
818     lnkpath_end = lnkpath + strlenW(lnkpath);
819     if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';
820
821     if (!(attrs & FLG_PROFITEM_GROUP) && SetupFindFirstLineW( hinf, field, SubDir, &context ))
822     {
823         unsigned int subdir_size;
824
825         if (!SetupGetStringFieldW( &context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &subdir_size ))
826             return TRUE;
827
828         lnkpath_end += subdir_size - 1;
829         if (lnkpath_end[-1] != '\\') *lnkpath_end++ = '\\';
830     }
831
832     if (!SetupGetStringFieldW( &name_context, 1, lnkpath_end, (lnkpath+MAX_PATH)-lnkpath_end, &name_size ))
833         return TRUE;
834
835     lnkpath_end += name_size - 1;
836
837     if (attrs & FLG_PROFITEM_GROUP)
838     {
839         SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE );
840     }
841     else
842     {
843         IShellLinkW* shelllink=NULL;
844         IPersistFile* persistfile=NULL;
845         HRESULT initresult=E_FAIL;
846
847         if (lnkpath+MAX_PATH < lnkpath_end + 5) return TRUE;
848         strcpyW( lnkpath_end, dotlnk );
849
850         TRACE( "link path: %s\n", debugstr_w(lnkpath) );
851
852         /* calculate command line */
853         if (SetupFindFirstLineW( hinf, field, CmdLine, &context ))
854         {
855             unsigned int dir_len=0, subdir_size=0, filename_size=0;
856             int dirid=0;
857             LPCWSTR dir;
858             LPWSTR cmdline_end;
859
860             SetupGetIntField( &context, 1, &dirid );
861             dir = DIRID_get_string( dirid );
862
863             if (dir) dir_len = strlenW(dir);
864
865             SetupGetStringFieldW( &context, 2, NULL, 0, &subdir_size );
866             SetupGetStringFieldW( &context, 3, NULL, 0, &filename_size );
867
868             if (dir_len && filename_size)
869             {
870                 cmdline = cmdline_end = HeapAlloc( GetProcessHeap(), 0, sizeof(WCHAR) * (dir_len+subdir_size+filename_size+1) );
871
872                 strcpyW( cmdline_end, dir );
873                 cmdline_end += dir_len;
874                 if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
875
876                 if (subdir_size)
877                 {
878                     SetupGetStringFieldW( &context, 2, cmdline_end, subdir_size, NULL );
879                     cmdline_end += subdir_size-1;
880                     if (cmdline_end[-1] != '\\') *cmdline_end++ = '\\';
881                 }
882                 SetupGetStringFieldW( &context, 3, cmdline_end, filename_size, NULL );
883                 TRACE( "cmdline: %s\n", debugstr_w(cmdline));
884             }
885         }
886
887         if (!cmdline) return TRUE;
888
889         initresult = CoInitialize(NULL);
890
891         if (FAILED(CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
892                                      &IID_IShellLinkW, (LPVOID*)&shelllink )))
893             goto done;
894
895         IShellLinkW_SetPath( shelllink, cmdline );
896         SHPathPrepareForWriteW( NULL, NULL, lnkpath, SHPPFW_DIRCREATE|SHPPFW_IGNOREFILENAME );
897         if (SUCCEEDED(IShellLinkW_QueryInterface( shelllink, &IID_IPersistFile, (LPVOID*)&persistfile)))
898         {
899             TRACE( "writing link: %s\n", debugstr_w(lnkpath) );
900             IPersistFile_Save( persistfile, lnkpath, FALSE );
901             IPersistFile_Release( persistfile );
902         }
903         IShellLinkW_Release( shelllink );
904
905     done:
906         if (SUCCEEDED(initresult)) CoUninitialize();
907         HeapFree( GetProcessHeap(), 0, cmdline );
908     }
909
910     return TRUE;
911 }
912
913 static BOOL copy_inf_callback( HINF hinf, PCWSTR field, void *arg )
914 {
915     FIXME( "should do copy inf %s\n", debugstr_w(field) );
916     return TRUE;
917 }
918
919
920 /***********************************************************************
921  *            iterate_section_fields
922  *
923  * Iterate over all fields of a certain key of a certain section
924  */
925 static BOOL iterate_section_fields( HINF hinf, PCWSTR section, PCWSTR key,
926                                     iterate_fields_func callback, void *arg )
927 {
928     WCHAR static_buffer[200];
929     WCHAR *buffer = static_buffer;
930     DWORD size = sizeof(static_buffer)/sizeof(WCHAR);
931     INFCONTEXT context;
932     BOOL ret = FALSE;
933
934     BOOL ok = SetupFindFirstLineW( hinf, section, key, &context );
935     while (ok)
936     {
937         UINT i, count = SetupGetFieldCount( &context );
938         for (i = 1; i <= count; i++)
939         {
940             if (!(buffer = get_field_string( &context, i, buffer, static_buffer, &size )))
941                 goto done;
942             if (!callback( hinf, buffer, arg ))
943             {
944                 WARN("callback failed for %s %s err %d\n",
945                      debugstr_w(section), debugstr_w(buffer), GetLastError() );
946                 goto done;
947             }
948         }
949         ok = SetupFindNextMatchLineW( &context, key, &context );
950     }
951     ret = TRUE;
952  done:
953     if (buffer != static_buffer) HeapFree( GetProcessHeap(), 0, buffer );
954     return ret;
955 }
956
957
958 /***********************************************************************
959  *            SetupInstallFilesFromInfSectionA   (SETUPAPI.@)
960  */
961 BOOL WINAPI SetupInstallFilesFromInfSectionA( HINF hinf, HINF hlayout, HSPFILEQ queue,
962                                               PCSTR section, PCSTR src_root, UINT flags )
963 {
964     UNICODE_STRING sectionW;
965     BOOL ret = FALSE;
966
967     if (!RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
968     {
969         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
970         return FALSE;
971     }
972     if (!src_root)
973         ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
974                                                 NULL, flags );
975     else
976     {
977         UNICODE_STRING srcW;
978         if (RtlCreateUnicodeStringFromAsciiz( &srcW, src_root ))
979         {
980             ret = SetupInstallFilesFromInfSectionW( hinf, hlayout, queue, sectionW.Buffer,
981                                                     srcW.Buffer, flags );
982             RtlFreeUnicodeString( &srcW );
983         }
984         else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
985     }
986     RtlFreeUnicodeString( &sectionW );
987     return ret;
988 }
989
990
991 /***********************************************************************
992  *            SetupInstallFilesFromInfSectionW   (SETUPAPI.@)
993  */
994 BOOL WINAPI SetupInstallFilesFromInfSectionW( HINF hinf, HINF hlayout, HSPFILEQ queue,
995                                               PCWSTR section, PCWSTR src_root, UINT flags )
996 {
997     struct files_callback_info info;
998
999     info.queue      = queue;
1000     info.src_root   = src_root;
1001     info.copy_flags = flags;
1002     info.layout     = hlayout;
1003     return iterate_section_fields( hinf, section, CopyFiles, copy_files_callback, &info );
1004 }
1005
1006
1007 /***********************************************************************
1008  *            SetupInstallFromInfSectionA   (SETUPAPI.@)
1009  */
1010 BOOL WINAPI SetupInstallFromInfSectionA( HWND owner, HINF hinf, PCSTR section, UINT flags,
1011                                          HKEY key_root, PCSTR src_root, UINT copy_flags,
1012                                          PSP_FILE_CALLBACK_A callback, PVOID context,
1013                                          HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
1014 {
1015     UNICODE_STRING sectionW, src_rootW;
1016     struct callback_WtoA_context ctx;
1017     BOOL ret = FALSE;
1018
1019     src_rootW.Buffer = NULL;
1020     if (src_root && !RtlCreateUnicodeStringFromAsciiz( &src_rootW, src_root ))
1021     {
1022         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1023         return FALSE;
1024     }
1025
1026     if (RtlCreateUnicodeStringFromAsciiz( &sectionW, section ))
1027     {
1028         ctx.orig_context = context;
1029         ctx.orig_handler = callback;
1030         ret = SetupInstallFromInfSectionW( owner, hinf, sectionW.Buffer, flags, key_root,
1031                                            src_rootW.Buffer, copy_flags, QUEUE_callback_WtoA,
1032                                            &ctx, devinfo, devinfo_data );
1033         RtlFreeUnicodeString( &sectionW );
1034     }
1035     else SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1036
1037     RtlFreeUnicodeString( &src_rootW );
1038     return ret;
1039 }
1040
1041
1042 /***********************************************************************
1043  *            SetupInstallFromInfSectionW   (SETUPAPI.@)
1044  */
1045 BOOL WINAPI SetupInstallFromInfSectionW( HWND owner, HINF hinf, PCWSTR section, UINT flags,
1046                                          HKEY key_root, PCWSTR src_root, UINT copy_flags,
1047                                          PSP_FILE_CALLBACK_W callback, PVOID context,
1048                                          HDEVINFO devinfo, PSP_DEVINFO_DATA devinfo_data )
1049 {
1050     if (flags & SPINST_FILES)
1051     {
1052         struct files_callback_info info;
1053         HSPFILEQ queue;
1054         BOOL ret;
1055
1056         if (!(queue = SetupOpenFileQueue())) return FALSE;
1057         info.queue      = queue;
1058         info.src_root   = src_root;
1059         info.copy_flags = copy_flags;
1060         info.layout     = hinf;
1061         ret = (iterate_section_fields( hinf, section, CopyFiles, copy_files_callback, &info ) &&
1062                iterate_section_fields( hinf, section, DelFiles, delete_files_callback, &info ) &&
1063                iterate_section_fields( hinf, section, RenFiles, rename_files_callback, &info ) &&
1064                SetupCommitFileQueueW( owner, queue, callback, context ));
1065         SetupCloseFileQueue( queue );
1066         if (!ret) return FALSE;
1067     }
1068     if (flags & SPINST_INIFILES)
1069     {
1070         if (!iterate_section_fields( hinf, section, UpdateInis, update_ini_callback, NULL ) ||
1071             !iterate_section_fields( hinf, section, UpdateIniFields,
1072                                      update_ini_fields_callback, NULL ))
1073             return FALSE;
1074     }
1075     if (flags & SPINST_INI2REG)
1076     {
1077         if (!iterate_section_fields( hinf, section, Ini2Reg, ini2reg_callback, NULL ))
1078             return FALSE;
1079     }
1080     if (flags & SPINST_LOGCONFIG)
1081     {
1082         if (!iterate_section_fields( hinf, section, LogConf, logconf_callback, NULL ))
1083             return FALSE;
1084     }
1085     if (flags & SPINST_REGSVR)
1086     {
1087         struct register_dll_info info;
1088
1089         info.unregister = FALSE;
1090         if (flags & SPINST_REGISTERCALLBACKAWARE)
1091         {
1092             info.callback         = callback;
1093             info.callback_context = context;
1094         }
1095         else info.callback = NULL;
1096
1097         if (iterate_section_fields( hinf, section, WineFakeDlls, fake_dlls_callback, NULL ))
1098             cleanup_fake_dlls();
1099         else
1100             return FALSE;
1101
1102         if (!iterate_section_fields( hinf, section, RegisterDlls, register_dlls_callback, &info ))
1103             return FALSE;
1104     }
1105     if (flags & SPINST_UNREGSVR)
1106     {
1107         struct register_dll_info info;
1108
1109         info.unregister = TRUE;
1110         if (flags & SPINST_REGISTERCALLBACKAWARE)
1111         {
1112             info.callback         = callback;
1113             info.callback_context = context;
1114         }
1115         else info.callback = NULL;
1116
1117         if (!iterate_section_fields( hinf, section, UnregisterDlls, register_dlls_callback, &info ))
1118             return FALSE;
1119     }
1120     if (flags & SPINST_REGISTRY)
1121     {
1122         struct registry_callback_info info;
1123
1124         info.default_root = key_root;
1125         info.delete = TRUE;
1126         if (!iterate_section_fields( hinf, section, DelReg, registry_callback, &info ))
1127             return FALSE;
1128         info.delete = FALSE;
1129         if (!iterate_section_fields( hinf, section, AddReg, registry_callback, &info ))
1130             return FALSE;
1131     }
1132     if (flags & SPINST_BITREG)
1133     {
1134         if (!iterate_section_fields( hinf, section, BitReg, bitreg_callback, NULL ))
1135             return FALSE;
1136     }
1137     if (flags & SPINST_PROFILEITEMS)
1138     {
1139         if (!iterate_section_fields( hinf, section, ProfileItems, profile_items_callback, NULL ))
1140             return FALSE;
1141     }
1142     if (flags & SPINST_COPYINF)
1143     {
1144         if (!iterate_section_fields( hinf, section, CopyINF, copy_inf_callback, NULL ))
1145             return FALSE;
1146     }
1147
1148     return TRUE;
1149 }
1150
1151
1152 /***********************************************************************
1153  *              InstallHinfSectionW  (SETUPAPI.@)
1154  *
1155  * NOTE: 'cmdline' is <section> <mode> <path> from
1156  *   RUNDLL32.EXE SETUPAPI.DLL,InstallHinfSection <section> <mode> <path>
1157  */
1158 void WINAPI InstallHinfSectionW( HWND hwnd, HINSTANCE handle, LPCWSTR cmdline, INT show )
1159 {
1160 #ifdef __i386__
1161     static const WCHAR nt_platformW[] = {'.','n','t','x','8','6',0};
1162 #elif defined(__x86_64)
1163     static const WCHAR nt_platformW[] = {'.','n','t','a','m','d','6','4',0};
1164 #else  /* FIXME: other platforms */
1165     static const WCHAR nt_platformW[] = {'.','n','t',0};
1166 #endif
1167     static const WCHAR nt_genericW[] = {'.','n','t',0};
1168     static const WCHAR servicesW[] = {'.','S','e','r','v','i','c','e','s',0};
1169
1170     WCHAR *s, *path, section[MAX_PATH + (sizeof(nt_platformW) + sizeof(servicesW)) / sizeof(WCHAR)];
1171     void *callback_context;
1172     UINT mode;
1173     HINF hinf;
1174
1175     TRACE("hwnd %p, handle %p, cmdline %s\n", hwnd, handle, debugstr_w(cmdline));
1176
1177     lstrcpynW( section, cmdline, MAX_PATH );
1178
1179     if (!(s = strchrW( section, ' ' ))) return;
1180     *s++ = 0;
1181     while (*s == ' ') s++;
1182     mode = atoiW( s );
1183
1184     /* quoted paths are not allowed on native, the rest of the command line is taken as the path */
1185     if (!(s = strchrW( s, ' ' ))) return;
1186     while (*s == ' ') s++;
1187     path = s;
1188
1189     hinf = SetupOpenInfFileW( path, NULL, INF_STYLE_WIN4, NULL );
1190     if (hinf == INVALID_HANDLE_VALUE) return;
1191
1192     if (!(GetVersion() & 0x80000000))
1193     {
1194         INFCONTEXT context;
1195
1196         /* check for <section>.ntx86 (or corresponding name for the current platform)
1197          * and then <section>.nt */
1198         s = section + strlenW(section);
1199         memcpy( s, nt_platformW, sizeof(nt_platformW) );
1200         if (!(SetupFindFirstLineW( hinf, section, NULL, &context )))
1201         {
1202             memcpy( s, nt_genericW, sizeof(nt_genericW) );
1203             if (!(SetupFindFirstLineW( hinf, section, NULL, &context ))) *s = 0;
1204         }
1205         if (*s) TRACE( "using section %s instead\n", debugstr_w(section) );
1206     }
1207
1208     callback_context = SetupInitDefaultQueueCallback( hwnd );
1209     SetupInstallFromInfSectionW( hwnd, hinf, section, SPINST_ALL, NULL, NULL, SP_COPY_NEWER,
1210                                  SetupDefaultQueueCallbackW, callback_context,
1211                                  NULL, NULL );
1212     SetupTermDefaultQueueCallback( callback_context );
1213     strcatW( section, servicesW );
1214     SetupInstallServicesFromInfSectionW( hinf, section, 0 );
1215     SetupCloseInfFile( hinf );
1216
1217     /* FIXME: should check the mode and maybe reboot */
1218     /* there isn't much point in doing that since we */
1219     /* don't yet handle deferred file copies anyway. */
1220 }
1221
1222
1223 /***********************************************************************
1224  *              InstallHinfSectionA  (SETUPAPI.@)
1225  */
1226 void WINAPI InstallHinfSectionA( HWND hwnd, HINSTANCE handle, LPCSTR cmdline, INT show )
1227 {
1228     UNICODE_STRING cmdlineW;
1229
1230     if (RtlCreateUnicodeStringFromAsciiz( &cmdlineW, cmdline ))
1231     {
1232         InstallHinfSectionW( hwnd, handle, cmdlineW.Buffer, show );
1233         RtlFreeUnicodeString( &cmdlineW );
1234     }
1235 }
1236
1237
1238 /***********************************************************************
1239  *            add_service
1240  *
1241  * Create a new service. Helper for SetupInstallServicesFromInfSectionW.
1242  */
1243 static BOOL add_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, const WCHAR *section, DWORD flags )
1244 {
1245     struct registry_callback_info info;
1246     SC_HANDLE service;
1247     INFCONTEXT context;
1248     SERVICE_DESCRIPTIONW descr;
1249     WCHAR *display_name, *start_name, *load_order, *binary_path;
1250     INT service_type = 0, start_type = 0, error_control = 0;
1251     DWORD size;
1252     HKEY hkey;
1253
1254     /* first the mandatory fields */
1255
1256     if (!SetupFindFirstLineW( hinf, section, ServiceType, &context ) ||
1257         !SetupGetIntField( &context, 1, &service_type ))
1258     {
1259         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1260         return FALSE;
1261     }
1262     if (!SetupFindFirstLineW( hinf, section, StartType, &context ) ||
1263         !SetupGetIntField( &context, 1, &start_type ))
1264     {
1265         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1266         return FALSE;
1267     }
1268     if (!SetupFindFirstLineW( hinf, section, ErrorControl, &context ) ||
1269         !SetupGetIntField( &context, 1, &error_control ))
1270     {
1271         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1272         return FALSE;
1273     }
1274     if (!(binary_path = dup_section_line_field( hinf, section, ServiceBinary, 1 )))
1275     {
1276         SetLastError( ERROR_BAD_SERVICE_INSTALLSECT );
1277         return FALSE;
1278     }
1279
1280     /* now the optional fields */
1281
1282     display_name = dup_section_line_field( hinf, section, DisplayName, 1 );
1283     start_name = dup_section_line_field( hinf, section, StartName, 1 );
1284     load_order = dup_section_line_field( hinf, section, LoadOrderGroup, 1 );
1285     descr.lpDescription = dup_section_line_field( hinf, section, Description, 1 );
1286
1287     /* FIXME: Dependencies field */
1288     /* FIXME: Security field */
1289
1290     TRACE( "service %s display %s type %x start %x error %x binary %s order %s startname %s flags %x\n",
1291            debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
1292            debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name), flags );
1293
1294     service = CreateServiceW( scm, name, display_name, SERVICE_ALL_ACCESS,
1295                               service_type, start_type, error_control, binary_path,
1296                               load_order, NULL, NULL, start_name, NULL );
1297     if (service)
1298     {
1299         if (descr.lpDescription) ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
1300     }
1301     else
1302     {
1303         if (GetLastError() != ERROR_SERVICE_EXISTS) goto done;
1304         service = OpenServiceW( scm, name, SERVICE_QUERY_CONFIG|SERVICE_CHANGE_CONFIG|SERVICE_START );
1305         if (!service) goto done;
1306
1307         if (flags & (SPSVCINST_NOCLOBBER_DISPLAYNAME | SPSVCINST_NOCLOBBER_STARTTYPE |
1308                      SPSVCINST_NOCLOBBER_ERRORCONTROL | SPSVCINST_NOCLOBBER_LOADORDERGROUP))
1309         {
1310             QUERY_SERVICE_CONFIGW *config = NULL;
1311
1312             if (!QueryServiceConfigW( service, NULL, 0, &size ) &&
1313                 GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1314                 config = HeapAlloc( GetProcessHeap(), 0, size );
1315             if (config && QueryServiceConfigW( service, config, size, &size ))
1316             {
1317                 if (flags & SPSVCINST_NOCLOBBER_STARTTYPE) start_type = config->dwStartType;
1318                 if (flags & SPSVCINST_NOCLOBBER_ERRORCONTROL) error_control = config->dwErrorControl;
1319                 if (flags & SPSVCINST_NOCLOBBER_DISPLAYNAME)
1320                 {
1321                     HeapFree( GetProcessHeap(), 0, display_name );
1322                     display_name = strdupW( config->lpDisplayName );
1323                 }
1324                 if (flags & SPSVCINST_NOCLOBBER_LOADORDERGROUP)
1325                 {
1326                     HeapFree( GetProcessHeap(), 0, load_order );
1327                     load_order = strdupW( config->lpLoadOrderGroup );
1328                 }
1329             }
1330             HeapFree( GetProcessHeap(), 0, config );
1331         }
1332         TRACE( "changing %s display %s type %x start %x error %x binary %s loadorder %s startname %s\n",
1333                debugstr_w(name), debugstr_w(display_name), service_type, start_type, error_control,
1334                debugstr_w(binary_path), debugstr_w(load_order), debugstr_w(start_name) );
1335
1336         ChangeServiceConfigW( service, service_type, start_type, error_control, binary_path,
1337                               load_order, NULL, NULL, start_name, NULL, display_name );
1338
1339         if (!(flags & SPSVCINST_NOCLOBBER_DESCRIPTION))
1340             ChangeServiceConfig2W( service, SERVICE_CONFIG_DESCRIPTION, &descr );
1341     }
1342
1343     /* execute the AddReg, DelReg and BitReg entries */
1344
1345     info.default_root = 0;
1346     if (!RegOpenKeyW( HKEY_LOCAL_MACHINE, ServicesKey, &hkey ))
1347     {
1348         RegOpenKeyW( hkey, name, &info.default_root );
1349         RegCloseKey( hkey );
1350     }
1351     if (info.default_root)
1352     {
1353         info.delete = TRUE;
1354         iterate_section_fields( hinf, section, DelReg, registry_callback, &info );
1355         info.delete = FALSE;
1356         iterate_section_fields( hinf, section, AddReg, registry_callback, &info );
1357         RegCloseKey( info.default_root );
1358     }
1359     iterate_section_fields( hinf, section, BitReg, bitreg_callback, NULL );
1360
1361     if (flags & SPSVCINST_STARTSERVICE) StartServiceW( service, 0, NULL );
1362     CloseServiceHandle( service );
1363
1364 done:
1365     if (!service) WARN( "failed err %u\n", GetLastError() );
1366     HeapFree( GetProcessHeap(), 0, binary_path );
1367     HeapFree( GetProcessHeap(), 0, display_name );
1368     HeapFree( GetProcessHeap(), 0, start_name );
1369     HeapFree( GetProcessHeap(), 0, load_order );
1370     HeapFree( GetProcessHeap(), 0, descr.lpDescription );
1371     return service != 0;
1372 }
1373
1374
1375 /***********************************************************************
1376  *            del_service
1377  *
1378  * Delete service. Helper for SetupInstallServicesFromInfSectionW.
1379  */
1380 static BOOL del_service( SC_HANDLE scm, HINF hinf, const WCHAR *name, DWORD flags )
1381 {
1382     BOOL ret;
1383     SC_HANDLE service;
1384     SERVICE_STATUS status;
1385
1386     if (!(service = OpenServiceW( scm, name, SERVICE_STOP | DELETE )))
1387     {
1388         if (GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST) return TRUE;
1389         WARN( "cannot open %s err %u\n", debugstr_w(name), GetLastError() );
1390         return FALSE;
1391     }
1392     if (flags & SPSVCINST_STOPSERVICE) ControlService( service, SERVICE_CONTROL_STOP, &status );
1393     TRACE( "deleting %s\n", debugstr_w(name) );
1394     ret = DeleteService( service );
1395     CloseServiceHandle( service );
1396     return ret;
1397 }
1398
1399
1400 /***********************************************************************
1401  *              SetupInstallServicesFromInfSectionW  (SETUPAPI.@)
1402  */
1403 BOOL WINAPI SetupInstallServicesFromInfSectionW( HINF hinf, PCWSTR section, DWORD flags )
1404 {
1405     WCHAR service_name[MAX_INF_STRING_LENGTH];
1406     WCHAR service_section[MAX_INF_STRING_LENGTH];
1407     SC_HANDLE scm;
1408     INFCONTEXT context;
1409     INT section_flags;
1410     BOOL ok, ret = FALSE;
1411
1412     if (!(scm = OpenSCManagerW( NULL, NULL, SC_MANAGER_ALL_ACCESS ))) return FALSE;
1413
1414     if (!(ok = SetupFindFirstLineW( hinf, section, AddService, &context )))
1415         SetLastError( ERROR_SECTION_NOT_FOUND );
1416     while (ok)
1417     {
1418         if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
1419             continue;
1420         if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
1421         if (!SetupGetStringFieldW( &context, 3, service_section, MAX_INF_STRING_LENGTH, NULL ))
1422             continue;
1423         if (!(ret = add_service( scm, hinf, service_name, service_section, section_flags | flags )))
1424             goto done;
1425         ok = SetupFindNextMatchLineW( &context, AddService, &context );
1426     }
1427
1428     if (!(ok = SetupFindFirstLineW( hinf, section, DelService, &context )))
1429         SetLastError( ERROR_SECTION_NOT_FOUND );
1430     while (ok)
1431     {
1432         if (!SetupGetStringFieldW( &context, 1, service_name, MAX_INF_STRING_LENGTH, NULL ))
1433             continue;
1434         if (!SetupGetIntField( &context, 2, &section_flags )) section_flags = 0;
1435         if (!(ret = del_service( scm, hinf, service_name, section_flags | flags ))) goto done;
1436         ok = SetupFindNextMatchLineW( &context, AddService, &context );
1437     }
1438     if (ret) SetLastError( ERROR_SUCCESS );
1439  done:
1440     CloseServiceHandle( scm );
1441     return ret;
1442 }
1443
1444
1445 /***********************************************************************
1446  *              SetupInstallServicesFromInfSectionA  (SETUPAPI.@)
1447  */
1448 BOOL WINAPI SetupInstallServicesFromInfSectionA( HINF Inf, PCSTR SectionName, DWORD Flags)
1449 {
1450     UNICODE_STRING SectionNameW;
1451     BOOL ret = FALSE;
1452
1453     if (RtlCreateUnicodeStringFromAsciiz( &SectionNameW, SectionName ))
1454     {
1455         ret = SetupInstallServicesFromInfSectionW( Inf, SectionNameW.Buffer, Flags );
1456         RtlFreeUnicodeString( &SectionNameW );
1457     }
1458     else
1459         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1460
1461     return ret;
1462 }
1463
1464
1465 /***********************************************************************
1466  *              SetupGetInfFileListA  (SETUPAPI.@)
1467  */
1468 BOOL WINAPI SetupGetInfFileListA(PCSTR dir, DWORD style, PSTR buffer,
1469                                  DWORD insize, PDWORD outsize)
1470 {
1471     UNICODE_STRING dirW;
1472     PWSTR bufferW = NULL;
1473     BOOL ret = FALSE;
1474     DWORD outsizeA, outsizeW;
1475
1476     if ( dir )
1477         RtlCreateUnicodeStringFromAsciiz( &dirW, dir );
1478     else
1479         dirW.Buffer = NULL;
1480
1481     if ( buffer )
1482         bufferW = HeapAlloc( GetProcessHeap(), 0, insize * sizeof( WCHAR ));
1483
1484     ret = SetupGetInfFileListW( dirW.Buffer, style, bufferW, insize, &outsizeW);
1485
1486     if ( ret )
1487     {
1488         outsizeA = WideCharToMultiByte( CP_ACP, 0, bufferW, outsizeW,
1489                                         buffer, insize, NULL, NULL);
1490         if ( outsize ) *outsize = outsizeA;
1491     }
1492
1493     HeapFree( GetProcessHeap(), 0, bufferW );
1494     RtlFreeUnicodeString( &dirW );
1495     return ret;
1496 }
1497
1498
1499 /***********************************************************************
1500  *              SetupGetInfFileListW  (SETUPAPI.@)
1501  */
1502 BOOL WINAPI SetupGetInfFileListW(PCWSTR dir, DWORD style, PWSTR buffer,
1503                                  DWORD insize, PDWORD outsize)
1504 {
1505     static WCHAR inf[] = {'\\','*','.','i','n','f',0 };
1506     WCHAR *filter, *fullname = NULL, *ptr = buffer;
1507     DWORD dir_len, name_len = 20, size ;
1508     WIN32_FIND_DATAW finddata;
1509     HANDLE hdl;
1510     if (style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
1511                    INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
1512     {
1513         FIXME( "unknown inf_style(s) 0x%x\n",
1514                style & ~( INF_STYLE_OLDNT | INF_STYLE_WIN4 |
1515                          INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ));
1516         if( outsize ) *outsize = 1;
1517         return TRUE;
1518     }
1519     if ((style & ( INF_STYLE_OLDNT | INF_STYLE_WIN4 )) == INF_STYLE_NONE)
1520     {
1521         FIXME( "inf_style INF_STYLE_NONE not handled\n" );
1522         if( outsize ) *outsize = 1;
1523         return TRUE;
1524     }
1525     if (style & ( INF_STYLE_CACHE_ENABLE | INF_STYLE_CACHE_DISABLE ))
1526         FIXME("ignored inf_style(s) %s %s\n",
1527               ( style & INF_STYLE_CACHE_ENABLE  ) ? "INF_STYLE_CACHE_ENABLE"  : "",
1528               ( style & INF_STYLE_CACHE_DISABLE ) ? "INF_STYLE_CACHE_DISABLE" : "");
1529     if( dir )
1530     {
1531         DWORD att;
1532         DWORD msize;
1533         dir_len = strlenW( dir );
1534         if ( !dir_len ) return FALSE;
1535         msize = ( 7 + dir_len )  * sizeof( WCHAR ); /* \\*.inf\0 */
1536         filter = HeapAlloc( GetProcessHeap(), 0, msize );
1537         if( !filter )
1538         {
1539             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1540             return FALSE;
1541         }
1542         strcpyW( filter, dir );
1543         if ( '\\' == filter[dir_len - 1] )
1544             filter[--dir_len] = 0;
1545
1546         att = GetFileAttributesW( filter );
1547         if (att != INVALID_FILE_ATTRIBUTES && !(att & FILE_ATTRIBUTE_DIRECTORY))
1548         {
1549             HeapFree( GetProcessHeap(), 0, filter );
1550             SetLastError( ERROR_DIRECTORY );
1551             return FALSE;
1552         }
1553     }
1554     else
1555     {
1556         WCHAR infdir[] = {'\\','i','n','f',0 };
1557         DWORD msize;
1558         dir_len = GetWindowsDirectoryW( NULL, 0 );
1559         msize = ( 7 + 4 + dir_len ) * sizeof( WCHAR );
1560         filter = HeapAlloc( GetProcessHeap(), 0, msize );
1561         if( !filter )
1562         {
1563             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1564             return FALSE;
1565         }
1566         GetWindowsDirectoryW( filter, msize );
1567         strcatW( filter, infdir );
1568     }
1569     strcatW( filter, inf );
1570
1571     hdl = FindFirstFileW( filter , &finddata );
1572     if ( hdl == INVALID_HANDLE_VALUE )
1573     {
1574         if( outsize ) *outsize = 1;
1575         HeapFree( GetProcessHeap(), 0, filter );
1576         return TRUE;
1577     }
1578     size = 1;
1579     do
1580     {
1581         static const WCHAR key[] =
1582                {'S','i','g','n','a','t','u','r','e',0 };
1583         static const WCHAR section[] =
1584                {'V','e','r','s','i','o','n',0 };
1585         static const WCHAR sig_win4_1[] =
1586                {'$','C','h','i','c','a','g','o','$',0 };
1587         static const WCHAR sig_win4_2[] =
1588                {'$','W','I','N','D','O','W','S',' ','N','T','$',0 };
1589         WCHAR signature[ MAX_PATH ];
1590         BOOL valid = FALSE;
1591         DWORD len = strlenW( finddata.cFileName );
1592         if (!fullname || ( name_len < len ))
1593         {
1594             name_len = ( name_len < len ) ? len : name_len;
1595             HeapFree( GetProcessHeap(), 0, fullname );
1596             fullname = HeapAlloc( GetProcessHeap(), 0,
1597                                   ( 2 + dir_len + name_len) * sizeof( WCHAR ));
1598             if( !fullname )
1599             {
1600                 HeapFree( GetProcessHeap(), 0, filter );
1601                 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1602                 return FALSE;
1603             }
1604             strcpyW( fullname, filter );
1605         }
1606         fullname[ dir_len + 1] = 0; /* keep '\\' */
1607         strcatW( fullname, finddata.cFileName );
1608         if (!GetPrivateProfileStringW( section, key, NULL, signature, MAX_PATH, fullname ))
1609             signature[0] = 0;
1610         if( INF_STYLE_OLDNT & style )
1611             valid = strcmpiW( sig_win4_1, signature ) &&
1612                     strcmpiW( sig_win4_2, signature );
1613         if( INF_STYLE_WIN4 & style )
1614             valid = valid || !strcmpiW( sig_win4_1, signature ) ||
1615                     !strcmpiW( sig_win4_2, signature );
1616         if( valid )
1617         {
1618             size += 1 + strlenW( finddata.cFileName );
1619             if( ptr && insize >= size )
1620             {
1621                 strcpyW( ptr, finddata.cFileName );
1622                 ptr += 1 + strlenW( finddata.cFileName );
1623                 *ptr = 0;
1624             }
1625         }
1626     }
1627     while( FindNextFileW( hdl, &finddata ));
1628     FindClose( hdl );
1629
1630     HeapFree( GetProcessHeap(), 0, fullname );
1631     HeapFree( GetProcessHeap(), 0, filter );
1632     if( outsize ) *outsize = size;
1633     return TRUE;
1634 }