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