dlls: Fix some specfiles with respect to 'str' and 'wstr' usage.
[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 szMsiAMD64[] = { 'M','s','i','A','M','D','6','4',0 };
688     static const WCHAR szMsix64[] = { 'M','s','i','x','6','4',0 };
689     static const WCHAR szSystem64Folder[] = { 'S','y','s','t','e','m','6','4','F','o','l','d','e','r',0 };
690     static const WCHAR szUserInfo[] = {
691         'S','O','F','T','W','A','R','E','\\',
692         'M','i','c','r','o','s','o','f','t','\\',
693         'M','S',' ','S','e','t','u','p',' ','(','A','C','M','E',')','\\',
694         'U','s','e','r',' ','I','n','f','o',0
695     };
696     static const WCHAR szDefName[] = { 'D','e','f','N','a','m','e',0 };
697     static const WCHAR szDefCompany[] = { 'D','e','f','C','o','m','p','a','n','y',0 };
698     static const WCHAR szCurrentVersion[] = {
699         'S','O','F','T','W','A','R','E','\\',
700         'M','i','c','r','o','s','o','f','t','\\',
701         'W','i','n','d','o','w','s',' ','N','T','\\',
702         'C','u','r','r','e','n','t','V','e','r','s','i','o','n',0
703     };
704     static const WCHAR szRegisteredUser[] = {'R','e','g','i','s','t','e','r','e','d','O','w','n','e','r',0};
705     static const WCHAR szRegisteredOrg[] = {
706         'R','e','g','i','s','t','e','r','e','d','O','r','g','a','n','i','z','a','t','i','o','n',0
707     };
708     static const WCHAR szUSERNAME[] = {'U','S','E','R','N','A','M','E',0};
709     static const WCHAR szCOMPANYNAME[] = {'C','O','M','P','A','N','Y','N','A','M','E',0};
710     static const WCHAR szDate[] = {'D','a','t','e',0};
711     static const WCHAR szTime[] = {'T','i','m','e',0};
712     static const WCHAR szUserLangID[] = {'U','s','e','r','L','a','n','g','u','a','g','e','I','D',0};
713     static const WCHAR szSystemLangID[] = {'S','y','s','t','e','m','L','a','n','g','u','a','g','e','I','D',0};
714     static const WCHAR szProductState[] = {'P','r','o','d','u','c','t','S','t','a','t','e',0};
715     static const WCHAR szLogonUser[] = {'L','o','g','o','n','U','s','e','r',0};
716
717     /*
718      * Other things that probably should be set:
719      *
720      * ComputerName VirtualMemory
721      * ShellAdvSupport DefaultUIFont PackagecodeChanging
722      * CaptionHeight BorderTop BorderSide TextHeight
723      * RedirectedDllSupport
724      */
725
726     SHGetFolderPathW(NULL,CSIDL_PROGRAM_FILES_COMMON,NULL,0,pth);
727     strcatW(pth, szBackSlash);
728     msi_set_property(package->db, CFF, pth);
729
730     SHGetFolderPathW(NULL,CSIDL_PROGRAM_FILES,NULL,0,pth);
731     strcatW(pth, szBackSlash);
732     msi_set_property(package->db, PFF, pth);
733
734     SHGetFolderPathW(NULL,CSIDL_COMMON_APPDATA,NULL,0,pth);
735     strcatW(pth, szBackSlash);
736     msi_set_property(package->db, CADF, pth);
737
738     SHGetFolderPathW(NULL,CSIDL_FAVORITES,NULL,0,pth);
739     strcatW(pth, szBackSlash);
740     msi_set_property(package->db, FaF, pth);
741
742     SHGetFolderPathW(NULL,CSIDL_FONTS,NULL,0,pth);
743     strcatW(pth, szBackSlash);
744     msi_set_property(package->db, FoF, pth);
745
746     SHGetFolderPathW(NULL,CSIDL_SENDTO,NULL,0,pth);
747     strcatW(pth, szBackSlash);
748     msi_set_property(package->db, SendTF, pth);
749
750     SHGetFolderPathW(NULL,CSIDL_STARTMENU,NULL,0,pth);
751     strcatW(pth, szBackSlash);
752     msi_set_property(package->db, SMF, pth);
753
754     SHGetFolderPathW(NULL,CSIDL_STARTUP,NULL,0,pth);
755     strcatW(pth, szBackSlash);
756     msi_set_property(package->db, StF, pth);
757
758     SHGetFolderPathW(NULL,CSIDL_TEMPLATES,NULL,0,pth);
759     strcatW(pth, szBackSlash);
760     msi_set_property(package->db, TemplF, pth);
761
762     SHGetFolderPathW(NULL,CSIDL_DESKTOP,NULL,0,pth);
763     strcatW(pth, szBackSlash);
764     msi_set_property(package->db, DF, pth);
765
766     SHGetFolderPathW(NULL,CSIDL_PROGRAMS,NULL,0,pth);
767     strcatW(pth, szBackSlash);
768     msi_set_property(package->db, PMF, pth);
769
770     SHGetFolderPathW(NULL,CSIDL_ADMINTOOLS,NULL,0,pth);
771     strcatW(pth, szBackSlash);
772     msi_set_property(package->db, ATF, pth);
773
774     SHGetFolderPathW(NULL,CSIDL_APPDATA,NULL,0,pth);
775     strcatW(pth, szBackSlash);
776     msi_set_property(package->db, ADF, pth);
777
778     SHGetFolderPathW(NULL,CSIDL_SYSTEM,NULL,0,pth);
779     strcatW(pth, szBackSlash);
780     msi_set_property(package->db, SF, pth);
781     msi_set_property(package->db, SF16, pth);
782
783     SHGetFolderPathW(NULL,CSIDL_LOCAL_APPDATA,NULL,0,pth);
784     strcatW(pth, szBackSlash);
785     msi_set_property(package->db, LADF, pth);
786
787     SHGetFolderPathW(NULL,CSIDL_MYPICTURES,NULL,0,pth);
788     strcatW(pth, szBackSlash);
789     msi_set_property(package->db, MPF, pth);
790
791     SHGetFolderPathW(NULL,CSIDL_PERSONAL,NULL,0,pth);
792     strcatW(pth, szBackSlash);
793     msi_set_property(package->db, PF, pth);
794
795     SHGetFolderPathW(NULL,CSIDL_WINDOWS,NULL,0,pth);
796     strcatW(pth, szBackSlash);
797     msi_set_property(package->db, WF, pth);
798     
799     /* Physical Memory is specified in MB. Using total amount. */
800     msex.dwLength = sizeof(msex);
801     GlobalMemoryStatusEx( &msex );
802     sprintfW( bufstr, szIntFormat, (int)(msex.ullTotalPhys/1024/1024));
803     msi_set_property(package->db, szPhysicalMemory, bufstr);
804
805     SHGetFolderPathW(NULL,CSIDL_WINDOWS,NULL,0,pth);
806     ptr = strchrW(pth,'\\');
807     if (ptr)
808         *(ptr+1) = 0;
809     msi_set_property(package->db, WV, pth);
810     
811     GetTempPathW(MAX_PATH,pth);
812     msi_set_property(package->db, TF, pth);
813
814
815     /* in a wine environment the user is always admin and privileged */
816     msi_set_property(package->db, szAdminUser, szOne);
817     msi_set_property(package->db, szPriv, szOne);
818
819     /* set the os things */
820     OSVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
821     GetVersionExW((OSVERSIONINFOW *)&OSVersion);
822     verval = OSVersion.dwMinorVersion+OSVersion.dwMajorVersion*100;
823     sprintfW(verstr,szFormat,verval);
824     switch (OSVersion.dwPlatformId)
825     {
826         case VER_PLATFORM_WIN32_WINDOWS:    
827             msi_set_property(package->db, v9x, verstr);
828             break;
829         case VER_PLATFORM_WIN32_NT:
830             msi_set_property(package->db, vNT, verstr);
831             sprintfW(verstr,szFormat,OSVersion.wProductType);
832             msi_set_property(package->db, szMsiNTProductType, verstr);
833             break;
834     }
835     sprintfW(verstr,szFormat,OSVersion.dwBuildNumber);
836     msi_set_property(package->db, szWinBuild, verstr);
837     /* just fudge this */
838     msi_set_property(package->db, szSPL, szSix);
839
840     sprintfW( bufstr, szFormat2, MSI_MAJORVERSION, MSI_MINORVERSION);
841     msi_set_property( package->db, szVersionMsi, bufstr );
842     sprintfW( bufstr, szFormat, MSI_MAJORVERSION * 100);
843     msi_set_property( package->db, szVersionDatabase, bufstr );
844
845     GetSystemInfo( &sys_info );
846     if (sys_info.u.s.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
847     {
848         sprintfW( bufstr, szIntFormat, sys_info.wProcessorLevel );
849         msi_set_property( package->db, szIntel, bufstr );
850     }
851     else if (sys_info.u.s.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
852     {
853         sprintfW( bufstr, szIntFormat, sys_info.wProcessorLevel );
854         msi_set_property( package->db, szMsiAMD64, bufstr );
855         msi_set_property( package->db, szMsix64, bufstr );
856
857         GetSystemDirectoryW( pth, MAX_PATH );
858         msi_set_property( package->db, szSystem64Folder, pth );
859     }
860
861     /* Screen properties. */
862     dc = GetDC(0);
863     sprintfW( bufstr, szIntFormat, GetDeviceCaps( dc, HORZRES ) );
864     msi_set_property( package->db, szScreenX, bufstr );
865     sprintfW( bufstr, szIntFormat, GetDeviceCaps( dc, VERTRES ));
866     msi_set_property( package->db, szScreenY, bufstr );
867     sprintfW( bufstr, szIntFormat, GetDeviceCaps( dc, BITSPIXEL ));
868     msi_set_property( package->db, szColorBits, bufstr );
869     ReleaseDC(0, dc);
870
871     /* USERNAME and COMPANYNAME */
872     username = msi_dup_property( package->db, szUSERNAME );
873     companyname = msi_dup_property( package->db, szCOMPANYNAME );
874
875     if ((!username || !companyname) &&
876         RegOpenKeyW( HKEY_CURRENT_USER, szUserInfo, &hkey ) == ERROR_SUCCESS)
877     {
878         if (!username &&
879             (username = msi_reg_get_val_str( hkey, szDefName )))
880             msi_set_property( package->db, szUSERNAME, username );
881         if (!companyname &&
882             (companyname = msi_reg_get_val_str( hkey, szDefCompany )))
883             msi_set_property( package->db, szCOMPANYNAME, companyname );
884         CloseHandle( hkey );
885     }
886     if ((!username || !companyname) &&
887         RegOpenKeyW( HKEY_LOCAL_MACHINE, szCurrentVersion, &hkey ) == ERROR_SUCCESS)
888     {
889         if (!username &&
890             (username = msi_reg_get_val_str( hkey, szRegisteredUser )))
891             msi_set_property( package->db, szUSERNAME, username );
892         if (!companyname &&
893             (companyname = msi_reg_get_val_str( hkey, szRegisteredOrg )))
894             msi_set_property( package->db, szCOMPANYNAME, companyname );
895         CloseHandle( hkey );
896     }
897     msi_free( username );
898     msi_free( companyname );
899
900     if ( set_user_sid_prop( package ) != ERROR_SUCCESS)
901         ERR("Failed to set the UserSID property\n");
902
903     /* Date and time properties */
904     GetSystemTime( &systemtime );
905     if (GetDateFormatW( LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systemtime,
906                         NULL, bufstr, sizeof(bufstr)/sizeof(bufstr[0]) ))
907         msi_set_property( package->db, szDate, bufstr );
908     else
909         ERR("Couldn't set Date property: GetDateFormat failed with error %d\n", GetLastError());
910
911     if (GetTimeFormatW( LOCALE_USER_DEFAULT,
912                         TIME_FORCE24HOURFORMAT | TIME_NOTIMEMARKER,
913                         &systemtime, NULL, bufstr,
914                         sizeof(bufstr)/sizeof(bufstr[0]) ))
915         msi_set_property( package->db, szTime, bufstr );
916     else
917         ERR("Couldn't set Time property: GetTimeFormat failed with error %d\n", GetLastError());
918
919     set_msi_assembly_prop( package );
920
921     langid = GetUserDefaultLangID();
922     sprintfW(bufstr, szIntFormat, langid);
923     msi_set_property( package->db, szUserLangID, bufstr );
924
925     langid = GetSystemDefaultLangID();
926     sprintfW(bufstr, szIntFormat, langid);
927     msi_set_property( package->db, szSystemLangID, bufstr );
928
929     sprintfW(bufstr, szIntFormat, MsiQueryProductStateW(package->ProductCode));
930     msi_set_property( package->db, szProductState, bufstr );
931
932     len = 0;
933     if (!GetUserNameW( NULL, &len ) && GetLastError() == ERROR_MORE_DATA)
934     {
935         WCHAR *username;
936         if ((username = msi_alloc( len * sizeof(WCHAR) )))
937         {
938             if (GetUserNameW( username, &len ))
939                 msi_set_property( package->db, szLogonUser, username );
940             msi_free( username );
941         }
942     }
943 }
944
945 static UINT msi_load_summary_properties( MSIPACKAGE *package )
946 {
947     UINT rc;
948     MSIHANDLE suminfo;
949     MSIHANDLE hdb = alloc_msihandle( &package->db->hdr );
950     INT count;
951     DWORD len;
952     LPWSTR package_code;
953     static const WCHAR szPackageCode[] = {
954         'P','a','c','k','a','g','e','C','o','d','e',0};
955
956     if (!hdb) {
957         ERR("Unable to allocate handle\n");
958         return ERROR_OUTOFMEMORY;
959     }
960
961     rc = MsiGetSummaryInformationW( hdb, NULL, 0, &suminfo );
962     MsiCloseHandle(hdb);
963     if (rc != ERROR_SUCCESS)
964     {
965         ERR("Unable to open Summary Information\n");
966         return rc;
967     }
968
969     rc = MsiSummaryInfoGetPropertyW( suminfo, PID_PAGECOUNT, NULL,
970                                      &count, NULL, NULL, NULL );
971     if (rc != ERROR_SUCCESS)
972     {
973         WARN("Unable to query page count: %d\n", rc);
974         goto done;
975     }
976
977     /* load package code property */
978     len = 0;
979     rc = MsiSummaryInfoGetPropertyW( suminfo, PID_REVNUMBER, NULL,
980                                      NULL, NULL, NULL, &len );
981     if (rc != ERROR_MORE_DATA)
982     {
983         WARN("Unable to query revision number: %d\n", rc);
984         rc = ERROR_FUNCTION_FAILED;
985         goto done;
986     }
987
988     len++;
989     package_code = msi_alloc( len * sizeof(WCHAR) );
990     rc = MsiSummaryInfoGetPropertyW( suminfo, PID_REVNUMBER, NULL,
991                                      NULL, NULL, package_code, &len );
992     if (rc != ERROR_SUCCESS)
993     {
994         WARN("Unable to query rev number: %d\n", rc);
995         goto done;
996     }
997
998     msi_set_property( package->db, szPackageCode, package_code );
999     msi_free( package_code );
1000
1001     /* load package attributes */
1002     count = 0;
1003     MsiSummaryInfoGetPropertyW( suminfo, PID_WORDCOUNT, NULL,
1004                                 &count, NULL, NULL, NULL );
1005     package->WordCount = count;
1006
1007 done:
1008     MsiCloseHandle(suminfo);
1009     return rc;
1010 }
1011
1012 static MSIPACKAGE *msi_alloc_package( void )
1013 {
1014     MSIPACKAGE *package;
1015
1016     package = alloc_msiobject( MSIHANDLETYPE_PACKAGE, sizeof (MSIPACKAGE),
1017                                MSI_FreePackage );
1018     if( package )
1019     {
1020         list_init( &package->components );
1021         list_init( &package->features );
1022         list_init( &package->files );
1023         list_init( &package->tempfiles );
1024         list_init( &package->folders );
1025         list_init( &package->subscriptions );
1026         list_init( &package->appids );
1027         list_init( &package->classes );
1028         list_init( &package->mimes );
1029         list_init( &package->extensions );
1030         list_init( &package->progids );
1031         list_init( &package->RunningActions );
1032         list_init( &package->sourcelist_info );
1033         list_init( &package->sourcelist_media );
1034         list_init( &package->patches );
1035     }
1036
1037     return package;
1038 }
1039
1040 static UINT msi_load_admin_properties(MSIPACKAGE *package)
1041 {
1042     BYTE *data;
1043     UINT r, sz;
1044
1045     static const WCHAR stmname[] = {'A','d','m','i','n','P','r','o','p','e','r','t','i','e','s',0};
1046
1047     r = read_stream_data(package->db->storage, stmname, FALSE, &data, &sz);
1048     if (r != ERROR_SUCCESS)
1049         return r;
1050
1051     r = msi_parse_command_line(package, (WCHAR *)data, TRUE);
1052
1053     msi_free(data);
1054     return r;
1055 }
1056
1057 void msi_adjust_allusers_property( MSIPACKAGE *package )
1058 {
1059     /* FIXME: this should depend on the user's privileges */
1060     if (msi_get_property_int( package->db, szAllUsers, 0 ) == 2)
1061     {
1062         TRACE("resetting ALLUSERS property from 2 to 1\n");
1063         msi_set_property( package->db, szAllUsers, szOne );
1064     }
1065 }
1066
1067 MSIPACKAGE *MSI_CreatePackage( MSIDATABASE *db, LPCWSTR base_url )
1068 {
1069     static const WCHAR szLevel[] = { 'U','I','L','e','v','e','l',0 };
1070     static const WCHAR szpi[] = {'%','i',0};
1071     MSIPACKAGE *package;
1072     WCHAR uilevel[10];
1073     UINT r;
1074
1075     TRACE("%p\n", db);
1076
1077     package = msi_alloc_package();
1078     if (package)
1079     {
1080         msiobj_addref( &db->hdr );
1081         package->db = db;
1082
1083         package->WordCount = 0;
1084         package->PackagePath = strdupW( db->path );
1085         package->BaseURL = strdupW( base_url );
1086
1087         create_temp_property_table( package );
1088         msi_clone_properties( package );
1089         msi_adjust_allusers_property( package );
1090
1091         package->ProductCode = msi_dup_property( package->db, szProductCode );
1092         package->script = msi_alloc_zero( sizeof(MSISCRIPT) );
1093
1094         set_installed_prop( package );
1095         set_installer_properties( package );
1096
1097         sprintfW(uilevel,szpi,gUILevel);
1098         msi_set_property(package->db, szLevel, uilevel);
1099
1100         r = msi_load_summary_properties( package );
1101         if (r != ERROR_SUCCESS)
1102         {
1103             msiobj_release( &package->hdr );
1104             return NULL;
1105         }
1106
1107         if (package->WordCount & msidbSumInfoSourceTypeAdminImage)
1108             msi_load_admin_properties( package );
1109     }
1110
1111     return package;
1112 }
1113
1114 /*
1115  * copy_package_to_temp   [internal]
1116  *
1117  * copy the msi file to a temp file to prevent locking a CD
1118  * with a multi disc install 
1119  *
1120  * FIXME: I think this is wrong, and instead of copying the package,
1121  *        we should read all the tables to memory, then open the
1122  *        database to read binary streams on demand.
1123  */ 
1124 static UINT copy_package_to_temp( LPCWSTR szPackage, LPWSTR filename )
1125 {
1126     WCHAR path[MAX_PATH];
1127
1128     GetTempPathW( MAX_PATH, path );
1129     GetTempFileNameW( path, szMsi, 0, filename );
1130
1131     if( !CopyFileW( szPackage, filename, FALSE ) )
1132     {
1133         UINT error = GetLastError();
1134         if ( error == ERROR_FILE_NOT_FOUND )
1135             ERR("can't find %s\n", debugstr_w(szPackage));
1136         else
1137             ERR("failed to copy package %s to %s (%u)\n", debugstr_w(szPackage), debugstr_w(filename), error);
1138         DeleteFileW( filename );
1139         return error;
1140     }
1141
1142     return ERROR_SUCCESS;
1143 }
1144
1145 UINT msi_download_file( LPCWSTR szUrl, LPWSTR filename )
1146 {
1147     LPINTERNET_CACHE_ENTRY_INFOW cache_entry;
1148     DWORD size = 0;
1149     HRESULT hr;
1150
1151     /* call will always fail, becase size is 0,
1152      * but will return ERROR_FILE_NOT_FOUND first
1153      * if the file doesn't exist
1154      */
1155     GetUrlCacheEntryInfoW( szUrl, NULL, &size );
1156     if ( GetLastError() != ERROR_FILE_NOT_FOUND )
1157     {
1158         cache_entry = msi_alloc( size );
1159         if ( !GetUrlCacheEntryInfoW( szUrl, cache_entry, &size ) )
1160         {
1161             UINT error = GetLastError();
1162             msi_free( cache_entry );
1163             return error;
1164         }
1165
1166         lstrcpyW( filename, cache_entry->lpszLocalFileName );
1167         msi_free( cache_entry );
1168         return ERROR_SUCCESS;
1169     }
1170
1171     hr = URLDownloadToCacheFileW( NULL, szUrl, filename, MAX_PATH, 0, NULL );
1172     if ( FAILED(hr) )
1173     {
1174         WARN("failed to download %s to cache file\n", debugstr_w(szUrl));
1175         return ERROR_FUNCTION_FAILED;
1176     }
1177
1178     return ERROR_SUCCESS;
1179 }
1180
1181 UINT msi_get_local_package_name( LPWSTR path, LPCWSTR suffix )
1182 {
1183     static const WCHAR szInstaller[] = {
1184         '\\','I','n','s','t','a','l','l','e','r','\\',0};
1185     static const WCHAR fmt[] = {'%','x',0};
1186     DWORD time, len, i, offset;
1187     HANDLE handle;
1188
1189     time = GetTickCount();
1190     GetWindowsDirectoryW( path, MAX_PATH );
1191     strcatW( path, szInstaller );
1192     CreateDirectoryW( path, NULL );
1193
1194     len = strlenW(path);
1195     for (i = 0; i < 0x10000; i++)
1196     {
1197         offset = snprintfW( path + len, MAX_PATH - len, fmt, (time + i) & 0xffff );
1198         memcpy( path + len + offset, suffix, (strlenW( suffix ) + 1) * sizeof(WCHAR) );
1199         handle = CreateFileW( path, GENERIC_WRITE, 0, NULL,
1200                               CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
1201         if (handle != INVALID_HANDLE_VALUE)
1202         {
1203             CloseHandle(handle);
1204             break;
1205         }
1206         if (GetLastError() != ERROR_FILE_EXISTS &&
1207             GetLastError() != ERROR_SHARING_VIOLATION)
1208             return ERROR_FUNCTION_FAILED;
1209     }
1210
1211     return ERROR_SUCCESS;
1212 }
1213
1214 static UINT apply_registered_patch( MSIPACKAGE *package, LPCWSTR patch_code )
1215 {
1216     UINT r;
1217     DWORD len;
1218     WCHAR patch_file[MAX_PATH];
1219     MSIDATABASE *patch_db;
1220     MSIPATCHINFO *patch_info;
1221     MSISUMMARYINFO *si;
1222
1223     len = sizeof(patch_file) / sizeof(WCHAR);
1224     r = MsiGetPatchInfoExW( patch_code, package->ProductCode, NULL, package->Context,
1225                             INSTALLPROPERTY_LOCALPACKAGEW, patch_file, &len );
1226     if (r != ERROR_SUCCESS)
1227     {
1228         ERR("failed to get patch filename %u\n", r);
1229         return r;
1230     }
1231
1232     r = MSI_OpenDatabaseW( patch_file, MSIDBOPEN_READONLY + MSIDBOPEN_PATCHFILE, &patch_db );
1233     if (r != ERROR_SUCCESS)
1234     {
1235         ERR("failed to open patch database %s\n", debugstr_w( patch_file ));
1236         return r;
1237     }
1238
1239     si = MSI_GetSummaryInformationW( patch_db->storage, 0 );
1240     if (!si)
1241     {
1242         msiobj_release( &patch_db->hdr );
1243         return ERROR_FUNCTION_FAILED;
1244     }
1245
1246     r = msi_parse_patch_summary( si, &patch_info );
1247     msiobj_release( &si->hdr );
1248     if (r != ERROR_SUCCESS)
1249     {
1250         ERR("failed to parse patch summary %u\n", r);
1251         msiobj_release( &patch_db->hdr );
1252         return r;
1253     }
1254
1255     patch_info->localfile = strdupW( patch_file );
1256     if (!patch_info->localfile)
1257     {
1258         msiobj_release( &patch_db->hdr );
1259         return ERROR_OUTOFMEMORY;
1260     }
1261
1262     r = msi_apply_patch_db( package, patch_db, patch_info );
1263     msiobj_release( &patch_db->hdr );
1264     if (r != ERROR_SUCCESS)
1265     {
1266         ERR("failed to apply patch %u\n", r);
1267         msi_free( patch_info->patchcode );
1268         msi_free( patch_info->transforms );
1269         msi_free( patch_info->localfile );
1270         msi_free( patch_info );
1271     }
1272     return r;
1273 }
1274
1275 UINT MSI_OpenPackageW(LPCWSTR szPackage, MSIPACKAGE **pPackage)
1276 {
1277     static const WCHAR Database[] = {'D','A','T','A','B','A','S','E',0};
1278     static const WCHAR dotmsi[] = {'.','m','s','i',0};
1279     MSIDATABASE *db = NULL;
1280     MSIPACKAGE *package;
1281     MSIHANDLE handle;
1282     LPWSTR ptr, base_url = NULL;
1283     UINT r;
1284     WCHAR temppath[MAX_PATH], localfile[MAX_PATH], cachefile[MAX_PATH];
1285     LPCWSTR file = szPackage;
1286     DWORD index = 0;
1287
1288     TRACE("%s %p\n", debugstr_w(szPackage), pPackage);
1289
1290     if( szPackage[0] == '#' )
1291     {
1292         handle = atoiW(&szPackage[1]);
1293         db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1294         if( !db )
1295         {
1296             IWineMsiRemoteDatabase *remote_database;
1297
1298             remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1299             if ( !remote_database )
1300                 return ERROR_INVALID_HANDLE;
1301
1302             IWineMsiRemoteDatabase_Release( remote_database );
1303             WARN("MsiOpenPackage not allowed during a custom action!\n");
1304
1305             return ERROR_FUNCTION_FAILED;
1306         }
1307     }
1308     else
1309     {
1310         if ( UrlIsW( szPackage, URLIS_URL ) )
1311         {
1312             r = msi_download_file( szPackage, cachefile );
1313             if ( r != ERROR_SUCCESS )
1314                 return r;
1315
1316             r = copy_package_to_temp( cachefile, temppath );
1317             if ( r != ERROR_SUCCESS )
1318                 return r;
1319
1320             file = temppath;
1321
1322             base_url = strdupW( szPackage );
1323             if ( !base_url )
1324                 return ERROR_OUTOFMEMORY;
1325
1326             ptr = strrchrW( base_url, '/' );
1327             if (ptr) *(ptr + 1) = '\0';
1328         }
1329         else
1330         {
1331             r = copy_package_to_temp( szPackage, temppath );
1332             if ( r != ERROR_SUCCESS )
1333                 return r;
1334
1335             file = temppath;
1336         }
1337
1338         r = msi_get_local_package_name( localfile, dotmsi );
1339         if (r != ERROR_SUCCESS)
1340             return r;
1341
1342         TRACE("Copying to local package %s\n", debugstr_w(localfile));
1343
1344         if (!CopyFileW( file, localfile, FALSE ))
1345         {
1346             ERR("Unable to copy package (%s -> %s) (error %u)\n",
1347                 debugstr_w(file), debugstr_w(localfile), GetLastError());
1348             return GetLastError();
1349         }
1350
1351         TRACE("Opening relocated package %s\n", debugstr_w( file ));
1352
1353         /* transforms that add binary streams require that we open the database
1354          * read/write, which is safe because we always create a copy that is thrown
1355          * away when we're done.
1356          */
1357         r = MSI_OpenDatabaseW( file, MSIDBOPEN_TRANSACT, &db );
1358         if( r != ERROR_SUCCESS )
1359         {
1360             if (file != szPackage)
1361                 DeleteFileW( file );
1362
1363             if (GetFileAttributesW(szPackage) == INVALID_FILE_ATTRIBUTES)
1364                 return ERROR_FILE_NOT_FOUND;
1365
1366             return r;
1367         }
1368
1369         db->localfile = strdupW( localfile );
1370     }
1371
1372     package = MSI_CreatePackage( db, base_url );
1373     msi_free( base_url );
1374     msiobj_release( &db->hdr );
1375     if( !package )
1376     {
1377         if (file != szPackage)
1378             DeleteFileW( file );
1379
1380         return ERROR_INSTALL_PACKAGE_INVALID;
1381     }
1382
1383     if( file != szPackage )
1384         track_tempfile( package, file );
1385
1386     msi_set_property( package->db, Database, db->path );
1387
1388     if( UrlIsW( szPackage, URLIS_URL ) )
1389         msi_set_property( package->db, szOriginalDatabase, szPackage );
1390     else if( szPackage[0] == '#' )
1391         msi_set_property( package->db, szOriginalDatabase, db->path );
1392     else
1393     {
1394         WCHAR fullpath[MAX_PATH];
1395
1396         GetFullPathNameW( szPackage, MAX_PATH, fullpath, NULL );
1397         msi_set_property( package->db, szOriginalDatabase, fullpath );
1398     }
1399
1400     msi_set_context( package );
1401
1402     while (1)
1403     {
1404         WCHAR patch_code[GUID_SIZE];
1405         r = MsiEnumPatchesExW( package->ProductCode, NULL, package->Context,
1406                                MSIPATCHSTATE_APPLIED, index, patch_code, NULL, NULL, NULL, NULL );
1407         if (r != ERROR_SUCCESS)
1408             break;
1409
1410         TRACE("found registered patch %s\n", debugstr_w(patch_code));
1411
1412         r = apply_registered_patch( package, patch_code );
1413         if (r != ERROR_SUCCESS)
1414         {
1415             ERR("registered patch failed to apply %u\n", r);
1416             MSI_FreePackage( (MSIOBJECTHDR *)package );
1417             return r;
1418         }
1419
1420         index++;
1421     }
1422
1423     if (index)
1424     {
1425         msi_clone_properties( package );
1426         msi_adjust_allusers_property( package );
1427     }
1428
1429     *pPackage = package;
1430     return ERROR_SUCCESS;
1431 }
1432
1433 UINT WINAPI MsiOpenPackageExW(LPCWSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
1434 {
1435     MSIPACKAGE *package = NULL;
1436     UINT ret;
1437
1438     TRACE("%s %08x %p\n", debugstr_w(szPackage), dwOptions, phPackage );
1439
1440     if( !szPackage || !phPackage )
1441         return ERROR_INVALID_PARAMETER;
1442
1443     if ( !*szPackage )
1444     {
1445         FIXME("Should create an empty database and package\n");
1446         return ERROR_FUNCTION_FAILED;
1447     }
1448
1449     if( dwOptions )
1450         FIXME("dwOptions %08x not supported\n", dwOptions);
1451
1452     ret = MSI_OpenPackageW( szPackage, &package );
1453     if( ret == ERROR_SUCCESS )
1454     {
1455         *phPackage = alloc_msihandle( &package->hdr );
1456         if (! *phPackage)
1457             ret = ERROR_NOT_ENOUGH_MEMORY;
1458         msiobj_release( &package->hdr );
1459     }
1460
1461     return ret;
1462 }
1463
1464 UINT WINAPI MsiOpenPackageW(LPCWSTR szPackage, MSIHANDLE *phPackage)
1465 {
1466     return MsiOpenPackageExW( szPackage, 0, phPackage );
1467 }
1468
1469 UINT WINAPI MsiOpenPackageExA(LPCSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
1470 {
1471     LPWSTR szwPack = NULL;
1472     UINT ret;
1473
1474     if( szPackage )
1475     {
1476         szwPack = strdupAtoW( szPackage );
1477         if( !szwPack )
1478             return ERROR_OUTOFMEMORY;
1479     }
1480
1481     ret = MsiOpenPackageExW( szwPack, dwOptions, phPackage );
1482
1483     msi_free( szwPack );
1484
1485     return ret;
1486 }
1487
1488 UINT WINAPI MsiOpenPackageA(LPCSTR szPackage, MSIHANDLE *phPackage)
1489 {
1490     return MsiOpenPackageExA( szPackage, 0, phPackage );
1491 }
1492
1493 MSIHANDLE WINAPI MsiGetActiveDatabase(MSIHANDLE hInstall)
1494 {
1495     MSIPACKAGE *package;
1496     MSIHANDLE handle = 0;
1497     IUnknown *remote_unk;
1498     IWineMsiRemotePackage *remote_package;
1499
1500     TRACE("(%d)\n",hInstall);
1501
1502     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
1503     if( package)
1504     {
1505         handle = alloc_msihandle( &package->db->hdr );
1506         msiobj_release( &package->hdr );
1507     }
1508     else if ((remote_unk = msi_get_remote(hInstall)))
1509     {
1510         if (IUnknown_QueryInterface(remote_unk, &IID_IWineMsiRemotePackage,
1511                                         (LPVOID *)&remote_package) == S_OK)
1512         {
1513             IWineMsiRemotePackage_GetActiveDatabase(remote_package, &handle);
1514             IWineMsiRemotePackage_Release(remote_package);
1515         }
1516         else
1517         {
1518             WARN("remote handle %d is not a package\n", hInstall);
1519         }
1520         IUnknown_Release(remote_unk);
1521     }
1522
1523     return handle;
1524 }
1525
1526 INT MSI_ProcessMessage( MSIPACKAGE *package, INSTALLMESSAGE eMessageType,
1527                                MSIRECORD *record)
1528 {
1529     static const WCHAR szActionData[] =
1530         {'A','c','t','i','o','n','D','a','t','a',0};
1531     static const WCHAR szSetProgress[] =
1532         {'S','e','t','P','r','o','g','r','e','s','s',0};
1533     static const WCHAR szActionText[] =
1534         {'A','c','t','i','o','n','T','e','x','t',0};
1535     DWORD log_type = 0;
1536     LPWSTR message;
1537     DWORD sz;
1538     DWORD total_size = 0;
1539     INT i;
1540     INT rc;
1541     char *msg;
1542     int len;
1543
1544     TRACE("%x\n", eMessageType);
1545     rc = 0;
1546
1547     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ERROR)
1548         log_type |= INSTALLLOGMODE_ERROR;
1549     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_WARNING)
1550         log_type |= INSTALLLOGMODE_WARNING;
1551     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_USER)
1552         log_type |= INSTALLLOGMODE_USER;
1553     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_INFO)
1554         log_type |= INSTALLLOGMODE_INFO;
1555     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_COMMONDATA)
1556         log_type |= INSTALLLOGMODE_COMMONDATA;
1557     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONSTART)
1558         log_type |= INSTALLLOGMODE_ACTIONSTART;
1559     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONDATA)
1560         log_type |= INSTALLLOGMODE_ACTIONDATA;
1561     /* just a guess */
1562     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_PROGRESS)
1563         log_type |= 0x800;
1564
1565     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONSTART)
1566     {
1567         static const WCHAR template_s[]=
1568             {'A','c','t','i','o','n',' ','%','s',':',' ','%','s','.',' ',0};
1569         static const WCHAR format[] = 
1570             {'H','H','\'',':','\'','m','m','\'',':','\'','s','s',0};
1571         WCHAR timet[0x100];
1572         LPCWSTR action_text, action;
1573         LPWSTR deformatted = NULL;
1574
1575         GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, format, timet, 0x100);
1576
1577         action = MSI_RecordGetString(record, 1);
1578         action_text = MSI_RecordGetString(record, 2);
1579
1580         if (!action || !action_text)
1581             return IDOK;
1582
1583         deformat_string(package, action_text, &deformatted);
1584
1585         len = strlenW(timet) + strlenW(action) + strlenW(template_s);
1586         if (deformatted)
1587             len += strlenW(deformatted);
1588         message = msi_alloc(len*sizeof(WCHAR));
1589         sprintfW(message, template_s, timet, action);
1590         if (deformatted)
1591             strcatW(message, deformatted);
1592         msi_free(deformatted);
1593     }
1594     else
1595     {
1596         INT msg_field=1;
1597         message = msi_alloc(1*sizeof (WCHAR));
1598         message[0]=0;
1599         msg_field = MSI_RecordGetFieldCount(record);
1600         for (i = 1; i <= msg_field; i++)
1601         {
1602             LPWSTR tmp;
1603             WCHAR number[3];
1604             static const WCHAR format[] = { '%','i',':',' ',0};
1605             sz = 0;
1606             MSI_RecordGetStringW(record,i,NULL,&sz);
1607             sz+=4;
1608             total_size+=sz*sizeof(WCHAR);
1609             tmp = msi_alloc(sz*sizeof(WCHAR));
1610             message = msi_realloc(message,total_size*sizeof (WCHAR));
1611
1612             MSI_RecordGetStringW(record,i,tmp,&sz);
1613
1614             if (msg_field > 1)
1615             {
1616                 sprintfW(number,format,i);
1617                 strcatW(message,number);
1618             }
1619             strcatW(message,tmp);
1620             if (msg_field > 1)
1621                 strcatW(message, szSpace);
1622
1623             msi_free(tmp);
1624         }
1625     }
1626
1627     TRACE("%p %p %p %x %x %s\n", gUIHandlerA, gUIHandlerW, gUIHandlerRecord,
1628           gUIFilter, log_type, debugstr_w(message));
1629
1630     /* convert it to ASCII */
1631     len = WideCharToMultiByte( CP_ACP, 0, message, -1, NULL, 0, NULL, NULL );
1632     msg = msi_alloc( len );
1633     WideCharToMultiByte( CP_ACP, 0, message, -1, msg, len, NULL, NULL );
1634
1635     if (gUIHandlerW && (gUIFilter & log_type))
1636     {
1637         rc = gUIHandlerW( gUIContext, eMessageType, message );
1638     }
1639     else if (gUIHandlerA && (gUIFilter & log_type))
1640     {
1641         rc = gUIHandlerA( gUIContext, eMessageType, msg );
1642     }
1643     else if (gUIHandlerRecord && (gUIFilter & log_type))
1644     {
1645         MSIHANDLE rec = MsiCreateRecord( 1 );
1646         MsiRecordSetStringW( rec, 0, message );
1647         rc = gUIHandlerRecord( gUIContext, eMessageType, rec );
1648         MsiCloseHandle( rec );
1649     }
1650
1651     if ((!rc) && (gszLogFile[0]) && !((eMessageType & 0xff000000) ==
1652                                       INSTALLMESSAGE_PROGRESS))
1653     {
1654         DWORD write;
1655         HANDLE log_file = CreateFileW(gszLogFile,GENERIC_WRITE, 0, NULL,
1656                                   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1657
1658         if (log_file != INVALID_HANDLE_VALUE)
1659         {
1660             SetFilePointer(log_file,0, NULL, FILE_END);
1661             WriteFile(log_file,msg,strlen(msg),&write,NULL);
1662             WriteFile(log_file,"\n",1,&write,NULL);
1663             CloseHandle(log_file);
1664         }
1665     }
1666     msi_free( msg );
1667     msi_free( message );
1668
1669     switch (eMessageType & 0xff000000)
1670     {
1671     case INSTALLMESSAGE_ACTIONDATA:
1672         /* FIXME: format record here instead of in ui_actiondata to get the
1673          * correct action data for external scripts */
1674         ControlEvent_FireSubscribedEvent(package, szActionData, record);
1675         break;
1676     case INSTALLMESSAGE_ACTIONSTART:
1677     {
1678         MSIRECORD *uirow;
1679         LPWSTR deformated;
1680         LPCWSTR action_text = MSI_RecordGetString(record, 2);
1681
1682         deformat_string(package, action_text, &deformated);
1683         uirow = MSI_CreateRecord(1);
1684         MSI_RecordSetStringW(uirow, 1, deformated);
1685         TRACE("INSTALLMESSAGE_ACTIONSTART: %s\n", debugstr_w(deformated));
1686         msi_free(deformated);
1687
1688         ControlEvent_FireSubscribedEvent(package, szActionText, uirow);
1689
1690         msiobj_release(&uirow->hdr);
1691         break;
1692     }
1693     case INSTALLMESSAGE_PROGRESS:
1694         ControlEvent_FireSubscribedEvent(package, szSetProgress, record);
1695         break;
1696     }
1697
1698     return ERROR_SUCCESS;
1699 }
1700
1701 INT WINAPI MsiProcessMessage( MSIHANDLE hInstall, INSTALLMESSAGE eMessageType,
1702                               MSIHANDLE hRecord)
1703 {
1704     UINT ret = ERROR_INVALID_HANDLE;
1705     MSIPACKAGE *package = NULL;
1706     MSIRECORD *record = NULL;
1707
1708     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE );
1709     if( !package )
1710     {
1711         HRESULT hr;
1712         IWineMsiRemotePackage *remote_package;
1713
1714         remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
1715         if (!remote_package)
1716             return ERROR_INVALID_HANDLE;
1717
1718         hr = IWineMsiRemotePackage_ProcessMessage( remote_package, eMessageType, hRecord );
1719
1720         IWineMsiRemotePackage_Release( remote_package );
1721
1722         if (FAILED(hr))
1723         {
1724             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
1725                 return HRESULT_CODE(hr);
1726
1727             return ERROR_FUNCTION_FAILED;
1728         }
1729
1730         return ERROR_SUCCESS;
1731     }
1732
1733     record = msihandle2msiinfo( hRecord, MSIHANDLETYPE_RECORD );
1734     if( !record )
1735         goto out;
1736
1737     ret = MSI_ProcessMessage( package, eMessageType, record );
1738
1739 out:
1740     msiobj_release( &package->hdr );
1741     if( record )
1742         msiobj_release( &record->hdr );
1743
1744     return ret;
1745 }
1746
1747 /* property code */
1748
1749 UINT WINAPI MsiSetPropertyA( MSIHANDLE hInstall, LPCSTR szName, LPCSTR szValue )
1750 {
1751     LPWSTR szwName = NULL, szwValue = NULL;
1752     UINT r = ERROR_OUTOFMEMORY;
1753
1754     szwName = strdupAtoW( szName );
1755     if( szName && !szwName )
1756         goto end;
1757
1758     szwValue = strdupAtoW( szValue );
1759     if( szValue && !szwValue )
1760         goto end;
1761
1762     r = MsiSetPropertyW( hInstall, szwName, szwValue);
1763
1764 end:
1765     msi_free( szwName );
1766     msi_free( szwValue );
1767
1768     return r;
1769 }
1770
1771 void msi_reset_folders( MSIPACKAGE *package, BOOL source )
1772 {
1773     MSIFOLDER *folder;
1774
1775     LIST_FOR_EACH_ENTRY( folder, &package->folders, MSIFOLDER, entry )
1776     {
1777         if ( source )
1778         {
1779             msi_free( folder->ResolvedSource );
1780             folder->ResolvedSource = NULL;
1781         }
1782         else
1783         {
1784             msi_free( folder->ResolvedTarget );
1785             folder->ResolvedTarget = NULL;
1786         }
1787     }
1788 }
1789
1790 UINT msi_set_property( MSIDATABASE *db, LPCWSTR szName, LPCWSTR szValue )
1791 {
1792     MSIQUERY *view;
1793     MSIRECORD *row = NULL;
1794     UINT rc;
1795     DWORD sz = 0;
1796     WCHAR Query[1024];
1797
1798     static const WCHAR Insert[] = {
1799         'I','N','S','E','R','T',' ','i','n','t','o',' ',
1800         '`','_','P','r','o','p','e','r','t','y','`',' ','(',
1801         '`','_','P','r','o','p','e','r','t','y','`',',',
1802         '`','V','a','l','u','e','`',')',' ','V','A','L','U','E','S'
1803         ,' ','(','?',',','?',')',0};
1804     static const WCHAR Update[] = {
1805         'U','P','D','A','T','E',' ','`','_','P','r','o','p','e','r','t','y','`',
1806         ' ','s','e','t',' ','`','V','a','l','u','e','`',' ','=',' ','?',' ',
1807         'w','h','e','r','e',' ','`','_','P','r','o','p','e','r','t','y','`',
1808         ' ','=',' ','\'','%','s','\'',0};
1809     static const WCHAR Delete[] = {
1810         'D','E','L','E','T','E',' ','F','R','O','M',' ',
1811         '`','_','P','r','o','p','e','r','t','y','`',' ','W','H','E','R','E',' ',
1812         '`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','\'','%','s','\'',0};
1813
1814     TRACE("%p %s %s\n", db, debugstr_w(szName), debugstr_w(szValue));
1815
1816     if (!szName)
1817         return ERROR_INVALID_PARAMETER;
1818
1819     /* this one is weird... */
1820     if (!szName[0])
1821         return szValue ? ERROR_FUNCTION_FAILED : ERROR_SUCCESS;
1822
1823     rc = msi_get_property(db, szName, 0, &sz);
1824     if (!szValue || !*szValue)
1825     {
1826         sprintfW(Query, Delete, szName);
1827     }
1828     else if (rc == ERROR_MORE_DATA || rc == ERROR_SUCCESS)
1829     {
1830         sprintfW(Query, Update, szName);
1831
1832         row = MSI_CreateRecord(1);
1833         MSI_RecordSetStringW(row, 1, szValue);
1834     }
1835     else
1836     {
1837         strcpyW(Query, Insert);
1838
1839         row = MSI_CreateRecord(2);
1840         MSI_RecordSetStringW(row, 1, szName);
1841         MSI_RecordSetStringW(row, 2, szValue);
1842     }
1843
1844     rc = MSI_DatabaseOpenViewW(db, Query, &view);
1845     if (rc == ERROR_SUCCESS)
1846     {
1847         rc = MSI_ViewExecute(view, row);
1848         MSI_ViewClose(view);
1849         msiobj_release(&view->hdr);
1850     }
1851
1852     if (row)
1853       msiobj_release(&row->hdr);
1854
1855     return rc;
1856 }
1857
1858 UINT WINAPI MsiSetPropertyW( MSIHANDLE hInstall, LPCWSTR szName, LPCWSTR szValue)
1859 {
1860     MSIPACKAGE *package;
1861     UINT ret;
1862
1863     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
1864     if( !package )
1865     {
1866         HRESULT hr;
1867         BSTR name = NULL, value = NULL;
1868         IWineMsiRemotePackage *remote_package;
1869
1870         remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
1871         if (!remote_package)
1872             return ERROR_INVALID_HANDLE;
1873
1874         name = SysAllocString( szName );
1875         value = SysAllocString( szValue );
1876         if ((!name && szName) || (!value && szValue))
1877         {
1878             SysFreeString( name );
1879             SysFreeString( value );
1880             IWineMsiRemotePackage_Release( remote_package );
1881             return ERROR_OUTOFMEMORY;
1882         }
1883
1884         hr = IWineMsiRemotePackage_SetProperty( remote_package, name, value );
1885
1886         SysFreeString( name );
1887         SysFreeString( value );
1888         IWineMsiRemotePackage_Release( remote_package );
1889
1890         if (FAILED(hr))
1891         {
1892             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
1893                 return HRESULT_CODE(hr);
1894
1895             return ERROR_FUNCTION_FAILED;
1896         }
1897
1898         return ERROR_SUCCESS;
1899     }
1900
1901     ret = msi_set_property( package->db, szName, szValue );
1902     if (ret == ERROR_SUCCESS && !strcmpW( szName, cszSourceDir ))
1903         msi_reset_folders( package, TRUE );
1904
1905     msiobj_release( &package->hdr );
1906     return ret;
1907 }
1908
1909 static MSIRECORD *msi_get_property_row( MSIDATABASE *db, LPCWSTR name )
1910 {
1911     MSIQUERY *view;
1912     MSIRECORD *rec, *row = NULL;
1913     UINT r;
1914
1915     static const WCHAR query[]= {
1916         'S','E','L','E','C','T',' ','`','V','a','l','u','e','`',' ',
1917         'F','R','O','M',' ' ,'`','_','P','r','o','p','e','r','t','y','`',
1918         ' ','W','H','E','R','E',' ' ,'`','_','P','r','o','p','e','r','t','y','`',
1919         '=','?',0};
1920
1921     if (!name || !*name)
1922         return NULL;
1923
1924     rec = MSI_CreateRecord(1);
1925     if (!rec)
1926         return NULL;
1927
1928     MSI_RecordSetStringW(rec, 1, name);
1929
1930     r = MSI_DatabaseOpenViewW(db, query, &view);
1931     if (r == ERROR_SUCCESS)
1932     {
1933         MSI_ViewExecute(view, rec);
1934         MSI_ViewFetch(view, &row);
1935         MSI_ViewClose(view);
1936         msiobj_release(&view->hdr);
1937     }
1938
1939     msiobj_release(&rec->hdr);
1940     return row;
1941 }
1942
1943 /* internal function, not compatible with MsiGetPropertyW */
1944 UINT msi_get_property( MSIDATABASE *db, LPCWSTR szName,
1945                        LPWSTR szValueBuf, LPDWORD pchValueBuf )
1946 {
1947     MSIRECORD *row;
1948     UINT rc = ERROR_FUNCTION_FAILED;
1949
1950     row = msi_get_property_row( db, szName );
1951
1952     if (*pchValueBuf > 0)
1953         szValueBuf[0] = 0;
1954
1955     if (row)
1956     {
1957         rc = MSI_RecordGetStringW(row, 1, szValueBuf, pchValueBuf);
1958         msiobj_release(&row->hdr);
1959     }
1960
1961     if (rc == ERROR_SUCCESS)
1962         TRACE("returning %s for property %s\n", debugstr_w(szValueBuf),
1963             debugstr_w(szName));
1964     else if (rc == ERROR_MORE_DATA)
1965         TRACE("need %d sized buffer for %s\n", *pchValueBuf,
1966             debugstr_w(szName));
1967     else
1968     {
1969         *pchValueBuf = 0;
1970         TRACE("property %s not found\n", debugstr_w(szName));
1971     }
1972
1973     return rc;
1974 }
1975
1976 LPWSTR msi_dup_property(MSIDATABASE *db, LPCWSTR prop)
1977 {
1978     DWORD sz = 0;
1979     LPWSTR str;
1980     UINT r;
1981
1982     r = msi_get_property(db, prop, NULL, &sz);
1983     if (r != ERROR_SUCCESS && r != ERROR_MORE_DATA)
1984         return NULL;
1985
1986     sz++;
1987     str = msi_alloc(sz * sizeof(WCHAR));
1988     r = msi_get_property(db, prop, str, &sz);
1989     if (r != ERROR_SUCCESS)
1990     {
1991         msi_free(str);
1992         str = NULL;
1993     }
1994
1995     return str;
1996 }
1997
1998 int msi_get_property_int( MSIDATABASE *db, LPCWSTR prop, int def )
1999 {
2000     LPWSTR str = msi_dup_property( db, prop );
2001     int val = str ? atoiW(str) : def;
2002     msi_free(str);
2003     return val;
2004 }
2005
2006 static UINT MSI_GetProperty( MSIHANDLE handle, LPCWSTR name,
2007                              awstring *szValueBuf, LPDWORD pchValueBuf )
2008 {
2009     MSIPACKAGE *package;
2010     MSIRECORD *row = NULL;
2011     UINT r = ERROR_FUNCTION_FAILED;
2012     LPCWSTR val = NULL;
2013
2014     TRACE("%u %s %p %p\n", handle, debugstr_w(name),
2015           szValueBuf->str.w, pchValueBuf );
2016
2017     if (!name)
2018         return ERROR_INVALID_PARAMETER;
2019
2020     package = msihandle2msiinfo( handle, MSIHANDLETYPE_PACKAGE );
2021     if (!package)
2022     {
2023         HRESULT hr;
2024         IWineMsiRemotePackage *remote_package;
2025         LPWSTR value = NULL;
2026         BSTR bname;
2027         DWORD len;
2028
2029         remote_package = (IWineMsiRemotePackage *)msi_get_remote( handle );
2030         if (!remote_package)
2031             return ERROR_INVALID_HANDLE;
2032
2033         bname = SysAllocString( name );
2034         if (!bname)
2035         {
2036             IWineMsiRemotePackage_Release( remote_package );
2037             return ERROR_OUTOFMEMORY;
2038         }
2039
2040         len = 0;
2041         hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, NULL, &len );
2042         if (FAILED(hr))
2043             goto done;
2044
2045         len++;
2046         value = msi_alloc(len * sizeof(WCHAR));
2047         if (!value)
2048         {
2049             r = ERROR_OUTOFMEMORY;
2050             goto done;
2051         }
2052
2053         hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, (BSTR *)value, &len );
2054         if (FAILED(hr))
2055             goto done;
2056
2057         r = msi_strcpy_to_awstring( value, szValueBuf, pchValueBuf );
2058
2059         /* Bug required by Adobe installers */
2060         if (!szValueBuf->unicode && !szValueBuf->str.a)
2061             *pchValueBuf *= sizeof(WCHAR);
2062
2063 done:
2064         IWineMsiRemotePackage_Release(remote_package);
2065         SysFreeString(bname);
2066         msi_free(value);
2067
2068         if (FAILED(hr))
2069         {
2070             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
2071                 return HRESULT_CODE(hr);
2072
2073             return ERROR_FUNCTION_FAILED;
2074         }
2075
2076         return r;
2077     }
2078
2079     row = msi_get_property_row( package->db, name );
2080     if (row)
2081         val = MSI_RecordGetString( row, 1 );
2082
2083     if (!val)
2084         val = szEmpty;
2085
2086     r = msi_strcpy_to_awstring( val, szValueBuf, pchValueBuf );
2087
2088     if (row)
2089         msiobj_release( &row->hdr );
2090     msiobj_release( &package->hdr );
2091
2092     return r;
2093 }
2094
2095 UINT WINAPI MsiGetPropertyA( MSIHANDLE hInstall, LPCSTR szName,
2096                              LPSTR szValueBuf, LPDWORD pchValueBuf )
2097 {
2098     awstring val;
2099     LPWSTR name;
2100     UINT r;
2101
2102     val.unicode = FALSE;
2103     val.str.a = szValueBuf;
2104
2105     name = strdupAtoW( szName );
2106     if (szName && !name)
2107         return ERROR_OUTOFMEMORY;
2108
2109     r = MSI_GetProperty( hInstall, name, &val, pchValueBuf );
2110     msi_free( name );
2111     return r;
2112 }
2113
2114 UINT WINAPI MsiGetPropertyW( MSIHANDLE hInstall, LPCWSTR szName,
2115                              LPWSTR szValueBuf, LPDWORD pchValueBuf )
2116 {
2117     awstring val;
2118
2119     val.unicode = TRUE;
2120     val.str.w = szValueBuf;
2121
2122     return MSI_GetProperty( hInstall, szName, &val, pchValueBuf );
2123 }
2124
2125 typedef struct _msi_remote_package_impl {
2126     const IWineMsiRemotePackageVtbl *lpVtbl;
2127     MSIHANDLE package;
2128     LONG refs;
2129 } msi_remote_package_impl;
2130
2131 static inline msi_remote_package_impl* mrp_from_IWineMsiRemotePackage( IWineMsiRemotePackage* iface )
2132 {
2133     return (msi_remote_package_impl*) iface;
2134 }
2135
2136 static HRESULT WINAPI mrp_QueryInterface( IWineMsiRemotePackage *iface,
2137                 REFIID riid,LPVOID *ppobj)
2138 {
2139     if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2140         IsEqualCLSID( riid, &IID_IWineMsiRemotePackage ) )
2141     {
2142         IUnknown_AddRef( iface );
2143         *ppobj = iface;
2144         return S_OK;
2145     }
2146
2147     return E_NOINTERFACE;
2148 }
2149
2150 static ULONG WINAPI mrp_AddRef( IWineMsiRemotePackage *iface )
2151 {
2152     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2153
2154     return InterlockedIncrement( &This->refs );
2155 }
2156
2157 static ULONG WINAPI mrp_Release( IWineMsiRemotePackage *iface )
2158 {
2159     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2160     ULONG r;
2161
2162     r = InterlockedDecrement( &This->refs );
2163     if (r == 0)
2164     {
2165         MsiCloseHandle( This->package );
2166         msi_free( This );
2167     }
2168     return r;
2169 }
2170
2171 static HRESULT WINAPI mrp_SetMsiHandle( IWineMsiRemotePackage *iface, MSIHANDLE handle )
2172 {
2173     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2174     This->package = handle;
2175     return S_OK;
2176 }
2177
2178 static HRESULT WINAPI mrp_GetActiveDatabase( IWineMsiRemotePackage *iface, MSIHANDLE *handle )
2179 {
2180     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2181     IWineMsiRemoteDatabase *rdb = NULL;
2182     HRESULT hr;
2183     MSIHANDLE hdb;
2184
2185     hr = create_msi_remote_database( NULL, (LPVOID *)&rdb );
2186     if (FAILED(hr) || !rdb)
2187     {
2188         ERR("Failed to create remote database\n");
2189         return hr;
2190     }
2191
2192     hdb = MsiGetActiveDatabase(This->package);
2193
2194     hr = IWineMsiRemoteDatabase_SetMsiHandle( rdb, hdb );
2195     if (FAILED(hr))
2196     {
2197         ERR("Failed to set the database handle\n");
2198         return hr;
2199     }
2200
2201     *handle = alloc_msi_remote_handle( (IUnknown *)rdb );
2202     return S_OK;
2203 }
2204
2205 static HRESULT WINAPI mrp_GetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR *value, DWORD *size )
2206 {
2207     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2208     UINT r;
2209
2210     r = MsiGetPropertyW(This->package, (LPWSTR)property, (LPWSTR)value, size);
2211     if (r != ERROR_SUCCESS)
2212         return HRESULT_FROM_WIN32(r);
2213
2214     return S_OK;
2215 }
2216
2217 static HRESULT WINAPI mrp_SetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR value )
2218 {
2219     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2220     UINT r = MsiSetPropertyW(This->package, property, value);
2221     return HRESULT_FROM_WIN32(r);
2222 }
2223
2224 static HRESULT WINAPI mrp_ProcessMessage( IWineMsiRemotePackage *iface, INSTALLMESSAGE message, MSIHANDLE record )
2225 {
2226     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2227     UINT r = MsiProcessMessage(This->package, message, record);
2228     return HRESULT_FROM_WIN32(r);
2229 }
2230
2231 static HRESULT WINAPI mrp_DoAction( IWineMsiRemotePackage *iface, BSTR action )
2232 {
2233     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2234     UINT r = MsiDoActionW(This->package, action);
2235     return HRESULT_FROM_WIN32(r);
2236 }
2237
2238 static HRESULT WINAPI mrp_Sequence( IWineMsiRemotePackage *iface, BSTR table, int sequence )
2239 {
2240     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2241     UINT r = MsiSequenceW(This->package, table, sequence);
2242     return HRESULT_FROM_WIN32(r);
2243 }
2244
2245 static HRESULT WINAPI mrp_GetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR *value, DWORD *size )
2246 {
2247     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2248     UINT r = MsiGetTargetPathW(This->package, (LPWSTR)folder, (LPWSTR)value, size);
2249     return HRESULT_FROM_WIN32(r);
2250 }
2251
2252 static HRESULT WINAPI mrp_SetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value)
2253 {
2254     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2255     UINT r = MsiSetTargetPathW(This->package, folder, value);
2256     return HRESULT_FROM_WIN32(r);
2257 }
2258
2259 static HRESULT WINAPI mrp_GetSourcePath( IWineMsiRemotePackage *iface, BSTR folder, BSTR *value, DWORD *size )
2260 {
2261     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2262     UINT r = MsiGetSourcePathW(This->package, (LPWSTR)folder, (LPWSTR)value, size);
2263     return HRESULT_FROM_WIN32(r);
2264 }
2265
2266 static HRESULT WINAPI mrp_GetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL *ret )
2267 {
2268     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2269     *ret = MsiGetMode(This->package, mode);
2270     return S_OK;
2271 }
2272
2273 static HRESULT WINAPI mrp_SetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL state )
2274 {
2275     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2276     UINT r = MsiSetMode(This->package, mode, state);
2277     return HRESULT_FROM_WIN32(r);
2278 }
2279
2280 static HRESULT WINAPI mrp_GetFeatureState( IWineMsiRemotePackage *iface, BSTR feature,
2281                                     INSTALLSTATE *installed, INSTALLSTATE *action )
2282 {
2283     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2284     UINT r = MsiGetFeatureStateW(This->package, feature, installed, action);
2285     return HRESULT_FROM_WIN32(r);
2286 }
2287
2288 static HRESULT WINAPI mrp_SetFeatureState( IWineMsiRemotePackage *iface, BSTR feature, INSTALLSTATE state )
2289 {
2290     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2291     UINT r = MsiSetFeatureStateW(This->package, feature, state);
2292     return HRESULT_FROM_WIN32(r);
2293 }
2294
2295 static HRESULT WINAPI mrp_GetComponentState( IWineMsiRemotePackage *iface, BSTR component,
2296                                       INSTALLSTATE *installed, INSTALLSTATE *action )
2297 {
2298     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2299     UINT r = MsiGetComponentStateW(This->package, component, installed, action);
2300     return HRESULT_FROM_WIN32(r);
2301 }
2302
2303 static HRESULT WINAPI mrp_SetComponentState( IWineMsiRemotePackage *iface, BSTR component, INSTALLSTATE state )
2304 {
2305     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2306     UINT r = MsiSetComponentStateW(This->package, component, state);
2307     return HRESULT_FROM_WIN32(r);
2308 }
2309
2310 static HRESULT WINAPI mrp_GetLanguage( IWineMsiRemotePackage *iface, LANGID *language )
2311 {
2312     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2313     *language = MsiGetLanguage(This->package);
2314     return S_OK;
2315 }
2316
2317 static HRESULT WINAPI mrp_SetInstallLevel( IWineMsiRemotePackage *iface, int level )
2318 {
2319     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2320     UINT r = MsiSetInstallLevel(This->package, level);
2321     return HRESULT_FROM_WIN32(r);
2322 }
2323
2324 static HRESULT WINAPI mrp_FormatRecord( IWineMsiRemotePackage *iface, MSIHANDLE record,
2325                                         BSTR *value)
2326 {
2327     DWORD size = 0;
2328     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2329     UINT r = MsiFormatRecordW(This->package, record, NULL, &size);
2330     if (r == ERROR_SUCCESS)
2331     {
2332         *value = SysAllocStringLen(NULL, size);
2333         if (!*value)
2334             return E_OUTOFMEMORY;
2335         size++;
2336         r = MsiFormatRecordW(This->package, record, *value, &size);
2337     }
2338     return HRESULT_FROM_WIN32(r);
2339 }
2340
2341 static HRESULT WINAPI mrp_EvaluateCondition( IWineMsiRemotePackage *iface, BSTR condition )
2342 {
2343     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2344     UINT r = MsiEvaluateConditionW(This->package, condition);
2345     return HRESULT_FROM_WIN32(r);
2346 }
2347
2348 static HRESULT WINAPI mrp_GetFeatureCost( IWineMsiRemotePackage *iface, BSTR feature,
2349                                           INT cost_tree, INSTALLSTATE state, INT *cost )
2350 {
2351     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2352     UINT r = MsiGetFeatureCostW(This->package, feature, cost_tree, state, cost);
2353     return HRESULT_FROM_WIN32(r);
2354 }
2355
2356 static const IWineMsiRemotePackageVtbl msi_remote_package_vtbl =
2357 {
2358     mrp_QueryInterface,
2359     mrp_AddRef,
2360     mrp_Release,
2361     mrp_SetMsiHandle,
2362     mrp_GetActiveDatabase,
2363     mrp_GetProperty,
2364     mrp_SetProperty,
2365     mrp_ProcessMessage,
2366     mrp_DoAction,
2367     mrp_Sequence,
2368     mrp_GetTargetPath,
2369     mrp_SetTargetPath,
2370     mrp_GetSourcePath,
2371     mrp_GetMode,
2372     mrp_SetMode,
2373     mrp_GetFeatureState,
2374     mrp_SetFeatureState,
2375     mrp_GetComponentState,
2376     mrp_SetComponentState,
2377     mrp_GetLanguage,
2378     mrp_SetInstallLevel,
2379     mrp_FormatRecord,
2380     mrp_EvaluateCondition,
2381     mrp_GetFeatureCost,
2382 };
2383
2384 HRESULT create_msi_remote_package( IUnknown *pOuter, LPVOID *ppObj )
2385 {
2386     msi_remote_package_impl* This;
2387
2388     This = msi_alloc( sizeof *This );
2389     if (!This)
2390         return E_OUTOFMEMORY;
2391
2392     This->lpVtbl = &msi_remote_package_vtbl;
2393     This->package = 0;
2394     This->refs = 1;
2395
2396     *ppObj = This;
2397
2398     return S_OK;
2399 }
2400
2401 UINT msi_package_add_info(MSIPACKAGE *package, DWORD context, DWORD options,
2402                           LPCWSTR property, LPWSTR value)
2403 {
2404     MSISOURCELISTINFO *info;
2405
2406     info = msi_alloc(sizeof(MSISOURCELISTINFO));
2407     if (!info)
2408         return ERROR_OUTOFMEMORY;
2409
2410     info->context = context;
2411     info->options = options;
2412     info->property = property;
2413     info->value = strdupW(value);
2414     list_add_head(&package->sourcelist_info, &info->entry);
2415
2416     return ERROR_SUCCESS;
2417 }
2418
2419 UINT msi_package_add_media_disk(MSIPACKAGE *package, DWORD context, DWORD options,
2420                                 DWORD disk_id, LPWSTR volume_label, LPWSTR disk_prompt)
2421 {
2422     MSIMEDIADISK *disk;
2423
2424     disk = msi_alloc(sizeof(MSIMEDIADISK));
2425     if (!disk)
2426         return ERROR_OUTOFMEMORY;
2427
2428     disk->context = context;
2429     disk->options = options;
2430     disk->disk_id = disk_id;
2431     disk->volume_label = strdupW(volume_label);
2432     disk->disk_prompt = strdupW(disk_prompt);
2433     list_add_head(&package->sourcelist_media, &disk->entry);
2434
2435     return ERROR_SUCCESS;
2436 }