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