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