Revert "msi: Avoid loading cabinet streams more than once.".
[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:
24  *
25  * InstallFiles
26  * DuplicateFiles
27  * MoveFiles
28  * PatchFiles
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 HMODULE hmspatcha;
51 static BOOL (WINAPI *ApplyPatchToFileW)(LPCWSTR, LPCWSTR, LPCWSTR, ULONG);
52
53 static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *action )
54 {
55     MSIRECORD *uirow;
56
57     uirow = MSI_CreateRecord( 9 );
58     MSI_RecordSetStringW( uirow, 1, f->FileName );
59     MSI_RecordSetStringW( uirow, 9, f->Component->Directory );
60     MSI_RecordSetInteger( uirow, 6, f->FileSize );
61     msi_ui_actiondata( package, action, uirow );
62     msiobj_release( &uirow->hdr );
63     msi_ui_progress( package, 2, f->FileSize, 0, 0 );
64 }
65
66 static msi_file_state calculate_install_state( MSIFILE *file )
67 {
68     MSICOMPONENT *comp = file->Component;
69     VS_FIXEDFILEINFO *file_version;
70     WCHAR *font_version;
71     msi_file_state state;
72     DWORD file_size;
73
74     if (comp->ActionRequest != INSTALLSTATE_LOCAL || !comp->Enabled ||
75         (comp->assembly && comp->assembly->installed))
76     {
77         TRACE("file %s is not scheduled for install\n", debugstr_w(file->File));
78         return msifs_skipped;
79     }
80     if ((comp->assembly && !comp->assembly->application && !comp->assembly->installed) ||
81         GetFileAttributesW( file->TargetPath ) == INVALID_FILE_ATTRIBUTES)
82     {
83         TRACE("file %s is missing\n", debugstr_w(file->File));
84         return msifs_missing;
85     }
86     if (file->Version)
87     {
88         if ((file_version = msi_get_disk_file_version( file->TargetPath )))
89         {
90             TRACE("new %s old %u.%u.%u.%u\n", debugstr_w(file->Version),
91                   HIWORD(file_version->dwFileVersionMS),
92                   LOWORD(file_version->dwFileVersionMS),
93                   HIWORD(file_version->dwFileVersionLS),
94                   LOWORD(file_version->dwFileVersionLS));
95
96             if (msi_compare_file_versions( file_version, file->Version ) < 0)
97                 state = msifs_overwrite;
98             else
99             {
100                 TRACE("destination file version equal or greater, not overwriting\n");
101                 state = msifs_present;
102             }
103             msi_free( file_version );
104             return state;
105         }
106         else if ((font_version = font_version_from_file( file->TargetPath )))
107         {
108             TRACE("new %s old %s\n", debugstr_w(file->Version), debugstr_w(font_version));
109
110             if (msi_compare_font_versions( font_version, file->Version ) < 0)
111                 state = msifs_overwrite;
112             else
113             {
114                 TRACE("destination file version equal or greater, not overwriting\n");
115                 state = msifs_present;
116             }
117             msi_free( font_version );
118             return state;
119         }
120     }
121     if ((file_size = msi_get_disk_file_size( file->TargetPath )) != file->FileSize)
122     {
123         return msifs_overwrite;
124     }
125     if (file->hash.dwFileHashInfoSize)
126     {
127         if (msi_file_hash_matches( file ))
128         {
129             TRACE("file hashes match, not overwriting\n");
130             return msifs_hashmatch;
131         }
132         else
133         {
134             TRACE("file hashes do not match, overwriting\n");
135             return msifs_overwrite;
136         }
137     }
138     /* assume present */
139     return msifs_present;
140 }
141
142 static void schedule_install_files(MSIPACKAGE *package)
143 {
144     MSIFILE *file;
145
146     LIST_FOR_EACH_ENTRY(file, &package->files, MSIFILE, entry)
147     {
148         MSICOMPONENT *comp = file->Component;
149
150         file->state = calculate_install_state( file );
151         if (file->state == msifs_overwrite && (comp->Attributes & msidbComponentAttributesNeverOverwrite))
152         {
153             TRACE("not overwriting %s\n", debugstr_w(file->TargetPath));
154             file->state = msifs_skipped;
155         }
156         comp->Action = INSTALLSTATE_LOCAL;
157         msi_ui_progress( package, 2, file->FileSize, 0, 0 );
158     }
159 }
160
161 static UINT copy_file(MSIFILE *file, LPWSTR source)
162 {
163     BOOL ret;
164
165     ret = CopyFileW(source, file->TargetPath, FALSE);
166     if (!ret)
167         return GetLastError();
168
169     SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
170
171     file->state = msifs_installed;
172     return ERROR_SUCCESS;
173 }
174
175 static UINT copy_install_file(MSIPACKAGE *package, MSIFILE *file, LPWSTR source)
176 {
177     UINT gle;
178
179     TRACE("Copying %s to %s\n", debugstr_w(source), debugstr_w(file->TargetPath));
180
181     gle = copy_file(file, source);
182     if (gle == ERROR_SUCCESS)
183         return gle;
184
185     if (gle == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
186     {
187         TRACE("overwriting existing file\n");
188         return ERROR_SUCCESS;
189     }
190     else if (gle == ERROR_ACCESS_DENIED)
191     {
192         SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
193
194         gle = copy_file(file, source);
195         TRACE("Overwriting existing file: %d\n", gle);
196     }
197     if (gle == ERROR_SHARING_VIOLATION || gle == ERROR_USER_MAPPED_FILE)
198     {
199         WCHAR tmpfileW[MAX_PATH], *pathW, *p;
200         DWORD len;
201
202         TRACE("file in use, scheduling rename operation\n");
203
204         GetTempFileNameW(szBackSlash, szMsi, 0, tmpfileW);
205         len = strlenW(file->TargetPath) + strlenW(tmpfileW) + 1;
206         if (!(pathW = msi_alloc(len * sizeof(WCHAR))))
207             return ERROR_OUTOFMEMORY;
208
209         strcpyW(pathW, file->TargetPath);
210         if ((p = strrchrW(pathW, '\\'))) *p = 0;
211         strcatW(pathW, tmpfileW);
212
213         if (CopyFileW(source, pathW, FALSE) &&
214             MoveFileExW(file->TargetPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT) &&
215             MoveFileExW(pathW, file->TargetPath, MOVEFILE_DELAY_UNTIL_REBOOT))
216         {
217             file->state = msifs_installed;
218             package->need_reboot = 1;
219             gle = ERROR_SUCCESS;
220         }
221         else
222         {
223             gle = GetLastError();
224             WARN("failed to schedule rename operation: %d)\n", gle);
225         }
226         msi_free(pathW);
227     }
228
229     return gle;
230 }
231
232 static UINT msi_create_directory( MSIPACKAGE *package, const WCHAR *dir )
233 {
234     MSIFOLDER *folder;
235     const WCHAR *install_path;
236
237     install_path = msi_get_target_folder( package, dir );
238     if (!install_path) return ERROR_FUNCTION_FAILED;
239
240     folder = msi_get_loaded_folder( package, dir );
241     if (folder->State == 0)
242     {
243         msi_create_full_path( install_path );
244         folder->State = 2;
245     }
246     return ERROR_SUCCESS;
247 }
248
249 static BOOL installfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
250                             LPWSTR *path, DWORD *attrs, PVOID user)
251 {
252     static MSIFILE *f = NULL;
253     UINT_PTR disk_id = (UINT_PTR)user;
254
255     if (action == MSICABEXTRACT_BEGINEXTRACT)
256     {
257         f = msi_get_loaded_file(package, file);
258         if (!f)
259         {
260             TRACE("unknown file in cabinet (%s)\n", debugstr_w(file));
261             return FALSE;
262         }
263
264         if (f->disk_id != disk_id || (f->state != msifs_missing && f->state != msifs_overwrite))
265             return FALSE;
266
267         msi_file_update_ui(package, f, szInstallFiles);
268         if (!f->Component->assembly || f->Component->assembly->application)
269         {
270             msi_create_directory(package, f->Component->Directory);
271         }
272         *path = strdupW(f->TargetPath);
273         *attrs = f->Attributes;
274     }
275     else if (action == MSICABEXTRACT_FILEEXTRACTED)
276     {
277         f->state = msifs_installed;
278         f = NULL;
279     }
280
281     return TRUE;
282 }
283
284 WCHAR *msi_resolve_file_source( MSIPACKAGE *package, MSIFILE *file )
285 {
286     WCHAR *p, *path;
287
288     TRACE("Working to resolve source of file %s\n", debugstr_w(file->File));
289
290     if (file->IsCompressed) return NULL;
291
292     p = msi_resolve_source_folder( package, file->Component->Directory, NULL );
293     path = msi_build_directory_name( 2, p, file->ShortName );
294
295     if (file->LongName && GetFileAttributesW( path ) == INVALID_FILE_ATTRIBUTES)
296     {
297         msi_free( path );
298         path = msi_build_directory_name( 2, p, file->LongName );
299     }
300     msi_free( p );
301     TRACE("file %s source resolves to %s\n", debugstr_w(file->File), debugstr_w(path));
302     return path;
303 }
304
305 /*
306  * ACTION_InstallFiles()
307  * 
308  * For efficiency, this is done in two passes:
309  * 1) Correct all the TargetPaths and determine what files are to be installed.
310  * 2) Extract Cabinets and copy files.
311  */
312 UINT ACTION_InstallFiles(MSIPACKAGE *package)
313 {
314     MSIMEDIAINFO *mi;
315     MSICOMPONENT *comp;
316     UINT rc = ERROR_SUCCESS;
317     MSIFILE *file;
318
319     /* increment progress bar each time action data is sent */
320     msi_ui_progress( package, 1, 1, 0, 0 );
321
322     schedule_install_files(package);
323     mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );
324
325     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
326     {
327         rc = msi_load_media_info( package, file->Sequence, mi );
328         if (rc != ERROR_SUCCESS)
329         {
330             ERR("Unable to load media info for %s (%u)\n", debugstr_w(file->File), rc);
331             return ERROR_FUNCTION_FAILED;
332         }
333         if (!file->Component->Enabled) continue;
334
335         if (file->state != msifs_hashmatch &&
336             (rc = ready_media( package, file->Sequence, file->IsCompressed, mi )))
337         {
338             ERR("Failed to ready media for %s\n", debugstr_w(file->File));
339             goto done;
340         }
341
342         if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
343             continue;
344
345         if (file->Sequence > mi->last_sequence || mi->is_continuous ||
346             (file->IsCompressed && !mi->is_extracted))
347         {
348             MSICABDATA data;
349
350             data.mi = mi;
351             data.package = package;
352             data.cb = installfiles_cb;
353             data.user = (PVOID)(UINT_PTR)mi->disk_id;
354
355             if (file->IsCompressed &&
356                 !msi_cabextract(package, mi, &data))
357             {
358                 ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
359                 rc = ERROR_INSTALL_FAILURE;
360                 goto done;
361             }
362         }
363
364         if (!file->IsCompressed)
365         {
366             WCHAR *source = msi_resolve_file_source(package, file);
367
368             TRACE("copying %s to %s\n", debugstr_w(source), debugstr_w(file->TargetPath));
369
370             msi_file_update_ui(package, file, szInstallFiles);
371             if (!file->Component->assembly || file->Component->assembly->application)
372             {
373                 msi_create_directory(package, file->Component->Directory);
374             }
375             rc = copy_install_file(package, file, source);
376             if (rc != ERROR_SUCCESS)
377             {
378                 ERR("Failed to copy %s to %s (%d)\n", debugstr_w(source),
379                     debugstr_w(file->TargetPath), rc);
380                 rc = ERROR_INSTALL_FAILURE;
381                 msi_free(source);
382                 goto done;
383             }
384             msi_free(source);
385         }
386         else if (file->state != msifs_installed && !(file->Attributes & msidbFileAttributesPatchAdded))
387         {
388             ERR("compressed file wasn't installed (%s)\n", debugstr_w(file->TargetPath));
389             rc = ERROR_INSTALL_FAILURE;
390             goto done;
391         }
392     }
393     msi_init_assembly_caches( package );
394     LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
395     {
396         if (comp->ActionRequest == INSTALLSTATE_LOCAL && comp->Enabled &&
397             comp->assembly && !comp->assembly->installed)
398         {
399             rc = msi_install_assembly( package, comp );
400             if (rc != ERROR_SUCCESS)
401             {
402                 ERR("Failed to install assembly\n");
403                 rc = ERROR_INSTALL_FAILURE;
404                 break;
405             }
406         }
407     }
408     msi_destroy_assembly_caches( package );
409
410 done:
411     msi_free_media_info(mi);
412     return rc;
413 }
414
415 static BOOL load_mspatcha(void)
416 {
417     hmspatcha = LoadLibraryA("mspatcha.dll");
418     if (!hmspatcha)
419     {
420         ERR("Failed to load mspatcha.dll: %d\n", GetLastError());
421         return FALSE;
422     }
423
424     ApplyPatchToFileW = (void*)GetProcAddress(hmspatcha, "ApplyPatchToFileW");
425     if(!ApplyPatchToFileW)
426     {
427         ERR("GetProcAddress(ApplyPatchToFileW) failed: %d.\n", GetLastError());
428         return FALSE;
429     }
430
431     return TRUE;
432 }
433
434 static void unload_mspatch(void)
435 {
436     FreeLibrary(hmspatcha);
437 }
438
439 static BOOL patchfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
440                           LPWSTR *path, DWORD *attrs, PVOID user)
441 {
442     static MSIFILEPATCH *p = NULL;
443     static WCHAR patch_path[MAX_PATH] = {0};
444     static WCHAR temp_folder[MAX_PATH] = {0};
445
446     if (action == MSICABEXTRACT_BEGINEXTRACT)
447     {
448         if (temp_folder[0] == '\0')
449             GetTempPathW(MAX_PATH, temp_folder);
450
451         p = msi_get_loaded_filepatch(package, file);
452         if (!p)
453         {
454             TRACE("unknown file in cabinet (%s)\n", debugstr_w(file));
455             return FALSE;
456         }
457
458         msi_file_update_ui(package, p->File, szPatchFiles);
459
460         GetTempFileNameW(temp_folder, NULL, 0, patch_path);
461
462         *path = strdupW(patch_path);
463         *attrs = p->File->Attributes;
464     }
465     else if (action == MSICABEXTRACT_FILEEXTRACTED)
466     {
467         WCHAR patched_file[MAX_PATH];
468         BOOL br;
469
470         GetTempFileNameW(temp_folder, NULL, 0, patched_file);
471
472         br = ApplyPatchToFileW(patch_path, p->File->TargetPath, patched_file, 0);
473         if (br)
474         {
475             /* FIXME: baseline cache */
476
477             DeleteFileW( p->File->TargetPath );
478             MoveFileW( patched_file, p->File->TargetPath );
479
480             p->IsApplied = TRUE;
481         }
482         else
483             ERR("Failed patch %s: %d.\n", debugstr_w(p->File->TargetPath), GetLastError());
484
485         DeleteFileW(patch_path);
486         p = NULL;
487     }
488
489     return TRUE;
490 }
491
492 UINT ACTION_PatchFiles( MSIPACKAGE *package )
493 {
494     MSIFILEPATCH *patch;
495     MSIMEDIAINFO *mi;
496     UINT rc = ERROR_SUCCESS;
497     BOOL mspatcha_loaded = FALSE;
498
499     TRACE("%p\n", package);
500
501     /* increment progress bar each time action data is sent */
502     msi_ui_progress( package, 1, 1, 0, 0 );
503
504     mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );
505
506     LIST_FOR_EACH_ENTRY( patch, &package->filepatches, MSIFILEPATCH, entry )
507     {
508         MSIFILE *file = patch->File;
509
510         rc = msi_load_media_info( package, patch->Sequence, mi );
511         if (rc != ERROR_SUCCESS)
512         {
513             ERR("Unable to load media info for %s (%u)\n", debugstr_w(file->File), rc);
514             return ERROR_FUNCTION_FAILED;
515         }
516         if (!file->Component->Enabled) continue;
517
518         if (!patch->IsApplied)
519         {
520             MSICABDATA data;
521
522             rc = ready_media( package, patch->Sequence, TRUE, mi );
523             if (rc != ERROR_SUCCESS)
524             {
525                 ERR("Failed to ready media for %s\n", debugstr_w(file->File));
526                 goto done;
527             }
528
529             if (!mspatcha_loaded && !load_mspatcha())
530             {
531                 rc = ERROR_FUNCTION_FAILED;
532                 goto done;
533             }
534             mspatcha_loaded = TRUE;
535
536             data.mi = mi;
537             data.package = package;
538             data.cb = patchfiles_cb;
539             data.user = (PVOID)(UINT_PTR)mi->disk_id;
540
541             if (!msi_cabextract(package, mi, &data))
542             {
543                 ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
544                 rc = ERROR_INSTALL_FAILURE;
545                 goto done;
546             }
547         }
548
549         if (!patch->IsApplied && !(patch->Attributes & msidbPatchAttributesNonVital))
550         {
551             ERR("Failed to apply patch to file: %s\n", debugstr_w(file->File));
552             rc = ERROR_INSTALL_FAILURE;
553             goto done;
554         }
555     }
556
557 done:
558     msi_free_media_info(mi);
559     if (mspatcha_loaded)
560         unload_mspatch();
561     return rc;
562 }
563
564 #define is_dot_dir(x) ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))
565
566 typedef struct
567 {
568     struct list entry;
569     LPWSTR sourcename;
570     LPWSTR destname;
571     LPWSTR source;
572     LPWSTR dest;
573 } FILE_LIST;
574
575 static BOOL msi_move_file(LPCWSTR source, LPCWSTR dest, int options)
576 {
577     BOOL ret;
578
579     if (GetFileAttributesW(source) == FILE_ATTRIBUTE_DIRECTORY ||
580         GetFileAttributesW(dest) == FILE_ATTRIBUTE_DIRECTORY)
581     {
582         WARN("Source or dest is directory, not moving\n");
583         return FALSE;
584     }
585
586     if (options == msidbMoveFileOptionsMove)
587     {
588         TRACE("moving %s -> %s\n", debugstr_w(source), debugstr_w(dest));
589         ret = MoveFileExW(source, dest, MOVEFILE_REPLACE_EXISTING);
590         if (!ret)
591         {
592             WARN("MoveFile failed: %d\n", GetLastError());
593             return FALSE;
594         }
595     }
596     else
597     {
598         TRACE("copying %s -> %s\n", debugstr_w(source), debugstr_w(dest));
599         ret = CopyFileW(source, dest, FALSE);
600         if (!ret)
601         {
602             WARN("CopyFile failed: %d\n", GetLastError());
603             return FALSE;
604         }
605     }
606
607     return TRUE;
608 }
609
610 static LPWSTR wildcard_to_file(LPWSTR wildcard, LPWSTR filename)
611 {
612     LPWSTR path, ptr;
613     DWORD dirlen, pathlen;
614
615     ptr = strrchrW(wildcard, '\\');
616     dirlen = ptr - wildcard + 1;
617
618     pathlen = dirlen + lstrlenW(filename) + 1;
619     path = msi_alloc(pathlen * sizeof(WCHAR));
620
621     lstrcpynW(path, wildcard, dirlen + 1);
622     lstrcatW(path, filename);
623
624     return path;
625 }
626
627 static void free_file_entry(FILE_LIST *file)
628 {
629     msi_free(file->source);
630     msi_free(file->dest);
631     msi_free(file);
632 }
633
634 static void free_list(FILE_LIST *list)
635 {
636     while (!list_empty(&list->entry))
637     {
638         FILE_LIST *file = LIST_ENTRY(list_head(&list->entry), FILE_LIST, entry);
639
640         list_remove(&file->entry);
641         free_file_entry(file);
642     }
643 }
644
645 static BOOL add_wildcard(FILE_LIST *files, LPWSTR source, LPWSTR dest)
646 {
647     FILE_LIST *new, *file;
648     LPWSTR ptr, filename;
649     DWORD size;
650
651     new = msi_alloc_zero(sizeof(FILE_LIST));
652     if (!new)
653         return FALSE;
654
655     new->source = strdupW(source);
656     ptr = strrchrW(dest, '\\') + 1;
657     filename = strrchrW(new->source, '\\') + 1;
658
659     new->sourcename = filename;
660
661     if (*ptr)
662         new->destname = ptr;
663     else
664         new->destname = new->sourcename;
665
666     size = (ptr - dest) + lstrlenW(filename) + 1;
667     new->dest = msi_alloc(size * sizeof(WCHAR));
668     if (!new->dest)
669     {
670         free_file_entry(new);
671         return FALSE;
672     }
673
674     lstrcpynW(new->dest, dest, ptr - dest + 1);
675     lstrcatW(new->dest, filename);
676
677     if (list_empty(&files->entry))
678     {
679         list_add_head(&files->entry, &new->entry);
680         return TRUE;
681     }
682
683     LIST_FOR_EACH_ENTRY(file, &files->entry, FILE_LIST, entry)
684     {
685         if (strcmpW( source, file->source ) < 0)
686         {
687             list_add_before(&file->entry, &new->entry);
688             return TRUE;
689         }
690     }
691
692     list_add_after(&file->entry, &new->entry);
693     return TRUE;
694 }
695
696 static BOOL move_files_wildcard(LPWSTR source, LPWSTR dest, int options)
697 {
698     WIN32_FIND_DATAW wfd;
699     HANDLE hfile;
700     LPWSTR path;
701     BOOL res;
702     FILE_LIST files, *file;
703     DWORD size;
704
705     hfile = FindFirstFileW(source, &wfd);
706     if (hfile == INVALID_HANDLE_VALUE) return FALSE;
707
708     list_init(&files.entry);
709
710     for (res = TRUE; res; res = FindNextFileW(hfile, &wfd))
711     {
712         if (is_dot_dir(wfd.cFileName)) continue;
713
714         path = wildcard_to_file(source, wfd.cFileName);
715         if (!path)
716         {
717             res = FALSE;
718             goto done;
719         }
720
721         add_wildcard(&files, path, dest);
722         msi_free(path);
723     }
724
725     /* no files match the wildcard */
726     if (list_empty(&files.entry))
727         goto done;
728
729     /* only the first wildcard match gets renamed to dest */
730     file = LIST_ENTRY(list_head(&files.entry), FILE_LIST, entry);
731     size = (strrchrW(file->dest, '\\') - file->dest) + lstrlenW(file->destname) + 2;
732     file->dest = msi_realloc(file->dest, size * sizeof(WCHAR));
733     if (!file->dest)
734     {
735         res = FALSE;
736         goto done;
737     }
738
739     /* file->dest may be shorter after the reallocation, so add a NULL
740      * terminator.  This is needed for the call to strrchrW, as there will no
741      * longer be a NULL terminator within the bounds of the allocation in this case.
742      */
743     file->dest[size - 1] = '\0';
744     lstrcpyW(strrchrW(file->dest, '\\') + 1, file->destname);
745
746     while (!list_empty(&files.entry))
747     {
748         file = LIST_ENTRY(list_head(&files.entry), FILE_LIST, entry);
749
750         msi_move_file(file->source, file->dest, options);
751
752         list_remove(&file->entry);
753         free_file_entry(file);
754     }
755
756     res = TRUE;
757
758 done:
759     free_list(&files);
760     FindClose(hfile);
761     return res;
762 }
763
764 void msi_reduce_to_long_filename( WCHAR *filename )
765 {
766     WCHAR *p = strchrW( filename, '|' );
767     if (p) memmove( filename, p + 1, (strlenW( p + 1 ) + 1) * sizeof(WCHAR) );
768 }
769
770 static UINT ITERATE_MoveFiles( MSIRECORD *rec, LPVOID param )
771 {
772     MSIPACKAGE *package = param;
773     MSIRECORD *uirow;
774     MSICOMPONENT *comp;
775     LPCWSTR sourcename, component;
776     LPWSTR sourcedir, destname = NULL, destdir = NULL, source = NULL, dest = NULL;
777     int options;
778     DWORD size;
779     BOOL ret, wildcards;
780
781     component = MSI_RecordGetString(rec, 2);
782     comp = msi_get_loaded_component(package, component);
783     if (!comp)
784         return ERROR_SUCCESS;
785
786     if (!comp->Enabled)
787     {
788         TRACE("component is disabled\n");
789         return ERROR_SUCCESS;
790     }
791
792     if (comp->ActionRequest != INSTALLSTATE_LOCAL && comp->ActionRequest != INSTALLSTATE_SOURCE)
793     {
794         TRACE("Component not scheduled for installation: %s\n", debugstr_w(component));
795         comp->Action = comp->Installed;
796         return ERROR_SUCCESS;
797     }
798     comp->Action = comp->ActionRequest;
799
800     sourcename = MSI_RecordGetString(rec, 3);
801     options = MSI_RecordGetInteger(rec, 7);
802
803     sourcedir = msi_dup_property(package->db, MSI_RecordGetString(rec, 5));
804     if (!sourcedir)
805         goto done;
806
807     destdir = msi_dup_property(package->db, MSI_RecordGetString(rec, 6));
808     if (!destdir)
809         goto done;
810
811     if (!sourcename)
812     {
813         if (GetFileAttributesW(sourcedir) == INVALID_FILE_ATTRIBUTES)
814             goto done;
815
816         source = strdupW(sourcedir);
817         if (!source)
818             goto done;
819     }
820     else
821     {
822         size = lstrlenW(sourcedir) + lstrlenW(sourcename) + 2;
823         source = msi_alloc(size * sizeof(WCHAR));
824         if (!source)
825             goto done;
826
827         lstrcpyW(source, sourcedir);
828         if (source[lstrlenW(source) - 1] != '\\')
829             lstrcatW(source, szBackSlash);
830         lstrcatW(source, sourcename);
831     }
832
833     wildcards = strchrW(source, '*') || strchrW(source, '?');
834
835     if (MSI_RecordIsNull(rec, 4))
836     {
837         if (!wildcards)
838         {
839             destname = strdupW(sourcename);
840             if (!destname)
841                 goto done;
842         }
843     }
844     else
845     {
846         destname = strdupW(MSI_RecordGetString(rec, 4));
847         if (destname) msi_reduce_to_long_filename(destname);
848     }
849
850     size = 0;
851     if (destname)
852         size = lstrlenW(destname);
853
854     size += lstrlenW(destdir) + 2;
855     dest = msi_alloc(size * sizeof(WCHAR));
856     if (!dest)
857         goto done;
858
859     lstrcpyW(dest, destdir);
860     if (dest[lstrlenW(dest) - 1] != '\\')
861         lstrcatW(dest, szBackSlash);
862
863     if (destname)
864         lstrcatW(dest, destname);
865
866     if (GetFileAttributesW(destdir) == INVALID_FILE_ATTRIBUTES)
867     {
868         ret = CreateDirectoryW(destdir, NULL);
869         if (!ret)
870         {
871             WARN("CreateDirectory failed: %d\n", GetLastError());
872             goto done;
873         }
874     }
875
876     if (!wildcards)
877         msi_move_file(source, dest, options);
878     else
879         move_files_wildcard(source, dest, options);
880
881 done:
882     uirow = MSI_CreateRecord( 9 );
883     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(rec, 1) );
884     MSI_RecordSetInteger( uirow, 6, 1 ); /* FIXME */
885     MSI_RecordSetStringW( uirow, 9, destdir );
886     msi_ui_actiondata( package, szMoveFiles, uirow );
887     msiobj_release( &uirow->hdr );
888
889     msi_free(sourcedir);
890     msi_free(destdir);
891     msi_free(destname);
892     msi_free(source);
893     msi_free(dest);
894
895     return ERROR_SUCCESS;
896 }
897
898 UINT ACTION_MoveFiles( MSIPACKAGE *package )
899 {
900     UINT rc;
901     MSIQUERY *view;
902
903     static const WCHAR ExecSeqQuery[] =
904         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
905          '`','M','o','v','e','F','i','l','e','`',0};
906
907     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
908     if (rc != ERROR_SUCCESS)
909         return ERROR_SUCCESS;
910
911     rc = MSI_IterateRecords(view, NULL, ITERATE_MoveFiles, package);
912     msiobj_release(&view->hdr);
913
914     return rc;
915 }
916
917 static WCHAR *get_duplicate_filename( MSIPACKAGE *package, MSIRECORD *row, const WCHAR *file_key, const WCHAR *src )
918 {
919     DWORD len;
920     WCHAR *dst_name, *dst_path, *dst;
921
922     if (MSI_RecordIsNull( row, 4 ))
923     {
924         len = strlenW( src ) + 1;
925         if (!(dst_name = msi_alloc( len * sizeof(WCHAR)))) return NULL;
926         strcpyW( dst_name, strrchrW( src, '\\' ) + 1 );
927     }
928     else
929     {
930         MSI_RecordGetStringW( row, 4, NULL, &len );
931         if (!(dst_name = msi_alloc( ++len * sizeof(WCHAR) ))) return NULL;
932         MSI_RecordGetStringW( row, 4, dst_name, &len );
933         msi_reduce_to_long_filename( dst_name );
934     }
935
936     if (MSI_RecordIsNull( row, 5 ))
937     {
938         WCHAR *p;
939         dst_path = strdupW( src );
940         p = strrchrW( dst_path, '\\' );
941         if (p) *p = 0;
942     }
943     else
944     {
945         const WCHAR *dst_key = MSI_RecordGetString( row, 5 );
946
947         dst_path = strdupW( msi_get_target_folder( package, dst_key ) );
948         if (!dst_path)
949         {
950             /* try a property */
951             dst_path = msi_dup_property( package->db, dst_key );
952             if (!dst_path)
953             {
954                 FIXME("Unable to get destination folder, try AppSearch properties\n");
955                 msi_free( dst_name );
956                 return NULL;
957             }
958         }
959     }
960
961     dst = msi_build_directory_name( 2, dst_path, dst_name );
962     msi_create_full_path( dst_path );
963
964     msi_free( dst_name );
965     msi_free( dst_path );
966     return dst;
967 }
968
969 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
970 {
971     MSIPACKAGE *package = param;
972     LPWSTR dest;
973     LPCWSTR file_key, component;
974     MSICOMPONENT *comp;
975     MSIRECORD *uirow;
976     MSIFILE *file;
977
978     component = MSI_RecordGetString(row,2);
979     comp = msi_get_loaded_component(package, component);
980     if (!comp)
981         return ERROR_SUCCESS;
982
983     if (!comp->Enabled)
984     {
985         TRACE("component is disabled\n");
986         return ERROR_SUCCESS;
987     }
988
989     if (comp->ActionRequest != INSTALLSTATE_LOCAL)
990     {
991         TRACE("Component not scheduled for installation %s\n", debugstr_w(component));
992         comp->Action = comp->Installed;
993         return ERROR_SUCCESS;
994     }
995     comp->Action = INSTALLSTATE_LOCAL;
996
997     file_key = MSI_RecordGetString(row,3);
998     if (!file_key)
999     {
1000         ERR("Unable to get file key\n");
1001         return ERROR_FUNCTION_FAILED;
1002     }
1003
1004     file = msi_get_loaded_file( package, file_key );
1005     if (!file)
1006     {
1007         ERR("Original file unknown %s\n", debugstr_w(file_key));
1008         return ERROR_SUCCESS;
1009     }
1010
1011     dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
1012     if (!dest)
1013     {
1014         WARN("Unable to get duplicate filename\n");
1015         return ERROR_SUCCESS;
1016     }
1017
1018     TRACE("Duplicating file %s to %s\n", debugstr_w(file->TargetPath), debugstr_w(dest));
1019
1020     if (!CopyFileW( file->TargetPath, dest, TRUE ))
1021     {
1022         WARN("Failed to copy file %s -> %s (%u)\n",
1023              debugstr_w(file->TargetPath), debugstr_w(dest), GetLastError());
1024     }
1025
1026     FIXME("We should track these duplicate files as well\n");   
1027
1028     uirow = MSI_CreateRecord( 9 );
1029     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString( row, 1 ) );
1030     MSI_RecordSetInteger( uirow, 6, file->FileSize );
1031     MSI_RecordSetStringW( uirow, 9, MSI_RecordGetString( row, 5 ) );
1032     msi_ui_actiondata( package, szDuplicateFiles, uirow );
1033     msiobj_release( &uirow->hdr );
1034
1035     msi_free(dest);
1036     return ERROR_SUCCESS;
1037 }
1038
1039 UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
1040 {
1041     UINT rc;
1042     MSIQUERY * view;
1043     static const WCHAR ExecSeqQuery[] =
1044         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1045          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
1046
1047     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
1048     if (rc != ERROR_SUCCESS)
1049         return ERROR_SUCCESS;
1050
1051     rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
1052     msiobj_release(&view->hdr);
1053
1054     return rc;
1055 }
1056
1057 static UINT ITERATE_RemoveDuplicateFiles( MSIRECORD *row, LPVOID param )
1058 {
1059     MSIPACKAGE *package = param;
1060     LPWSTR dest;
1061     LPCWSTR file_key, component;
1062     MSICOMPONENT *comp;
1063     MSIRECORD *uirow;
1064     MSIFILE *file;
1065
1066     component = MSI_RecordGetString( row, 2 );
1067     comp = msi_get_loaded_component( package, component );
1068     if (!comp)
1069         return ERROR_SUCCESS;
1070
1071     if (!comp->Enabled)
1072     {
1073         TRACE("component is disabled\n");
1074         return ERROR_SUCCESS;
1075     }
1076
1077     if (comp->ActionRequest != INSTALLSTATE_ABSENT)
1078     {
1079         TRACE("Component not scheduled for removal %s\n", debugstr_w(component));
1080         comp->Action = comp->Installed;
1081         return ERROR_SUCCESS;
1082     }
1083     comp->Action = INSTALLSTATE_ABSENT;
1084
1085     file_key = MSI_RecordGetString( row, 3 );
1086     if (!file_key)
1087     {
1088         ERR("Unable to get file key\n");
1089         return ERROR_FUNCTION_FAILED;
1090     }
1091
1092     file = msi_get_loaded_file( package, file_key );
1093     if (!file)
1094     {
1095         ERR("Original file unknown %s\n", debugstr_w(file_key));
1096         return ERROR_SUCCESS;
1097     }
1098
1099     dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
1100     if (!dest)
1101     {
1102         WARN("Unable to get duplicate filename\n");
1103         return ERROR_SUCCESS;
1104     }
1105
1106     TRACE("Removing duplicate %s of %s\n", debugstr_w(dest), debugstr_w(file->TargetPath));
1107
1108     if (!DeleteFileW( dest ))
1109     {
1110         WARN("Failed to delete duplicate file %s (%u)\n", debugstr_w(dest), GetLastError());
1111     }
1112
1113     uirow = MSI_CreateRecord( 9 );
1114     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString( row, 1 ) );
1115     MSI_RecordSetStringW( uirow, 9, MSI_RecordGetString( row, 5 ) );
1116     msi_ui_actiondata( package, szRemoveDuplicateFiles, uirow );
1117     msiobj_release( &uirow->hdr );
1118
1119     msi_free(dest);
1120     return ERROR_SUCCESS;
1121 }
1122
1123 UINT ACTION_RemoveDuplicateFiles( MSIPACKAGE *package )
1124 {
1125     UINT rc;
1126     MSIQUERY *view;
1127     static const WCHAR query[] =
1128         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1129          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
1130
1131     rc = MSI_DatabaseOpenViewW( package->db, query, &view );
1132     if (rc != ERROR_SUCCESS)
1133         return ERROR_SUCCESS;
1134
1135     rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveDuplicateFiles, package );
1136     msiobj_release( &view->hdr );
1137
1138     return rc;
1139 }
1140
1141 static BOOL verify_comp_for_removal(MSICOMPONENT *comp, UINT install_mode)
1142 {
1143     INSTALLSTATE request = comp->ActionRequest;
1144
1145     /* special case */
1146     if (request != INSTALLSTATE_SOURCE &&
1147         comp->Attributes & msidbComponentAttributesSourceOnly &&
1148         (install_mode == msidbRemoveFileInstallModeOnRemove ||
1149          install_mode == msidbRemoveFileInstallModeOnBoth)) return TRUE;
1150
1151     switch (request)
1152     {
1153     case INSTALLSTATE_LOCAL:
1154     case INSTALLSTATE_SOURCE:
1155         if (install_mode == msidbRemoveFileInstallModeOnInstall ||
1156             install_mode == msidbRemoveFileInstallModeOnBoth) return TRUE;
1157         break;
1158     case INSTALLSTATE_ABSENT:
1159         if (install_mode == msidbRemoveFileInstallModeOnRemove ||
1160             install_mode == msidbRemoveFileInstallModeOnBoth) return TRUE;
1161         break;
1162     default: break;
1163     }
1164     return FALSE;
1165 }
1166
1167 static UINT ITERATE_RemoveFiles(MSIRECORD *row, LPVOID param)
1168 {
1169     MSIPACKAGE *package = param;
1170     MSICOMPONENT *comp;
1171     MSIRECORD *uirow;
1172     LPCWSTR component, dirprop;
1173     UINT install_mode;
1174     LPWSTR dir = NULL, path = NULL, filename = NULL;
1175     DWORD size;
1176     UINT ret = ERROR_SUCCESS;
1177
1178     component = MSI_RecordGetString(row, 2);
1179     dirprop = MSI_RecordGetString(row, 4);
1180     install_mode = MSI_RecordGetInteger(row, 5);
1181
1182     comp = msi_get_loaded_component(package, component);
1183     if (!comp->Enabled)
1184     {
1185         TRACE("component is disabled\n");
1186         return ERROR_SUCCESS;
1187     }
1188
1189     if (!verify_comp_for_removal(comp, install_mode))
1190     {
1191         TRACE("Skipping removal due to install mode\n");
1192         comp->Action = comp->Installed;
1193         return ERROR_SUCCESS;
1194     }
1195
1196     if (comp->Attributes & msidbComponentAttributesPermanent)
1197     {
1198         TRACE("permanent component, not removing file\n");
1199         return ERROR_SUCCESS;
1200     }
1201
1202     dir = msi_dup_property(package->db, dirprop);
1203     if (!dir)
1204         return ERROR_OUTOFMEMORY;
1205
1206     size = 0;
1207     if ((filename = strdupW( MSI_RecordGetString(row, 3) )))
1208     {
1209         msi_reduce_to_long_filename( filename );
1210         size = lstrlenW( filename );
1211     }
1212     size += lstrlenW(dir) + 2;
1213     path = msi_alloc(size * sizeof(WCHAR));
1214     if (!path)
1215     {
1216         ret = ERROR_OUTOFMEMORY;
1217         goto done;
1218     }
1219
1220     if (filename)
1221     {
1222         lstrcpyW(path, dir);
1223         PathAddBackslashW(path);
1224         lstrcatW(path, filename);
1225
1226         TRACE("Deleting misc file: %s\n", debugstr_w(path));
1227         DeleteFileW(path);
1228     }
1229     else
1230     {
1231         TRACE("Removing misc directory: %s\n", debugstr_w(dir));
1232         RemoveDirectoryW(dir);
1233     }
1234
1235 done:
1236     uirow = MSI_CreateRecord( 9 );
1237     MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(row, 1) );
1238     MSI_RecordSetStringW( uirow, 9, dir );
1239     msi_ui_actiondata( package, szRemoveFiles, uirow );
1240     msiobj_release( &uirow->hdr );
1241
1242     msi_free(filename);
1243     msi_free(path);
1244     msi_free(dir);
1245     return ret;
1246 }
1247
1248 static BOOL has_persistent_dir( MSIPACKAGE *package, MSICOMPONENT *comp )
1249 {
1250     MSIQUERY *view;
1251     UINT r = ERROR_FUNCTION_FAILED;
1252
1253     static const WCHAR query[] = {
1254         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1255         '`','C','r','e','a','t','e','F','o','l','d','e','r','`',' ','W','H','E','R','E',' ',
1256         '`','C','o','m','p','o','n','e','n','t','_','`',' ','=','\'','%','s','\'',' ','A','N','D',' ',
1257         '`','D','i','r','e','c','t','o','r','y','_','`',' ','=','\'','%','s','\'',0};
1258
1259     if (!MSI_OpenQuery( package->db, &view, query, comp->Component, comp->Directory ))
1260     {
1261         if (!MSI_ViewExecute( view, NULL ))
1262         {
1263             MSIRECORD *rec;
1264             if (!(r = MSI_ViewFetch( view, &rec )))
1265             {
1266                 TRACE("directory %s is persistent\n", debugstr_w(comp->Directory));
1267                 msiobj_release( &rec->hdr );
1268             }
1269         }
1270         msiobj_release( &view->hdr );
1271     }
1272     return (r == ERROR_SUCCESS);
1273 }
1274
1275 UINT ACTION_RemoveFiles( MSIPACKAGE *package )
1276 {
1277     MSIQUERY *view;
1278     MSIFILE *file;
1279     UINT r;
1280
1281     static const WCHAR query[] = {
1282         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1283         '`','R','e','m','o','v','e','F','i','l','e','`',0};
1284
1285     r = MSI_DatabaseOpenViewW(package->db, query, &view);
1286     if (r == ERROR_SUCCESS)
1287     {
1288         MSI_IterateRecords(view, NULL, ITERATE_RemoveFiles, package);
1289         msiobj_release(&view->hdr);
1290     }
1291
1292     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
1293     {
1294         MSIRECORD *uirow;
1295         LPWSTR dir, p;
1296         VS_FIXEDFILEINFO *ver;
1297
1298         if ( file->state == msifs_installed )
1299             ERR("removing installed file %s\n", debugstr_w(file->TargetPath));
1300
1301         if ( file->Component->ActionRequest != INSTALLSTATE_ABSENT ||
1302              file->Component->Installed == INSTALLSTATE_SOURCE )
1303             continue;
1304
1305         if (!file->Component->Enabled)
1306         {
1307             TRACE("component is disabled\n");
1308             continue;
1309         }
1310
1311         if (file->Component->Attributes & msidbComponentAttributesPermanent)
1312         {
1313             TRACE("permanent component, not removing file\n");
1314             continue;
1315         }
1316
1317         if (file->Version)
1318         {
1319             ver = msi_get_disk_file_version( file->TargetPath );
1320             if (ver && msi_compare_file_versions( ver, file->Version ) > 0)
1321             {
1322                 TRACE("newer version detected, not removing file\n");
1323                 msi_free( ver );
1324                 continue;
1325             }
1326             msi_free( ver );
1327         }
1328
1329         TRACE("removing %s\n", debugstr_w(file->File) );
1330
1331         SetFileAttributesW( file->TargetPath, FILE_ATTRIBUTE_NORMAL );
1332         if (!DeleteFileW( file->TargetPath ))
1333         {
1334             WARN("failed to delete %s (%u)\n",  debugstr_w(file->TargetPath), GetLastError());
1335         }
1336         else if (!has_persistent_dir( package, file->Component ))
1337         {
1338             if ((dir = strdupW( file->TargetPath )))
1339             {
1340                 if ((p = strrchrW( dir, '\\' ))) *p = 0;
1341                 RemoveDirectoryW( dir );
1342                 msi_free( dir );
1343             }
1344         }
1345         file->state = msifs_missing;
1346
1347         uirow = MSI_CreateRecord( 9 );
1348         MSI_RecordSetStringW( uirow, 1, file->FileName );
1349         MSI_RecordSetStringW( uirow, 9, file->Component->Directory );
1350         msi_ui_actiondata( package, szRemoveFiles, uirow );
1351         msiobj_release( &uirow->hdr );
1352         /* FIXME: call msi_ui_progress here? */
1353     }
1354
1355     return ERROR_SUCCESS;
1356 }