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