rpcrt4: Try a lot harder to resuse existing connections by comparing inside the RpcQu...
[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
286     ptr = strrchrW(mi->source, '\\') + 1;
287     lstrcpyW(ptr, mi->cabinet);
288     msiobj_release(&row->hdr);
289
290     return ERROR_SUCCESS;
291 }
292
293 static INT_PTR cabinet_notify(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
294 {
295     TRACE("(%d)\n", fdint);
296
297     switch (fdint)
298     {
299     case fdintPARTIAL_FILE:
300     {
301         CabData *data = (CabData *)pfdin->pv;
302         data->mi->is_continuous = FALSE;
303         return 0;
304     }
305     case fdintNEXT_CABINET:
306     {
307         CabData *data = (CabData *)pfdin->pv;
308         struct media_info *mi = data->mi;
309         LPWSTR cab = strdupAtoW(pfdin->psz1);
310         UINT rc;
311
312         msi_free(mi->disk_prompt);
313
314         mi->disk_id++;
315         mi->is_continuous = TRUE;
316
317         rc = msi_media_get_disk_info(data->package, mi);
318         if (rc != ERROR_SUCCESS)
319         {
320             ERR("Failed to get next cabinet information: %d\n", rc);
321             return -1;
322         }
323
324         if (lstrcmpiW(mi->cabinet, cab))
325         {
326             msi_free(cab);
327             ERR("Continuous cabinet does not match the next cabinet in the Media table\n");
328             return -1;
329         }
330
331         msi_free(cab);
332
333         TRACE("Searching for %s\n", debugstr_w(mi->source));
334
335         if (GetFileAttributesW(mi->source) == INVALID_FILE_ATTRIBUTES)
336             rc = msi_change_media(data->package, mi);
337
338         if (rc != ERROR_SUCCESS)
339             return -1;
340
341         return 0;
342     }
343     case fdintCOPY_FILE:
344     {
345         CabData *data = (CabData*) pfdin->pv;
346         HANDLE handle;
347         LPWSTR file;
348         MSIFILE *f;
349         DWORD attrs;
350
351         file = strdupAtoW(pfdin->psz1);
352         f = get_loaded_file(data->package, file);
353         msi_free(file);
354
355         if (!f)
356         {
357             WARN("unknown file in cabinet (%s)\n",debugstr_a(pfdin->psz1));
358             return 0;
359         }
360
361         if (f->state != msifs_missing && f->state != msifs_overwrite)
362         {
363             TRACE("Skipping extraction of %s\n",debugstr_a(pfdin->psz1));
364             return 0;
365         }
366
367         msi_file_update_ui( data->package, f, szInstallFiles );
368
369         TRACE("extracting %s\n", debugstr_w(f->TargetPath) );
370
371         attrs = f->Attributes & (FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
372         if (!attrs) attrs = FILE_ATTRIBUTE_NORMAL;
373
374         handle = CreateFileW( f->TargetPath, GENERIC_READ | GENERIC_WRITE, 0,
375                               NULL, CREATE_ALWAYS, attrs, NULL );
376         if ( handle == INVALID_HANDLE_VALUE )
377         {
378             if ( GetFileAttributesW( f->TargetPath ) != INVALID_FILE_ATTRIBUTES )
379                 f->state = msifs_installed;
380             else
381                 ERR("failed to create %s (error %d)\n",
382                     debugstr_w( f->TargetPath ), GetLastError() );
383
384             return 0;
385         }
386
387         f->state = msifs_installed;
388         return (INT_PTR) handle;
389     }
390     case fdintCLOSE_FILE_INFO:
391     {
392         FILETIME ft;
393         FILETIME ftLocal;
394         HANDLE handle = (HANDLE) pfdin->hf;
395
396         if (!DosDateTimeToFileTime(pfdin->date, pfdin->time, &ft))
397             return -1;
398         if (!LocalFileTimeToFileTime(&ft, &ftLocal))
399             return -1;
400         if (!SetFileTime(handle, &ftLocal, 0, &ftLocal))
401             return -1;
402         CloseHandle(handle);
403         return 1;
404     }
405     default:
406         return 0;
407     }
408 }
409
410 /***********************************************************************
411  *            extract_cabinet_file
412  *
413  * Extract files from a cab file.
414  */
415 static BOOL extract_cabinet_file(MSIPACKAGE* package, struct media_info *mi)
416 {
417     LPSTR cabinet, cab_path = NULL;
418     LPWSTR ptr;
419     HFDI hfdi;
420     ERF erf;
421     BOOL ret = FALSE;
422     CabData data;
423
424     TRACE("Extracting %s\n", debugstr_w(mi->source));
425
426     hfdi = FDICreate(cabinet_alloc, cabinet_free, cabinet_open, cabinet_read,
427                      cabinet_write, cabinet_close, cabinet_seek, 0, &erf);
428     if (!hfdi)
429     {
430         ERR("FDICreate failed\n");
431         return FALSE;
432     }
433
434     ptr = strrchrW(mi->source, '\\') + 1;
435     cabinet = strdupWtoA(ptr);
436     if (!cabinet)
437         goto done;
438
439     cab_path = strdupWtoA(mi->source);
440     if (!cab_path)
441         goto done;
442
443     cab_path[ptr - mi->source] = '\0';
444
445     data.package = package;
446     data.mi = mi;
447
448     ret = FDICopy(hfdi, cabinet, cab_path, 0, cabinet_notify, NULL, &data);
449     if (!ret)
450         ERR("FDICopy failed\n");
451
452 done:
453     FDIDestroy(hfdi);
454     msi_free(cabinet);
455     msi_free(cab_path);
456
457     if (ret)
458         mi->is_extracted = TRUE;
459
460     return ret;
461 }
462
463 static VOID set_file_source(MSIPACKAGE* package, MSIFILE* file, LPCWSTR path)
464 {
465     if (!file->IsCompressed)
466     {
467         LPWSTR p, path;
468         p = resolve_folder(package, file->Component->Directory, TRUE, FALSE, TRUE, NULL);
469         path = build_directory_name(2, p, file->ShortName);
470         if (file->LongName &&
471             INVALID_FILE_ATTRIBUTES == GetFileAttributesW( path ))
472         {
473             msi_free(path);
474             path = build_directory_name(2, p, file->LongName);
475         }
476         file->SourcePath = path;
477         msi_free(p);
478     }
479     else
480         file->SourcePath = build_directory_name(2, path, file->File);
481 }
482
483 static void free_media_info( struct media_info *mi )
484 {
485     msi_free( mi->disk_prompt );
486     msi_free( mi->cabinet );
487     msi_free( mi->volume_label );
488     msi_free( mi );
489 }
490
491 static UINT download_remote_cabinet(MSIPACKAGE *package, struct media_info *mi)
492 {
493     WCHAR temppath[MAX_PATH];
494     LPWSTR src, ptr;
495     LPCWSTR cab;
496
497     src = strdupW(package->BaseURL);
498     if (!src)
499         return ERROR_OUTOFMEMORY;
500
501     ptr = strrchrW(src, '/');
502     if (!ptr)
503     {
504         msi_free(src);
505         return ERROR_FUNCTION_FAILED;
506     }
507
508     *(ptr + 1) = '\0';
509     ptr = strrchrW(mi->source, '\\');
510     if (!ptr)
511         ptr = mi->source;
512
513     src = msi_realloc(src, (lstrlenW(src) + lstrlenW(ptr)) * sizeof(WCHAR));
514     if (!src)
515         return ERROR_OUTOFMEMORY;
516
517     lstrcatW(src, ptr + 1);
518
519     temppath[0] = '\0';
520     cab = msi_download_file(src, temppath);
521     lstrcpyW(mi->source, cab);
522
523     msi_free(src);
524     return ERROR_SUCCESS;
525 }
526
527 static UINT load_media_info(MSIPACKAGE *package, MSIFILE *file, struct media_info *mi)
528 {
529     MSIRECORD *row;
530     LPWSTR source_dir;
531     UINT r;
532
533     static const WCHAR query[] = {
534         'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
535         '`','M','e','d','i','a','`',' ','W','H','E','R','E',' ',
536         '`','L','a','s','t','S','e','q','u','e','n','c','e','`',' ','>','=',
537         ' ','%','i',' ','A','N','D',' ','`','D','i','s','k','I','d','`',' ','>','=',
538         ' ','%','i',' ','O','R','D','E','R',' ','B','Y',' ',
539         '`','D','i','s','k','I','d','`',0
540     };
541
542     row = MSI_QueryGetRecord(package->db, query, file->Sequence, mi->disk_id);
543     if (!row)
544     {
545         TRACE("Unable to query row\n");
546         return ERROR_FUNCTION_FAILED;
547     }
548
549     mi->is_extracted = FALSE;
550     mi->disk_id = MSI_RecordGetInteger(row, 1);
551     mi->last_sequence = MSI_RecordGetInteger(row, 2);
552     msi_free(mi->disk_prompt);
553     mi->disk_prompt = strdupW(MSI_RecordGetString(row, 3));
554     msi_free(mi->cabinet);
555     mi->cabinet = strdupW(MSI_RecordGetString(row, 4));
556     msi_free(mi->volume_label);
557     mi->volume_label = strdupW(MSI_RecordGetString(row, 5));
558     msiobj_release(&row->hdr);
559
560     source_dir = msi_dup_property(package, cszSourceDir);
561
562     if (mi->cabinet && mi->cabinet[0] == '#')
563     {
564         r = writeout_cabinet_stream(package, &mi->cabinet[1], mi->source);
565         if (r != ERROR_SUCCESS)
566         {
567             ERR("Failed to extract cabinet stream\n");
568             return ERROR_FUNCTION_FAILED;
569         }
570     }
571     else
572     {
573         lstrcpyW(mi->source, source_dir);
574
575
576         if (mi->cabinet)
577             lstrcatW(mi->source, mi->cabinet);
578     }
579
580     MsiSourceListAddMediaDiskW(package->ProductCode, NULL,
581         MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT,
582         mi->disk_id, mi->volume_label, mi->disk_prompt);
583
584     MsiSourceListSetInfoW(package->ProductCode, NULL,
585         MSIINSTALLCONTEXT_USERMANAGED,
586         MSICODE_PRODUCT | MSISOURCETYPE_MEDIA,
587         INSTALLPROPERTY_LASTUSEDSOURCEW, mi->source);
588
589     msi_free(source_dir);
590     return ERROR_SUCCESS;
591 }
592
593 static UINT ready_media(MSIPACKAGE *package, MSIFILE *file, struct media_info *mi)
594 {
595     UINT rc = ERROR_SUCCESS, type;
596     BOOL found = TRUE;
597     LPWSTR source_dir;
598
599     /* media info for continuous cabinet is already loaded */
600     if (mi->is_continuous)
601         return ERROR_SUCCESS;
602
603     rc = load_media_info(package, file, mi);
604     if (rc != ERROR_SUCCESS)
605     {
606         ERR("Unable to load media info\n");
607         return ERROR_FUNCTION_FAILED;
608     }
609
610     if (mi->volume_label && mi->disk_id > 1)
611     {
612         source_dir = msi_dup_property(package, cszSourceDir);
613         PathStripToRootW(source_dir);
614         type = GetDriveTypeW(source_dir);
615
616         if (type == DRIVE_CDROM || type == DRIVE_REMOVABLE)
617             found = source_matches_volume(mi, source_dir);
618
619         if (!found)
620             found = GetFileAttributesW(mi->cabinet) != INVALID_FILE_ATTRIBUTES;
621
622         msi_free(source_dir);
623     }
624
625     if (file->IsCompressed &&
626         GetFileAttributesW(mi->source) == INVALID_FILE_ATTRIBUTES)
627     {
628         found = FALSE;
629
630         if (package->BaseURL && UrlIsW(package->BaseURL, URLIS_URL))
631         {
632             rc = download_remote_cabinet(package, mi);
633             if (rc == ERROR_SUCCESS &&
634                 GetFileAttributesW(mi->source) != INVALID_FILE_ATTRIBUTES)
635             {
636                 found = TRUE;
637             }
638         }
639     }
640
641     if (!found)
642         rc = msi_change_media(package, mi);
643
644     return rc;
645 }
646
647 static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
648                             MSIFILE** file)
649 {
650     LIST_FOR_EACH_ENTRY( *file, &package->files, MSIFILE, entry )
651     {
652         if (lstrcmpW( file_key, (*file)->File )==0)
653         {
654             if ((*file)->state >= msifs_overwrite)
655                 return ERROR_SUCCESS;
656             else
657                 return ERROR_FILE_NOT_FOUND;
658         }
659     }
660
661     return ERROR_FUNCTION_FAILED;
662 }
663
664 static void schedule_install_files(MSIPACKAGE *package)
665 {
666     MSIFILE *file;
667
668     LIST_FOR_EACH_ENTRY(file, &package->files, MSIFILE, entry)
669     {
670         if (!ACTION_VerifyComponentForAction(file->Component, INSTALLSTATE_LOCAL))
671         {
672             TRACE("File %s is not scheduled for install\n", debugstr_w(file->File));
673
674             ui_progress(package,2,file->FileSize,0,0);
675             file->state = msifs_skipped;
676         }
677     }
678 }
679
680 static UINT copy_file(MSIFILE *file)
681 {
682     BOOL ret;
683
684     ret = CopyFileW(file->SourcePath, file->TargetPath, FALSE);
685     if (ret)
686     {
687         file->state = msifs_installed;
688         return ERROR_SUCCESS;
689     }
690
691     return GetLastError();
692 }
693
694 static UINT copy_install_file(MSIFILE *file)
695 {
696     UINT gle;
697
698     TRACE("Copying %s to %s\n", debugstr_w(file->SourcePath),
699           debugstr_w(file->TargetPath));
700
701     gle = copy_file(file);
702     if (gle == ERROR_SUCCESS)
703         return gle;
704
705     if (gle == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
706     {
707         TRACE("overwriting existing file\n");
708         gle = ERROR_SUCCESS;
709     }
710     else if (gle == ERROR_FILE_NOT_FOUND)
711     {
712         /* FIXME: this needs to be tested, I'm pretty sure it fails */
713         TRACE("Source file not found\n");
714         gle = ERROR_SUCCESS;
715     }
716     else if (gle == ERROR_ACCESS_DENIED)
717     {
718         SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
719
720         gle = copy_file(file);
721         TRACE("Overwriting existing file: %d\n", gle);
722     }
723     else if (!(file->Attributes & msidbFileAttributesVital))
724     {
725         TRACE("Ignoring error for nonvital\n");
726         gle = ERROR_SUCCESS;
727     }
728
729     return gle;
730 }
731
732 /*
733  * ACTION_InstallFiles()
734  * 
735  * For efficiency, this is done in two passes:
736  * 1) Correct all the TargetPaths and determine what files are to be installed.
737  * 2) Extract Cabinets and copy files.
738  */
739 UINT ACTION_InstallFiles(MSIPACKAGE *package)
740 {
741     struct media_info *mi;
742     UINT rc = ERROR_SUCCESS;
743     LPWSTR ptr;
744     MSIFILE *file;
745
746     /* increment progress bar each time action data is sent */
747     ui_progress(package,1,1,0,0);
748
749     /* handle the keys for the SourceList */
750     ptr = strrchrW(package->PackagePath,'\\');
751     if (ptr)
752     {
753         ptr++;
754         MsiSourceListSetInfoW(package->ProductCode, NULL,
755                 MSIINSTALLCONTEXT_USERMANAGED,
756                 MSICODE_PRODUCT,
757                 INSTALLPROPERTY_PACKAGENAMEW, ptr);
758     }
759
760     schedule_install_files(package);
761
762     /*
763      * Despite MSDN specifying that the CreateFolders action
764      * should be called before InstallFiles, some installers don't
765      * do that, and they seem to work correctly.  We need to create
766      * directories here to make sure that the files can be copied.
767      */
768     msi_create_component_directories( package );
769
770     mi = msi_alloc_zero( sizeof(struct media_info) );
771
772     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
773     {
774         if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
775             continue;
776
777         if (file->Sequence > mi->last_sequence || mi->is_continuous ||
778             (file->IsCompressed && !mi->is_extracted))
779         {
780             rc = ready_media(package, file, mi);
781             if (rc != ERROR_SUCCESS)
782             {
783                 ERR("Failed to ready media\n");
784                 rc = ERROR_FUNCTION_FAILED;
785                 break;
786             }
787
788             if (file->IsCompressed && !extract_cabinet_file(package, mi))
789             {
790                 ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
791                 rc = ERROR_FUNCTION_FAILED;
792                 break;
793             }
794         }
795
796         set_file_source(package, file, mi->source);
797
798         TRACE("file paths %s to %s\n",debugstr_w(file->SourcePath),
799               debugstr_w(file->TargetPath));
800
801         if (!file->IsCompressed)
802         {
803             msi_file_update_ui(package, file, szInstallFiles);
804             rc = copy_install_file(file);
805             if (rc != ERROR_SUCCESS)
806             {
807                 ERR("Failed to copy %s to %s (%d)\n", debugstr_w(file->SourcePath),
808                     debugstr_w(file->TargetPath), rc);
809                 rc = ERROR_INSTALL_FAILURE;
810                 break;
811             }
812         }
813         else if (file->state != msifs_installed)
814         {
815             ERR("compressed file wasn't extracted (%s)\n", debugstr_w(file->TargetPath));
816             rc = ERROR_INSTALL_FAILURE;
817             break;
818         }
819     }
820
821     free_media_info( mi );
822     return rc;
823 }
824
825 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
826 {
827     MSIPACKAGE *package = (MSIPACKAGE*)param;
828     WCHAR dest_name[0x100];
829     LPWSTR dest_path, dest;
830     LPCWSTR file_key, component;
831     DWORD sz;
832     DWORD rc;
833     MSICOMPONENT *comp;
834     MSIFILE *file;
835
836     component = MSI_RecordGetString(row,2);
837     comp = get_loaded_component(package,component);
838
839     if (!ACTION_VerifyComponentForAction( comp, INSTALLSTATE_LOCAL ))
840     {
841         TRACE("Skipping copy due to disabled component %s\n",
842                         debugstr_w(component));
843
844         /* the action taken was the same as the current install state */        
845         comp->Action = comp->Installed;
846
847         return ERROR_SUCCESS;
848     }
849
850     comp->Action = INSTALLSTATE_LOCAL;
851
852     file_key = MSI_RecordGetString(row,3);
853     if (!file_key)
854     {
855         ERR("Unable to get file key\n");
856         return ERROR_FUNCTION_FAILED;
857     }
858
859     rc = get_file_target(package,file_key,&file);
860
861     if (rc != ERROR_SUCCESS)
862     {
863         ERR("Original file unknown %s\n",debugstr_w(file_key));
864         return ERROR_SUCCESS;
865     }
866
867     if (MSI_RecordIsNull(row,4))
868         strcpyW(dest_name,strrchrW(file->TargetPath,'\\')+1);
869     else
870     {
871         sz=0x100;
872         MSI_RecordGetStringW(row,4,dest_name,&sz);
873         reduce_to_longfilename(dest_name);
874     }
875
876     if (MSI_RecordIsNull(row,5))
877     {
878         LPWSTR p;
879         dest_path = strdupW(file->TargetPath);
880         p = strrchrW(dest_path,'\\');
881         if (p)
882             *p=0;
883     }
884     else
885     {
886         LPCWSTR destkey;
887         destkey = MSI_RecordGetString(row,5);
888         dest_path = resolve_folder(package, destkey, FALSE, FALSE, TRUE, NULL);
889         if (!dest_path)
890         {
891             /* try a Property */
892             dest_path = msi_dup_property( package, destkey );
893             if (!dest_path)
894             {
895                 FIXME("Unable to get destination folder, try AppSearch properties\n");
896                 return ERROR_SUCCESS;
897             }
898         }
899     }
900
901     dest = build_directory_name(2, dest_path, dest_name);
902
903     TRACE("Duplicating file %s to %s\n",debugstr_w(file->TargetPath),
904                     debugstr_w(dest)); 
905
906     CreateDirectoryW(dest_path, NULL);
907
908     if (strcmpW(file->TargetPath,dest))
909         rc = !CopyFileW(file->TargetPath,dest,TRUE);
910     else
911         rc = ERROR_SUCCESS;
912
913     if (rc != ERROR_SUCCESS)
914         ERR("Failed to copy file %s -> %s, last error %d\n",
915             debugstr_w(file->TargetPath), debugstr_w(dest_path), GetLastError());
916
917     FIXME("We should track these duplicate files as well\n");   
918
919     msi_free(dest_path);
920     msi_free(dest);
921
922     msi_file_update_ui(package, file, szDuplicateFiles);
923
924     return ERROR_SUCCESS;
925 }
926
927 UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
928 {
929     UINT rc;
930     MSIQUERY * view;
931     static const WCHAR ExecSeqQuery[] =
932         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
933          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
934
935     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
936     if (rc != ERROR_SUCCESS)
937         return ERROR_SUCCESS;
938
939     rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
940     msiobj_release(&view->hdr);
941
942     return rc;
943 }
944
945 /* compares the version of a file read from the filesystem and
946  * the version specified in the File table
947  */
948 static int msi_compare_file_version( MSIFILE *file )
949 {
950     WCHAR version[MAX_PATH];
951     DWORD size;
952     UINT r;
953
954     size = MAX_PATH;
955     version[0] = '\0';
956     r = MsiGetFileVersionW( file->TargetPath, version, &size, NULL, NULL );
957     if ( r != ERROR_SUCCESS )
958         return 0;
959
960     return lstrcmpW( version, file->Version );
961 }
962
963 UINT ACTION_RemoveFiles( MSIPACKAGE *package )
964 {
965     MSIFILE *file;
966
967     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
968     {
969         MSIRECORD *uirow;
970         LPWSTR uipath, p;
971
972         if ( !file->Component )
973             continue;
974         if ( file->Component->Installed == INSTALLSTATE_LOCAL )
975             continue;
976
977         if ( file->state == msifs_installed )
978             ERR("removing installed file %s\n", debugstr_w(file->TargetPath));
979
980         if ( file->state != msifs_present )
981             continue;
982
983         /* only remove a file if the version to be installed
984          * is strictly newer than the old file
985          */
986         if ( msi_compare_file_version( file ) >= 0 )
987             continue;
988
989         TRACE("removing %s\n", debugstr_w(file->File) );
990         if ( !DeleteFileW( file->TargetPath ) )
991             ERR("failed to delete %s\n",  debugstr_w(file->TargetPath) );
992         file->state = msifs_missing;
993
994         /* the UI chunk */
995         uirow = MSI_CreateRecord( 9 );
996         MSI_RecordSetStringW( uirow, 1, file->FileName );
997         uipath = strdupW( file->TargetPath );
998         p = strrchrW(uipath,'\\');
999         if (p)
1000             p[1]=0;
1001         MSI_RecordSetStringW( uirow, 9, uipath);
1002         ui_actiondata( package, szRemoveFiles, uirow);
1003         msiobj_release( &uirow->hdr );
1004         msi_free( uipath );
1005         /* FIXME: call ui_progress here? */
1006     }
1007
1008     return ERROR_SUCCESS;
1009 }