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