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