msi: Add tests for registering and unregistering MIME info.
[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
28  * PatchFiles (TODO)
29  * RemoveDuplicateFiles
30  * RemoveFiles
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 "msipriv.h"
43 #include "winuser.h"
44 #include "winreg.h"
45 #include "shlwapi.h"
46 #include "wine/unicode.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(msi);
49
50 static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *action )
51 {
52     MSIRECORD *uirow;
53     LPWSTR uipath, p;
54
55     /* the UI chunk */
56     uirow = MSI_CreateRecord( 9 );
57     MSI_RecordSetStringW( uirow, 1, f->FileName );
58     uipath = strdupW( f->TargetPath );
59     p = strrchrW(uipath,'\\');
60     if (p)
61         p[1]=0;
62     MSI_RecordSetStringW( uirow, 9, uipath);
63     MSI_RecordSetInteger( uirow, 6, f->FileSize );
64     ui_actiondata( package, action, uirow);
65     msiobj_release( &uirow->hdr );
66     msi_free( uipath );
67     ui_progress( package, 2, f->FileSize, 0, 0);
68 }
69
70 /* compares the version of a file read from the filesystem and
71  * the version specified in the File table
72  */
73 static int msi_compare_file_version(MSIFILE *file)
74 {
75     WCHAR version[MAX_PATH];
76     DWORD size;
77     UINT r;
78
79     size = MAX_PATH;
80     version[0] = '\0';
81     r = MsiGetFileVersionW(file->TargetPath, version, &size, NULL, NULL);
82     if (r != ERROR_SUCCESS)
83         return 0;
84
85     return lstrcmpW(version, file->Version);
86 }
87
88 static void schedule_install_files(MSIPACKAGE *package)
89 {
90     MSIFILE *file;
91
92     LIST_FOR_EACH_ENTRY(file, &package->files, MSIFILE, entry)
93     {
94         if (file->Component->ActionRequest != INSTALLSTATE_LOCAL)
95         {
96             TRACE("File %s is not scheduled for install\n", debugstr_w(file->File));
97
98             ui_progress(package,2,file->FileSize,0,0);
99             file->state = msifs_skipped;
100         }
101         else
102             file->Component->Action = INSTALLSTATE_LOCAL;
103     }
104 }
105
106 static UINT copy_file(MSIFILE *file, LPWSTR source)
107 {
108     BOOL ret;
109
110     ret = CopyFileW(source, file->TargetPath, FALSE);
111     if (!ret)
112         return GetLastError();
113
114     SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
115
116     file->state = msifs_installed;
117     return ERROR_SUCCESS;
118 }
119
120 static UINT copy_install_file(MSIPACKAGE *package, MSIFILE *file, LPWSTR source)
121 {
122     UINT gle;
123
124     TRACE("Copying %s to %s\n", debugstr_w(source),
125           debugstr_w(file->TargetPath));
126
127     gle = copy_file(file, source);
128     if (gle == ERROR_SUCCESS)
129         return gle;
130
131     if (gle == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
132     {
133         TRACE("overwriting existing file\n");
134         return ERROR_SUCCESS;
135     }
136     else if (gle == ERROR_ACCESS_DENIED)
137     {
138         SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
139
140         gle = copy_file(file, source);
141         TRACE("Overwriting existing file: %d\n", gle);
142     }
143     if (gle == ERROR_SHARING_VIOLATION || gle == ERROR_USER_MAPPED_FILE)
144     {
145         WCHAR tmpfileW[MAX_PATH], *pathW, *p;
146         DWORD len;
147
148         TRACE("file in use, scheduling rename operation\n");
149
150         GetTempFileNameW(szBackSlash, szMsi, 0, tmpfileW);
151         len = strlenW(file->TargetPath) + strlenW(tmpfileW) + 1;
152         if (!(pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
153             return ERROR_OUTOFMEMORY;
154
155         strcpyW(pathW, file->TargetPath);
156         if ((p = strrchrW(pathW, '\\'))) *p = 0;
157         strcatW(pathW, tmpfileW);
158
159         if (CopyFileW(source, pathW, FALSE) &&
160             MoveFileExW(file->TargetPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT) &&
161             MoveFileExW(pathW, file->TargetPath, MOVEFILE_DELAY_UNTIL_REBOOT))
162         {
163             file->state = msifs_installed;
164             package->need_reboot = 1;
165             gle = ERROR_SUCCESS;
166         }
167         else
168         {
169             gle = GetLastError();
170             WARN("failed to schedule rename operation: %d)\n", gle);
171         }
172         HeapFree(GetProcessHeap(), 0, pathW);
173     }
174
175     return gle;
176 }
177
178 static BOOL check_dest_hash_matches(MSIFILE *file)
179 {
180     MSIFILEHASHINFO hash;
181     UINT r;
182
183     if (!file->hash.dwFileHashInfoSize)
184         return FALSE;
185
186     hash.dwFileHashInfoSize = sizeof(MSIFILEHASHINFO);
187     r = MsiGetFileHashW(file->TargetPath, 0, &hash);
188     if (r != ERROR_SUCCESS)
189         return FALSE;
190
191     return !memcmp(&hash, &file->hash, sizeof(MSIFILEHASHINFO));
192 }
193
194 static BOOL installfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
195                             LPWSTR *path, DWORD *attrs, PVOID user)
196 {
197     static MSIFILE *f = NULL;
198
199     if (action == MSICABEXTRACT_BEGINEXTRACT)
200     {
201         f = get_loaded_file(package, file);
202         if (!f)
203         {
204             WARN("unknown file in cabinet (%s)\n", debugstr_w(file));
205             return FALSE;
206         }
207
208         if (f->state != msifs_missing && f->state != msifs_overwrite)
209         {
210             TRACE("Skipping extraction of %s\n", debugstr_w(file));
211             return FALSE;
212         }
213
214         msi_file_update_ui(package, f, szInstallFiles);
215
216         *path = strdupW(f->TargetPath);
217         *attrs = f->Attributes;
218     }
219     else if (action == MSICABEXTRACT_FILEEXTRACTED)
220     {
221         f->state = msifs_installed;
222         f = NULL;
223     }
224
225     return TRUE;
226 }
227
228 /*
229  * ACTION_InstallFiles()
230  * 
231  * For efficiency, this is done in two passes:
232  * 1) Correct all the TargetPaths and determine what files are to be installed.
233  * 2) Extract Cabinets and copy files.
234  */
235 UINT ACTION_InstallFiles(MSIPACKAGE *package)
236 {
237     MSIMEDIAINFO *mi;
238     UINT rc = ERROR_SUCCESS;
239     MSIFILE *file;
240
241     /* increment progress bar each time action data is sent */
242     ui_progress(package,1,1,0,0);
243
244     schedule_install_files(package);
245
246     /*
247      * Despite MSDN specifying that the CreateFolders action
248      * should be called before InstallFiles, some installers don't
249      * do that, and they seem to work correctly.  We need to create
250      * directories here to make sure that the files can be copied.
251      */
252     msi_create_component_directories( package );
253
254     mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );
255
256     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
257     {
258         if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
259             continue;
260
261         if (check_dest_hash_matches(file))
262         {
263             TRACE("File hashes match, not overwriting\n");
264             continue;
265         }
266
267         if (MsiGetFileVersionW(file->TargetPath, NULL, NULL, NULL, NULL) == ERROR_SUCCESS &&
268             msi_compare_file_version(file) >= 0)
269         {
270             TRACE("Destination file version greater, not overwriting\n");
271             continue;
272         }
273
274         if (file->Sequence > mi->last_sequence || mi->is_continuous ||
275             (file->IsCompressed && !mi->is_extracted))
276         {
277             MSICABDATA data;
278
279             rc = ready_media(package, file, mi);
280             if (rc != ERROR_SUCCESS)
281             {
282                 ERR("Failed to ready media\n");
283                 break;
284             }
285
286             data.mi = mi;
287             data.package = package;
288             data.cb = installfiles_cb;
289             data.user = NULL;
290
291             if (file->IsCompressed &&
292                 !msi_cabextract(package, mi, &data))
293             {
294                 ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
295                 rc = ERROR_INSTALL_FAILURE;
296                 break;
297             }
298         }
299
300         if (!file->IsCompressed)
301         {
302             LPWSTR source = resolve_file_source(package, file);
303
304             TRACE("file paths %s to %s\n", debugstr_w(source),
305                   debugstr_w(file->TargetPath));
306
307             msi_file_update_ui(package, file, szInstallFiles);
308             rc = copy_install_file(package, file, source);
309             if (rc != ERROR_SUCCESS)
310             {
311                 ERR("Failed to copy %s to %s (%d)\n", debugstr_w(source),
312                     debugstr_w(file->TargetPath), rc);
313                 rc = ERROR_INSTALL_FAILURE;
314                 msi_free(source);
315                 break;
316             }
317
318             msi_free(source);
319         }
320         else if (file->state != msifs_installed)
321         {
322             ERR("compressed file wasn't extracted (%s)\n",
323                 debugstr_w(file->TargetPath));
324             rc = ERROR_INSTALL_FAILURE;
325             break;
326         }
327     }
328
329     msi_free_media_info(mi);
330     return rc;
331 }
332
333 #define is_dot_dir(x) ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
334
335 typedef struct
336 {
337     struct list entry;
338     LPWSTR sourcename;
339     LPWSTR destname;
340     LPWSTR source;
341     LPWSTR dest;
342 } FILE_LIST;
343
344 static BOOL msi_move_file(LPCWSTR source, LPCWSTR dest, int options)
345 {
346     BOOL ret;
347
348     if (GetFileAttributesW(source) == FILE_ATTRIBUTE_DIRECTORY ||
349         GetFileAttributesW(dest) == FILE_ATTRIBUTE_DIRECTORY)
350     {
351         WARN("Source or dest is directory, not moving\n");
352         return FALSE;
353     }
354
355     if (options == msidbMoveFileOptionsMove)
356     {
357         TRACE("moving %s -> %s\n", debugstr_w(source), debugstr_w(dest));
358         ret = MoveFileExW(source, dest, MOVEFILE_REPLACE_EXISTING);
359         if (!ret)
360         {
361             WARN("MoveFile failed: %d\n", GetLastError());
362             return FALSE;
363         }
364     }
365     else
366     {
367         TRACE("copying %s -> %s\n", debugstr_w(source), debugstr_w(dest));
368         ret = CopyFileW(source, dest, FALSE);
369         if (!ret)
370         {
371             WARN("CopyFile failed: %d\n", GetLastError());
372             return FALSE;
373         }
374     }
375
376     return TRUE;
377 }
378
379 static LPWSTR wildcard_to_file(LPWSTR wildcard, LPWSTR filename)
380 {
381     LPWSTR path, ptr;
382     DWORD dirlen, pathlen;
383
384     ptr = strrchrW(wildcard, '\\');
385     dirlen = ptr - wildcard + 1;
386
387     pathlen = dirlen + lstrlenW(filename) + 1;
388     path = msi_alloc(pathlen * sizeof(WCHAR));
389
390     lstrcpynW(path, wildcard, dirlen + 1);
391     lstrcatW(path, filename);
392
393     return path;
394 }
395
396 static void free_file_entry(FILE_LIST *file)
397 {
398     msi_free(file->source);
399     msi_free(file->dest);
400     msi_free(file);
401 }
402
403 static void free_list(FILE_LIST *list)
404 {
405     while (!list_empty(&list->entry))
406     {
407         FILE_LIST *file = LIST_ENTRY(list_head(&list->entry), FILE_LIST, entry);
408
409         list_remove(&file->entry);
410         free_file_entry(file);
411     }
412 }
413
414 static BOOL add_wildcard(FILE_LIST *files, LPWSTR source, LPWSTR dest)
415 {
416     FILE_LIST *new, *file;
417     LPWSTR ptr, filename;
418     DWORD size;
419
420     new = msi_alloc_zero(sizeof(FILE_LIST));
421     if (!new)
422         return FALSE;
423
424     new->source = strdupW(source);
425     ptr = strrchrW(dest, '\\') + 1;
426     filename = strrchrW(new->source, '\\') + 1;
427
428     new->sourcename = filename;
429
430     if (*ptr)
431         new->destname = ptr;
432     else
433         new->destname = new->sourcename;
434
435     size = (ptr - dest) + lstrlenW(filename) + 1;
436     new->dest = msi_alloc(size * sizeof(WCHAR));
437     if (!new->dest)
438     {
439         free_file_entry(new);
440         return FALSE;
441     }
442
443     lstrcpynW(new->dest, dest, ptr - dest + 1);
444     lstrcatW(new->dest, filename);
445
446     if (list_empty(&files->entry))
447     {
448         list_add_head(&files->entry, &new->entry);
449         return TRUE;
450     }
451
452     LIST_FOR_EACH_ENTRY(file, &files->entry, FILE_LIST, entry)
453     {
454         if (lstrcmpW(source, file->source) < 0)
455         {
456             list_add_before(&file->entry, &new->entry);
457             return TRUE;
458         }
459     }
460
461     list_add_after(&file->entry, &new->entry);
462     return TRUE;
463 }
464
465 static BOOL move_files_wildcard(LPWSTR source, LPWSTR dest, int options)
466 {
467     WIN32_FIND_DATAW wfd;
468     HANDLE hfile;
469     LPWSTR path;
470     BOOL res;
471     FILE_LIST files, *file;
472     DWORD size;
473
474     hfile = FindFirstFileW(source, &wfd);
475     if (hfile == INVALID_HANDLE_VALUE) return FALSE;
476
477     list_init(&files.entry);
478
479     for (res = TRUE; res; res = FindNextFileW(hfile, &wfd))
480     {
481         if (is_dot_dir(wfd.cFileName)) continue;
482
483         path = wildcard_to_file(source, wfd.cFileName);
484         if (!path)
485         {
486             res = FALSE;
487             goto done;
488         }
489
490         add_wildcard(&files, path, dest);
491         msi_free(path);
492     }
493
494     /* no files match the wildcard */
495     if (list_empty(&files.entry))
496         goto done;
497
498     /* only the first wildcard match gets renamed to dest */
499     file = LIST_ENTRY(list_head(&files.entry), FILE_LIST, entry);
500     size = (strrchrW(file->dest, '\\') - file->dest) + lstrlenW(file->destname) + 2;
501     file->dest = msi_realloc(file->dest, size * sizeof(WCHAR));
502     if (!file->dest)
503     {
504         res = FALSE;
505         goto done;
506     }
507
508     /* file->dest may be shorter after the reallocation, so add a NULL
509      * terminator.  This is needed for the call to strrchrW, as there will no
510      * longer be a NULL terminator within the bounds of the allocation in this case.
511      */
512     file->dest[size - 1] = '\0';
513     lstrcpyW(strrchrW(file->dest, '\\') + 1, file->destname);
514
515     while (!list_empty(&files.entry))
516     {
517         file = LIST_ENTRY(list_head(&files.entry), FILE_LIST, entry);
518
519         msi_move_file(file->source, file->dest, options);
520
521         list_remove(&file->entry);
522         free_file_entry(file);
523     }
524
525     res = TRUE;
526
527 done:
528     free_list(&files);
529     FindClose(hfile);
530     return res;
531 }
532
533 static UINT ITERATE_MoveFiles( MSIRECORD *rec, LPVOID param )
534 {
535     MSIPACKAGE *package = param;
536     MSIRECORD *uirow;
537     MSICOMPONENT *comp;
538     LPCWSTR sourcename, component;
539     LPWSTR sourcedir, destname = NULL, destdir = NULL, source = NULL, dest = NULL;
540     int options;
541     DWORD size;
542     BOOL ret, wildcards;
543
544     component = MSI_RecordGetString(rec, 2);
545     comp = get_loaded_component(package, component);
546     if (!comp)
547         return ERROR_SUCCESS;
548
549     if (comp->ActionRequest != INSTALLSTATE_LOCAL && comp->ActionRequest != INSTALLSTATE_SOURCE)
550     {
551         TRACE("Component not scheduled for installation: %s\n", debugstr_w(component));
552         comp->Action = comp->Installed;
553         return ERROR_SUCCESS;
554     }
555     comp->Action = comp->ActionRequest;
556
557     sourcename = MSI_RecordGetString(rec, 3);
558     options = MSI_RecordGetInteger(rec, 7);
559
560     sourcedir = msi_dup_property(package, MSI_RecordGetString(rec, 5));
561     if (!sourcedir)
562         goto done;
563
564     destdir = msi_dup_property(package, MSI_RecordGetString(rec, 6));
565     if (!destdir)
566         goto done;
567
568     if (!sourcename)
569     {
570         if (GetFileAttributesW(sourcedir) == INVALID_FILE_ATTRIBUTES)
571             goto done;
572
573         source = strdupW(sourcedir);
574         if (!source)
575             goto done;
576     }
577     else
578     {
579         size = lstrlenW(sourcedir) + lstrlenW(sourcename) + 2;
580         source = msi_alloc(size * sizeof(WCHAR));
581         if (!source)
582             goto done;
583
584         lstrcpyW(source, sourcedir);
585         if (source[lstrlenW(source) - 1] != '\\')
586             lstrcatW(source, szBackSlash);
587         lstrcatW(source, sourcename);
588     }
589
590     wildcards = strchrW(source, '*') || strchrW(source, '?');
591
592     if (MSI_RecordIsNull(rec, 4))
593     {
594         if (!wildcards)
595         {
596             destname = strdupW(sourcename);
597             if (!destname)
598                 goto done;
599         }
600     }
601     else
602     {
603         destname = strdupW(MSI_RecordGetString(rec, 4));
604         if (destname)
605             reduce_to_longfilename(destname);
606     }
607
608     size = 0;
609     if (destname)
610         size = lstrlenW(destname);
611
612     size += lstrlenW(destdir) + 2;
613     dest = msi_alloc(size * sizeof(WCHAR));
614     if (!dest)
615         goto done;
616
617     lstrcpyW(dest, destdir);
618     if (dest[lstrlenW(dest) - 1] != '\\')
619         lstrcatW(dest, szBackSlash);
620
621     if (destname)
622         lstrcatW(dest, destname);
623
624     if (GetFileAttributesW(destdir) == INVALID_FILE_ATTRIBUTES)
625     {
626         ret = CreateDirectoryW(destdir, NULL);
627         if (!ret)
628         {
629             WARN("CreateDirectory failed: %d\n", GetLastError());
630             goto done;
631         }
632     }
633
634     if (!wildcards)
635         msi_move_file(source, dest, options);
636     else
637         move_files_wildcard(source, dest, options);
638
639 done:
640     uirow = MSI_CreateRecord( 9 );
641     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(rec, 1) );
642     MSI_RecordSetInteger( uirow, 6, 1 ); /* FIXME */
643     MSI_RecordSetStringW( uirow, 9, destdir );
644     ui_actiondata( package, szMoveFiles, uirow );
645     msiobj_release( &uirow->hdr );
646
647     msi_free(sourcedir);
648     msi_free(destdir);
649     msi_free(destname);
650     msi_free(source);
651     msi_free(dest);
652
653     return ERROR_SUCCESS;
654 }
655
656 UINT ACTION_MoveFiles( MSIPACKAGE *package )
657 {
658     UINT rc;
659     MSIQUERY *view;
660
661     static const WCHAR ExecSeqQuery[] =
662         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
663          '`','M','o','v','e','F','i','l','e','`',0};
664
665     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
666     if (rc != ERROR_SUCCESS)
667         return ERROR_SUCCESS;
668
669     rc = MSI_IterateRecords(view, NULL, ITERATE_MoveFiles, package);
670     msiobj_release(&view->hdr);
671
672     return rc;
673 }
674
675 static WCHAR *get_duplicate_filename( MSIPACKAGE *package, MSIRECORD *row, const WCHAR *file_key, const WCHAR *src )
676 {
677     DWORD len;
678     WCHAR *dst_name, *dst_path, *dst;
679
680     if (MSI_RecordIsNull( row, 4 ))
681     {
682         len = strlenW( src ) + 1;
683         if (!(dst_name = msi_alloc( len * sizeof(WCHAR)))) return NULL;
684         strcpyW( dst_name, strrchrW( src, '\\' ) + 1 );
685     }
686     else
687     {
688         MSI_RecordGetStringW( row, 4, NULL, &len );
689         if (!(dst_name = msi_alloc( ++len * sizeof(WCHAR) ))) return NULL;
690         MSI_RecordGetStringW( row, 4, dst_name, &len );
691         reduce_to_longfilename( dst_name );
692     }
693
694     if (MSI_RecordIsNull( row, 5 ))
695     {
696         WCHAR *p;
697         dst_path = strdupW( src );
698         p = strrchrW( dst_path, '\\' );
699         if (p) *p = 0;
700     }
701     else
702     {
703         const WCHAR *dst_key = MSI_RecordGetString( row, 5 );
704
705         dst_path = resolve_folder( package, dst_key, FALSE, FALSE, TRUE, NULL );
706         if (!dst_path)
707         {
708             /* try a property */
709             dst_path = msi_dup_property( package, dst_key );
710             if (!dst_path)
711             {
712                 FIXME("Unable to get destination folder, try AppSearch properties\n");
713                 msi_free( dst_name );
714                 return NULL;
715             }
716         }
717     }
718
719     dst = build_directory_name( 2, dst_path, dst_name );
720     create_full_pathW( dst_path );
721
722     msi_free( dst_name );
723     msi_free( dst_path );
724     return dst;
725 }
726
727 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
728 {
729     MSIPACKAGE *package = param;
730     LPWSTR dest;
731     LPCWSTR file_key, component;
732     MSICOMPONENT *comp;
733     MSIRECORD *uirow;
734     MSIFILE *file;
735
736     component = MSI_RecordGetString(row,2);
737     comp = get_loaded_component(package,component);
738     if (!comp)
739         return ERROR_SUCCESS;
740
741     if (comp->ActionRequest != INSTALLSTATE_LOCAL)
742     {
743         TRACE("Component not scheduled for installation %s\n", debugstr_w(component));
744         comp->Action = comp->Installed;
745         return ERROR_SUCCESS;
746     }
747     comp->Action = INSTALLSTATE_LOCAL;
748
749     file_key = MSI_RecordGetString(row,3);
750     if (!file_key)
751     {
752         ERR("Unable to get file key\n");
753         return ERROR_FUNCTION_FAILED;
754     }
755
756     file = get_loaded_file( package, file_key );
757     if (!file)
758     {
759         ERR("Original file unknown %s\n", debugstr_w(file_key));
760         return ERROR_SUCCESS;
761     }
762
763     dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
764     if (!dest)
765     {
766         WARN("Unable to get duplicate filename\n");
767         return ERROR_SUCCESS;
768     }
769
770     TRACE("Duplicating file %s to %s\n", debugstr_w(file->TargetPath), debugstr_w(dest));
771
772     if (!CopyFileW( file->TargetPath, dest, TRUE ))
773     {
774         WARN("Failed to copy file %s -> %s (%u)\n",
775              debugstr_w(file->TargetPath), debugstr_w(dest), GetLastError());
776     }
777
778     FIXME("We should track these duplicate files as well\n");   
779
780     uirow = MSI_CreateRecord( 9 );
781     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString( row, 1 ) );
782     MSI_RecordSetInteger( uirow, 6, file->FileSize );
783     MSI_RecordSetStringW( uirow, 9, MSI_RecordGetString( row, 5 ) );
784     ui_actiondata( package, szDuplicateFiles, uirow );
785     msiobj_release( &uirow->hdr );
786
787     msi_free(dest);
788     return ERROR_SUCCESS;
789 }
790
791 UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
792 {
793     UINT rc;
794     MSIQUERY * view;
795     static const WCHAR ExecSeqQuery[] =
796         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
797          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
798
799     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
800     if (rc != ERROR_SUCCESS)
801         return ERROR_SUCCESS;
802
803     rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
804     msiobj_release(&view->hdr);
805
806     return rc;
807 }
808
809 static UINT ITERATE_RemoveDuplicateFiles( MSIRECORD *row, LPVOID param )
810 {
811     MSIPACKAGE *package = param;
812     LPWSTR dest;
813     LPCWSTR file_key, component;
814     MSICOMPONENT *comp;
815     MSIRECORD *uirow;
816     MSIFILE *file;
817
818     component = MSI_RecordGetString( row, 2 );
819     comp = get_loaded_component( package, component );
820     if (!comp)
821         return ERROR_SUCCESS;
822
823     if (comp->ActionRequest != INSTALLSTATE_ABSENT)
824     {
825         TRACE("Component not scheduled for removal %s\n", debugstr_w(component));
826         comp->Action = comp->Installed;
827         return ERROR_SUCCESS;
828     }
829     comp->Action = INSTALLSTATE_ABSENT;
830
831     file_key = MSI_RecordGetString( row, 3 );
832     if (!file_key)
833     {
834         ERR("Unable to get file key\n");
835         return ERROR_FUNCTION_FAILED;
836     }
837
838     file = get_loaded_file( package, file_key );
839     if (!file)
840     {
841         ERR("Original file unknown %s\n", debugstr_w(file_key));
842         return ERROR_SUCCESS;
843     }
844
845     dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
846     if (!dest)
847     {
848         WARN("Unable to get duplicate filename\n");
849         return ERROR_SUCCESS;
850     }
851
852     TRACE("Removing duplicate %s of %s\n", debugstr_w(dest), debugstr_w(file->TargetPath));
853
854     if (!DeleteFileW( dest ))
855     {
856         WARN("Failed to delete duplicate file %s (%u)\n", debugstr_w(dest), GetLastError());
857     }
858
859     uirow = MSI_CreateRecord( 9 );
860     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString( row, 1 ) );
861     MSI_RecordSetStringW( uirow, 9, MSI_RecordGetString( row, 5 ) );
862     ui_actiondata( package, szRemoveDuplicateFiles, uirow );
863     msiobj_release( &uirow->hdr );
864
865     msi_free(dest);
866     return ERROR_SUCCESS;
867 }
868
869 UINT ACTION_RemoveDuplicateFiles( MSIPACKAGE *package )
870 {
871     UINT rc;
872     MSIQUERY *view;
873     static const WCHAR query[] =
874         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
875          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
876
877     rc = MSI_DatabaseOpenViewW( package->db, query, &view );
878     if (rc != ERROR_SUCCESS)
879         return ERROR_SUCCESS;
880
881     rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveDuplicateFiles, package );
882     msiobj_release( &view->hdr );
883
884     return rc;
885 }
886
887 static BOOL verify_comp_for_removal(MSICOMPONENT *comp, UINT install_mode)
888 {
889     INSTALLSTATE request = comp->ActionRequest;
890
891     if (request == INSTALLSTATE_UNKNOWN)
892         return FALSE;
893
894     if (install_mode == msidbRemoveFileInstallModeOnInstall &&
895         (request == INSTALLSTATE_LOCAL || request == INSTALLSTATE_SOURCE))
896         return TRUE;
897
898     if (request == INSTALLSTATE_ABSENT)
899     {
900         if (!comp->ComponentId)
901             return FALSE;
902
903         if (install_mode == msidbRemoveFileInstallModeOnRemove)
904             return TRUE;
905     }
906
907     if (install_mode == msidbRemoveFileInstallModeOnBoth)
908         return TRUE;
909
910     return FALSE;
911 }
912
913 static UINT ITERATE_RemoveFiles(MSIRECORD *row, LPVOID param)
914 {
915     MSIPACKAGE *package = param;
916     MSICOMPONENT *comp;
917     MSIRECORD *uirow;
918     LPCWSTR component, filename, dirprop;
919     UINT install_mode;
920     LPWSTR dir = NULL, path = NULL;
921     DWORD size;
922     UINT r;
923
924     component = MSI_RecordGetString(row, 2);
925     filename = MSI_RecordGetString(row, 3);
926     dirprop = MSI_RecordGetString(row, 4);
927     install_mode = MSI_RecordGetInteger(row, 5);
928
929     comp = get_loaded_component(package, component);
930     if (!comp)
931     {
932         ERR("Invalid component: %s\n", debugstr_w(component));
933         return ERROR_FUNCTION_FAILED;
934     }
935
936     if (!verify_comp_for_removal(comp, install_mode))
937     {
938         TRACE("Skipping removal due to missing conditions\n");
939         comp->Action = comp->Installed;
940         return ERROR_SUCCESS;
941     }
942
943     dir = msi_dup_property(package, dirprop);
944     if (!dir)
945         return ERROR_OUTOFMEMORY;
946
947     size = (filename != NULL) ? lstrlenW(filename) : 0;
948     size += lstrlenW(dir) + 2;
949     path = msi_alloc(size * sizeof(WCHAR));
950     if (!path)
951     {
952         r = ERROR_OUTOFMEMORY;
953         goto done;
954     }
955
956     if (filename)
957     {
958         lstrcpyW(path, dir);
959         PathAddBackslashW(path);
960         lstrcatW(path, filename);
961
962         TRACE("Deleting misc file: %s\n", debugstr_w(path));
963         DeleteFileW(path);
964     }
965     else
966     {
967         TRACE("Removing misc directory: %s\n", debugstr_w(dir));
968         RemoveDirectoryW(dir);
969     }
970
971 done:
972     uirow = MSI_CreateRecord( 9 );
973     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(row, 1) );
974     MSI_RecordSetStringW( uirow, 9, dir );
975     ui_actiondata( package, szRemoveFiles, uirow );
976     msiobj_release( &uirow->hdr );
977
978     msi_free(path);
979     msi_free(dir);
980     return ERROR_SUCCESS;
981 }
982
983 UINT ACTION_RemoveFiles( MSIPACKAGE *package )
984 {
985     MSIQUERY *view;
986     MSIFILE *file;
987     UINT r;
988
989     static const WCHAR query[] = {
990         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
991         '`','R','e','m','o','v','e','F','i','l','e','`',0};
992     static const WCHAR folder_query[] = {
993         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
994         '`','C','r','e','a','t','e','F','o','l','d','e','r','`',0};
995
996     r = MSI_DatabaseOpenViewW(package->db, query, &view);
997     if (r == ERROR_SUCCESS)
998     {
999         MSI_IterateRecords(view, NULL, ITERATE_RemoveFiles, package);
1000         msiobj_release(&view->hdr);
1001     }
1002
1003     r = MSI_DatabaseOpenViewW(package->db, folder_query, &view);
1004     if (r == ERROR_SUCCESS)
1005         msiobj_release(&view->hdr);
1006
1007     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
1008     {
1009         MSIRECORD *uirow;
1010         LPWSTR dir, uipath, p;
1011
1012         if ( file->state == msifs_installed )
1013             ERR("removing installed file %s\n", debugstr_w(file->TargetPath));
1014
1015         if ( file->Component->ActionRequest != INSTALLSTATE_ABSENT ||
1016              file->Component->Installed == INSTALLSTATE_SOURCE )
1017             continue;
1018
1019         /* don't remove a file if the old file
1020          * is strictly newer than the version to be installed
1021          */
1022         if ( msi_compare_file_version( file ) < 0 )
1023             continue;
1024
1025         TRACE("removing %s\n", debugstr_w(file->File) );
1026         if (!DeleteFileW( file->TargetPath ))
1027         {
1028             WARN("failed to delete %s\n",  debugstr_w(file->TargetPath));
1029         }
1030         /* FIXME: check persistence for each directory */
1031         else if (r && (dir = strdupW( file->TargetPath )))
1032         {
1033             if ((p = strrchrW( dir, '\\' ))) *p = 0;
1034             RemoveDirectoryW( dir );
1035             msi_free( dir );
1036         }
1037         file->state = msifs_missing;
1038
1039         /* the UI chunk */
1040         uirow = MSI_CreateRecord( 9 );
1041         MSI_RecordSetStringW( uirow, 1, file->FileName );
1042         uipath = strdupW( file->TargetPath );
1043         p = strrchrW(uipath,'\\');
1044         if (p)
1045             p[1]=0;
1046         MSI_RecordSetStringW( uirow, 9, uipath);
1047         ui_actiondata( package, szRemoveFiles, uirow);
1048         msiobj_release( &uirow->hdr );
1049         msi_free( uipath );
1050         /* FIXME: call ui_progress here? */
1051     }
1052
1053     return ERROR_SUCCESS;
1054 }