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