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