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