msi: Don't remove a misc file if the action is unknown.
[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 (TODO)
28  * PatchFiles (TODO)
29  * RemoveDuplicateFiles(TODO)
30  * RemoveFiles(TODO)
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 "msvcrt/fcntl.h"
43 #include "msipriv.h"
44 #include "winuser.h"
45 #include "winreg.h"
46 #include "shlwapi.h"
47 #include "wine/unicode.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(msi);
50
51 extern const WCHAR szInstallFiles[];
52 extern const WCHAR szDuplicateFiles[];
53 extern const WCHAR szMoveFiles[];
54 extern const WCHAR szPatchFiles[];
55 extern const WCHAR szRemoveDuplicateFiles[];
56 extern const WCHAR szRemoveFiles[];
57
58 static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *action )
59 {
60     MSIRECORD *uirow;
61     LPWSTR uipath, p;
62
63     /* the UI chunk */
64     uirow = MSI_CreateRecord( 9 );
65     MSI_RecordSetStringW( uirow, 1, f->FileName );
66     uipath = strdupW( f->TargetPath );
67     p = strrchrW(uipath,'\\');
68     if (p)
69         p[1]=0;
70     MSI_RecordSetStringW( uirow, 9, uipath);
71     MSI_RecordSetInteger( uirow, 6, f->FileSize );
72     ui_actiondata( package, action, uirow);
73     msiobj_release( &uirow->hdr );
74     msi_free( uipath );
75     ui_progress( package, 2, f->FileSize, 0, 0);
76 }
77
78 /* compares the version of a file read from the filesystem and
79  * the version specified in the File table
80  */
81 static int msi_compare_file_version(MSIFILE *file)
82 {
83     WCHAR version[MAX_PATH];
84     DWORD size;
85     UINT r;
86
87     size = MAX_PATH;
88     version[0] = '\0';
89     r = MsiGetFileVersionW(file->TargetPath, version, &size, NULL, NULL);
90     if (r != ERROR_SUCCESS)
91         return 0;
92
93     return lstrcmpW(version, file->Version);
94 }
95
96 static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
97                             MSIFILE** file)
98 {
99     LIST_FOR_EACH_ENTRY( *file, &package->files, MSIFILE, entry )
100     {
101         if (lstrcmpW( file_key, (*file)->File )==0)
102         {
103             if ((*file)->state >= msifs_overwrite)
104                 return ERROR_SUCCESS;
105             else
106                 return ERROR_FILE_NOT_FOUND;
107         }
108     }
109
110     return ERROR_FUNCTION_FAILED;
111 }
112
113 static void schedule_install_files(MSIPACKAGE *package)
114 {
115     MSIFILE *file;
116
117     LIST_FOR_EACH_ENTRY(file, &package->files, MSIFILE, entry)
118     {
119         if (!ACTION_VerifyComponentForAction(file->Component, INSTALLSTATE_LOCAL))
120         {
121             TRACE("File %s is not scheduled for install\n", debugstr_w(file->File));
122
123             ui_progress(package,2,file->FileSize,0,0);
124             file->state = msifs_skipped;
125         }
126     }
127 }
128
129 static UINT copy_file(MSIFILE *file)
130 {
131     BOOL ret;
132
133     ret = CopyFileW(file->SourcePath, file->TargetPath, FALSE);
134     if (ret)
135     {
136         file->state = msifs_installed;
137         return ERROR_SUCCESS;
138     }
139
140     return GetLastError();
141 }
142
143 static UINT copy_install_file(MSIFILE *file)
144 {
145     UINT gle;
146
147     TRACE("Copying %s to %s\n", debugstr_w(file->SourcePath),
148           debugstr_w(file->TargetPath));
149
150     gle = copy_file(file);
151     if (gle == ERROR_SUCCESS)
152         return gle;
153
154     if (gle == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
155     {
156         TRACE("overwriting existing file\n");
157         gle = ERROR_SUCCESS;
158     }
159     else if (gle == ERROR_ACCESS_DENIED)
160     {
161         SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
162
163         gle = copy_file(file);
164         TRACE("Overwriting existing file: %d\n", gle);
165     }
166
167     return gle;
168 }
169
170 static BOOL check_dest_hash_matches(MSIFILE *file)
171 {
172     MSIFILEHASHINFO hash;
173     UINT r;
174
175     if (!file->hash.dwFileHashInfoSize)
176         return FALSE;
177
178     hash.dwFileHashInfoSize = sizeof(MSIFILEHASHINFO);
179     r = MsiGetFileHashW(file->TargetPath, 0, &hash);
180     if (r != ERROR_SUCCESS)
181         return FALSE;
182
183     return !memcmp(&hash, &file->hash, sizeof(MSIFILEHASHINFO));
184 }
185
186 static BOOL installfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
187                             LPWSTR *path, DWORD *attrs, PVOID user)
188 {
189     static MSIFILE *f = NULL;
190
191     if (action == MSICABEXTRACT_BEGINEXTRACT)
192     {
193         f = get_loaded_file(package, file);
194         if (!f)
195         {
196             WARN("unknown file in cabinet (%s)\n", debugstr_w(file));
197             return FALSE;
198         }
199
200         if (f->state != msifs_missing && f->state != msifs_overwrite)
201         {
202             TRACE("Skipping extraction of %s\n", debugstr_w(file));
203             return FALSE;
204         }
205
206         msi_file_update_ui(package, f, szInstallFiles);
207
208         *path = strdupW(f->TargetPath);
209         *attrs = f->Attributes;
210     }
211     else if (action == MSICABEXTRACT_FILEEXTRACTED)
212     {
213         f->state = msifs_installed;
214         f = NULL;
215     }
216
217     return TRUE;
218 }
219
220 /*
221  * ACTION_InstallFiles()
222  * 
223  * For efficiency, this is done in two passes:
224  * 1) Correct all the TargetPaths and determine what files are to be installed.
225  * 2) Extract Cabinets and copy files.
226  */
227 UINT ACTION_InstallFiles(MSIPACKAGE *package)
228 {
229     MSIMEDIAINFO *mi;
230     UINT rc = ERROR_SUCCESS;
231     MSIFILE *file;
232
233     /* increment progress bar each time action data is sent */
234     ui_progress(package,1,1,0,0);
235
236     schedule_install_files(package);
237
238     /*
239      * Despite MSDN specifying that the CreateFolders action
240      * should be called before InstallFiles, some installers don't
241      * do that, and they seem to work correctly.  We need to create
242      * directories here to make sure that the files can be copied.
243      */
244     msi_create_component_directories( package );
245
246     mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );
247
248     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
249     {
250         if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
251             continue;
252
253         if (check_dest_hash_matches(file))
254         {
255             TRACE("File hashes match, not overwriting\n");
256             continue;
257         }
258
259         if (MsiGetFileVersionW(file->TargetPath, NULL, NULL, NULL, NULL) == ERROR_SUCCESS &&
260             msi_compare_file_version(file) >= 0)
261         {
262             TRACE("Destination file version greater, not overwriting\n");
263             continue;
264         }
265
266         if (file->Sequence > mi->last_sequence || mi->is_continuous ||
267             (file->IsCompressed && !mi->is_extracted))
268         {
269             MSICABDATA data;
270
271             rc = ready_media(package, file, mi);
272             if (rc != ERROR_SUCCESS)
273             {
274                 ERR("Failed to ready media\n");
275                 break;
276             }
277
278             data.mi = mi;
279             data.package = package;
280             data.cb = installfiles_cb;
281             data.user = NULL;
282
283             if (file->IsCompressed &&
284                 !msi_cabextract(package, mi, &data))
285             {
286                 ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
287                 rc = ERROR_FUNCTION_FAILED;
288                 break;
289             }
290         }
291
292         if (!file->IsCompressed)
293         {
294             TRACE("file paths %s to %s\n", debugstr_w(file->SourcePath),
295                   debugstr_w(file->TargetPath));
296
297             msi_file_update_ui(package, file, szInstallFiles);
298             rc = copy_install_file(file);
299             if (rc != ERROR_SUCCESS)
300             {
301                 ERR("Failed to copy %s to %s (%d)\n", debugstr_w(file->SourcePath),
302                     debugstr_w(file->TargetPath), rc);
303                 rc = ERROR_INSTALL_FAILURE;
304                 break;
305             }
306         }
307         else if (file->state != msifs_installed)
308         {
309             ERR("compressed file wasn't extracted (%s)\n", debugstr_w(file->TargetPath));
310             rc = ERROR_INSTALL_FAILURE;
311             break;
312         }
313     }
314
315     msi_free_media_info(mi);
316     return rc;
317 }
318
319 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
320 {
321     MSIPACKAGE *package = (MSIPACKAGE*)param;
322     WCHAR dest_name[0x100];
323     LPWSTR dest_path, dest;
324     LPCWSTR file_key, component;
325     DWORD sz;
326     DWORD rc;
327     MSICOMPONENT *comp;
328     MSIFILE *file;
329
330     component = MSI_RecordGetString(row,2);
331     comp = get_loaded_component(package,component);
332
333     if (!ACTION_VerifyComponentForAction( comp, INSTALLSTATE_LOCAL ))
334     {
335         TRACE("Skipping copy due to disabled component %s\n",
336                         debugstr_w(component));
337
338         /* the action taken was the same as the current install state */        
339         comp->Action = comp->Installed;
340
341         return ERROR_SUCCESS;
342     }
343
344     comp->Action = INSTALLSTATE_LOCAL;
345
346     file_key = MSI_RecordGetString(row,3);
347     if (!file_key)
348     {
349         ERR("Unable to get file key\n");
350         return ERROR_FUNCTION_FAILED;
351     }
352
353     rc = get_file_target(package,file_key,&file);
354
355     if (rc != ERROR_SUCCESS)
356     {
357         ERR("Original file unknown %s\n",debugstr_w(file_key));
358         return ERROR_SUCCESS;
359     }
360
361     if (MSI_RecordIsNull(row,4))
362         strcpyW(dest_name,strrchrW(file->TargetPath,'\\')+1);
363     else
364     {
365         sz=0x100;
366         MSI_RecordGetStringW(row,4,dest_name,&sz);
367         reduce_to_longfilename(dest_name);
368     }
369
370     if (MSI_RecordIsNull(row,5))
371     {
372         LPWSTR p;
373         dest_path = strdupW(file->TargetPath);
374         p = strrchrW(dest_path,'\\');
375         if (p)
376             *p=0;
377     }
378     else
379     {
380         LPCWSTR destkey;
381         destkey = MSI_RecordGetString(row,5);
382         dest_path = resolve_folder(package, destkey, FALSE, FALSE, TRUE, NULL);
383         if (!dest_path)
384         {
385             /* try a Property */
386             dest_path = msi_dup_property( package, destkey );
387             if (!dest_path)
388             {
389                 FIXME("Unable to get destination folder, try AppSearch properties\n");
390                 return ERROR_SUCCESS;
391             }
392         }
393     }
394
395     dest = build_directory_name(2, dest_path, dest_name);
396     create_full_pathW(dest_path);
397
398     TRACE("Duplicating file %s to %s\n",debugstr_w(file->TargetPath),
399                     debugstr_w(dest)); 
400
401     if (strcmpW(file->TargetPath,dest))
402         rc = !CopyFileW(file->TargetPath,dest,TRUE);
403     else
404         rc = ERROR_SUCCESS;
405
406     if (rc != ERROR_SUCCESS)
407         ERR("Failed to copy file %s -> %s, last error %d\n",
408             debugstr_w(file->TargetPath), debugstr_w(dest_path), GetLastError());
409
410     FIXME("We should track these duplicate files as well\n");   
411
412     msi_free(dest_path);
413     msi_free(dest);
414
415     msi_file_update_ui(package, file, szDuplicateFiles);
416
417     return ERROR_SUCCESS;
418 }
419
420 UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
421 {
422     UINT rc;
423     MSIQUERY * view;
424     static const WCHAR ExecSeqQuery[] =
425         {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
426          '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
427
428     rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
429     if (rc != ERROR_SUCCESS)
430         return ERROR_SUCCESS;
431
432     rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
433     msiobj_release(&view->hdr);
434
435     return rc;
436 }
437
438 static BOOL verify_comp_for_removal(MSICOMPONENT *comp, UINT install_mode)
439 {
440     INSTALLSTATE request = comp->ActionRequest;
441
442     if (request == INSTALLSTATE_UNKNOWN)
443         return FALSE;
444
445     if (install_mode == msidbRemoveFileInstallModeOnInstall &&
446         (request == INSTALLSTATE_LOCAL || request == INSTALLSTATE_SOURCE))
447         return TRUE;
448
449     if (request == INSTALLSTATE_ABSENT)
450     {
451         if (!comp->ComponentId)
452             return FALSE;
453
454         if (install_mode == msidbRemoveFileInstallModeOnRemove)
455             return TRUE;
456     }
457
458     if (install_mode == msidbRemoveFileInstallModeOnBoth)
459         return TRUE;
460
461     return FALSE;
462 }
463
464 static UINT ITERATE_RemoveFiles(MSIRECORD *row, LPVOID param)
465 {
466     MSIPACKAGE *package = (MSIPACKAGE*)param;
467     MSICOMPONENT *comp;
468     LPCWSTR component, filename, dirprop;
469     UINT install_mode;
470     LPWSTR dir = NULL, path = NULL;
471     DWORD size;
472     UINT r;
473
474     component = MSI_RecordGetString(row, 2);
475     filename = MSI_RecordGetString(row, 3);
476     dirprop = MSI_RecordGetString(row, 4);
477     install_mode = MSI_RecordGetInteger(row, 5);
478
479     comp = get_loaded_component(package, component);
480     if (!comp)
481     {
482         ERR("Invalid component: %s\n", debugstr_w(component));
483         return ERROR_FUNCTION_FAILED;
484     }
485
486     if (!verify_comp_for_removal(comp, install_mode))
487     {
488         TRACE("Skipping removal due to missing conditions\n");
489         comp->Action = comp->Installed;
490         return ERROR_SUCCESS;
491     }
492
493     dir = msi_dup_property(package, dirprop);
494     if (!dir)
495         return ERROR_OUTOFMEMORY;
496
497     size = (filename != NULL) ? lstrlenW(filename) : 0;
498     size += lstrlenW(dir) + 2;
499     path = msi_alloc(size * sizeof(WCHAR));
500     if (!path)
501     {
502         r = ERROR_OUTOFMEMORY;
503         goto done;
504     }
505
506     lstrcpyW(path, dir);
507     PathAddBackslashW(path);
508
509     if (filename)
510     {
511         lstrcatW(path, filename);
512
513         TRACE("Deleting misc file: %s\n", debugstr_w(path));
514         DeleteFileW(path);
515     }
516     else
517     {
518         TRACE("Removing misc directory: %s\n", debugstr_w(path));
519         RemoveDirectoryW(path);
520     }
521
522 done:
523     msi_free(path);
524     msi_free(dir);
525     return ERROR_SUCCESS;
526 }
527
528 UINT ACTION_RemoveFiles( MSIPACKAGE *package )
529 {
530     MSIQUERY *view;
531     MSIFILE *file;
532     UINT r;
533
534     static const WCHAR query[] = {
535         'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
536         '`','R','e','m','o','v','e','F','i','l','e','`',0};
537
538     r = MSI_DatabaseOpenViewW(package->db, query, &view);
539     if (r == ERROR_SUCCESS)
540     {
541         MSI_IterateRecords(view, NULL, ITERATE_RemoveFiles, package);
542         msiobj_release(&view->hdr);
543     }
544
545     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
546     {
547         MSIRECORD *uirow;
548         LPWSTR uipath, p;
549
550         if ( file->state == msifs_installed )
551             ERR("removing installed file %s\n", debugstr_w(file->TargetPath));
552
553         if ( file->Component->ActionRequest != INSTALLSTATE_ABSENT ||
554              file->Component->Installed == INSTALLSTATE_SOURCE )
555             continue;
556
557         /* don't remove a file if the old file
558          * is strictly newer than the version to be installed
559          */
560         if ( msi_compare_file_version( file ) < 0 )
561             continue;
562
563         TRACE("removing %s\n", debugstr_w(file->File) );
564         if ( !DeleteFileW( file->TargetPath ) )
565             TRACE("failed to delete %s\n",  debugstr_w(file->TargetPath));
566         file->state = msifs_missing;
567
568         /* the UI chunk */
569         uirow = MSI_CreateRecord( 9 );
570         MSI_RecordSetStringW( uirow, 1, file->FileName );
571         uipath = strdupW( file->TargetPath );
572         p = strrchrW(uipath,'\\');
573         if (p)
574             p[1]=0;
575         MSI_RecordSetStringW( uirow, 9, uipath);
576         ui_actiondata( package, szRemoveFiles, uirow);
577         msiobj_release( &uirow->hdr );
578         msi_free( uipath );
579         /* FIXME: call ui_progress here? */
580     }
581
582     return ERROR_SUCCESS;
583 }