janitorial: Remove remaining NULL checks before free() (found by Smatch).
[wine] / dlls / msi / files.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 /*
23  * Actions dealing with files These are
24  *
25  * InstallFiles
26  * DuplicateFiles
27  * MoveFiles (TODO)
28  * PatchFiles (TODO)
29  * RemoveDuplicateFiles(TODO)
30  * RemoveFiles(TODO)
31  */
32
33 #include <stdarg.h>
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winerror.h"
38 #include "wine/debug.h"
39 #include "fdi.h"
40 #include "msi.h"
41 #include "msidefs.h"
42 #include "msvcrt/fcntl.h"
43 #include "msipriv.h"
44 #include "winuser.h"
45 #include "winreg.h"
46 #include "shlwapi.h"
47 #include "wine/unicode.h"
48 #include "action.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(msi);
51
52 extern const WCHAR szInstallFiles[];
53 extern const WCHAR szDuplicateFiles[];
54 extern const WCHAR szMoveFiles[];
55 extern const WCHAR szPatchFiles[];
56 extern const WCHAR szRemoveDuplicateFiles[];
57 extern const WCHAR szRemoveFiles[];
58
59 static const WCHAR cszTempFolder[]= {'T','e','m','p','F','o','l','d','e','r',0};
60
61 /*
62  * This is a helper function for handling embedded cabinet media
63  */
64 static UINT writeout_cabinet_stream(MSIPACKAGE *package, LPCWSTR stream_name,
65                                     WCHAR* source)
66 {
67     UINT rc;
68     USHORT* data;
69     UINT    size;
70     DWORD   write;
71     HANDLE  the_file;
72     WCHAR tmp[MAX_PATH];
73
74     rc = read_raw_stream_data(package->db,stream_name,&data,&size); 
75     if (rc != ERROR_SUCCESS)
76         return rc;
77
78     write = MAX_PATH;
79     if (MSI_GetPropertyW(package, cszTempFolder, tmp, &write))
80         GetTempPathW(MAX_PATH,tmp);
81
82     GetTempFileNameW(tmp,stream_name,0,source);
83
84     track_tempfile(package,strrchrW(source,'\\'), source);
85     the_file = CreateFileW(source, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
86                            FILE_ATTRIBUTE_NORMAL, NULL);
87
88     if (the_file == INVALID_HANDLE_VALUE)
89     {
90         ERR("Unable to create file %s\n",debugstr_w(source));
91         rc = ERROR_FUNCTION_FAILED;
92         goto end;
93     }
94
95     WriteFile(the_file,data,size,&write,NULL);
96     CloseHandle(the_file);
97     TRACE("wrote %i bytes to %s\n",write,debugstr_w(source));
98 end:
99     msi_free(data);
100     return rc;
101 }
102
103
104 /* Support functions for FDI functions */
105 typedef struct
106 {
107     MSIPACKAGE* package;
108     LPCSTR cab_path;
109 } CabData;
110
111 static void * cabinet_alloc(ULONG cb)
112 {
113     return msi_alloc(cb);
114 }
115
116 static void cabinet_free(void *pv)
117 {
118     msi_free(pv);
119 }
120
121 static INT_PTR cabinet_open(char *pszFile, int oflag, int pmode)
122 {
123     HANDLE handle;
124     DWORD dwAccess = 0;
125     DWORD dwShareMode = 0;
126     DWORD dwCreateDisposition = OPEN_EXISTING;
127     switch (oflag & _O_ACCMODE)
128     {
129     case _O_RDONLY:
130         dwAccess = GENERIC_READ;
131         dwShareMode = FILE_SHARE_READ | FILE_SHARE_DELETE;
132         break;
133     case _O_WRONLY:
134         dwAccess = GENERIC_WRITE;
135         dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
136         break;
137     case _O_RDWR:
138         dwAccess = GENERIC_READ | GENERIC_WRITE;
139         dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
140         break;
141     }
142     if ((oflag & (_O_CREAT | _O_EXCL)) == (_O_CREAT | _O_EXCL))
143         dwCreateDisposition = CREATE_NEW;
144     else if (oflag & _O_CREAT)
145         dwCreateDisposition = CREATE_ALWAYS;
146     handle = CreateFileA( pszFile, dwAccess, dwShareMode, NULL, 
147                           dwCreateDisposition, 0, NULL );
148     if (handle == INVALID_HANDLE_VALUE)
149         return 0;
150     return (INT_PTR) handle;
151 }
152
153 static UINT cabinet_read(INT_PTR hf, void *pv, UINT cb)
154 {
155     HANDLE handle = (HANDLE) hf;
156     DWORD dwRead;
157     if (ReadFile(handle, pv, cb, &dwRead, NULL))
158         return dwRead;
159     return 0;
160 }
161
162 static UINT cabinet_write(INT_PTR hf, void *pv, UINT cb)
163 {
164     HANDLE handle = (HANDLE) hf;
165     DWORD dwWritten;
166     if (WriteFile(handle, pv, cb, &dwWritten, NULL))
167         return dwWritten;
168     return 0;
169 }
170
171 static int cabinet_close(INT_PTR hf)
172 {
173     HANDLE handle = (HANDLE) hf;
174     return CloseHandle(handle) ? 0 : -1;
175 }
176
177 static long cabinet_seek(INT_PTR hf, long dist, int seektype)
178 {
179     HANDLE handle = (HANDLE) hf;
180     /* flags are compatible and so are passed straight through */
181     return SetFilePointer(handle, dist, NULL, seektype);
182 }
183
184 static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *action )
185 {
186     MSIRECORD *uirow;
187     LPWSTR uipath, p;
188
189     /* the UI chunk */
190     uirow = MSI_CreateRecord( 9 );
191     MSI_RecordSetStringW( uirow, 1, f->FileName );
192     uipath = strdupW( f->TargetPath );
193     p = strrchrW(uipath,'\\');
194     if (p)
195         p[1]=0;
196     MSI_RecordSetStringW( uirow, 9, uipath);
197     MSI_RecordSetInteger( uirow, 6, f->FileSize );
198     ui_actiondata( package, action, uirow);
199     msiobj_release( &uirow->hdr );
200     msi_free( uipath );
201     ui_progress( package, 2, f->FileSize, 0, 0);
202 }
203
204 static INT_PTR cabinet_notify(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
205 {
206     switch (fdint)
207     {
208     case fdintCOPY_FILE:
209     {
210         CabData *data = (CabData*) pfdin->pv;
211         HANDLE handle;
212         LPWSTR file;
213         MSIFILE *f;
214         DWORD attrs;
215
216         file = strdupAtoW(pfdin->psz1);
217         f = get_loaded_file(data->package, file);
218         msi_free(file);
219
220         if (!f)
221         {
222             WARN("unknown file in cabinet (%s)\n",debugstr_a(pfdin->psz1));
223             return 0;
224         }
225
226         if (f->state != msifs_missing && f->state != msifs_overwrite)
227         {
228             TRACE("Skipping extraction of %s\n",debugstr_a(pfdin->psz1));
229             return 0;
230         }
231
232         msi_file_update_ui( data->package, f, szInstallFiles );
233
234         TRACE("extracting %s\n", debugstr_w(f->TargetPath) );
235
236         attrs = f->Attributes & (FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
237         if (!attrs) attrs = FILE_ATTRIBUTE_NORMAL;
238
239         handle = CreateFileW( f->TargetPath, GENERIC_READ | GENERIC_WRITE, 0,
240                               NULL, CREATE_ALWAYS, attrs, NULL );
241         if ( handle == INVALID_HANDLE_VALUE )
242         {
243             ERR("failed to create %s (error %d)\n",
244                 debugstr_w( f->TargetPath ), GetLastError() );
245             return 0;
246         }
247
248         f->state = msifs_installed;
249         return (INT_PTR) handle;
250     }
251     case fdintCLOSE_FILE_INFO:
252     {
253         FILETIME ft;
254         FILETIME ftLocal;
255         HANDLE handle = (HANDLE) pfdin->hf;
256
257         if (!DosDateTimeToFileTime(pfdin->date, pfdin->time, &ft))
258             return -1;
259         if (!LocalFileTimeToFileTime(&ft, &ftLocal))
260             return -1;
261         if (!SetFileTime(handle, &ftLocal, 0, &ftLocal))
262             return -1;
263         CloseHandle(handle);
264         return 1;
265     }
266     default:
267         return 0;
268     }
269 }
270
271 /***********************************************************************
272  *            extract_cabinet_file
273  *
274  * Extract files from a cab file.
275  */
276 static BOOL extract_cabinet_file(MSIPACKAGE* package, LPCWSTR source, 
277                                  LPCWSTR path)
278 {
279     HFDI hfdi;
280     ERF erf;
281     BOOL ret;
282     char *cabinet;
283     char *cab_path;
284     static CHAR empty[] = "";
285     CabData data;
286
287     TRACE("Extracting %s to %s\n",debugstr_w(source), debugstr_w(path));
288
289     hfdi = FDICreate(cabinet_alloc,
290                      cabinet_free,
291                      cabinet_open,
292                      cabinet_read,
293                      cabinet_write,
294                      cabinet_close,
295                      cabinet_seek,
296                      0,
297                      &erf);
298     if (!hfdi)
299     {
300         ERR("FDICreate failed\n");
301         return FALSE;
302     }
303
304     if (!(cabinet = strdupWtoA( source )))
305     {
306         FDIDestroy(hfdi);
307         return FALSE;
308     }
309     if (!(cab_path = strdupWtoA( path )))
310     {
311         FDIDestroy(hfdi);
312         msi_free(cabinet);
313         return FALSE;
314     }
315
316     data.package = package;
317     data.cab_path = cab_path;
318
319     ret = FDICopy(hfdi, cabinet, empty, 0, cabinet_notify, NULL, &data);
320
321     if (!ret)
322         ERR("FDICopy failed\n");
323
324     FDIDestroy(hfdi);
325
326     msi_free(cabinet);
327     msi_free(cab_path);
328
329     return ret;
330 }
331
332 static VOID set_file_source(MSIPACKAGE* package, MSIFILE* file, MSICOMPONENT*
333         comp, LPCWSTR path)
334 {
335     if (!file->IsCompressed)
336     {
337         LPWSTR p, path;
338         p = resolve_folder(package, comp->Directory, TRUE, FALSE, NULL);
339         path = build_directory_name(2, p, file->ShortName);
340         if (INVALID_FILE_ATTRIBUTES == GetFileAttributesW( path ))
341         {
342             msi_free(path);
343             path = build_directory_name(2, p, file->LongName);
344         }
345         file->SourcePath = path;
346         msi_free(p);
347     }
348     else
349         file->SourcePath = build_directory_name(2, path, file->File);
350 }
351
352 struct media_info {
353     UINT last_sequence; 
354     LPWSTR last_volume;
355     LPWSTR last_path;
356     DWORD count;
357     WCHAR source[MAX_PATH];
358 };
359
360 static struct media_info *create_media_info( void )
361 {
362     struct media_info *mi;
363
364     mi = msi_alloc( sizeof *mi  );
365     if (mi)
366     {
367         mi->last_sequence = 0; 
368         mi->last_volume = NULL;
369         mi->last_path = NULL;
370         mi->count = 0;
371         mi->source[0] = 0;
372     }
373
374     return mi;
375 }
376
377 static void free_media_info( struct media_info *mi )
378 {
379     msi_free( mi->last_path );
380     msi_free( mi );
381 }
382
383 /* downloads a remote cabinet and extracts it if it exists */
384 static UINT msi_extract_remote_cabinet( MSIPACKAGE *package, struct media_info *mi )
385 {
386     FDICABINETINFO cabinfo;
387     WCHAR temppath[MAX_PATH];
388     WCHAR src[MAX_PATH];
389     LPSTR cabpath;
390     LPCWSTR file;
391     LPWSTR ptr;
392     HFDI hfdi;
393     ERF erf;
394     int hf;
395
396     /* the URL is the path prefix of the package URL and the filename
397      * of the file to download
398      */
399     ptr = strrchrW(package->PackagePath, '/');
400     lstrcpynW(src, package->PackagePath, ptr - package->PackagePath + 2);
401     ptr = strrchrW(mi->source, '\\');
402     lstrcatW(src, ptr + 1);
403
404     file = msi_download_file( src, temppath );
405     lstrcpyW(mi->source, file);
406
407     /* check if the remote cabinet still exists, ignore if it doesn't */
408     hfdi = FDICreate(cabinet_alloc, cabinet_free, cabinet_open, cabinet_read,
409                      cabinet_write, cabinet_close, cabinet_seek, 0, &erf);
410     if (!hfdi)
411     {
412         ERR("FDICreate failed\n");
413         return ERROR_FUNCTION_FAILED;
414     }
415
416     cabpath = strdupWtoA(mi->source);
417     hf = cabinet_open(cabpath, _O_RDONLY, 0);
418     if (!FDIIsCabinet(hfdi, hf, &cabinfo))
419     {
420         WARN("Remote cabinet %s does not exist.\n", debugstr_w(mi->source));
421         msi_free(cabpath);
422         return ERROR_SUCCESS;
423     }
424
425     msi_free(cabpath);
426     return !extract_cabinet_file(package, mi->source, mi->last_path);
427 }
428
429 static UINT ready_media_for_file( MSIPACKAGE *package, struct media_info *mi,
430                                   MSIFILE *file )
431 {
432     UINT rc = ERROR_SUCCESS;
433     MSIRECORD * row = 0;
434     static const WCHAR ExecSeqQuery[] =
435         {'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
436          '`','M','e','d','i','a','`',' ','W','H','E','R','E',' ',
437          '`','L','a','s','t','S','e','q','u','e','n','c','e','`',' ','>','=',
438          ' ','%', 'i',' ','O','R','D','E','R',' ','B','Y',' ',
439          '`','L','a','s','t','S','e','q','u','e','n','c','e','`',0};
440     LPCWSTR cab, volume;
441     DWORD sz;
442     INT seq;
443     LPCWSTR prompt;
444     MSICOMPONENT *comp = file->Component;
445
446     if (file->Sequence <= mi->last_sequence)
447     {
448         set_file_source(package,file,comp,mi->last_path);
449         TRACE("Media already ready (%u, %u)\n",file->Sequence,mi->last_sequence);
450         return ERROR_SUCCESS;
451     }
452
453     mi->count ++;
454     row = MSI_QueryGetRecord(package->db, ExecSeqQuery, file->Sequence);
455     if (!row)
456     {
457         TRACE("Unable to query row\n");
458         return ERROR_FUNCTION_FAILED;
459     }
460
461     volume = MSI_RecordGetString(row, 5);
462     prompt = MSI_RecordGetString(row, 3);
463
464     msi_free(mi->last_path);
465     mi->last_path = NULL;
466
467     if (!file->IsCompressed)
468     {
469         mi->last_path = resolve_folder(package, comp->Directory, TRUE, FALSE, NULL);
470         set_file_source(package,file,comp,mi->last_path);
471
472         MsiSourceListAddMediaDiskW(package->ProductCode, NULL, 
473             MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count, volume,
474             prompt);
475
476         MsiSourceListSetInfoW(package->ProductCode, NULL, 
477                 MSIINSTALLCONTEXT_USERMANAGED, 
478                 MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
479                 INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
480         msiobj_release(&row->hdr);
481         return rc;
482     }
483
484     seq = MSI_RecordGetInteger(row,2);
485     mi->last_sequence = seq;
486
487     cab = MSI_RecordGetString(row,4);
488     if (cab)
489     {
490         TRACE("Source is CAB %s\n",debugstr_w(cab));
491         /* the stream does not contain the # character */
492         if (cab[0]=='#')
493         {
494             LPWSTR path;
495
496             writeout_cabinet_stream(package,&cab[1],mi->source);
497             mi->last_path = strdupW(mi->source);
498             *(strrchrW(mi->last_path,'\\')+1)=0;
499
500             path = msi_dup_property( package, cszSourceDir );
501
502             MsiSourceListAddMediaDiskW(package->ProductCode, NULL, 
503                 MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count,
504                 volume, prompt);
505
506             MsiSourceListSetInfoW(package->ProductCode, NULL,
507                 MSIINSTALLCONTEXT_USERMANAGED,
508                 MSICODE_PRODUCT|MSISOURCETYPE_NETWORK,
509                 INSTALLPROPERTY_LASTUSEDSOURCEW, path);
510
511             msi_free(path);
512         }
513         else
514         {
515             sz = MAX_PATH;
516             mi->last_path = msi_alloc(MAX_PATH*sizeof(WCHAR));
517             if (MSI_GetPropertyW(package, cszSourceDir, mi->source, &sz))
518             {
519                 ERR("No Source dir defined\n");
520                 rc = ERROR_FUNCTION_FAILED;
521             }
522             else
523             {
524                 strcpyW(mi->last_path,mi->source);
525                 strcatW(mi->source,cab);
526
527                 MsiSourceListSetInfoW(package->ProductCode, NULL,
528                             MSIINSTALLCONTEXT_USERMANAGED,
529                             MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
530                             INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
531
532                 /* extract the cab file into a folder in the temp folder */
533                 sz = MAX_PATH;
534                 if (MSI_GetPropertyW(package, cszTempFolder,mi->last_path, &sz) 
535                                     != ERROR_SUCCESS)
536                     GetTempPathW(MAX_PATH,mi->last_path);
537             }
538         }
539
540         /* only download the remote cabinet file if a local copy does not exist */
541         if (GetFileAttributesW(mi->source) == INVALID_FILE_ATTRIBUTES &&
542             UrlIsW(package->PackagePath, URLIS_URL))
543         {
544             rc = msi_extract_remote_cabinet(package, mi);
545         }
546         else
547         {
548             rc = !extract_cabinet_file(package, mi->source, mi->last_path);
549         }
550     }
551     else
552     {
553         sz = MAX_PATH;
554         mi->last_path = msi_alloc(MAX_PATH*sizeof(WCHAR));
555         MSI_GetPropertyW(package,cszSourceDir,mi->source,&sz);
556         strcpyW(mi->last_path,mi->source);
557
558         MsiSourceListSetInfoW(package->ProductCode, NULL,
559                     MSIINSTALLCONTEXT_USERMANAGED,
560                     MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
561                     INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
562     }
563     set_file_source(package, file, comp, mi->last_path);
564
565     MsiSourceListAddMediaDiskW(package->ProductCode, NULL,
566             MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count, volume,
567             prompt);
568
569     msiobj_release(&row->hdr);
570
571     return rc;
572 }
573
574 static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
575                             MSIFILE** file)
576 {
577     LIST_FOR_EACH_ENTRY( *file, &package->files, MSIFILE, entry )
578     {
579         if (lstrcmpW( file_key, (*file)->File )==0)
580         {
581             if ((*file)->state >= msifs_overwrite)
582                 return ERROR_SUCCESS;
583             else
584                 return ERROR_FILE_NOT_FOUND;
585         }
586     }
587
588     return ERROR_FUNCTION_FAILED;
589 }
590
591 /*
592  * ACTION_InstallFiles()
593  * 
594  * For efficiency, this is done in two passes:
595  * 1) Correct all the TargetPaths and determine what files are to be installed.
596  * 2) Extract Cabinets and copy files.
597  */
598 UINT ACTION_InstallFiles(MSIPACKAGE *package)
599 {
600     struct media_info *mi;
601     UINT rc = ERROR_SUCCESS;
602     LPWSTR ptr;
603     MSIFILE *file;
604
605     /* increment progress bar each time action data is sent */
606     ui_progress(package,1,1,0,0);
607
608     /* handle the keys for the SourceList */
609     ptr = strrchrW(package->PackagePath,'\\');
610     if (ptr)
611     {
612         ptr ++;
613         MsiSourceListSetInfoW(package->ProductCode, NULL,
614                 MSIINSTALLCONTEXT_USERMANAGED,
615                 MSICODE_PRODUCT,
616                 INSTALLPROPERTY_PACKAGENAMEW, ptr);
617     }
618     /* FIXME("Write DiskPrompt\n"); */
619     
620     /* Pass 1 */
621     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
622     {
623         if (!ACTION_VerifyComponentForAction( file->Component, INSTALLSTATE_LOCAL ))
624         {
625             ui_progress(package,2,file->FileSize,0,0);
626             TRACE("File %s is not scheduled for install\n",
627                    debugstr_w(file->File));
628
629             file->state = msifs_skipped;
630         }
631     }
632
633     /*
634      * Despite MSDN specifying that the CreateFolders action
635      * should be called before InstallFiles, some installers don't
636      * do that, and they seem to work correctly.  We need to create
637      * directories here to make sure that the files can be copied.
638      */
639     msi_create_component_directories( package );
640
641     mi = create_media_info();
642
643     /* Pass 2 */
644     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
645     {
646         if (file->state != msifs_missing && file->state != msifs_overwrite)
647             continue;
648
649         TRACE("Pass 2: %s\n",debugstr_w(file->File));
650
651         rc = ready_media_for_file( package, mi, file );
652         if (rc != ERROR_SUCCESS)
653         {
654             ERR("Unable to ready media\n");
655             rc = ERROR_FUNCTION_FAILED;
656             break;
657         }
658
659         TRACE("file paths %s to %s\n",debugstr_w(file->SourcePath),
660               debugstr_w(file->TargetPath));
661
662         if (file->state != msifs_missing && file->state != msifs_overwrite)
663             continue;
664
665         /* compressed files are extracted in ready_media_for_file */
666         if (file->IsCompressed)
667         {
668             if (INVALID_FILE_ATTRIBUTES == GetFileAttributesW(file->TargetPath))
669                 ERR("compressed file wasn't extracted (%s)\n",
670                     debugstr_w(file->TargetPath));
671             continue;
672         }
673
674         rc = CopyFileW(file->SourcePath,file->TargetPath,FALSE);
675         if (!rc)
676         {
677             rc = GetLastError();
678             ERR("Unable to copy file (%s -> %s) (error %d)\n",
679                 debugstr_w(file->SourcePath), debugstr_w(file->TargetPath), rc);
680             if (rc == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
681             {
682                 rc = 0;
683             }
684             else if (rc == ERROR_FILE_NOT_FOUND)
685             {
686                 ERR("Source File Not Found!  Continuing\n");
687                 rc = 0;
688             }
689             else if (file->Attributes & msidbFileAttributesVital)
690             {
691                 ERR("Ignoring Error and continuing (nonvital file)...\n");
692                 rc = 0;
693             }
694         }
695         else
696         {
697             file->state = msifs_installed;
698             rc = ERROR_SUCCESS;
699         }
700     }
701
702     /* cleanup */
703     free_media_info( mi );
704     return rc;
705 }
706
707 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
708 {
709     MSIPACKAGE *package = (MSIPACKAGE*)param;
710     WCHAR dest_name[0x100];
711     LPWSTR dest_path, dest;
712     LPCWSTR file_key, component;
713     DWORD sz;
714     DWORD rc;
715     MSICOMPONENT *comp;
716     MSIFILE *file;
717
718     component = MSI_RecordGetString(row,2);
719     comp = get_loaded_component(package,component);
720
721     if (!ACTION_VerifyComponentForAction( comp, INSTALLSTATE_LOCAL ))
722     {
723         TRACE("Skipping copy due to disabled component %s\n",
724                         debugstr_w(component));
725
726         /* the action taken was the same as the current install state */        
727         comp->Action = comp->Installed;
728
729         return ERROR_SUCCESS;
730     }
731
732     comp->Action = INSTALLSTATE_LOCAL;
733
734     file_key = MSI_RecordGetString(row,3);
735     if (!file_key)
736     {
737         ERR("Unable to get file key\n");
738         return ERROR_FUNCTION_FAILED;
739     }
740
741     rc = get_file_target(package,file_key,&file);
742
743     if (rc != ERROR_SUCCESS)
744     {
745         ERR("Original file unknown %s\n",debugstr_w(file_key));
746         return ERROR_SUCCESS;
747     }
748
749     if (MSI_RecordIsNull(row,4))
750         strcpyW(dest_name,strrchrW(file->TargetPath,'\\')+1);
751     else
752     {
753         sz=0x100;
754         MSI_RecordGetStringW(row,4,dest_name,&sz);
755         reduce_to_longfilename(dest_name);
756     }
757
758     if (MSI_RecordIsNull(row,5))
759     {
760         LPWSTR p;
761         dest_path = strdupW(file->TargetPath);
762         p = strrchrW(dest_path,'\\');
763         if (p)
764             *p=0;
765     }
766     else
767     {
768         LPCWSTR destkey;
769         destkey = MSI_RecordGetString(row,5);
770         dest_path = resolve_folder(package, destkey, FALSE,FALSE,NULL);
771         if (!dest_path)
772         {
773             /* try a Property */
774             dest_path = msi_dup_property( package, destkey );
775             if (!dest_path)
776             {
777                 FIXME("Unable to get destination folder, try AppSearch properties\n");
778                 return ERROR_SUCCESS;
779             }
780         }
781     }
782
783     dest = build_directory_name(2, dest_path, dest_name);
784
785     TRACE("Duplicating file %s to %s\n",debugstr_w(file->TargetPath),
786                     debugstr_w(dest)); 
787
788     if (strcmpW(file->TargetPath,dest))
789         rc = !CopyFileW(file->TargetPath,dest,TRUE);
790     else
791         rc = ERROR_SUCCESS;
792
793     if (rc != ERROR_SUCCESS)
794         ERR("Failed to copy file %s -> %s, last error %d\n",
795             debugstr_w(file->TargetPath), debugstr_w(dest_path), GetLastError());
796
797     FIXME("We should track these duplicate files as well\n");   
798
799     msi_free(dest_path);
800     msi_free(dest);
801
802     msi_file_update_ui(package, file, szDuplicateFiles);
803
804     return ERROR_SUCCESS;
805 }
806
807 UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
808 {
809     UINT rc;
810     MSIQUERY * view;
811     static const WCHAR ExecSeqQuery[] =
812         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
813          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
814
815     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
816     if (rc != ERROR_SUCCESS)
817         return ERROR_SUCCESS;
818
819     rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
820     msiobj_release(&view->hdr);
821
822     return rc;
823 }
824
825 /* compares the version of a file read from the filesystem and
826  * the version specified in the File table
827  */
828 static int msi_compare_file_version( MSIFILE *file )
829 {
830     WCHAR version[MAX_PATH];
831     DWORD size;
832     UINT r;
833
834     size = MAX_PATH;
835     version[0] = '\0';
836     r = MsiGetFileVersionW( file->TargetPath, version, &size, NULL, NULL );
837     if ( r != ERROR_SUCCESS )
838         return 0;
839
840     return lstrcmpW( version, file->Version );
841 }
842
843 UINT ACTION_RemoveFiles( MSIPACKAGE *package )
844 {
845     MSIFILE *file;
846
847     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
848     {
849         MSIRECORD *uirow;
850         LPWSTR uipath, p;
851
852         if ( !file->Component )
853             continue;
854         if ( file->Component->Installed == INSTALLSTATE_LOCAL )
855             continue;
856
857         if ( file->state == msifs_installed )
858             ERR("removing installed file %s\n", debugstr_w(file->TargetPath));
859
860         if ( file->state != msifs_present )
861             continue;
862
863         /* only remove a file if the version to be installed
864          * is strictly newer than the old file
865          */
866         if ( msi_compare_file_version( file ) >= 0 )
867             continue;
868
869         TRACE("removing %s\n", debugstr_w(file->File) );
870         if ( !DeleteFileW( file->TargetPath ) )
871             ERR("failed to delete %s\n",  debugstr_w(file->TargetPath) );
872         file->state = msifs_missing;
873
874         /* the UI chunk */
875         uirow = MSI_CreateRecord( 9 );
876         MSI_RecordSetStringW( uirow, 1, file->FileName );
877         uipath = strdupW( file->TargetPath );
878         p = strrchrW(uipath,'\\');
879         if (p)
880             p[1]=0;
881         MSI_RecordSetStringW( uirow, 9, uipath);
882         ui_actiondata( package, szRemoveFiles, uirow);
883         msiobj_release( &uirow->hdr );
884         msi_free( uipath );
885         /* FIXME: call ui_progress here? */
886     }
887
888     return ERROR_SUCCESS;
889 }