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