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