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