Fix a memory leak in the cabinet extracting code.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 "wine/unicode.h"
46 #include "action.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(msi);
49
50 extern const WCHAR szInstallFiles[];
51 extern const WCHAR szDuplicateFiles[];
52 extern const WCHAR szMoveFiles[];
53 extern const WCHAR szPatchFiles[];
54 extern const WCHAR szRemoveDuplicateFiles[];
55 extern const WCHAR szRemoveFiles[];
56
57 static const WCHAR cszTempFolder[]= {'T','e','m','p','F','o','l','d','e','r',0};
58
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 %li 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     DWORD dwAccess = 0;
123     DWORD dwShareMode = 0;
124     DWORD dwCreateDisposition = OPEN_EXISTING;
125     switch (oflag & _O_ACCMODE)
126     {
127     case _O_RDONLY:
128         dwAccess = GENERIC_READ;
129         dwShareMode = FILE_SHARE_READ | FILE_SHARE_DELETE;
130         break;
131     case _O_WRONLY:
132         dwAccess = GENERIC_WRITE;
133         dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
134         break;
135     case _O_RDWR:
136         dwAccess = GENERIC_READ | GENERIC_WRITE;
137         dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
138         break;
139     }
140     if ((oflag & (_O_CREAT | _O_EXCL)) == (_O_CREAT | _O_EXCL))
141         dwCreateDisposition = CREATE_NEW;
142     else if (oflag & _O_CREAT)
143         dwCreateDisposition = CREATE_ALWAYS;
144     return (INT_PTR)CreateFileA(pszFile, dwAccess, dwShareMode, NULL, 
145                                 dwCreateDisposition, 0, NULL);
146 }
147
148 static UINT cabinet_read(INT_PTR hf, void *pv, UINT cb)
149 {
150     DWORD dwRead;
151     if (ReadFile((HANDLE)hf, pv, cb, &dwRead, NULL))
152         return dwRead;
153     return 0;
154 }
155
156 static UINT cabinet_write(INT_PTR hf, void *pv, UINT cb)
157 {
158     DWORD dwWritten;
159     if (WriteFile((HANDLE)hf, pv, cb, &dwWritten, NULL))
160         return dwWritten;
161     return 0;
162 }
163
164 static int cabinet_close(INT_PTR hf)
165 {
166     return CloseHandle((HANDLE)hf) ? 0 : -1;
167 }
168
169 static long cabinet_seek(INT_PTR hf, long dist, int seektype)
170 {
171     /* flags are compatible and so are passed straight through */
172     return SetFilePointer((HANDLE)hf, dist, NULL, seektype);
173 }
174
175 static INT_PTR cabinet_notify(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
176 {
177     switch (fdint)
178     {
179     case fdintCOPY_FILE:
180     {
181         CabData *data = (CabData*) pfdin->pv;
182         ULONG len = strlen(data->cab_path) + strlen(pfdin->psz1);
183         char *file;
184         INT_PTR handle;
185
186         LPWSTR trackname;
187         LPWSTR trackpath;
188         LPWSTR tracknametmp;
189         static const WCHAR tmpprefix[] = {'C','A','B','T','M','P','_',0};
190         LPWSTR given_file;
191
192         MSIRECORD * uirow;
193         LPWSTR uipath;
194         MSIFILE *f;
195
196         given_file = strdupAtoW(pfdin->psz1);
197         f = get_loaded_file(data->package, given_file);
198         msi_free(given_file);
199
200         if (!f)
201         {
202             ERR("Unknown File in Cabinet (%s)\n",debugstr_a(pfdin->psz1));
203             return 0;
204         }
205
206         if (!((f->State == 1 || f->State == 2)))
207         {
208             TRACE("Skipping extraction of %s\n",debugstr_a(pfdin->psz1));
209             return 0;
210         }
211
212         file = msi_alloc((len+1)*sizeof(char));
213         strcpy(file, data->cab_path);
214         strcat(file, pfdin->psz1);
215
216         TRACE("file: %s\n", debugstr_a(file));
217
218         /* track this file so it can be deleted if not installed */
219         trackpath=strdupAtoW(file);
220         tracknametmp=strdupAtoW(strrchr(file,'\\')+1);
221         trackname = msi_alloc((strlenW(tracknametmp) + 
222                                   strlenW(tmpprefix)+1) * sizeof(WCHAR));
223
224         strcpyW(trackname,tmpprefix);
225         strcatW(trackname,tracknametmp);
226
227         track_tempfile(data->package, trackname, trackpath);
228
229         msi_free(trackpath);
230         msi_free(trackname);
231         msi_free(tracknametmp);
232
233         /* the UI chunk */
234         uirow=MSI_CreateRecord(9);
235         MSI_RecordSetStringW( uirow, 1, f->FileName );
236         uipath = strdupW( f->TargetPath );
237         *(strrchrW(uipath,'\\')+1)=0;
238         MSI_RecordSetStringW(uirow,9,uipath);
239         MSI_RecordSetInteger( uirow, 6, f->FileSize );
240         ui_actiondata(data->package,szInstallFiles,uirow);
241         msiobj_release( &uirow->hdr );
242         msi_free(uipath);
243
244         ui_progress( data->package, 2, f->FileSize, 0, 0);
245
246         handle = cabinet_open(file, _O_WRONLY | _O_CREAT, 0);
247         msi_free( file );
248         return handle;
249     }
250     case fdintCLOSE_FILE_INFO:
251     {
252         FILETIME ft;
253             FILETIME ftLocal;
254         if (!DosDateTimeToFileTime(pfdin->date, pfdin->time, &ft))
255             return -1;
256         if (!LocalFileTimeToFileTime(&ft, &ftLocal))
257             return -1;
258         if (!SetFileTime((HANDLE)pfdin->hf, &ftLocal, 0, &ftLocal))
259             return -1;
260
261         cabinet_close(pfdin->hf);
262         return 1;
263     }
264     default:
265         return 0;
266     }
267 }
268
269 /***********************************************************************
270  *            extract_cabinet_file
271  *
272  * Extract files from a cab file.
273  */
274 static BOOL extract_cabinet_file(MSIPACKAGE* package, LPCWSTR source, 
275                                  LPCWSTR path)
276 {
277     HFDI hfdi;
278     ERF erf;
279     BOOL ret;
280     char *cabinet;
281     char *cab_path;
282     CabData data;
283
284     TRACE("Extracting %s to %s\n",debugstr_w(source), debugstr_w(path));
285
286     hfdi = FDICreate(cabinet_alloc,
287                      cabinet_free,
288                      cabinet_open,
289                      cabinet_read,
290                      cabinet_write,
291                      cabinet_close,
292                      cabinet_seek,
293                      0,
294                      &erf);
295     if (!hfdi)
296     {
297         ERR("FDICreate failed\n");
298         return FALSE;
299     }
300
301     if (!(cabinet = strdupWtoA( source )))
302     {
303         FDIDestroy(hfdi);
304         return FALSE;
305     }
306     if (!(cab_path = strdupWtoA( path )))
307     {
308         FDIDestroy(hfdi);
309         msi_free(cabinet);
310         return FALSE;
311     }
312
313     data.package = package;
314     data.cab_path = cab_path;
315
316     ret = FDICopy(hfdi, cabinet, "", 0, cabinet_notify, NULL, &data);
317
318     if (!ret)
319         ERR("FDICopy failed\n");
320
321     FDIDestroy(hfdi);
322
323     msi_free(cabinet);
324     msi_free(cab_path);
325
326     return ret;
327 }
328
329 static VOID set_file_source(MSIPACKAGE* package, MSIFILE* file, MSICOMPONENT*
330         comp, LPCWSTR path)
331 {
332     if (file->Attributes & msidbFileAttributesNoncompressed)
333     {
334         LPWSTR p;
335         p = resolve_folder(package, comp->Directory, TRUE, FALSE, NULL);
336         file->SourcePath = build_directory_name(2, p, file->ShortName);
337         msi_free(p);
338     }
339     else
340         file->SourcePath = build_directory_name(2, path, file->File);
341 }
342
343 static BOOL check_volume(LPCWSTR path, LPCWSTR want_volume, LPWSTR volume, 
344         UINT *intype)
345 {
346     WCHAR drive[4];
347     WCHAR name[MAX_PATH];
348     UINT type;
349
350     if (!(path[0] && path[1] == ':'))
351         return TRUE;
352
353     drive[0] = path[0];
354     drive[1] = path[1];
355     drive[2] = '\\';
356     drive[3] = 0;
357     TRACE("Checking volume %s .. (%s)\n",debugstr_w(drive), debugstr_w(want_volume));
358     type = GetDriveTypeW(drive);
359     TRACE("drive is of type %x\n",type);
360
361     if (type == DRIVE_UNKNOWN || type == DRIVE_NO_ROOT_DIR || 
362             type == DRIVE_FIXED || type == DRIVE_RAMDISK)
363         return TRUE;
364
365     GetVolumeInformationW(drive, name, MAX_PATH, NULL, NULL, NULL, NULL, 0);
366     TRACE("Drive contains %s\n", debugstr_w(name));
367     volume = strdupW(name);
368     if (*intype)
369         *intype=type;
370     return (strcmpiW(want_volume,name)==0);
371 }
372
373 static BOOL check_for_sourcefile(LPCWSTR source)
374 {
375     DWORD attrib = GetFileAttributesW(source);
376     return (!(attrib == INVALID_FILE_ATTRIBUTES));
377 }
378
379 static UINT ready_volume(MSIPACKAGE* package, LPCWSTR path, LPWSTR last_volume, 
380                          MSIRECORD *row,UINT *type )
381 {
382     LPWSTR volume = NULL; 
383     LPCWSTR want_volume = MSI_RecordGetString(row, 5);
384     BOOL ok = check_volume(path, want_volume, volume, type);
385
386     TRACE("Readying Volume for %s (%s, %s)\n",debugstr_w(path), debugstr_w(want_volume), debugstr_w(last_volume));
387
388     if (check_for_sourcefile(path) && !ok)
389     {
390         FIXME("Found the Sourcefile but not on the correct volume.(%s,%s,%s)\n",
391                 debugstr_w(path),debugstr_w(want_volume), debugstr_w(volume));
392         return ERROR_SUCCESS;
393     }
394
395     while (!ok)
396     {
397         INT rc;
398         LPCWSTR prompt;
399         LPWSTR msg;
400       
401         prompt = MSI_RecordGetString(row,3);
402         msg = generate_error_string(package, 1302, 1, prompt);
403         rc = MessageBoxW(NULL,msg,NULL,MB_OKCANCEL);
404         msi_free(volume);
405         msi_free(msg);
406         if (rc == IDOK)
407             ok = check_for_sourcefile(path);
408         else
409             return ERROR_INSTALL_USEREXIT;
410     }
411
412     msi_free(last_volume);
413     last_volume = strdupW(volume);
414     return ERROR_SUCCESS;
415 }
416
417 struct media_info {
418     UINT last_sequence; 
419     LPWSTR last_volume;
420     LPWSTR last_path;
421     DWORD count;
422     WCHAR source[MAX_PATH];
423 };
424
425 static struct media_info *create_media_info( void )
426 {
427     struct media_info *mi;
428
429     mi = msi_alloc( sizeof *mi  );
430     if (mi)
431     {
432         mi->last_sequence = 0; 
433         mi->last_volume = NULL;
434         mi->last_path = NULL;
435         mi->count = 0;
436         mi->source[0] = 0;
437     }
438
439     return mi;
440 }
441
442 static void free_media_info( struct media_info *mi )
443 {
444     msi_free( mi->last_path );
445     msi_free( mi );
446 }
447
448 static UINT ready_media_for_file( MSIPACKAGE *package, struct media_info *mi,
449                                   MSIFILE *file )
450 {
451     UINT rc = ERROR_SUCCESS;
452     MSIRECORD * row = 0;
453     static const WCHAR ExecSeqQuery[] =
454         {'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
455          '`','M','e','d','i','a','`',' ','W','H','E','R','E',' ',
456          '`','L','a','s','t','S','e','q','u','e','n','c','e','`',' ','>','=',
457          ' ','%', 'i',' ','O','R','D','E','R',' ','B','Y',' ',
458          '`','L','a','s','t','S','e','q','u','e','n','c','e','`',0};
459     LPCWSTR cab, volume;
460     DWORD sz;
461     INT seq;
462     UINT type;
463     LPCWSTR prompt;
464     MSICOMPONENT *comp = file->Component;
465
466     if (file->Sequence <= mi->last_sequence)
467     {
468         set_file_source(package,file,comp,mi->last_path);
469         TRACE("Media already ready (%u, %u)\n",file->Sequence,mi->last_sequence);
470         return ERROR_SUCCESS;
471     }
472
473     mi->count ++;
474     row = MSI_QueryGetRecord(package->db, ExecSeqQuery, file->Sequence);
475     if (!row)
476     {
477         TRACE("Unable to query row\n");
478         return ERROR_FUNCTION_FAILED;
479     }
480
481     seq = MSI_RecordGetInteger(row,2);
482     mi->last_sequence = seq;
483
484     volume = MSI_RecordGetString(row, 5);
485     prompt = MSI_RecordGetString(row, 3);
486
487     msi_free(mi->last_path);
488     mi->last_path = NULL;
489
490     if (file->Attributes & msidbFileAttributesNoncompressed)
491     {
492         mi->last_path = resolve_folder(package, comp->Directory, TRUE, FALSE, NULL);
493         set_file_source(package,file,comp,mi->last_path);
494         rc = ready_volume(package, file->SourcePath, mi->last_volume, row,&type);
495
496         MsiSourceListAddMediaDiskW(package->ProductCode, NULL, 
497             MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count, volume,
498             prompt);
499
500         if (type == DRIVE_REMOVABLE || type == DRIVE_CDROM || 
501                 type == DRIVE_RAMDISK)
502             MsiSourceListSetInfoW(package->ProductCode, NULL, 
503                 MSIINSTALLCONTEXT_USERMANAGED, 
504                 MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
505                 INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
506         else
507             MsiSourceListSetInfoW(package->ProductCode, NULL, 
508                 MSIINSTALLCONTEXT_USERMANAGED, 
509                 MSICODE_PRODUCT|MSISOURCETYPE_NETWORK,
510                 INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
511         msiobj_release(&row->hdr);
512         return rc;
513     }
514
515     cab = MSI_RecordGetString(row,4);
516     if (cab)
517     {
518         TRACE("Source is CAB %s\n",debugstr_w(cab));
519         /* the stream does not contain the # character */
520         if (cab[0]=='#')
521         {
522             LPWSTR path;
523
524             writeout_cabinet_stream(package,&cab[1],mi->source);
525             mi->last_path = strdupW(mi->source);
526             *(strrchrW(mi->last_path,'\\')+1)=0;
527
528             path = msi_dup_property( package, cszSourceDir );
529
530             MsiSourceListAddMediaDiskW(package->ProductCode, NULL, 
531                 MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count,
532                 volume, prompt);
533
534             MsiSourceListSetInfoW(package->ProductCode, NULL,
535                 MSIINSTALLCONTEXT_USERMANAGED,
536                 MSICODE_PRODUCT|MSISOURCETYPE_NETWORK,
537                 INSTALLPROPERTY_LASTUSEDSOURCEW, path);
538
539             msi_free(path);
540         }
541         else
542         {
543             sz = MAX_PATH;
544             mi->last_path = msi_alloc(MAX_PATH*sizeof(WCHAR));
545             if (MSI_GetPropertyW(package, cszSourceDir, mi->source, &sz))
546             {
547                 ERR("No Source dir defined \n");
548                 rc = ERROR_FUNCTION_FAILED;
549             }
550             else
551             {
552                 strcpyW(mi->last_path,mi->source);
553                 strcatW(mi->source,cab);
554
555                 rc = ready_volume(package, mi->source, mi->last_volume, row, &type);
556                 if (type == DRIVE_REMOVABLE || type == DRIVE_CDROM || 
557                         type == DRIVE_RAMDISK)
558                     MsiSourceListSetInfoW(package->ProductCode, NULL,
559                             MSIINSTALLCONTEXT_USERMANAGED,
560                             MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
561                             INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
562                 else
563                     MsiSourceListSetInfoW(package->ProductCode, NULL,
564                             MSIINSTALLCONTEXT_USERMANAGED,
565                             MSICODE_PRODUCT|MSISOURCETYPE_NETWORK,
566                             INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
567
568                 /* extract the cab file into a folder in the temp folder */
569                 sz = MAX_PATH;
570                 if (MSI_GetPropertyW(package, cszTempFolder,mi->last_path, &sz) 
571                                     != ERROR_SUCCESS)
572                     GetTempPathW(MAX_PATH,mi->last_path);
573             }
574         }
575         rc = !extract_cabinet_file(package, mi->source, mi->last_path);
576     }
577     else
578     {
579         sz = MAX_PATH;
580         mi->last_path = msi_alloc(MAX_PATH*sizeof(WCHAR));
581         MSI_GetPropertyW(package,cszSourceDir,mi->source,&sz);
582         strcpyW(mi->last_path,mi->source);
583         rc = ready_volume(package, mi->last_path, mi->last_volume, row, &type);
584
585         if (type == DRIVE_REMOVABLE || type == DRIVE_CDROM || 
586                 type == DRIVE_RAMDISK)
587             MsiSourceListSetInfoW(package->ProductCode, NULL,
588                     MSIINSTALLCONTEXT_USERMANAGED,
589                     MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
590                     INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
591         else
592             MsiSourceListSetInfoW(package->ProductCode, NULL,
593                     MSIINSTALLCONTEXT_USERMANAGED,
594                     MSICODE_PRODUCT|MSISOURCETYPE_NETWORK,
595                     INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
596     }
597     set_file_source(package, file, comp, mi->last_path);
598
599     MsiSourceListAddMediaDiskW(package->ProductCode, NULL,
600             MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count, volume,
601             prompt);
602
603     msiobj_release(&row->hdr);
604
605     return rc;
606 }
607
608 static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
609                                    LPWSTR* file_source)
610 {
611     MSIFILE *file;
612
613     if (!package)
614         return ERROR_INVALID_HANDLE;
615
616     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
617     {
618         if (lstrcmpW( file_key, file->File )==0)
619         {
620             if (file->State >= 2)
621             {
622                 *file_source = strdupW( file->TargetPath );
623                 return ERROR_SUCCESS;
624             }
625             else
626                 return ERROR_FILE_NOT_FOUND;
627         }
628     }
629
630     return ERROR_FUNCTION_FAILED;
631 }
632
633 /*
634  * In order to make this work more effeciencly I am going to do this in 2
635  * passes.
636  * Pass 1) Correct all the TargetPaths and determin what files are to be
637  * installed.
638  * Pass 2) Extract Cabinents and copy files.
639  */
640 UINT ACTION_InstallFiles(MSIPACKAGE *package)
641 {
642     struct media_info *mi;
643     UINT rc = ERROR_SUCCESS;
644     LPWSTR ptr;
645     MSIFILE *file;
646
647     if (!package)
648         return ERROR_INVALID_HANDLE;
649
650     /* increment progress bar each time action data is sent */
651     ui_progress(package,1,1,0,0);
652
653     /* handle the keys for the SouceList */
654     ptr = strrchrW(package->PackagePath,'\\');
655     if (ptr)
656     {
657         ptr ++;
658         MsiSourceListSetInfoW(package->ProductCode, NULL,
659                 MSIINSTALLCONTEXT_USERMANAGED,
660                 MSICODE_PRODUCT,
661                 INSTALLPROPERTY_PACKAGENAMEW, ptr);
662     }
663     FIXME("Write DiskPrompt\n");
664     
665     /* Pass 1 */
666     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
667     {
668         if (!ACTION_VerifyComponentForAction(package, file->Component, 
669                                        INSTALLSTATE_LOCAL))
670         {
671             ui_progress(package,2,file->FileSize,0,0);
672             TRACE("File %s is not scheduled for install\n",
673                    debugstr_w(file->File));
674
675             file->State = 5;
676         }
677     }
678
679     mi = create_media_info();
680
681     /* Pass 2 */
682     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
683     {
684         if ((file->State == 1) || (file->State == 2))
685         {
686             TRACE("Pass 2: %s\n",debugstr_w(file->File));
687
688             rc = ready_media_for_file( package, mi, file );
689             if (rc != ERROR_SUCCESS)
690             {
691                 ERR("Unable to ready media\n");
692                 rc = ERROR_FUNCTION_FAILED;
693                 break;
694             }
695
696             TRACE("file paths %s to %s\n",debugstr_w(file->SourcePath),
697                   debugstr_w(file->TargetPath));
698
699             if (file->Attributes & msidbFileAttributesNoncompressed)
700                 rc = CopyFileW(file->SourcePath,file->TargetPath,FALSE);
701             else
702                 rc = MoveFileW(file->SourcePath, file->TargetPath);
703
704             if (!rc)
705             {
706                 rc = GetLastError();
707                 ERR("Unable to move/copy file (%s -> %s) (error %d)\n",
708                      debugstr_w(file->SourcePath), debugstr_w(file->TargetPath),
709                       rc);
710                 if (rc == ERROR_ALREADY_EXISTS && file->State == 2)
711                 {
712                     if (!CopyFileW(file->SourcePath,file->TargetPath,FALSE))
713                         ERR("Unable to copy file (%s -> %s) (error %ld)\n",
714                             debugstr_w(file->SourcePath), 
715                             debugstr_w(file->TargetPath), GetLastError());
716                     if (!(file->Attributes & msidbFileAttributesNoncompressed))
717                         DeleteFileW(file->SourcePath);
718                     rc = 0;
719                 }
720                 else if (rc == ERROR_FILE_NOT_FOUND)
721                 {
722                     ERR("Source File Not Found!  Continuing\n");
723                     rc = 0;
724                 }
725                 else if (file->Attributes & msidbFileAttributesVital)
726                 {
727                     ERR("Ignoring Error and continuing (nonvital file)...\n");
728                     rc = 0;
729                 }
730             }
731             else
732             {
733                 file->State = 4;
734                 rc = ERROR_SUCCESS;
735             }
736         }
737     }
738
739     /* cleanup */
740     free_media_info( mi );
741     return rc;
742 }
743
744 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
745 {
746     MSIPACKAGE *package = (MSIPACKAGE*)param;
747     WCHAR *file_source = NULL;
748     WCHAR dest_name[0x100];
749     LPWSTR dest_path, dest;
750     LPCWSTR file_key, component;
751     DWORD sz;
752     DWORD rc;
753     MSICOMPONENT *comp;
754
755     component = MSI_RecordGetString(row,2);
756     comp = get_loaded_component(package,component);
757
758     if (!ACTION_VerifyComponentForAction(package, comp, INSTALLSTATE_LOCAL))
759     {
760         TRACE("Skipping copy due to disabled component %s\n",
761                         debugstr_w(component));
762
763         /* the action taken was the same as the current install state */        
764         comp->Action = comp->Installed;
765
766         return ERROR_SUCCESS;
767     }
768
769     comp->Action = INSTALLSTATE_LOCAL;
770
771     file_key = MSI_RecordGetString(row,3);
772     if (!file_key)
773     {
774         ERR("Unable to get file key\n");
775         return ERROR_FUNCTION_FAILED;
776     }
777
778     rc = get_file_target(package,file_key,&file_source);
779
780     if (rc != ERROR_SUCCESS)
781     {
782         ERR("Original file unknown %s\n",debugstr_w(file_key));
783         msi_free(file_source);
784         return ERROR_SUCCESS;
785     }
786
787     if (MSI_RecordIsNull(row,4))
788         strcpyW(dest_name,strrchrW(file_source,'\\')+1);
789     else
790     {
791         sz=0x100;
792         MSI_RecordGetStringW(row,4,dest_name,&sz);
793         reduce_to_longfilename(dest_name);
794     }
795
796     if (MSI_RecordIsNull(row,5))
797     {
798         LPWSTR p;
799         dest_path = strdupW(file_source);
800         p = strrchrW(dest_path,'\\');
801         if (p)
802             *p=0;
803     }
804     else
805     {
806         LPCWSTR destkey;
807         destkey = MSI_RecordGetString(row,5);
808         dest_path = resolve_folder(package, destkey, FALSE,FALSE,NULL);
809         if (!dest_path)
810         {
811             /* try a Property */
812             dest_path = msi_dup_property( package, destkey );
813             if (!dest_path)
814             {
815                 FIXME("Unable to get destination folder, try AppSearch properties\n");
816                 msi_free(file_source);
817                 return ERROR_SUCCESS;
818             }
819         }
820     }
821
822     dest = build_directory_name(2, dest_path, dest_name);
823
824     TRACE("Duplicating file %s to %s\n",debugstr_w(file_source),
825                     debugstr_w(dest)); 
826
827     if (strcmpW(file_source,dest))
828         rc = !CopyFileW(file_source,dest,TRUE);
829     else
830         rc = ERROR_SUCCESS;
831
832     if (rc != ERROR_SUCCESS)
833         ERR("Failed to copy file %s -> %s, last error %ld\n", debugstr_w(file_source), debugstr_w(dest_path), GetLastError());
834
835     FIXME("We should track these duplicate files as well\n");   
836
837     msi_free(dest_path);
838     msi_free(dest);
839     msi_free(file_source);
840
841     return ERROR_SUCCESS;
842 }
843
844 UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
845 {
846     UINT rc;
847     MSIQUERY * view;
848     static const WCHAR ExecSeqQuery[] =
849         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
850          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
851
852     if (!package)
853         return ERROR_INVALID_HANDLE;
854
855     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
856     if (rc != ERROR_SUCCESS)
857         return ERROR_SUCCESS;
858
859     rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
860     msiobj_release(&view->hdr);
861
862     return rc;
863 }