mcicda: Rework MCI notification system.
[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         if ( error == ERROR_FILE_NOT_FOUND )
1123             ERR("can't find %s\n", debugstr_w(szPackage));
1124         else
1125             ERR("failed to copy package %s to %s (%u)\n", debugstr_w(szPackage), debugstr_w(filename), error);
1126         DeleteFileW( filename );
1127         return error;
1128     }
1129
1130     return ERROR_SUCCESS;
1131 }
1132
1133 UINT msi_download_file( LPCWSTR szUrl, LPWSTR filename )
1134 {
1135     LPINTERNET_CACHE_ENTRY_INFOW cache_entry;
1136     DWORD size = 0;
1137     HRESULT hr;
1138
1139     /* call will always fail, becase size is 0,
1140      * but will return ERROR_FILE_NOT_FOUND first
1141      * if the file doesn't exist
1142      */
1143     GetUrlCacheEntryInfoW( szUrl, NULL, &size );
1144     if ( GetLastError() != ERROR_FILE_NOT_FOUND )
1145     {
1146         cache_entry = msi_alloc( size );
1147         if ( !GetUrlCacheEntryInfoW( szUrl, cache_entry, &size ) )
1148         {
1149             UINT error = GetLastError();
1150             msi_free( cache_entry );
1151             return error;
1152         }
1153
1154         lstrcpyW( filename, cache_entry->lpszLocalFileName );
1155         msi_free( cache_entry );
1156         return ERROR_SUCCESS;
1157     }
1158
1159     hr = URLDownloadToCacheFileW( NULL, szUrl, filename, MAX_PATH, 0, NULL );
1160     if ( FAILED(hr) )
1161     {
1162         WARN("failed to download %s to cache file\n", debugstr_w(szUrl));
1163         return ERROR_FUNCTION_FAILED;
1164     }
1165
1166     return ERROR_SUCCESS;
1167 }
1168
1169 UINT msi_get_local_package_name( LPWSTR path, LPCWSTR suffix )
1170 {
1171     static const WCHAR szInstaller[] = {
1172         '\\','I','n','s','t','a','l','l','e','r','\\',0};
1173     static const WCHAR fmt[] = {'%','x',0};
1174     DWORD time, len, i, offset;
1175     HANDLE handle;
1176
1177     time = GetTickCount();
1178     GetWindowsDirectoryW( path, MAX_PATH );
1179     strcatW( path, szInstaller );
1180     CreateDirectoryW( path, NULL );
1181
1182     len = strlenW(path);
1183     for (i = 0; i < 0x10000; i++)
1184     {
1185         offset = snprintfW( path + len, MAX_PATH - len, fmt, (time + i) & 0xffff );
1186         memcpy( path + len + offset, suffix, (strlenW( suffix ) + 1) * sizeof(WCHAR) );
1187         handle = CreateFileW( path, GENERIC_WRITE, 0, NULL,
1188                               CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
1189         if (handle != INVALID_HANDLE_VALUE)
1190         {
1191             CloseHandle(handle);
1192             break;
1193         }
1194         if (GetLastError() != ERROR_FILE_EXISTS &&
1195             GetLastError() != ERROR_SHARING_VIOLATION)
1196             return ERROR_FUNCTION_FAILED;
1197     }
1198
1199     return ERROR_SUCCESS;
1200 }
1201
1202 static UINT apply_registered_patch( MSIPACKAGE *package, LPCWSTR patch_code )
1203 {
1204     UINT r;
1205     DWORD len;
1206     WCHAR patch_file[MAX_PATH];
1207     MSIDATABASE *patch_db;
1208     MSIPATCHINFO *patch_info;
1209     MSISUMMARYINFO *si;
1210
1211     len = sizeof(patch_file) / sizeof(WCHAR);
1212     r = MsiGetPatchInfoExW( patch_code, package->ProductCode, NULL, package->Context,
1213                             INSTALLPROPERTY_LOCALPACKAGEW, patch_file, &len );
1214     if (r != ERROR_SUCCESS)
1215     {
1216         ERR("failed to get patch filename %u\n", r);
1217         return r;
1218     }
1219
1220     r = MSI_OpenDatabaseW( patch_file, MSIDBOPEN_READONLY + MSIDBOPEN_PATCHFILE, &patch_db );
1221     if (r != ERROR_SUCCESS)
1222     {
1223         ERR("failed to open patch database %s\n", debugstr_w( patch_file ));
1224         return r;
1225     }
1226
1227     si = MSI_GetSummaryInformationW( patch_db->storage, 0 );
1228     if (!si)
1229     {
1230         msiobj_release( &patch_db->hdr );
1231         return ERROR_FUNCTION_FAILED;
1232     }
1233
1234     r = msi_parse_patch_summary( si, &patch_info );
1235     msiobj_release( &si->hdr );
1236     if (r != ERROR_SUCCESS)
1237     {
1238         ERR("failed to parse patch summary %u\n", r);
1239         msiobj_release( &patch_db->hdr );
1240         return r;
1241     }
1242
1243     patch_info->localfile = strdupW( patch_file );
1244     if (!patch_info->localfile)
1245     {
1246         msiobj_release( &patch_db->hdr );
1247         return ERROR_OUTOFMEMORY;
1248     }
1249
1250     r = msi_apply_patch_db( package, patch_db, patch_info );
1251     msiobj_release( &patch_db->hdr );
1252     if (r != ERROR_SUCCESS)
1253     {
1254         ERR("failed to apply patch %u\n", r);
1255         msi_free( patch_info->patchcode );
1256         msi_free( patch_info->transforms );
1257         msi_free( patch_info->localfile );
1258         msi_free( patch_info );
1259     }
1260     return r;
1261 }
1262
1263 UINT MSI_OpenPackageW(LPCWSTR szPackage, MSIPACKAGE **pPackage)
1264 {
1265     static const WCHAR Database[] = {'D','A','T','A','B','A','S','E',0};
1266     static const WCHAR dotmsi[] = {'.','m','s','i',0};
1267     MSIDATABASE *db = NULL;
1268     MSIPACKAGE *package;
1269     MSIHANDLE handle;
1270     LPWSTR ptr, base_url = NULL;
1271     UINT r;
1272     WCHAR temppath[MAX_PATH], localfile[MAX_PATH], cachefile[MAX_PATH];
1273     LPCWSTR file = szPackage;
1274     DWORD index = 0;
1275
1276     TRACE("%s %p\n", debugstr_w(szPackage), pPackage);
1277
1278     if( szPackage[0] == '#' )
1279     {
1280         handle = atoiW(&szPackage[1]);
1281         db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1282         if( !db )
1283         {
1284             IWineMsiRemoteDatabase *remote_database;
1285
1286             remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1287             if ( !remote_database )
1288                 return ERROR_INVALID_HANDLE;
1289
1290             IWineMsiRemoteDatabase_Release( remote_database );
1291             WARN("MsiOpenPackage not allowed during a custom action!\n");
1292
1293             return ERROR_FUNCTION_FAILED;
1294         }
1295     }
1296     else
1297     {
1298         if ( UrlIsW( szPackage, URLIS_URL ) )
1299         {
1300             r = msi_download_file( szPackage, cachefile );
1301             if ( r != ERROR_SUCCESS )
1302                 return r;
1303
1304             r = copy_package_to_temp( cachefile, temppath );
1305             if ( r != ERROR_SUCCESS )
1306                 return r;
1307
1308             file = temppath;
1309
1310             base_url = strdupW( szPackage );
1311             if ( !base_url )
1312                 return ERROR_OUTOFMEMORY;
1313
1314             ptr = strrchrW( base_url, '/' );
1315             if (ptr) *(ptr + 1) = '\0';
1316         }
1317         else
1318         {
1319             r = copy_package_to_temp( szPackage, temppath );
1320             if ( r != ERROR_SUCCESS )
1321                 return r;
1322
1323             file = temppath;
1324         }
1325
1326         r = msi_get_local_package_name( localfile, dotmsi );
1327         if (r != ERROR_SUCCESS)
1328             return r;
1329
1330         TRACE("Copying to local package %s\n", debugstr_w(localfile));
1331
1332         if (!CopyFileW( file, localfile, FALSE ))
1333         {
1334             ERR("Unable to copy package (%s -> %s) (error %u)\n",
1335                 debugstr_w(file), debugstr_w(localfile), GetLastError());
1336             return GetLastError();
1337         }
1338
1339         TRACE("Opening relocated package %s\n", debugstr_w( file ));
1340
1341         /* transforms that add binary streams require that we open the database
1342          * read/write, which is safe because we always create a copy that is thrown
1343          * away when we're done.
1344          */
1345         r = MSI_OpenDatabaseW( file, MSIDBOPEN_DIRECT, &db );
1346         if( r != ERROR_SUCCESS )
1347         {
1348             if (file != szPackage)
1349                 DeleteFileW( file );
1350
1351             if (GetFileAttributesW(szPackage) == INVALID_FILE_ATTRIBUTES)
1352                 return ERROR_FILE_NOT_FOUND;
1353
1354             return r;
1355         }
1356
1357         db->localfile = strdupW( localfile );
1358     }
1359
1360     package = MSI_CreatePackage( db, base_url );
1361     msi_free( base_url );
1362     msiobj_release( &db->hdr );
1363     if( !package )
1364     {
1365         if (file != szPackage)
1366             DeleteFileW( file );
1367
1368         return ERROR_INSTALL_PACKAGE_INVALID;
1369     }
1370
1371     if( file != szPackage )
1372         track_tempfile( package, file );
1373
1374     msi_set_property( package->db, Database, db->path );
1375
1376     if( UrlIsW( szPackage, URLIS_URL ) )
1377         msi_set_property( package->db, szOriginalDatabase, szPackage );
1378     else if( szPackage[0] == '#' )
1379         msi_set_property( package->db, szOriginalDatabase, db->path );
1380     else
1381     {
1382         WCHAR fullpath[MAX_PATH];
1383
1384         GetFullPathNameW( szPackage, MAX_PATH, fullpath, NULL );
1385         msi_set_property( package->db, szOriginalDatabase, fullpath );
1386     }
1387
1388     msi_set_context( package );
1389
1390     while (1)
1391     {
1392         WCHAR patch_code[GUID_SIZE];
1393         r = MsiEnumPatchesExW( package->ProductCode, NULL, package->Context,
1394                                MSIPATCHSTATE_APPLIED, index, patch_code, NULL, NULL, NULL, NULL );
1395         if (r != ERROR_SUCCESS)
1396             break;
1397
1398         TRACE("found registered patch %s\n", debugstr_w(patch_code));
1399
1400         r = apply_registered_patch( package, patch_code );
1401         if (r != ERROR_SUCCESS)
1402         {
1403             ERR("registered patch failed to apply %u\n", r);
1404             MSI_FreePackage( (MSIOBJECTHDR *)package );
1405             return r;
1406         }
1407
1408         index++;
1409     }
1410
1411     if (index)
1412     {
1413         msi_clone_properties( package );
1414         msi_adjust_allusers_property( package );
1415     }
1416
1417     *pPackage = package;
1418     return ERROR_SUCCESS;
1419 }
1420
1421 UINT WINAPI MsiOpenPackageExW(LPCWSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
1422 {
1423     MSIPACKAGE *package = NULL;
1424     UINT ret;
1425
1426     TRACE("%s %08x %p\n", debugstr_w(szPackage), dwOptions, phPackage );
1427
1428     if( !szPackage || !phPackage )
1429         return ERROR_INVALID_PARAMETER;
1430
1431     if ( !*szPackage )
1432     {
1433         FIXME("Should create an empty database and package\n");
1434         return ERROR_FUNCTION_FAILED;
1435     }
1436
1437     if( dwOptions )
1438         FIXME("dwOptions %08x not supported\n", dwOptions);
1439
1440     ret = MSI_OpenPackageW( szPackage, &package );
1441     if( ret == ERROR_SUCCESS )
1442     {
1443         *phPackage = alloc_msihandle( &package->hdr );
1444         if (! *phPackage)
1445             ret = ERROR_NOT_ENOUGH_MEMORY;
1446         msiobj_release( &package->hdr );
1447     }
1448
1449     return ret;
1450 }
1451
1452 UINT WINAPI MsiOpenPackageW(LPCWSTR szPackage, MSIHANDLE *phPackage)
1453 {
1454     return MsiOpenPackageExW( szPackage, 0, phPackage );
1455 }
1456
1457 UINT WINAPI MsiOpenPackageExA(LPCSTR szPackage, DWORD dwOptions, MSIHANDLE *phPackage)
1458 {
1459     LPWSTR szwPack = NULL;
1460     UINT ret;
1461
1462     if( szPackage )
1463     {
1464         szwPack = strdupAtoW( szPackage );
1465         if( !szwPack )
1466             return ERROR_OUTOFMEMORY;
1467     }
1468
1469     ret = MsiOpenPackageExW( szwPack, dwOptions, phPackage );
1470
1471     msi_free( szwPack );
1472
1473     return ret;
1474 }
1475
1476 UINT WINAPI MsiOpenPackageA(LPCSTR szPackage, MSIHANDLE *phPackage)
1477 {
1478     return MsiOpenPackageExA( szPackage, 0, phPackage );
1479 }
1480
1481 MSIHANDLE WINAPI MsiGetActiveDatabase(MSIHANDLE hInstall)
1482 {
1483     MSIPACKAGE *package;
1484     MSIHANDLE handle = 0;
1485     IUnknown *remote_unk;
1486     IWineMsiRemotePackage *remote_package;
1487
1488     TRACE("(%d)\n",hInstall);
1489
1490     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
1491     if( package)
1492     {
1493         handle = alloc_msihandle( &package->db->hdr );
1494         msiobj_release( &package->hdr );
1495     }
1496     else if ((remote_unk = msi_get_remote(hInstall)))
1497     {
1498         if (IUnknown_QueryInterface(remote_unk, &IID_IWineMsiRemotePackage,
1499                                         (LPVOID *)&remote_package) == S_OK)
1500         {
1501             IWineMsiRemotePackage_GetActiveDatabase(remote_package, &handle);
1502             IWineMsiRemotePackage_Release(remote_package);
1503         }
1504         else
1505         {
1506             WARN("remote handle %d is not a package\n", hInstall);
1507         }
1508         IUnknown_Release(remote_unk);
1509     }
1510
1511     return handle;
1512 }
1513
1514 INT MSI_ProcessMessage( MSIPACKAGE *package, INSTALLMESSAGE eMessageType,
1515                                MSIRECORD *record)
1516 {
1517     static const WCHAR szActionData[] =
1518         {'A','c','t','i','o','n','D','a','t','a',0};
1519     static const WCHAR szSetProgress[] =
1520         {'S','e','t','P','r','o','g','r','e','s','s',0};
1521     static const WCHAR szActionText[] =
1522         {'A','c','t','i','o','n','T','e','x','t',0};
1523     DWORD log_type = 0;
1524     LPWSTR message;
1525     DWORD sz;
1526     DWORD total_size = 0;
1527     INT i;
1528     INT rc;
1529     char *msg;
1530     int len;
1531
1532     TRACE("%x\n", eMessageType);
1533     rc = 0;
1534
1535     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ERROR)
1536         log_type |= INSTALLLOGMODE_ERROR;
1537     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_WARNING)
1538         log_type |= INSTALLLOGMODE_WARNING;
1539     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_USER)
1540         log_type |= INSTALLLOGMODE_USER;
1541     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_INFO)
1542         log_type |= INSTALLLOGMODE_INFO;
1543     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_COMMONDATA)
1544         log_type |= INSTALLLOGMODE_COMMONDATA;
1545     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONSTART)
1546         log_type |= INSTALLLOGMODE_ACTIONSTART;
1547     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONDATA)
1548         log_type |= INSTALLLOGMODE_ACTIONDATA;
1549     /* just a guess */
1550     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_PROGRESS)
1551         log_type |= 0x800;
1552
1553     if ((eMessageType & 0xff000000) == INSTALLMESSAGE_ACTIONSTART)
1554     {
1555         static const WCHAR template_s[]=
1556             {'A','c','t','i','o','n',' ','%','s',':',' ','%','s','.',' ',0};
1557         static const WCHAR format[] = 
1558             {'H','H','\'',':','\'','m','m','\'',':','\'','s','s',0};
1559         WCHAR timet[0x100];
1560         LPCWSTR action_text, action;
1561         LPWSTR deformatted = NULL;
1562
1563         GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, format, timet, 0x100);
1564
1565         action = MSI_RecordGetString(record, 1);
1566         action_text = MSI_RecordGetString(record, 2);
1567
1568         if (!action || !action_text)
1569             return IDOK;
1570
1571         deformat_string(package, action_text, &deformatted);
1572
1573         len = strlenW(timet) + strlenW(action) + strlenW(template_s);
1574         if (deformatted)
1575             len += strlenW(deformatted);
1576         message = msi_alloc(len*sizeof(WCHAR));
1577         sprintfW(message, template_s, timet, action);
1578         if (deformatted)
1579             strcatW(message, deformatted);
1580         msi_free(deformatted);
1581     }
1582     else
1583     {
1584         INT msg_field=1;
1585         message = msi_alloc(1*sizeof (WCHAR));
1586         message[0]=0;
1587         msg_field = MSI_RecordGetFieldCount(record);
1588         for (i = 1; i <= msg_field; i++)
1589         {
1590             LPWSTR tmp;
1591             WCHAR number[3];
1592             static const WCHAR format[] = { '%','i',':',' ',0};
1593             sz = 0;
1594             MSI_RecordGetStringW(record,i,NULL,&sz);
1595             sz+=4;
1596             total_size+=sz*sizeof(WCHAR);
1597             tmp = msi_alloc(sz*sizeof(WCHAR));
1598             message = msi_realloc(message,total_size*sizeof (WCHAR));
1599
1600             MSI_RecordGetStringW(record,i,tmp,&sz);
1601
1602             if (msg_field > 1)
1603             {
1604                 sprintfW(number,format,i);
1605                 strcatW(message,number);
1606             }
1607             strcatW(message,tmp);
1608             if (msg_field > 1)
1609                 strcatW(message, szSpace);
1610
1611             msi_free(tmp);
1612         }
1613     }
1614
1615     TRACE("%p %p %p %x %x %s\n", gUIHandlerA, gUIHandlerW, gUIHandlerRecord,
1616           gUIFilter, log_type, debugstr_w(message));
1617
1618     /* convert it to ASCII */
1619     len = WideCharToMultiByte( CP_ACP, 0, message, -1, NULL, 0, NULL, NULL );
1620     msg = msi_alloc( len );
1621     WideCharToMultiByte( CP_ACP, 0, message, -1, msg, len, NULL, NULL );
1622
1623     if (gUIHandlerW && (gUIFilter & log_type))
1624     {
1625         rc = gUIHandlerW( gUIContext, eMessageType, message );
1626     }
1627     else if (gUIHandlerA && (gUIFilter & log_type))
1628     {
1629         rc = gUIHandlerA( gUIContext, eMessageType, msg );
1630     }
1631     else if (gUIHandlerRecord && (gUIFilter & log_type))
1632     {
1633         MSIHANDLE rec = MsiCreateRecord( 1 );
1634         MsiRecordSetStringW( rec, 0, message );
1635         rc = gUIHandlerRecord( gUIContext, eMessageType, rec );
1636         MsiCloseHandle( rec );
1637     }
1638
1639     if ((!rc) && (gszLogFile[0]) && !((eMessageType & 0xff000000) ==
1640                                       INSTALLMESSAGE_PROGRESS))
1641     {
1642         DWORD write;
1643         HANDLE log_file = CreateFileW(gszLogFile,GENERIC_WRITE, 0, NULL,
1644                                   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1645
1646         if (log_file != INVALID_HANDLE_VALUE)
1647         {
1648             SetFilePointer(log_file,0, NULL, FILE_END);
1649             WriteFile(log_file,msg,strlen(msg),&write,NULL);
1650             WriteFile(log_file,"\n",1,&write,NULL);
1651             CloseHandle(log_file);
1652         }
1653     }
1654     msi_free( msg );
1655     msi_free( message );
1656
1657     switch (eMessageType & 0xff000000)
1658     {
1659     case INSTALLMESSAGE_ACTIONDATA:
1660         /* FIXME: format record here instead of in ui_actiondata to get the
1661          * correct action data for external scripts */
1662         ControlEvent_FireSubscribedEvent(package, szActionData, record);
1663         break;
1664     case INSTALLMESSAGE_ACTIONSTART:
1665     {
1666         MSIRECORD *uirow;
1667         LPWSTR deformated;
1668         LPCWSTR action_text = MSI_RecordGetString(record, 2);
1669
1670         deformat_string(package, action_text, &deformated);
1671         uirow = MSI_CreateRecord(1);
1672         MSI_RecordSetStringW(uirow, 1, deformated);
1673         TRACE("INSTALLMESSAGE_ACTIONSTART: %s\n", debugstr_w(deformated));
1674         msi_free(deformated);
1675
1676         ControlEvent_FireSubscribedEvent(package, szActionText, uirow);
1677
1678         msiobj_release(&uirow->hdr);
1679         break;
1680     }
1681     case INSTALLMESSAGE_PROGRESS:
1682         ControlEvent_FireSubscribedEvent(package, szSetProgress, record);
1683         break;
1684     }
1685
1686     return ERROR_SUCCESS;
1687 }
1688
1689 INT WINAPI MsiProcessMessage( MSIHANDLE hInstall, INSTALLMESSAGE eMessageType,
1690                               MSIHANDLE hRecord)
1691 {
1692     UINT ret = ERROR_INVALID_HANDLE;
1693     MSIPACKAGE *package = NULL;
1694     MSIRECORD *record = NULL;
1695
1696     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE );
1697     if( !package )
1698     {
1699         HRESULT hr;
1700         IWineMsiRemotePackage *remote_package;
1701
1702         remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
1703         if (!remote_package)
1704             return ERROR_INVALID_HANDLE;
1705
1706         hr = IWineMsiRemotePackage_ProcessMessage( remote_package, eMessageType, hRecord );
1707
1708         IWineMsiRemotePackage_Release( remote_package );
1709
1710         if (FAILED(hr))
1711         {
1712             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
1713                 return HRESULT_CODE(hr);
1714
1715             return ERROR_FUNCTION_FAILED;
1716         }
1717
1718         return ERROR_SUCCESS;
1719     }
1720
1721     record = msihandle2msiinfo( hRecord, MSIHANDLETYPE_RECORD );
1722     if( !record )
1723         goto out;
1724
1725     ret = MSI_ProcessMessage( package, eMessageType, record );
1726
1727 out:
1728     msiobj_release( &package->hdr );
1729     if( record )
1730         msiobj_release( &record->hdr );
1731
1732     return ret;
1733 }
1734
1735 /* property code */
1736
1737 UINT WINAPI MsiSetPropertyA( MSIHANDLE hInstall, LPCSTR szName, LPCSTR szValue )
1738 {
1739     LPWSTR szwName = NULL, szwValue = NULL;
1740     UINT r = ERROR_OUTOFMEMORY;
1741
1742     szwName = strdupAtoW( szName );
1743     if( szName && !szwName )
1744         goto end;
1745
1746     szwValue = strdupAtoW( szValue );
1747     if( szValue && !szwValue )
1748         goto end;
1749
1750     r = MsiSetPropertyW( hInstall, szwName, szwValue);
1751
1752 end:
1753     msi_free( szwName );
1754     msi_free( szwValue );
1755
1756     return r;
1757 }
1758
1759 void msi_reset_folders( MSIPACKAGE *package, BOOL source )
1760 {
1761     MSIFOLDER *folder;
1762
1763     LIST_FOR_EACH_ENTRY( folder, &package->folders, MSIFOLDER, entry )
1764     {
1765         if ( source )
1766         {
1767             msi_free( folder->ResolvedSource );
1768             folder->ResolvedSource = NULL;
1769         }
1770         else
1771         {
1772             msi_free( folder->ResolvedTarget );
1773             folder->ResolvedTarget = NULL;
1774         }
1775     }
1776 }
1777
1778 UINT msi_set_property( MSIDATABASE *db, LPCWSTR szName, LPCWSTR szValue )
1779 {
1780     MSIQUERY *view;
1781     MSIRECORD *row = NULL;
1782     UINT rc;
1783     DWORD sz = 0;
1784     WCHAR Query[1024];
1785
1786     static const WCHAR Insert[] = {
1787         'I','N','S','E','R','T',' ','i','n','t','o',' ',
1788         '`','_','P','r','o','p','e','r','t','y','`',' ','(',
1789         '`','_','P','r','o','p','e','r','t','y','`',',',
1790         '`','V','a','l','u','e','`',')',' ','V','A','L','U','E','S'
1791         ,' ','(','?',',','?',')',0};
1792     static const WCHAR Update[] = {
1793         'U','P','D','A','T','E',' ','`','_','P','r','o','p','e','r','t','y','`',
1794         ' ','s','e','t',' ','`','V','a','l','u','e','`',' ','=',' ','?',' ',
1795         'w','h','e','r','e',' ','`','_','P','r','o','p','e','r','t','y','`',
1796         ' ','=',' ','\'','%','s','\'',0};
1797     static const WCHAR Delete[] = {
1798         'D','E','L','E','T','E',' ','F','R','O','M',' ',
1799         '`','_','P','r','o','p','e','r','t','y','`',' ','W','H','E','R','E',' ',
1800         '`','_','P','r','o','p','e','r','t','y','`',' ','=',' ','\'','%','s','\'',0};
1801
1802     TRACE("%p %s %s\n", db, debugstr_w(szName), debugstr_w(szValue));
1803
1804     if (!szName)
1805         return ERROR_INVALID_PARAMETER;
1806
1807     /* this one is weird... */
1808     if (!szName[0])
1809         return szValue ? ERROR_FUNCTION_FAILED : ERROR_SUCCESS;
1810
1811     rc = msi_get_property(db, szName, 0, &sz);
1812     if (!szValue || !*szValue)
1813     {
1814         sprintfW(Query, Delete, szName);
1815     }
1816     else if (rc == ERROR_MORE_DATA || rc == ERROR_SUCCESS)
1817     {
1818         sprintfW(Query, Update, szName);
1819
1820         row = MSI_CreateRecord(1);
1821         MSI_RecordSetStringW(row, 1, szValue);
1822     }
1823     else
1824     {
1825         strcpyW(Query, Insert);
1826
1827         row = MSI_CreateRecord(2);
1828         MSI_RecordSetStringW(row, 1, szName);
1829         MSI_RecordSetStringW(row, 2, szValue);
1830     }
1831
1832     rc = MSI_DatabaseOpenViewW(db, Query, &view);
1833     if (rc == ERROR_SUCCESS)
1834     {
1835         rc = MSI_ViewExecute(view, row);
1836         MSI_ViewClose(view);
1837         msiobj_release(&view->hdr);
1838     }
1839
1840     if (row)
1841       msiobj_release(&row->hdr);
1842
1843     return rc;
1844 }
1845
1846 UINT WINAPI MsiSetPropertyW( MSIHANDLE hInstall, LPCWSTR szName, LPCWSTR szValue)
1847 {
1848     MSIPACKAGE *package;
1849     UINT ret;
1850
1851     package = msihandle2msiinfo( hInstall, MSIHANDLETYPE_PACKAGE);
1852     if( !package )
1853     {
1854         HRESULT hr;
1855         BSTR name = NULL, value = NULL;
1856         IWineMsiRemotePackage *remote_package;
1857
1858         remote_package = (IWineMsiRemotePackage *)msi_get_remote( hInstall );
1859         if (!remote_package)
1860             return ERROR_INVALID_HANDLE;
1861
1862         name = SysAllocString( szName );
1863         value = SysAllocString( szValue );
1864         if ((!name && szName) || (!value && szValue))
1865         {
1866             SysFreeString( name );
1867             SysFreeString( value );
1868             IWineMsiRemotePackage_Release( remote_package );
1869             return ERROR_OUTOFMEMORY;
1870         }
1871
1872         hr = IWineMsiRemotePackage_SetProperty( remote_package, name, value );
1873
1874         SysFreeString( name );
1875         SysFreeString( value );
1876         IWineMsiRemotePackage_Release( remote_package );
1877
1878         if (FAILED(hr))
1879         {
1880             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
1881                 return HRESULT_CODE(hr);
1882
1883             return ERROR_FUNCTION_FAILED;
1884         }
1885
1886         return ERROR_SUCCESS;
1887     }
1888
1889     ret = msi_set_property( package->db, szName, szValue );
1890     if (ret == ERROR_SUCCESS && !strcmpW( szName, cszSourceDir ))
1891         msi_reset_folders( package, TRUE );
1892
1893     msiobj_release( &package->hdr );
1894     return ret;
1895 }
1896
1897 static MSIRECORD *msi_get_property_row( MSIDATABASE *db, LPCWSTR name )
1898 {
1899     MSIQUERY *view;
1900     MSIRECORD *rec, *row = NULL;
1901     UINT r;
1902
1903     static const WCHAR query[]= {
1904         'S','E','L','E','C','T',' ','`','V','a','l','u','e','`',' ',
1905         'F','R','O','M',' ' ,'`','_','P','r','o','p','e','r','t','y','`',
1906         ' ','W','H','E','R','E',' ' ,'`','_','P','r','o','p','e','r','t','y','`',
1907         '=','?',0};
1908
1909     if (!name || !*name)
1910         return NULL;
1911
1912     rec = MSI_CreateRecord(1);
1913     if (!rec)
1914         return NULL;
1915
1916     MSI_RecordSetStringW(rec, 1, name);
1917
1918     r = MSI_DatabaseOpenViewW(db, query, &view);
1919     if (r == ERROR_SUCCESS)
1920     {
1921         MSI_ViewExecute(view, rec);
1922         MSI_ViewFetch(view, &row);
1923         MSI_ViewClose(view);
1924         msiobj_release(&view->hdr);
1925     }
1926
1927     msiobj_release(&rec->hdr);
1928     return row;
1929 }
1930
1931 /* internal function, not compatible with MsiGetPropertyW */
1932 UINT msi_get_property( MSIDATABASE *db, LPCWSTR szName,
1933                        LPWSTR szValueBuf, LPDWORD pchValueBuf )
1934 {
1935     MSIRECORD *row;
1936     UINT rc = ERROR_FUNCTION_FAILED;
1937
1938     row = msi_get_property_row( db, szName );
1939
1940     if (*pchValueBuf > 0)
1941         szValueBuf[0] = 0;
1942
1943     if (row)
1944     {
1945         rc = MSI_RecordGetStringW(row, 1, szValueBuf, pchValueBuf);
1946         msiobj_release(&row->hdr);
1947     }
1948
1949     if (rc == ERROR_SUCCESS)
1950         TRACE("returning %s for property %s\n", debugstr_w(szValueBuf),
1951             debugstr_w(szName));
1952     else if (rc == ERROR_MORE_DATA)
1953         TRACE("need %d sized buffer for %s\n", *pchValueBuf,
1954             debugstr_w(szName));
1955     else
1956     {
1957         *pchValueBuf = 0;
1958         TRACE("property %s not found\n", debugstr_w(szName));
1959     }
1960
1961     return rc;
1962 }
1963
1964 LPWSTR msi_dup_property(MSIDATABASE *db, LPCWSTR prop)
1965 {
1966     DWORD sz = 0;
1967     LPWSTR str;
1968     UINT r;
1969
1970     r = msi_get_property(db, prop, NULL, &sz);
1971     if (r != ERROR_SUCCESS && r != ERROR_MORE_DATA)
1972         return NULL;
1973
1974     sz++;
1975     str = msi_alloc(sz * sizeof(WCHAR));
1976     r = msi_get_property(db, prop, str, &sz);
1977     if (r != ERROR_SUCCESS)
1978     {
1979         msi_free(str);
1980         str = NULL;
1981     }
1982
1983     return str;
1984 }
1985
1986 int msi_get_property_int( MSIDATABASE *db, LPCWSTR prop, int def )
1987 {
1988     LPWSTR str = msi_dup_property( db, prop );
1989     int val = str ? atoiW(str) : def;
1990     msi_free(str);
1991     return val;
1992 }
1993
1994 static UINT MSI_GetProperty( MSIHANDLE handle, LPCWSTR name,
1995                              awstring *szValueBuf, LPDWORD pchValueBuf )
1996 {
1997     MSIPACKAGE *package;
1998     MSIRECORD *row = NULL;
1999     UINT r = ERROR_FUNCTION_FAILED;
2000     LPCWSTR val = NULL;
2001
2002     TRACE("%u %s %p %p\n", handle, debugstr_w(name),
2003           szValueBuf->str.w, pchValueBuf );
2004
2005     if (!name)
2006         return ERROR_INVALID_PARAMETER;
2007
2008     package = msihandle2msiinfo( handle, MSIHANDLETYPE_PACKAGE );
2009     if (!package)
2010     {
2011         HRESULT hr;
2012         IWineMsiRemotePackage *remote_package;
2013         LPWSTR value = NULL;
2014         BSTR bname;
2015         DWORD len;
2016
2017         remote_package = (IWineMsiRemotePackage *)msi_get_remote( handle );
2018         if (!remote_package)
2019             return ERROR_INVALID_HANDLE;
2020
2021         bname = SysAllocString( name );
2022         if (!bname)
2023         {
2024             IWineMsiRemotePackage_Release( remote_package );
2025             return ERROR_OUTOFMEMORY;
2026         }
2027
2028         len = 0;
2029         hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, NULL, &len );
2030         if (FAILED(hr))
2031             goto done;
2032
2033         len++;
2034         value = msi_alloc(len * sizeof(WCHAR));
2035         if (!value)
2036         {
2037             r = ERROR_OUTOFMEMORY;
2038             goto done;
2039         }
2040
2041         hr = IWineMsiRemotePackage_GetProperty( remote_package, bname, (BSTR *)value, &len );
2042         if (FAILED(hr))
2043             goto done;
2044
2045         r = msi_strcpy_to_awstring( value, szValueBuf, pchValueBuf );
2046
2047         /* Bug required by Adobe installers */
2048         if (!szValueBuf->unicode && !szValueBuf->str.a)
2049             *pchValueBuf *= sizeof(WCHAR);
2050
2051 done:
2052         IWineMsiRemotePackage_Release(remote_package);
2053         SysFreeString(bname);
2054         msi_free(value);
2055
2056         if (FAILED(hr))
2057         {
2058             if (HRESULT_FACILITY(hr) == FACILITY_WIN32)
2059                 return HRESULT_CODE(hr);
2060
2061             return ERROR_FUNCTION_FAILED;
2062         }
2063
2064         return r;
2065     }
2066
2067     row = msi_get_property_row( package->db, name );
2068     if (row)
2069         val = MSI_RecordGetString( row, 1 );
2070
2071     if (!val)
2072         val = szEmpty;
2073
2074     r = msi_strcpy_to_awstring( val, szValueBuf, pchValueBuf );
2075
2076     if (row)
2077         msiobj_release( &row->hdr );
2078     msiobj_release( &package->hdr );
2079
2080     return r;
2081 }
2082
2083 UINT WINAPI MsiGetPropertyA( MSIHANDLE hInstall, LPCSTR szName,
2084                              LPSTR szValueBuf, LPDWORD pchValueBuf )
2085 {
2086     awstring val;
2087     LPWSTR name;
2088     UINT r;
2089
2090     val.unicode = FALSE;
2091     val.str.a = szValueBuf;
2092
2093     name = strdupAtoW( szName );
2094     if (szName && !name)
2095         return ERROR_OUTOFMEMORY;
2096
2097     r = MSI_GetProperty( hInstall, name, &val, pchValueBuf );
2098     msi_free( name );
2099     return r;
2100 }
2101
2102 UINT WINAPI MsiGetPropertyW( MSIHANDLE hInstall, LPCWSTR szName,
2103                              LPWSTR szValueBuf, LPDWORD pchValueBuf )
2104 {
2105     awstring val;
2106
2107     val.unicode = TRUE;
2108     val.str.w = szValueBuf;
2109
2110     return MSI_GetProperty( hInstall, szName, &val, pchValueBuf );
2111 }
2112
2113 typedef struct _msi_remote_package_impl {
2114     const IWineMsiRemotePackageVtbl *lpVtbl;
2115     MSIHANDLE package;
2116     LONG refs;
2117 } msi_remote_package_impl;
2118
2119 static inline msi_remote_package_impl* mrp_from_IWineMsiRemotePackage( IWineMsiRemotePackage* iface )
2120 {
2121     return (msi_remote_package_impl*) iface;
2122 }
2123
2124 static HRESULT WINAPI mrp_QueryInterface( IWineMsiRemotePackage *iface,
2125                 REFIID riid,LPVOID *ppobj)
2126 {
2127     if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2128         IsEqualCLSID( riid, &IID_IWineMsiRemotePackage ) )
2129     {
2130         IUnknown_AddRef( iface );
2131         *ppobj = iface;
2132         return S_OK;
2133     }
2134
2135     return E_NOINTERFACE;
2136 }
2137
2138 static ULONG WINAPI mrp_AddRef( IWineMsiRemotePackage *iface )
2139 {
2140     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2141
2142     return InterlockedIncrement( &This->refs );
2143 }
2144
2145 static ULONG WINAPI mrp_Release( IWineMsiRemotePackage *iface )
2146 {
2147     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2148     ULONG r;
2149
2150     r = InterlockedDecrement( &This->refs );
2151     if (r == 0)
2152     {
2153         MsiCloseHandle( This->package );
2154         msi_free( This );
2155     }
2156     return r;
2157 }
2158
2159 static HRESULT WINAPI mrp_SetMsiHandle( IWineMsiRemotePackage *iface, MSIHANDLE handle )
2160 {
2161     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2162     This->package = handle;
2163     return S_OK;
2164 }
2165
2166 static HRESULT WINAPI mrp_GetActiveDatabase( IWineMsiRemotePackage *iface, MSIHANDLE *handle )
2167 {
2168     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2169     IWineMsiRemoteDatabase *rdb = NULL;
2170     HRESULT hr;
2171     MSIHANDLE hdb;
2172
2173     hr = create_msi_remote_database( NULL, (LPVOID *)&rdb );
2174     if (FAILED(hr) || !rdb)
2175     {
2176         ERR("Failed to create remote database\n");
2177         return hr;
2178     }
2179
2180     hdb = MsiGetActiveDatabase(This->package);
2181
2182     hr = IWineMsiRemoteDatabase_SetMsiHandle( rdb, hdb );
2183     if (FAILED(hr))
2184     {
2185         ERR("Failed to set the database handle\n");
2186         return hr;
2187     }
2188
2189     *handle = alloc_msi_remote_handle( (IUnknown *)rdb );
2190     return S_OK;
2191 }
2192
2193 static HRESULT WINAPI mrp_GetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR *value, DWORD *size )
2194 {
2195     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2196     UINT r;
2197
2198     r = MsiGetPropertyW(This->package, (LPWSTR)property, (LPWSTR)value, size);
2199     if (r != ERROR_SUCCESS)
2200         return HRESULT_FROM_WIN32(r);
2201
2202     return S_OK;
2203 }
2204
2205 static HRESULT WINAPI mrp_SetProperty( IWineMsiRemotePackage *iface, BSTR property, BSTR value )
2206 {
2207     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2208     UINT r = MsiSetPropertyW(This->package, property, value);
2209     return HRESULT_FROM_WIN32(r);
2210 }
2211
2212 static HRESULT WINAPI mrp_ProcessMessage( IWineMsiRemotePackage *iface, INSTALLMESSAGE message, MSIHANDLE record )
2213 {
2214     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2215     UINT r = MsiProcessMessage(This->package, message, record);
2216     return HRESULT_FROM_WIN32(r);
2217 }
2218
2219 static HRESULT WINAPI mrp_DoAction( IWineMsiRemotePackage *iface, BSTR action )
2220 {
2221     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2222     UINT r = MsiDoActionW(This->package, action);
2223     return HRESULT_FROM_WIN32(r);
2224 }
2225
2226 static HRESULT WINAPI mrp_Sequence( IWineMsiRemotePackage *iface, BSTR table, int sequence )
2227 {
2228     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2229     UINT r = MsiSequenceW(This->package, table, sequence);
2230     return HRESULT_FROM_WIN32(r);
2231 }
2232
2233 static HRESULT WINAPI mrp_GetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR *value, DWORD *size )
2234 {
2235     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2236     UINT r = MsiGetTargetPathW(This->package, (LPWSTR)folder, (LPWSTR)value, size);
2237     return HRESULT_FROM_WIN32(r);
2238 }
2239
2240 static HRESULT WINAPI mrp_SetTargetPath( IWineMsiRemotePackage *iface, BSTR folder, BSTR value)
2241 {
2242     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2243     UINT r = MsiSetTargetPathW(This->package, folder, value);
2244     return HRESULT_FROM_WIN32(r);
2245 }
2246
2247 static HRESULT WINAPI mrp_GetSourcePath( IWineMsiRemotePackage *iface, BSTR folder, BSTR *value, DWORD *size )
2248 {
2249     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2250     UINT r = MsiGetSourcePathW(This->package, (LPWSTR)folder, (LPWSTR)value, size);
2251     return HRESULT_FROM_WIN32(r);
2252 }
2253
2254 static HRESULT WINAPI mrp_GetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL *ret )
2255 {
2256     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2257     *ret = MsiGetMode(This->package, mode);
2258     return S_OK;
2259 }
2260
2261 static HRESULT WINAPI mrp_SetMode( IWineMsiRemotePackage *iface, MSIRUNMODE mode, BOOL state )
2262 {
2263     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2264     UINT r = MsiSetMode(This->package, mode, state);
2265     return HRESULT_FROM_WIN32(r);
2266 }
2267
2268 static HRESULT WINAPI mrp_GetFeatureState( IWineMsiRemotePackage *iface, BSTR feature,
2269                                     INSTALLSTATE *installed, INSTALLSTATE *action )
2270 {
2271     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2272     UINT r = MsiGetFeatureStateW(This->package, feature, installed, action);
2273     return HRESULT_FROM_WIN32(r);
2274 }
2275
2276 static HRESULT WINAPI mrp_SetFeatureState( IWineMsiRemotePackage *iface, BSTR feature, INSTALLSTATE state )
2277 {
2278     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2279     UINT r = MsiSetFeatureStateW(This->package, feature, state);
2280     return HRESULT_FROM_WIN32(r);
2281 }
2282
2283 static HRESULT WINAPI mrp_GetComponentState( IWineMsiRemotePackage *iface, BSTR component,
2284                                       INSTALLSTATE *installed, INSTALLSTATE *action )
2285 {
2286     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2287     UINT r = MsiGetComponentStateW(This->package, component, installed, action);
2288     return HRESULT_FROM_WIN32(r);
2289 }
2290
2291 static HRESULT WINAPI mrp_SetComponentState( IWineMsiRemotePackage *iface, BSTR component, INSTALLSTATE state )
2292 {
2293     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2294     UINT r = MsiSetComponentStateW(This->package, component, state);
2295     return HRESULT_FROM_WIN32(r);
2296 }
2297
2298 static HRESULT WINAPI mrp_GetLanguage( IWineMsiRemotePackage *iface, LANGID *language )
2299 {
2300     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2301     *language = MsiGetLanguage(This->package);
2302     return S_OK;
2303 }
2304
2305 static HRESULT WINAPI mrp_SetInstallLevel( IWineMsiRemotePackage *iface, int level )
2306 {
2307     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2308     UINT r = MsiSetInstallLevel(This->package, level);
2309     return HRESULT_FROM_WIN32(r);
2310 }
2311
2312 static HRESULT WINAPI mrp_FormatRecord( IWineMsiRemotePackage *iface, MSIHANDLE record,
2313                                         BSTR *value)
2314 {
2315     DWORD size = 0;
2316     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2317     UINT r = MsiFormatRecordW(This->package, record, NULL, &size);
2318     if (r == ERROR_SUCCESS)
2319     {
2320         *value = SysAllocStringLen(NULL, size);
2321         if (!*value)
2322             return E_OUTOFMEMORY;
2323         size++;
2324         r = MsiFormatRecordW(This->package, record, *value, &size);
2325     }
2326     return HRESULT_FROM_WIN32(r);
2327 }
2328
2329 static HRESULT WINAPI mrp_EvaluateCondition( IWineMsiRemotePackage *iface, BSTR condition )
2330 {
2331     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2332     UINT r = MsiEvaluateConditionW(This->package, condition);
2333     return HRESULT_FROM_WIN32(r);
2334 }
2335
2336 static HRESULT WINAPI mrp_GetFeatureCost( IWineMsiRemotePackage *iface, BSTR feature,
2337                                           INT cost_tree, INSTALLSTATE state, INT *cost )
2338 {
2339     msi_remote_package_impl* This = mrp_from_IWineMsiRemotePackage( iface );
2340     UINT r = MsiGetFeatureCostW(This->package, feature, cost_tree, state, cost);
2341     return HRESULT_FROM_WIN32(r);
2342 }
2343
2344 static const IWineMsiRemotePackageVtbl msi_remote_package_vtbl =
2345 {
2346     mrp_QueryInterface,
2347     mrp_AddRef,
2348     mrp_Release,
2349     mrp_SetMsiHandle,
2350     mrp_GetActiveDatabase,
2351     mrp_GetProperty,
2352     mrp_SetProperty,
2353     mrp_ProcessMessage,
2354     mrp_DoAction,
2355     mrp_Sequence,
2356     mrp_GetTargetPath,
2357     mrp_SetTargetPath,
2358     mrp_GetSourcePath,
2359     mrp_GetMode,
2360     mrp_SetMode,
2361     mrp_GetFeatureState,
2362     mrp_SetFeatureState,
2363     mrp_GetComponentState,
2364     mrp_SetComponentState,
2365     mrp_GetLanguage,
2366     mrp_SetInstallLevel,
2367     mrp_FormatRecord,
2368     mrp_EvaluateCondition,
2369     mrp_GetFeatureCost,
2370 };
2371
2372 HRESULT create_msi_remote_package( IUnknown *pOuter, LPVOID *ppObj )
2373 {
2374     msi_remote_package_impl* This;
2375
2376     This = msi_alloc( sizeof *This );
2377     if (!This)
2378         return E_OUTOFMEMORY;
2379
2380     This->lpVtbl = &msi_remote_package_vtbl;
2381     This->package = 0;
2382     This->refs = 1;
2383
2384     *ppObj = This;
2385
2386     return S_OK;
2387 }
2388
2389 UINT msi_package_add_info(MSIPACKAGE *package, DWORD context, DWORD options,
2390                           LPCWSTR property, LPWSTR value)
2391 {
2392     MSISOURCELISTINFO *info;
2393
2394     info = msi_alloc(sizeof(MSISOURCELISTINFO));
2395     if (!info)
2396         return ERROR_OUTOFMEMORY;
2397
2398     info->context = context;
2399     info->options = options;
2400     info->property = property;
2401     info->value = strdupW(value);
2402     list_add_head(&package->sourcelist_info, &info->entry);
2403
2404     return ERROR_SUCCESS;
2405 }
2406
2407 UINT msi_package_add_media_disk(MSIPACKAGE *package, DWORD context, DWORD options,
2408                                 DWORD disk_id, LPWSTR volume_label, LPWSTR disk_prompt)
2409 {
2410     MSIMEDIADISK *disk;
2411
2412     disk = msi_alloc(sizeof(MSIMEDIADISK));
2413     if (!disk)
2414         return ERROR_OUTOFMEMORY;
2415
2416     disk->context = context;
2417     disk->options = options;
2418     disk->disk_id = disk_id;
2419     disk->volume_label = strdupW(volume_label);
2420     disk->disk_prompt = strdupW(disk_prompt);
2421     list_add_head(&package->sourcelist_media, &disk->entry);
2422
2423     return ERROR_SUCCESS;
2424 }