msi: Set all folders' source paths to the root directory if the source type is compre...
[wine] / dlls / msi / helpers.c
1 /*
2  * Implementation of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2005 Aric Stewart for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 /*
22  * Here are helper functions formally in action.c that are used by a variety of
23  * actions and functions.
24  */
25
26 #include <stdarg.h>
27
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winerror.h"
31 #include "wine/debug.h"
32 #include "msipriv.h"
33 #include "winuser.h"
34 #include "winreg.h"
35 #include "shlwapi.h"
36 #include "wine/unicode.h"
37 #include "msidefs.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(msi);
40
41 static const WCHAR cszTargetDir[] = {'T','A','R','G','E','T','D','I','R',0};
42 static const WCHAR cszDatabase[]={'D','A','T','A','B','A','S','E',0};
43
44 const WCHAR cszSourceDir[] = {'S','o','u','r','c','e','D','i','r',0};
45 const WCHAR cszSOURCEDIR[] = {'S','O','U','R','C','E','D','I','R',0};
46 const WCHAR cszRootDrive[] = {'R','O','O','T','D','R','I','V','E',0};
47 const WCHAR cszbs[]={'\\',0};
48
49 LPWSTR build_icon_path(MSIPACKAGE *package, LPCWSTR icon_name )
50 {
51     LPWSTR SystemFolder, dest, FilePath;
52
53     static const WCHAR szInstaller[] = 
54         {'M','i','c','r','o','s','o','f','t','\\',
55          'I','n','s','t','a','l','l','e','r','\\',0};
56     static const WCHAR szFolder[] =
57         {'A','p','p','D','a','t','a','F','o','l','d','e','r',0};
58
59     SystemFolder = msi_dup_property( package, szFolder );
60
61     dest = build_directory_name(3, SystemFolder, szInstaller, package->ProductCode);
62
63     create_full_pathW(dest);
64
65     FilePath = build_directory_name(2, dest, icon_name);
66
67     msi_free(SystemFolder);
68     msi_free(dest);
69     return FilePath;
70 }
71
72 LPWSTR msi_dup_record_field( MSIRECORD *rec, INT field )
73 {
74     DWORD sz = 0;
75     LPWSTR str;
76     UINT r;
77
78     if (MSI_RecordIsNull( rec, field ))
79         return NULL;
80
81     r = MSI_RecordGetStringW( rec, field, NULL, &sz );
82     if (r != ERROR_SUCCESS)
83         return NULL;
84
85     sz ++;
86     str = msi_alloc( sz * sizeof (WCHAR) );
87     if (!str)
88         return str;
89     str[0] = 0;
90     r = MSI_RecordGetStringW( rec, field, str, &sz );
91     if (r != ERROR_SUCCESS)
92     {
93         ERR("failed to get string!\n");
94         msi_free( str );
95         return NULL;
96     }
97     return str;
98 }
99
100 MSICOMPONENT* get_loaded_component( MSIPACKAGE* package, LPCWSTR Component )
101 {
102     MSICOMPONENT *comp;
103
104     LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
105     {
106         if (lstrcmpW(Component,comp->Component)==0)
107             return comp;
108     }
109     return NULL;
110 }
111
112 MSIFEATURE* get_loaded_feature(MSIPACKAGE* package, LPCWSTR Feature )
113 {
114     MSIFEATURE *feature;
115
116     LIST_FOR_EACH_ENTRY( feature, &package->features, MSIFEATURE, entry )
117     {
118         if (lstrcmpW( Feature, feature->Feature )==0)
119             return feature;
120     }
121     return NULL;
122 }
123
124 MSIFILE* get_loaded_file( MSIPACKAGE* package, LPCWSTR key )
125 {
126     MSIFILE *file;
127
128     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
129     {
130         if (lstrcmpW( key, file->File )==0)
131             return file;
132     }
133     return NULL;
134 }
135
136 int track_tempfile( MSIPACKAGE *package, LPCWSTR path )
137 {
138     MSITEMPFILE *temp;
139
140     TRACE("%s\n", debugstr_w(path));
141
142     LIST_FOR_EACH_ENTRY( temp, &package->tempfiles, MSITEMPFILE, entry )
143         if (!lstrcmpW( path, temp->Path ))
144             return 0;
145
146     temp = msi_alloc_zero( sizeof (MSITEMPFILE) );
147     if (!temp)
148         return -1;
149
150     list_add_head( &package->tempfiles, &temp->entry );
151     temp->Path = strdupW( path );
152
153     return 0;
154 }
155
156 MSIFOLDER *get_loaded_folder( MSIPACKAGE *package, LPCWSTR dir )
157 {
158     MSIFOLDER *folder;
159
160     LIST_FOR_EACH_ENTRY( folder, &package->folders, MSIFOLDER, entry )
161     {
162         if (lstrcmpW( dir, folder->Directory )==0)
163             return folder;
164     }
165     return NULL;
166 }
167
168 static LPWSTR get_source_root( MSIPACKAGE *package )
169 {
170     LPWSTR path, p;
171
172     path = msi_dup_property( package, cszSourceDir );
173     if (path)
174         return path;
175
176     path = msi_dup_property( package, cszDatabase );
177     if (path)
178     {
179         p = strrchrW(path,'\\');
180         if (p)
181             *(p+1) = 0;
182     }
183     return path;
184 }
185
186 /*
187  * clean_spaces_from_path()
188  *
189  * removes spaces from the beginning and end of path segments
190  * removes multiple \\ characters
191  */
192 static void clean_spaces_from_path( LPWSTR p )
193 {
194     LPWSTR q = p;
195     int n, len = 0;
196
197     while (1)
198     {
199         /* copy until the end of the string or a space */
200         while (*p != ' ' && (*q = *p))
201         {
202             p++, len++;
203             /* reduce many backslashes to one */
204             if (*p != '\\' || *q != '\\')
205                 q++;
206         }
207
208         /* quit at the end of the string */
209         if (!*p)
210             break;
211
212         /* count the number of spaces */
213         n = 0;
214         while (p[n] == ' ')
215             n++;
216
217         /* if it's leading or trailing space, skip it */
218         if ( len == 0 || p[-1] == '\\' || p[n] == '\\' )
219             p += n;
220         else  /* copy n spaces */
221             while (n && (*q++ = *p++)) n--;
222     }
223 }
224
225 LPWSTR resolve_folder(MSIPACKAGE *package, LPCWSTR name, BOOL source, 
226                       BOOL set_prop, BOOL load_prop, MSIFOLDER **folder)
227 {
228     MSIFOLDER *f;
229     LPWSTR p, path = NULL, parent;
230
231     TRACE("Working to resolve %s\n",debugstr_w(name));
232
233     if (!name)
234         return NULL;
235
236     if (!lstrcmpW(name,cszSourceDir))
237         name = cszTargetDir;
238
239     f = get_loaded_folder( package, name );
240     if (!f)
241         return NULL;
242
243     /* special resolving for Target and Source root dir */
244     if (!strcmpW(name,cszTargetDir))
245     {
246         if (!f->ResolvedTarget && !f->Property)
247         {
248             LPWSTR check_path;
249             check_path = msi_dup_property( package, cszTargetDir );
250             if (!check_path)
251             {
252                 check_path = msi_dup_property( package, cszRootDrive );
253                 if (set_prop)
254                     MSI_SetPropertyW(package,cszTargetDir,check_path);
255             }
256
257             /* correct misbuilt target dir */
258             path = build_directory_name(2, check_path, NULL);
259             clean_spaces_from_path( path );
260             if (strcmpiW(path,check_path)!=0)
261                 MSI_SetPropertyW(package,cszTargetDir,path);
262             msi_free(check_path);
263
264             f->ResolvedTarget = path;
265         }
266
267         if (!f->ResolvedSource)
268             f->ResolvedSource = get_source_root( package );
269     }
270
271     if (folder)
272         *folder = f;
273
274     if (!source && f->ResolvedTarget)
275     {
276         path = strdupW( f->ResolvedTarget );
277         TRACE("   already resolved to %s\n",debugstr_w(path));
278         return path;
279     }
280
281     if (source && f->ResolvedSource)
282     {
283         path = strdupW( f->ResolvedSource );
284         TRACE("   (source)already resolved to %s\n",debugstr_w(path));
285         return path;
286     }
287
288     if (!source && f->Property)
289     {
290         path = build_directory_name( 2, f->Property, NULL );
291
292         TRACE("   internally set to %s\n",debugstr_w(path));
293         if (set_prop)
294             MSI_SetPropertyW( package, name, path );
295         return path;
296     }
297
298     if (!source && load_prop && (path = msi_dup_property( package, name )))
299     {
300         f->ResolvedTarget = strdupW( path );
301         TRACE("   property set to %s\n", debugstr_w(path));
302         return path;
303     }
304
305     if (!f->Parent)
306         return path;
307
308     parent = f->Parent;
309
310     TRACE(" ! Parent is %s\n", debugstr_w(parent));
311
312     p = resolve_folder(package, parent, source, set_prop, load_prop, NULL);
313     if (!source)
314     {
315         TRACE("   TargetDefault = %s\n", debugstr_w(f->TargetDefault));
316
317         path = build_directory_name( 3, p, f->TargetDefault, NULL );
318         clean_spaces_from_path( path );
319         f->ResolvedTarget = strdupW( path );
320         TRACE("target -> %s\n", debugstr_w(path));
321         if (set_prop)
322             MSI_SetPropertyW(package,name,path);
323     }
324     else
325     {
326         path = NULL;
327
328         if (package->WordCount & msidbSumInfoSourceTypeCompressed)
329             path = get_source_root( package );
330         else
331             path = build_directory_name( 3, p, f->SourceLongPath, NULL );
332
333         TRACE("source -> %s\n", debugstr_w(path));
334         f->ResolvedSource = strdupW( path );
335     }
336     msi_free(p);
337
338     return path;
339 }
340
341 /* wrapper to resist a need for a full rewrite right now */
342 DWORD deformat_string(MSIPACKAGE *package, LPCWSTR ptr, WCHAR** data )
343 {
344     if (ptr)
345     {
346         MSIRECORD *rec = MSI_CreateRecord(1);
347         DWORD size = 0;
348
349         MSI_RecordSetStringW(rec,0,ptr);
350         MSI_FormatRecordW(package,rec,NULL,&size);
351
352         size++;
353         *data = msi_alloc(size*sizeof(WCHAR));
354         if (size > 1)
355             MSI_FormatRecordW(package,rec,*data,&size);
356         else
357             *data[0] = 0;
358
359         msiobj_release( &rec->hdr );
360         return sizeof(WCHAR)*size;
361     }
362
363     *data = NULL;
364     return 0;
365 }
366
367 UINT schedule_action(MSIPACKAGE *package, UINT script, LPCWSTR action)
368 {
369     UINT count;
370     LPWSTR *newbuf = NULL;
371     if (script >= TOTAL_SCRIPTS)
372     {
373         FIXME("Unknown script requested %i\n",script);
374         return ERROR_FUNCTION_FAILED;
375     }
376     TRACE("Scheduling Action %s in script %i\n",debugstr_w(action), script);
377     
378     count = package->script->ActionCount[script];
379     package->script->ActionCount[script]++;
380     if (count != 0)
381         newbuf = msi_realloc( package->script->Actions[script],
382                         package->script->ActionCount[script]* sizeof(LPWSTR));
383     else
384         newbuf = msi_alloc( sizeof(LPWSTR));
385
386     newbuf[count] = strdupW(action);
387     package->script->Actions[script] = newbuf;
388
389    return ERROR_SUCCESS;
390 }
391
392 void msi_free_action_script(MSIPACKAGE *package, UINT script)
393 {
394     int i;
395     for (i = 0; i < package->script->ActionCount[script]; i++)
396         msi_free(package->script->Actions[script][i]);
397
398     msi_free(package->script->Actions[script]);
399     package->script->Actions[script] = NULL;
400     package->script->ActionCount[script] = 0;
401 }
402
403 static void remove_tracked_tempfiles(MSIPACKAGE* package)
404 {
405     struct list *item, *cursor;
406
407     LIST_FOR_EACH_SAFE( item, cursor, &package->tempfiles )
408     {
409         MSITEMPFILE *temp = LIST_ENTRY( item, MSITEMPFILE, entry );
410
411         list_remove( &temp->entry );
412         TRACE("deleting temp file %s\n", debugstr_w( temp->Path ));
413         if (!DeleteFileW( temp->Path ))
414             ERR("failed to delete %s\n", debugstr_w( temp->Path ));
415         msi_free( temp->Path );
416         msi_free( temp );
417     }
418 }
419
420 static void free_feature( MSIFEATURE *feature )
421 {
422     struct list *item, *cursor;
423
424     LIST_FOR_EACH_SAFE( item, cursor, &feature->Children )
425     {
426         FeatureList *fl = LIST_ENTRY( item, FeatureList, entry );
427         list_remove( &fl->entry );
428         msi_free( fl );
429     }
430
431     LIST_FOR_EACH_SAFE( item, cursor, &feature->Components )
432     {
433         ComponentList *cl = LIST_ENTRY( item, ComponentList, entry );
434         list_remove( &cl->entry );
435         msi_free( cl );
436     }
437     msi_free( feature->Feature );
438     msi_free( feature->Feature_Parent );
439     msi_free( feature->Directory );
440     msi_free( feature->Description );
441     msi_free( feature->Title );
442     msi_free( feature );
443 }
444
445 static void free_extension( MSIEXTENSION *ext )
446 {
447     struct list *item, *cursor;
448
449     LIST_FOR_EACH_SAFE( item, cursor, &ext->verbs )
450     {
451         MSIVERB *verb = LIST_ENTRY( item, MSIVERB, entry );
452
453         list_remove( &verb->entry );
454         msi_free( verb->Verb );
455         msi_free( verb->Command );
456         msi_free( verb->Argument );
457         msi_free( verb );
458     }
459
460     msi_free( ext->Extension );
461     msi_free( ext->ProgIDText );
462     msi_free( ext );
463 }
464
465 /* Called when the package is being closed */
466 void ACTION_free_package_structures( MSIPACKAGE* package)
467 {
468     INT i;
469     struct list *item, *cursor;
470
471     TRACE("Freeing package action data\n");
472
473     remove_tracked_tempfiles(package);
474
475     LIST_FOR_EACH_SAFE( item, cursor, &package->features )
476     {
477         MSIFEATURE *feature = LIST_ENTRY( item, MSIFEATURE, entry );
478         list_remove( &feature->entry );
479         free_feature( feature );
480     }
481
482     LIST_FOR_EACH_SAFE( item, cursor, &package->folders )
483     {
484         MSIFOLDER *folder = LIST_ENTRY( item, MSIFOLDER, entry );
485
486         list_remove( &folder->entry );
487         msi_free( folder->Parent );
488         msi_free( folder->Directory );
489         msi_free( folder->TargetDefault );
490         msi_free( folder->SourceLongPath );
491         msi_free( folder->SourceShortPath );
492         msi_free( folder->ResolvedTarget );
493         msi_free( folder->ResolvedSource );
494         msi_free( folder->Property );
495         msi_free( folder );
496     }
497
498     LIST_FOR_EACH_SAFE( item, cursor, &package->components )
499     {
500         MSICOMPONENT *comp = LIST_ENTRY( item, MSICOMPONENT, entry );
501
502         list_remove( &comp->entry );
503         msi_free( comp->Component );
504         msi_free( comp->ComponentId );
505         msi_free( comp->Directory );
506         msi_free( comp->Condition );
507         msi_free( comp->KeyPath );
508         msi_free( comp->FullKeypath );
509         msi_free( comp );
510     }
511
512     LIST_FOR_EACH_SAFE( item, cursor, &package->files )
513     {
514         MSIFILE *file = LIST_ENTRY( item, MSIFILE, entry );
515
516         list_remove( &file->entry );
517         msi_free( file->File );
518         msi_free( file->FileName );
519         msi_free( file->ShortName );
520         msi_free( file->LongName );
521         msi_free( file->Version );
522         msi_free( file->Language );
523         msi_free( file->SourcePath );
524         msi_free( file->TargetPath );
525         msi_free( file );
526     }
527
528     /* clean up extension, progid, class and verb structures */
529     LIST_FOR_EACH_SAFE( item, cursor, &package->classes )
530     {
531         MSICLASS *cls = LIST_ENTRY( item, MSICLASS, entry );
532
533         list_remove( &cls->entry );
534         msi_free( cls->clsid );
535         msi_free( cls->Context );
536         msi_free( cls->Description );
537         msi_free( cls->FileTypeMask );
538         msi_free( cls->IconPath );
539         msi_free( cls->DefInprocHandler );
540         msi_free( cls->DefInprocHandler32 );
541         msi_free( cls->Argument );
542         msi_free( cls->ProgIDText );
543         msi_free( cls );
544     }
545
546     LIST_FOR_EACH_SAFE( item, cursor, &package->extensions )
547     {
548         MSIEXTENSION *ext = LIST_ENTRY( item, MSIEXTENSION, entry );
549
550         list_remove( &ext->entry );
551         free_extension( ext );
552     }
553
554     LIST_FOR_EACH_SAFE( item, cursor, &package->progids )
555     {
556         MSIPROGID *progid = LIST_ENTRY( item, MSIPROGID, entry );
557
558         list_remove( &progid->entry );
559         msi_free( progid->ProgID );
560         msi_free( progid->Description );
561         msi_free( progid->IconPath );
562         msi_free( progid );
563     }
564
565     LIST_FOR_EACH_SAFE( item, cursor, &package->mimes )
566     {
567         MSIMIME *mt = LIST_ENTRY( item, MSIMIME, entry );
568
569         list_remove( &mt->entry );
570         msi_free( mt->clsid );
571         msi_free( mt->ContentType );
572         msi_free( mt );
573     }
574
575     LIST_FOR_EACH_SAFE( item, cursor, &package->appids )
576     {
577         MSIAPPID *appid = LIST_ENTRY( item, MSIAPPID, entry );
578
579         list_remove( &appid->entry );
580         msi_free( appid->AppID );
581         msi_free( appid->RemoteServerName );
582         msi_free( appid->LocalServer );
583         msi_free( appid->ServiceParameters );
584         msi_free( appid->DllSurrogate );
585         msi_free( appid );
586     }
587
588     LIST_FOR_EACH_SAFE( item, cursor, &package->sourcelist_info )
589     {
590         MSISOURCELISTINFO *info = LIST_ENTRY( item, MSISOURCELISTINFO, entry );
591
592         list_remove( &info->entry );
593         msi_free( info->value );
594         msi_free( info );
595     }
596
597     LIST_FOR_EACH_SAFE( item, cursor, &package->sourcelist_media )
598     {
599         MSIMEDIADISK *info = LIST_ENTRY( item, MSIMEDIADISK, entry );
600
601         list_remove( &info->entry );
602         msi_free( info->volume_label );
603         msi_free( info->disk_prompt );
604         msi_free( info );
605     }
606
607     if (package->script)
608     {
609         for (i = 0; i < TOTAL_SCRIPTS; i++)
610             msi_free_action_script(package, i);
611
612         for (i = 0; i < package->script->UniqueActionsCount; i++)
613             msi_free(package->script->UniqueActions[i]);
614
615         msi_free(package->script->UniqueActions);
616         msi_free(package->script);
617     }
618
619     msi_free(package->BaseURL);
620     msi_free(package->PackagePath);
621     msi_free(package->ProductCode);
622     msi_free(package->ActionFormat);
623     msi_free(package->LastAction);
624
625     /* cleanup control event subscriptions */
626     ControlEvent_CleanupSubscriptions(package);
627 }
628
629 /*
630  *  build_directory_name()
631  *
632  *  This function is to save messing round with directory names
633  *  It handles adding backslashes between path segments, 
634  *   and can add \ at the end of the directory name if told to.
635  *
636  *  It takes a variable number of arguments.
637  *  It always allocates a new string for the result, so make sure
638  *   to free the return value when finished with it.
639  *
640  *  The first arg is the number of path segments that follow.
641  *  The arguments following count are a list of path segments.
642  *  A path segment may be NULL.
643  *
644  *  Path segments will be added with a \ separating them.
645  *  A \ will not be added after the last segment, however if the
646  *    last segment is NULL, then the last character will be a \
647  * 
648  */
649 LPWSTR build_directory_name(DWORD count, ...)
650 {
651     DWORD sz = 1, i;
652     LPWSTR dir;
653     va_list va;
654
655     va_start(va,count);
656     for(i=0; i<count; i++)
657     {
658         LPCWSTR str = va_arg(va,LPCWSTR);
659         if (str)
660             sz += strlenW(str) + 1;
661     }
662     va_end(va);
663
664     dir = msi_alloc(sz*sizeof(WCHAR));
665     dir[0]=0;
666
667     va_start(va,count);
668     for(i=0; i<count; i++)
669     {
670         LPCWSTR str = va_arg(va,LPCWSTR);
671         if (!str)
672             continue;
673         strcatW(dir, str);
674         if( ((i+1)!=count) && dir[strlenW(dir)-1]!='\\')
675             strcatW(dir, cszbs);
676     }
677     return dir;
678 }
679
680 /***********************************************************************
681  *            create_full_pathW
682  *
683  * Recursively create all directories in the path.
684  *
685  * shamelessly stolen from setupapi/queue.c
686  */
687 BOOL create_full_pathW(const WCHAR *path)
688 {
689     BOOL ret = TRUE;
690     int len;
691     WCHAR *new_path;
692
693     new_path = msi_alloc( (strlenW(path) + 1) * sizeof(WCHAR));
694
695     strcpyW(new_path, path);
696
697     while((len = strlenW(new_path)) && new_path[len - 1] == '\\')
698     new_path[len - 1] = 0;
699
700     while(!CreateDirectoryW(new_path, NULL))
701     {
702         WCHAR *slash;
703         DWORD last_error = GetLastError();
704         if(last_error == ERROR_ALREADY_EXISTS)
705             break;
706
707         if(last_error != ERROR_PATH_NOT_FOUND)
708         {
709             ret = FALSE;
710             break;
711         }
712
713         if(!(slash = strrchrW(new_path, '\\')))
714         {
715             ret = FALSE;
716             break;
717         }
718
719         len = slash - new_path;
720         new_path[len] = 0;
721         if(!create_full_pathW(new_path))
722         {
723             ret = FALSE;
724             break;
725         }
726         new_path[len] = '\\';
727     }
728
729     msi_free(new_path);
730     return ret;
731 }
732
733 void ui_progress(MSIPACKAGE *package, int a, int b, int c, int d )
734 {
735     MSIRECORD * row;
736
737     row = MSI_CreateRecord(4);
738     MSI_RecordSetInteger(row,1,a);
739     MSI_RecordSetInteger(row,2,b);
740     MSI_RecordSetInteger(row,3,c);
741     MSI_RecordSetInteger(row,4,d);
742     MSI_ProcessMessage(package, INSTALLMESSAGE_PROGRESS, row);
743     msiobj_release(&row->hdr);
744
745     msi_dialog_check_messages(NULL);
746 }
747
748 void ui_actiondata(MSIPACKAGE *package, LPCWSTR action, MSIRECORD * record)
749 {
750     static const WCHAR Query_t[] = 
751         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
752          '`','A','c','t','i','o', 'n','T','e','x','t','`',' ',
753          'W','H','E','R','E',' ', '`','A','c','t','i','o','n','`',' ','=', 
754          ' ','\'','%','s','\'',0};
755     WCHAR message[1024];
756     MSIRECORD * row = 0;
757     DWORD size;
758
759     if (!package->LastAction || strcmpW(package->LastAction,action))
760     {
761         row = MSI_QueryGetRecord(package->db, Query_t, action);
762         if (!row)
763             return;
764
765         if (MSI_RecordIsNull(row,3))
766         {
767             msiobj_release(&row->hdr);
768             return;
769         }
770
771         /* update the cached actionformat */
772         msi_free(package->ActionFormat);
773         package->ActionFormat = msi_dup_record_field(row,3);
774
775         msi_free(package->LastAction);
776         package->LastAction = strdupW(action);
777
778         msiobj_release(&row->hdr);
779     }
780
781     MSI_RecordSetStringW(record,0,package->ActionFormat);
782     size = 1024;
783     MSI_FormatRecordW(package,record,message,&size);
784
785     row = MSI_CreateRecord(1);
786     MSI_RecordSetStringW(row,1,message);
787  
788     MSI_ProcessMessage(package, INSTALLMESSAGE_ACTIONDATA, row);
789
790     msiobj_release(&row->hdr);
791 }
792
793 BOOL ACTION_VerifyComponentForAction( const MSICOMPONENT* comp, INSTALLSTATE check )
794 {
795     if (!comp)
796         return FALSE;
797
798     if (comp->Installed == check)
799         return FALSE;
800
801     if (comp->ActionRequest == check)
802         return TRUE;
803     else
804         return FALSE;
805 }
806
807 BOOL ACTION_VerifyFeatureForAction( const MSIFEATURE* feature, INSTALLSTATE check )
808 {
809     if (!feature)
810         return FALSE;
811
812     if (feature->ActionRequest == check)
813         return TRUE;
814     else
815         return FALSE;
816 }
817
818 void reduce_to_longfilename(WCHAR* filename)
819 {
820     LPWSTR p = strchrW(filename,'|');
821     if (p)
822         memmove(filename, p+1, (strlenW(p+1)+1)*sizeof(WCHAR));
823 }
824
825 void reduce_to_shortfilename(WCHAR* filename)
826 {
827     LPWSTR p = strchrW(filename,'|');
828     if (p)
829         *p = 0;
830 }
831
832 LPWSTR create_component_advertise_string(MSIPACKAGE* package, 
833                 MSICOMPONENT* component, LPCWSTR feature)
834 {
835     static const WCHAR fmt[] = {'%','s','%','s','%','c','%','s',0};
836     WCHAR productid_85[21], component_85[21];
837     LPWSTR output = NULL;
838     DWORD sz = 0;
839     GUID clsid;
840
841     /* > is used if there is a component GUID and < if not.  */
842
843     productid_85[0] = 0;
844     component_85[0] = 0;
845
846     CLSIDFromString(package->ProductCode, &clsid);
847     encode_base85_guid(&clsid, productid_85);
848
849     if (component)
850     {
851         CLSIDFromString(component->ComponentId, &clsid);
852         encode_base85_guid(&clsid, component_85);
853     }
854
855     TRACE("prod=%s feat=%s comp=%s\n", debugstr_w(productid_85),
856           debugstr_w(feature), debugstr_w(component_85));
857  
858     sz = 20 + lstrlenW(feature) + 20 + 3;
859
860     output = msi_alloc_zero(sz*sizeof(WCHAR));
861
862     sprintfW(output, fmt, productid_85, feature,
863              component?'>':'<', component_85);
864     
865     return output;
866 }
867
868 /* update component state based on a feature change */
869 void ACTION_UpdateComponentStates(MSIPACKAGE *package, LPCWSTR szFeature)
870 {
871     INSTALLSTATE newstate;
872     MSIFEATURE *feature;
873     ComponentList *cl;
874
875     feature = get_loaded_feature(package,szFeature);
876     if (!feature)
877         return;
878
879     newstate = feature->ActionRequest;
880
881     if (newstate == INSTALLSTATE_ABSENT)
882         newstate = INSTALLSTATE_UNKNOWN;
883
884     LIST_FOR_EACH_ENTRY( cl, &feature->Components, ComponentList, entry )
885     {
886         MSICOMPONENT* component = cl->component;
887     
888         TRACE("MODIFYING(%i): Component %s (Installed %i, Action %i, Request %i)\n",
889             newstate, debugstr_w(component->Component), component->Installed, 
890             component->Action, component->ActionRequest);
891         
892         if (!component->Enabled)
893             continue;
894  
895         if (newstate == INSTALLSTATE_LOCAL)
896             msi_component_set_state( component, INSTALLSTATE_LOCAL );
897         else 
898         {
899             ComponentList *clist;
900             MSIFEATURE *f;
901
902             component->hasLocalFeature = FALSE;
903
904             msi_component_set_state( component, newstate );
905
906             /*if any other feature wants is local we need to set it local*/
907             LIST_FOR_EACH_ENTRY( f, &package->features, MSIFEATURE, entry )
908             {
909                 if ( f->ActionRequest != INSTALLSTATE_LOCAL &&
910                      f->ActionRequest != INSTALLSTATE_SOURCE )
911                 {
912                     continue;
913                 }
914
915                 LIST_FOR_EACH_ENTRY( clist, &f->Components, ComponentList, entry )
916                 {
917                     if ( clist->component == component &&
918                          (f->ActionRequest == INSTALLSTATE_LOCAL ||
919                           f->ActionRequest == INSTALLSTATE_SOURCE) )
920                     {
921                         TRACE("Saved by %s\n", debugstr_w(f->Feature));
922                         component->hasLocalFeature = TRUE;
923
924                         if (component->Attributes & msidbComponentAttributesOptional)
925                         {
926                             if (f->Attributes & msidbFeatureAttributesFavorSource)
927                                 msi_component_set_state( component, INSTALLSTATE_SOURCE );
928                             else
929                                 msi_component_set_state( component, INSTALLSTATE_LOCAL );
930                         }
931                         else if (component->Attributes & msidbComponentAttributesSourceOnly)
932                             msi_component_set_state( component, INSTALLSTATE_SOURCE );
933                         else
934                             msi_component_set_state( component, INSTALLSTATE_LOCAL );
935                     }
936                 }
937             }
938         }
939         TRACE("Result (%i): Component %s (Installed %i, Action %i, Request %i)\n",
940             newstate, debugstr_w(component->Component), component->Installed, 
941             component->Action, component->ActionRequest);
942     } 
943 }
944
945 UINT register_unique_action(MSIPACKAGE *package, LPCWSTR action)
946 {
947     UINT count;
948     LPWSTR *newbuf = NULL;
949
950     if (!package->script)
951         return FALSE;
952
953     TRACE("Registering Action %s as having fun\n",debugstr_w(action));
954     
955     count = package->script->UniqueActionsCount;
956     package->script->UniqueActionsCount++;
957     if (count != 0)
958         newbuf = msi_realloc( package->script->UniqueActions,
959                         package->script->UniqueActionsCount* sizeof(LPWSTR));
960     else
961         newbuf = msi_alloc( sizeof(LPWSTR));
962
963     newbuf[count] = strdupW(action);
964     package->script->UniqueActions = newbuf;
965
966     return ERROR_SUCCESS;
967 }
968
969 BOOL check_unique_action(const MSIPACKAGE *package, LPCWSTR action)
970 {
971     INT i;
972
973     if (!package->script)
974         return FALSE;
975
976     for (i = 0; i < package->script->UniqueActionsCount; i++)
977         if (!strcmpW(package->script->UniqueActions[i],action))
978             return TRUE;
979
980     return FALSE;
981 }
982
983 WCHAR* generate_error_string(MSIPACKAGE *package, UINT error, DWORD count, ... )
984 {
985     static const WCHAR query[] = {'S','E','L','E','C','T',' ','`','M','e','s','s','a','g','e','`',' ','F','R','O','M',' ','`','E','r','r','o','r','`',' ','W','H','E','R','E',' ','`','E','r','r','o','r','`',' ','=',' ','%','i',0};
986
987     MSIRECORD *rec;
988     MSIRECORD *row;
989     DWORD size = 0;
990     DWORD i;
991     va_list va;
992     LPCWSTR str;
993     LPWSTR data;
994
995     row = MSI_QueryGetRecord(package->db, query, error);
996     if (!row)
997         return 0;
998
999     rec = MSI_CreateRecord(count+2);
1000
1001     str = MSI_RecordGetString(row,1);
1002     MSI_RecordSetStringW(rec,0,str);
1003     msiobj_release( &row->hdr );
1004     MSI_RecordSetInteger(rec,1,error);
1005
1006     va_start(va,count);
1007     for (i = 0; i < count; i++)
1008     {
1009         str = va_arg(va,LPCWSTR);
1010         MSI_RecordSetStringW(rec,(i+2),str);
1011     }
1012     va_end(va);
1013
1014     MSI_FormatRecordW(package,rec,NULL,&size);
1015
1016     size++;
1017     data = msi_alloc(size*sizeof(WCHAR));
1018     if (size > 1)
1019         MSI_FormatRecordW(package,rec,data,&size);
1020     else
1021         data[0] = 0;
1022     msiobj_release( &rec->hdr );
1023     return data;
1024 }
1025
1026 void msi_ui_error( DWORD msg_id, DWORD type )
1027 {
1028     WCHAR text[2048];
1029
1030     static const WCHAR title[] = {
1031         'W','i','n','d','o','w','s',' ','I','n','s','t','a','l','l','e','r',0
1032     };
1033
1034     if (!MsiLoadStringW( -1, msg_id, text, sizeof(text) / sizeof(text[0]),
1035                          MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) ))
1036         return;
1037
1038     MessageBoxW( NULL, text, title, type );
1039 }
1040
1041 typedef struct
1042 {
1043     MSIPACKAGE *package;
1044     MSIMEDIAINFO *mi;
1045     MSIFILE *file;
1046     LPWSTR destination;
1047 } CabData;
1048
1049 static INT_PTR cabinet_notify(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
1050 {
1051     TRACE("(%d)\n", fdint);
1052
1053     switch (fdint)
1054     {
1055     case fdintNEXT_CABINET:
1056     {
1057         ERR("continuous cabinets not handled\n");
1058         return 0;
1059     }
1060
1061     case fdintCOPY_FILE:
1062     {
1063         CabData *data = (CabData*) pfdin->pv;
1064         LPWSTR file, path;
1065         DWORD attrs, size;
1066         HANDLE handle;
1067         MSIFILE *f;
1068
1069         file = strdupAtoW(pfdin->psz1);
1070         f = get_loaded_file(data->package, file);
1071         msi_free(file);
1072
1073         if (!f)
1074         {
1075             WARN("unknown file in cabinet (%s)\n",debugstr_a(pfdin->psz1));
1076             return 0;
1077         }
1078
1079         if (lstrcmpW(f->File, data->file->File))
1080             return 0;
1081
1082         size = lstrlenW(data->destination) + lstrlenW(data->file->FileName) + 2;
1083         path = msi_alloc(size * sizeof(WCHAR));
1084         lstrcpyW(path, data->destination);
1085         PathAddBackslashW(path);
1086         lstrcatW(path, data->file->FileName);
1087
1088         TRACE("extracting %s\n", debugstr_w(path));
1089
1090         attrs = f->Attributes & (FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
1091         if (!attrs) attrs = FILE_ATTRIBUTE_NORMAL;
1092
1093         handle = CreateFileW(path, GENERIC_READ | GENERIC_WRITE, 0,
1094                              NULL, CREATE_ALWAYS, attrs, NULL);
1095         if (handle == INVALID_HANDLE_VALUE)
1096         {
1097             if (GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES)
1098                 ERR("failed to create %s (error %d)\n",
1099                     debugstr_w(path), GetLastError());
1100
1101             msi_free(path);
1102             return 0;
1103         }
1104
1105         msi_free(path);
1106         return (INT_PTR)handle;
1107     }
1108
1109     case fdintCLOSE_FILE_INFO:
1110     {
1111         FILETIME ft;
1112         FILETIME ftLocal;
1113         HANDLE handle = (HANDLE)pfdin->hf;
1114
1115         if (!DosDateTimeToFileTime(pfdin->date, pfdin->time, &ft))
1116             return -1;
1117         if (!LocalFileTimeToFileTime(&ft, &ftLocal))
1118             return -1;
1119         if (!SetFileTime(handle, &ftLocal, 0, &ftLocal))
1120             return -1;
1121         CloseHandle(handle);
1122         return 1;
1123     }
1124
1125     default:
1126         return 0;
1127     }
1128 }
1129
1130 UINT msi_extract_file(MSIPACKAGE *package, MSIFILE *file, LPWSTR destdir)
1131 {
1132     MSIMEDIAINFO *mi;
1133     CabData data;
1134     UINT r;
1135
1136     mi = msi_alloc_zero(sizeof(MSIMEDIAINFO));
1137     if (!mi)
1138         return ERROR_OUTOFMEMORY;
1139
1140     r = msi_load_media_info(package, file, mi);
1141     if (r != ERROR_SUCCESS)
1142         goto done;
1143
1144     if (GetFileAttributesW(mi->source) == INVALID_FILE_ATTRIBUTES)
1145     {
1146         r = find_published_source(package, mi);
1147         if (r != ERROR_SUCCESS)
1148         {
1149             ERR("Cabinet not found: %s\n", debugstr_w(mi->source));
1150             return ERROR_INSTALL_FAILURE;
1151         }
1152     }
1153
1154     data.package = package;
1155     data.mi = mi;
1156     data.file = file;
1157     data.destination = destdir;
1158
1159     if (!msi_cabextract(package, mi, cabinet_notify, &data))
1160     {
1161         ERR("Failed to extract cabinet file\n");
1162         r = ERROR_FUNCTION_FAILED;
1163     }
1164
1165 done:
1166     msi_free_media_info(mi);
1167     return r;
1168 }