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