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