Free allocated buffers.
[wine] / dlls / msi / action.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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /*
22  * Pages I need
23  *
24 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msi/setup/installexecutesequence_table.asp
25
26 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/msi/setup/standard_actions_reference.asp
27  */
28
29 #include <stdarg.h>
30 #include <stdio.h>
31
32 #define COBJMACROS
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winerror.h"
37 #include "winreg.h"
38 #include "wine/debug.h"
39 #include "fdi.h"
40 #include "msi.h"
41 #include "msiquery.h"
42 #include "msvcrt/fcntl.h"
43 #include "objbase.h"
44 #include "objidl.h"
45 #include "msipriv.h"
46 #include "winnls.h"
47 #include "winuser.h"
48 #include "shlobj.h"
49 #include "wine/unicode.h"
50 #include "ver.h"
51
52 #define CUSTOM_ACTION_TYPE_MASK 0x3F
53
54 WINE_DEFAULT_DEBUG_CHANNEL(msi);
55
56 typedef struct tagMSIFEATURE
57 {
58     WCHAR Feature[96];
59     WCHAR Feature_Parent[96];
60     WCHAR Title[0x100];
61     WCHAR Description[0x100];
62     INT Display;
63     INT Level;
64     WCHAR Directory[96];
65     INT Attributes;
66     
67     INSTALLSTATE Installed;
68     INSTALLSTATE ActionRequest;
69     INSTALLSTATE Action;
70
71     INT ComponentCount;
72     INT Components[1024]; /* yes hardcoded limit.... I am bad */
73     INT Cost;
74 } MSIFEATURE;
75
76 typedef struct tagMSICOMPONENT
77 {
78     WCHAR Component[96];
79     WCHAR ComponentId[96];
80     WCHAR Directory[96];
81     INT Attributes;
82     WCHAR Condition[0x100];
83     WCHAR KeyPath[96];
84
85     INSTALLSTATE Installed;
86     INSTALLSTATE ActionRequest;
87     INSTALLSTATE Action;
88
89     BOOL Enabled;
90     INT  Cost;
91 } MSICOMPONENT;
92
93 typedef struct tagMSIFOLDER
94 {
95     LPWSTR Directory;
96     LPWSTR TargetDefault;
97     LPWSTR SourceDefault;
98
99     LPWSTR ResolvedTarget;
100     LPWSTR ResolvedSource;
101     LPWSTR Property;   /* initially set property */
102     INT   ParentIndex;
103     INT   State;
104         /* 0 = uninitialized */
105         /* 1 = existing */
106         /* 2 = created remove if empty */
107         /* 3 = created persist if empty */
108     INT   Cost;
109     INT   Space;
110 }MSIFOLDER;
111
112 typedef struct tagMSIFILE
113 {
114     LPWSTR File;
115     INT ComponentIndex;
116     LPWSTR FileName;
117     INT FileSize;
118     LPWSTR Version;
119     LPWSTR Language;
120     INT Attributes;
121     INT Sequence;   
122
123     INT State;
124        /* 0 = uninitialize */
125        /* 1 = not present */
126        /* 2 = present but replace */
127        /* 3 = present do not replace */
128        /* 4 = Installed */
129     LPWSTR  SourcePath;
130     LPWSTR  TargetPath;
131     BOOL    Temporary; 
132 }MSIFILE;
133
134 /*
135  * Prototypes
136  */
137 static UINT ACTION_ProcessExecSequence(MSIPACKAGE *package, BOOL UIran);
138 static UINT ACTION_ProcessUISequence(MSIPACKAGE *package);
139
140 static UINT ACTION_PerformActionSequence(MSIPACKAGE *package, UINT seq);
141 UINT ACTION_PerformAction(MSIPACKAGE *package, const WCHAR *action);
142
143 static UINT ACTION_LaunchConditions(MSIPACKAGE *package);
144 static UINT ACTION_CostInitialize(MSIPACKAGE *package);
145 static UINT ACTION_CreateFolders(MSIPACKAGE *package);
146 static UINT ACTION_CostFinalize(MSIPACKAGE *package);
147 static UINT ACTION_FileCost(MSIPACKAGE *package);
148 static UINT ACTION_InstallFiles(MSIPACKAGE *package);
149 static UINT ACTION_DuplicateFiles(MSIPACKAGE *package);
150 static UINT ACTION_WriteRegistryValues(MSIPACKAGE *package);
151 static UINT ACTION_CustomAction(MSIPACKAGE *package,const WCHAR *action);
152 static UINT ACTION_InstallInitialize(MSIPACKAGE *package);
153 static UINT ACTION_InstallValidate(MSIPACKAGE *package);
154 static UINT ACTION_ProcessComponents(MSIPACKAGE *package);
155 static UINT ACTION_RegisterTypeLibraries(MSIPACKAGE *package);
156 static UINT ACTION_RegisterClassInfo(MSIPACKAGE *package);
157 static UINT ACTION_RegisterProgIdInfo(MSIPACKAGE *package);
158 static UINT ACTION_CreateShortcuts(MSIPACKAGE *package);
159 static UINT ACTION_PublishProduct(MSIPACKAGE *package);
160
161 static UINT HANDLE_CustomType1(MSIPACKAGE *package, const LPWSTR source, 
162                                 const LPWSTR target, const INT type);
163 static UINT HANDLE_CustomType2(MSIPACKAGE *package, const LPWSTR source, 
164                                 const LPWSTR target, const INT type);
165 static UINT HANDLE_CustomType18(MSIPACKAGE *package, const LPWSTR source, 
166                                 const LPWSTR target, const INT type);
167 static UINT HANDLE_CustomType50(MSIPACKAGE *package, const LPWSTR source, 
168                                 const LPWSTR target, const INT type);
169 static UINT HANDLE_CustomType34(MSIPACKAGE *package, const LPWSTR source, 
170                                 const LPWSTR target, const INT type);
171
172 static DWORD deformat_string(MSIPACKAGE *package, WCHAR* ptr,WCHAR** data);
173 static LPWSTR resolve_folder(MSIPACKAGE *package, LPCWSTR name,
174                            BOOL source, BOOL set_prop, MSIFOLDER **folder);
175
176 static int track_tempfile(MSIPACKAGE *package, LPCWSTR name, LPCWSTR path);
177  
178 /*
179  * consts and values used
180  */
181 static const WCHAR cszSourceDir[] = {'S','o','u','r','c','e','D','i','r',0};
182 static const WCHAR cszRootDrive[] = {'R','O','O','T','D','R','I','V','E',0};
183 static const WCHAR cszTargetDir[] = {'T','A','R','G','E','T','D','I','R',0};
184 static const WCHAR cszTempFolder[]= {'T','e','m','p','F','o','l','d','e','r',0};
185 static const WCHAR cszDatabase[]={'D','A','T','A','B','A','S','E',0};
186 static const WCHAR c_collen[] = {'C',':','\\',0};
187  
188 static const WCHAR cszlsb[]={'[',0};
189 static const WCHAR cszrsb[]={']',0};
190 static const WCHAR cszbs[]={'\\',0};
191
192 const static WCHAR szCreateFolders[] =
193     {'C','r','e','a','t','e','F','o','l','d','e','r','s',0};
194 const static WCHAR szCostFinalize[] =
195     {'C','o','s','t','F','i','n','a','l','i','z','e',0};
196 const static WCHAR szInstallFiles[] =
197     {'I','n','s','t','a','l','l','F','i','l','e','s',0};
198 const static WCHAR szDuplicateFiles[] =
199     {'D','u','p','l','i','c','a','t','e','F','i','l','e','s',0};
200 const static WCHAR szWriteRegistryValues[] =
201 {'W','r','i','t','e','R','e','g','i','s','t','r','y','V','a','l','u','e','s',0};
202 const static WCHAR szCostInitialize[] =
203     {'C','o','s','t','I','n','i','t','i','a','l','i','z','e',0};
204 const static WCHAR szFileCost[] = {'F','i','l','e','C','o','s','t',0};
205 const static WCHAR szInstallInitialize[] = 
206     {'I','n','s','t','a','l','l','I','n','i','t','i','a','l','i','z','e',0};
207 const static WCHAR szInstallValidate[] = 
208     {'I','n','s','t','a','l','l','V','a','l','i','d','a','t','e',0};
209 const static WCHAR szLaunchConditions[] = 
210     {'L','a','u','n','c','h','C','o','n','d','i','t','i','o','n','s',0};
211 const static WCHAR szProcessComponents[] = 
212     {'P','r','o','c','e','s','s','C','o','m','p','o','n','e','n','t','s',0};
213 const static WCHAR szRegisterTypeLibraries[] = 
214 {'R','e','g','i','s','t','e','r','T','y','p','e','L','i','b','r','a','r',
215 'i','e','s',0};
216 const static WCHAR szRegisterClassInfo[] = 
217 {'R','e','g','i','s','t','e','r','C','l','a','s','s','I','n','f','o',0};
218 const static WCHAR szRegisterProgIdInfo[] = 
219 {'R','e','g','i','s','t','e','r','P','r','o','g','I','d','I','n','f','o',0};
220 const static WCHAR szCreateShortcuts[] = 
221 {'C','r','e','a','t','e','S','h','o','r','t','c','u','t','s',0};
222 const static WCHAR szPublishProduct[] = 
223 {'P','u','b','l','i','s','h','P','r','o','d','u','c','t',0};
224
225 /******************************************************** 
226  * helper functions to get around current HACKS and such
227  ********************************************************/
228 inline static void reduce_to_longfilename(WCHAR* filename)
229 {
230     LPWSTR p = strchrW(filename,'|');
231     if (p)
232         memmove(filename, p+1, (strlenW(p+1)+1)*sizeof(WCHAR));
233 }
234
235 inline static char *strdupWtoA( const WCHAR *str )
236 {
237     char *ret = NULL;
238     if (str)
239     {
240         DWORD len = WideCharToMultiByte( CP_ACP, 0, str, -1, NULL, 0, NULL, NULL
241 );
242         if ((ret = HeapAlloc( GetProcessHeap(), 0, len )))
243             WideCharToMultiByte( CP_ACP, 0, str, -1, ret, len, NULL, NULL );
244     }
245     return ret;
246 }
247
248 inline static WCHAR *strdupAtoW( const char *str )
249 {
250     WCHAR *ret = NULL;
251     if (str)
252     {
253         DWORD len = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 );
254         if ((ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
255             MultiByteToWideChar( CP_ACP, 0, str, -1, ret, len );
256     }
257     return ret;
258 }
259
260 static LPWSTR dupstrW(LPCWSTR src)
261 {
262     LPWSTR dest;
263     if (!src) return NULL;
264     dest = HeapAlloc(GetProcessHeap(), 0, (strlenW(src)+1)*sizeof(WCHAR));
265     strcpyW(dest, src);
266     return dest;
267 }
268
269 inline static WCHAR *load_dynamic_stringW(MSIRECORD *row, INT index)
270 {
271     UINT rc;
272     DWORD sz;
273     LPWSTR ret;
274    
275     sz = 0; 
276     if (MSI_RecordIsNull(row,index))
277         return NULL;
278
279     rc = MSI_RecordGetStringW(row,index,NULL,&sz);
280
281     /* having an empty string is different than NULL */
282     if (sz == 0)
283     {
284         ret = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR));
285         ret[0] = 0;
286         return ret;
287     }
288
289     sz ++;
290     ret = HeapAlloc(GetProcessHeap(),0,sz * sizeof (WCHAR));
291     rc = MSI_RecordGetStringW(row,index,ret,&sz);
292     if (rc!=ERROR_SUCCESS)
293     {
294         ERR("Unable to load dynamic string\n");
295         HeapFree(GetProcessHeap(), 0, ret);
296         ret = NULL;
297     }
298     return ret;
299 }
300
301 inline static LPWSTR load_dynamic_property(MSIPACKAGE *package, LPCWSTR prop,
302                                            UINT* rc)
303 {
304     DWORD sz = 0;
305     LPWSTR str;
306     UINT r;
307
308     r = MSI_GetPropertyW(package, prop, NULL, &sz);
309     if (r != ERROR_SUCCESS && r != ERROR_MORE_DATA)
310     {
311         if (rc)
312             *rc = r;
313         return NULL;
314     }
315     sz++;
316     str = HeapAlloc(GetProcessHeap(),0,sz*sizeof(WCHAR));
317     r = MSI_GetPropertyW(package, prop, str, &sz);
318     if (r != ERROR_SUCCESS)
319     {
320         HeapFree(GetProcessHeap(),0,str);
321         str = NULL;
322     }
323     if (rc)
324         *rc = r;
325     return str;
326 }
327
328 inline static int get_loaded_component(MSIPACKAGE* package, LPCWSTR Component )
329 {
330     int rc = -1;
331     DWORD i;
332
333     for (i = 0; i < package->loaded_components; i++)
334     {
335         if (strcmpW(Component,package->components[i].Component)==0)
336         {
337             rc = i;
338             break;
339         }
340     }
341     return rc;
342 }
343
344 inline static int get_loaded_feature(MSIPACKAGE* package, LPCWSTR Feature )
345 {
346     int rc = -1;
347     DWORD i;
348
349     for (i = 0; i < package->loaded_features; i++)
350     {
351         if (strcmpW(Feature,package->features[i].Feature)==0)
352         {
353             rc = i;
354             break;
355         }
356     }
357     return rc;
358 }
359
360 inline static int get_loaded_file(MSIPACKAGE* package, LPCWSTR file)
361 {
362     int rc = -1;
363     DWORD i;
364
365     for (i = 0; i < package->loaded_files; i++)
366     {
367         if (strcmpW(file,package->files[i].File)==0)
368         {
369             rc = i;
370             break;
371         }
372     }
373     return rc;
374 }
375
376
377 static int track_tempfile(MSIPACKAGE *package, LPCWSTR name, LPCWSTR path)
378 {
379     DWORD i;
380     DWORD index;
381
382     if (!package)
383         return -2;
384
385     for (i=0; i < package->loaded_files; i++)
386         if (strcmpW(package->files[i].File,name)==0)
387             return -1;
388
389     index = package->loaded_files;
390     package->loaded_files++;
391     if (package->loaded_files== 1)
392         package->files = HeapAlloc(GetProcessHeap(),0,sizeof(MSIFILE));
393     else
394         package->files = HeapReAlloc(GetProcessHeap(),0,
395             package->files , package->loaded_files * sizeof(MSIFILE));
396
397     memset(&package->files[index],0,sizeof(MSIFILE));
398
399     package->files[index].File = dupstrW(name);
400     package->files[index].TargetPath = dupstrW(path);
401     package->files[index].Temporary = TRUE;
402
403     TRACE("Tracking tempfile (%s)\n",debugstr_w(package->files[index].File));  
404
405     return 0;
406 }
407
408 void ACTION_remove_tracked_tempfiles(MSIPACKAGE* package)
409 {
410     DWORD i;
411
412     if (!package)
413         return;
414
415     for (i = 0; i < package->loaded_files; i++)
416     {
417         if (package->files[i].Temporary)
418         {
419             TRACE("Cleaning up %s\n",debugstr_w(package->files[i].TargetPath));
420             DeleteFileW(package->files[i].TargetPath);
421         }
422
423     }
424 }
425
426 /* Called when the package is being closed */
427 extern void ACTION_free_package_structures( MSIPACKAGE* package)
428 {
429     INT i;
430     
431     TRACE("Freeing package action data\n");
432
433     /* No dynamic buffers in features */
434     if (package->features && package->loaded_features > 0)
435         HeapFree(GetProcessHeap(),0,package->features);
436
437     for (i = 0; i < package->loaded_folders; i++)
438     {
439         HeapFree(GetProcessHeap(),0,package->folders[i].Directory);
440         HeapFree(GetProcessHeap(),0,package->folders[i].TargetDefault);
441         HeapFree(GetProcessHeap(),0,package->folders[i].SourceDefault);
442         HeapFree(GetProcessHeap(),0,package->folders[i].ResolvedTarget);
443         HeapFree(GetProcessHeap(),0,package->folders[i].ResolvedSource);
444         HeapFree(GetProcessHeap(),0,package->folders[i].Property);
445     }
446     if (package->folders && package->loaded_folders > 0)
447         HeapFree(GetProcessHeap(),0,package->folders);
448
449     /* no dynamic buffers in components */ 
450     if (package->components && package->loaded_components > 0)
451         HeapFree(GetProcessHeap(),0,package->components);
452
453     for (i = 0; i < package->loaded_files; i++)
454     {
455         HeapFree(GetProcessHeap(),0,package->files[i].File);
456         HeapFree(GetProcessHeap(),0,package->files[i].FileName);
457         HeapFree(GetProcessHeap(),0,package->files[i].Version);
458         HeapFree(GetProcessHeap(),0,package->files[i].Language);
459         HeapFree(GetProcessHeap(),0,package->files[i].SourcePath);
460         HeapFree(GetProcessHeap(),0,package->files[i].TargetPath);
461     }
462
463     if (package->files && package->loaded_files > 0)
464         HeapFree(GetProcessHeap(),0,package->files);
465 }
466
467 static UINT ACTION_OpenQuery( MSIDATABASE *db, MSIQUERY **view, LPCWSTR fmt, ... )
468 {
469     LPWSTR szQuery;
470     LPCWSTR p;
471     UINT sz, rc;
472     va_list va;
473
474     /* figure out how much space we need to allocate */
475     va_start(va, fmt);
476     sz = strlenW(fmt) + 1;
477     p = fmt;
478     while (*p)
479     {
480         p = strchrW(p, '%');
481         if (!p)
482             break;
483         p++;
484         switch (*p)
485         {
486         case 's':  /* a string */
487             sz += strlenW(va_arg(va,LPCWSTR));
488             break;
489         case 'd':
490         case 'i':  /* an integer -2147483648 seems to be longest */
491             sz += 3*sizeof(int);
492             (void)va_arg(va,int);
493             break;
494         case '%':  /* a single % - leave it alone */
495             break;
496         default:
497             FIXME("Unhandled character type %c\n",*p);
498         }
499         p++;
500     }
501     va_end(va);
502
503     /* construct the string */
504     szQuery = HeapAlloc(GetProcessHeap(), 0, sz*sizeof(WCHAR));
505     va_start(va, fmt);
506     vsnprintfW(szQuery, sz, fmt, va);
507     va_end(va);
508
509     /* perform the query */
510     rc = MSI_DatabaseOpenViewW(db, szQuery, view);
511     HeapFree(GetProcessHeap(), 0, szQuery);
512     return rc;
513 }
514
515 static void ui_progress(MSIPACKAGE *package, int a, int b, int c, int d )
516 {
517     MSIRECORD * row;
518
519     row = MSI_CreateRecord(4);
520     MSI_RecordSetInteger(row,1,a);
521     MSI_RecordSetInteger(row,2,b);
522     MSI_RecordSetInteger(row,3,c);
523     MSI_RecordSetInteger(row,4,d);
524     MSI_ProcessMessage(package, INSTALLMESSAGE_PROGRESS, row);
525     msiobj_release(&row->hdr);
526 }
527
528 static void ui_actiondata(MSIPACKAGE *package, LPCWSTR action, MSIRECORD * record)
529 {
530     static const WCHAR Query_t[] = 
531 {'S','E','L','E','C','T',' ','*',' ','f','r','o','m',' ','A','c','t','i','o',
532 'n','T','e','x','t',' ','w','h','e','r','e',' ','A','c','t','i','o','n',' ','=',
533 ' ','\'','%','s','\'',0};
534     WCHAR message[1024];
535     UINT rc;
536     MSIQUERY * view;
537     MSIRECORD * row = 0;
538     LPWSTR ptr;
539
540     if (!package->LastAction || strcmpW(package->LastAction,action))
541     {
542         rc = ACTION_OpenQuery(package->db, &view, Query_t, action);
543         if (rc != ERROR_SUCCESS)
544             return;
545
546         rc = MSI_ViewExecute(view, 0);
547         if (rc != ERROR_SUCCESS)
548         {
549             MSI_ViewClose(view);
550             return;
551         }
552         rc = MSI_ViewFetch(view,&row);
553         if (rc != ERROR_SUCCESS)
554         {
555             MSI_ViewClose(view);
556             return;
557         }
558
559         if (MSI_RecordIsNull(row,3))
560         {
561             msiobj_release(&row->hdr);
562             MSI_ViewClose(view);
563             msiobj_release(&view->hdr);
564             return;
565         }
566
567         /* update the cached actionformat */
568         if (package->ActionFormat)
569             HeapFree(GetProcessHeap(),0,package->ActionFormat);
570         package->ActionFormat = load_dynamic_stringW(row,3);
571
572         if (package->LastAction)
573             HeapFree(GetProcessHeap(),0,package->LastAction);
574         package->LastAction = dupstrW(action);
575
576         msiobj_release(&row->hdr);
577         MSI_ViewClose(view);
578         msiobj_release(&view->hdr);
579     }
580
581     message[0]=0;
582     ptr = package->ActionFormat;
583     while (*ptr)
584     {
585         LPWSTR ptr2;
586         LPWSTR data=NULL;
587         WCHAR tmp[1023];
588         INT field;
589
590         ptr2 = strchrW(ptr,'[');
591         if (ptr2)
592         {
593             strncpyW(tmp,ptr,ptr2-ptr);
594             tmp[ptr2-ptr]=0;
595             strcatW(message,tmp);
596             ptr2++;
597             field = atoiW(ptr2);
598             data = load_dynamic_stringW(record,field);
599             if (data)
600             {
601                 strcatW(message,data);
602                 HeapFree(GetProcessHeap(),0,data);
603             }
604             ptr=strchrW(ptr2,']');
605             ptr++;
606         }
607         else
608         {
609             strcatW(message,ptr);
610             break;
611         }
612     }
613
614     row = MSI_CreateRecord(1);
615     MSI_RecordSetStringW(row,1,message);
616  
617     MSI_ProcessMessage(package, INSTALLMESSAGE_ACTIONDATA, row);
618     msiobj_release(&row->hdr);
619 }
620
621
622 static void ui_actionstart(MSIPACKAGE *package, LPCWSTR action)
623 {
624     static const WCHAR template_s[]=
625 {'A','c','t','i','o','n',' ','%','s',':',' ','%','s','.',' ','%','s','.',0};
626     static const WCHAR format[] = 
627 {'H','H','\'',':','\'','m','m','\'',':','\'','s','s',0};
628     static const WCHAR Query_t[] = 
629 {'S','E','L','E','C','T',' ','*',' ','f','r','o','m',' ','A','c','t','i','o',
630 'n','T','e','x','t',' ','w','h','e','r','e',' ','A','c','t','i','o','n',' ','=',
631 ' ','\'','%','s','\'',0};
632     WCHAR message[1024];
633     WCHAR timet[0x100];
634     UINT rc;
635     MSIQUERY * view;
636     MSIRECORD * row = 0;
637     WCHAR *ActionText=NULL;
638
639     GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, format, timet, 0x100);
640
641     rc = ACTION_OpenQuery(package->db, &view, Query_t, action);
642     if (rc != ERROR_SUCCESS)
643         return;
644     rc = MSI_ViewExecute(view, 0);
645     if (rc != ERROR_SUCCESS)
646     {
647         MSI_ViewClose(view);
648         msiobj_release(&view->hdr);
649         return;
650     }
651     rc = MSI_ViewFetch(view,&row);
652     if (rc != ERROR_SUCCESS)
653     {
654         MSI_ViewClose(view);
655         msiobj_release(&view->hdr);
656         return;
657     }
658
659     ActionText = load_dynamic_stringW(row,2);
660     msiobj_release(&row->hdr);
661     MSI_ViewClose(view);
662     msiobj_release(&view->hdr);
663
664     sprintfW(message,template_s,timet,action,ActionText);
665
666     row = MSI_CreateRecord(1);
667     MSI_RecordSetStringW(row,1,message);
668  
669     MSI_ProcessMessage(package, INSTALLMESSAGE_ACTIONSTART, row);
670     msiobj_release(&row->hdr);
671     HeapFree(GetProcessHeap(),0,ActionText);
672 }
673
674 static void ui_actioninfo(MSIPACKAGE *package, LPCWSTR action, BOOL start, 
675                           UINT rc)
676 {
677     MSIRECORD * row;
678     static const WCHAR template_s[]=
679 {'A','c','t','i','o','n',' ','s','t','a','r','t',' ','%','s',':',' ','%','s',
680 '.',0};
681     static const WCHAR template_e[]=
682 {'A','c','t','i','o','n',' ','e','n','d','e','d',' ','%','s',':',' ','%','s',
683 '.',' ','R','e','t','u','r','n',' ','v','a','l','u','e',' ','%','i','.',0};
684     static const WCHAR format[] = 
685 {'H','H','\'',':','\'','m','m','\'',':','\'','s','s',0};
686     WCHAR message[1024];
687     WCHAR timet[0x100];
688
689     GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, format, timet, 0x100);
690     if (start)
691         sprintfW(message,template_s,timet,action);
692     else
693         sprintfW(message,template_e,timet,action,rc);
694     
695     row = MSI_CreateRecord(1);
696     MSI_RecordSetStringW(row,1,message);
697  
698     MSI_ProcessMessage(package, INSTALLMESSAGE_INFO, row);
699     msiobj_release(&row->hdr);
700 }
701
702 /*
703  *  build_directory_name()
704  *
705  *  This function is to save messing round with directory names
706  *  It handles adding backslashes between path segments, 
707  *   and can add \ at the end of the directory name if told to.
708  *
709  *  It takes a variable number of arguments.
710  *  It always allocates a new string for the result, so make sure
711  *   to free the return value when finished with it.
712  *
713  *  The first arg is the number of path segments that follow.
714  *  The arguments following count are a list of path segments.
715  *  A path segment may be NULL.
716  *
717  *  Path segments will be added with a \ seperating them.
718  *  A \ will not be added after the last segment, however if the
719  *    last segment is NULL, then the last character will be a \
720  * 
721  */
722 static LPWSTR build_directory_name(DWORD count, ...)
723 {
724     DWORD sz = 1, i;
725     LPWSTR dir;
726     va_list va;
727
728     va_start(va,count);
729     for(i=0; i<count; i++)
730     {
731         LPCWSTR str = va_arg(va,LPCWSTR);
732         if (str)
733             sz += strlenW(str) + 1;
734     }
735     va_end(va);
736
737     dir = HeapAlloc(GetProcessHeap(), 0, sz*sizeof(WCHAR));
738     dir[0]=0;
739
740     va_start(va,count);
741     for(i=0; i<count; i++)
742     {
743         LPCWSTR str = va_arg(va,LPCWSTR);
744         if (!str)
745             continue;
746         strcatW(dir, str);
747         if( ((i+1)!=count) && dir[strlenW(dir)-1]!='\\')
748             strcatW(dir, cszbs);
749     }
750     return dir;
751 }
752
753
754 /****************************************************
755  * TOP level entry points 
756  *****************************************************/
757
758 UINT ACTION_DoTopLevelINSTALL(MSIPACKAGE *package, LPCWSTR szPackagePath,
759                               LPCWSTR szCommandLine)
760 {
761     DWORD sz;
762     WCHAR buffer[10];
763     UINT rc;
764     static const WCHAR szUILevel[] = {'U','I','L','e','v','e','l',0};
765
766     if (szPackagePath)   
767     {
768         LPWSTR p, check, path;
769  
770         path = dupstrW(szPackagePath);
771         p = strrchrW(path,'\\');    
772         if (p)
773         {
774             p++;
775             *p=0;
776         }
777
778         check = load_dynamic_property(package, cszSourceDir,NULL);
779         if (!check)
780             MSI_SetPropertyW(package, cszSourceDir, path);
781         else
782             HeapFree(GetProcessHeap(), 0, check);
783
784         HeapFree(GetProcessHeap(), 0, path);
785     }
786
787     if (szCommandLine)
788     {
789         LPWSTR ptr,ptr2;
790         ptr = (LPWSTR)szCommandLine;
791        
792         while (*ptr)
793         {
794             WCHAR *prop = NULL;
795             WCHAR *val = NULL;
796
797             TRACE("Looking at %s\n",debugstr_w(ptr));
798
799             ptr2 = strchrW(ptr,'=');
800             if (ptr2)
801             {
802                 BOOL quote=FALSE;
803                 DWORD len = 0;
804
805                 while (*ptr == ' ') ptr++;
806                 len = ptr2-ptr;
807                 prop = HeapAlloc(GetProcessHeap(),0,(len+1)*sizeof(WCHAR));
808                 strncpyW(prop,ptr,len);
809                 prop[len]=0;
810                 ptr2++;
811            
812                 len = 0; 
813                 ptr = ptr2; 
814                 while (*ptr && (quote || (!quote && *ptr!=' ')))
815                 {
816                     if (*ptr == '"')
817                         quote = !quote;
818                     ptr++;
819                     len++;
820                 }
821                
822                 if (*ptr2=='"')
823                 {
824                     ptr2++;
825                     len -= 2;
826                 }
827                 val = HeapAlloc(GetProcessHeap(),0,(len+1)*sizeof(WCHAR));
828                 strncpyW(val,ptr2,len);
829                 val[len] = 0;
830
831                 if (strlenW(prop) > 0)
832                 {
833                     TRACE("Found commandline property (%s) = (%s)\n", 
834                                        debugstr_w(prop), debugstr_w(val));
835                     MSI_SetPropertyW(package,prop,val);
836                 }
837                 HeapFree(GetProcessHeap(),0,val);
838                 HeapFree(GetProcessHeap(),0,prop);
839             }
840             ptr++;
841         }
842     }
843   
844     sz = 10; 
845     if (MSI_GetPropertyW(package,szUILevel,buffer,&sz) == ERROR_SUCCESS)
846     {
847         if (atoiW(buffer) >= INSTALLUILEVEL_REDUCED)
848         {
849             rc = ACTION_ProcessUISequence(package);
850             if (rc == ERROR_SUCCESS)
851                 rc = ACTION_ProcessExecSequence(package,TRUE);
852         }
853         else
854             rc = ACTION_ProcessExecSequence(package,FALSE);
855     }
856     else
857         rc = ACTION_ProcessExecSequence(package,FALSE);
858
859     /* process the ending type action */
860     if (rc == ERROR_SUCCESS)
861         rc = ACTION_PerformActionSequence(package,-1);
862     else if (rc == ERROR_FUNCTION_FAILED) 
863         rc = ACTION_PerformActionSequence(package,-3);
864     
865     return rc;
866 }
867
868 static UINT ACTION_PerformActionSequence(MSIPACKAGE *package, UINT seq)
869 {
870     MSIQUERY * view;
871     UINT rc;
872     WCHAR buffer[0x100];
873     DWORD sz = 0x100;
874     MSIRECORD * row = 0;
875     static const WCHAR ExecSeqQuery[] =  {
876    's','e','l','e','c','t',' ','*',' ',
877    'f','r','o','m',' ',
878        'I','n','s','t','a','l','l','E','x','e','c','u','t','e',
879        'S','e','q','u','e','n','c','e',' ',
880    'w','h','e','r','e',' ','S','e','q','u','e','n','c','e',' ',
881        '=',' ','%','i',0};
882
883     rc = ACTION_OpenQuery(package->db, &view, ExecSeqQuery, seq);
884
885     if (rc == ERROR_SUCCESS)
886     {
887         rc = MSI_ViewExecute(view, 0);
888
889         if (rc != ERROR_SUCCESS)
890         {
891             MSI_ViewClose(view);
892             msiobj_release(&view->hdr);
893             goto end;
894         }
895        
896         TRACE("Running the actions\n"); 
897
898         rc = MSI_ViewFetch(view,&row);
899         if (rc != ERROR_SUCCESS)
900         {
901             rc = ERROR_SUCCESS;
902             goto end;
903         }
904
905         /* check conditions */
906         if (!MSI_RecordIsNull(row,2))
907         {
908             LPWSTR cond = NULL;
909             cond = load_dynamic_stringW(row,2);
910
911             if (cond)
912             {
913                 /* this is a hack to skip errors in the condition code */
914                 if (MSI_EvaluateConditionW(package, cond) == MSICONDITION_FALSE)
915                 {
916                     HeapFree(GetProcessHeap(),0,cond);
917                     msiobj_release(&row->hdr);
918                     goto end;
919                 }
920                 else
921                     HeapFree(GetProcessHeap(),0,cond);
922             }
923         }
924
925         sz=0x100;
926         rc =  MSI_RecordGetStringW(row,1,buffer,&sz);
927         if (rc != ERROR_SUCCESS)
928         {
929             ERR("Error is %x\n",rc);
930             msiobj_release(&row->hdr);
931             goto end;
932         }
933
934         rc = ACTION_PerformAction(package,buffer);
935         msiobj_release(&row->hdr);
936 end:
937         MSI_ViewClose(view);
938         msiobj_release(&view->hdr);
939     }
940     else
941         rc = ERROR_SUCCESS;
942
943     return rc;
944 }
945
946 static UINT ACTION_ProcessExecSequence(MSIPACKAGE *package, BOOL UIran)
947 {
948     MSIQUERY * view;
949     UINT rc;
950     static const WCHAR ExecSeqQuery[] =  {
951        's','e','l','e','c','t',' ','*',' ',
952        'f','r','o','m',' ',
953            'I','n','s','t','a','l','l','E','x','e','c','u','t','e',
954            'S','e','q','u','e','n','c','e',' ',
955        'w','h','e','r','e',' ','S','e','q','u','e','n','c','e',' ',
956            '>',' ','%','i',' ','o','r','d','e','r',' ',
957        'b','y',' ','S','e','q','u','e','n','c','e',0 };
958     MSIRECORD * row = 0;
959     static const WCHAR IVQuery[] = {
960        's','e','l','e','c','t',' ','S','e','q','u','e','n','c','e',' ',
961        'f','r','o','m',' ','I','n','s','t','a','l','l',
962            'E','x','e','c','u','t','e','S','e','q','u','e','n','c','e',' ',
963        'w','h','e','r','e',' ','A','c','t','i','o','n',' ','=',' ',
964            '`','I','n','s','t','a','l','l','V','a','l','i','d','a','t','e','`',
965        0};
966     INT seq = 0;
967
968     /* get the sequence number */
969     if (UIran)
970     {
971         rc = MSI_DatabaseOpenViewW(package->db, IVQuery, &view);
972         if (rc != ERROR_SUCCESS)
973             return rc;
974         rc = MSI_ViewExecute(view, 0);
975         if (rc != ERROR_SUCCESS)
976         {
977             MSI_ViewClose(view);
978             msiobj_release(&view->hdr);
979             return rc;
980         }
981         rc = MSI_ViewFetch(view,&row);
982         if (rc != ERROR_SUCCESS)
983         {
984             MSI_ViewClose(view);
985             msiobj_release(&view->hdr);
986             return rc;
987         }
988         seq = MSI_RecordGetInteger(row,1);
989         msiobj_release(&row->hdr);
990         MSI_ViewClose(view);
991         msiobj_release(&view->hdr);
992     }
993
994     rc = ACTION_OpenQuery(package->db, &view, ExecSeqQuery, seq);
995     if (rc == ERROR_SUCCESS)
996     {
997         rc = MSI_ViewExecute(view, 0);
998
999         if (rc != ERROR_SUCCESS)
1000         {
1001             MSI_ViewClose(view);
1002             msiobj_release(&view->hdr);
1003             goto end;
1004         }
1005        
1006         TRACE("Running the actions\n"); 
1007
1008         while (1)
1009         {
1010             WCHAR buffer[0x100];
1011             DWORD sz = 0x100;
1012
1013             rc = MSI_ViewFetch(view,&row);
1014             if (rc != ERROR_SUCCESS)
1015             {
1016                 rc = ERROR_SUCCESS;
1017                 break;
1018             }
1019
1020             /* check conditions */
1021             if (!MSI_RecordIsNull(row,2))
1022             {
1023                 LPWSTR cond = NULL;
1024                 cond = load_dynamic_stringW(row,2);
1025
1026                 if (cond)
1027                 {
1028                     /* this is a hack to skip errors in the condition code */
1029                     if (MSI_EvaluateConditionW(package, cond) ==
1030                             MSICONDITION_FALSE)
1031                     {
1032                         HeapFree(GetProcessHeap(),0,cond);
1033                         msiobj_release(&row->hdr);
1034                         continue; 
1035                     }
1036                     else
1037                         HeapFree(GetProcessHeap(),0,cond);
1038                 }
1039             }
1040
1041             sz=0x100;
1042             rc =  MSI_RecordGetStringW(row,1,buffer,&sz);
1043             if (rc != ERROR_SUCCESS)
1044             {
1045                 ERR("Error is %x\n",rc);
1046                 msiobj_release(&row->hdr);
1047                 break;
1048             }
1049
1050             rc = ACTION_PerformAction(package,buffer);
1051
1052             if (rc == ERROR_FUNCTION_NOT_CALLED)
1053                 rc = ERROR_SUCCESS;
1054
1055             if (rc != ERROR_SUCCESS)
1056             {
1057                 ERR("Execution halted due to error (%i)\n",rc);
1058                 msiobj_release(&row->hdr);
1059                 break;
1060             }
1061
1062             msiobj_release(&row->hdr);
1063         }
1064
1065         MSI_ViewClose(view);
1066         msiobj_release(&view->hdr);
1067     }
1068
1069 end:
1070     return rc;
1071 }
1072
1073
1074 static UINT ACTION_ProcessUISequence(MSIPACKAGE *package)
1075 {
1076     MSIQUERY * view;
1077     UINT rc;
1078     static const WCHAR ExecSeqQuery [] = {
1079       's','e','l','e','c','t',' ','*',' ',
1080       'f','r','o','m',' ','I','n','s','t','a','l','l',
1081             'U','I','S','e','q','u','e','n','c','e',' ',
1082       'w','h','e','r','e',' ','S','e','q','u','e','n','c','e',' ', '>',' ','0',' ',
1083       'o','r','d','e','r',' ','b','y',' ','S','e','q','u','e','n','c','e',0};
1084     
1085     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
1086     
1087     if (rc == ERROR_SUCCESS)
1088     {
1089         rc = MSI_ViewExecute(view, 0);
1090
1091         if (rc != ERROR_SUCCESS)
1092         {
1093             MSI_ViewClose(view);
1094             msiobj_release(&view->hdr);
1095             goto end;
1096         }
1097        
1098         TRACE("Running the actions \n"); 
1099
1100         while (1)
1101         {
1102             WCHAR buffer[0x100];
1103             DWORD sz = 0x100;
1104             MSIRECORD * row = 0;
1105
1106             rc = MSI_ViewFetch(view,&row);
1107             if (rc != ERROR_SUCCESS)
1108             {
1109                 rc = ERROR_SUCCESS;
1110                 break;
1111             }
1112
1113             /* check conditions */
1114             if (!MSI_RecordIsNull(row,2))
1115             {
1116                 LPWSTR cond = NULL;
1117                 cond = load_dynamic_stringW(row,2);
1118
1119                 if (cond)
1120                 {
1121                     /* this is a hack to skip errors in the condition code */
1122                     if (MSI_EvaluateConditionW(package, cond) ==
1123                             MSICONDITION_FALSE)
1124                     {
1125                         HeapFree(GetProcessHeap(),0,cond);
1126                         msiobj_release(&row->hdr);
1127                         continue; 
1128                     }
1129                     else
1130                         HeapFree(GetProcessHeap(),0,cond);
1131                 }
1132             }
1133
1134             sz=0x100;
1135             rc =  MSI_RecordGetStringW(row,1,buffer,&sz);
1136             if (rc != ERROR_SUCCESS)
1137             {
1138                 ERR("Error is %x\n",rc);
1139                 msiobj_release(&row->hdr);
1140                 break;
1141             }
1142
1143             rc = ACTION_PerformAction(package,buffer);
1144
1145             if (rc == ERROR_FUNCTION_NOT_CALLED)
1146                 rc = ERROR_SUCCESS;
1147
1148             if (rc != ERROR_SUCCESS)
1149             {
1150                 ERR("Execution halted due to error (%i)\n",rc);
1151                 msiobj_release(&row->hdr);
1152                 break;
1153             }
1154
1155             msiobj_release(&row->hdr);
1156         }
1157
1158         MSI_ViewClose(view);
1159         msiobj_release(&view->hdr);
1160     }
1161
1162 end:
1163     return rc;
1164 }
1165
1166 /********************************************************
1167  * ACTION helper functions and functions that perform the actions
1168  *******************************************************/
1169
1170 /* 
1171  * Alot of actions are really important even if they don't do anything
1172  * explicit.. Lots of properties are set at the beginning of the installation
1173  * CostFinalize does a bunch of work to translated the directories and such
1174  * 
1175  * But until I get write access to the database that is hard, so I am going to
1176  * hack it to see if I can get something to run.
1177  */
1178 UINT ACTION_PerformAction(MSIPACKAGE *package, const WCHAR *action)
1179 {
1180     UINT rc = ERROR_SUCCESS; 
1181
1182     TRACE("Performing action (%s)\n",debugstr_w(action));
1183     ui_actioninfo(package, action, TRUE, 0);
1184     ui_actionstart(package, action);
1185     ui_progress(package,2,1,0,0);
1186
1187     /* pre install, setup and configuration block */
1188     if (strcmpW(action,szLaunchConditions)==0)
1189         rc = ACTION_LaunchConditions(package);
1190     else if (strcmpW(action,szCostInitialize)==0)
1191         rc = ACTION_CostInitialize(package);
1192     else if (strcmpW(action,szFileCost)==0)
1193         rc = ACTION_FileCost(package);
1194     else if (strcmpW(action,szCostFinalize)==0)
1195         rc = ACTION_CostFinalize(package);
1196     else if (strcmpW(action,szInstallValidate)==0)
1197         rc = ACTION_InstallValidate(package);
1198
1199     /* install block */
1200     else if (strcmpW(action,szProcessComponents)==0)
1201         rc = ACTION_ProcessComponents(package);
1202     else if (strcmpW(action,szInstallInitialize)==0)
1203         rc = ACTION_InstallInitialize(package);
1204     else if (strcmpW(action,szCreateFolders)==0)
1205         rc = ACTION_CreateFolders(package);
1206     else if (strcmpW(action,szInstallFiles)==0)
1207         rc = ACTION_InstallFiles(package);
1208     else if (strcmpW(action,szDuplicateFiles)==0)
1209         rc = ACTION_DuplicateFiles(package);
1210     else if (strcmpW(action,szWriteRegistryValues)==0)
1211         rc = ACTION_WriteRegistryValues(package);
1212      else if (strcmpW(action,szRegisterTypeLibraries)==0)
1213         rc = ACTION_RegisterTypeLibraries(package);
1214      else if (strcmpW(action,szRegisterClassInfo)==0)
1215         rc = ACTION_RegisterClassInfo(package);
1216      else if (strcmpW(action,szRegisterProgIdInfo)==0)
1217         rc = ACTION_RegisterProgIdInfo(package);
1218      else if (strcmpW(action,szCreateShortcuts)==0)
1219         rc = ACTION_CreateShortcuts(package);
1220     else if (strcmpW(action,szPublishProduct)==0)
1221         rc = ACTION_PublishProduct(package);
1222
1223     /*
1224      Called during iTunes but unimplemented and seem important
1225
1226      ResolveSource  (sets SourceDir)
1227      RegisterProduct
1228      InstallFinalize
1229      */
1230      else if ((rc = ACTION_CustomAction(package,action)) != ERROR_SUCCESS)
1231      {
1232         FIXME("UNHANDLED MSI ACTION %s\n",debugstr_w(action));
1233         rc = ERROR_FUNCTION_NOT_CALLED;
1234      }
1235
1236     ui_actioninfo(package, action, FALSE, rc);
1237     return rc;
1238 }
1239
1240
1241 static UINT ACTION_CustomAction(MSIPACKAGE *package,const WCHAR *action)
1242 {
1243     UINT rc = ERROR_SUCCESS;
1244     MSIQUERY * view;
1245     MSIRECORD * row = 0;
1246     static const WCHAR ExecSeqQuery[] =
1247     {'s','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','C','u','s','t','o'
1248         ,'m','A','c','t','i','o','n',' ','w','h','e','r','e',' ','`','A','c','t','i'
1249         ,'o','n','`',' ','=',' ','`','%','s','`',0};
1250     UINT type;
1251     LPWSTR source;
1252     LPWSTR target;
1253     WCHAR *deformated=NULL;
1254
1255     rc = ACTION_OpenQuery(package->db, &view, ExecSeqQuery, action);
1256     if (rc != ERROR_SUCCESS)
1257         return rc;
1258
1259     rc = MSI_ViewExecute(view, 0);
1260     if (rc != ERROR_SUCCESS)
1261     {
1262         MSI_ViewClose(view);
1263         msiobj_release(&view->hdr);
1264         return rc;
1265     }
1266
1267     rc = MSI_ViewFetch(view,&row);
1268     if (rc != ERROR_SUCCESS)
1269     {
1270         MSI_ViewClose(view);
1271         msiobj_release(&view->hdr);
1272         return rc;
1273     }
1274
1275     type = MSI_RecordGetInteger(row,2);
1276
1277     source = load_dynamic_stringW(row,3);
1278     target = load_dynamic_stringW(row,4);
1279
1280     TRACE("Handling custom action %s (%x %s %s)\n",debugstr_w(action),type,
1281           debugstr_w(source), debugstr_w(target));
1282
1283     /* we are ignoring ALOT of flags and important synchronization stuff */
1284     switch (type & CUSTOM_ACTION_TYPE_MASK)
1285     {
1286         case 1: /* DLL file stored in a Binary table stream */
1287             rc = HANDLE_CustomType1(package,source,target,type);
1288             break;
1289         case 2: /* EXE file stored in a Binary table strem */
1290             rc = HANDLE_CustomType2(package,source,target,type);
1291             break;
1292         case 18: /*EXE file installed with package */
1293             rc = HANDLE_CustomType18(package,source,target,type);
1294             break;
1295         case 50: /*EXE file specified by a property value */
1296             rc = HANDLE_CustomType50(package,source,target,type);
1297             break;
1298         case 34: /*EXE to be run in specified directory */
1299             rc = HANDLE_CustomType34(package,source,target,type);
1300             break;
1301         case 35: /* Directory set with formatted text. */
1302         case 51: /* Property set with formatted text. */
1303             deformat_string(package,target,&deformated);
1304             rc = MSI_SetPropertyW(package,source,deformated);
1305             HeapFree(GetProcessHeap(),0,deformated);
1306             break;
1307         default:
1308             FIXME("UNHANDLED ACTION TYPE %i (%s %s)\n",
1309              type & CUSTOM_ACTION_TYPE_MASK, debugstr_w(source),
1310              debugstr_w(target));
1311     }
1312
1313     HeapFree(GetProcessHeap(),0,source);
1314     HeapFree(GetProcessHeap(),0,target);
1315     msiobj_release(&row->hdr);
1316     MSI_ViewClose(view);
1317     msiobj_release(&view->hdr);
1318     return rc;
1319 }
1320
1321 static UINT store_binary_to_temp(MSIPACKAGE *package, const LPWSTR source, 
1322                                 LPWSTR tmp_file)
1323 {
1324     DWORD sz=MAX_PATH;
1325
1326     if (MSI_GetPropertyW(package, cszTempFolder, tmp_file, &sz) 
1327         != ERROR_SUCCESS)
1328         GetTempPathW(MAX_PATH,tmp_file);
1329
1330     strcatW(tmp_file,source);
1331
1332     if (GetFileAttributesW(tmp_file) != INVALID_FILE_ATTRIBUTES)
1333     {
1334         TRACE("File already exists\n");
1335         return ERROR_SUCCESS;
1336     }
1337     else
1338     {
1339         /* write out the file */
1340         UINT rc;
1341         MSIQUERY * view;
1342         MSIRECORD * row = 0;
1343         static const WCHAR fmt[] =
1344         {'s','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','B','i'
1345 ,'n','a','r','y',' ','w','h','e','r','e',' ','N','a','m','e','=','`','%','s','`',0};
1346         HANDLE the_file;
1347         CHAR buffer[1024];
1348
1349         if (track_tempfile(package, source, tmp_file)!=0)
1350             FIXME("File Name in temp tracking collision\n");
1351
1352         the_file = CreateFileW(tmp_file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
1353                            FILE_ATTRIBUTE_NORMAL, NULL);
1354     
1355         if (the_file == INVALID_HANDLE_VALUE)
1356             return ERROR_FUNCTION_FAILED;
1357
1358         rc = ACTION_OpenQuery(package->db, &view, fmt, source);
1359         if (rc != ERROR_SUCCESS)
1360             return rc;
1361
1362         rc = MSI_ViewExecute(view, 0);
1363         if (rc != ERROR_SUCCESS)
1364         {
1365             MSI_ViewClose(view);
1366             msiobj_release(&view->hdr);
1367             return rc;
1368         }
1369
1370         rc = MSI_ViewFetch(view,&row);
1371         if (rc != ERROR_SUCCESS)
1372         {
1373             MSI_ViewClose(view);
1374             msiobj_release(&view->hdr);
1375             return rc;
1376         }
1377
1378         do 
1379         {
1380             DWORD write;
1381             sz = 1024;
1382             rc = MSI_RecordReadStream(row,2,buffer,&sz);
1383             if (rc != ERROR_SUCCESS)
1384             {
1385                 ERR("Failed to get stream\n");
1386                 CloseHandle(the_file);  
1387                 DeleteFileW(tmp_file);
1388                 break;
1389             }
1390             WriteFile(the_file,buffer,sz,&write,NULL);
1391         } while (sz == 1024);
1392
1393         CloseHandle(the_file);
1394
1395         msiobj_release(&row->hdr);
1396         MSI_ViewClose(view);
1397         msiobj_release(&view->hdr);
1398     }
1399
1400     return ERROR_SUCCESS;
1401 }
1402
1403 typedef UINT __stdcall CustomEntry(MSIHANDLE);
1404 typedef struct 
1405 {
1406         MSIPACKAGE *package;
1407         WCHAR *target;
1408         WCHAR *source;
1409 } thread_struct;
1410
1411 static DWORD WINAPI DllThread(LPVOID info)
1412 {
1413     HANDLE DLL;
1414     LPSTR proc;
1415     thread_struct *stuff;
1416     CustomEntry *fn;
1417      
1418     stuff = (thread_struct*)info;
1419
1420     TRACE("Asynchronous start (%s, %s) \n", debugstr_w(stuff->source),
1421           debugstr_w(stuff->target));
1422
1423     DLL = LoadLibraryW(stuff->source);
1424     if (DLL)
1425     {
1426         proc = strdupWtoA( stuff->target );
1427         fn = (CustomEntry*)GetProcAddress(DLL,proc);
1428         if (fn)
1429         {
1430             MSIHANDLE hPackage;
1431             MSIPACKAGE *package = stuff->package;
1432
1433             TRACE("Calling function\n");
1434             hPackage = msiobj_findhandle( &package->hdr );
1435             if( !hPackage )
1436                 ERR("Handle for object %p not found\n", package );
1437             fn(hPackage);
1438             msiobj_release( &package->hdr );
1439         }
1440         else
1441             ERR("Cannot load functon\n");
1442
1443         HeapFree(GetProcessHeap(),0,proc);
1444         FreeLibrary(DLL);
1445     }
1446     else
1447         ERR("Unable to load library\n");
1448     msiobj_release( &stuff->package->hdr );
1449     HeapFree(GetProcessHeap(),0,stuff->source);
1450     HeapFree(GetProcessHeap(),0,stuff->target);
1451     HeapFree(GetProcessHeap(), 0, stuff);
1452     return 0;
1453 }
1454
1455 static UINT HANDLE_CustomType1(MSIPACKAGE *package, const LPWSTR source, 
1456                                 const LPWSTR target, const INT type)
1457 {
1458     WCHAR tmp_file[MAX_PATH];
1459     CustomEntry *fn;
1460     HANDLE DLL;
1461     LPSTR proc;
1462
1463     store_binary_to_temp(package, source, tmp_file);
1464
1465     TRACE("Calling function %s from %s\n",debugstr_w(target),
1466           debugstr_w(tmp_file));
1467
1468     if (!strchrW(tmp_file,'.'))
1469     {
1470         static const WCHAR dot[]={'.',0};
1471         strcatW(tmp_file,dot);
1472     } 
1473
1474     if (type & 0xc0)
1475     {
1476         DWORD ThreadId;
1477         HANDLE ThreadHandle;
1478         thread_struct *info = HeapAlloc( GetProcessHeap(), 0, sizeof(*info) );
1479
1480         msiobj_addref( &package->hdr );
1481         info->package = package;
1482         info->target = dupstrW(target);
1483         info->source = dupstrW(tmp_file);
1484         TRACE("Start Asynchronous execution of dll\n");
1485         ThreadHandle = CreateThread(NULL,0,DllThread,(LPVOID)info,0,&ThreadId);
1486         CloseHandle(ThreadHandle);
1487         /* FIXME: release the package if the CreateThread fails */
1488         return ERROR_SUCCESS;
1489     }
1490  
1491     DLL = LoadLibraryW(tmp_file);
1492     if (DLL)
1493     {
1494         proc = strdupWtoA( target );
1495         fn = (CustomEntry*)GetProcAddress(DLL,proc);
1496         if (fn)
1497         {
1498             MSIHANDLE hPackage;
1499
1500             TRACE("Calling function\n");
1501             hPackage = msiobj_findhandle( &package->hdr );
1502             if( !hPackage )
1503                 ERR("Handle for object %p not found\n", package );
1504             fn(hPackage);
1505             msiobj_release( &package->hdr );
1506         }
1507         else
1508             ERR("Cannot load functon\n");
1509
1510         HeapFree(GetProcessHeap(),0,proc);
1511         FreeLibrary(DLL);
1512     }
1513     else
1514         ERR("Unable to load library\n");
1515
1516     return ERROR_SUCCESS;
1517 }
1518
1519 static UINT HANDLE_CustomType2(MSIPACKAGE *package, const LPWSTR source, 
1520                                 const LPWSTR target, const INT type)
1521 {
1522     WCHAR tmp_file[MAX_PATH];
1523     STARTUPINFOW si;
1524     PROCESS_INFORMATION info;
1525     BOOL rc;
1526     INT len;
1527     WCHAR *deformated;
1528     WCHAR *cmd;
1529     static const WCHAR spc[] = {' ',0};
1530
1531     memset(&si,0,sizeof(STARTUPINFOW));
1532
1533     store_binary_to_temp(package, source, tmp_file);
1534
1535     deformat_string(package,target,&deformated);
1536
1537     len = strlenW(tmp_file) + strlenW(deformated) + 2;
1538    
1539     cmd = (WCHAR*)HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*len);
1540
1541     strcpyW(cmd,tmp_file);
1542     strcatW(cmd,spc);
1543     strcatW(cmd,deformated);
1544
1545     HeapFree(GetProcessHeap(),0,deformated);
1546
1547     TRACE("executing exe %s \n",debugstr_w(cmd));
1548
1549     rc = CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL,
1550                   c_collen, &si, &info);
1551
1552     HeapFree(GetProcessHeap(),0,cmd);
1553
1554     if ( !rc )
1555     {
1556         ERR("Unable to execute command\n");
1557         return ERROR_SUCCESS;
1558     }
1559
1560     if (!(type & 0xc0))
1561         WaitForSingleObject(info.hProcess,INFINITE);
1562
1563     CloseHandle( info.hProcess );
1564     CloseHandle( info.hThread );
1565     return ERROR_SUCCESS;
1566 }
1567
1568 static UINT HANDLE_CustomType18(MSIPACKAGE *package, const LPWSTR source, 
1569                                 const LPWSTR target, const INT type)
1570 {
1571     STARTUPINFOW si;
1572     PROCESS_INFORMATION info;
1573     BOOL rc;
1574     WCHAR *deformated;
1575     WCHAR *cmd;
1576     INT len;
1577     static const WCHAR spc[] = {' ',0};
1578     int index;
1579
1580     memset(&si,0,sizeof(STARTUPINFOW));
1581
1582     index = get_loaded_file(package,source);
1583
1584     len = strlenW(package->files[index].TargetPath);
1585
1586     deformat_string(package,target,&deformated);
1587     len += strlenW(deformated);
1588     len += 2;
1589
1590     cmd = (WCHAR*)HeapAlloc(GetProcessHeap(),0,len * sizeof(WCHAR));
1591
1592     strcpyW(cmd, package->files[index].TargetPath);
1593     strcatW(cmd, spc);
1594     strcatW(cmd, deformated);
1595
1596     HeapFree(GetProcessHeap(),0,deformated);
1597
1598     TRACE("executing exe %s \n",debugstr_w(cmd));
1599
1600     rc = CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL,
1601                   c_collen, &si, &info);
1602
1603     HeapFree(GetProcessHeap(),0,cmd);
1604     
1605     if ( !rc )
1606     {
1607         ERR("Unable to execute command\n");
1608         return ERROR_SUCCESS;
1609     }
1610
1611     if (!(type & 0xc0))
1612         WaitForSingleObject(info.hProcess,INFINITE);
1613
1614     CloseHandle( info.hProcess );
1615     CloseHandle( info.hThread );
1616     return ERROR_SUCCESS;
1617 }
1618
1619 static UINT HANDLE_CustomType50(MSIPACKAGE *package, const LPWSTR source, 
1620                                 const LPWSTR target, const INT type)
1621 {
1622     STARTUPINFOW si;
1623     PROCESS_INFORMATION info;
1624     WCHAR *prop;
1625     BOOL rc;
1626     WCHAR *deformated;
1627     WCHAR *cmd;
1628     INT len;
1629     UINT prc;
1630     static const WCHAR spc[] = {' ',0};
1631
1632     memset(&si,0,sizeof(STARTUPINFOW));
1633     memset(&info,0,sizeof(PROCESS_INFORMATION));
1634
1635     prop = load_dynamic_property(package,source,&prc);
1636     if (!prop)
1637         return prc;
1638
1639     deformat_string(package,target,&deformated);
1640     len = strlenW(prop) + strlenW(deformated) + 2;
1641     cmd = (WCHAR*)HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*len);
1642
1643     strcpyW(cmd,prop);
1644     strcatW(cmd,spc);
1645     strcatW(cmd,deformated);
1646
1647     HeapFree(GetProcessHeap(),0,deformated);
1648
1649     TRACE("executing exe %s \n",debugstr_w(cmd));
1650
1651     rc = CreateProcessW(NULL, cmd, NULL, NULL, FALSE, 0, NULL,
1652                   c_collen, &si, &info);
1653
1654     HeapFree(GetProcessHeap(),0,cmd);
1655     
1656     if ( !rc )
1657     {
1658         ERR("Unable to execute command\n");
1659         return ERROR_SUCCESS;
1660     }
1661
1662     if (!(type & 0xc0))
1663         WaitForSingleObject(info.hProcess,INFINITE);
1664
1665     CloseHandle( info.hProcess );
1666     CloseHandle( info.hThread );
1667     return ERROR_SUCCESS;
1668 }
1669
1670 static UINT HANDLE_CustomType34(MSIPACKAGE *package, const LPWSTR source, 
1671                                 const LPWSTR target, const INT type)
1672 {
1673     LPWSTR filename, deformated;
1674     STARTUPINFOW si;
1675     PROCESS_INFORMATION info;
1676     BOOL rc;
1677
1678     memset(&si,0,sizeof(STARTUPINFOW));
1679
1680     filename = resolve_folder(package, source, FALSE, FALSE, NULL);
1681
1682     if (!filename)
1683         return ERROR_FUNCTION_FAILED;
1684
1685     SetCurrentDirectoryW(filename);
1686     HeapFree(GetProcessHeap(),0,filename);
1687
1688     deformat_string(package,target,&deformated);
1689
1690     TRACE("executing exe %s \n",debugstr_w(deformated));
1691
1692     rc = CreateProcessW(NULL, deformated, NULL, NULL, FALSE, 0, NULL,
1693                   c_collen, &si, &info);
1694     HeapFree(GetProcessHeap(),0,deformated);
1695
1696     if ( !rc )
1697     {
1698         ERR("Unable to execute command\n");
1699         return ERROR_SUCCESS;
1700     }
1701
1702     if (!(type & 0xc0))
1703         WaitForSingleObject(info.hProcess,INFINITE);
1704
1705     CloseHandle( info.hProcess );
1706     CloseHandle( info.hThread );
1707     return ERROR_SUCCESS;
1708 }
1709
1710 /***********************************************************************
1711  *            create_full_pathW
1712  *
1713  * Recursively create all directories in the path.
1714  *
1715  * shamelessly stolen from setupapi/queue.c
1716  */
1717 static BOOL create_full_pathW(const WCHAR *path)
1718 {
1719     BOOL ret = TRUE;
1720     int len;
1721     WCHAR *new_path;
1722
1723     new_path = HeapAlloc(GetProcessHeap(), 0, (strlenW(path) + 1) *
1724                                               sizeof(WCHAR));
1725
1726     strcpyW(new_path, path);
1727
1728     while((len = strlenW(new_path)) && new_path[len - 1] == '\\')
1729     new_path[len - 1] = 0;
1730
1731     while(!CreateDirectoryW(new_path, NULL))
1732     {
1733     WCHAR *slash;
1734     DWORD last_error = GetLastError();
1735     if(last_error == ERROR_ALREADY_EXISTS)
1736         break;
1737
1738     if(last_error != ERROR_PATH_NOT_FOUND)
1739     {
1740         ret = FALSE;
1741         break;
1742     }
1743
1744     if(!(slash = strrchrW(new_path, '\\')))
1745     {
1746         ret = FALSE;
1747         break;
1748     }
1749
1750     len = slash - new_path;
1751     new_path[len] = 0;
1752     if(!create_full_pathW(new_path))
1753     {
1754         ret = FALSE;
1755         break;
1756     }
1757     new_path[len] = '\\';
1758     }
1759
1760     HeapFree(GetProcessHeap(), 0, new_path);
1761     return ret;
1762 }
1763
1764 /*
1765  * Also we cannot enable/disable components either, so for now I am just going 
1766  * to do all the directories for all the components.
1767  */
1768 static UINT ACTION_CreateFolders(MSIPACKAGE *package)
1769 {
1770     static const WCHAR ExecSeqQuery[] = {
1771         's','e','l','e','c','t',' ','D','i','r','e','c','t','o','r','y','_',' ',
1772         'f','r','o','m',' ','C','r','e','a','t','e','F','o','l','d','e','r',0 };
1773     UINT rc;
1774     MSIQUERY *view;
1775     MSIFOLDER *folder;
1776
1777     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view );
1778     if (rc != ERROR_SUCCESS)
1779         return ERROR_SUCCESS;
1780
1781     rc = MSI_ViewExecute(view, 0);
1782     if (rc != ERROR_SUCCESS)
1783     {
1784         MSI_ViewClose(view);
1785         msiobj_release(&view->hdr);
1786         return rc;
1787     }
1788     
1789     while (1)
1790     {
1791         WCHAR dir[0x100];
1792         LPWSTR full_path;
1793         DWORD sz;
1794         MSIRECORD *row = NULL, *uirow;
1795
1796         rc = MSI_ViewFetch(view,&row);
1797         if (rc != ERROR_SUCCESS)
1798         {
1799             rc = ERROR_SUCCESS;
1800             break;
1801         }
1802
1803         sz=0x100;
1804         rc = MSI_RecordGetStringW(row,1,dir,&sz);
1805
1806         if (rc!= ERROR_SUCCESS)
1807         {
1808             ERR("Unable to get folder id \n");
1809             msiobj_release(&row->hdr);
1810             continue;
1811         }
1812
1813         sz = MAX_PATH;
1814         full_path = resolve_folder(package,dir,FALSE,FALSE,&folder);
1815         if (!full_path)
1816         {
1817             ERR("Unable to resolve folder id %s\n",debugstr_w(dir));
1818             msiobj_release(&row->hdr);
1819             continue;
1820         }
1821
1822         TRACE("Folder is %s\n",debugstr_w(full_path));
1823
1824         /* UI stuff */
1825         uirow = MSI_CreateRecord(1);
1826         MSI_RecordSetStringW(uirow,1,full_path);
1827         ui_actiondata(package,szCreateFolders,uirow);
1828         msiobj_release( &uirow->hdr );
1829
1830         if (folder->State == 0)
1831             create_full_pathW(full_path);
1832
1833         folder->State = 3;
1834
1835         msiobj_release(&row->hdr);
1836         HeapFree(GetProcessHeap(),0,full_path);
1837     }
1838     MSI_ViewClose(view);
1839     msiobj_release(&view->hdr);
1840    
1841     return rc;
1842 }
1843
1844 static int load_component(MSIPACKAGE* package, MSIRECORD * row)
1845 {
1846     int index = package->loaded_components;
1847     DWORD sz;
1848
1849     /* fill in the data */
1850
1851     package->loaded_components++;
1852     if (package->loaded_components == 1)
1853         package->components = HeapAlloc(GetProcessHeap(),0,
1854                                         sizeof(MSICOMPONENT));
1855     else
1856         package->components = HeapReAlloc(GetProcessHeap(),0,
1857             package->components, package->loaded_components * 
1858             sizeof(MSICOMPONENT));
1859
1860     memset(&package->components[index],0,sizeof(MSICOMPONENT));
1861
1862     sz = 96;       
1863     MSI_RecordGetStringW(row,1,package->components[index].Component,&sz);
1864
1865     TRACE("Loading Component %s\n",
1866            debugstr_w(package->components[index].Component));
1867
1868     sz = 0x100;
1869     if (!MSI_RecordIsNull(row,2))
1870         MSI_RecordGetStringW(row,2,package->components[index].ComponentId,&sz);
1871             
1872     sz = 96;       
1873     MSI_RecordGetStringW(row,3,package->components[index].Directory,&sz);
1874
1875     package->components[index].Attributes = MSI_RecordGetInteger(row,4);
1876
1877     sz = 0x100;       
1878     MSI_RecordGetStringW(row,5,package->components[index].Condition,&sz);
1879
1880     sz = 96;       
1881     MSI_RecordGetStringW(row,6,package->components[index].KeyPath,&sz);
1882
1883     package->components[index].Installed = INSTALLSTATE_ABSENT;
1884     package->components[index].Action = INSTALLSTATE_UNKNOWN;
1885     package->components[index].ActionRequest = INSTALLSTATE_UNKNOWN;
1886
1887     package->components[index].Enabled = TRUE;
1888
1889     return index;
1890 }
1891
1892 static void load_feature(MSIPACKAGE* package, MSIRECORD * row)
1893 {
1894     int index = package->loaded_features;
1895     DWORD sz;
1896     static const WCHAR Query1[] = {'S','E','L','E','C','T',' ','C','o','m','p',
1897         'o','n','e','n','t','_',' ','F','R','O','M',' ','F','e','a','t','u','r','e',
1898         'C','o','m','p','o','n','e','n','t','s',' ','W','H','E','R','E',' ','F','e',
1899         'a','t','u','r','e','_','=','\'','%','s','\'',0};
1900     static const WCHAR Query2[] = {'S','E','L','E','C','T',' ','*',' ','F','R',
1901         'O','M',' ','C','o','m','p','o','n','e','n','t',' ','W','H','E','R','E',' ','C',
1902         'o','m','p','o','n','e','n','t','=','\'','%','s','\'',0};
1903     MSIQUERY * view;
1904     MSIQUERY * view2;
1905     MSIRECORD * row2;
1906     MSIRECORD * row3;
1907     UINT    rc;
1908
1909     /* fill in the data */
1910
1911     package->loaded_features ++;
1912     if (package->loaded_features == 1)
1913         package->features = HeapAlloc(GetProcessHeap(),0,sizeof(MSIFEATURE));
1914     else
1915         package->features = HeapReAlloc(GetProcessHeap(),0,package->features,
1916                                 package->loaded_features * sizeof(MSIFEATURE));
1917
1918     memset(&package->features[index],0,sizeof(MSIFEATURE));
1919     
1920     sz = 96;       
1921     MSI_RecordGetStringW(row,1,package->features[index].Feature,&sz);
1922
1923     TRACE("Loading feature %s\n",debugstr_w(package->features[index].Feature));
1924
1925     sz = 96;
1926     if (!MSI_RecordIsNull(row,2))
1927         MSI_RecordGetStringW(row,2,package->features[index].Feature_Parent,&sz);
1928
1929     sz = 0x100;
1930      if (!MSI_RecordIsNull(row,3))
1931         MSI_RecordGetStringW(row,3,package->features[index].Title,&sz);
1932
1933      sz = 0x100;
1934      if (!MSI_RecordIsNull(row,4))
1935         MSI_RecordGetStringW(row,4,package->features[index].Description,&sz);
1936
1937     if (!MSI_RecordIsNull(row,5))
1938         package->features[index].Display = MSI_RecordGetInteger(row,5);
1939   
1940     package->features[index].Level= MSI_RecordGetInteger(row,6);
1941
1942      sz = 96;
1943      if (!MSI_RecordIsNull(row,7))
1944         MSI_RecordGetStringW(row,7,package->features[index].Directory,&sz);
1945
1946     package->features[index].Attributes= MSI_RecordGetInteger(row,8);
1947
1948     package->features[index].Installed = INSTALLSTATE_ABSENT;
1949     package->features[index].Action = INSTALLSTATE_UNKNOWN;
1950     package->features[index].ActionRequest = INSTALLSTATE_UNKNOWN;
1951
1952     /* load feature components */
1953
1954     rc = ACTION_OpenQuery(package->db, &view, Query1, package->features[index].Feature);
1955     if (rc != ERROR_SUCCESS)
1956         return;
1957     rc = MSI_ViewExecute(view,0);
1958     if (rc != ERROR_SUCCESS)
1959     {
1960         MSI_ViewClose(view);
1961         msiobj_release(&view->hdr);
1962         return;
1963     }
1964     while (1)
1965     {
1966         DWORD sz = 0x100;
1967         WCHAR buffer[0x100];
1968         DWORD rc;
1969         INT c_indx;
1970         INT cnt = package->features[index].ComponentCount;
1971
1972         rc = MSI_ViewFetch(view,&row2);
1973         if (rc != ERROR_SUCCESS)
1974             break;
1975
1976         sz = 0x100;
1977         MSI_RecordGetStringW(row2,1,buffer,&sz);
1978
1979         /* check to see if the component is already loaded */
1980         c_indx = get_loaded_component(package,buffer);
1981         if (c_indx != -1)
1982         {
1983             TRACE("Component %s already loaded at %i\n", debugstr_w(buffer),
1984                   c_indx);
1985             package->features[index].Components[cnt] = c_indx;
1986             package->features[index].ComponentCount ++;
1987             continue;
1988         }
1989
1990         rc = ACTION_OpenQuery(package->db, &view2, Query2, buffer);
1991         if (rc != ERROR_SUCCESS)
1992         {
1993             msiobj_release( &row2->hdr );
1994             continue;
1995         }
1996         rc = MSI_ViewExecute(view2,0);
1997         if (rc != ERROR_SUCCESS)
1998         {
1999             msiobj_release( &row2->hdr );
2000             MSI_ViewClose(view2);
2001             msiobj_release( &view2->hdr );  
2002             continue;
2003         }
2004         while (1)
2005         {
2006             DWORD rc;
2007
2008             rc = MSI_ViewFetch(view2,&row3);
2009             if (rc != ERROR_SUCCESS)
2010                 break;
2011             c_indx = load_component(package,row3);
2012             msiobj_release( &row3->hdr );
2013
2014             package->features[index].Components[cnt] = c_indx;
2015             package->features[index].ComponentCount ++;
2016             TRACE("Loaded new component to index %i\n",c_indx);
2017         }
2018         MSI_ViewClose(view2);
2019         msiobj_release( &view2->hdr );
2020         msiobj_release( &row2->hdr );
2021     }
2022     MSI_ViewClose(view);
2023     msiobj_release(&view->hdr);
2024 }
2025
2026 /*
2027  * I am not doing any of the costing functionality yet. 
2028  * Mostly looking at doing the Component and Feature loading
2029  *
2030  * The native MSI does ALOT of modification to tables here. Mostly adding alot
2031  * of temporary columns to the Feature and Component tables. 
2032  *
2033  *    note: native msi also tracks the short filename. but I am only going to
2034  *          track the long ones.  Also looking at this directory table
2035  *          it appears that the directory table does not get the parents
2036  *          resolved base on property only based on their entrys in the 
2037  *          directory table.
2038  */
2039 static UINT ACTION_CostInitialize(MSIPACKAGE *package)
2040 {
2041     MSIQUERY * view;
2042     MSIRECORD * row;
2043     UINT rc;
2044     static const WCHAR Query_all[] = {
2045        'S','E','L','E','C','T',' ','*',' ',
2046        'F','R','O','M',' ','F','e','a','t','u','r','e',0};
2047     static const WCHAR szCosting[] = {
2048        'C','o','s','t','i','n','g','C','o','m','p','l','e','t','e',0 };
2049     static const WCHAR szZero[] = { '0', 0 };
2050
2051     MSI_SetPropertyW(package, szCosting, szZero);
2052     MSI_SetPropertyW(package, cszRootDrive , c_collen);
2053
2054     rc = MSI_DatabaseOpenViewW(package->db,Query_all,&view);
2055     if (rc != ERROR_SUCCESS)
2056         return rc;
2057     rc = MSI_ViewExecute(view,0);
2058     if (rc != ERROR_SUCCESS)
2059     {
2060         MSI_ViewClose(view);
2061         msiobj_release(&view->hdr);
2062         return rc;
2063     }
2064     while (1)
2065     {
2066         DWORD rc;
2067
2068         rc = MSI_ViewFetch(view,&row);
2069         if (rc != ERROR_SUCCESS)
2070             break;
2071        
2072         load_feature(package,row); 
2073         msiobj_release(&row->hdr);
2074     }
2075     MSI_ViewClose(view);
2076     msiobj_release(&view->hdr);
2077
2078     return ERROR_SUCCESS;
2079 }
2080
2081 static UINT load_file(MSIPACKAGE* package, MSIRECORD * row)
2082 {
2083     DWORD index = package->loaded_files;
2084     DWORD i;
2085     LPWSTR buffer;
2086
2087     /* fill in the data */
2088
2089     package->loaded_files++;
2090     if (package->loaded_files== 1)
2091         package->files = HeapAlloc(GetProcessHeap(),0,sizeof(MSIFILE));
2092     else
2093         package->files = HeapReAlloc(GetProcessHeap(),0,
2094             package->files , package->loaded_files * sizeof(MSIFILE));
2095
2096     memset(&package->files[index],0,sizeof(MSIFILE));
2097  
2098     package->files[index].File = load_dynamic_stringW(row, 1);
2099     buffer = load_dynamic_stringW(row, 2);
2100
2101     package->files[index].ComponentIndex = -1;
2102     for (i = 0; i < package->loaded_components; i++)
2103         if (strcmpW(package->components[i].Component,buffer)==0)
2104         {
2105             package->files[index].ComponentIndex = i;
2106             break;
2107         }
2108     if (package->files[index].ComponentIndex == -1)
2109         ERR("Unfound Component %s\n",debugstr_w(buffer));
2110     HeapFree(GetProcessHeap(), 0, buffer);
2111
2112     package->files[index].FileName = load_dynamic_stringW(row,3);
2113
2114     reduce_to_longfilename(package->files[index].FileName);
2115     
2116     package->files[index].FileSize = MSI_RecordGetInteger(row,4);
2117     package->files[index].Version = load_dynamic_stringW(row, 5);
2118     package->files[index].Language = load_dynamic_stringW(row, 6);
2119     package->files[index].Attributes= MSI_RecordGetInteger(row,7);
2120     package->files[index].Sequence= MSI_RecordGetInteger(row,8);
2121
2122     package->files[index].Temporary = FALSE;
2123     package->files[index].State = 0;
2124
2125     TRACE("File Loaded (%s)\n",debugstr_w(package->files[index].File));  
2126  
2127     return ERROR_SUCCESS;
2128 }
2129
2130 static UINT ACTION_FileCost(MSIPACKAGE *package)
2131 {
2132     MSIQUERY * view;
2133     MSIRECORD * row;
2134     UINT rc;
2135     static const WCHAR Query[] = {
2136         'S','E','L','E','C','T',' ','*',' ',
2137         'F','R','O','M',' ','F','i','l','e',' ',
2138         'O','r','d','e','r',' ','b','y',' ','S','e','q','u','e','n','c','e', 0};
2139
2140     if (!package)
2141         return ERROR_INVALID_HANDLE;
2142
2143     rc = MSI_DatabaseOpenViewW(package->db, Query, &view);
2144     if (rc != ERROR_SUCCESS)
2145         return ERROR_SUCCESS;
2146    
2147     rc = MSI_ViewExecute(view, 0);
2148     if (rc != ERROR_SUCCESS)
2149     {
2150         MSI_ViewClose(view);
2151         msiobj_release(&view->hdr);
2152         return ERROR_SUCCESS;
2153     }
2154
2155     while (1)
2156     {
2157         rc = MSI_ViewFetch(view,&row);
2158         if (rc != ERROR_SUCCESS)
2159         {
2160             rc = ERROR_SUCCESS;
2161             break;
2162         }
2163         load_file(package,row);
2164         msiobj_release(&row->hdr);
2165     }
2166     MSI_ViewClose(view);
2167     msiobj_release(&view->hdr);
2168
2169     return ERROR_SUCCESS;
2170 }
2171
2172 static INT load_folder(MSIPACKAGE *package, const WCHAR* dir)
2173
2174 {
2175     static const WCHAR Query[] =
2176         {'s','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','D','i','r','e','c',
2177          't','o','r','y',' ','w','h','e','r','e',' ','`','D','i','r','e','c','t',
2178          'o','r','y','`',' ','=',' ','`','%','s','`',0};
2179     UINT rc;
2180     MSIQUERY * view;
2181     LPWSTR targetdir, parent, srcdir;
2182     MSIRECORD * row = 0;
2183     INT index = -1;
2184     DWORD i;
2185
2186     TRACE("Looking for dir %s\n",debugstr_w(dir));
2187
2188     for (i = 0; i < package->loaded_folders; i++)
2189     {
2190         if (strcmpW(package->folders[i].Directory,dir)==0)
2191         {
2192             TRACE(" %s retuning on index %lu\n",debugstr_w(dir),i);
2193             return i;
2194         }
2195     }
2196
2197     TRACE("Working to load %s\n",debugstr_w(dir));
2198
2199     index = package->loaded_folders++;
2200     if (package->loaded_folders==1)
2201         package->folders = HeapAlloc(GetProcessHeap(),0,
2202                                         sizeof(MSIFOLDER));
2203     else
2204         package->folders= HeapReAlloc(GetProcessHeap(),0,
2205             package->folders, package->loaded_folders* 
2206             sizeof(MSIFOLDER));
2207
2208     memset(&package->folders[index],0,sizeof(MSIFOLDER));
2209
2210     package->folders[index].Directory = dupstrW(dir);
2211
2212     rc = ACTION_OpenQuery(package->db, &view, Query, dir);
2213     if (rc != ERROR_SUCCESS)
2214         return -1;
2215
2216     rc = MSI_ViewExecute(view, 0);
2217     if (rc != ERROR_SUCCESS)
2218     {
2219         MSI_ViewClose(view);
2220         msiobj_release(&view->hdr);
2221         return -1;
2222     }
2223
2224     rc = MSI_ViewFetch(view,&row);
2225     if (rc != ERROR_SUCCESS)
2226     {
2227         MSI_ViewClose(view);
2228         msiobj_release(&view->hdr);
2229         return -1;
2230     }
2231
2232     targetdir = load_dynamic_stringW(row,3);
2233
2234     /* split src and target dir */
2235     if (strchrW(targetdir,':'))
2236     {
2237         srcdir=strchrW(targetdir,':');
2238         *srcdir=0;
2239         srcdir ++;
2240     }
2241     else
2242         srcdir=NULL;
2243
2244     /* for now only pick long filename versions */
2245     if (strchrW(targetdir,'|'))
2246     {
2247         targetdir = strchrW(targetdir,'|'); 
2248         *targetdir = 0;
2249         targetdir ++;
2250     }
2251     if (srcdir && strchrW(srcdir,'|'))
2252     {
2253         srcdir= strchrW(srcdir,'|'); 
2254         *srcdir= 0;
2255         srcdir ++;
2256     }
2257
2258     /* now check for root dirs */
2259     if (targetdir[0] == '.' && targetdir[1] == 0)
2260         targetdir = NULL;
2261         
2262     if (srcdir && srcdir[0] == '.' && srcdir[1] == 0)
2263         srcdir = NULL;
2264
2265     if (targetdir)
2266     {
2267         TRACE("   TargetDefault = %s\n",debugstr_w(targetdir));
2268         if (package->folders[index].TargetDefault)
2269             HeapFree(GetProcessHeap(),0, package->folders[index].TargetDefault);
2270         package->folders[index].TargetDefault = dupstrW(targetdir);
2271     }
2272
2273     if (srcdir)
2274        package->folders[index].SourceDefault = dupstrW(srcdir);
2275     else if (targetdir)
2276         package->folders[index].SourceDefault = dupstrW(targetdir);
2277     HeapFree(GetProcessHeap(), 0, targetdir);
2278
2279     parent = load_dynamic_stringW(row,2);
2280     if (parent) 
2281     {
2282         i = load_folder(package,parent);
2283         package->folders[index].ParentIndex = i;
2284         TRACE("Parent is index %i... %s %s\n",
2285                     package->folders[index].ParentIndex,
2286         debugstr_w(package->folders[package->folders[index].ParentIndex].Directory),
2287                     debugstr_w(parent));
2288     }
2289     else
2290         package->folders[index].ParentIndex = -2;
2291     HeapFree(GetProcessHeap(), 0, parent);
2292
2293     package->folders[index].Property = load_dynamic_property(package, dir,NULL);
2294
2295     msiobj_release(&row->hdr);
2296     MSI_ViewClose(view);
2297     msiobj_release(&view->hdr);
2298     TRACE(" %s retuning on index %i\n",debugstr_w(dir),index);
2299     return index;
2300 }
2301
2302
2303 static LPWSTR resolve_folder(MSIPACKAGE *package, LPCWSTR name,
2304                            BOOL source, BOOL set_prop, MSIFOLDER **folder)
2305 {
2306     DWORD i;
2307     LPWSTR p, path = NULL;
2308
2309     TRACE("Working to resolve %s\n",debugstr_w(name));
2310
2311     /* special resolving for Target and Source root dir */
2312     if (strcmpW(name,cszTargetDir)==0 || strcmpW(name,cszSourceDir)==0)
2313     {
2314         if (!source)
2315         {
2316             path = load_dynamic_property(package,cszTargetDir,NULL);
2317             if (!path)
2318             {
2319                 path = load_dynamic_property(package,cszRootDrive,NULL);
2320                 if (set_prop)
2321                     MSI_SetPropertyW(package,cszTargetDir,path);
2322             }
2323             if (folder)
2324                 *folder = &(package->folders[0]);
2325             return path;
2326         }
2327         else
2328         {
2329             path = load_dynamic_property(package,cszSourceDir,NULL);
2330             if (!path)
2331             {
2332                 path = load_dynamic_property(package,cszDatabase,NULL);
2333                 if (path)
2334                 {
2335                     p = strrchrW(path,'\\');
2336                     if (p)
2337                         *(p+1) = 0;
2338                 }
2339             }
2340             if (folder)
2341                 *folder = &(package->folders[0]);
2342             return path;
2343         }
2344     }
2345
2346     for (i = 0; i < package->loaded_folders; i++)
2347     {
2348         if (strcmpW(package->folders[i].Directory,name)==0)
2349             break;
2350     }
2351
2352     if (i >= package->loaded_folders)
2353         return NULL;
2354
2355     if (folder)
2356         *folder = &(package->folders[i]);
2357
2358     if (!source && package->folders[i].ResolvedTarget)
2359     {
2360         path = dupstrW(package->folders[i].ResolvedTarget);
2361         TRACE("   already resolved to %s\n",debugstr_w(path));
2362         return path;
2363     }
2364     else if (source && package->folders[i].ResolvedSource)
2365     {
2366         path = dupstrW(package->folders[i].ResolvedSource);
2367         return path;
2368     }
2369     else if (!source && package->folders[i].Property)
2370     {
2371         path = dupstrW(package->folders[i].Property);
2372         TRACE("   internally set to %s\n",debugstr_w(path));
2373         if (set_prop)
2374             MSI_SetPropertyW(package,name,path);
2375         return path;
2376     }
2377
2378     if (package->folders[i].ParentIndex >= 0)
2379     {
2380         LPWSTR parent = package->folders[package->folders[i].ParentIndex].Directory;
2381
2382         TRACE(" ! Parent is %s\n", debugstr_w(parent));
2383
2384         p = resolve_folder(package, parent, source, set_prop, NULL);
2385         if (!source)
2386         {
2387             TRACE("   TargetDefault = %s\n",debugstr_w(package->folders[i].TargetDefault));
2388             path = build_directory_name(3, p, package->folders[i].TargetDefault, NULL);
2389             package->folders[i].ResolvedTarget = dupstrW(path);
2390             TRACE("   resolved into %s\n",debugstr_w(path));
2391             if (set_prop)
2392                 MSI_SetPropertyW(package,name,path);
2393         }
2394         else 
2395         {
2396             path = build_directory_name(3, p, package->folders[i].SourceDefault, NULL);
2397             package->folders[i].ResolvedSource = dupstrW(path);
2398         }
2399         HeapFree(GetProcessHeap(),0,p);
2400     }
2401     return path;
2402 }
2403
2404 static UINT SetFeatureStates(MSIPACKAGE *package)
2405 {
2406     LPWSTR level;
2407     INT install_level;
2408     DWORD i;
2409     INT j;
2410     LPWSTR override = NULL;
2411     static const WCHAR all[]={'A','L','L',0};
2412     static const WCHAR szlevel[] = {
2413         'I','N','S','T','A','L','L','L','E','V','E','L',0};
2414     static const WCHAR szAddLocal[] = {
2415         'A','D','D','L','O','C','A','L',0};
2416
2417     /* I do not know if this is where it should happen.. but */
2418
2419     TRACE("Checking Install Level\n");
2420
2421     level = load_dynamic_property(package,szlevel,NULL);
2422     if (level)
2423     {
2424         install_level = atoiW(level);
2425         HeapFree(GetProcessHeap(), 0, level);
2426     }
2427     else
2428         install_level = 1;
2429
2430     /* ok hereis the rub
2431      * ADDLOCAL and its friend OVERRIDE INSTALLLEVLE
2432      * I have confirmed this if ADDLOCALis stated then the INSTALLLEVEL is
2433      * itnored for all the features. seems strange, epsecially since it is not
2434      * documented anywhere, but it is how it works. 
2435      */
2436     
2437     override = load_dynamic_property(package,szAddLocal,NULL);
2438   
2439     if (override)
2440     {
2441         for(i = 0; i < package->loaded_features; i++)
2442         {
2443             if (strcmpiW(override,all)==0)
2444             {
2445                 package->features[i].ActionRequest= INSTALLSTATE_LOCAL;
2446                 package->features[i].Action = INSTALLSTATE_LOCAL;
2447             }
2448             else
2449             {
2450                 LPWSTR ptr = override;
2451                 LPWSTR ptr2 = strchrW(override,',');
2452
2453                 while (ptr)
2454                 {
2455                     if ((ptr2 && 
2456                         strncmpW(ptr,package->features[i].Feature, ptr2-ptr)==0)
2457                         || (!ptr2 &&
2458                         strcmpW(ptr,package->features[i].Feature)==0))
2459                     {
2460                         package->features[i].ActionRequest= INSTALLSTATE_LOCAL;
2461                         package->features[i].Action = INSTALLSTATE_LOCAL;
2462                         break;
2463                     }
2464                     if (ptr2)
2465                     {
2466                         ptr=ptr2+1;
2467                         ptr2 = strchrW(ptr,',');
2468                     }
2469                     else
2470                         break;
2471                 }
2472             }
2473         }
2474         HeapFree(GetProcessHeap(),0,override);
2475     } 
2476     else
2477     {
2478         for(i = 0; i < package->loaded_features; i++)
2479         {
2480             BOOL feature_state= ((package->features[i].Level > 0) &&
2481                              (package->features[i].Level <= install_level));
2482
2483             if (feature_state)
2484             {
2485                 package->features[i].ActionRequest= INSTALLSTATE_LOCAL;
2486                 package->features[i].Action = INSTALLSTATE_LOCAL;
2487             }
2488         }
2489     }
2490
2491     /*
2492      * now we want to enable or disable components base on feature 
2493     */
2494
2495     for(i = 0; i < package->loaded_features; i++)
2496     {
2497         MSIFEATURE* feature = &package->features[i];
2498         TRACE("Examining Feature %s (Installed %i, Action %i, Request %i)\n",
2499             debugstr_w(feature->Feature), feature->Installed, feature->Action,
2500             feature->ActionRequest);
2501
2502         for( j = 0; j < feature->ComponentCount; j++)
2503         {
2504             MSICOMPONENT* component = &package->components[
2505                                                     feature->Components[j]];
2506
2507             if (!component->Enabled)
2508             {
2509                 component->Action = INSTALLSTATE_ABSENT;
2510                 component->ActionRequest = INSTALLSTATE_ABSENT;
2511             }
2512             else
2513             {
2514                 if (feature->Action == INSTALLSTATE_LOCAL)
2515                     component->Action = INSTALLSTATE_LOCAL;
2516                 if (feature->ActionRequest == INSTALLSTATE_LOCAL)
2517                     component->ActionRequest = INSTALLSTATE_LOCAL;
2518             }
2519         }
2520     } 
2521
2522     for(i = 0; i < package->loaded_components; i++)
2523     {
2524         MSICOMPONENT* component= &package->components[i];
2525
2526         TRACE("Result: Component %s (Installed %i, Action %i, Request %i)\n",
2527             debugstr_w(component->Component), component->Installed, 
2528             component->Action, component->ActionRequest);
2529     }
2530
2531
2532     return ERROR_SUCCESS;
2533 }
2534
2535 /* 
2536  * Alot is done in this function aside from just the costing.
2537  * The costing needs to be implemented at some point but for now I am going
2538  * to focus on the directory building
2539  *
2540  */
2541 static UINT ACTION_CostFinalize(MSIPACKAGE *package)
2542 {
2543     static const WCHAR ExecSeqQuery[] = {
2544         's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ',
2545         'D','i','r','e','c','t','o','r','y',0};
2546     static const WCHAR ConditionQuery[] = {
2547         's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ',
2548         'C','o','n','d','i','t','i','o','n',0};
2549     static const WCHAR szCosting[] = {
2550        'C','o','s','t','i','n','g','C','o','m','p','l','e','t','e',0 };
2551     static const WCHAR szlevel[] = {
2552         'I','N','S','T','A','L','L','L','E','V','E','L',0};
2553     static const WCHAR szOne[] = { '1', 0 };
2554     UINT rc;
2555     MSIQUERY * view;
2556     DWORD i;
2557     LPWSTR level;
2558
2559     TRACE("Building Directory properties\n");
2560
2561     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
2562     if (rc == ERROR_SUCCESS)
2563     {
2564         rc = MSI_ViewExecute(view, 0);
2565         if (rc != ERROR_SUCCESS)
2566         {
2567             MSI_ViewClose(view);
2568             msiobj_release(&view->hdr);
2569             return rc;
2570         }
2571
2572         while (1)
2573         {
2574             WCHAR name[0x100];
2575             LPWSTR path;
2576             MSIRECORD * row = 0;
2577             DWORD sz;
2578
2579             rc = MSI_ViewFetch(view,&row);
2580             if (rc != ERROR_SUCCESS)
2581             {
2582                 rc = ERROR_SUCCESS;
2583                 break;
2584             }
2585
2586             sz=0x100;
2587             MSI_RecordGetStringW(row,1,name,&sz);
2588
2589             /* This helper function now does ALL the work */
2590             TRACE("Dir %s ...\n",debugstr_w(name));
2591             load_folder(package,name);
2592             path = resolve_folder(package,name,FALSE,TRUE,NULL);
2593             TRACE("resolves to %s\n",debugstr_w(path));
2594             HeapFree( GetProcessHeap(), 0, path);
2595
2596             msiobj_release(&row->hdr);
2597         }
2598         MSI_ViewClose(view);
2599         msiobj_release(&view->hdr);
2600     }
2601
2602     TRACE("File calculations %i files\n",package->loaded_files);
2603
2604     for (i = 0; i < package->loaded_files; i++)
2605     {
2606         MSICOMPONENT* comp = NULL;
2607         MSIFILE* file= NULL;
2608
2609         file = &package->files[i];
2610         if (file->ComponentIndex >= 0)
2611             comp = &package->components[file->ComponentIndex];
2612
2613         if (file->Temporary == TRUE)
2614             continue;
2615
2616         if (comp)
2617         {
2618             LPWSTR p;
2619
2620             /* calculate target */
2621             p = resolve_folder(package, comp->Directory, FALSE, FALSE, NULL);
2622
2623             if (file->TargetPath)
2624                 HeapFree(GetProcessHeap(),0,file->TargetPath);
2625
2626             TRACE("file %s is named %s\n",
2627                    debugstr_w(file->File),debugstr_w(file->FileName));       
2628
2629             file->TargetPath = build_directory_name(2, p, file->FileName);
2630
2631             HeapFree(GetProcessHeap(),0,p);
2632
2633             TRACE("file %s resolves to %s\n",
2634                    debugstr_w(file->File),debugstr_w(file->TargetPath));       
2635
2636             if (GetFileAttributesW(file->TargetPath) == INVALID_FILE_ATTRIBUTES)
2637             {
2638                 file->State = 1;
2639                 comp->Cost += file->FileSize;
2640             }
2641             else
2642             {
2643                 if (file->Version)
2644                 {
2645                     DWORD handle;
2646                     DWORD versize;
2647                     UINT sz;
2648                     LPVOID version;
2649                     static const WCHAR name[] = 
2650                     {'\\',0};
2651                     static const WCHAR name_fmt[] = 
2652                     {'%','u','.','%','u','.','%','u','.','%','u',0};
2653                     WCHAR filever[0x100];
2654                     VS_FIXEDFILEINFO *lpVer;
2655
2656                     FIXME("Version comparison.. \n");
2657                     versize = GetFileVersionInfoSizeW(file->TargetPath,&handle);
2658                     version = HeapAlloc(GetProcessHeap(),0,versize);
2659                     GetFileVersionInfoW(file->TargetPath, 0, versize, version);
2660
2661                     VerQueryValueW(version, name, (LPVOID*)&lpVer, &sz);
2662
2663                     sprintfW(filever,name_fmt,
2664                         HIWORD(lpVer->dwFileVersionMS),
2665                         LOWORD(lpVer->dwFileVersionMS),
2666                         HIWORD(lpVer->dwFileVersionLS),
2667                         LOWORD(lpVer->dwFileVersionLS));
2668
2669                     TRACE("new %s old %s\n", debugstr_w(file->Version),
2670                           debugstr_w(filever));
2671                     if (strcmpiW(filever,file->Version)<0)
2672                     {
2673                         file->State = 2;
2674                         FIXME("cost should be diff in size\n");
2675                         comp->Cost += file->FileSize;
2676                     }
2677                     else
2678                         file->State = 3;
2679                     HeapFree(GetProcessHeap(),0,version);
2680                 }
2681                 else
2682                     file->State = 3;
2683             }
2684         } 
2685     }
2686
2687     TRACE("Evaluating Condition Table\n");
2688
2689     rc = MSI_DatabaseOpenViewW(package->db, ConditionQuery, &view);
2690     if (rc == ERROR_SUCCESS)
2691     {
2692     rc = MSI_ViewExecute(view, 0);
2693     if (rc != ERROR_SUCCESS)
2694     {
2695         MSI_ViewClose(view);
2696         msiobj_release(&view->hdr);
2697         return rc;
2698     }
2699     
2700     while (1)
2701     {
2702         WCHAR Feature[0x100];
2703         MSIRECORD * row = 0;
2704         DWORD sz;
2705         int feature_index;
2706
2707         rc = MSI_ViewFetch(view,&row);
2708
2709         if (rc != ERROR_SUCCESS)
2710         {
2711             rc = ERROR_SUCCESS;
2712             break;
2713         }
2714
2715         sz = 0x100;
2716         MSI_RecordGetStringW(row,1,Feature,&sz);
2717
2718         feature_index = get_loaded_feature(package,Feature);
2719         if (feature_index < 0)
2720             ERR("FAILED to find loaded feature %s\n",debugstr_w(Feature));
2721         else
2722         {
2723             LPWSTR Condition;
2724             Condition = load_dynamic_stringW(row,3);
2725
2726                 if (MSI_EvaluateConditionW(package,Condition) == 
2727                     MSICONDITION_TRUE)
2728             {
2729                 int level = MSI_RecordGetInteger(row,2);
2730                     TRACE("Reseting feature %s to level %i\n",
2731                            debugstr_w(Feature), level);
2732                 package->features[feature_index].Level = level;
2733             }
2734             HeapFree(GetProcessHeap(),0,Condition);
2735         }
2736
2737         msiobj_release(&row->hdr);
2738     }
2739     MSI_ViewClose(view);
2740     msiobj_release(&view->hdr);
2741     }
2742
2743     TRACE("Enabling or Disabling Components\n");
2744     for (i = 0; i < package->loaded_components; i++)
2745     {
2746         if (package->components[i].Condition[0])
2747         {
2748             if (MSI_EvaluateConditionW(package,
2749                 package->components[i].Condition) == MSICONDITION_FALSE)
2750             {
2751                 TRACE("Disabling component %s\n",
2752                       debugstr_w(package->components[i].Component));
2753                 package->components[i].Enabled = FALSE;
2754             }
2755         }
2756     }
2757
2758     MSI_SetPropertyW(package,szCosting,szOne);
2759     /* set default run level if not set */
2760     level = load_dynamic_property(package,szlevel,NULL);
2761     if (!level)
2762         MSI_SetPropertyW(package,szlevel, szOne);
2763     else
2764         HeapFree(GetProcessHeap(),0,level);
2765
2766     return SetFeatureStates(package);
2767
2768 }
2769
2770 /*
2771  * This is a helper function for handling embedded cabinet media
2772  */
2773 static UINT writeout_cabinet_stream(MSIPACKAGE *package, WCHAR* stream_name,
2774                                     WCHAR* source)
2775 {
2776     UINT rc;
2777     USHORT* data;
2778     UINT    size;
2779     DWORD   write;
2780     HANDLE  the_file;
2781     WCHAR tmp[MAX_PATH];
2782
2783     rc = read_raw_stream_data(package->db,stream_name,&data,&size); 
2784     if (rc != ERROR_SUCCESS)
2785         return rc;
2786
2787     write = MAX_PATH;
2788     if (MSI_GetPropertyW(package, cszTempFolder, tmp, &write))
2789         GetTempPathW(MAX_PATH,tmp);
2790
2791     GetTempFileNameW(tmp,stream_name,0,source);
2792
2793     track_tempfile(package,strrchrW(source,'\\'), source);
2794     the_file = CreateFileW(source, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
2795                            FILE_ATTRIBUTE_NORMAL, NULL);
2796
2797     if (the_file == INVALID_HANDLE_VALUE)
2798     {
2799         rc = ERROR_FUNCTION_FAILED;
2800         goto end;
2801     }
2802
2803     WriteFile(the_file,data,size,&write,NULL);
2804     CloseHandle(the_file);
2805     TRACE("wrote %li bytes to %s\n",write,debugstr_w(source));
2806 end:
2807     HeapFree(GetProcessHeap(),0,data);
2808     return rc;
2809 }
2810
2811
2812 /* Support functions for FDI functions */
2813 typedef struct
2814 {
2815     MSIPACKAGE* package;
2816     LPCSTR cab_path;
2817 } CabData;
2818
2819 static void * cabinet_alloc(ULONG cb)
2820 {
2821     return HeapAlloc(GetProcessHeap(), 0, cb);
2822 }
2823
2824 static void cabinet_free(void *pv)
2825 {
2826     HeapFree(GetProcessHeap(), 0, pv);
2827 }
2828
2829 static INT_PTR cabinet_open(char *pszFile, int oflag, int pmode)
2830 {
2831     DWORD dwAccess = 0;
2832     DWORD dwShareMode = 0;
2833     DWORD dwCreateDisposition = OPEN_EXISTING;
2834     switch (oflag & _O_ACCMODE)
2835     {
2836     case _O_RDONLY:
2837         dwAccess = GENERIC_READ;
2838         dwShareMode = FILE_SHARE_READ | FILE_SHARE_DELETE;
2839         break;
2840     case _O_WRONLY:
2841         dwAccess = GENERIC_WRITE;
2842         dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
2843         break;
2844     case _O_RDWR:
2845         dwAccess = GENERIC_READ | GENERIC_WRITE;
2846         dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
2847         break;
2848     }
2849     if ((oflag & (_O_CREAT | _O_EXCL)) == (_O_CREAT | _O_EXCL))
2850         dwCreateDisposition = CREATE_NEW;
2851     else if (oflag & _O_CREAT)
2852         dwCreateDisposition = CREATE_ALWAYS;
2853     return (INT_PTR)CreateFileA(pszFile, dwAccess, dwShareMode, NULL, dwCreateDisposition, 0, NULL);
2854 }
2855
2856 static UINT cabinet_read(INT_PTR hf, void *pv, UINT cb)
2857 {
2858     DWORD dwRead;
2859     if (ReadFile((HANDLE)hf, pv, cb, &dwRead, NULL))
2860         return dwRead;
2861     return 0;
2862 }
2863
2864 static UINT cabinet_write(INT_PTR hf, void *pv, UINT cb)
2865 {
2866     DWORD dwWritten;
2867     if (WriteFile((HANDLE)hf, pv, cb, &dwWritten, NULL))
2868         return dwWritten;
2869     return 0;
2870 }
2871
2872 static int cabinet_close(INT_PTR hf)
2873 {
2874     return CloseHandle((HANDLE)hf) ? 0 : -1;
2875 }
2876
2877 static long cabinet_seek(INT_PTR hf, long dist, int seektype)
2878 {
2879     /* flags are compatible and so are passed straight through */
2880     return SetFilePointer((HANDLE)hf, dist, NULL, seektype);
2881 }
2882
2883 static INT_PTR cabinet_notify(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
2884 {
2885     /* FIXME: try to do more processing in this function */
2886     switch (fdint)
2887     {
2888     case fdintCOPY_FILE:
2889     {
2890         CabData *data = (CabData*) pfdin->pv;
2891         ULONG len = strlen(data->cab_path) + strlen(pfdin->psz1);
2892         char *file = cabinet_alloc((len+1)*sizeof(char));
2893
2894         LPWSTR trackname;
2895         LPWSTR trackpath;
2896         LPWSTR tracknametmp;
2897         static const WCHAR tmpprefix[] = {'C','A','B','T','M','P','_',0};
2898         
2899         strcpy(file, data->cab_path);
2900         strcat(file, pfdin->psz1);
2901
2902         TRACE("file: %s\n", debugstr_a(file));
2903
2904         /* track this file so it can be deleted if not installed */
2905         trackpath=strdupAtoW(file);
2906         tracknametmp=strdupAtoW(strrchr(file,'\\')+1);
2907         trackname = HeapAlloc(GetProcessHeap(),0,(strlenW(tracknametmp) + 
2908                                   strlenW(tmpprefix)+1) * sizeof(WCHAR));
2909
2910         strcpyW(trackname,tmpprefix);
2911         strcatW(trackname,tracknametmp);
2912
2913         track_tempfile(data->package, trackname, trackpath);
2914
2915         HeapFree(GetProcessHeap(),0,trackpath);
2916         HeapFree(GetProcessHeap(),0,trackname);
2917         HeapFree(GetProcessHeap(),0,tracknametmp);
2918
2919         return cabinet_open(file, _O_WRONLY | _O_CREAT, 0);
2920     }
2921     case fdintCLOSE_FILE_INFO:
2922     {
2923         FILETIME ft;
2924             FILETIME ftLocal;
2925         if (!DosDateTimeToFileTime(pfdin->date, pfdin->time, &ft))
2926             return -1;
2927         if (!LocalFileTimeToFileTime(&ft, &ftLocal))
2928             return -1;
2929         if (!SetFileTime((HANDLE)pfdin->hf, &ftLocal, 0, &ftLocal))
2930             return -1;
2931
2932         cabinet_close(pfdin->hf);
2933         return 1;
2934     }
2935     default:
2936         return 0;
2937     }
2938 }
2939
2940 /***********************************************************************
2941  *            extract_cabinet_file
2942  *
2943  * Extract files from a cab file.
2944  */
2945 static BOOL extract_cabinet_file(MSIPACKAGE* package, const WCHAR* source, 
2946                                  const WCHAR* path)
2947 {
2948     HFDI hfdi;
2949     ERF erf;
2950     BOOL ret;
2951     char *cabinet;
2952     char *cab_path;
2953     CabData data;
2954
2955     TRACE("Extracting %s to %s\n",debugstr_w(source), debugstr_w(path));
2956
2957     hfdi = FDICreate(cabinet_alloc,
2958                      cabinet_free,
2959                      cabinet_open,
2960                      cabinet_read,
2961                      cabinet_write,
2962                      cabinet_close,
2963                      cabinet_seek,
2964                      0,
2965                      &erf);
2966     if (!hfdi)
2967     {
2968         ERR("FDICreate failed\n");
2969         return FALSE;
2970     }
2971
2972     if (!(cabinet = strdupWtoA( source )))
2973     {
2974         FDIDestroy(hfdi);
2975         return FALSE;
2976     }
2977     if (!(cab_path = strdupWtoA( path )))
2978     {
2979         FDIDestroy(hfdi);
2980         HeapFree(GetProcessHeap(), 0, cabinet);
2981         return FALSE;
2982     }
2983
2984     data.package = package;
2985     data.cab_path = cab_path;
2986
2987     ret = FDICopy(hfdi, cabinet, "", 0, cabinet_notify, NULL, &data);
2988
2989     if (!ret)
2990         ERR("FDICopy failed\n");
2991
2992     FDIDestroy(hfdi);
2993
2994     HeapFree(GetProcessHeap(), 0, cabinet);
2995     HeapFree(GetProcessHeap(), 0, cab_path);
2996
2997     return ret;
2998 }
2999
3000 static UINT ready_media_for_file(MSIPACKAGE *package, UINT sequence, 
3001                                  WCHAR* path)
3002 {
3003     UINT rc;
3004     MSIQUERY * view;
3005     MSIRECORD * row = 0;
3006     WCHAR source[MAX_PATH];
3007     static const WCHAR ExecSeqQuery[] = {
3008         's','e','l','e','c','t',' ','*',' ',
3009         'f','r','o','m',' ','M','e','d','i','a',' ',
3010         'w','h','e','r','e',' ','L','a','s','t','S','e','q','u','e','n','c','e',' ','>','=',' ','%','i',' ',
3011         'o','r','d','e','r',' ','b','y',' ','L','a','s','t','S','e','q','u','e','n','c','e',0};
3012     WCHAR Query[1024];
3013     WCHAR cab[0x100];
3014     DWORD sz=0x100;
3015     INT seq;
3016     static UINT last_sequence = 0; 
3017
3018     if (sequence <= last_sequence)
3019     {
3020         TRACE("Media already ready (%u, %u)\n",sequence,last_sequence);
3021         return ERROR_SUCCESS;
3022     }
3023
3024     sprintfW(Query,ExecSeqQuery,sequence);
3025
3026     rc = MSI_DatabaseOpenViewW(package->db, Query, &view);
3027     if (rc != ERROR_SUCCESS)
3028         return rc;
3029
3030     rc = MSI_ViewExecute(view, 0);
3031     if (rc != ERROR_SUCCESS)
3032     {
3033         MSI_ViewClose(view);
3034         msiobj_release(&view->hdr);
3035         return rc;
3036     }
3037
3038     rc = MSI_ViewFetch(view,&row);
3039     if (rc != ERROR_SUCCESS)
3040     {
3041         MSI_ViewClose(view);
3042         msiobj_release(&view->hdr);
3043         return rc;
3044     }
3045     seq = MSI_RecordGetInteger(row,2);
3046     last_sequence = seq;
3047
3048     if (!MSI_RecordIsNull(row,4))
3049     {
3050         sz=0x100;
3051         MSI_RecordGetStringW(row,4,cab,&sz);
3052         TRACE("Source is CAB %s\n",debugstr_w(cab));
3053         /* the stream does not contain the # character */
3054         if (cab[0]=='#')
3055         {
3056             writeout_cabinet_stream(package,&cab[1],source);
3057             strcpyW(path,source);
3058             *(strrchrW(path,'\\')+1)=0;
3059         }
3060         else
3061         {
3062             sz = MAX_PATH;
3063             if (MSI_GetPropertyW(package, cszSourceDir, source, &sz))
3064             {
3065                 ERR("No Source dir defined \n");
3066                 rc = ERROR_FUNCTION_FAILED;
3067             }
3068             else
3069             {
3070                 strcpyW(path,source);
3071                 strcatW(source,cab);
3072                 /* extract the cab file into a folder in the temp folder */
3073                 sz = MAX_PATH;
3074                 if (MSI_GetPropertyW(package, cszTempFolder,path, &sz) 
3075                                     != ERROR_SUCCESS)
3076                     GetTempPathW(MAX_PATH,path);
3077             }
3078         }
3079         rc = !extract_cabinet_file(package, source,path);
3080     }
3081     msiobj_release(&row->hdr);
3082     MSI_ViewClose(view);
3083     msiobj_release(&view->hdr);
3084     return rc;
3085 }
3086
3087 inline static UINT create_component_directory ( MSIPACKAGE* package, INT component)
3088 {
3089     UINT rc;
3090     MSIFOLDER *folder;
3091     LPWSTR install_path;
3092
3093     install_path = resolve_folder(package, package->components[component].Directory,
3094                         FALSE, FALSE, &folder);
3095     if (!install_path)
3096         return ERROR_FUNCTION_FAILED; 
3097
3098     /* create the path */
3099     if (folder->State == 0)
3100     {
3101         create_full_pathW(install_path);
3102         folder->State = 2;
3103     }
3104     HeapFree(GetProcessHeap(), 0, install_path);
3105
3106     return rc;
3107 }
3108
3109 static UINT ACTION_InstallFiles(MSIPACKAGE *package)
3110 {
3111     UINT rc = ERROR_SUCCESS;
3112     DWORD index;
3113     MSIRECORD * uirow;
3114     WCHAR uipath[MAX_PATH];
3115
3116     if (!package)
3117         return ERROR_INVALID_HANDLE;
3118
3119     /* increment progress bar each time action data is sent */
3120     ui_progress(package,1,1,1,0);
3121
3122     for (index = 0; index < package->loaded_files; index++)
3123     {
3124         WCHAR path_to_source[MAX_PATH];
3125         MSIFILE *file;
3126         
3127         file = &package->files[index];
3128
3129         if (file->Temporary)
3130             continue;
3131
3132         if (package->components[file->ComponentIndex].ActionRequest != 
3133              INSTALLSTATE_LOCAL)
3134         {
3135             TRACE("File %s is not scheduled for install\n",
3136                    debugstr_w(file->File));
3137
3138             continue;
3139         }
3140
3141         if ((file->State == 1) || (file->State == 2))
3142         {
3143             TRACE("Installing %s\n",debugstr_w(file->File));
3144             rc = ready_media_for_file(package,file->Sequence,path_to_source);
3145             /* 
3146              * WARNING!
3147              * our file table could change here because a new temp file
3148              * may have been created
3149              */
3150             file = &package->files[index];
3151             if (rc != ERROR_SUCCESS)
3152             {
3153                 ERR("Unable to ready media\n");
3154                 rc = ERROR_FUNCTION_FAILED;
3155                 break;
3156             }
3157
3158             create_component_directory( package, file->ComponentIndex);
3159
3160             strcpyW(file->SourcePath, path_to_source);
3161             strcatW(file->SourcePath, file->File);
3162
3163             TRACE("file paths %s to %s\n",debugstr_w(file->SourcePath),
3164                   debugstr_w(file->TargetPath));
3165
3166             /* the UI chunk */
3167             uirow=MSI_CreateRecord(9);
3168             MSI_RecordSetStringW(uirow,1,file->File);
3169             strcpyW(uipath,file->TargetPath);
3170             *(strrchrW(uipath,'\\')+1)=0;
3171             MSI_RecordSetStringW(uirow,9,uipath);
3172             MSI_RecordSetInteger(uirow,6,file->FileSize);
3173             ui_actiondata(package,szInstallFiles,uirow);
3174             msiobj_release( &uirow->hdr );
3175
3176             if (!MoveFileW(file->SourcePath,file->TargetPath))
3177             {
3178                 rc = GetLastError();
3179                 ERR("Unable to move file (%s -> %s) (error %d)\n",
3180                      debugstr_w(file->SourcePath), debugstr_w(file->TargetPath),
3181                       rc);
3182                 if (rc == ERROR_ALREADY_EXISTS && file->State == 2)
3183                 {
3184                     CopyFileW(file->SourcePath,file->TargetPath,FALSE);
3185                     DeleteFileW(file->SourcePath);
3186                     rc = 0;
3187                 }
3188                 else if (rc == ERROR_FILE_NOT_FOUND)
3189                 {
3190                     ERR("Source File Not Found!  Continueing\n");
3191                     rc = 0;
3192                 }
3193                 else
3194                 {
3195                     ERR("Ignoring Error and continuing...\n");
3196                     rc = 0;
3197                 }
3198             }
3199             else
3200                 file->State = 4;
3201
3202             ui_progress(package,2,0,0,0);
3203         }
3204     }
3205
3206     return rc;
3207 }
3208
3209 inline static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
3210                                    LPWSTR* file_source)
3211 {
3212     DWORD index;
3213
3214     if (!package)
3215         return ERROR_INVALID_HANDLE;
3216
3217     for (index = 0; index < package->loaded_files; index ++)
3218     {
3219         if (strcmpW(file_key,package->files[index].File)==0)
3220         {
3221             if (package->files[index].State >= 3)
3222             {
3223                 *file_source = dupstrW(package->files[index].TargetPath);
3224                 return ERROR_SUCCESS;
3225             }
3226             else
3227                 return ERROR_FILE_NOT_FOUND;
3228         }
3229     }
3230
3231     return ERROR_FUNCTION_FAILED;
3232 }
3233
3234 static UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
3235 {
3236     UINT rc;
3237     MSIQUERY * view;
3238     MSIRECORD * row = 0;
3239     static const WCHAR ExecSeqQuery[] = {
3240         's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ',
3241         'D','u','p','l','i','c','a','t','e','F','i','l','e',0};
3242
3243     if (!package)
3244         return ERROR_INVALID_HANDLE;
3245
3246     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
3247     if (rc != ERROR_SUCCESS)
3248         return ERROR_SUCCESS;
3249
3250     rc = MSI_ViewExecute(view, 0);
3251     if (rc != ERROR_SUCCESS)
3252     {
3253         MSI_ViewClose(view);
3254         msiobj_release(&view->hdr);
3255         return rc;
3256     }
3257
3258     while (1)
3259     {
3260         WCHAR file_key[0x100];
3261         WCHAR *file_source = NULL;
3262         WCHAR dest_name[0x100];
3263         LPWSTR dest_path, dest;
3264         WCHAR component[0x100];
3265         INT component_index;
3266
3267         DWORD sz=0x100;
3268
3269         rc = MSI_ViewFetch(view,&row);
3270         if (rc != ERROR_SUCCESS)
3271         {
3272             rc = ERROR_SUCCESS;
3273             break;
3274         }
3275
3276         sz=0x100;
3277         rc = MSI_RecordGetStringW(row,2,component,&sz);
3278         if (rc != ERROR_SUCCESS)
3279         {
3280             ERR("Unable to get component\n");
3281             msiobj_release(&row->hdr);
3282             break;
3283         }
3284
3285         component_index = get_loaded_component(package,component);
3286         if (package->components[component_index].ActionRequest != 
3287              INSTALLSTATE_LOCAL)
3288         {
3289             TRACE("Skipping copy due to disabled component\n");
3290             msiobj_release(&row->hdr);
3291             continue;
3292         }
3293
3294         sz=0x100;
3295         rc = MSI_RecordGetStringW(row,3,file_key,&sz);
3296         if (rc != ERROR_SUCCESS)
3297         {
3298             ERR("Unable to get file key\n");
3299             msiobj_release(&row->hdr);
3300             break;
3301         }
3302
3303         rc = get_file_target(package,file_key,&file_source);
3304
3305         if (rc != ERROR_SUCCESS)
3306         {
3307             ERR("Original file unknown %s\n",debugstr_w(file_key));
3308             msiobj_release(&row->hdr);
3309             if (file_source)
3310                 HeapFree(GetProcessHeap(),0,file_source);
3311             break;
3312         }
3313
3314         if (MSI_RecordIsNull(row,4))
3315         {
3316             strcpyW(dest_name,strrchrW(file_source,'\\')+1);
3317         }
3318         else
3319         {
3320             sz=0x100;
3321             MSI_RecordGetStringW(row,4,dest_name,&sz);
3322             reduce_to_longfilename(dest_name);
3323          }
3324
3325         if (MSI_RecordIsNull(row,5))
3326         {
3327             LPWSTR p;
3328             dest_path = dupstrW(file_source);
3329             p = strrchrW(dest_path,'\\');
3330             if (p)
3331                 *p=0;
3332         }
3333         else
3334         {
3335             WCHAR destkey[0x100];
3336             sz=0x100;
3337             MSI_RecordGetStringW(row,5,destkey,&sz);
3338             sz = 0x100;
3339             dest_path = resolve_folder(package, destkey, FALSE,FALSE,NULL);
3340             if (!dest_path)
3341             {
3342                 ERR("Unable to get destination folder\n");
3343                 msiobj_release(&row->hdr);
3344                 if (file_source)
3345                     HeapFree(GetProcessHeap(),0,file_source);
3346                 break;
3347             }
3348         }
3349
3350         dest = build_directory_name(2, dest_path, dest_name);
3351         HeapFree(GetProcessHeap(), 0, dest_path);
3352            
3353         TRACE("Duplicating file %s to %s\n",debugstr_w(file_source),
3354               debugstr_w(dest)); 
3355         
3356         if (strcmpW(file_source,dest))
3357             rc = !CopyFileW(file_source,dest,TRUE);
3358         else
3359             rc = ERROR_SUCCESS;
3360         
3361         if (rc != ERROR_SUCCESS)
3362             ERR("Failed to copy file\n");
3363
3364         FIXME("We should track these duplicate files as well\n");   
3365  
3366         msiobj_release(&row->hdr);
3367         HeapFree(GetProcessHeap(),0,dest);
3368         HeapFree(GetProcessHeap(),0,file_source);
3369     }
3370     MSI_ViewClose(view);
3371     msiobj_release(&view->hdr);
3372     return rc;
3373 }
3374
3375
3376 /* OK this value is "interpretted" and then formatted based on the 
3377    first few characters */
3378 static LPSTR parse_value(MSIPACKAGE *package, WCHAR *value, DWORD *type, 
3379                          DWORD *size)
3380 {
3381     LPSTR data = NULL;
3382     if (value[0]=='#' && value[1]!='#' && value[1]!='%')
3383     {
3384         if (value[1]=='x')
3385         {
3386             LPWSTR ptr;
3387             CHAR byte[5];
3388             LPWSTR deformated;
3389             int count;
3390
3391             deformat_string(package, &value[2], &deformated);
3392
3393             /* binary value type */
3394             ptr = deformated; 
3395             *type=REG_BINARY;
3396             *size = strlenW(ptr)/2;
3397             data = HeapAlloc(GetProcessHeap(),0,*size);
3398           
3399             byte[0] = '0'; 
3400             byte[1] = 'x'; 
3401             byte[4] = 0; 
3402             count = 0;
3403             while (*ptr)
3404             {
3405                 byte[2]= *ptr;
3406                 ptr++;
3407                 byte[3]= *ptr;
3408                 ptr++;
3409                 data[count] = (BYTE)strtol(byte,NULL,0);
3410                 count ++;
3411             }
3412             HeapFree(GetProcessHeap(),0,deformated);
3413
3414             TRACE("Data %li bytes(%i)\n",*size,count);
3415         }
3416         else
3417         {
3418             LPWSTR deformated;
3419             deformat_string(package, &value[1], &deformated);
3420
3421             *type=REG_DWORD; 
3422             *size = sizeof(DWORD);
3423             data = HeapAlloc(GetProcessHeap(),0,*size);
3424             *(LPDWORD)data = atoiW(deformated); 
3425             TRACE("DWORD %i\n",*data);
3426
3427             HeapFree(GetProcessHeap(),0,deformated);
3428         }
3429     }
3430     else
3431     {
3432         WCHAR *ptr;
3433         *type=REG_SZ;
3434
3435         if (value[0]=='#')
3436         {
3437             if (value[1]=='%')
3438             {
3439                 ptr = &value[2];
3440                 *type=REG_EXPAND_SZ;
3441             }
3442             else
3443                 ptr = &value[1];
3444          }
3445          else
3446             ptr=value;
3447
3448         *size = deformat_string(package, ptr,(LPWSTR*)&data);
3449     }
3450     return data;
3451 }
3452
3453 static UINT ACTION_WriteRegistryValues(MSIPACKAGE *package)
3454 {
3455     UINT rc;
3456     MSIQUERY * view;
3457     MSIRECORD * row = 0;
3458     static const WCHAR ExecSeqQuery[] = {
3459         's','e','l','e','c','t',' ','*',' ',
3460         'f','r','o','m',' ','R','e','g','i','s','t','r','y',0 };
3461
3462     if (!package)
3463         return ERROR_INVALID_HANDLE;
3464
3465     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
3466     if (rc != ERROR_SUCCESS)
3467         return ERROR_SUCCESS;
3468
3469     rc = MSI_ViewExecute(view, 0);
3470     if (rc != ERROR_SUCCESS)
3471     {
3472         MSI_ViewClose(view);
3473         msiobj_release(&view->hdr);
3474         return rc;
3475     }
3476
3477     /* increment progress bar each time action data is sent */
3478     ui_progress(package,1,1,1,0);
3479
3480     while (1)
3481     {
3482         static const WCHAR szHCR[] = 
3483 {'H','K','E','Y','_','C','L','A','S','S','E','S','_','R','O','O','T','\\',0};
3484         static const WCHAR szHCU[] =
3485 {'H','K','E','Y','_','C','U','R','R','E','N','T','_','U','S','E','R','\\',0};
3486         static const WCHAR szHLM[] =
3487 {'H','K','E','Y','_','L','O','C','A','L','_','M','A','C','H','I','N','E',
3488 '\\',0};
3489         static const WCHAR szHU[] =
3490 {'H','K','E','Y','_','U','S','E','R','S','\\',0};
3491
3492         LPSTR value_data = NULL;
3493         HKEY  root_key, hkey;
3494         DWORD type,size;
3495         LPWSTR value, key, name, component;
3496         LPCWSTR szRoot;
3497         INT component_index;
3498         MSIRECORD * uirow;
3499         LPWSTR uikey;
3500         INT   root;
3501
3502         rc = MSI_ViewFetch(view,&row);
3503         if (rc != ERROR_SUCCESS)
3504         {
3505             rc = ERROR_SUCCESS;
3506             break;
3507         }
3508
3509         value = NULL;
3510         key = NULL;
3511         uikey = NULL;
3512         name = NULL;
3513
3514         component = load_dynamic_stringW(row, 6);
3515         component_index = get_loaded_component(package,component);
3516
3517         if (package->components[component_index].ActionRequest != 
3518              INSTALLSTATE_LOCAL)
3519         {
3520             TRACE("Skipping write due to disabled component\n");
3521             msiobj_release(&row->hdr);
3522             goto next;
3523         }
3524
3525         /* null values have special meanings during uninstalls and such */
3526         
3527         if(MSI_RecordIsNull(row,5))
3528         {
3529             msiobj_release(&row->hdr);
3530             goto next;
3531         }
3532
3533         root = MSI_RecordGetInteger(row,2);
3534         key = load_dynamic_stringW(row, 3);
3535       
3536         name = load_dynamic_stringW(row, 4);
3537    
3538         /* get the root key */
3539         switch (root)
3540         {
3541             case 0:  root_key = HKEY_CLASSES_ROOT; 
3542                      szRoot = szHCR;
3543                      break;
3544             case 1:  root_key = HKEY_CURRENT_USER;
3545                      szRoot = szHCU;
3546                      break;
3547             case 2:  root_key = HKEY_LOCAL_MACHINE;
3548                      szRoot = szHLM;
3549                      break;
3550             case 3:  root_key = HKEY_USERS; 
3551                      szRoot = szHU;
3552                      break;
3553             default:
3554                  ERR("Unknown root %i\n",root);
3555                  root_key=NULL;
3556                  szRoot = NULL;
3557                  break;
3558         }
3559         if (!root_key)
3560         {
3561             msiobj_release(&row->hdr);
3562             goto next;
3563         }
3564
3565         size = strlenW(key) + strlenW(szRoot) + 1;
3566         uikey = HeapAlloc(GetProcessHeap(), 0, size*sizeof(WCHAR));
3567         strcpyW(uikey,szRoot);
3568         strcatW(uikey,key);
3569         if (RegCreateKeyW( root_key, key, &hkey))
3570         {
3571             ERR("Could not create key %s\n",debugstr_w(key));
3572             msiobj_release(&row->hdr);
3573             goto next;
3574         }
3575
3576         value = load_dynamic_stringW(row,5);
3577         value_data = parse_value(package, value, &type, &size); 
3578
3579         if (value_data)
3580         {
3581             TRACE("Setting value %s\n",debugstr_w(name));
3582             RegSetValueExW(hkey, name, 0, type, value_data, size);
3583
3584             uirow = MSI_CreateRecord(3);
3585             MSI_RecordSetStringW(uirow,2,name);
3586             MSI_RecordSetStringW(uirow,1,uikey);
3587
3588             if (type == REG_SZ)
3589                 MSI_RecordSetStringW(uirow,3,(LPWSTR)value_data);
3590             else
3591                 MSI_RecordSetStringW(uirow,3,value);
3592
3593             ui_actiondata(package,szWriteRegistryValues,uirow);
3594             ui_progress(package,2,0,0,0);
3595             msiobj_release( &uirow->hdr );
3596
3597             HeapFree(GetProcessHeap(),0,value_data);
3598         }
3599         HeapFree(GetProcessHeap(),0,value);
3600
3601         msiobj_release(&row->hdr);
3602         RegCloseKey(hkey);
3603 next:
3604         if (uikey)
3605             HeapFree(GetProcessHeap(),0,uikey);
3606         if (key)
3607             HeapFree(GetProcessHeap(),0,key);
3608         if (name)
3609             HeapFree(GetProcessHeap(),0,name);
3610         if (component)
3611             HeapFree(GetProcessHeap(),0,component);
3612     }
3613     MSI_ViewClose(view);
3614     msiobj_release(&view->hdr);
3615     return rc;
3616 }
3617
3618 /*
3619  * This helper function should probably go alot of places
3620  *
3621  * Thinking about this, maybe this should become yet another Bison file
3622  */
3623 static DWORD deformat_string(MSIPACKAGE *package, WCHAR* ptr,WCHAR** data)
3624 {
3625     WCHAR* mark=NULL;
3626     DWORD size=0;
3627     DWORD chunk=0;
3628     WCHAR key[0x100];
3629     LPWSTR value;
3630     DWORD sz;
3631     UINT rc;
3632
3633     if (ptr==NULL)
3634     {
3635         TRACE("Deformatting NULL string\n");
3636         *data = NULL;
3637         return 0;
3638     }
3639     /* scan for special characters */
3640     if (!strchrW(ptr,'[') || (strchrW(ptr,'[') && !strchrW(ptr,']')))
3641     {
3642         /* not formatted */
3643         size = (strlenW(ptr)+1) * sizeof(WCHAR);
3644         *data = HeapAlloc(GetProcessHeap(),0,size);
3645         strcpyW(*data,ptr);
3646         return size;
3647     }
3648    
3649     /* formatted string located */ 
3650     mark = strchrW(ptr,'[');
3651     if (mark != ptr)
3652     {
3653         INT cnt = (mark - ptr);
3654         TRACE("%i  (%i) characters before marker\n",cnt,(mark-ptr));
3655         size = cnt * sizeof(WCHAR);
3656         size += sizeof(WCHAR);
3657         *data = HeapAlloc(GetProcessHeap(),0,size);
3658         strncpyW(*data,ptr,cnt);
3659         (*data)[cnt]=0;
3660     }
3661     else
3662     {
3663         size = sizeof(WCHAR);
3664         *data = HeapAlloc(GetProcessHeap(),0,size);
3665         (*data)[0]=0;
3666     }
3667     mark++;
3668     strcpyW(key,mark);
3669     *strchrW(key,']')=0;
3670     mark = strchrW(mark,']');
3671     mark++;
3672     TRACE("Current %s .. %s\n",debugstr_w(*data),debugstr_w(mark));
3673     sz = 0;
3674     rc = MSI_GetPropertyW(package, key, NULL, &sz);
3675     if ((rc == ERROR_SUCCESS) || (rc == ERROR_MORE_DATA))
3676     {
3677         LPWSTR newdata;
3678
3679         sz++;
3680         value = HeapAlloc(GetProcessHeap(),0,sz * sizeof(WCHAR));
3681         MSI_GetPropertyW(package, key, value, &sz);
3682
3683         chunk = (strlenW(value)+1) * sizeof(WCHAR);
3684         size+=chunk;   
3685         newdata = HeapReAlloc(GetProcessHeap(),0,*data,size);
3686         *data = newdata;
3687         strcatW(*data,value);
3688     }
3689     TRACE("Current %s .. %s\n",debugstr_w(*data),debugstr_w(mark));
3690     if (*mark!=0)
3691     {
3692         LPWSTR newdata;
3693         chunk = (strlenW(mark)+1) * sizeof(WCHAR);
3694         size+=chunk;
3695         newdata = HeapReAlloc(GetProcessHeap(),0,*data,size);
3696         *data = newdata;
3697         strcatW(*data,mark);
3698     }
3699     (*data)[strlenW(*data)]=0;
3700     TRACE("Current %s .. %s\n",debugstr_w(*data),debugstr_w(mark));
3701
3702     /* recursively do this to clean up */
3703     mark = HeapAlloc(GetProcessHeap(),0,size);
3704     strcpyW(mark,*data);
3705     TRACE("String at this point %s\n",debugstr_w(mark));
3706     size = deformat_string(package,mark,data);
3707     HeapFree(GetProcessHeap(),0,mark);
3708     return size;
3709 }
3710
3711 static UINT ACTION_InstallInitialize(MSIPACKAGE *package)
3712 {
3713     return ERROR_SUCCESS;
3714 }
3715
3716
3717 static UINT ACTION_InstallValidate(MSIPACKAGE *package)
3718 {
3719     DWORD progress = 0;
3720     static const WCHAR q1[]={
3721         'S','E','L','E','C','T',' ','*',' ',
3722         'F','R','O','M',' ','R','e','g','i','s','t','r','y',0};
3723     UINT rc;
3724     MSIQUERY * view;
3725     MSIRECORD * row = 0;
3726
3727     TRACE(" InstallValidate \n");
3728
3729     rc = MSI_DatabaseOpenViewW(package->db, q1, &view);
3730     if (rc != ERROR_SUCCESS)
3731         return ERROR_SUCCESS;
3732
3733     rc = MSI_ViewExecute(view, 0);
3734     if (rc != ERROR_SUCCESS)
3735     {
3736         MSI_ViewClose(view);
3737         msiobj_release(&view->hdr);
3738         return rc;
3739     }
3740     while (1)
3741     {
3742         rc = MSI_ViewFetch(view,&row);
3743         if (rc != ERROR_SUCCESS)
3744         {
3745             rc = ERROR_SUCCESS;
3746             break;
3747         }
3748         progress +=1;
3749
3750         msiobj_release(&row->hdr);
3751     }
3752     MSI_ViewClose(view);
3753     msiobj_release(&view->hdr);
3754
3755     ui_progress(package,0,progress+package->loaded_files,0,0);
3756
3757     return ERROR_SUCCESS;
3758 }
3759
3760 static UINT ACTION_LaunchConditions(MSIPACKAGE *package)
3761 {
3762     UINT rc;
3763     MSIQUERY * view = NULL;
3764     MSIRECORD * row = 0;
3765     static const WCHAR ExecSeqQuery[] = {
3766         'S','E','L','E','C','T',' ','*',' ',
3767         'f','r','o','m',' ','L','a','u','n','c','h','C','o','n','d','i','t','i','o','n',0};
3768     static const WCHAR title[]=
3769             {'I','n','s','t','a','l','l',' ','F','a', 'i','l','e','d',0};
3770
3771     TRACE("Checking launch conditions\n");
3772
3773     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
3774     if (rc != ERROR_SUCCESS)
3775         return ERROR_SUCCESS;
3776
3777     rc = MSI_ViewExecute(view, 0);
3778     if (rc != ERROR_SUCCESS)
3779     {
3780         MSI_ViewClose(view);
3781         msiobj_release(&view->hdr);
3782         return rc;
3783     }
3784
3785     rc = ERROR_SUCCESS;
3786     while (rc == ERROR_SUCCESS)
3787     {
3788         LPWSTR cond = NULL; 
3789         LPWSTR message = NULL;
3790
3791         rc = MSI_ViewFetch(view,&row);
3792         if (rc != ERROR_SUCCESS)
3793         {
3794             rc = ERROR_SUCCESS;
3795             break;
3796         }
3797
3798         cond = load_dynamic_stringW(row,1);
3799
3800         if (MSI_EvaluateConditionW(package,cond) != MSICONDITION_TRUE)
3801         {
3802             message = load_dynamic_stringW(row,2);
3803             MessageBoxW(NULL,message,title,MB_OK);
3804             HeapFree(GetProcessHeap(),0,message);
3805             rc = ERROR_FUNCTION_FAILED;
3806         }
3807         HeapFree(GetProcessHeap(),0,cond);
3808         msiobj_release(&row->hdr);
3809     }
3810     MSI_ViewClose(view);
3811     msiobj_release(&view->hdr);
3812     return rc;
3813 }
3814
3815 static LPWSTR resolve_keypath( MSIPACKAGE* package, INT
3816                             component_index)
3817 {
3818     MSICOMPONENT* cmp = &package->components[component_index];
3819
3820     if (cmp->KeyPath[0]==0)
3821     {
3822         LPWSTR p = resolve_folder(package,cmp->Directory,FALSE,FALSE,NULL);
3823         return p;
3824     }
3825     if ((cmp->Attributes & 0x4) || (cmp->Attributes & 0x20))
3826     {
3827         FIXME("UNIMPLEMENTED keypath as Registry or ODBC Source\n");
3828         return NULL;
3829     }
3830     else
3831     {
3832         int j;
3833         j = get_loaded_file(package,cmp->KeyPath);
3834
3835         if (j>=0)
3836         {
3837             LPWSTR p = dupstrW(package->files[j].TargetPath);
3838             return p;
3839         }
3840     }
3841     return NULL;
3842 }
3843
3844 /*
3845  * Ok further analysis makes me think that this work is
3846  * actually done in the PublishComponents and PublishFeatures
3847  * step, and not here.  It appears like the keypath and all that is
3848  * resolved in this step, however actually written in the Publish steps.
3849  * But we will leave it here for now because it is unclear
3850  */
3851 static UINT ACTION_ProcessComponents(MSIPACKAGE *package)
3852 {
3853     LPWSTR productcode;
3854     WCHAR squished_pc[0x100];
3855     WCHAR squished_cc[0x100];
3856     UINT rc;
3857     DWORD i;
3858     HKEY hkey=0,hkey2=0,hkey3=0;
3859     static const WCHAR szProductCode[]=
3860          {'P','r','o','d','u','c','t','C','o','d','e',0};
3861     static const WCHAR szInstaller[] = {
3862          'S','o','f','t','w','a','r','e','\\',
3863          'M','i','c','r','o','s','o','f','t','\\',
3864          'W','i','n','d','o','w','s','\\',
3865          'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3866          'I','n','s','t','a','l','l','e','r',0 };
3867     static const WCHAR szFeatures[] = {
3868          'F','e','a','t','u','r','e','s',0 };
3869     static const WCHAR szComponents[] = {
3870          'C','o','m','p','o','n','e','n','t','s',0 };
3871
3872     if (!package)
3873         return ERROR_INVALID_HANDLE;
3874
3875     /* writes the Component and Features values to the registry */
3876     productcode = load_dynamic_property(package,szProductCode,&rc);
3877     if (!productcode)
3878         return rc;
3879
3880     squash_guid(productcode,squished_pc);
3881     rc = RegCreateKeyW(HKEY_LOCAL_MACHINE,szInstaller,&hkey);
3882     if (rc != ERROR_SUCCESS)
3883         goto end;
3884
3885     rc = RegCreateKeyW(hkey,szFeatures,&hkey2);
3886     if (rc != ERROR_SUCCESS)
3887         goto end;
3888
3889     rc = RegCreateKeyW(hkey2,squished_pc,&hkey3);
3890     if (rc != ERROR_SUCCESS)
3891         goto end;
3892
3893     /* here the guids are base 85 encoded */
3894     for (i = 0; i < package->loaded_features; i++)
3895     {
3896         LPWSTR data = NULL;
3897         GUID clsid;
3898         int j;
3899         INT size;
3900
3901         size = package->features[i].ComponentCount*21*sizeof(WCHAR);
3902         data = HeapAlloc(GetProcessHeap(), 0, size);
3903
3904         data[0] = 0;
3905         for (j = 0; j < package->features[i].ComponentCount; j++)
3906         {
3907             WCHAR buf[21];
3908             TRACE("From %s\n",debugstr_w(package->components
3909                             [package->features[i].Components[j]].ComponentId));
3910             CLSIDFromString(package->components
3911                             [package->features[i].Components[j]].ComponentId,
3912                             &clsid);
3913             encode_base85_guid(&clsid,buf);
3914             TRACE("to %s\n",debugstr_w(buf));
3915             strcatW(data,buf);
3916         }
3917
3918         size = strlenW(data)*sizeof(WCHAR);
3919         RegSetValueExW(hkey3,package->features[i].Feature,0,REG_SZ,
3920                        (LPSTR)data,size);
3921         HeapFree(GetProcessHeap(),0,data);
3922     }
3923
3924     RegCloseKey(hkey3);
3925     RegCloseKey(hkey2);
3926
3927     rc = RegCreateKeyW(hkey,szComponents,&hkey2);
3928     if (rc != ERROR_SUCCESS)
3929         goto end;
3930   
3931     for (i = 0; i < package->loaded_components; i++)
3932     {
3933         if (package->components[i].ComponentId[0]!=0)
3934         {
3935             WCHAR *keypath = NULL;
3936             MSIRECORD * uirow;
3937
3938             squash_guid(package->components[i].ComponentId,squished_cc);
3939             rc = RegCreateKeyW(hkey2,squished_cc,&hkey3);
3940             if (rc != ERROR_SUCCESS)
3941                 continue;
3942            
3943             keypath = resolve_keypath(package,i);
3944             if (keypath)
3945             {
3946                 RegSetValueExW(hkey3,squished_pc,0,REG_SZ,(LPVOID)keypath,
3947                             (strlenW(keypath)+1)*sizeof(WCHAR));
3948                 RegCloseKey(hkey3);
3949         
3950                 /* UI stuff */
3951                 uirow = MSI_CreateRecord(3);
3952                 MSI_RecordSetStringW(uirow,1,productcode);
3953                 MSI_RecordSetStringW(uirow,2,package->components[i].
3954                                                         ComponentId);
3955                 MSI_RecordSetStringW(uirow,3,keypath);
3956                 ui_actiondata(package,szProcessComponents,uirow);
3957                 msiobj_release( &uirow->hdr );
3958                 HeapFree(GetProcessHeap(),0,keypath);
3959             }
3960         }
3961     } 
3962 end:
3963     HeapFree(GetProcessHeap(), 0, productcode);
3964     RegCloseKey(hkey2);
3965     RegCloseKey(hkey);
3966     return rc;
3967 }
3968
3969 static UINT ACTION_RegisterTypeLibraries(MSIPACKAGE *package)
3970 {
3971     /* 
3972      * OK this is a bit confusing.. I am given a _Component key and I believe
3973      * that the file that is being registered as a type library is the "key file
3974      * of that component" which I interpret to mean "The file in the KeyPath of
3975      * that component".
3976      */
3977     UINT rc;
3978     MSIQUERY * view;
3979     MSIRECORD * row = 0;
3980     static const WCHAR Query[] = {
3981         'S','E','L','E','C','T',' ','*',' ',
3982         'f','r','o','m',' ','T','y','p','e','L','i','b',0};
3983     ITypeLib *ptLib;
3984     HRESULT res;
3985
3986     if (!package)
3987         return ERROR_INVALID_HANDLE;
3988
3989     rc = MSI_DatabaseOpenViewW(package->db, Query, &view);
3990     if (rc != ERROR_SUCCESS)
3991         return ERROR_SUCCESS;
3992
3993     rc = MSI_ViewExecute(view, 0);
3994     if (rc != ERROR_SUCCESS)
3995     {
3996         MSI_ViewClose(view);
3997         msiobj_release(&view->hdr);
3998         return rc;
3999     }
4000
4001     while (1)
4002     {   
4003         WCHAR component[0x100];
4004         DWORD sz;
4005         INT index;
4006
4007         rc = MSI_ViewFetch(view,&row);
4008         if (rc != ERROR_SUCCESS)
4009         {
4010             rc = ERROR_SUCCESS;
4011             break;
4012         }
4013
4014         sz = 0x100;
4015         MSI_RecordGetStringW(row,3,component,&sz);
4016
4017         index = get_loaded_component(package,component);
4018         if (index < 0)
4019         {
4020             msiobj_release(&row->hdr);
4021             continue;
4022         }
4023
4024         if (package->components[index].ActionRequest != INSTALLSTATE_LOCAL)
4025         {
4026             TRACE("Skipping typelib reg due to disabled component\n");
4027             msiobj_release(&row->hdr);
4028             continue;
4029         }
4030
4031         index = get_loaded_file(package,package->components[index].KeyPath); 
4032    
4033         if (index < 0)
4034         {
4035             msiobj_release(&row->hdr);
4036             continue;
4037         }
4038
4039         res = LoadTypeLib(package->files[index].TargetPath,&ptLib);
4040         if (SUCCEEDED(res))
4041         {
4042             LPWSTR help;
4043             WCHAR helpid[0x100];
4044
4045             sz = 0x100;
4046             MSI_RecordGetStringW(row,6,helpid,&sz);
4047
4048             help = resolve_folder(package,helpid,FALSE,FALSE,NULL);
4049             res = RegisterTypeLib(ptLib,package->files[index].TargetPath,help);
4050             HeapFree(GetProcessHeap(),0,help);
4051
4052             if (!SUCCEEDED(res))
4053                 ERR("Failed to register type library %s\n",
4054                      debugstr_w(package->files[index].TargetPath));
4055             else
4056             {
4057                 /* Yes the row has more fields than I need, but #1 is 
4058                    correct and the only one I need. Why make a new row? */
4059
4060                 ui_actiondata(package,szRegisterTypeLibraries,row);
4061                 
4062                 TRACE("Registered %s\n",
4063                        debugstr_w(package->files[index].TargetPath));
4064             }
4065
4066             if (ptLib)
4067                 ITypeLib_Release(ptLib);
4068         }
4069         else
4070             ERR("Failed to load type library %s\n",
4071                 debugstr_w(package->files[index].TargetPath));
4072         
4073         msiobj_release(&row->hdr);
4074     }
4075     MSI_ViewClose(view);
4076     msiobj_release(&view->hdr);
4077     return rc;
4078    
4079 }
4080
4081 static UINT register_appid(MSIPACKAGE *package, LPCWSTR clsid, LPCWSTR app )
4082 {
4083     static const WCHAR szAppID[] = { 'A','p','p','I','D',0 };
4084     UINT rc;
4085     MSIQUERY * view;
4086     MSIRECORD * row = 0;
4087     static const WCHAR ExecSeqQuery[] = 
4088         {'S','E','L','E','C','T',' ','*',' ','f','r','o','m',' ','A','p','p','I'
4089         ,'d',' ','w','h','e','r','e',' ','A','p','p','I','d','=','`','%','s','`',0};
4090     HKEY hkey2,hkey3;
4091     LPWSTR buffer=0;
4092
4093     if (!package)
4094         return ERROR_INVALID_HANDLE;
4095
4096     rc = ACTION_OpenQuery(package->db, &view, ExecSeqQuery, clsid);
4097     if (rc != ERROR_SUCCESS)
4098         return rc;
4099
4100     rc = MSI_ViewExecute(view, 0);
4101     if (rc != ERROR_SUCCESS)
4102     {
4103         MSI_ViewClose(view);
4104         msiobj_release(&view->hdr);
4105         return rc;
4106     }
4107
4108     RegCreateKeyW(HKEY_CLASSES_ROOT,szAppID,&hkey2);
4109     RegCreateKeyW(hkey2,clsid,&hkey3);
4110     RegSetValueExW(hkey3,NULL,0,REG_SZ,(LPVOID)app,
4111                    (strlenW(app)+1)*sizeof(WCHAR));
4112
4113     rc = MSI_ViewFetch(view,&row);
4114     if (rc != ERROR_SUCCESS)
4115     {
4116         MSI_ViewClose(view);
4117         msiobj_release(&view->hdr);
4118         return rc;
4119     }
4120
4121     if (!MSI_RecordIsNull(row,2)) 
4122     {
4123         LPWSTR deformated=0;
4124         UINT size; 
4125         static const WCHAR szRemoteServerName[] =
4126              {'R','e','m','o','t','e','S','e','r','v','e','r','N','a','m','e',0};
4127         buffer = load_dynamic_stringW(row,2);
4128         size = deformat_string(package,buffer,&deformated);
4129         RegSetValueExW(hkey3,szRemoteServerName,0,REG_SZ,(LPVOID)deformated,
4130                        size);
4131         HeapFree(GetProcessHeap(),0,deformated);
4132         HeapFree(GetProcessHeap(),0,buffer);
4133     }
4134
4135     if (!MSI_RecordIsNull(row,3)) 
4136     {
4137         static const WCHAR szLocalService[] =
4138              {'L','o','c','a','l','S','e','r','v','i','c','e',0};
4139         UINT size;
4140         buffer = load_dynamic_stringW(row,3);
4141         size = (strlenW(buffer)+1) * sizeof(WCHAR);
4142         RegSetValueExW(hkey3,szLocalService,0,REG_SZ,(LPVOID)buffer,size);
4143         HeapFree(GetProcessHeap(),0,buffer);
4144     }
4145
4146     if (!MSI_RecordIsNull(row,4)) 
4147     {
4148         static const WCHAR szService[] =
4149              {'S','e','r','v','i','c','e','P','a','r','a','m','e','t','e','r','s',0};
4150         UINT size;
4151         buffer = load_dynamic_stringW(row,4);
4152         size = (strlenW(buffer)+1) * sizeof(WCHAR);
4153         RegSetValueExW(hkey3,szService,0,REG_SZ,(LPVOID)buffer,size);
4154         HeapFree(GetProcessHeap(),0,buffer);
4155     }
4156
4157     if (!MSI_RecordIsNull(row,5)) 
4158     {
4159         static const WCHAR szDLL[] =
4160              {'D','l','l','S','u','r','r','o','g','a','t','e',0};
4161         UINT size;
4162         buffer = load_dynamic_stringW(row,5);
4163         size = (strlenW(buffer)+1) * sizeof(WCHAR);
4164         RegSetValueExW(hkey3,szDLL,0,REG_SZ,(LPVOID)buffer,size);
4165         HeapFree(GetProcessHeap(),0,buffer);
4166     }
4167
4168     if (!MSI_RecordIsNull(row,6)) 
4169     {
4170         static const WCHAR szActivate[] =
4171              {'A','c','t','i','v','a','t','e','A','s','S','t','o','r','a','g','e',0};
4172         static const WCHAR szY[] = {'Y',0};
4173
4174         if (MSI_RecordGetInteger(row,6))
4175             RegSetValueExW(hkey3,szActivate,0,REG_SZ,(LPVOID)szY,4);
4176     }
4177
4178     if (!MSI_RecordIsNull(row,7)) 
4179     {
4180         static const WCHAR szRunAs[] = {'R','u','n','A','s',0};
4181         static const WCHAR szUser[] = 
4182              {'I','n','t','e','r','a','c','t','i','v','e',' ','U','s','e','r',0};
4183
4184         if (MSI_RecordGetInteger(row,7))
4185             RegSetValueExW(hkey3,szRunAs,0,REG_SZ,(LPVOID)szUser,34);
4186     }
4187
4188     msiobj_release(&row->hdr);
4189     MSI_ViewClose(view);
4190     msiobj_release(&view->hdr);
4191     RegCloseKey(hkey3);
4192     RegCloseKey(hkey2);
4193     return rc;
4194 }
4195
4196 static UINT ACTION_RegisterClassInfo(MSIPACKAGE *package)
4197 {
4198     /* 
4199      * Again I am assuming the words, "Whose key file represents" when referring
4200      * to a Component as to meaning that Components KeyPath file
4201      *
4202      * Also there is a very strong connection between ClassInfo and ProgID
4203      * that I am mostly glossing over.  
4204      * What would be more propper is to load the ClassInfo and the ProgID info
4205      * into memory data structures and then be able to enable and disable them
4206      * based on component. 
4207      */
4208     
4209     UINT rc;
4210     MSIQUERY * view;
4211     MSIRECORD * row = 0;
4212     static const WCHAR ExecSeqQuery[] = {
4213         'S','E','L','E','C','T',' ','*',' ',
4214         'f','r','o','m',' ','C','l','a','s','s',0};
4215     static const WCHAR szCLSID[] = { 'C','L','S','I','D',0 };
4216     static const WCHAR szProgID[] = { 'P','r','o','g','I','D',0 };
4217     static const WCHAR szAppID[] = { 'A','p','p','I','D',0 };
4218     HKEY hkey,hkey2,hkey3;
4219
4220     if (!package)
4221         return ERROR_INVALID_HANDLE;
4222
4223     rc = RegCreateKeyW(HKEY_CLASSES_ROOT,szCLSID,&hkey);
4224     if (rc != ERROR_SUCCESS)
4225         return ERROR_FUNCTION_FAILED;
4226
4227     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
4228     if (rc != ERROR_SUCCESS)
4229     {
4230         rc = ERROR_SUCCESS;
4231         goto end;
4232     }
4233
4234     rc = MSI_ViewExecute(view, 0);
4235     if (rc != ERROR_SUCCESS)
4236     {
4237         MSI_ViewClose(view);
4238         msiobj_release(&view->hdr);
4239         goto end;
4240     }
4241
4242     while (1)
4243     {
4244         WCHAR clsid[0x100];
4245         WCHAR buffer[0x100];
4246         WCHAR desc[0x100];
4247         DWORD sz;
4248         INT index;
4249      
4250         rc = MSI_ViewFetch(view,&row);
4251         if (rc != ERROR_SUCCESS)
4252         {
4253             rc = ERROR_SUCCESS;
4254             break;
4255         }
4256
4257         sz=0x100;
4258         MSI_RecordGetStringW(row,3,buffer,&sz);
4259
4260         index = get_loaded_component(package,buffer);
4261
4262         if (index < 0)
4263         {
4264             msiobj_release(&row->hdr);
4265             continue;
4266         }
4267
4268         if (package->components[index].ActionRequest != INSTALLSTATE_LOCAL)
4269         {
4270             TRACE("Skipping class reg due to disabled component\n");
4271             msiobj_release(&row->hdr);
4272             continue;
4273         }
4274
4275         sz=0x100;
4276         MSI_RecordGetStringW(row,1,clsid,&sz);
4277         RegCreateKeyW(hkey,clsid,&hkey2);
4278
4279         if (!MSI_RecordIsNull(row,5))
4280         {
4281             sz=0x100;
4282             MSI_RecordGetStringW(row,5,desc,&sz);
4283
4284             RegSetValueExW(hkey2,NULL,0,REG_SZ,(LPVOID)desc,
4285                            (strlenW(desc)+1)*sizeof(WCHAR));
4286         }
4287         else
4288             desc[0]=0;
4289
4290         sz=0x100;
4291         MSI_RecordGetStringW(row,2,buffer,&sz);
4292
4293         RegCreateKeyW(hkey2,buffer,&hkey3);
4294
4295         index = get_loaded_file(package,package->components[index].KeyPath);
4296         RegSetValueExW(hkey3,NULL,0,REG_SZ,
4297                        (LPVOID)package->files[index].TargetPath,
4298                        (strlenW(package->files[index].TargetPath)+1)
4299                         *sizeof(WCHAR));
4300
4301         RegCloseKey(hkey3);
4302
4303         if (!MSI_RecordIsNull(row,4))
4304         {
4305             sz=0x100;
4306             MSI_RecordGetStringW(row,4,buffer,&sz);
4307
4308             RegCreateKeyW(hkey2,szProgID,&hkey3);
4309     
4310             RegSetValueExW(hkey3,NULL,0,REG_SZ,(LPVOID)buffer,
4311                        (strlenW(buffer)+1)*sizeof(WCHAR));
4312
4313             RegCloseKey(hkey3);
4314         }
4315
4316         if (!MSI_RecordIsNull(row,6))
4317         { 
4318             sz=0x100;
4319             MSI_RecordGetStringW(row,6,buffer,&sz);
4320
4321             RegSetValueExW(hkey2,szAppID,0,REG_SZ,(LPVOID)buffer,
4322                        (strlenW(buffer)+1)*sizeof(WCHAR));
4323
4324             register_appid(package,buffer,desc);
4325         }
4326
4327         RegCloseKey(hkey2);
4328
4329         FIXME("Process the rest of the fields >7\n");
4330
4331         ui_actiondata(package,szRegisterClassInfo,row);
4332
4333         msiobj_release(&row->hdr);
4334     }
4335     MSI_ViewClose(view);
4336     msiobj_release(&view->hdr);
4337
4338 end:
4339     RegCloseKey(hkey);
4340     return rc;
4341 }
4342
4343 static UINT register_progid_base(MSIRECORD * row, LPWSTR clsid)
4344 {
4345     static const WCHAR szCLSID[] = { 'C','L','S','I','D',0 };
4346     HKEY hkey,hkey2;
4347     WCHAR buffer[0x100];
4348     DWORD sz;
4349
4350
4351     sz = 0x100;
4352     MSI_RecordGetStringW(row,1,buffer,&sz);
4353     RegCreateKeyW(HKEY_CLASSES_ROOT,buffer,&hkey);
4354
4355     if (!MSI_RecordIsNull(row,4))
4356     {
4357         sz = 0x100;
4358         MSI_RecordGetStringW(row,4,buffer,&sz);
4359         RegSetValueExW(hkey,NULL,0,REG_SZ,(LPVOID)buffer, (strlenW(buffer)+1) *
4360                        sizeof(WCHAR));
4361     }
4362
4363     if (!MSI_RecordIsNull(row,3))
4364     {   
4365         sz = 0x100;
4366     
4367         MSI_RecordGetStringW(row,3,buffer,&sz);
4368         RegCreateKeyW(hkey,szCLSID,&hkey2);
4369         RegSetValueExW(hkey2,NULL,0,REG_SZ,(LPVOID)buffer, (strlenW(buffer)+1) *
4370                        sizeof(WCHAR));
4371
4372         if (clsid)
4373             strcpyW(clsid,buffer);
4374
4375         RegCloseKey(hkey2);
4376     }
4377     else
4378     {
4379         FIXME("UNHANDLED case, Parent progid but classid is NULL\n");
4380         return ERROR_FUNCTION_FAILED;
4381     }
4382     if (!MSI_RecordIsNull(row,5))
4383         FIXME ("UNHANDLED icon in Progid\n");
4384     return ERROR_SUCCESS;
4385 }
4386
4387 static UINT register_progid(MSIPACKAGE *package, MSIRECORD * row, LPWSTR clsid);
4388
4389 static UINT register_parent_progid(MSIPACKAGE *package, LPCWSTR parent, 
4390                                    LPWSTR clsid)
4391 {
4392     UINT rc;
4393     MSIQUERY * view;
4394     MSIRECORD * row = 0;
4395     static const WCHAR Query_t[] = 
4396         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','P','r','o','g'
4397         ,'I','d',' ','w','h','e','r','e',' ','P','r','o','g','I','d',' ','=',' ','`'
4398         ,'%','s','`',0};
4399
4400     if (!package)
4401         return ERROR_INVALID_HANDLE;
4402
4403     rc = ACTION_OpenQuery(package->db, &view, Query_t, parent);
4404     if (rc != ERROR_SUCCESS)
4405         return rc;
4406
4407     rc = MSI_ViewExecute(view, 0);
4408     if (rc != ERROR_SUCCESS)
4409     {
4410         MSI_ViewClose(view);
4411         msiobj_release(&view->hdr);
4412         return rc;
4413     }
4414
4415     rc = MSI_ViewFetch(view,&row);
4416     if (rc != ERROR_SUCCESS)
4417     {
4418         MSI_ViewClose(view);
4419         msiobj_release(&view->hdr);
4420         return rc;
4421     }
4422
4423     register_progid(package,row,clsid);
4424
4425     msiobj_release(&row->hdr);
4426     MSI_ViewClose(view);
4427     msiobj_release(&view->hdr);
4428     return rc;
4429 }
4430
4431 static UINT register_progid(MSIPACKAGE *package, MSIRECORD * row, LPWSTR clsid)
4432 {
4433     UINT rc = ERROR_SUCCESS; 
4434
4435     if (MSI_RecordIsNull(row,2))
4436         rc = register_progid_base(row,clsid);
4437     else
4438     {
4439         WCHAR buffer[0x1000];
4440         DWORD sz, disp;
4441         HKEY hkey,hkey2;
4442         static const WCHAR szCLSID[] = { 'C','L','S','I','D',0 };
4443
4444         /* check if already registered */
4445         sz = 0x100;
4446         MSI_RecordGetStringW(row,1,buffer,&sz);
4447         RegCreateKeyExW(HKEY_CLASSES_ROOT, buffer, 0, NULL, 0,
4448                         KEY_ALL_ACCESS, NULL, &hkey, &disp );
4449         if (disp == REG_OPENED_EXISTING_KEY)
4450         {
4451             TRACE("Key already registered\n");
4452             RegCloseKey(hkey);
4453             return rc;
4454         }
4455         /* clsid is same as parent */
4456         RegCreateKeyW(hkey,szCLSID,&hkey2);
4457         RegSetValueExW(hkey2,NULL,0,REG_SZ,(LPVOID)clsid, (strlenW(clsid)+1) *
4458                        sizeof(WCHAR));
4459
4460         RegCloseKey(hkey2);
4461
4462         sz = 0x100;
4463         MSI_RecordGetStringW(row,2,buffer,&sz);
4464         rc = register_parent_progid(package,buffer,clsid);
4465
4466         if (!MSI_RecordIsNull(row,4))
4467         {
4468             sz = 0x100;
4469             MSI_RecordGetStringW(row,4,buffer,&sz);
4470             RegSetValueExW(hkey,NULL,0,REG_SZ,(LPVOID)buffer,
4471                            (strlenW(buffer)+1) * sizeof(WCHAR));
4472         }
4473
4474         if (!MSI_RecordIsNull(row,5))
4475             FIXME ("UNHANDLED icon in Progid\n");
4476
4477         RegCloseKey(hkey);
4478     }
4479     return rc;
4480 }
4481
4482 static UINT ACTION_RegisterProgIdInfo(MSIPACKAGE *package)
4483 {
4484     /* 
4485      * Sigh, here I am just brute force registering all progids
4486      * this needs to be linked to the Classes that have been registered
4487      * but the easiest way to do that is to load all these stuff into
4488      * memory for easy checking.
4489      *
4490      * Gives me something to continue to work toward.
4491      */
4492     UINT rc;
4493     MSIQUERY * view;
4494     MSIRECORD * row = 0;
4495     static const WCHAR Query[] = {
4496         'S','E','L','E','C','T',' ','*',' ',
4497         'F','R','O','M',' ','P','r','o','g','I','d',0};
4498
4499     if (!package)
4500         return ERROR_INVALID_HANDLE;
4501
4502     rc = MSI_DatabaseOpenViewW(package->db, Query, &view);
4503     if (rc != ERROR_SUCCESS)
4504         return ERROR_SUCCESS;
4505
4506     rc = MSI_ViewExecute(view, 0);
4507     if (rc != ERROR_SUCCESS)
4508     {
4509         MSI_ViewClose(view);
4510         msiobj_release(&view->hdr);
4511         return rc;
4512     }
4513
4514     while (1)
4515     {
4516         WCHAR clsid[0x1000];
4517
4518         rc = MSI_ViewFetch(view,&row);
4519         if (rc != ERROR_SUCCESS)
4520         {
4521             rc = ERROR_SUCCESS;
4522             break;
4523         }
4524         
4525         register_progid(package,row,clsid);
4526         ui_actiondata(package,szRegisterProgIdInfo,row);
4527
4528         msiobj_release(&row->hdr);
4529     }
4530     MSI_ViewClose(view);
4531     msiobj_release(&view->hdr);
4532     return rc;
4533 }
4534
4535 static UINT build_icon_path(MSIPACKAGE *package, LPCWSTR icon_name, 
4536                             LPWSTR *FilePath)
4537 {
4538     LPWSTR ProductCode;
4539     LPWSTR SystemFolder;
4540     LPWSTR dest;
4541     UINT rc;
4542
4543     static const WCHAR szInstaller[] = 
4544         {'I','n','s','t','a','l','l','e','r','\\',0};
4545     static const WCHAR szProductCode[] =
4546         {'P','r','o','d','u','c','t','C','o','d','e',0};
4547     static const WCHAR szFolder[] =
4548         {'W','i','n','d','o','w','s','F','o','l','d','e','r',0};
4549
4550     ProductCode = load_dynamic_property(package,szProductCode,&rc);
4551     if (!ProductCode)
4552         return rc;
4553
4554     SystemFolder = load_dynamic_property(package,szFolder,NULL);
4555
4556     dest = build_directory_name(3, SystemFolder, szInstaller, ProductCode);
4557
4558     create_full_pathW(dest);
4559
4560     *FilePath = build_directory_name(2, dest, icon_name);
4561
4562     HeapFree(GetProcessHeap(),0,SystemFolder);
4563     HeapFree(GetProcessHeap(),0,ProductCode);
4564     HeapFree(GetProcessHeap(),0,dest);
4565     return ERROR_SUCCESS;
4566 }
4567
4568 static UINT ACTION_CreateShortcuts(MSIPACKAGE *package)
4569 {
4570     UINT rc;
4571     MSIQUERY * view;
4572     MSIRECORD * row = 0;
4573     static const WCHAR Query[] = {
4574        'S','E','L','E','C','T',' ','*',' ','f','r','o','m',' ',
4575        'S','h','o','r','t','c','u','t',0};
4576     IShellLinkW *sl;
4577     IPersistFile *pf;
4578     HRESULT res;
4579
4580     if (!package)
4581         return ERROR_INVALID_HANDLE;
4582
4583     res = CoInitialize( NULL );
4584     if (FAILED (res))
4585     {
4586         ERR("CoInitialize failed\n");
4587         return ERROR_FUNCTION_FAILED;
4588     }
4589
4590     rc = MSI_DatabaseOpenViewW(package->db, Query, &view);
4591     if (rc != ERROR_SUCCESS)
4592         return ERROR_SUCCESS;
4593
4594     rc = MSI_ViewExecute(view, 0);
4595     if (rc != ERROR_SUCCESS)
4596     {
4597         MSI_ViewClose(view);
4598         msiobj_release(&view->hdr);
4599         return rc;
4600     }
4601
4602     while (1)
4603     {
4604         LPWSTR target_file, target_folder;
4605         WCHAR buffer[0x100];
4606         DWORD sz;
4607         DWORD index;
4608         static const WCHAR szlnk[]={'.','l','n','k',0};
4609
4610         rc = MSI_ViewFetch(view,&row);
4611         if (rc != ERROR_SUCCESS)
4612         {
4613             rc = ERROR_SUCCESS;
4614             break;
4615         }
4616         
4617         sz = 0x100;
4618         MSI_RecordGetStringW(row,4,buffer,&sz);
4619
4620         index = get_loaded_component(package,buffer);
4621
4622         if (index < 0)
4623         {
4624             msiobj_release(&row->hdr);
4625             continue;
4626         }
4627
4628         if (package->components[index].ActionRequest != INSTALLSTATE_LOCAL)
4629         {
4630             TRACE("Skipping shortcut creation due to disabled component\n");
4631             msiobj_release(&row->hdr);
4632             continue;
4633         }
4634
4635         ui_actiondata(package,szCreateShortcuts,row);
4636
4637         res = CoCreateInstance( &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
4638                               &IID_IShellLinkW, (LPVOID *) &sl );
4639
4640         if (FAILED(res))
4641         {
4642             ERR("Is IID_IShellLink\n");
4643             msiobj_release(&row->hdr);
4644             continue;
4645         }
4646
4647         res = IShellLinkW_QueryInterface( sl, &IID_IPersistFile,(LPVOID*) &pf );
4648         if( FAILED( res ) )
4649         {
4650             ERR("Is IID_IPersistFile\n");
4651             msiobj_release(&row->hdr);
4652             continue;
4653         }
4654
4655         sz = 0x100;
4656         MSI_RecordGetStringW(row,2,buffer,&sz);
4657         target_folder = resolve_folder(package, buffer,FALSE,FALSE,NULL);
4658
4659         /* may be needed because of a bug somehwere else */
4660         create_full_pathW(target_folder);
4661
4662         sz = 0x100;
4663         MSI_RecordGetStringW(row,3,buffer,&sz);
4664         reduce_to_longfilename(buffer);
4665         if (!strchrW(buffer,'.'))
4666             strcatW(buffer,szlnk);
4667         target_file = build_directory_name(2, target_folder, buffer);
4668         HeapFree(GetProcessHeap(),0,target_folder);
4669
4670         sz = 0x100;
4671         MSI_RecordGetStringW(row,5,buffer,&sz);
4672         if (strchrW(buffer,'['))
4673         {
4674             LPWSTR deformated;
4675             deformat_string(package,buffer,&deformated);
4676             IShellLinkW_SetPath(sl,deformated);
4677             HeapFree(GetProcessHeap(),0,deformated);
4678         }
4679         else
4680         {
4681             FIXME("UNHANDLED shortcut format, advertised shortcut\n");
4682             IPersistFile_Release( pf );
4683             IShellLinkW_Release( sl );
4684             msiobj_release(&row->hdr);
4685             continue;
4686         }
4687
4688         if (!MSI_RecordIsNull(row,6))
4689         {
4690             LPWSTR deformated;
4691             sz = 0x100;
4692             MSI_RecordGetStringW(row,6,buffer,&sz);
4693             deformat_string(package,buffer,&deformated);
4694             IShellLinkW_SetArguments(sl,deformated);
4695             HeapFree(GetProcessHeap(),0,deformated);
4696         }
4697
4698         if (!MSI_RecordIsNull(row,7))
4699         {
4700             LPWSTR deformated;
4701             deformated = load_dynamic_stringW(row,7);
4702             IShellLinkW_SetDescription(sl,deformated);
4703             HeapFree(GetProcessHeap(),0,deformated);
4704         }
4705
4706         if (!MSI_RecordIsNull(row,8))
4707             IShellLinkW_SetHotkey(sl,MSI_RecordGetInteger(row,8));
4708
4709         if (!MSI_RecordIsNull(row,9))
4710         {
4711             WCHAR *Path = NULL;
4712             INT index; 
4713
4714             sz = 0x100;
4715             MSI_RecordGetStringW(row,9,buffer,&sz);
4716
4717             build_icon_path(package,buffer,&Path);
4718             index = MSI_RecordGetInteger(row,10);
4719
4720             IShellLinkW_SetIconLocation(sl,Path,index);
4721             HeapFree(GetProcessHeap(),0,Path);
4722         }
4723
4724         if (!MSI_RecordIsNull(row,11))
4725             IShellLinkW_SetShowCmd(sl,MSI_RecordGetInteger(row,11));
4726
4727         if (!MSI_RecordIsNull(row,12))
4728         {
4729             LPWSTR Path;
4730             sz = 0x100;
4731             MSI_RecordGetStringW(row,12,buffer,&sz);
4732             Path = resolve_folder(package, buffer, FALSE, FALSE, NULL);
4733             IShellLinkW_SetWorkingDirectory(sl,Path);
4734             HeapFree(GetProcessHeap(), 0, Path);
4735         }
4736
4737         TRACE("Writing shortcut to %s\n",debugstr_w(target_file));
4738         IPersistFile_Save(pf,target_file,FALSE);
4739     
4740         HeapFree(GetProcessHeap(),0,target_file);    
4741
4742         IPersistFile_Release( pf );
4743         IShellLinkW_Release( sl );
4744
4745         msiobj_release(&row->hdr);
4746     }
4747     MSI_ViewClose(view);
4748     msiobj_release(&view->hdr);
4749
4750
4751     CoUninitialize();
4752
4753     return rc;
4754 }
4755
4756
4757 /*
4758  * 99% of the work done here is only done for 
4759  * advertised installs. However this is where the
4760  * Icon table is processed and written out
4761  * so that is what I am going to do here.
4762  */
4763 static UINT ACTION_PublishProduct(MSIPACKAGE *package)
4764 {
4765     UINT rc;
4766     MSIQUERY * view;
4767     MSIRECORD * row = 0;
4768     static const WCHAR Query[]={
4769         'S','E','L','E','C','T',' ','*',' ',
4770         'f','r','o','m',' ','I','c','o','n',0};
4771     DWORD sz;
4772
4773     if (!package)
4774         return ERROR_INVALID_HANDLE;
4775
4776     rc = MSI_DatabaseOpenViewW(package->db, Query, &view);
4777     if (rc != ERROR_SUCCESS)
4778         return ERROR_SUCCESS;
4779
4780     rc = MSI_ViewExecute(view, 0);
4781     if (rc != ERROR_SUCCESS)
4782     {
4783         MSI_ViewClose(view);
4784         msiobj_release(&view->hdr);
4785         return rc;
4786     }
4787
4788     while (1)
4789     {
4790         HANDLE the_file;
4791         WCHAR *FilePath=NULL;
4792         WCHAR *FileName=NULL;
4793         CHAR buffer[1024];
4794
4795         rc = MSI_ViewFetch(view,&row);
4796         if (rc != ERROR_SUCCESS)
4797         {
4798             rc = ERROR_SUCCESS;
4799             break;
4800         }
4801     
4802         FileName = load_dynamic_stringW(row,1);
4803         if (!FileName)
4804         {
4805             ERR("Unable to get FileName\n");
4806             msiobj_release(&row->hdr);
4807             continue;
4808         }
4809
4810         build_icon_path(package,FileName,&FilePath);
4811
4812         HeapFree(GetProcessHeap(),0,FileName);
4813
4814         TRACE("Creating icon file at %s\n",debugstr_w(FilePath));
4815         
4816         the_file = CreateFileW(FilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
4817                            FILE_ATTRIBUTE_NORMAL, NULL);
4818
4819         if (the_file == INVALID_HANDLE_VALUE)
4820         {
4821             ERR("Unable to create file %s\n",debugstr_w(FilePath));
4822             msiobj_release(&row->hdr);
4823             HeapFree(GetProcessHeap(),0,FilePath);
4824             continue;
4825         }
4826
4827         do 
4828         {
4829             DWORD write;
4830             sz = 1024;
4831             rc = MSI_RecordReadStream(row,2,buffer,&sz);
4832             if (rc != ERROR_SUCCESS)
4833             {
4834                 ERR("Failed to get stream\n");
4835                 CloseHandle(the_file);  
4836                 DeleteFileW(FilePath);
4837                 break;
4838             }
4839             WriteFile(the_file,buffer,sz,&write,NULL);
4840         } while (sz == 1024);
4841
4842         HeapFree(GetProcessHeap(),0,FilePath);
4843
4844         CloseHandle(the_file);
4845         msiobj_release(&row->hdr);
4846     }
4847     MSI_ViewClose(view);
4848     msiobj_release(&view->hdr);
4849     return rc;
4850
4851 }
4852
4853 /* Msi functions that seem appropriate here */
4854 UINT WINAPI MsiDoActionA( MSIHANDLE hInstall, LPCSTR szAction )
4855 {
4856     LPWSTR szwAction;
4857     UINT rc;
4858
4859     TRACE(" exteral attempt at action %s\n",szAction);
4860
4861     if (!szAction)
4862         return ERROR_FUNCTION_FAILED;
4863     if (hInstall == 0)
4864         return ERROR_FUNCTION_FAILED;
4865
4866     szwAction = strdupAtoW(szAction);
4867
4868     if (!szwAction)
4869         return ERROR_FUNCTION_FAILED; 
4870
4871
4872     rc = MsiDoActionW(hInstall, szwAction);
4873     HeapFree(GetProcessHeap(),0,szwAction);
4874     return rc;
4875 }
4876
4877 UINT WINAPI MsiDoActionW( MSIHANDLE hInstall, LPCWSTR szAction )
4878 {
4879     MSIPACKAGE *package;
4880     UINT ret = ERROR_INVALID_HANDLE;
4881
4882     TRACE(" external attempt at action %s \n",debugstr_w(szAction));
4883
4884     package = msihandle2msiinfo(hInstall, MSIHANDLETYPE_PACKAGE);
4885     if( package )
4886     {
4887         ret = ACTION_PerformAction(package,szAction);
4888         msiobj_release( &package->hdr );
4889     }
4890     return ret;
4891 }
4892
4893 UINT WINAPI MsiGetTargetPathA( MSIHANDLE hInstall, LPCSTR szFolder, 
4894                                LPSTR szPathBuf, DWORD* pcchPathBuf) 
4895 {
4896     LPWSTR szwFolder;
4897     LPWSTR szwPathBuf;
4898     UINT rc;
4899
4900     TRACE("getting folder %s %p %li\n",szFolder,szPathBuf, *pcchPathBuf);
4901
4902     if (!szFolder)
4903         return ERROR_FUNCTION_FAILED;
4904     if (hInstall == 0)
4905         return ERROR_FUNCTION_FAILED;
4906
4907     szwFolder = strdupAtoW(szFolder);
4908
4909     if (!szwFolder)
4910         return ERROR_FUNCTION_FAILED; 
4911
4912     szwPathBuf = HeapAlloc( GetProcessHeap(), 0 , *pcchPathBuf * sizeof(WCHAR));
4913
4914     rc = MsiGetTargetPathW(hInstall, szwFolder, szwPathBuf,pcchPathBuf);
4915
4916     WideCharToMultiByte( CP_ACP, 0, szwPathBuf, *pcchPathBuf, szPathBuf,
4917                          *pcchPathBuf, NULL, NULL );
4918
4919     HeapFree(GetProcessHeap(),0,szwFolder);
4920     HeapFree(GetProcessHeap(),0,szwPathBuf);
4921
4922     return rc;
4923 }
4924
4925 UINT WINAPI MsiGetTargetPathW( MSIHANDLE hInstall, LPCWSTR szFolder, LPWSTR
4926                                 szPathBuf, DWORD* pcchPathBuf) 
4927 {
4928     LPWSTR path;
4929     UINT rc = ERROR_FUNCTION_FAILED;
4930     MSIPACKAGE *package;
4931
4932     TRACE("(%s %p %li)\n",debugstr_w(szFolder),szPathBuf,*pcchPathBuf);
4933
4934     package = msihandle2msiinfo(hInstall, MSIHANDLETYPE_PACKAGE);
4935     if (!package)
4936         return ERROR_INVALID_HANDLE;
4937     path = resolve_folder(package, szFolder, FALSE, FALSE, NULL);
4938     msiobj_release( &package->hdr );
4939
4940     if (path && (strlenW(path) > *pcchPathBuf))
4941     {
4942         *pcchPathBuf = strlenW(path)+1;
4943         rc = ERROR_MORE_DATA;
4944     }
4945     else if (path)
4946     {
4947         *pcchPathBuf = strlenW(path)+1;
4948         strcpyW(szPathBuf,path);
4949         TRACE("Returning Path %s\n",debugstr_w(path));
4950         rc = ERROR_SUCCESS;
4951     }
4952     HeapFree(GetProcessHeap(),0,path);
4953     
4954     return rc;
4955 }
4956
4957
4958 UINT WINAPI MsiGetSourcePathA( MSIHANDLE hInstall, LPCSTR szFolder, 
4959                                LPSTR szPathBuf, DWORD* pcchPathBuf) 
4960 {
4961     LPWSTR szwFolder;
4962     LPWSTR szwPathBuf;
4963     UINT rc;
4964
4965     TRACE("getting source %s %p %li\n",szFolder,szPathBuf, *pcchPathBuf);
4966
4967     if (!szFolder)
4968         return ERROR_FUNCTION_FAILED;
4969     if (hInstall == 0)
4970         return ERROR_FUNCTION_FAILED;
4971
4972     szwFolder = strdupAtoW(szFolder);
4973     if (!szwFolder)
4974         return ERROR_FUNCTION_FAILED; 
4975
4976     szwPathBuf = HeapAlloc( GetProcessHeap(), 0 , *pcchPathBuf * sizeof(WCHAR));
4977
4978     rc = MsiGetSourcePathW(hInstall, szwFolder, szwPathBuf,pcchPathBuf);
4979
4980     WideCharToMultiByte( CP_ACP, 0, szwPathBuf, *pcchPathBuf, szPathBuf,
4981                          *pcchPathBuf, NULL, NULL );
4982
4983     HeapFree(GetProcessHeap(),0,szwFolder);
4984     HeapFree(GetProcessHeap(),0,szwPathBuf);
4985
4986     return rc;
4987 }
4988
4989 UINT WINAPI MsiGetSourcePathW( MSIHANDLE hInstall, LPCWSTR szFolder, LPWSTR
4990                                 szPathBuf, DWORD* pcchPathBuf) 
4991 {
4992     LPWSTR path;
4993     UINT rc = ERROR_FUNCTION_FAILED;
4994     MSIPACKAGE *package;
4995
4996     TRACE("(%s %p %li)\n",debugstr_w(szFolder),szPathBuf,*pcchPathBuf);
4997
4998     package = msihandle2msiinfo(hInstall, MSIHANDLETYPE_PACKAGE);
4999     if( !package )
5000         return ERROR_INVALID_HANDLE;
5001     path = resolve_folder(package, szFolder, TRUE, FALSE, NULL);
5002     msiobj_release( &package->hdr );
5003
5004     if (path && strlenW(path) > *pcchPathBuf)
5005     {
5006         *pcchPathBuf = strlenW(path)+1;
5007         rc = ERROR_MORE_DATA;
5008     }
5009     else if (path)
5010     {
5011         *pcchPathBuf = strlenW(path)+1;
5012         strcpyW(szPathBuf,path);
5013         TRACE("Returning Path %s\n",debugstr_w(path));
5014         rc = ERROR_SUCCESS;
5015     }
5016     HeapFree(GetProcessHeap(),0,path);
5017     
5018     return rc;
5019 }
5020
5021
5022 UINT WINAPI MsiSetTargetPathA(MSIHANDLE hInstall, LPCSTR szFolder, 
5023                              LPCSTR szFolderPath)
5024 {
5025     LPWSTR szwFolder;
5026     LPWSTR szwFolderPath;
5027     UINT rc;
5028
5029     if (!szFolder)
5030         return ERROR_FUNCTION_FAILED;
5031     if (hInstall == 0)
5032         return ERROR_FUNCTION_FAILED;
5033
5034     szwFolder = strdupAtoW(szFolder);
5035     if (!szwFolder)
5036         return ERROR_FUNCTION_FAILED; 
5037
5038     szwFolderPath = strdupAtoW(szFolderPath);
5039     if (!szwFolderPath)
5040     {
5041         HeapFree(GetProcessHeap(),0,szwFolder);
5042         return ERROR_FUNCTION_FAILED; 
5043     }
5044
5045     rc = MsiSetTargetPathW(hInstall, szwFolder, szwFolderPath);
5046
5047     HeapFree(GetProcessHeap(),0,szwFolder);
5048     HeapFree(GetProcessHeap(),0,szwFolderPath);
5049
5050     return rc;
5051 }
5052
5053 UINT MSI_SetTargetPathW(MSIPACKAGE *package, LPCWSTR szFolder, 
5054                              LPCWSTR szFolderPath)
5055 {
5056     DWORD i;
5057     LPWSTR path = NULL;
5058     MSIFOLDER *folder;
5059
5060     TRACE("(%p %s %s)\n",package, debugstr_w(szFolder),debugstr_w(szFolderPath));
5061
5062     if (package==NULL)
5063         return ERROR_INVALID_HANDLE;
5064
5065     if (szFolderPath[0]==0)
5066         return ERROR_FUNCTION_FAILED;
5067
5068     if (GetFileAttributesW(szFolderPath) == INVALID_FILE_ATTRIBUTES)
5069         return ERROR_FUNCTION_FAILED;
5070
5071     path = resolve_folder(package,szFolder,FALSE,FALSE,&folder);
5072     if (!path)
5073         return ERROR_INVALID_PARAMETER;
5074     HeapFree(GetProcessHeap(),0,path);
5075
5076     strcpyW(folder->Property,szFolderPath);
5077
5078     for (i = 0; i < package->loaded_folders; i++)
5079         package->folders[i].ResolvedTarget=NULL;
5080
5081     for (i = 0; i < package->loaded_folders; i++)
5082     {
5083         path = resolve_folder(package, package->folders[i].Directory, FALSE,
5084                        TRUE, NULL);
5085         HeapFree(GetProcessHeap(),0,path);
5086     }
5087
5088     return ERROR_SUCCESS;
5089 }
5090
5091 UINT WINAPI MsiSetTargetPathW(MSIHANDLE hInstall, LPCWSTR szFolder, 
5092                              LPCWSTR szFolderPath)
5093 {
5094     MSIPACKAGE *package;
5095     UINT ret;
5096
5097     TRACE("(%s %s)\n",debugstr_w(szFolder),debugstr_w(szFolderPath));
5098
5099     package = msihandle2msiinfo(hInstall, MSIHANDLETYPE_PACKAGE);
5100     ret = MSI_SetTargetPathW( package, szFolder, szFolderPath );
5101     msiobj_release( &package->hdr );
5102     return ret;
5103 }
5104
5105 /***********************************************************************
5106  *           MsiGetMode    (MSI.@)
5107  *
5108  * Returns an internal installer state (if it is running in a mode iRunMode)
5109  *
5110  * PARAMS
5111  *   hInstall    [I]  Handle to the installation
5112  *   hRunMode    [I]  Checking run mode
5113  *        MSIRUNMODE_ADMIN             Administrative mode
5114  *        MSIRUNMODE_ADVERTISE         Advertisement mode
5115  *        MSIRUNMODE_MAINTENANCE       Maintenance mode
5116  *        MSIRUNMODE_ROLLBACKENABLED   Rollback is enabled
5117  *        MSIRUNMODE_LOGENABLED        Log file is writing
5118  *        MSIRUNMODE_OPERATIONS        Operations in progress??
5119  *        MSIRUNMODE_REBOOTATEND       We need to reboot after installation completed
5120  *        MSIRUNMODE_REBOOTNOW         We need to reboot to continue the installation
5121  *        MSIRUNMODE_CABINET           Files from cabinet are installed
5122  *        MSIRUNMODE_SOURCESHORTNAMES  Long names in source files is supressed
5123  *        MSIRUNMODE_TARGETSHORTNAMES  Long names in destination files is supressed
5124  *        MSIRUNMODE_RESERVED11        Reserved
5125  *        MSIRUNMODE_WINDOWS9X         Running under Windows95/98
5126  *        MSIRUNMODE_ZAWENABLED        Demand installation is supported
5127  *        MSIRUNMODE_RESERVED14        Reserved
5128  *        MSIRUNMODE_RESERVED15        Reserved
5129  *        MSIRUNMODE_SCHEDULED         called from install script
5130  *        MSIRUNMODE_ROLLBACK          called from rollback script
5131  *        MSIRUNMODE_COMMIT            called from commit script
5132  *
5133  * RETURNS
5134  *    In the state: TRUE
5135  *    Not in the state: FALSE
5136  *
5137  */
5138
5139 BOOL WINAPI MsiGetMode(MSIHANDLE hInstall, MSIRUNMODE iRunMode)
5140 {
5141     FIXME("STUB (iRunMode=%i)\n",iRunMode);
5142     return TRUE;
5143 }
5144
5145 /*
5146  * According to the docs, when this is called it immediately recalculates
5147  * all the component states as well
5148  */
5149 UINT WINAPI MsiSetFeatureStateA(MSIHANDLE hInstall, LPCSTR szFeature,
5150                                 INSTALLSTATE iState)
5151 {
5152     LPWSTR szwFeature = NULL;
5153     UINT rc;
5154
5155     szwFeature = strdupAtoW(szFeature);
5156
5157     if (!szwFeature)
5158         return ERROR_FUNCTION_FAILED;
5159    
5160     rc = MsiSetFeatureStateW(hInstall,szwFeature, iState); 
5161
5162     HeapFree(GetProcessHeap(),0,szwFeature);
5163
5164     return rc;
5165 }
5166
5167 UINT WINAPI MsiSetFeatureStateW(MSIHANDLE hInstall, LPCWSTR szFeature,
5168                                 INSTALLSTATE iState)
5169 {
5170     MSIPACKAGE* package;
5171     INT index;
5172
5173     TRACE(" %s to %i\n",debugstr_w(szFeature), iState);
5174
5175     package = msihandle2msiinfo(hInstall, MSIHANDLETYPE_PACKAGE);
5176     if (!package)
5177         return ERROR_INVALID_HANDLE;
5178
5179     index = get_loaded_feature(package,szFeature);
5180     if (index < 0)
5181         return ERROR_UNKNOWN_FEATURE;
5182
5183     package->features[index].ActionRequest= iState;
5184
5185     return ERROR_SUCCESS;
5186 }
5187
5188 UINT WINAPI MsiGetFeatureStateA(MSIHANDLE hInstall, LPSTR szFeature,
5189                   INSTALLSTATE *piInstalled, INSTALLSTATE *piAction)
5190 {
5191     LPWSTR szwFeature = NULL;
5192     UINT rc;
5193     
5194     szwFeature = strdupAtoW(szFeature);
5195
5196     rc = MsiGetFeatureStateW(hInstall,szwFeature,piInstalled, piAction);
5197
5198     HeapFree( GetProcessHeap(), 0 , szwFeature);
5199
5200     return rc;
5201 }
5202
5203 UINT MSI_GetFeatureStateW(MSIPACKAGE *package, LPWSTR szFeature,
5204                   INSTALLSTATE *piInstalled, INSTALLSTATE *piAction)
5205 {
5206     INT index;
5207
5208     index = get_loaded_feature(package,szFeature);
5209     if (index < 0)
5210         return ERROR_UNKNOWN_FEATURE;
5211
5212     if (piInstalled)
5213         *piInstalled = package->features[index].Installed;
5214
5215     if (piAction)
5216         *piAction = package->features[index].Action;
5217
5218     TRACE("returning %i %i\n",*piInstalled,*piAction);
5219
5220     return ERROR_SUCCESS;
5221 }
5222
5223 UINT WINAPI MsiGetFeatureStateW(MSIHANDLE hInstall, LPWSTR szFeature,
5224                   INSTALLSTATE *piInstalled, INSTALLSTATE *piAction)
5225 {
5226     MSIPACKAGE* package;
5227     UINT ret;
5228
5229     TRACE("%ld %s %p %p\n", hInstall, debugstr_w(szFeature), piInstalled,
5230 piAction);
5231
5232     package = msihandle2msiinfo(hInstall, MSIHANDLETYPE_PACKAGE);
5233     if (!package)
5234         return ERROR_INVALID_HANDLE;
5235     ret = MSI_GetFeatureStateW(package, szFeature, piInstalled, piAction);
5236     msiobj_release( &package->hdr );
5237     return ret;
5238 }
5239
5240 UINT WINAPI MsiGetComponentStateA(MSIHANDLE hInstall, LPSTR szComponent,
5241                   INSTALLSTATE *piInstalled, INSTALLSTATE *piAction)
5242 {
5243     LPWSTR szwComponent= NULL;
5244     UINT rc;
5245     
5246     szwComponent= strdupAtoW(szComponent);
5247
5248     rc = MsiGetComponentStateW(hInstall,szwComponent,piInstalled, piAction);
5249
5250     HeapFree( GetProcessHeap(), 0 , szwComponent);
5251
5252     return rc;
5253 }
5254
5255 UINT MSI_GetComponentStateW(MSIPACKAGE *package, LPWSTR szComponent,
5256                   INSTALLSTATE *piInstalled, INSTALLSTATE *piAction)
5257 {
5258     INT index;
5259
5260     TRACE("%p %s %p %p\n", package, debugstr_w(szComponent), piInstalled,
5261 piAction);
5262
5263     index = get_loaded_component(package,szComponent);
5264     if (index < 0)
5265         return ERROR_UNKNOWN_COMPONENT;
5266
5267     if (piInstalled)
5268         *piInstalled = package->components[index].Installed;
5269
5270     if (piAction)
5271         *piInstalled = package->components[index].Action;
5272
5273     return ERROR_SUCCESS;
5274 }
5275
5276 UINT WINAPI MsiGetComponentStateW(MSIHANDLE hInstall, LPWSTR szComponent,
5277                   INSTALLSTATE *piInstalled, INSTALLSTATE *piAction)
5278 {
5279     MSIPACKAGE* package;
5280     UINT ret;
5281
5282     TRACE("%ld %s %p %p\n", hInstall, debugstr_w(szComponent),
5283            piInstalled, piAction);
5284
5285     package = msihandle2msiinfo(hInstall, MSIHANDLETYPE_PACKAGE);
5286     if (!package)
5287         return ERROR_INVALID_HANDLE;
5288     ret = MSI_GetComponentStateW( package, szComponent, piInstalled, piAction);
5289     msiobj_release( &package->hdr );
5290     return ret;
5291 }
5292
5293 #if 0
5294 static UINT ACTION_Template(MSIPACKAGE *package)
5295 {
5296     UINT rc;
5297     MSIQUERY * view;
5298     MSIRECORD * row = 0;
5299     static const WCHAR ExecSeqQuery[] = {0};
5300
5301     rc = MsiDatabaseOpenViewW(package->db, ExecSeqQuery, &view);
5302     if (rc != ERROR_SUCCESS)
5303         return rc;
5304
5305     rc = MsiViewExecute(view, 0);
5306     if (rc != ERROR_SUCCESS)
5307     {
5308         MsiViewClose(view);
5309         msiobj_release(&view->hdr);
5310         return rc;
5311     }
5312
5313     while (1)
5314     {
5315         rc = MsiViewFetch(view,&row);
5316         if (rc != ERROR_SUCCESS)
5317         {
5318             rc = ERROR_SUCCESS;
5319             break;
5320         }
5321
5322         msiobj_release(&row->hdr);
5323     }
5324     MsiViewClose(view);
5325     msiobj_release(&view->hdr);
5326     return rc;
5327 }
5328 #endif