msi: Implement the RemoveDuplicateFiles standard action.
[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 static WCHAR *get_duplicate_filename( MSIPACKAGE *package, MSIRECORD *row, const WCHAR *file_key, const WCHAR *src )
332 {
333     DWORD len;
334     WCHAR *dst_name, *dst_path, *dst;
335
336     if (MSI_RecordIsNull( row, 4 ))
337     {
338         len = strlenW( src ) + 1;
339         if (!(dst_name = msi_alloc( len * sizeof(WCHAR)))) return NULL;
340         strcpyW( dst_name, strrchrW( src, '\\' ) + 1 );
341     }
342     else
343     {
344         MSI_RecordGetStringW( row, 4, NULL, &len );
345         if (!(dst_name = msi_alloc( ++len * sizeof(WCHAR) ))) return NULL;
346         MSI_RecordGetStringW( row, 4, dst_name, &len );
347         reduce_to_longfilename( dst_name );
348     }
349
350     if (MSI_RecordIsNull( row, 5 ))
351     {
352         WCHAR *p;
353         dst_path = strdupW( src );
354         p = strrchrW( dst_path, '\\' );
355         if (p) *p = 0;
356     }
357     else
358     {
359         const WCHAR *dst_key = MSI_RecordGetString( row, 5 );
360
361         dst_path = resolve_folder( package, dst_key, FALSE, FALSE, TRUE, NULL );
362         if (!dst_path)
363         {
364             /* try a property */
365             dst_path = msi_dup_property( package, dst_key );
366             if (!dst_path)
367             {
368                 FIXME("Unable to get destination folder, try AppSearch properties\n");
369                 msi_free( dst_name );
370                 return NULL;
371             }
372         }
373     }
374
375     dst = build_directory_name( 2, dst_path, dst_name );
376     create_full_pathW( dst_path );
377
378     msi_free( dst_name );
379     msi_free( dst_path );
380     return dst;
381 }
382
383 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
384 {
385     MSIPACKAGE *package = param;
386     LPWSTR dest;
387     LPCWSTR file_key, component;
388     MSICOMPONENT *comp;
389     MSIFILE *file;
390
391     component = MSI_RecordGetString(row,2);
392     comp = get_loaded_component(package,component);
393     if (!comp)
394         return ERROR_SUCCESS;
395
396     if (comp->ActionRequest != INSTALLSTATE_LOCAL)
397     {
398         TRACE("Component not scheduled for installation %s\n", debugstr_w(component));
399         comp->Action = comp->Installed;
400         return ERROR_SUCCESS;
401     }
402     comp->Action = INSTALLSTATE_LOCAL;
403
404     file_key = MSI_RecordGetString(row,3);
405     if (!file_key)
406     {
407         ERR("Unable to get file key\n");
408         return ERROR_FUNCTION_FAILED;
409     }
410
411     file = get_loaded_file( package, file_key );
412     if (!file)
413     {
414         ERR("Original file unknown %s\n", debugstr_w(file_key));
415         return ERROR_SUCCESS;
416     }
417
418     dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
419     if (!dest)
420     {
421         WARN("Unable to get duplicate filename\n");
422         return ERROR_SUCCESS;
423     }
424
425     TRACE("Duplicating file %s to %s\n", debugstr_w(file->TargetPath), debugstr_w(dest));
426
427     if (!CopyFileW( file->TargetPath, dest, TRUE ))
428     {
429         WARN("Failed to copy file %s -> %s (%u)\n",
430              debugstr_w(file->TargetPath), debugstr_w(dest), GetLastError());
431     }
432
433     FIXME("We should track these duplicate files as well\n");   
434
435     msi_file_update_ui(package, file, szDuplicateFiles);
436
437     msi_free(dest);
438     return ERROR_SUCCESS;
439 }
440
441 UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
442 {
443     UINT rc;
444     MSIQUERY * view;
445     static const WCHAR ExecSeqQuery[] =
446         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
447          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
448
449     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
450     if (rc != ERROR_SUCCESS)
451         return ERROR_SUCCESS;
452
453     rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
454     msiobj_release(&view->hdr);
455
456     return rc;
457 }
458
459 static UINT ITERATE_RemoveDuplicateFiles( MSIRECORD *row, LPVOID param )
460 {
461     MSIPACKAGE *package = param;
462     LPWSTR dest;
463     LPCWSTR file_key, component;
464     MSICOMPONENT *comp;
465     MSIFILE *file;
466
467     component = MSI_RecordGetString( row, 2 );
468     comp = get_loaded_component( package, component );
469     if (!comp)
470         return ERROR_SUCCESS;
471
472     if (comp->ActionRequest != INSTALLSTATE_ABSENT)
473     {
474         TRACE("Component not scheduled for removal %s\n", debugstr_w(component));
475         comp->Action = comp->Installed;
476         return ERROR_SUCCESS;
477     }
478     comp->Action = INSTALLSTATE_ABSENT;
479
480     file_key = MSI_RecordGetString( row, 3 );
481     if (!file_key)
482     {
483         ERR("Unable to get file key\n");
484         return ERROR_FUNCTION_FAILED;
485     }
486
487     file = get_loaded_file( package, file_key );
488     if (!file)
489     {
490         ERR("Original file unknown %s\n", debugstr_w(file_key));
491         return ERROR_SUCCESS;
492     }
493
494     dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
495     if (!dest)
496     {
497         WARN("Unable to get duplicate filename\n");
498         return ERROR_SUCCESS;
499     }
500
501     TRACE("Removing duplicate %s of %s\n", debugstr_w(dest), debugstr_w(file->TargetPath));
502
503     if (!DeleteFileW( dest ))
504     {
505         WARN("Failed to delete duplicate file %s (%u)\n", debugstr_w(dest), GetLastError());
506     }
507
508     msi_file_update_ui( package, file, szRemoveDuplicateFiles );
509
510     msi_free(dest);
511     return ERROR_SUCCESS;
512 }
513
514 UINT ACTION_RemoveDuplicateFiles( MSIPACKAGE *package )
515 {
516     UINT rc;
517     MSIQUERY *view;
518     static const WCHAR query[] =
519         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
520          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
521
522     rc = MSI_DatabaseOpenViewW( package->db, query, &view );
523     if (rc != ERROR_SUCCESS)
524         return ERROR_SUCCESS;
525
526     rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveDuplicateFiles, package );
527     msiobj_release( &view->hdr );
528
529     return rc;
530 }
531
532 static BOOL verify_comp_for_removal(MSICOMPONENT *comp, UINT install_mode)
533 {
534     INSTALLSTATE request = comp->ActionRequest;
535
536     if (request == INSTALLSTATE_UNKNOWN)
537         return FALSE;
538
539     if (install_mode == msidbRemoveFileInstallModeOnInstall &&
540         (request == INSTALLSTATE_LOCAL || request == INSTALLSTATE_SOURCE))
541         return TRUE;
542
543     if (request == INSTALLSTATE_ABSENT)
544     {
545         if (!comp->ComponentId)
546             return FALSE;
547
548         if (install_mode == msidbRemoveFileInstallModeOnRemove)
549             return TRUE;
550     }
551
552     if (install_mode == msidbRemoveFileInstallModeOnBoth)
553         return TRUE;
554
555     return FALSE;
556 }
557
558 static UINT ITERATE_RemoveFiles(MSIRECORD *row, LPVOID param)
559 {
560     MSIPACKAGE *package = param;
561     MSICOMPONENT *comp;
562     LPCWSTR component, filename, dirprop;
563     UINT install_mode;
564     LPWSTR dir = NULL, path = NULL;
565     DWORD size;
566     UINT r;
567
568     component = MSI_RecordGetString(row, 2);
569     filename = MSI_RecordGetString(row, 3);
570     dirprop = MSI_RecordGetString(row, 4);
571     install_mode = MSI_RecordGetInteger(row, 5);
572
573     comp = get_loaded_component(package, component);
574     if (!comp)
575     {
576         ERR("Invalid component: %s\n", debugstr_w(component));
577         return ERROR_FUNCTION_FAILED;
578     }
579
580     if (!verify_comp_for_removal(comp, install_mode))
581     {
582         TRACE("Skipping removal due to missing conditions\n");
583         comp->Action = comp->Installed;
584         return ERROR_SUCCESS;
585     }
586
587     dir = msi_dup_property(package, dirprop);
588     if (!dir)
589         return ERROR_OUTOFMEMORY;
590
591     size = (filename != NULL) ? lstrlenW(filename) : 0;
592     size += lstrlenW(dir) + 2;
593     path = msi_alloc(size * sizeof(WCHAR));
594     if (!path)
595     {
596         r = ERROR_OUTOFMEMORY;
597         goto done;
598     }
599
600     lstrcpyW(path, dir);
601     PathAddBackslashW(path);
602
603     if (filename)
604     {
605         lstrcatW(path, filename);
606
607         TRACE("Deleting misc file: %s\n", debugstr_w(path));
608         DeleteFileW(path);
609     }
610     else
611     {
612         TRACE("Removing misc directory: %s\n", debugstr_w(path));
613         RemoveDirectoryW(path);
614     }
615
616 done:
617     msi_free(path);
618     msi_free(dir);
619     return ERROR_SUCCESS;
620 }
621
622 UINT ACTION_RemoveFiles( MSIPACKAGE *package )
623 {
624     MSIQUERY *view;
625     MSIFILE *file;
626     UINT r;
627
628     static const WCHAR query[] = {
629         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
630         '`','R','e','m','o','v','e','F','i','l','e','`',0};
631
632     r = MSI_DatabaseOpenViewW(package->db, query, &view);
633     if (r == ERROR_SUCCESS)
634     {
635         MSI_IterateRecords(view, NULL, ITERATE_RemoveFiles, package);
636         msiobj_release(&view->hdr);
637     }
638
639     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
640     {
641         MSIRECORD *uirow;
642         LPWSTR uipath, p;
643
644         if ( file->state == msifs_installed )
645             ERR("removing installed file %s\n", debugstr_w(file->TargetPath));
646
647         if ( file->Component->ActionRequest != INSTALLSTATE_ABSENT ||
648              file->Component->Installed == INSTALLSTATE_SOURCE )
649             continue;
650
651         /* don't remove a file if the old file
652          * is strictly newer than the version to be installed
653          */
654         if ( msi_compare_file_version( file ) < 0 )
655             continue;
656
657         TRACE("removing %s\n", debugstr_w(file->File) );
658         if ( !DeleteFileW( file->TargetPath ) )
659             TRACE("failed to delete %s\n",  debugstr_w(file->TargetPath));
660         file->state = msifs_missing;
661
662         /* the UI chunk */
663         uirow = MSI_CreateRecord( 9 );
664         MSI_RecordSetStringW( uirow, 1, file->FileName );
665         uipath = strdupW( file->TargetPath );
666         p = strrchrW(uipath,'\\');
667         if (p)
668             p[1]=0;
669         MSI_RecordSetStringW( uirow, 9, uipath);
670         ui_actiondata( package, szRemoveFiles, uirow);
671         msiobj_release( &uirow->hdr );
672         msi_free( uipath );
673         /* FIXME: call ui_progress here? */
674     }
675
676     return ERROR_SUCCESS;
677 }