jscript: Rename jsheap_t to heap_pool_t.
[wine] / dlls / msi / package.c
1 /*
2  * Implementation of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2004 Aric Stewart 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 #define NONAMELESSUNION
22 #define NONAMELESSSTRUCT
23 #define COBJMACROS
24
25 #include <stdarg.h>
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "shlwapi.h"
31 #include "wingdi.h"
32 #include "wine/debug.h"
33 #include "msi.h"
34 #include "msiquery.h"
35 #include "objidl.h"
36 #include "wincrypt.h"
37 #include "winuser.h"
38 #include "wininet.h"
39 #include "winver.h"
40 #include "urlmon.h"
41 #include "shlobj.h"
42 #include "wine/unicode.h"
43 #include "objbase.h"
44 #include "msidefs.h"
45 #include "sddl.h"
46
47 #include "msipriv.h"
48 #include "msiserver.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(msi);
51
52 static void remove_tracked_tempfiles( MSIPACKAGE *package )
53 {
54     struct list *item, *cursor;
55
56     LIST_FOR_EACH_SAFE( item, cursor, &package->tempfiles )
57     {
58         MSITEMPFILE *temp = LIST_ENTRY( item, MSITEMPFILE, entry );
59
60         list_remove( &temp->entry );
61         TRACE("deleting temp file %s\n", debugstr_w( temp->Path ));
62         DeleteFileW( temp->Path );
63         msi_free( temp->Path );
64         msi_free( temp );
65     }
66 }
67
68 static void free_feature( MSIFEATURE *feature )
69 {
70     struct list *item, *cursor;
71
72     LIST_FOR_EACH_SAFE( item, cursor, &feature->Children )
73     {
74         FeatureList *fl = LIST_ENTRY( item, FeatureList, entry );
75         list_remove( &fl->entry );
76         msi_free( fl );
77     }
78
79     LIST_FOR_EACH_SAFE( item, cursor, &feature->Components )
80     {
81         ComponentList *cl = LIST_ENTRY( item, ComponentList, entry );
82         list_remove( &cl->entry );
83         msi_free( cl );
84     }
85     msi_free( feature->Feature );
86     msi_free( feature->Feature_Parent );
87     msi_free( feature->Directory );
88     msi_free( feature->Description );
89     msi_free( feature->Title );
90     msi_free( feature );
91 }
92
93 static void free_folder( MSIFOLDER *folder )
94 {
95     struct list *item, *cursor;
96
97     LIST_FOR_EACH_SAFE( item, cursor, &folder->children )
98     {
99         FolderList *fl = LIST_ENTRY( item, FolderList, entry );
100         list_remove( &fl->entry );
101         msi_free( fl );
102     }
103     msi_free( folder->Parent );
104     msi_free( folder->Directory );
105     msi_free( folder->TargetDefault );
106     msi_free( folder->SourceLongPath );
107     msi_free( folder->SourceShortPath );
108     msi_free( folder->ResolvedTarget );
109     msi_free( folder->ResolvedSource );
110     msi_free( folder );
111 }
112
113 static void free_extension( MSIEXTENSION *ext )
114 {
115     struct list *item, *cursor;
116
117     LIST_FOR_EACH_SAFE( item, cursor, &ext->verbs )
118     {
119         MSIVERB *verb = LIST_ENTRY( item, MSIVERB, entry );
120
121         list_remove( &verb->entry );
122         msi_free( verb->Verb );
123         msi_free( verb->Command );
124         msi_free( verb->Argument );
125         msi_free( verb );
126     }
127
128     msi_free( ext->Extension );
129     msi_free( ext->ProgIDText );
130     msi_free( ext );
131 }
132
133 static void free_assembly( MSIASSEMBLY *assembly )
134 {
135     msi_free( assembly->feature );
136     msi_free( assembly->manifest );
137     msi_free( assembly->application );
138     msi_free( assembly->display_name );
139     if (assembly->tempdir) RemoveDirectoryW( assembly->tempdir );
140     msi_free( assembly->tempdir );
141     msi_free( assembly );
142 }
143
144 void msi_free_action_script( MSIPACKAGE *package, UINT script )
145 {
146     UINT i;
147     for (i = 0; i < package->script->ActionCount[script]; i++)
148         msi_free( package->script->Actions[script][i] );
149
150     msi_free( package->script->Actions[script] );
151     package->script->Actions[script] = NULL;
152     package->script->ActionCount[script] = 0;
153 }
154
155 static void free_package_structures( MSIPACKAGE *package )
156 {
157     INT i;
158     struct list *item, *cursor;
159
160     LIST_FOR_EACH_SAFE( item, cursor, &package->features )
161     {
162         MSIFEATURE *feature = LIST_ENTRY( item, MSIFEATURE, entry );
163         list_remove( &feature->entry );
164         free_feature( feature );
165     }
166
167     LIST_FOR_EACH_SAFE( item, cursor, &package->folders )
168     {
169         MSIFOLDER *folder = LIST_ENTRY( item, MSIFOLDER, entry );
170         list_remove( &folder->entry );
171         free_folder( folder );
172     }
173
174     LIST_FOR_EACH_SAFE( item, cursor, &package->components )
175     {
176         MSICOMPONENT *comp = LIST_ENTRY( item, MSICOMPONENT, entry );
177
178         list_remove( &comp->entry );
179         msi_free( comp->Component );
180         msi_free( comp->ComponentId );
181         msi_free( comp->Directory );
182         msi_free( comp->Condition );
183         msi_free( comp->KeyPath );
184         msi_free( comp->FullKeypath );
185         if (comp->assembly) free_assembly( comp->assembly );
186         msi_free( comp );
187     }
188
189     LIST_FOR_EACH_SAFE( item, cursor, &package->files )
190     {
191         MSIFILE *file = LIST_ENTRY( item, MSIFILE, entry );
192
193         list_remove( &file->entry );
194         msi_free( file->File );
195         msi_free( file->FileName );
196         msi_free( file->ShortName );
197         msi_free( file->LongName );
198         msi_free( file->Version );
199         msi_free( file->Language );
200         msi_free( file->TargetPath );
201         msi_free( file );
202     }
203
204     /* clean up extension, progid, class and verb structures */
205     LIST_FOR_EACH_SAFE( item, cursor, &package->classes )
206     {
207         MSICLASS *cls = LIST_ENTRY( item, MSICLASS, entry );
208
209         list_remove( &cls->entry );
210         msi_free( cls->clsid );
211         msi_free( cls->Context );
212         msi_free( cls->Description );
213         msi_free( cls->FileTypeMask );
214         msi_free( cls->IconPath );
215         msi_free( cls->DefInprocHandler );
216         msi_free( cls->DefInprocHandler32 );
217         msi_free( cls->Argument );
218         msi_free( cls->ProgIDText );
219         msi_free( cls );
220     }
221
222     LIST_FOR_EACH_SAFE( item, cursor, &package->extensions )
223     {
224         MSIEXTENSION *ext = LIST_ENTRY( item, MSIEXTENSION, entry );
225
226         list_remove( &ext->entry );
227         free_extension( ext );
228     }
229
230     LIST_FOR_EACH_SAFE( item, cursor, &package->progids )
231     {
232         MSIPROGID *progid = LIST_ENTRY( item, MSIPROGID, entry );
233
234         list_remove( &progid->entry );
235         msi_free( progid->ProgID );
236         msi_free( progid->Description );
237         msi_free( progid->IconPath );
238         msi_free( progid );
239     }
240
241     LIST_FOR_EACH_SAFE( item, cursor, &package->mimes )
242     {
243         MSIMIME *mt = LIST_ENTRY( item, MSIMIME, entry );
244
245         list_remove( &mt->entry );
246         msi_free( mt->suffix );
247         msi_free( mt->clsid );
248         msi_free( mt->ContentType );
249         msi_free( mt );
250     }
251
252     LIST_FOR_EACH_SAFE( item, cursor, &package->appids )
253     {
254         MSIAPPID *appid = LIST_ENTRY( item, MSIAPPID, entry );
255
256         list_remove( &appid->entry );
257         msi_free( appid->AppID );
258         msi_free( appid->RemoteServerName );
259         msi_free( appid->LocalServer );
260         msi_free( appid->ServiceParameters );
261         msi_free( appid->DllSurrogate );
262         msi_free( appid );
263     }
264
265     LIST_FOR_EACH_SAFE( item, cursor, &package->sourcelist_info )
266     {
267         MSISOURCELISTINFO *info = LIST_ENTRY( item, MSISOURCELISTINFO, entry );
268
269         list_remove( &info->entry );
270         msi_free( info->value );
271         msi_free( info );
272     }
273
274     LIST_FOR_EACH_SAFE( item, cursor, &package->sourcelist_media )
275     {
276         MSIMEDIADISK *info = LIST_ENTRY( item, MSIMEDIADISK, entry );
277
278         list_remove( &info->entry );
279         msi_free( info->volume_label );
280         msi_free( info->disk_prompt );
281         msi_free( info );
282     }
283
284     if (package->script)
285     {
286         for (i = 0; i < SCRIPT_MAX; i++)
287             msi_free_action_script( package, i );
288
289         for (i = 0; i < package->script->UniqueActionsCount; i++)
290             msi_free( package->script->UniqueActions[i] );
291
292         msi_free( package->script->UniqueActions );
293         msi_free( package->script );
294     }
295
296     LIST_FOR_EACH_SAFE( item, cursor, &package->binaries )
297     {
298         MSIBINARY *binary = LIST_ENTRY( item, MSIBINARY, entry );
299
300         list_remove( &binary->entry );
301         if (binary->module)
302             FreeLibrary( binary->module );
303         if (!DeleteFileW( binary->tmpfile ))
304             ERR("failed to delete %s (%u)\n", debugstr_w(binary->tmpfile), GetLastError());
305         msi_free( binary->source );
306         msi_free( binary->tmpfile );
307         msi_free( binary );
308     }
309
310     LIST_FOR_EACH_SAFE( item, cursor, &package->cabinet_streams )
311     {
312         MSICABINETSTREAM *cab = LIST_ENTRY( item, MSICABINETSTREAM, entry );
313
314         list_remove( &cab->entry );
315         IStorage_Release( cab->storage );
316         msi_free( cab->stream );
317         msi_free( cab );
318     }
319
320     LIST_FOR_EACH_SAFE( item, cursor, &package->patches )
321     {
322         MSIPATCHINFO *patch = LIST_ENTRY( item, MSIPATCHINFO, entry );
323
324         list_remove( &patch->entry );
325         if (patch->delete_on_close && !DeleteFileW( patch->localfile ))
326         {
327             ERR("failed to delete %s (%u)\n", debugstr_w(patch->localfile), GetLastError());
328         }
329         msi_free_patchinfo( patch );
330     }
331
332     msi_free( package->BaseURL );
333     msi_free( package->PackagePath );
334     msi_free( package->ProductCode );
335     msi_free( package->ActionFormat );
336     msi_free( package->LastAction );
337     msi_free( package->langids );
338
339     remove_tracked_tempfiles(package);
340
341     /* cleanup control event subscriptions */
342     ControlEvent_CleanupSubscriptions( package );
343 }
344
345 static void MSI_FreePackage( MSIOBJECTHDR *arg)
346 {
347     MSIPACKAGE *package = (MSIPACKAGE *)arg;
348
349     msi_destroy_assembly_caches( package );
350
351     if( package->dialog )
352         msi_dialog_destroy( package->dialog );
353
354     msiobj_release( &package->db->hdr );
355     free_package_structures(package);
356     CloseHandle( package->log_file );
357
358     if (package->delete_on_close) DeleteFileW( package->localfile );
359     msi_free( package->localfile );
360 }
361
362 static UINT create_temp_property_table(MSIPACKAGE *package)
363 {
364     static const WCHAR query[] = {
365         'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
366         '`','_','P','r','o','p','e','r','t','y','`',' ','(',' ',
367         '`','_','P','r','o','p','e','r','t','y','`',' ',
368         'C','H','A','R','(','5','6',')',' ','N','O','T',' ','N','U','L','L',' ',
369         'T','E','M','P','O','R','A','R','Y',',',' ',
370         '`','V','a','l','u','e','`',' ','C','H','A','R','(','9','8',')',' ',
371         'N','O','T',' ','N','U','L','L',' ','T','E','M','P','O','R','A','R','Y',
372         ' ','P','R','I','M','A','R','Y',' ','K','E','Y',' ',
373         '`','_','P','r','o','p','e','r','t','y','`',')',' ','H','O','L','D',0};
374     MSIQUERY *view;
375     UINT rc;
376
377     rc = MSI_DatabaseOpenViewW(package->db, query, &view);
378     if (rc != ERROR_SUCCESS)
379         return rc;
380
381     rc = MSI_ViewExecute(view, 0);
382     MSI_ViewClose(view);
383     msiobj_release(&view->hdr);
384     return rc;
385 }
386
387 UINT msi_clone_properties(MSIPACKAGE *package)
388 {
389     static const WCHAR query_select[] = {
390         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
391         '`','P','r','o','p','e','r','t','y','`',0};
392     static const WCHAR query_insert[] = {
393         'I','N','S','E','R','T',' ','I','N','T','O',' ',
394         '`','_','P','r','o','p','e','r','t','y','`',' ',
395         '(','`','_','P','r','o','p','e','r','t','y','`',',','`','V','a','l','u','e','`',')',' ',
396         'V','A','L','U','E','S',' ','(','?',',','?',')',0};
397     static const WCHAR query_update[] = {
398         'U','P','D','A','T','E',' ','`','_','P','r','o','p','e','r','t','y','`',' ',
399         'S','E','T',' ','`','V','a','l','u','e','`',' ','=',' ','?',' ',
400         'W','H','E','R','E',' ','`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','?',0};
401     MSIQUERY *view_select;
402     UINT rc;
403
404     rc = MSI_DatabaseOpenViewW( package->db, query_select, &view_select );
405     if (rc != ERROR_SUCCESS)
406         return rc;
407
408     rc = MSI_ViewExecute( view_select, 0 );
409     if (rc != ERROR_SUCCESS)
410     {
411         MSI_ViewClose( view_select );
412         msiobj_release( &view_select->hdr );
413         return rc;
414     }
415
416     while (1)
417     {
418         MSIQUERY *view_insert, *view_update;
419         MSIRECORD *rec_select;
420
421         rc = MSI_ViewFetch( view_select, &rec_select );
422         if (rc != ERROR_SUCCESS)
423             break;
424
425         rc = MSI_DatabaseOpenViewW( package->db, query_insert, &view_insert );
426         if (rc != ERROR_SUCCESS)
427         {
428             msiobj_release( &rec_select->hdr );
429             continue;
430         }
431
432         rc = MSI_ViewExecute( view_insert, rec_select );
433         MSI_ViewClose( view_insert );
434         msiobj_release( &view_insert->hdr );
435         if (rc != ERROR_SUCCESS)
436         {
437             MSIRECORD *rec_update;
438
439             TRACE("insert failed, trying update\n");
440
441             rc = MSI_DatabaseOpenViewW( package->db, query_update, &view_update );
442             if (rc != ERROR_SUCCESS)
443             {
444                 WARN("open view failed %u\n", rc);
445                 msiobj_release( &rec_select->hdr );
446                 continue;
447             }
448
449             rec_update = MSI_CreateRecord( 2 );
450             MSI_RecordCopyField( rec_select, 1, rec_update, 2 );
451             MSI_RecordCopyField( rec_select, 2, rec_update, 1 );
452             rc = MSI_ViewExecute( view_update, rec_update );
453             if (rc != ERROR_SUCCESS)
454                 WARN("update failed %u\n", rc);
455
456             MSI_ViewClose( view_update );
457             msiobj_release( &view_update->hdr );
458             msiobj_release( &rec_update->hdr );
459         }
460
461         msiobj_release( &rec_select->hdr );
462     }
463
464     MSI_ViewClose( view_select );
465     msiobj_release( &view_select->hdr );
466     return rc;
467 }
468
469 /*
470  * set_installed_prop
471  *
472  * Sets the "Installed" property to indicate that
473  *  the product is installed for the current user.
474  */
475 static UINT set_installed_prop( MSIPACKAGE *package )
476 {
477     HKEY hkey;
478     UINT r;
479
480     if (!package->ProductCode) return ERROR_FUNCTION_FAILED;
481
482     r = MSIREG_OpenUninstallKey( package->ProductCode, package->platform, &hkey, FALSE );
483     if (r == ERROR_SUCCESS)
484     {
485         RegCloseKey( hkey );
486         msi_set_property( package->db, szInstalled, szOne, -1 );
487     }
488     return r;
489 }
490
491 static UINT set_user_sid_prop( MSIPACKAGE *package )
492 {
493     SID_NAME_USE use;
494     LPWSTR user_name;
495     LPWSTR sid_str = NULL, dom = NULL;
496     DWORD size, dom_size;
497     PSID psid = NULL;
498     UINT r = ERROR_FUNCTION_FAILED;
499
500     size = 0;
501     GetUserNameW( NULL, &size );
502
503     user_name = msi_alloc( (size + 1) * sizeof(WCHAR) );
504     if (!user_name)
505         return ERROR_OUTOFMEMORY;
506
507     if (!GetUserNameW( user_name, &size ))
508         goto done;
509
510     size = 0;
511     dom_size = 0;
512     LookupAccountNameW( NULL, user_name, NULL, &size, NULL, &dom_size, &use );
513
514     psid = msi_alloc( size );
515     dom = msi_alloc( dom_size*sizeof (WCHAR) );
516     if (!psid || !dom)
517     {
518         r = ERROR_OUTOFMEMORY;
519         goto done;
520     }
521
522     if (!LookupAccountNameW( NULL, user_name, psid, &size, dom, &dom_size, &use ))
523         goto done;
524
525     if (!ConvertSidToStringSidW( psid, &sid_str ))
526         goto done;
527
528     r = msi_set_property( package->db, szUserSID, sid_str, -1 );
529
530 done:
531     LocalFree( sid_str );
532     msi_free( dom );
533     msi_free( psid );
534     msi_free( user_name );
535
536     return r;
537 }
538
539 static LPWSTR get_fusion_filename(MSIPACKAGE *package)
540 {
541     HKEY netsetup;
542     LONG res;
543     LPWSTR file = NULL;
544     DWORD index = 0, size;
545     WCHAR ver[MAX_PATH];
546     WCHAR name[MAX_PATH];
547     WCHAR windir[MAX_PATH];
548
549     static const WCHAR fusion[] = {'f','u','s','i','o','n','.','d','l','l',0};
550     static const WCHAR sub[] = {
551         'S','o','f','t','w','a','r','e','\\',
552         'M','i','c','r','o','s','o','f','t','\\',
553         'N','E','T',' ','F','r','a','m','e','w','o','r','k',' ','S','e','t','u','p','\\',
554         'N','D','P',0
555     };
556     static const WCHAR subdir[] = {
557         'M','i','c','r','o','s','o','f','t','.','N','E','T','\\',
558         'F','r','a','m','e','w','o','r','k','\\',0
559     };
560
561     res = RegOpenKeyExW(HKEY_LOCAL_MACHINE, sub, 0, KEY_ENUMERATE_SUB_KEYS, &netsetup);
562     if (res != ERROR_SUCCESS)
563         return NULL;
564
565     GetWindowsDirectoryW(windir, MAX_PATH);
566
567     ver[0] = '\0';
568     size = MAX_PATH;
569     while (RegEnumKeyExW(netsetup, index, name, &size, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
570     {
571         index++;
572
573         /* verify existence of fusion.dll .Net 3.0 does not install a new one */
574         if (strcmpW( ver, name ) < 0)
575         {
576             LPWSTR check;
577             size = lstrlenW(windir) + lstrlenW(subdir) + lstrlenW(name) +lstrlenW(fusion) + 3;
578             check = msi_alloc(size * sizeof(WCHAR));
579
580             if (!check)
581             {
582                 msi_free(file);
583                 return NULL;
584             }
585
586             lstrcpyW(check, windir);
587             lstrcatW(check, szBackSlash);
588             lstrcatW(check, subdir);
589             lstrcatW(check, name);
590             lstrcatW(check, szBackSlash);
591             lstrcatW(check, fusion);
592
593             if(GetFileAttributesW(check) != INVALID_FILE_ATTRIBUTES)
594             {
595                 msi_free(file);
596                 file = check;
597                 lstrcpyW(ver, name);
598             }
599             else
600                 msi_free(check);
601         }
602     }
603
604     RegCloseKey(netsetup);
605     return file;
606 }
607
608 typedef struct tagLANGANDCODEPAGE
609 {
610   WORD wLanguage;
611   WORD wCodePage;
612 } LANGANDCODEPAGE;
613
614 static void set_msi_assembly_prop(MSIPACKAGE *package)
615 {
616     UINT val_len;
617     DWORD size, handle;
618     LPVOID version = NULL;
619     WCHAR buf[MAX_PATH];
620     LPWSTR fusion, verstr;
621     LANGANDCODEPAGE *translate;
622
623     static const WCHAR netasm[] = {
624         'M','s','i','N','e','t','A','s','s','e','m','b','l','y','S','u','p','p','o','r','t',0
625     };
626     static const WCHAR translation[] = {
627         '\\','V','a','r','F','i','l','e','I','n','f','o',
628         '\\','T','r','a','n','s','l','a','t','i','o','n',0
629     };
630     static const WCHAR verfmt[] = {
631         '\\','S','t','r','i','n','g','F','i','l','e','I','n','f','o',
632         '\\','%','0','4','x','%','0','4','x',
633         '\\','P','r','o','d','u','c','t','V','e','r','s','i','o','n',0
634     };
635
636     fusion = get_fusion_filename(package);
637     if (!fusion)
638         return;
639
640     size = GetFileVersionInfoSizeW(fusion, &handle);
641     if (!size)
642         goto done;
643
644     version = msi_alloc(size);
645     if (!version)
646         goto done;
647
648     if (!GetFileVersionInfoW(fusion, handle, size, version))
649         goto done;
650
651     if (!VerQueryValueW(version, translation, (LPVOID *)&translate, &val_len))
652         goto done;
653
654     sprintfW(buf, verfmt, translate[0].wLanguage, translate[0].wCodePage);
655
656     if (!VerQueryValueW(version, buf, (LPVOID *)&verstr, &val_len))
657         goto done;
658
659     if (!val_len || !verstr)
660         goto done;
661
662     msi_set_property( package->db, netasm, verstr, -1 );
663
664 done:
665     msi_free(fusion);
666     msi_free(version);
667 }
668
669 static VOID set_installer_properties(MSIPACKAGE *package)
670 {
671     WCHAR *ptr;
672     OSVERSIONINFOEXW OSVersion;
673     MEMORYSTATUSEX msex;
674     DWORD verval, len;
675     WCHAR pth[MAX_PATH], verstr[11], bufstr[22];
676     HDC dc;
677     HKEY hkey;
678     LPWSTR username, companyname;
679     SYSTEM_INFO sys_info;
680     SYSTEMTIME systemtime;
681     LANGID langid;
682
683     static const WCHAR szCommonFilesFolder[] = {'C','o','m','m','o','n','F','i','l','e','s','F','o','l','d','e','r',0};
684     static const WCHAR szProgramFilesFolder[] = {'P','r','o','g','r','a','m','F','i','l','e','s','F','o','l','d','e','r',0};
685     static const WCHAR szCommonAppDataFolder[] = {'C','o','m','m','o','n','A','p','p','D','a','t','a','F','o','l','d','e','r',0};
686     static const WCHAR szFavoritesFolder[] = {'F','a','v','o','r','i','t','e','s','F','o','l','d','e','r',0};
687     static const WCHAR szFontsFolder[] = {'F','o','n','t','s','F','o','l','d','e','r',0};
688     static const WCHAR szSendToFolder[] = {'S','e','n','d','T','o','F','o','l','d','e','r',0};
689     static const WCHAR szStartMenuFolder[] = {'S','t','a','r','t','M','e','n','u','F','o','l','d','e','r',0};
690     static const WCHAR szStartupFolder[] = {'S','t','a','r','t','u','p','F','o','l','d','e','r',0};
691     static const WCHAR szTemplateFolder[] = {'T','e','m','p','l','a','t','e','F','o','l','d','e','r',0};
692     static const WCHAR szDesktopFolder[] = {'D','e','s','k','t','o','p','F','o','l','d','e','r',0};
693     static const WCHAR szProgramMenuFolder[] = {'P','r','o','g','r','a','m','M','e','n','u','F','o','l','d','e','r',0};
694     static const WCHAR szAdminToolsFolder[] = {'A','d','m','i','n','T','o','o','l','s','F','o','l','d','e','r',0};
695     static const WCHAR szSystemFolder[] = {'S','y','s','t','e','m','F','o','l','d','e','r',0};
696     static const WCHAR szSystem16Folder[] = {'S','y','s','t','e','m','1','6','F','o','l','d','e','r',0};
697     static const WCHAR szLocalAppDataFolder[] = {'L','o','c','a','l','A','p','p','D','a','t','a','F','o','l','d','e','r',0};
698     static const WCHAR szMyPicturesFolder[] = {'M','y','P','i','c','t','u','r','e','s','F','o','l','d','e','r',0};
699     static const WCHAR szPersonalFolder[] = {'P','e','r','s','o','n','a','l','F','o','l','d','e','r',0};
700     static const WCHAR szWindowsVolume[] = {'W','i','n','d','o','w','s','V','o','l','u','m','e',0};
701     static const WCHAR szPrivileged[] = {'P','r','i','v','i','l','e','g','e','d',0};
702     static const WCHAR szVersion9x[] = {'V','e','r','s','i','o','n','9','X',0};
703     static const WCHAR szVersionNT[] = {'V','e','r','s','i','o','n','N','T',0};
704     static const WCHAR szMsiNTProductType[] = {'M','s','i','N','T','P','r','o','d','u','c','t','T','y','p','e',0};
705     static const WCHAR szFormat[] = {'%','u',0};
706     static const WCHAR szFormat2[] = {'%','u','.','%','u',0};
707     static const WCHAR szWindowsBuild[] = {'W','i','n','d','o','w','s','B','u','i','l','d',0};
708     static const WCHAR szServicePackLevel[] = {'S','e','r','v','i','c','e','P','a','c','k','L','e','v','e','l',0};
709     static const WCHAR szVersionMsi[] = { 'V','e','r','s','i','o','n','M','s','i',0 };
710     static const WCHAR szVersionDatabase[] = { 'V','e','r','s','i','o','n','D','a','t','a','b','a','s','e',0 };
711     static const WCHAR szPhysicalMemory[] = { 'P','h','y','s','i','c','a','l','M','e','m','o','r','y',0 };
712     static const WCHAR szScreenX[] = {'S','c','r','e','e','n','X',0};
713     static const WCHAR szScreenY[] = {'S','c','r','e','e','n','Y',0};
714     static const WCHAR szColorBits[] = {'C','o','l','o','r','B','i','t','s',0};
715     static const WCHAR szIntFormat[] = {'%','d',0};
716     static const WCHAR szMsiAMD64[] = { 'M','s','i','A','M','D','6','4',0 };
717     static const WCHAR szMsix64[] = { 'M','s','i','x','6','4',0 };
718     static const WCHAR szSystem64Folder[] = { 'S','y','s','t','e','m','6','4','F','o','l','d','e','r',0 };
719     static const WCHAR szCommonFiles64Folder[] = { 'C','o','m','m','o','n','F','i','l','e','s','6','4','F','o','l','d','e','r',0 };
720     static const WCHAR szProgramFiles64Folder[] = { 'P','r','o','g','r','a','m','F','i','l','e','s','6','4','F','o','l','d','e','r',0 };
721     static const WCHAR szVersionNT64[] = { 'V','e','r','s','i','o','n','N','T','6','4',0 };
722     static const WCHAR szUserInfo[] = {
723         'S','O','F','T','W','A','R','E','\\',
724         'M','i','c','r','o','s','o','f','t','\\',
725         'M','S',' ','S','e','t','u','p',' ','(','A','C','M','E',')','\\',
726         'U','s','e','r',' ','I','n','f','o',0
727     };
728     static const WCHAR szDefName[] = { 'D','e','f','N','a','m','e',0 };
729     static const WCHAR szDefCompany[] = { 'D','e','f','C','o','m','p','a','n','y',0 };
730     static const WCHAR szCurrentVersion[] = {
731         'S','O','F','T','W','A','R','E','\\',
732         'M','i','c','r','o','s','o','f','t','\\',
733         'W','i','n','d','o','w','s',' ','N','T','\\',
734         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0
735     };
736     static const WCHAR szRegisteredUser[] = {'R','e','g','i','s','t','e','r','e','d','O','w','n','e','r',0};
737     static const WCHAR szRegisteredOrganization[] = {
738         'R','e','g','i','s','t','e','r','e','d','O','r','g','a','n','i','z','a','t','i','o','n',0
739     };
740     static const WCHAR szUSERNAME[] = {'U','S','E','R','N','A','M','E',0};
741     static const WCHAR szCOMPANYNAME[] = {'C','O','M','P','A','N','Y','N','A','M','E',0};
742     static const WCHAR szDate[] = {'D','a','t','e',0};
743     static const WCHAR szTime[] = {'T','i','m','e',0};
744     static const WCHAR szUserLanguageID[] = {'U','s','e','r','L','a','n','g','u','a','g','e','I','D',0};
745     static const WCHAR szSystemLangID[] = {'S','y','s','t','e','m','L','a','n','g','u','a','g','e','I','D',0};
746     static const WCHAR szProductState[] = {'P','r','o','d','u','c','t','S','t','a','t','e',0};
747     static const WCHAR szLogonUser[] = {'L','o','g','o','n','U','s','e','r',0};
748     static const WCHAR szNetHoodFolder[] = {'N','e','t','H','o','o','d','F','o','l','d','e','r',0};
749     static const WCHAR szPrintHoodFolder[] = {'P','r','i','n','t','H','o','o','d','F','o','l','d','e','r',0};
750     static const WCHAR szRecentFolder[] = {'R','e','c','e','n','t','F','o','l','d','e','r',0};
751     static const WCHAR szComputerName[] = {'C','o','m','p','u','t','e','r','N','a','m','e',0};
752     static const WCHAR szBrowseProperty[] = {'_','B','r','o','w','s','e','P','r','o','p','e','r','t','y',0};
753     static const WCHAR szInstallDir[] = {'I','N','S','T','A','L','L','D','I','R',0};
754
755     /*
756      * Other things that probably should be set:
757      *
758      * VirtualMemory ShellAdvSupport DefaultUIFont PackagecodeChanging
759      * CaptionHeight BorderTop BorderSide TextHeight RedirectedDllSupport
760      */
761
762     SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, 0, pth);
763     strcatW(pth, szBackSlash);
764     msi_set_property( package->db, szCommonAppDataFolder, pth, -1 );
765
766     SHGetFolderPathW(NULL, CSIDL_FAVORITES, NULL, 0, pth);
767     strcatW(pth, szBackSlash);
768     msi_set_property( package->db, szFavoritesFolder, pth, -1 );
769
770     SHGetFolderPathW(NULL, CSIDL_FONTS, NULL, 0, pth);
771     strcatW(pth, szBackSlash);
772     msi_set_property( package->db, szFontsFolder, pth, -1 );
773
774     SHGetFolderPathW(NULL, CSIDL_SENDTO, NULL, 0, pth);
775     strcatW(pth, szBackSlash);
776     msi_set_property( package->db, szSendToFolder, pth, -1 );
777
778     SHGetFolderPathW(NULL, CSIDL_STARTMENU, NULL, 0, pth);
779     strcatW(pth, szBackSlash);
780     msi_set_property( package->db, szStartMenuFolder, pth, -1 );
781
782     SHGetFolderPathW(NULL, CSIDL_STARTUP, NULL, 0, pth);
783     strcatW(pth, szBackSlash);
784     msi_set_property( package->db, szStartupFolder, pth, -1 );
785
786     SHGetFolderPathW(NULL, CSIDL_TEMPLATES, NULL, 0, pth);
787     strcatW(pth, szBackSlash);
788     msi_set_property( package->db, szTemplateFolder, pth, -1 );
789
790     SHGetFolderPathW(NULL, CSIDL_DESKTOP, NULL, 0, pth);
791     strcatW(pth, szBackSlash);
792     msi_set_property( package->db, szDesktopFolder, pth, -1 );
793
794     /* FIXME: set to AllUsers profile path if ALLUSERS is set */
795     SHGetFolderPathW(NULL, CSIDL_PROGRAMS, NULL, 0, pth);
796     strcatW(pth, szBackSlash);
797     msi_set_property( package->db, szProgramMenuFolder, pth, -1 );
798
799     SHGetFolderPathW(NULL, CSIDL_ADMINTOOLS, NULL, 0, pth);
800     strcatW(pth, szBackSlash);
801     msi_set_property( package->db, szAdminToolsFolder, pth, -1 );
802
803     SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, pth);
804     strcatW(pth, szBackSlash);
805     msi_set_property( package->db, szAppDataFolder, pth, -1 );
806
807     SHGetFolderPathW(NULL, CSIDL_SYSTEM, NULL, 0, pth);
808     strcatW(pth, szBackSlash);
809     msi_set_property( package->db, szSystemFolder, pth, -1 );
810     msi_set_property( package->db, szSystem16Folder, pth, -1 );
811
812     SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, pth);
813     strcatW(pth, szBackSlash);
814     msi_set_property( package->db, szLocalAppDataFolder, pth, -1 );
815
816     SHGetFolderPathW(NULL, CSIDL_MYPICTURES, NULL, 0, pth);
817     strcatW(pth, szBackSlash);
818     msi_set_property( package->db, szMyPicturesFolder, pth, -1 );
819
820     SHGetFolderPathW(NULL, CSIDL_PERSONAL, NULL, 0, pth);
821     strcatW(pth, szBackSlash);
822     msi_set_property( package->db, szPersonalFolder, pth, -1 );
823
824     SHGetFolderPathW(NULL, CSIDL_WINDOWS, NULL, 0, pth);
825     strcatW(pth, szBackSlash);
826     msi_set_property( package->db, szWindowsFolder, pth, -1 );
827     
828     SHGetFolderPathW(NULL, CSIDL_PRINTHOOD, NULL, 0, pth);
829     strcatW(pth, szBackSlash);
830     msi_set_property( package->db, szPrintHoodFolder, pth, -1 );
831
832     SHGetFolderPathW(NULL, CSIDL_NETHOOD, NULL, 0, pth);
833     strcatW(pth, szBackSlash);
834     msi_set_property( package->db, szNetHoodFolder, pth, -1 );
835
836     SHGetFolderPathW(NULL, CSIDL_RECENT, NULL, 0, pth);
837     strcatW(pth, szBackSlash);
838     msi_set_property( package->db, szRecentFolder, pth, -1 );
839
840     /* Physical Memory is specified in MB. Using total amount. */
841     msex.dwLength = sizeof(msex);
842     GlobalMemoryStatusEx( &msex );
843     len = sprintfW( bufstr, szIntFormat, (int)(msex.ullTotalPhys / 1024 / 1024) );
844     msi_set_property( package->db, szPhysicalMemory, bufstr, len );
845
846     SHGetFolderPathW(NULL, CSIDL_WINDOWS, NULL, 0, pth);
847     ptr = strchrW(pth,'\\');
848     if (ptr) *(ptr + 1) = 0;
849     msi_set_property( package->db, szWindowsVolume, pth, -1 );
850     
851     len = GetTempPathW(MAX_PATH, pth);
852     msi_set_property( package->db, szTempFolder, pth, len );
853
854     /* in a wine environment the user is always admin and privileged */
855     msi_set_property( package->db, szAdminUser, szOne, -1 );
856     msi_set_property( package->db, szPrivileged, szOne, -1 );
857
858     /* set the os things */
859     OSVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
860     GetVersionExW((OSVERSIONINFOW *)&OSVersion);
861     verval = OSVersion.dwMinorVersion + OSVersion.dwMajorVersion * 100;
862     len = sprintfW( verstr, szFormat, verval );
863     switch (OSVersion.dwPlatformId)
864     {
865         case VER_PLATFORM_WIN32_WINDOWS:    
866             msi_set_property( package->db, szVersion9x, verstr, len );
867             break;
868         case VER_PLATFORM_WIN32_NT:
869             msi_set_property( package->db, szVersionNT, verstr, len );
870             len = sprintfW( verstr, szFormat,OSVersion.wProductType );
871             msi_set_property( package->db, szMsiNTProductType, verstr, len );
872             break;
873     }
874     len = sprintfW( verstr, szFormat, OSVersion.dwBuildNumber );
875     msi_set_property( package->db, szWindowsBuild, verstr, len );
876     len = sprintfW( verstr, szFormat, OSVersion.wServicePackMajor );
877     msi_set_property( package->db, szServicePackLevel, verstr, len );
878
879     len = sprintfW( bufstr, szFormat2, MSI_MAJORVERSION, MSI_MINORVERSION );
880     msi_set_property( package->db, szVersionMsi, bufstr, len );
881     len = sprintfW( bufstr, szFormat, MSI_MAJORVERSION * 100 );
882     msi_set_property( package->db, szVersionDatabase, bufstr, len );
883
884     GetNativeSystemInfo( &sys_info );
885     len = sprintfW( bufstr, szIntFormat, sys_info.wProcessorLevel );
886     msi_set_property( package->db, szIntel, bufstr, len );
887     if (sys_info.u.s.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
888     {
889         GetSystemDirectoryW( pth, MAX_PATH );
890         PathAddBackslashW( pth );
891         msi_set_property( package->db, szSystemFolder, pth, -1 );
892
893         SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES, NULL, 0, pth );
894         PathAddBackslashW( pth );
895         msi_set_property( package->db, szProgramFilesFolder, pth, -1 );
896
897         SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES_COMMON, NULL, 0, pth );
898         PathAddBackslashW( pth );
899         msi_set_property( package->db, szCommonFilesFolder, pth, -1 );
900     }
901     else if (sys_info.u.s.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
902     {
903         msi_set_property( package->db, szMsiAMD64, bufstr, -1 );
904         msi_set_property( package->db, szMsix64, bufstr, -1 );
905         msi_set_property( package->db, szVersionNT64, verstr, -1 );
906
907         GetSystemDirectoryW( pth, MAX_PATH );
908         PathAddBackslashW( pth );
909         msi_set_property( package->db, szSystem64Folder, pth, -1 );
910
911         GetSystemWow64DirectoryW( pth, MAX_PATH );
912         PathAddBackslashW( pth );
913         msi_set_property( package->db, szSystemFolder, pth, -1 );
914
915         SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES, NULL, 0, pth );
916         PathAddBackslashW( pth );
917         msi_set_property( package->db, szProgramFiles64Folder, pth, -1 );
918
919         SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILESX86, NULL, 0, pth );
920         PathAddBackslashW( pth );
921         msi_set_property( package->db, szProgramFilesFolder, pth, -1 );
922
923         SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES_COMMON, NULL, 0, pth );
924         PathAddBackslashW( pth );
925         msi_set_property( package->db, szCommonFiles64Folder, pth, -1 );
926
927         SHGetFolderPathW( NULL, CSIDL_PROGRAM_FILES_COMMONX86, NULL, 0, pth );
928         PathAddBackslashW( pth );
929         msi_set_property( package->db, szCommonFilesFolder, pth, -1 );
930     }
931
932     /* Screen properties. */
933     dc = GetDC(0);
934     len = sprintfW( bufstr, szIntFormat, GetDeviceCaps(dc, HORZRES) );
935     msi_set_property( package->db, szScreenX, bufstr, len );
936     len = sprintfW( bufstr, szIntFormat, GetDeviceCaps(dc, VERTRES) );
937     msi_set_property( package->db, szScreenY, bufstr, len );
938     len = sprintfW( bufstr, szIntFormat, GetDeviceCaps(dc, BITSPIXEL) );
939     msi_set_property( package->db, szColorBits, bufstr, len );
940     ReleaseDC(0, dc);
941
942     /* USERNAME and COMPANYNAME */
943     username = msi_dup_property( package->db, szUSERNAME );
944     companyname = msi_dup_property( package->db, szCOMPANYNAME );
945
946     if ((!username || !companyname) &&
947         RegOpenKeyW( HKEY_CURRENT_USER, szUserInfo, &hkey ) == ERROR_SUCCESS)
948     {
949         if (!username &&
950             (username = msi_reg_get_val_str( hkey, szDefName )))
951             msi_set_property( package->db, szUSERNAME, username, -1 );
952         if (!companyname &&
953             (companyname = msi_reg_get_val_str( hkey, szDefCompany )))
954             msi_set_property( package->db, szCOMPANYNAME, companyname, -1 );
955         CloseHandle( hkey );
956     }
957     if ((!username || !companyname) &&
958         RegOpenKeyW( HKEY_LOCAL_MACHINE, szCurrentVersion, &hkey ) == ERROR_SUCCESS)
959     {
960         if (!username &&
961             (username = msi_reg_get_val_str( hkey, szRegisteredUser )))
962             msi_set_property( package->db, szUSERNAME, username, -1 );
963         if (!companyname &&
964             (companyname = msi_reg_get_val_str( hkey, szRegisteredOrganization )))
965             msi_set_property( package->db, szCOMPANYNAME, companyname, -1 );
966         CloseHandle( hkey );
967     }
968     msi_free( username );
969     msi_free( companyname );
970
971     if ( set_user_sid_prop( package ) != ERROR_SUCCESS)
972         ERR("Failed to set the UserSID property\n");
973
974     /* Date and time properties */
975     GetSystemTime( &systemtime );
976     if (GetDateFormatW( LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systemtime,
977                         NULL, bufstr, sizeof(bufstr)/sizeof(bufstr[0]) ))
978         msi_set_property( package->db, szDate, bufstr, -1 );
979     else
980         ERR("Couldn't set Date property: GetDateFormat failed with error %d\n", GetLastError());
981
982     if (GetTimeFormatW( LOCALE_USER_DEFAULT,
983                         TIME_FORCE24HOURFORMAT | TIME_NOTIMEMARKER,
984                         &systemtime, NULL, bufstr,
985                         sizeof(bufstr)/sizeof(bufstr[0]) ))
986         msi_set_property( package->db, szTime, bufstr, -1 );
987     else
988         ERR("Couldn't set Time property: GetTimeFormat failed with error %d\n", GetLastError());
989
990     set_msi_assembly_prop( package );
991
992     langid = GetUserDefaultLangID();
993     len = sprintfW( bufstr, szIntFormat, langid );
994     msi_set_property( package->db, szUserLanguageID, bufstr, len );
995
996     langid = GetSystemDefaultLangID();
997     len = sprintfW( bufstr, szIntFormat, langid );
998     msi_set_property( package->db, szSystemLangID, bufstr, len );
999
1000     len = sprintfW( bufstr, szIntFormat, MsiQueryProductStateW(package->ProductCode) );
1001     msi_set_property( package->db, szProductState, bufstr, len );
1002
1003     len = 0;
1004     if (!GetUserNameW( NULL, &len ) && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
1005     {
1006         WCHAR *username;
1007         if ((username = msi_alloc( len * sizeof(WCHAR) )))
1008         {
1009             if (GetUserNameW( username, &len ))
1010                 msi_set_property( package->db, szLogonUser, username, len - 1 );
1011             msi_free( username );
1012         }
1013     }
1014     len = 0;
1015     if (!GetComputerNameW( NULL, &len ) && GetLastError() == ERROR_BUFFER_OVERFLOW)
1016     {
1017         WCHAR *computername;
1018         if ((computername = msi_alloc( len * sizeof(WCHAR) )))
1019         {
1020             if (GetComputerNameW( computername, &len ))
1021                 msi_set_property( package->db, szComputerName, computername, len - 1 );
1022             msi_free( computername );
1023         }
1024     }
1025     msi_set_property( package->db, szBrowseProperty, szInstallDir, -1 );
1026 }
1027
1028 static UINT msi_load_summary_properties( MSIPACKAGE *package )
1029 {
1030     UINT rc;
1031     MSIHANDLE suminfo;
1032     MSIHANDLE hdb = alloc_msihandle( &package->db->hdr );
1033     INT count;
1034     DWORD len;
1035     LPWSTR package_code;
1036     static const WCHAR szPackageCode[] = {
1037         'P','a','c','k','a','g','e','C','o','d','e',0};
1038
1039     if (!hdb) {
1040         ERR("Unable to allocate handle\n");
1041         return ERROR_OUTOFMEMORY;
1042     }
1043
1044     rc = MsiGetSummaryInformationW( hdb, NULL, 0, &suminfo );
1045     MsiCloseHandle(hdb);
1046     if (rc != ERROR_SUCCESS)
1047     {
1048         ERR("Unable to open Summary Information\n");
1049         return rc;
1050     }
1051
1052     rc = MsiSummaryInfoGetPropertyW( suminfo, PID_PAGECOUNT, NULL,
1053                                      &count, NULL, NULL, NULL );
1054     if (rc != ERROR_SUCCESS)
1055     {
1056         WARN("Unable to query page count: %d\n", rc);
1057         goto done;
1058     }
1059
1060     /* load package code property */
1061     len = 0;
1062     rc = MsiSummaryInfoGetPropertyW( suminfo, PID_REVNUMBER, NULL,
1063                                      NULL, NULL, NULL, &len );
1064     if (rc != ERROR_MORE_DATA)
1065     {
1066         WARN("Unable to query revision number: %d\n", rc);
1067         rc = ERROR_FUNCTION_FAILED;
1068         goto done;
1069     }
1070
1071     len++;
1072     package_code = msi_alloc( len * sizeof(WCHAR) );
1073     rc = MsiSummaryInfoGetPropertyW( suminfo, PID_REVNUMBER, NULL,
1074                                      NULL, NULL, package_code, &len );
1075     if (rc != ERROR_SUCCESS)
1076     {
1077         WARN("Unable to query rev number: %d\n", rc);
1078         goto done;
1079     }
1080
1081     msi_set_property( package->db, szPackageCode, package_code, len );
1082     msi_free( package_code );
1083
1084     /* load package attributes */
1085     count = 0;
1086     MsiSummaryInfoGetPropertyW( suminfo, PID_WORDCOUNT, NULL,
1087                                 &count, NULL, NULL, NULL );
1088     package->WordCount = count;
1089
1090 done:
1091     MsiCloseHandle(suminfo);
1092     return rc;
1093 }
1094
1095 static MSIPACKAGE *msi_alloc_package( void )
1096 {
1097     MSIPACKAGE *package;
1098
1099     package = alloc_msiobject( MSIHANDLETYPE_PACKAGE, sizeof (MSIPACKAGE),
1100                                MSI_FreePackage );
1101     if( package )
1102     {
1103         list_init( &package->components );
1104         list_init( &package->features );
1105         list_init( &package->files );
1106         list_init( &package->filepatches );
1107         list_init( &package->tempfiles );
1108         list_init( &package->folders );
1109         list_init( &package->subscriptions );
1110         list_init( &package->appids );
1111         list_init( &package->classes );
1112         list_init( &package->mimes );
1113         list_init( &package->extensions );
1114         list_init( &package->progids );
1115         list_init( &package->RunningActions );
1116         list_init( &package->sourcelist_info );
1117         list_init( &package->sourcelist_media );
1118         list_init( &package->patches );
1119         list_init( &package->binaries );
1120         list_init( &package->cabinet_streams );
1121     }
1122
1123     return package;
1124 }
1125
1126 static UINT msi_load_admin_properties(MSIPACKAGE *package)
1127 {
1128     BYTE *data;
1129     UINT r, sz;
1130
1131     static const WCHAR stmname[] = {'A','d','m','i','n','P','r','o','p','e','r','t','i','e','s',0};
1132
1133     r = read_stream_data(package->db->storage, stmname, FALSE, &data, &sz);
1134     if (r != ERROR_SUCCESS)
1135         return r;
1136
1137     r = msi_parse_command_line(package, (WCHAR *)data, TRUE);
1138
1139     msi_free(data);
1140     return r;
1141 }
1142
1143 void msi_adjust_privilege_properties( MSIPACKAGE *package )
1144 {
1145     /* FIXME: this should depend on the user's privileges */
1146     if (msi_get_property_int( package->db, szAllUsers, 0 ) == 2)
1147     {
1148         TRACE("resetting ALLUSERS property from 2 to 1\n");
1149         msi_set_property( package->db, szAllUsers, szOne, -1 );
1150     }
1151     msi_set_property( package->db, szAdminUser, szOne, -1 );
1152 }
1153
1154 MSIPACKAGE *MSI_CreatePackage( MSIDATABASE *db, LPCWSTR base_url )
1155 {
1156     static const WCHAR fmtW[] = {'%','u',0};
1157     MSIPACKAGE *package;
1158     WCHAR uilevel[11];
1159     int len;
1160     UINT r;
1161
1162     TRACE("%p\n", db);
1163
1164     package = msi_alloc_package();
1165     if (package)
1166     {
1167         msiobj_addref( &db->hdr );
1168         package->db = db;
1169
1170         package->WordCount = 0;
1171         package->PackagePath = strdupW( db->path );
1172         package->BaseURL = strdupW( base_url );
1173
1174         create_temp_property_table( package );
1175         msi_clone_properties( package );
1176         msi_adjust_privilege_properties( package );
1177
1178         package->ProductCode = msi_dup_property( package->db, szProductCode );
1179         package->script = msi_alloc_zero( sizeof(MSISCRIPT) );
1180
1181         set_installed_prop( package );
1182         set_installer_properties( package );
1183
1184         package->ui_level = gUILevel;
1185         len = sprintfW( uilevel, fmtW, gUILevel & INSTALLUILEVEL_MASK );
1186         msi_set_property( package->db, szUILevel, uilevel, len );
1187
1188         r = msi_load_summary_properties( package );
1189         if (r != ERROR_SUCCESS)
1190         {
1191             msiobj_release( &package->hdr );
1192             return NULL;
1193         }
1194
1195         if (package->WordCount & msidbSumInfoSourceTypeAdminImage)
1196             msi_load_admin_properties( package );
1197
1198         package->log_file = INVALID_HANDLE_VALUE;
1199     }
1200     return package;
1201 }
1202
1203 UINT msi_download_file( LPCWSTR szUrl, LPWSTR filename )
1204 {
1205     LPINTERNET_CACHE_ENTRY_INFOW cache_entry;
1206     DWORD size = 0;
1207     HRESULT hr;
1208
1209     /* call will always fail, because size is 0,
1210      * but will return ERROR_FILE_NOT_FOUND first
1211      * if the file doesn't exist
1212      */
1213     GetUrlCacheEntryInfoW( szUrl, NULL, &size );
1214     if ( GetLastError() != ERROR_FILE_NOT_FOUND )
1215     {
1216         cache_entry = msi_alloc( size );
1217         if ( !GetUrlCacheEntryInfoW( szUrl, cache_entry, &size ) )
1218         {
1219             UINT error = GetLastError();
1220             msi_free( cache_entry );
1221             return error;
1222         }
1223
1224         lstrcpyW( filename, cache_entry->lpszLocalFileName );
1225         msi_free( cache_entry );
1226         return ERROR_SUCCESS;
1227     }
1228
1229     hr = URLDownloadToCacheFileW( NULL, szUrl, filename, MAX_PATH, 0, NULL );
1230     if ( FAILED(hr) )
1231     {
1232         WARN("failed to download %s to cache file\n", debugstr_w(szUrl));
1233         return ERROR_FUNCTION_FAILED;
1234     }
1235
1236     return ERROR_SUCCESS;
1237 }
1238
1239 UINT msi_create_empty_local_file( LPWSTR path, LPCWSTR suffix )
1240 {
1241     static const WCHAR szInstaller[] = {
1242         '\\','I','n','s','t','a','l','l','e','r','\\',0};
1243     static const WCHAR fmt[] = {'%','x',0};
1244     DWORD time, len, i, offset;
1245     HANDLE handle;
1246
1247     time = GetTickCount();
1248     GetWindowsDirectoryW( path, MAX_PATH );
1249     strcatW( path, szInstaller );
1250     CreateDirectoryW( path, NULL );
1251
1252     len = strlenW(path);
1253     for (i = 0; i < 0x10000; i++)
1254     {
1255         offset = snprintfW( path + len, MAX_PATH - len, fmt, (time + i) & 0xffff );
1256         memcpy( path + len + offset, suffix, (strlenW( suffix ) + 1) * sizeof(WCHAR) );
1257         handle = CreateFileW( path, GENERIC_WRITE, 0, NULL,
1258                               CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
1259         if (handle != INVALID_HANDLE_VALUE)
1260         {
1261             CloseHandle(handle);
1262             break;
1263         }
1264         if (GetLastError() != ERROR_FILE_EXISTS &&
1265             GetLastError() != ERROR_SHARING_VIOLATION)
1266             return ERROR_FUNCTION_FAILED;
1267     }
1268
1269     return ERROR_SUCCESS;
1270 }
1271
1272 static enum platform parse_platform( WCHAR *str )
1273 {
1274     if (!str[0] || !strcmpW( str, szIntel )) return PLATFORM_INTEL;
1275     else if (!strcmpW( str, szIntel64 )) return PLATFORM_INTEL64;
1276     else if (!strcmpW( str, szX64 ) || !strcmpW( str, szAMD64 )) return PLATFORM_X64;
1277     else if (!strcmpW( str, szARM )) return PLATFORM_ARM;
1278     return PLATFORM_UNKNOWN;
1279 }
1280
1281 static UINT msi_parse_summary( MSISUMMARYINFO *si, MSIPACKAGE *package )
1282 {
1283     WCHAR *template, *p, *q, *platform;
1284     DWORD i, count;
1285
1286     package->version = msi_suminfo_get_int32( si, PID_PAGECOUNT );
1287     TRACE("version: %d\n", package->version);
1288
1289     template = msi_suminfo_dup_string( si, PID_TEMPLATE );
1290     if (!template)
1291         return ERROR_SUCCESS; /* native accepts missing template property */
1292
1293     TRACE("template: %s\n", debugstr_w(template));
1294
1295     p = strchrW( template, ';' );
1296     if (!p)
1297     {
1298         WARN("invalid template string %s\n", debugstr_w(template));
1299         msi_free( template );
1300         return ERROR_PATCH_PACKAGE_INVALID;
1301     }
1302     *p = 0;
1303     platform = template;
1304     if ((q = strchrW( platform, ',' ))) *q = 0;
1305     package->platform = parse_platform( platform );
1306     while (package->platform == PLATFORM_UNKNOWN && q)
1307     {
1308         platform = q + 1;
1309         if ((q = strchrW( platform, ',' ))) *q = 0;
1310         package->platform = parse_platform( platform );
1311     }
1312     if (package->platform == PLATFORM_UNKNOWN)
1313     {
1314         WARN("unknown platform %s\n", debugstr_w(template));
1315         msi_free( template );
1316         return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
1317     }
1318     p++;
1319     if (!*p)
1320     {
1321         msi_free( template );
1322         return ERROR_SUCCESS;
1323     }
1324     count = 1;
1325     for (q = p; (q = strchrW( q, ',' )); q++) count++;
1326
1327     package->langids = msi_alloc( count * sizeof(LANGID) );
1328     if (!package->langids)
1329     {
1330         msi_free( template );
1331         return ERROR_OUTOFMEMORY;
1332     }
1333
1334     i = 0;
1335     while (*p)
1336     {
1337         q = strchrW( p, ',' );
1338         if (q) *q = 0;
1339         package->langids[i] = atoiW( p );
1340         if (!q) break;
1341         p = q + 1;
1342         i++;
1343     }
1344     package->num_langids = i + 1;
1345
1346     msi_free( template );
1347     return ERROR_SUCCESS;
1348 }
1349
1350 static UINT validate_package( MSIPACKAGE *package )
1351 {
1352     UINT i;
1353
1354     if (package->platform == PLATFORM_INTEL64)
1355         return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
1356 #ifndef __arm__
1357     if (package->platform == PLATFORM_ARM)
1358         return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
1359 #endif
1360     if (package->platform == PLATFORM_X64)
1361     {
1362         if (!is_64bit && !is_wow64)
1363             return ERROR_INSTALL_PLATFORM_UNSUPPORTED;
1364         if (package->version < 200)
1365             return ERROR_INSTALL_PACKAGE_INVALID;
1366     }
1367     if (!package->num_langids)
1368     {
1369         return ERROR_SUCCESS;
1370     }
1371     for (i = 0; i < package->num_langids; i++)
1372     {
1373         LANGID langid = package->langids[i];
1374
1375         if (PRIMARYLANGID( langid ) == LANG_NEUTRAL)
1376         {
1377             langid = MAKELANGID( PRIMARYLANGID( GetSystemDefaultLangID() ), SUBLANGID( langid ) );
1378         }
1379         if (SUBLANGID( langid ) == SUBLANG_NEUTRAL)
1380         {
1381             langid = MAKELANGID( PRIMARYLANGID( langid ), SUBLANGID( GetSystemDefaultLangID() ) );
1382         }
1383         if (IsValidLocale( langid, LCID_INSTALLED ))
1384             return ERROR_SUCCESS;
1385     }
1386     return ERROR_INSTALL_LANGUAGE_UNSUPPORTED;
1387 }
1388
1389 int msi_track_tempfile( MSIPACKAGE *package, const WCHAR *path )
1390 {
1391     MSITEMPFILE *temp;
1392
1393     TRACE("%s\n", debugstr_w(path));
1394
1395     LIST_FOR_EACH_ENTRY( temp, &package->tempfiles, MSITEMPFILE, entry )
1396     {
1397         if (!strcmpW( path, temp->Path )) return 0;
1398     }
1399     if (!(temp = msi_alloc_zero( sizeof (MSITEMPFILE) ))) return -1;
1400     list_add_head( &package->tempfiles, &temp->entry );
1401     temp->Path = strdupW( path );
1402     return 0;
1403 }
1404
1405 static WCHAR *get_product_code( MSIDATABASE *db )
1406 {
1407     static const WCHAR query[] = {
1408         'S','E','L','E','C','T',' ','`','V','a','l','u','e','`',' ',
1409         'F','R','O','M',' ','`','P','r','o','p','e','r','t','y','`',' ',
1410         'W','H','E','R','E',' ','`','P','r','o','p','e','r','t','y','`','=',
1411         '\'','P','r','o','d','u','c','t','C','o','d','e','\'',0};
1412     MSIQUERY *view;
1413     MSIRECORD *rec;
1414     WCHAR *ret = NULL;
1415
1416     if (MSI_DatabaseOpenViewW( db, query, &view ) != ERROR_SUCCESS)
1417     {
1418         return NULL;
1419     }
1420     if (MSI_ViewExecute( view, 0 ) != ERROR_SUCCESS)
1421     {
1422         MSI_ViewClose( view );
1423         msiobj_release( &view->hdr );
1424         return NULL;
1425     }
1426     if (MSI_ViewFetch( view, &rec ) == ERROR_SUCCESS)
1427     {
1428         ret = strdupW( MSI_RecordGetString( rec, 1 ) );
1429         msiobj_release( &rec->hdr );
1430     }
1431     MSI_ViewClose( view );
1432     msiobj_release( &view->hdr );
1433     return ret;
1434 }
1435
1436 static UINT get_registered_local_package( const WCHAR *product, const WCHAR *package, WCHAR *localfile )
1437 {
1438     MSIINSTALLCONTEXT context;
1439     HKEY product_key, props_key;
1440     WCHAR *registered_package = NULL, unsquashed[GUID_SIZE];
1441     UINT r;
1442
1443     r = msi_locate_product( product, &context );
1444     if (r != ERROR_SUCCESS)
1445         return r;
1446
1447     r = MSIREG_OpenProductKey( product, NULL, context, &product_key, FALSE );
1448     if (r != ERROR_SUCCESS)
1449         return r;
1450
1451     r = MSIREG_OpenInstallProps( product, context, NULL, &props_key, FALSE );
1452     if (r != ERROR_SUCCESS)
1453     {
1454         RegCloseKey( product_key );
1455         return r;
1456     }
1457     r = ERROR_FUNCTION_FAILED;
1458     registered_package = msi_reg_get_val_str( product_key, INSTALLPROPERTY_PACKAGECODEW );
1459     if (!registered_package)
1460         goto done;
1461
1462     unsquash_guid( registered_package, unsquashed );
1463     if (!strcmpiW( package, unsquashed ))
1464     {
1465         WCHAR *filename = msi_reg_get_val_str( props_key, INSTALLPROPERTY_LOCALPACKAGEW );
1466         if (!filename)
1467             goto done;
1468
1469         strcpyW( localfile, filename );
1470         msi_free( filename );
1471         r = ERROR_SUCCESS;
1472     }
1473 done:
1474     msi_free( registered_package );
1475     RegCloseKey( props_key );
1476     RegCloseKey( product_key );
1477     return r;
1478 }
1479
1480 static WCHAR *get_package_code( MSIDATABASE *db )
1481 {
1482     WCHAR *ret;
1483     MSISUMMARYINFO *si;
1484
1485     if (!(si = MSI_GetSummaryInformationW( db->storage, 0 )))
1486     {
1487         WARN("failed to load summary info\n");
1488         return NULL;
1489     }
1490     ret = msi_suminfo_dup_string( si, PID_REVNUMBER );
1491     msiobj_release( &si->hdr );
1492     return ret;
1493 }
1494
1495 static UINT get_local_package( const WCHAR *filename, WCHAR *localfile )
1496 {
1497     WCHAR *product_code, *package_code;
1498     MSIDATABASE *db;
1499     UINT r;
1500
1501     if ((r = MSI_OpenDatabaseW( filename, MSIDBOPEN_READONLY, &db )) != ERROR_SUCCESS)
1502     {
1503         if (GetFileAttributesW( filename ) == INVALID_FILE_ATTRIBUTES)
1504             return ERROR_FILE_NOT_FOUND;
1505         return r;
1506     }
1507     if (!(product_code = get_product_code( db )))
1508     {
1509         msiobj_release( &db->hdr );
1510         return ERROR_INSTALL_PACKAGE_INVALID;
1511     }
1512     if (!(package_code = get_package_code( db )))
1513     {
1514         msi_free( product_code );
1515         msiobj_release( &db->hdr );
1516         return ERROR_INSTALL_PACKAGE_INVALID;
1517     }
1518     r = get_registered_local_package( product_code, package_code, localfile );
1519     msi_free( package_code );
1520     msi_free( product_code );
1521     msiobj_release( &db->hdr );
1522     return r;
1523 }
1524
1525 UINT msi_set_original_database_property( MSIDATABASE *db, const WCHAR *package )
1526 {
1527     UINT r;
1528
1529     if (UrlIsW( package, URLIS_URL ))
1530         r = msi_set_property( db, szOriginalDatabase, package, -1 );
1531     else if (package[0] == '#')
1532         r = msi_set_property( db, szOriginalDatabase, db->path, -1 );
1533     else
1534     {
1535         DWORD len;
1536         WCHAR *path;
1537
1538         if (!(len = GetFullPathNameW( package, 0, NULL, NULL ))) return GetLastError();
1539         if (!(path = msi_alloc( len * sizeof(WCHAR) ))) return ERROR_OUTOFMEMORY;
1540         len = GetFullPathNameW( package, len, path, NULL );
1541         r = msi_set_property( db, szOriginalDatabase, path, len );
1542         msi_free( path );
1543     }
1544     return r;
1545 }
1546
1547 UINT MSI_OpenPackageW(LPCWSTR szPackage, MSIPACKAGE **pPackage)
1548 {
1549     static const WCHAR dotmsi[] = {'.','m','s','i',0};
1550     MSIDATABASE *db;
1551     MSIPACKAGE *package;
1552     MSIHANDLE handle;
1553     LPWSTR ptr, base_url = NULL;
1554     UINT r;
1555     WCHAR localfile[MAX_PATH], cachefile[MAX_PATH];
1556     LPCWSTR file = szPackage;
1557     DWORD index = 0;
1558     MSISUMMARYINFO *si;
1559     BOOL delete_on_close = FALSE;
1560
1561     TRACE("%s %p\n", debugstr_w(szPackage), pPackage);
1562
1563     localfile[0] = 0;
1564     if( szPackage[0] == '#' )
1565     {
1566         handle = atoiW(&szPackage[1]);
1567         db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1568         if( !db )
1569         {
1570             IWineMsiRemoteDatabase *remote_database;
1571
1572             remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1573             if ( !remote_database )
1574                 return ERROR_INVALID_HANDLE;
1575
1576             IWineMsiRemoteDatabase_Release( remote_database );
1577             WARN("MsiOpenPackage not allowed during a custom action!\n");
1578
1579             return ERROR_FUNCTION_FAILED;
1580         }
1581     }
1582     else
1583     {
1584         if ( UrlIsW( szPackage, URLIS_URL ) )
1585         {
1586             r = msi_download_file( szPackage, cachefile );
1587             if (r != ERROR_SUCCESS)
1588                 return r;
1589
1590             file = cachefile;
1591
1592             base_url = strdupW( szPackage );
1593             if (!base_url)
1594                 return ERROR_OUTOFMEMORY;
1595
1596             ptr = strrchrW( base_url, '/' );
1597             if (ptr) *(ptr + 1) = '\0';
1598         }
1599         r = get_local_package( file, localfile );
1600         if (r != ERROR_SUCCESS || GetFileAttributesW( localfile ) == INVALID_FILE_ATTRIBUTES)
1601         {
1602             r = msi_create_empty_local_file( localfile, dotmsi );
1603             if (r != ERROR_SUCCESS)
1604             {
1605                 msi_free ( base_url );
1606                 return r;
1607             }
1608
1609             if (!CopyFileW( file, localfile, FALSE ))
1610             {
1611                 r = GetLastError();
1612                 WARN("unable to copy package %s to %s (%u)\n", debugstr_w(file), debugstr_w(localfile), r);
1613                 DeleteFileW( localfile );
1614                 msi_free ( base_url );
1615                 return r;
1616             }
1617             delete_on_close = TRUE;
1618         }
1619         TRACE("opening package %s\n", debugstr_w( localfile ));
1620         r = MSI_OpenDatabaseW( localfile, MSIDBOPEN_TRANSACT, &db );
1621         if (r != ERROR_SUCCESS)
1622         {
1623             msi_free ( base_url );
1624             return r;
1625         }
1626     }
1627     package = MSI_CreatePackage( db, base_url );
1628     msi_free( base_url );
1629     msiobj_release( &db->hdr );
1630     if (!package) return ERROR_INSTALL_PACKAGE_INVALID;
1631     package->localfile = strdupW( localfile );
1632     package->delete_on_close = delete_on_close;
1633
1634     si = MSI_GetSummaryInformationW( db->storage, 0 );
1635     if (!si)
1636     {
1637         WARN("failed to load summary info\n");
1638         msiobj_release( &package->hdr );
1639         return ERROR_INSTALL_PACKAGE_INVALID;
1640     }
1641     r = msi_parse_summary( si, package );
1642     msiobj_release( &si->hdr );
1643     if (r != ERROR_SUCCESS)
1644     {
1645         WARN("failed to parse summary info %u\n", r);
1646         msiobj_release( &package->hdr );
1647         return r;
1648     }
1649     r = validate_package( package );
1650     if (r != ERROR_SUCCESS)
1651     {
1652         msiobj_release( &package->hdr );
1653         return r;
1654     }
1655     msi_set_property( package->db, szDatabase, db->path, -1 );
1656     msi_set_context( package );
1657
1658     while (1)
1659     {
1660         WCHAR patch_code[GUID_SIZE];
1661         r = MsiEnumPatchesExW( package->ProductCode, NULL, package->Context,
1662                                MSIPATCHSTATE_APPLIED, index, patch_code, NULL, NULL, NULL, NULL );
1663         if (r != ERROR_SUCCESS)
1664             break;
1665
1666         TRACE("found registered patch %s\n", debugstr_w(patch_code));
1667
1668         r = msi_apply_registered_patch( package, patch_code );
1669         if (r != ERROR_SUCCESS)
1670         {
1671             ERR("registered patch failed to apply %u\n", r);
1672             msiobj_release( &package->hdr );
1673             return r;
1674         }
1675         index++;
1676     }
1677     if (index)
1678     {
1679         msi_clone_properties( package );
1680         msi_adjust_privilege_properties( package );
1681     }
1682     r = msi_set_original_database_property( package->db, szPackage );
1683     if (r != ERROR_SUCCESS)
1684     {
1685         msiobj_release( &package->hdr );
1686         return r;
1687     }
1688     if (gszLogFile)
1689         package->log_file = CreateFileW( gszLogFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
1690                                          OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
1691     *pPackage = package;
1692     return ERROR_SUCCESS;
1693 }
1694
1695 UINT WINAPI MsiOpenPackageExW(LPCWSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
1696 {
1697     MSIPACKAGE *package = NULL;
1698     UINT ret;
1699
1700     TRACE("%s %08x %p\n", debugstr_w(szPackage), dwOptions, phPackage );
1701
1702     if( !szPackage || !phPackage )
1703         return ERROR_INVALID_PARAMETER;
1704
1705     if ( !*szPackage )
1706     {
1707         FIXME("Should create an empty database and package\n");
1708         return ERROR_FUNCTION_FAILED;
1709     }
1710
1711     if( dwOptions )
1712         FIXME("dwOptions %08x not supported\n", dwOptions);
1713
1714     ret = MSI_OpenPackageW( szPackage, &package );
1715     if( ret == ERROR_SUCCESS )
1716     {
1717         *phPackage = alloc_msihandle( &package->hdr );
1718         if (! *phPackage)
1719             ret = ERROR_NOT_ENOUGH_MEMORY;
1720         msiobj_release( &package->hdr );
1721     }
1722
1723     return ret;
1724 }
1725
1726 UINT WINAPI MsiOpenPackageW(LPCWSTR szPackage, MSIHANDLE *phPackage)
1727 {
1728     return MsiOpenPackageExW( szPackage, 0, phPackage );
1729 }
1730
1731 UINT WINAPI MsiOpenPackageExA(LPCSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
1732 {
1733     LPWSTR szwPack = NULL;
1734     UINT ret;
1735
1736     if( szPackage )
1737     {
1738         szwPack = strdupAtoW( szPackage );
1739         if( !szwPack )
1740             return ERROR_OUTOFMEMORY;
1741     }
1742
1743     ret = MsiOpenPackageExW( szwPack, dwOptions, phPackage );
1744
1745     msi_free( szwPack );
1746
1747     return ret;
1748 }
1749
1750 UINT WINAPI MsiOpenPackageA(LPCSTR szPackage, MSIHANDLE *phPackage)
1751 {
1752     return MsiOpenPackageExA( szPackage, 0, phPackage );
1753 }
1754
1755 MSIHANDLE WINAPI MsiGetActiveDatabase(MSIHANDLE hInstall)
1756 {
1757     MSIPACKAGE *package;
1758     MSIHANDLE handle = 0;
1759     IUnknown *remote_unk;
1760     IWineMsiRemotePackage *remote_package;
1761
1762     TRACE("(%d)\n",hInstall);
1763
1764     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
1765     if( package)
1766     {
1767         handle = alloc_msihandle( &package->db->hdr );
1768         msiobj_release( &package->hdr );
1769     }
1770     else if ((remote_unk = msi_get_remote(hInstall)))
1771     {
1772         if (IUnknown_QueryInterface(remote_unk, &IID_IWineMsiRemotePackage,
1773                                         (LPVOID *)&remote_package) == S_OK)
1774         {
1775             IWineMsiRemotePackage_GetActiveDatabase(remote_package, &handle);
1776             IWineMsiRemotePackage_Release(remote_package);
1777         }
1778         else
1779         {
1780             WARN("remote handle %d is not a package\n", hInstall);
1781         }
1782         IUnknown_Release(remote_unk);
1783     }
1784
1785     return handle;
1786 }
1787
1788 INT MSI_ProcessMessage( MSIPACKAGE *package, INSTALLMESSAGE eMessageType, MSIRECORD *record )
1789 {
1790     static const WCHAR szActionData[] = {'A','c','t','i','o','n','D','a','t','a',0};
1791     static const WCHAR szSetProgress[] = {'S','e','t','P','r','o','g','r','e','s','s',0};
1792     static const WCHAR szActionText[] = {'A','c','t','i','o','n','T','e','x','t',0};
1793     MSIRECORD *uirow;
1794     LPWSTR deformated, message;
1795     DWORD i, len, total_len, log_type = 0;
1796     INT rc = 0;
1797     char *msg;
1798
1799     TRACE("%x\n", eMessageType);
1800
1801     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_FATALEXIT)
1802         log_type |= INSTALLLOGMODE_FATALEXIT;
1803     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ERROR)
1804         log_type |= INSTALLLOGMODE_ERROR;
1805     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_WARNING)
1806         log_type |= INSTALLLOGMODE_WARNING;
1807     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_USER)
1808         log_type |= INSTALLLOGMODE_USER;
1809     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_INFO)
1810         log_type |= INSTALLLOGMODE_INFO;
1811     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_RESOLVESOURCE)
1812         log_type |= INSTALLLOGMODE_RESOLVESOURCE;
1813     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_OUTOFDISKSPACE)
1814         log_type |= INSTALLLOGMODE_OUTOFDISKSPACE;
1815     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_COMMONDATA)
1816         log_type |= INSTALLLOGMODE_COMMONDATA;
1817     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONSTART)
1818         log_type |= INSTALLLOGMODE_ACTIONSTART;
1819     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONDATA)
1820         log_type |= INSTALLLOGMODE_ACTIONDATA;
1821     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_PROGRESS)
1822         log_type |= INSTALLLOGMODE_PROGRESS;
1823     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_INITIALIZE)
1824         log_type |= INSTALLLOGMODE_INITIALIZE;
1825     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_TERMINATE)
1826         log_type |= INSTALLLOGMODE_TERMINATE;
1827     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_SHOWDIALOG)
1828         log_type |= INSTALLLOGMODE_SHOWDIALOG;
1829
1830     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONSTART)
1831     {
1832         static const WCHAR template_s[]=
1833             {'A','c','t','i','o','n',' ','%','s',':',' ','%','s','.',' ',0};
1834         static const WCHAR format[] = 
1835             {'H','H','\'',':','\'','m','m','\'',':','\'','s','s',0};
1836         WCHAR timet[0x100];
1837         LPCWSTR action_text, action;
1838         LPWSTR deformatted = NULL;
1839
1840         GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, format, timet, 0x100);
1841
1842         action = MSI_RecordGetString(record, 1);
1843         action_text = MSI_RecordGetString(record, 2);
1844
1845         if (!action || !action_text)
1846             return IDOK;
1847
1848         deformat_string(package, action_text, &deformatted);
1849
1850         len = strlenW(timet) + strlenW(action) + strlenW(template_s);
1851         if (deformatted)
1852             len += strlenW(deformatted);
1853         message = msi_alloc(len*sizeof(WCHAR));
1854         sprintfW(message, template_s, timet, action);
1855         if (deformatted)
1856             strcatW(message, deformatted);
1857         msi_free(deformatted);
1858     }
1859     else
1860     {
1861         static const WCHAR format[] = {'%','u',':',' ',0};
1862         UINT count = MSI_RecordGetFieldCount( record );
1863         WCHAR *p;
1864
1865         total_len = 1;
1866         for (i = 1; i <= count; i++)
1867         {
1868             len = 0;
1869             MSI_RecordGetStringW( record, i, NULL, &len );
1870             total_len += len + 13;
1871         }
1872         p = message = msi_alloc( total_len * sizeof(WCHAR) );
1873         if (!p) return ERROR_OUTOFMEMORY;
1874
1875         for (i = 1; i <= count; i++)
1876         {
1877             if (count > 1)
1878             {
1879                 len = sprintfW( p, format, i );
1880                 total_len -= len;
1881                 p += len;
1882             }
1883             len = total_len;
1884             MSI_RecordGetStringW( record, i, p, &len );
1885             total_len -= len;
1886             p += len;
1887             if (count > 1 && total_len)
1888             {
1889                 *p++ = ' ';
1890                 total_len--;
1891             }
1892         }
1893         p[0] = 0;
1894     }
1895
1896     TRACE("%p %p %p %x %x %s\n", gUIHandlerA, gUIHandlerW, gUIHandlerRecord,
1897           gUIFilter, log_type, debugstr_w(message));
1898
1899     /* convert it to ASCII */
1900     len = WideCharToMultiByte( CP_ACP, 0, message, -1, NULL, 0, NULL, NULL );
1901     msg = msi_alloc( len );
1902     WideCharToMultiByte( CP_ACP, 0, message, -1, msg, len, NULL, NULL );
1903
1904     if (gUIHandlerW && (gUIFilter & log_type))
1905     {
1906         rc = gUIHandlerW( gUIContext, eMessageType, message );
1907     }
1908     else if (gUIHandlerA && (gUIFilter & log_type))
1909     {
1910         rc = gUIHandlerA( gUIContext, eMessageType, msg );
1911     }
1912     else if (gUIHandlerRecord && (gUIFilter & log_type))
1913     {
1914         MSIHANDLE rec = MsiCreateRecord( 1 );
1915         MsiRecordSetStringW( rec, 0, message );
1916         rc = gUIHandlerRecord( gUIContext, eMessageType, rec );
1917         MsiCloseHandle( rec );
1918     }
1919
1920     if (!rc && package->log_file != INVALID_HANDLE_VALUE &&
1921         (eMessageType & 0xff000000) != INSTALLMESSAGE_PROGRESS)
1922     {
1923         DWORD written;
1924         WriteFile( package->log_file, msg, len - 1, &written, NULL );
1925         WriteFile( package->log_file, "\n", 1, &written, NULL );
1926     }
1927     msi_free( msg );
1928     msi_free( message );
1929
1930     switch (eMessageType & 0xff000000)
1931     {
1932     case INSTALLMESSAGE_ACTIONDATA:
1933         deformat_string(package, MSI_RecordGetString(record, 2), &deformated);
1934         uirow = MSI_CreateRecord(1);
1935         MSI_RecordSetStringW(uirow, 1, deformated);
1936         msi_free(deformated);
1937
1938         ControlEvent_FireSubscribedEvent(package, szActionData, uirow);
1939         msiobj_release(&uirow->hdr);
1940
1941         if (package->action_progress_increment)
1942         {
1943             uirow = MSI_CreateRecord(2);
1944             MSI_RecordSetInteger(uirow, 1, 2);
1945             MSI_RecordSetInteger(uirow, 2, package->action_progress_increment);
1946             ControlEvent_FireSubscribedEvent(package, szSetProgress, uirow);
1947             msiobj_release(&uirow->hdr);
1948         }
1949         break;
1950
1951     case INSTALLMESSAGE_ACTIONSTART:
1952         deformat_string(package, MSI_RecordGetString(record, 2), &deformated);
1953         uirow = MSI_CreateRecord(1);
1954         MSI_RecordSetStringW(uirow, 1, deformated);
1955         msi_free(deformated);
1956
1957         ControlEvent_FireSubscribedEvent(package, szActionText, uirow);
1958
1959         msiobj_release(&uirow->hdr);
1960         break;
1961
1962     case INSTALLMESSAGE_PROGRESS:
1963         ControlEvent_FireSubscribedEvent(package, szSetProgress, record);
1964         break;
1965     }
1966
1967     return ERROR_SUCCESS;
1968 }
1969
1970 INT WINAPI MsiProcessMessage( MSIHANDLE hInstall, INSTALLMESSAGE eMessageType,
1971                               MSIHANDLE hRecord)
1972 {
1973     UINT ret = ERROR_INVALID_HANDLE;
1974     MSIPACKAGE *package = NULL;
1975     MSIRECORD *record = NULL;
1976
1977     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE );
1978     if( !package )
1979     {
1980         HRESULT hr;
1981         IWineMsiRemotePackage *remote_package;
1982
1983         remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
1984         if (!remote_package)
1985             return ERROR_INVALID_HANDLE;
1986
1987         hr = IWineMsiRemotePackage_ProcessMessage( remote_package, eMessageType, hRecord );
1988
1989         IWineMsiRemotePackage_Release( remote_package );
1990
1991         if (FAILED(hr))
1992         {
1993             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
1994                 return HRESULT_CODE(hr);
1995
1996             return ERROR_FUNCTION_FAILED;
1997         }
1998
1999         return ERROR_SUCCESS;
2000     }
2001
2002     record = msihandle2msiinfo( hRecord, MSIHANDLETYPE_RECORD );
2003     if( !record )
2004         goto out;
2005
2006     ret = MSI_ProcessMessage( package, eMessageType, record );
2007
2008 out:
2009     msiobj_release( &package->hdr );
2010     if( record )
2011         msiobj_release( &record->hdr );
2012
2013     return ret;
2014 }
2015
2016 /* property code */
2017
2018 UINT WINAPI MsiSetPropertyA( MSIHANDLE hInstall, LPCSTR szName, LPCSTR szValue )
2019 {
2020     LPWSTR szwName = NULL, szwValue = NULL;
2021     UINT r = ERROR_OUTOFMEMORY;
2022
2023     szwName = strdupAtoW( szName );
2024     if( szName && !szwName )
2025         goto end;
2026
2027     szwValue = strdupAtoW( szValue );
2028     if( szValue && !szwValue )
2029         goto end;
2030
2031     r = MsiSetPropertyW( hInstall, szwName, szwValue);
2032
2033 end:
2034     msi_free( szwName );
2035     msi_free( szwValue );
2036
2037     return r;
2038 }
2039
2040 void msi_reset_folders( MSIPACKAGE *package, BOOL source )
2041 {
2042     MSIFOLDER *folder;
2043
2044     LIST_FOR_EACH_ENTRY( folder, &package->folders, MSIFOLDER, entry )
2045     {
2046         if ( source )
2047         {
2048             msi_free( folder->ResolvedSource );
2049             folder->ResolvedSource = NULL;
2050         }
2051         else
2052         {
2053             msi_free( folder->ResolvedTarget );
2054             folder->ResolvedTarget = NULL;
2055         }
2056     }
2057 }
2058
2059 UINT msi_set_property( MSIDATABASE *db, const WCHAR *name, const WCHAR *value, int len )
2060 {
2061     static const WCHAR insert_query[] = {
2062         'I','N','S','E','R','T',' ','I','N','T','O',' ',
2063         '`','_','P','r','o','p','e','r','t','y','`',' ',
2064         '(','`','_','P','r','o','p','e','r','t','y','`',',','`','V','a','l','u','e','`',')',' ',
2065         'V','A','L','U','E','S',' ','(','?',',','?',')',0};
2066     static const WCHAR update_query[] = {
2067         'U','P','D','A','T','E',' ','`','_','P','r','o','p','e','r','t','y','`',' ',
2068         'S','E','T',' ','`','V','a','l','u','e','`',' ','=',' ','?',' ','W','H','E','R','E',' ',
2069         '`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','\'','%','s','\'',0};
2070     static const WCHAR delete_query[] = {
2071         'D','E','L','E','T','E',' ','F','R','O','M',' ',
2072         '`','_','P','r','o','p','e','r','t','y','`',' ','W','H','E','R','E',' ',
2073         '`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','\'','%','s','\'',0};
2074     MSIQUERY *view;
2075     MSIRECORD *row = NULL;
2076     DWORD sz = 0;
2077     WCHAR query[1024];
2078     UINT rc;
2079
2080     TRACE("%p %s %s %d\n", db, debugstr_w(name), debugstr_wn(value, len), len);
2081
2082     if (!name)
2083         return ERROR_INVALID_PARAMETER;
2084
2085     /* this one is weird... */
2086     if (!name[0])
2087         return value ? ERROR_FUNCTION_FAILED : ERROR_SUCCESS;
2088
2089     if (value && len < 0) len = strlenW( value );
2090
2091     rc = msi_get_property( db, name, 0, &sz );
2092     if (!value || (!*value && !len))
2093     {
2094         sprintfW( query, delete_query, name );
2095     }
2096     else if (rc == ERROR_MORE_DATA || rc == ERROR_SUCCESS)
2097     {
2098         sprintfW( query, update_query, name );
2099         row = MSI_CreateRecord(1);
2100         msi_record_set_string( row, 1, value, len );
2101     }
2102     else
2103     {
2104         strcpyW( query, insert_query );
2105         row = MSI_CreateRecord(2);
2106         msi_record_set_string( row, 1, name, -1 );
2107         msi_record_set_string( row, 2, value, len );
2108     }
2109
2110     rc = MSI_DatabaseOpenViewW(db, query, &view);
2111     if (rc == ERROR_SUCCESS)
2112     {
2113         rc = MSI_ViewExecute(view, row);
2114         MSI_ViewClose(view);
2115         msiobj_release(&view->hdr);
2116     }
2117     if (row) msiobj_release(&row->hdr);
2118     return rc;
2119 }
2120
2121 UINT WINAPI MsiSetPropertyW( MSIHANDLE hInstall, LPCWSTR szName, LPCWSTR szValue)
2122 {
2123     MSIPACKAGE *package;
2124     UINT ret;
2125
2126     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
2127     if( !package )
2128     {
2129         HRESULT hr;
2130         BSTR name = NULL, value = NULL;
2131         IWineMsiRemotePackage *remote_package;
2132
2133         remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
2134         if (!remote_package)
2135             return ERROR_INVALID_HANDLE;
2136
2137         name = SysAllocString( szName );
2138         value = SysAllocString( szValue );
2139         if ((!name && szName) || (!value && szValue))
2140         {
2141             SysFreeString( name );
2142             SysFreeString( value );
2143             IWineMsiRemotePackage_Release( remote_package );
2144             return ERROR_OUTOFMEMORY;
2145         }
2146
2147         hr = IWineMsiRemotePackage_SetProperty( remote_package, name, value );
2148
2149         SysFreeString( name );
2150         SysFreeString( value );
2151         IWineMsiRemotePackage_Release( remote_package );
2152
2153         if (FAILED(hr))
2154         {
2155             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
2156                 return HRESULT_CODE(hr);
2157
2158             return ERROR_FUNCTION_FAILED;
2159         }
2160
2161         return ERROR_SUCCESS;
2162     }
2163
2164     ret = msi_set_property( package->db, szName, szValue, -1 );
2165     if (ret == ERROR_SUCCESS && !strcmpW( szName, szSourceDir ))
2166         msi_reset_folders( package, TRUE );
2167
2168     msiobj_release( &package->hdr );
2169     return ret;
2170 }
2171
2172 static MSIRECORD *msi_get_property_row( MSIDATABASE *db, LPCWSTR name )
2173 {
2174     static const WCHAR query[]= {
2175         'S','E','L','E','C','T',' ','`','V','a','l','u','e','`',' ',
2176         'F','R','O','M',' ' ,'`','_','P','r','o','p','e','r','t','y','`',' ',
2177         'W','H','E','R','E',' ' ,'`','_','P','r','o','p','e','r','t','y','`','=','?',0};
2178     MSIRECORD *rec, *row = NULL;
2179     MSIQUERY *view;
2180     UINT r;
2181
2182     if (!name || !*name)
2183         return NULL;
2184
2185     rec = MSI_CreateRecord(1);
2186     if (!rec)
2187         return NULL;
2188
2189     MSI_RecordSetStringW(rec, 1, name);
2190
2191     r = MSI_DatabaseOpenViewW(db, query, &view);
2192     if (r == ERROR_SUCCESS)
2193     {
2194         MSI_ViewExecute(view, rec);
2195         MSI_ViewFetch(view, &row);
2196         MSI_ViewClose(view);
2197         msiobj_release(&view->hdr);
2198     }
2199     msiobj_release(&rec->hdr);
2200     return row;
2201 }
2202
2203 /* internal function, not compatible with MsiGetPropertyW */
2204 UINT msi_get_property( MSIDATABASE *db, LPCWSTR szName,
2205                        LPWSTR szValueBuf, LPDWORD pchValueBuf )
2206 {
2207     MSIRECORD *row;
2208     UINT rc = ERROR_FUNCTION_FAILED;
2209
2210     row = msi_get_property_row( db, szName );
2211
2212     if (*pchValueBuf > 0)
2213         szValueBuf[0] = 0;
2214
2215     if (row)
2216     {
2217         rc = MSI_RecordGetStringW(row, 1, szValueBuf, pchValueBuf);
2218         msiobj_release(&row->hdr);
2219     }
2220
2221     if (rc == ERROR_SUCCESS)
2222         TRACE("returning %s for property %s\n", debugstr_wn(szValueBuf, *pchValueBuf),
2223             debugstr_w(szName));
2224     else if (rc == ERROR_MORE_DATA)
2225         TRACE("need %d sized buffer for %s\n", *pchValueBuf,
2226             debugstr_w(szName));
2227     else
2228     {
2229         *pchValueBuf = 0;
2230         TRACE("property %s not found\n", debugstr_w(szName));
2231     }
2232
2233     return rc;
2234 }
2235
2236 LPWSTR msi_dup_property(MSIDATABASE *db, LPCWSTR prop)
2237 {
2238     DWORD sz = 0;
2239     LPWSTR str;
2240     UINT r;
2241
2242     r = msi_get_property(db, prop, NULL, &sz);
2243     if (r != ERROR_SUCCESS && r != ERROR_MORE_DATA)
2244         return NULL;
2245
2246     sz++;
2247     str = msi_alloc(sz * sizeof(WCHAR));
2248     r = msi_get_property(db, prop, str, &sz);
2249     if (r != ERROR_SUCCESS)
2250     {
2251         msi_free(str);
2252         str = NULL;
2253     }
2254
2255     return str;
2256 }
2257
2258 int msi_get_property_int( MSIDATABASE *db, LPCWSTR prop, int def )
2259 {
2260     LPWSTR str = msi_dup_property( db, prop );
2261     int val = str ? atoiW(str) : def;
2262     msi_free(str);
2263     return val;
2264 }
2265
2266 static UINT MSI_GetProperty( MSIHANDLE handle, LPCWSTR name,
2267                              awstring *szValueBuf, LPDWORD pchValueBuf )
2268 {
2269     MSIPACKAGE *package;
2270     MSIRECORD *row = NULL;
2271     UINT r = ERROR_FUNCTION_FAILED;
2272     LPCWSTR val = NULL;
2273     DWORD len = 0;
2274
2275     TRACE("%u %s %p %p\n", handle, debugstr_w(name),
2276           szValueBuf->str.w, pchValueBuf );
2277
2278     if (!name)
2279         return ERROR_INVALID_PARAMETER;
2280
2281     package = msihandle2msiinfo( handle, MSIHANDLETYPE_PACKAGE );
2282     if (!package)
2283     {
2284         HRESULT hr;
2285         IWineMsiRemotePackage *remote_package;
2286         LPWSTR value = NULL;
2287         BSTR bname;
2288
2289         remote_package = (IWineMsiRemotePackage *)msi_get_remote( handle );
2290         if (!remote_package)
2291             return ERROR_INVALID_HANDLE;
2292
2293         bname = SysAllocString( name );
2294         if (!bname)
2295         {
2296             IWineMsiRemotePackage_Release( remote_package );
2297             return ERROR_OUTOFMEMORY;
2298         }
2299
2300         hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, NULL, &len );
2301         if (FAILED(hr))
2302             goto done;
2303
2304         len++;
2305         value = msi_alloc(len * sizeof(WCHAR));
2306         if (!value)
2307         {
2308             r = ERROR_OUTOFMEMORY;
2309             goto done;
2310         }
2311
2312         hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, value, &len );
2313         if (FAILED(hr))
2314             goto done;
2315
2316         r = msi_strcpy_to_awstring( value, len, szValueBuf, pchValueBuf );
2317
2318         /* Bug required by Adobe installers */
2319         if (!szValueBuf->unicode && !szValueBuf->str.a)
2320             *pchValueBuf *= sizeof(WCHAR);
2321
2322 done:
2323         IWineMsiRemotePackage_Release(remote_package);
2324         SysFreeString(bname);
2325         msi_free(value);
2326
2327         if (FAILED(hr))
2328         {
2329             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
2330                 return HRESULT_CODE(hr);
2331
2332             return ERROR_FUNCTION_FAILED;
2333         }
2334
2335         return r;
2336     }
2337
2338     row = msi_get_property_row( package->db, name );
2339     if (row)
2340         val = msi_record_get_string( row, 1, (int *)&len );
2341
2342     if (!val)
2343         val = szEmpty;
2344
2345     r = msi_strcpy_to_awstring( val, len, szValueBuf, pchValueBuf );
2346
2347     if (row)
2348         msiobj_release( &row->hdr );
2349     msiobj_release( &package->hdr );
2350
2351     return r;
2352 }
2353
2354 UINT WINAPI MsiGetPropertyA( MSIHANDLE hInstall, LPCSTR szName,
2355                              LPSTR szValueBuf, LPDWORD pchValueBuf )
2356 {
2357     awstring val;
2358     LPWSTR name;
2359     UINT r;
2360
2361     val.unicode = FALSE;
2362     val.str.a = szValueBuf;
2363
2364     name = strdupAtoW( szName );
2365     if (szName && !name)
2366         return ERROR_OUTOFMEMORY;
2367
2368     r = MSI_GetProperty( hInstall, name, &val, pchValueBuf );
2369     msi_free( name );
2370     return r;
2371 }
2372
2373 UINT WINAPI MsiGetPropertyW( MSIHANDLE hInstall, LPCWSTR szName,
2374                              LPWSTR szValueBuf, LPDWORD pchValueBuf )
2375 {
2376     awstring val;
2377
2378     val.unicode = TRUE;
2379     val.str.w = szValueBuf;
2380
2381     return MSI_GetProperty( hInstall, szName, &val, pchValueBuf );
2382 }
2383
2384 typedef struct _msi_remote_package_impl {
2385     IWineMsiRemotePackage IWineMsiRemotePackage_iface;
2386     MSIHANDLE package;
2387     LONG refs;
2388 } msi_remote_package_impl;
2389
2390 static inline msi_remote_package_impl *impl_from_IWineMsiRemotePackage( IWineMsiRemotePackage *iface )
2391 {
2392     return CONTAINING_RECORD(iface, msi_remote_package_impl, IWineMsiRemotePackage_iface);
2393 }
2394
2395 static HRESULT WINAPI mrp_QueryInterface( IWineMsiRemotePackage *iface,
2396                 REFIID riid,LPVOID *ppobj)
2397 {
2398     if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2399         IsEqualCLSID( riid, &IID_IWineMsiRemotePackage ) )
2400     {
2401         IWineMsiRemotePackage_AddRef( iface );
2402         *ppobj = iface;
2403         return S_OK;
2404     }
2405
2406     return E_NOINTERFACE;
2407 }
2408
2409 static ULONG WINAPI mrp_AddRef( IWineMsiRemotePackage *iface )
2410 {
2411     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2412
2413     return InterlockedIncrement( &This->refs );
2414 }
2415
2416 static ULONG WINAPI mrp_Release( IWineMsiRemotePackage *iface )
2417 {
2418     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2419     ULONG r;
2420
2421     r = InterlockedDecrement( &This->refs );
2422     if (r == 0)
2423     {
2424         MsiCloseHandle( This->package );
2425         msi_free( This );
2426     }
2427     return r;
2428 }
2429
2430 static HRESULT WINAPI mrp_SetMsiHandle( IWineMsiRemotePackage *iface, MSIHANDLE handle )
2431 {
2432     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2433     This->package = handle;
2434     return S_OK;
2435 }
2436
2437 static HRESULT WINAPI mrp_GetActiveDatabase( IWineMsiRemotePackage *iface, MSIHANDLE *handle )
2438 {
2439     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2440     IWineMsiRemoteDatabase *rdb = NULL;
2441     HRESULT hr;
2442     MSIHANDLE hdb;
2443
2444     hr = create_msi_remote_database( NULL, (LPVOID *)&rdb );
2445     if (FAILED(hr) || !rdb)
2446     {
2447         ERR("Failed to create remote database\n");
2448         return hr;
2449     }
2450
2451     hdb = MsiGetActiveDatabase(This->package);
2452
2453     hr = IWineMsiRemoteDatabase_SetMsiHandle( rdb, hdb );
2454     if (FAILED(hr))
2455     {
2456         ERR("Failed to set the database handle\n");
2457         return hr;
2458     }
2459
2460     *handle = alloc_msi_remote_handle( (IUnknown *)rdb );
2461     return S_OK;
2462 }
2463
2464 static HRESULT WINAPI mrp_GetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR value, DWORD *size )
2465 {
2466     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2467     UINT r = MsiGetPropertyW(This->package, property, value, size);
2468     if (r != ERROR_SUCCESS) return HRESULT_FROM_WIN32(r);
2469     return S_OK;
2470 }
2471
2472 static HRESULT WINAPI mrp_SetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR value )
2473 {
2474     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2475     UINT r = MsiSetPropertyW(This->package, property, value);
2476     return HRESULT_FROM_WIN32(r);
2477 }
2478
2479 static HRESULT WINAPI mrp_ProcessMessage( IWineMsiRemotePackage *iface, INSTALLMESSAGE message, MSIHANDLE record )
2480 {
2481     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2482     UINT r = MsiProcessMessage(This->package, message, record);
2483     return HRESULT_FROM_WIN32(r);
2484 }
2485
2486 static HRESULT WINAPI mrp_DoAction( IWineMsiRemotePackage *iface, BSTR action )
2487 {
2488     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2489     UINT r = MsiDoActionW(This->package, action);
2490     return HRESULT_FROM_WIN32(r);
2491 }
2492
2493 static HRESULT WINAPI mrp_Sequence( IWineMsiRemotePackage *iface, BSTR table, int sequence )
2494 {
2495     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2496     UINT r = MsiSequenceW(This->package, table, sequence);
2497     return HRESULT_FROM_WIN32(r);
2498 }
2499
2500 static HRESULT WINAPI mrp_GetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value, DWORD *size )
2501 {
2502     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2503     UINT r = MsiGetTargetPathW(This->package, folder, value, size);
2504     return HRESULT_FROM_WIN32(r);
2505 }
2506
2507 static HRESULT WINAPI mrp_SetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value)
2508 {
2509     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2510     UINT r = MsiSetTargetPathW(This->package, folder, value);
2511     return HRESULT_FROM_WIN32(r);
2512 }
2513
2514 static HRESULT WINAPI mrp_GetSourcePath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value, DWORD *size )
2515 {
2516     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2517     UINT r = MsiGetSourcePathW(This->package, folder, value, size);
2518     return HRESULT_FROM_WIN32(r);
2519 }
2520
2521 static HRESULT WINAPI mrp_GetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL *ret )
2522 {
2523     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2524     *ret = MsiGetMode(This->package, mode);
2525     return S_OK;
2526 }
2527
2528 static HRESULT WINAPI mrp_SetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL state )
2529 {
2530     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2531     UINT r = MsiSetMode(This->package, mode, state);
2532     return HRESULT_FROM_WIN32(r);
2533 }
2534
2535 static HRESULT WINAPI mrp_GetFeatureState( IWineMsiRemotePackage *iface, BSTR feature,
2536                                     INSTALLSTATE *installed, INSTALLSTATE *action )
2537 {
2538     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2539     UINT r = MsiGetFeatureStateW(This->package, feature, installed, action);
2540     return HRESULT_FROM_WIN32(r);
2541 }
2542
2543 static HRESULT WINAPI mrp_SetFeatureState( IWineMsiRemotePackage *iface, BSTR feature, INSTALLSTATE state )
2544 {
2545     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2546     UINT r = MsiSetFeatureStateW(This->package, feature, state);
2547     return HRESULT_FROM_WIN32(r);
2548 }
2549
2550 static HRESULT WINAPI mrp_GetComponentState( IWineMsiRemotePackage *iface, BSTR component,
2551                                       INSTALLSTATE *installed, INSTALLSTATE *action )
2552 {
2553     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2554     UINT r = MsiGetComponentStateW(This->package, component, installed, action);
2555     return HRESULT_FROM_WIN32(r);
2556 }
2557
2558 static HRESULT WINAPI mrp_SetComponentState( IWineMsiRemotePackage *iface, BSTR component, INSTALLSTATE state )
2559 {
2560     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2561     UINT r = MsiSetComponentStateW(This->package, component, state);
2562     return HRESULT_FROM_WIN32(r);
2563 }
2564
2565 static HRESULT WINAPI mrp_GetLanguage( IWineMsiRemotePackage *iface, LANGID *language )
2566 {
2567     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2568     *language = MsiGetLanguage(This->package);
2569     return S_OK;
2570 }
2571
2572 static HRESULT WINAPI mrp_SetInstallLevel( IWineMsiRemotePackage *iface, int level )
2573 {
2574     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2575     UINT r = MsiSetInstallLevel(This->package, level);
2576     return HRESULT_FROM_WIN32(r);
2577 }
2578
2579 static HRESULT WINAPI mrp_FormatRecord( IWineMsiRemotePackage *iface, MSIHANDLE record,
2580                                         BSTR *value)
2581 {
2582     DWORD size = 0;
2583     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2584     UINT r = MsiFormatRecordW(This->package, record, NULL, &size);
2585     if (r == ERROR_SUCCESS)
2586     {
2587         *value = SysAllocStringLen(NULL, size);
2588         if (!*value)
2589             return E_OUTOFMEMORY;
2590         size++;
2591         r = MsiFormatRecordW(This->package, record, *value, &size);
2592     }
2593     return HRESULT_FROM_WIN32(r);
2594 }
2595
2596 static HRESULT WINAPI mrp_EvaluateCondition( IWineMsiRemotePackage *iface, BSTR condition )
2597 {
2598     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2599     UINT r = MsiEvaluateConditionW(This->package, condition);
2600     return HRESULT_FROM_WIN32(r);
2601 }
2602
2603 static HRESULT WINAPI mrp_GetFeatureCost( IWineMsiRemotePackage *iface, BSTR feature,
2604                                           INT cost_tree, INSTALLSTATE state, INT *cost )
2605 {
2606     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2607     UINT r = MsiGetFeatureCostW(This->package, feature, cost_tree, state, cost);
2608     return HRESULT_FROM_WIN32(r);
2609 }
2610
2611 static HRESULT WINAPI mrp_EnumComponentCosts( IWineMsiRemotePackage *iface, BSTR component,
2612                                               DWORD index, INSTALLSTATE state, BSTR drive,
2613                                               DWORD *buflen, INT *cost, INT *temp )
2614 {
2615     msi_remote_package_impl* This = impl_from_IWineMsiRemotePackage( iface );
2616     UINT r = MsiEnumComponentCostsW(This->package, component, index, state, drive, buflen, cost, temp);
2617     return HRESULT_FROM_WIN32(r);
2618 }
2619
2620 static const IWineMsiRemotePackageVtbl msi_remote_package_vtbl =
2621 {
2622     mrp_QueryInterface,
2623     mrp_AddRef,
2624     mrp_Release,
2625     mrp_SetMsiHandle,
2626     mrp_GetActiveDatabase,
2627     mrp_GetProperty,
2628     mrp_SetProperty,
2629     mrp_ProcessMessage,
2630     mrp_DoAction,
2631     mrp_Sequence,
2632     mrp_GetTargetPath,
2633     mrp_SetTargetPath,
2634     mrp_GetSourcePath,
2635     mrp_GetMode,
2636     mrp_SetMode,
2637     mrp_GetFeatureState,
2638     mrp_SetFeatureState,
2639     mrp_GetComponentState,
2640     mrp_SetComponentState,
2641     mrp_GetLanguage,
2642     mrp_SetInstallLevel,
2643     mrp_FormatRecord,
2644     mrp_EvaluateCondition,
2645     mrp_GetFeatureCost,
2646     mrp_EnumComponentCosts
2647 };
2648
2649 HRESULT create_msi_remote_package( IUnknown *pOuter, LPVOID *ppObj )
2650 {
2651     msi_remote_package_impl* This;
2652
2653     This = msi_alloc( sizeof *This );
2654     if (!This)
2655         return E_OUTOFMEMORY;
2656
2657     This->IWineMsiRemotePackage_iface.lpVtbl = &msi_remote_package_vtbl;
2658     This->package = 0;
2659     This->refs = 1;
2660
2661     *ppObj = This;
2662
2663     return S_OK;
2664 }
2665
2666 UINT msi_package_add_info(MSIPACKAGE *package, DWORD context, DWORD options,
2667                           LPCWSTR property, LPWSTR value)
2668 {
2669     MSISOURCELISTINFO *info;
2670
2671     LIST_FOR_EACH_ENTRY( info, &package->sourcelist_info, MSISOURCELISTINFO, entry )
2672     {
2673         if (!strcmpW( info->value, value )) return ERROR_SUCCESS;
2674     }
2675
2676     info = msi_alloc(sizeof(MSISOURCELISTINFO));
2677     if (!info)
2678         return ERROR_OUTOFMEMORY;
2679
2680     info->context = context;
2681     info->options = options;
2682     info->property = property;
2683     info->value = strdupW(value);
2684     list_add_head(&package->sourcelist_info, &info->entry);
2685
2686     return ERROR_SUCCESS;
2687 }
2688
2689 UINT msi_package_add_media_disk(MSIPACKAGE *package, DWORD context, DWORD options,
2690                                 DWORD disk_id, LPWSTR volume_label, LPWSTR disk_prompt)
2691 {
2692     MSIMEDIADISK *disk;
2693
2694     LIST_FOR_EACH_ENTRY( disk, &package->sourcelist_media, MSIMEDIADISK, entry )
2695     {
2696         if (disk->disk_id == disk_id) return ERROR_SUCCESS;
2697     }
2698
2699     disk = msi_alloc(sizeof(MSIMEDIADISK));
2700     if (!disk)
2701         return ERROR_OUTOFMEMORY;
2702
2703     disk->context = context;
2704     disk->options = options;
2705     disk->disk_id = disk_id;
2706     disk->volume_label = strdupW(volume_label);
2707     disk->disk_prompt = strdupW(disk_prompt);
2708     list_add_head(&package->sourcelist_media, &disk->entry);
2709
2710     return ERROR_SUCCESS;
2711 }