files.c 36.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Implementation of the Microsoft Installer (msi.dll)
 *
 * Copyright 2005 Aric Stewart for CodeWeavers
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 26
 *
 * InstallFiles
 * DuplicateFiles
27
 * MoveFiles
28
 * PatchFiles
29 30
 * RemoveDuplicateFiles
 * RemoveFiles
31 32 33 34 35 36 37 38 39
 */

#include <stdarg.h>

#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "wine/debug.h"
#include "fdi.h"
40
#include "msi.h"
41 42 43
#include "msidefs.h"
#include "msipriv.h"
#include "winuser.h"
44 45
#include "winreg.h"
#include "shlwapi.h"
46 47 48 49
#include "wine/unicode.h"

WINE_DEFAULT_DEBUG_CHANNEL(msi);

50 51 52
static HMODULE hmspatcha;
static BOOL (WINAPI *ApplyPatchToFileW)(LPCWSTR, LPCWSTR, LPCWSTR, ULONG);

53
static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *action )
54 55 56 57 58
{
    MSIRECORD *uirow;

    uirow = MSI_CreateRecord( 9 );
    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( MSIPACKAGE *package, MSIFILE *file )
67 68 69 70 71 72 73
{
    MSICOMPONENT *comp = file->Component;
    VS_FIXEDFILEINFO *file_version;
    WCHAR *font_version;
    msi_file_state state;
    DWORD file_size;

74 75
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL || (comp->assembly && comp->assembly->installed))
76 77 78 79
    {
        TRACE("file %s is not scheduled for install\n", debugstr_w(file->File));
        return msifs_skipped;
    }
80
    if ((comp->assembly && !comp->assembly->application && !comp->assembly->installed) ||
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
        GetFileAttributesW( file->TargetPath ) == INVALID_FILE_ATTRIBUTES)
    {
        TRACE("file %s is missing\n", debugstr_w(file->File));
        return msifs_missing;
    }
    if (file->Version)
    {
        if ((file_version = msi_get_disk_file_version( file->TargetPath )))
        {
            TRACE("new %s old %u.%u.%u.%u\n", debugstr_w(file->Version),
                  HIWORD(file_version->dwFileVersionMS),
                  LOWORD(file_version->dwFileVersionMS),
                  HIWORD(file_version->dwFileVersionLS),
                  LOWORD(file_version->dwFileVersionLS));

            if (msi_compare_file_versions( file_version, file->Version ) < 0)
                state = msifs_overwrite;
            else
            {
                TRACE("destination file version equal or greater, not overwriting\n");
                state = msifs_present;
            }
            msi_free( file_version );
            return state;
        }
106
        else if ((font_version = msi_font_version_from_file( file->TargetPath )))
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        {
            TRACE("new %s old %s\n", debugstr_w(file->Version), debugstr_w(font_version));

            if (msi_compare_font_versions( font_version, file->Version ) < 0)
                state = msifs_overwrite;
            else
            {
                TRACE("destination file version equal or greater, not overwriting\n");
                state = msifs_present;
            }
            msi_free( font_version );
            return state;
        }
    }
    if ((file_size = msi_get_disk_file_size( file->TargetPath )) != file->FileSize)
    {
        return msifs_overwrite;
    }
125
    if (file->hash.dwFileHashInfoSize)
126
    {
127 128 129 130 131 132 133 134 135 136
        if (msi_file_hash_matches( file ))
        {
            TRACE("file hashes match, not overwriting\n");
            return msifs_hashmatch;
        }
        else
        {
            TRACE("file hashes do not match, overwriting\n");
            return msifs_overwrite;
        }
137
    }
138 139
    /* assume present */
    return msifs_present;
140 141
}

142 143 144 145 146 147
static void schedule_install_files(MSIPACKAGE *package)
{
    MSIFILE *file;

    LIST_FOR_EACH_ENTRY(file, &package->files, MSIFILE, entry)
    {
148 149
        MSICOMPONENT *comp = file->Component;

150
        file->state = calculate_install_state( package, file );
151
        if (file->state == msifs_overwrite && (comp->Attributes & msidbComponentAttributesNeverOverwrite))
152
        {
153
            TRACE("not overwriting %s\n", debugstr_w(file->TargetPath));
154 155
            file->state = msifs_skipped;
        }
156 157 158
    }
}

159
static UINT copy_file(MSIFILE *file, LPWSTR source)
160 161 162
{
    BOOL ret;

163
    ret = CopyFileW(source, file->TargetPath, FALSE);
164 165 166 167
    if (!ret)
        return GetLastError();

    SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
168

169 170
    file->state = msifs_installed;
    return ERROR_SUCCESS;
171 172
}

173
static UINT copy_install_file(MSIPACKAGE *package, MSIFILE *file, LPWSTR source)
174 175 176
{
    UINT gle;

177
    TRACE("Copying %s to %s\n", debugstr_w(source), debugstr_w(file->TargetPath));
178

179
    gle = copy_file(file, source);
180 181 182
    if (gle == ERROR_SUCCESS)
        return gle;

183 184 185
    if (gle == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
    {
        TRACE("overwriting existing file\n");
186
        return ERROR_SUCCESS;
187
    }
188 189 190 191
    else if (gle == ERROR_ACCESS_DENIED)
    {
        SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);

192
        gle = copy_file(file, source);
193 194
        TRACE("Overwriting existing file: %d\n", gle);
    }
195
    if (gle == ERROR_SHARING_VIOLATION || gle == ERROR_USER_MAPPED_FILE)
196
    {
197
        WCHAR *tmpfileW, *pathW, *p;
198 199 200 201
        DWORD len;

        TRACE("file in use, scheduling rename operation\n");

202
        if (!(pathW = strdupW( file->TargetPath ))) return ERROR_OUTOFMEMORY;
203
        if ((p = strrchrW(pathW, '\\'))) *p = 0;
204 205 206 207 208 209 210 211
        len = strlenW( pathW ) + 16;
        if (!(tmpfileW = msi_alloc(len * sizeof(WCHAR))))
        {
            msi_free( pathW );
            return ERROR_OUTOFMEMORY;
        }
        if (!GetTempFileNameW( pathW, szMsi, 0, tmpfileW )) tmpfileW[0] = 0;
        msi_free( pathW );
212

213
        if (CopyFileW(source, tmpfileW, FALSE) &&
214
            MoveFileExW(file->TargetPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT) &&
215
            MoveFileExW(tmpfileW, file->TargetPath, MOVEFILE_DELAY_UNTIL_REBOOT))
216 217 218 219 220 221 222 223 224
        {
            file->state = msifs_installed;
            package->need_reboot = 1;
            gle = ERROR_SUCCESS;
        }
        else
        {
            gle = GetLastError();
            WARN("failed to schedule rename operation: %d)\n", gle);
225
            DeleteFileW( tmpfileW );
226
        }
227
        msi_free(tmpfileW);
228
    }
229 230 231 232

    return gle;
}

233 234 235
static UINT msi_create_directory( MSIPACKAGE *package, const WCHAR *dir )
{
    MSIFOLDER *folder;
236
    const WCHAR *install_path;
237

238 239
    install_path = msi_get_target_folder( package, dir );
    if (!install_path) return ERROR_FUNCTION_FAILED;
240

241
    folder = msi_get_loaded_folder( package, dir );
242
    if (folder->State == FOLDER_STATE_UNINITIALIZED)
243
    {
244
        msi_create_full_path( install_path );
245
        folder->State = FOLDER_STATE_CREATED;
246 247 248 249
    }
    return ERROR_SUCCESS;
}

250 251 252 253
static BOOL installfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
                            LPWSTR *path, DWORD *attrs, PVOID user)
{
    static MSIFILE *f = NULL;
254
    UINT_PTR disk_id = (UINT_PTR)user;
255 256 257

    if (action == MSICABEXTRACT_BEGINEXTRACT)
    {
258
        f = msi_get_loaded_file(package, file);
259 260
        if (!f)
        {
261
            TRACE("unknown file in cabinet (%s)\n", debugstr_w(file));
262 263
            return FALSE;
        }
264
        if (f->disk_id != disk_id || (f->state != msifs_missing && f->state != msifs_overwrite))
265 266
            return FALSE;

267 268
        if (!f->Component->assembly || f->Component->assembly->application)
        {
269
            msi_create_directory(package, f->Component->Directory);
270
        }
271 272 273 274 275 276 277 278 279 280 281 282
        *path = strdupW(f->TargetPath);
        *attrs = f->Attributes;
    }
    else if (action == MSICABEXTRACT_FILEEXTRACTED)
    {
        f->state = msifs_installed;
        f = NULL;
    }

    return TRUE;
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
WCHAR *msi_resolve_file_source( MSIPACKAGE *package, MSIFILE *file )
{
    WCHAR *p, *path;

    TRACE("Working to resolve source of file %s\n", debugstr_w(file->File));

    if (file->IsCompressed) return NULL;

    p = msi_resolve_source_folder( package, file->Component->Directory, NULL );
    path = msi_build_directory_name( 2, p, file->ShortName );

    if (file->LongName && GetFileAttributesW( path ) == INVALID_FILE_ATTRIBUTES)
    {
        msi_free( path );
        path = msi_build_directory_name( 2, p, file->LongName );
    }
    msi_free( p );
    TRACE("file %s source resolves to %s\n", debugstr_w(file->File), debugstr_w(path));
    return path;
}

304
/*
305 306 307 308 309
 * ACTION_InstallFiles()
 * 
 * For efficiency, this is done in two passes:
 * 1) Correct all the TargetPaths and determine what files are to be installed.
 * 2) Extract Cabinets and copy files.
310
 */
311 312
UINT ACTION_InstallFiles(MSIPACKAGE *package)
{
313
    MSIMEDIAINFO *mi;
314
    MSICOMPONENT *comp;
315
    UINT rc = ERROR_SUCCESS;
316
    MSIFILE *file;
317

318
    schedule_install_files(package);
319
    mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );
320

321
    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
322
    {
323 324
        msi_file_update_ui( package, file, szInstallFiles );

325
        rc = msi_load_media_info( package, file->Sequence, mi );
326 327 328 329 330
        if (rc != ERROR_SUCCESS)
        {
            ERR("Unable to load media info for %s (%u)\n", debugstr_w(file->File), rc);
            return ERROR_FUNCTION_FAILED;
        }
331 332
        if (!file->Component->Enabled) continue;

333
        if (file->state != msifs_hashmatch &&
334 335
            file->state != msifs_skipped &&
            (file->state != msifs_present || !msi_get_property_int( package->db, szInstalled, 0 )) &&
336
            (rc = ready_media( package, file->IsCompressed, mi )))
337 338 339 340
        {
            ERR("Failed to ready media for %s\n", debugstr_w(file->File));
            goto done;
        }
341

342
        if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
343 344
            continue;

345 346
        if (file->Sequence > mi->last_sequence || mi->is_continuous ||
            (file->IsCompressed && !mi->is_extracted))
347
        {
348
            MSICABDATA data;
349 350 351

            data.mi = mi;
            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 371
            if (!file->Component->assembly || file->Component->assembly->application)
            {
372
                msi_create_directory(package, file->Component->Directory);
373
            }
374
            rc = copy_install_file(package, file, source);
375
            if (rc != ERROR_SUCCESS)
376
            {
377
                ERR("Failed to copy %s to %s (%d)\n", debugstr_w(source),
378
                    debugstr_w(file->TargetPath), rc);
379
                rc = ERROR_INSTALL_FAILURE;
380
                msi_free(source);
381
                goto done;
382
            }
383
            msi_free(source);
384
        }
385
        else if (file->state != msifs_installed && !(file->Attributes & msidbFileAttributesPatchAdded))
386
        {
387
            ERR("compressed file wasn't installed (%s)\n", debugstr_w(file->TargetPath));
388
            rc = ERROR_INSTALL_FAILURE;
389 390 391
            goto done;
        }
    }
392
    msi_init_assembly_caches( package );
393 394
    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
    {
395 396
        comp->Action = msi_get_component_action( package, comp );
        if (comp->Action == INSTALLSTATE_LOCAL && comp->assembly && !comp->assembly->installed)
397
        {
398
            rc = msi_install_assembly( package, comp );
399 400 401 402 403 404
            if (rc != ERROR_SUCCESS)
            {
                ERR("Failed to install assembly\n");
                rc = ERROR_INSTALL_FAILURE;
                break;
            }
405
        }
406
    }
407
    msi_destroy_assembly_caches( package );
408

409
done:
410
    msi_free_media_info(mi);
411 412 413
    return rc;
}

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
static BOOL load_mspatcha(void)
{
    hmspatcha = LoadLibraryA("mspatcha.dll");
    if (!hmspatcha)
    {
        ERR("Failed to load mspatcha.dll: %d\n", GetLastError());
        return FALSE;
    }

    ApplyPatchToFileW = (void*)GetProcAddress(hmspatcha, "ApplyPatchToFileW");
    if(!ApplyPatchToFileW)
    {
        ERR("GetProcAddress(ApplyPatchToFileW) failed: %d.\n", GetLastError());
        return FALSE;
    }

    return TRUE;
}

static void unload_mspatch(void)
{
    FreeLibrary(hmspatcha);
}

static BOOL patchfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
                          LPWSTR *path, DWORD *attrs, PVOID user)
{
    static MSIFILEPATCH *p = NULL;
    static WCHAR patch_path[MAX_PATH] = {0};
    static WCHAR temp_folder[MAX_PATH] = {0};

    if (action == MSICABEXTRACT_BEGINEXTRACT)
    {
        if (temp_folder[0] == '\0')
            GetTempPathW(MAX_PATH, temp_folder);

450
        p = msi_get_loaded_filepatch(package, file);
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        if (!p)
        {
            TRACE("unknown file in cabinet (%s)\n", debugstr_w(file));
            return FALSE;
        }
        GetTempFileNameW(temp_folder, NULL, 0, patch_path);

        *path = strdupW(patch_path);
        *attrs = p->File->Attributes;
    }
    else if (action == MSICABEXTRACT_FILEEXTRACTED)
    {
        WCHAR patched_file[MAX_PATH];
        BOOL br;

        GetTempFileNameW(temp_folder, NULL, 0, patched_file);

        br = ApplyPatchToFileW(patch_path, p->File->TargetPath, patched_file, 0);
        if (br)
        {
            /* FIXME: baseline cache */

            DeleteFileW( p->File->TargetPath );
            MoveFileW( patched_file, p->File->TargetPath );

            p->IsApplied = TRUE;
        }
        else
            ERR("Failed patch %s: %d.\n", debugstr_w(p->File->TargetPath), GetLastError());

        DeleteFileW(patch_path);
        p = NULL;
    }

    return TRUE;
}

UINT ACTION_PatchFiles( MSIPACKAGE *package )
{
    MSIFILEPATCH *patch;
    MSIMEDIAINFO *mi;
    UINT rc = ERROR_SUCCESS;
    BOOL mspatcha_loaded = FALSE;

    TRACE("%p\n", package);

    mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );

    LIST_FOR_EACH_ENTRY( patch, &package->filepatches, MSIFILEPATCH, entry )
    {
        MSIFILE *file = patch->File;
502
        MSICOMPONENT *comp = file->Component;
503 504 505 506 507 508 509

        rc = msi_load_media_info( package, patch->Sequence, mi );
        if (rc != ERROR_SUCCESS)
        {
            ERR("Unable to load media info for %s (%u)\n", debugstr_w(file->File), rc);
            return ERROR_FUNCTION_FAILED;
        }
510 511
        comp->Action = msi_get_component_action( package, comp );
        if (!comp->Enabled || comp->Action != INSTALLSTATE_LOCAL) continue;
512 513 514 515 516

        if (!patch->IsApplied)
        {
            MSICABDATA data;

517
            rc = ready_media( package, TRUE, mi );
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
            if (rc != ERROR_SUCCESS)
            {
                ERR("Failed to ready media for %s\n", debugstr_w(file->File));
                goto done;
            }

            if (!mspatcha_loaded && !load_mspatcha())
            {
                rc = ERROR_FUNCTION_FAILED;
                goto done;
            }
            mspatcha_loaded = TRUE;

            data.mi = mi;
            data.package = package;
            data.cb = patchfiles_cb;
            data.user = (PVOID)(UINT_PTR)mi->disk_id;

            if (!msi_cabextract(package, mi, &data))
            {
                ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
                rc = ERROR_INSTALL_FAILURE;
                goto done;
            }
        }

        if (!patch->IsApplied && !(patch->Attributes & msidbPatchAttributesNonVital))
        {
            ERR("Failed to apply patch to file: %s\n", debugstr_w(file->File));
            rc = ERROR_INSTALL_FAILURE;
            goto done;
        }
    }

done:
    msi_free_media_info(mi);
    if (mspatcha_loaded)
        unload_mspatch();
    return rc;
}

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
#define is_dot_dir(x) ((x[0] == '.') && ((x[1] == 0) || ((x[1] == '.') && (x[2] == 0))))

typedef struct
{
    struct list entry;
    LPWSTR sourcename;
    LPWSTR destname;
    LPWSTR source;
    LPWSTR dest;
} FILE_LIST;

static BOOL msi_move_file(LPCWSTR source, LPCWSTR dest, int options)
{
    BOOL ret;

    if (GetFileAttributesW(source) == FILE_ATTRIBUTE_DIRECTORY ||
        GetFileAttributesW(dest) == FILE_ATTRIBUTE_DIRECTORY)
    {
        WARN("Source or dest is directory, not moving\n");
        return FALSE;
    }

    if (options == msidbMoveFileOptionsMove)
    {
        TRACE("moving %s -> %s\n", debugstr_w(source), debugstr_w(dest));
        ret = MoveFileExW(source, dest, MOVEFILE_REPLACE_EXISTING);
        if (!ret)
        {
            WARN("MoveFile failed: %d\n", GetLastError());
            return FALSE;
        }
    }
    else
    {
        TRACE("copying %s -> %s\n", debugstr_w(source), debugstr_w(dest));
        ret = CopyFileW(source, dest, FALSE);
        if (!ret)
        {
            WARN("CopyFile failed: %d\n", GetLastError());
            return FALSE;
        }
    }

    return TRUE;
}

static LPWSTR wildcard_to_file(LPWSTR wildcard, LPWSTR filename)
{
    LPWSTR path, ptr;
    DWORD dirlen, pathlen;

    ptr = strrchrW(wildcard, '\\');
    dirlen = ptr - wildcard + 1;

    pathlen = dirlen + lstrlenW(filename) + 1;
    path = msi_alloc(pathlen * sizeof(WCHAR));

    lstrcpynW(path, wildcard, dirlen + 1);
    lstrcatW(path, filename);

    return path;
}

static void free_file_entry(FILE_LIST *file)
{
    msi_free(file->source);
    msi_free(file->dest);
    msi_free(file);
}

static void free_list(FILE_LIST *list)
{
    while (!list_empty(&list->entry))
    {
        FILE_LIST *file = LIST_ENTRY(list_head(&list->entry), FILE_LIST, entry);

        list_remove(&file->entry);
        free_file_entry(file);
    }
}

static BOOL add_wildcard(FILE_LIST *files, LPWSTR source, LPWSTR dest)
{
    FILE_LIST *new, *file;
    LPWSTR ptr, filename;
    DWORD size;

    new = msi_alloc_zero(sizeof(FILE_LIST));
    if (!new)
        return FALSE;

    new->source = strdupW(source);
    ptr = strrchrW(dest, '\\') + 1;
    filename = strrchrW(new->source, '\\') + 1;

    new->sourcename = filename;

    if (*ptr)
        new->destname = ptr;
    else
        new->destname = new->sourcename;

    size = (ptr - dest) + lstrlenW(filename) + 1;
    new->dest = msi_alloc(size * sizeof(WCHAR));
    if (!new->dest)
    {
        free_file_entry(new);
        return FALSE;
    }

    lstrcpynW(new->dest, dest, ptr - dest + 1);
    lstrcatW(new->dest, filename);

    if (list_empty(&files->entry))
    {
        list_add_head(&files->entry, &new->entry);
        return TRUE;
    }

    LIST_FOR_EACH_ENTRY(file, &files->entry, FILE_LIST, entry)
    {
680
        if (strcmpW( source, file->source ) < 0)
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
        {
            list_add_before(&file->entry, &new->entry);
            return TRUE;
        }
    }

    list_add_after(&file->entry, &new->entry);
    return TRUE;
}

static BOOL move_files_wildcard(LPWSTR source, LPWSTR dest, int options)
{
    WIN32_FIND_DATAW wfd;
    HANDLE hfile;
    LPWSTR path;
    BOOL res;
    FILE_LIST files, *file;
    DWORD size;

    hfile = FindFirstFileW(source, &wfd);
    if (hfile == INVALID_HANDLE_VALUE) return FALSE;

    list_init(&files.entry);

    for (res = TRUE; res; res = FindNextFileW(hfile, &wfd))
    {
        if (is_dot_dir(wfd.cFileName)) continue;

        path = wildcard_to_file(source, wfd.cFileName);
        if (!path)
        {
            res = FALSE;
            goto done;
        }

        add_wildcard(&files, path, dest);
        msi_free(path);
    }

    /* no files match the wildcard */
    if (list_empty(&files.entry))
        goto done;

    /* only the first wildcard match gets renamed to dest */
    file = LIST_ENTRY(list_head(&files.entry), FILE_LIST, entry);
    size = (strrchrW(file->dest, '\\') - file->dest) + lstrlenW(file->destname) + 2;
    file->dest = msi_realloc(file->dest, size * sizeof(WCHAR));
    if (!file->dest)
    {
        res = FALSE;
        goto done;
    }

    /* file->dest may be shorter after the reallocation, so add a NULL
     * terminator.  This is needed for the call to strrchrW, as there will no
     * longer be a NULL terminator within the bounds of the allocation in this case.
     */
    file->dest[size - 1] = '\0';
    lstrcpyW(strrchrW(file->dest, '\\') + 1, file->destname);

    while (!list_empty(&files.entry))
    {
        file = LIST_ENTRY(list_head(&files.entry), FILE_LIST, entry);

        msi_move_file(file->source, file->dest, options);

        list_remove(&file->entry);
        free_file_entry(file);
    }

    res = TRUE;

done:
    free_list(&files);
    FindClose(hfile);
    return res;
}

759 760 761 762 763 764
void msi_reduce_to_long_filename( WCHAR *filename )
{
    WCHAR *p = strchrW( filename, '|' );
    if (p) memmove( filename, p + 1, (strlenW( p + 1 ) + 1) * sizeof(WCHAR) );
}

765 766 767
static UINT ITERATE_MoveFiles( MSIRECORD *rec, LPVOID param )
{
    MSIPACKAGE *package = param;
768
    MSIRECORD *uirow;
769 770
    MSICOMPONENT *comp;
    LPCWSTR sourcename, component;
771
    LPWSTR sourcedir, destname = NULL, destdir = NULL, source = NULL, dest = NULL;
772 773 774 775 776
    int options;
    DWORD size;
    BOOL ret, wildcards;

    component = MSI_RecordGetString(rec, 2);
777
    comp = msi_get_loaded_component(package, component);
778 779 780
    if (!comp)
        return ERROR_SUCCESS;

781 782
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
783
    {
784
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
785 786 787
        return ERROR_SUCCESS;
    }

788 789 790
    sourcename = MSI_RecordGetString(rec, 3);
    options = MSI_RecordGetInteger(rec, 7);

791
    sourcedir = msi_dup_property(package->db, MSI_RecordGetString(rec, 5));
792 793 794
    if (!sourcedir)
        goto done;

795
    destdir = msi_dup_property(package->db, MSI_RecordGetString(rec, 6));
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
    if (!destdir)
        goto done;

    if (!sourcename)
    {
        if (GetFileAttributesW(sourcedir) == INVALID_FILE_ATTRIBUTES)
            goto done;

        source = strdupW(sourcedir);
        if (!source)
            goto done;
    }
    else
    {
        size = lstrlenW(sourcedir) + lstrlenW(sourcename) + 2;
        source = msi_alloc(size * sizeof(WCHAR));
        if (!source)
            goto done;

        lstrcpyW(source, sourcedir);
        if (source[lstrlenW(source) - 1] != '\\')
            lstrcatW(source, szBackSlash);
        lstrcatW(source, sourcename);
    }

    wildcards = strchrW(source, '*') || strchrW(source, '?');

    if (MSI_RecordIsNull(rec, 4))
    {
        if (!wildcards)
        {
            destname = strdupW(sourcename);
            if (!destname)
                goto done;
        }
    }
    else
    {
        destname = strdupW(MSI_RecordGetString(rec, 4));
835
        if (destname) msi_reduce_to_long_filename(destname);
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    }

    size = 0;
    if (destname)
        size = lstrlenW(destname);

    size += lstrlenW(destdir) + 2;
    dest = msi_alloc(size * sizeof(WCHAR));
    if (!dest)
        goto done;

    lstrcpyW(dest, destdir);
    if (dest[lstrlenW(dest) - 1] != '\\')
        lstrcatW(dest, szBackSlash);

    if (destname)
        lstrcatW(dest, destname);

    if (GetFileAttributesW(destdir) == INVALID_FILE_ATTRIBUTES)
    {
856
        if (!(ret = msi_create_full_path(destdir)))
857
        {
858
            WARN("failed to create directory %u\n", GetLastError());
859
            goto done;
860 861 862 863 864 865 866 867 868
        }
    }

    if (!wildcards)
        msi_move_file(source, dest, options);
    else
        move_files_wildcard(source, dest, options);

done:
869 870 871 872
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(rec, 1) );
    MSI_RecordSetInteger( uirow, 6, 1 ); /* FIXME */
    MSI_RecordSetStringW( uirow, 9, destdir );
873
    msi_ui_actiondata( package, szMoveFiles, uirow );
874 875
    msiobj_release( &uirow->hdr );

876 877 878 879 880 881 882 883 884 885 886
    msi_free(sourcedir);
    msi_free(destdir);
    msi_free(destname);
    msi_free(source);
    msi_free(dest);

    return ERROR_SUCCESS;
}

UINT ACTION_MoveFiles( MSIPACKAGE *package )
{
887 888 889
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','M','o','v','e','F','i','l','e','`',0};
890
    MSIQUERY *view;
891
    UINT rc;
892

893
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
894 895 896 897 898 899 900 901
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    rc = MSI_IterateRecords(view, NULL, ITERATE_MoveFiles, package);
    msiobj_release(&view->hdr);
    return rc;
}

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
static WCHAR *get_duplicate_filename( MSIPACKAGE *package, MSIRECORD *row, const WCHAR *file_key, const WCHAR *src )
{
    DWORD len;
    WCHAR *dst_name, *dst_path, *dst;

    if (MSI_RecordIsNull( row, 4 ))
    {
        len = strlenW( src ) + 1;
        if (!(dst_name = msi_alloc( len * sizeof(WCHAR)))) return NULL;
        strcpyW( dst_name, strrchrW( src, '\\' ) + 1 );
    }
    else
    {
        MSI_RecordGetStringW( row, 4, NULL, &len );
        if (!(dst_name = msi_alloc( ++len * sizeof(WCHAR) ))) return NULL;
        MSI_RecordGetStringW( row, 4, dst_name, &len );
918
        msi_reduce_to_long_filename( dst_name );
919 920 921 922 923 924 925 926 927 928 929 930 931
    }

    if (MSI_RecordIsNull( row, 5 ))
    {
        WCHAR *p;
        dst_path = strdupW( src );
        p = strrchrW( dst_path, '\\' );
        if (p) *p = 0;
    }
    else
    {
        const WCHAR *dst_key = MSI_RecordGetString( row, 5 );

932
        dst_path = strdupW( msi_get_target_folder( package, dst_key ) );
933 934 935
        if (!dst_path)
        {
            /* try a property */
936
            dst_path = msi_dup_property( package->db, dst_key );
937 938 939 940 941 942 943 944 945
            if (!dst_path)
            {
                FIXME("Unable to get destination folder, try AppSearch properties\n");
                msi_free( dst_name );
                return NULL;
            }
        }
    }

946 947
    dst = msi_build_directory_name( 2, dst_path, dst_name );
    msi_create_full_path( dst_path );
948 949 950 951 952 953

    msi_free( dst_name );
    msi_free( dst_path );
    return dst;
}

954
static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
955
{
956
    MSIPACKAGE *package = param;
957
    LPWSTR dest;
958
    LPCWSTR file_key, component;
959
    MSICOMPONENT *comp;
960
    MSIRECORD *uirow;
961
    MSIFILE *file;
962

963
    component = MSI_RecordGetString(row,2);
964
    comp = msi_get_loaded_component(package, component);
965 966
    if (!comp)
        return ERROR_SUCCESS;
967

968 969
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
970
    {
971
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
972 973 974
        return ERROR_SUCCESS;
    }

975 976
    file_key = MSI_RecordGetString(row,3);
    if (!file_key)
977
    {
978 979
        ERR("Unable to get file key\n");
        return ERROR_FUNCTION_FAILED;
980 981
    }

982
    file = msi_get_loaded_file( package, file_key );
983
    if (!file)
984
    {
985
        ERR("Original file unknown %s\n", debugstr_w(file_key));
986 987
        return ERROR_SUCCESS;
    }
988

989 990
    dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
    if (!dest)
991
    {
992 993
        WARN("Unable to get duplicate filename\n");
        return ERROR_SUCCESS;
994
    }
995

996 997 998
    TRACE("Duplicating file %s to %s\n", debugstr_w(file->TargetPath), debugstr_w(dest));

    if (!CopyFileW( file->TargetPath, dest, TRUE ))
999
    {
1000 1001
        WARN("Failed to copy file %s -> %s (%u)\n",
             debugstr_w(file->TargetPath), debugstr_w(dest), GetLastError());
1002
    }
1003

1004
    FIXME("We should track these duplicate files as well\n");   
1005

1006 1007 1008 1009
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString( row, 1 ) );
    MSI_RecordSetInteger( uirow, 6, file->FileSize );
    MSI_RecordSetStringW( uirow, 9, MSI_RecordGetString( row, 5 ) );
1010
    msi_ui_actiondata( package, szDuplicateFiles, uirow );
1011
    msiobj_release( &uirow->hdr );
1012

1013
    msi_free(dest);
1014 1015
    return ERROR_SUCCESS;
}
1016

1017 1018
UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
{
1019 1020 1021 1022
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
    MSIQUERY *view;
1023
    UINT rc;
1024

1025
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
1026 1027
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;
1028

1029
    rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
1030 1031 1032
    msiobj_release(&view->hdr);
    return rc;
}
1033

1034 1035 1036 1037 1038 1039
static UINT ITERATE_RemoveDuplicateFiles( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPWSTR dest;
    LPCWSTR file_key, component;
    MSICOMPONENT *comp;
1040
    MSIRECORD *uirow;
1041 1042 1043
    MSIFILE *file;

    component = MSI_RecordGetString( row, 2 );
1044
    comp = msi_get_loaded_component( package, component );
1045 1046 1047
    if (!comp)
        return ERROR_SUCCESS;

1048 1049
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
1050
    {
1051
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
1052 1053 1054
        return ERROR_SUCCESS;
    }

1055 1056 1057 1058 1059 1060 1061
    file_key = MSI_RecordGetString( row, 3 );
    if (!file_key)
    {
        ERR("Unable to get file key\n");
        return ERROR_FUNCTION_FAILED;
    }

1062
    file = msi_get_loaded_file( package, file_key );
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    if (!file)
    {
        ERR("Original file unknown %s\n", debugstr_w(file_key));
        return ERROR_SUCCESS;
    }

    dest = get_duplicate_filename( package, row, file_key, file->TargetPath );
    if (!dest)
    {
        WARN("Unable to get duplicate filename\n");
        return ERROR_SUCCESS;
    }

    TRACE("Removing duplicate %s of %s\n", debugstr_w(dest), debugstr_w(file->TargetPath));

    if (!DeleteFileW( dest ))
    {
        WARN("Failed to delete duplicate file %s (%u)\n", debugstr_w(dest), GetLastError());
    }

1083 1084 1085
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString( row, 1 ) );
    MSI_RecordSetStringW( uirow, 9, MSI_RecordGetString( row, 5 ) );
1086
    msi_ui_actiondata( package, szRemoveDuplicateFiles, uirow );
1087
    msiobj_release( &uirow->hdr );
1088 1089 1090 1091 1092 1093 1094

    msi_free(dest);
    return ERROR_SUCCESS;
}

UINT ACTION_RemoveDuplicateFiles( MSIPACKAGE *package )
{
1095 1096 1097
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
1098
    MSIQUERY *view;
1099
    UINT rc;
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109

    rc = MSI_DatabaseOpenViewW( package->db, query, &view );
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

    rc = MSI_IterateRecords( view, NULL, ITERATE_RemoveDuplicateFiles, package );
    msiobj_release( &view->hdr );
    return rc;
}

1110 1111
static BOOL verify_comp_for_removal(MSICOMPONENT *comp, UINT install_mode)
{
1112
    /* special case */
1113
    if (comp->Action != INSTALLSTATE_SOURCE &&
1114 1115 1116 1117
        comp->Attributes & msidbComponentAttributesSourceOnly &&
        (install_mode == msidbRemoveFileInstallModeOnRemove ||
         install_mode == msidbRemoveFileInstallModeOnBoth)) return TRUE;

1118
    switch (comp->Action)
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
    {
    case INSTALLSTATE_LOCAL:
    case INSTALLSTATE_SOURCE:
        if (install_mode == msidbRemoveFileInstallModeOnInstall ||
            install_mode == msidbRemoveFileInstallModeOnBoth) return TRUE;
        break;
    case INSTALLSTATE_ABSENT:
        if (install_mode == msidbRemoveFileInstallModeOnRemove ||
            install_mode == msidbRemoveFileInstallModeOnBoth) return TRUE;
        break;
    default: break;
1130 1131 1132 1133 1134 1135
    }
    return FALSE;
}

static UINT ITERATE_RemoveFiles(MSIRECORD *row, LPVOID param)
{
1136
    MSIPACKAGE *package = param;
1137
    MSICOMPONENT *comp;
1138
    MSIRECORD *uirow;
1139
    LPCWSTR component, dirprop;
1140
    UINT install_mode;
1141
    LPWSTR dir = NULL, path = NULL, filename = NULL;
1142
    DWORD size;
1143
    UINT ret = ERROR_SUCCESS;
1144 1145 1146 1147 1148

    component = MSI_RecordGetString(row, 2);
    dirprop = MSI_RecordGetString(row, 4);
    install_mode = MSI_RecordGetInteger(row, 5);

1149
    comp = msi_get_loaded_component(package, component);
1150 1151 1152
    if (!comp)
        return ERROR_SUCCESS;

1153
    comp->Action = msi_get_component_action( package, comp );
1154 1155
    if (!verify_comp_for_removal(comp, install_mode))
    {
1156
        TRACE("Skipping removal due to install mode\n");
1157 1158
        return ERROR_SUCCESS;
    }
1159 1160 1161 1162
    if (comp->assembly && !comp->assembly->application)
    {
        return ERROR_SUCCESS;
    }
1163 1164 1165 1166 1167 1168
    if (comp->Attributes & msidbComponentAttributesPermanent)
    {
        TRACE("permanent component, not removing file\n");
        return ERROR_SUCCESS;
    }

1169
    dir = msi_dup_property(package->db, dirprop);
1170
    if (!dir)
1171 1172 1173 1174
    {
        WARN("directory property has no value\n");
        return ERROR_SUCCESS;
    }
1175
    size = 0;
1176
    if ((filename = strdupW( MSI_RecordGetString(row, 3) )))
1177
    {
1178
        msi_reduce_to_long_filename( filename );
1179 1180
        size = lstrlenW( filename );
    }
1181
    size += lstrlenW(dir) + 2;
1182 1183 1184
    path = msi_alloc(size * sizeof(WCHAR));
    if (!path)
    {
1185
        ret = ERROR_OUTOFMEMORY;
1186 1187 1188
        goto done;
    }

1189 1190
    if (filename)
    {
1191 1192
        lstrcpyW(path, dir);
        PathAddBackslashW(path);
1193 1194 1195 1196 1197 1198 1199
        lstrcatW(path, filename);

        TRACE("Deleting misc file: %s\n", debugstr_w(path));
        DeleteFileW(path);
    }
    else
    {
1200 1201
        TRACE("Removing misc directory: %s\n", debugstr_w(dir));
        RemoveDirectoryW(dir);
1202
    }
1203 1204

done:
1205 1206 1207
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(row, 1) );
    MSI_RecordSetStringW( uirow, 9, dir );
1208
    msi_ui_actiondata( package, szRemoveFiles, uirow );
1209 1210
    msiobj_release( &uirow->hdr );

1211
    msi_free(filename);
1212 1213
    msi_free(path);
    msi_free(dir);
1214
    return ret;
1215 1216
}

1217
static void remove_folder( MSIFOLDER *folder )
1218
{
1219
    FolderList *fl;
1220

1221
    LIST_FOR_EACH_ENTRY( fl, &folder->children, FolderList, entry )
1222
    {
1223 1224 1225 1226 1227
        remove_folder( fl->folder );
    }
    if (!folder->persistent && folder->State != FOLDER_STATE_REMOVED)
    {
        if (RemoveDirectoryW( folder->ResolvedTarget )) folder->State = FOLDER_STATE_REMOVED;
1228 1229 1230
    }
}

1231 1232
UINT ACTION_RemoveFiles( MSIPACKAGE *package )
{
1233 1234 1235
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','R','e','m','o','v','e','F','i','l','e','`',0};
1236
    MSIQUERY *view;
1237
    MSICOMPONENT *comp;
1238
    MSIFILE *file;
1239 1240 1241 1242 1243
    UINT r;

    r = MSI_DatabaseOpenViewW(package->db, query, &view);
    if (r == ERROR_SUCCESS)
    {
1244
        r = MSI_IterateRecords(view, NULL, ITERATE_RemoveFiles, package);
1245
        msiobj_release(&view->hdr);
1246 1247
        if (r != ERROR_SUCCESS)
            return r;
1248
    }
1249 1250 1251

    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
    {
1252
        MSIRECORD *uirow;
1253
        VS_FIXEDFILEINFO *ver;
1254

1255
        comp = file->Component;
1256 1257
        msi_file_update_ui( package, file, szRemoveFiles );

1258 1259 1260 1261 1262
        comp->Action = msi_get_component_action( package, comp );
        if (comp->Action != INSTALLSTATE_ABSENT || comp->Installed == INSTALLSTATE_SOURCE)
            continue;

        if (comp->assembly && !comp->assembly->application)
1263 1264
            continue;

1265
        if (comp->Attributes & msidbComponentAttributesPermanent)
1266 1267 1268 1269 1270
        {
            TRACE("permanent component, not removing file\n");
            continue;
        }

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
        if (file->Version)
        {
            ver = msi_get_disk_file_version( file->TargetPath );
            if (ver && msi_compare_file_versions( ver, file->Version ) > 0)
            {
                TRACE("newer version detected, not removing file\n");
                msi_free( ver );
                continue;
            }
            msi_free( ver );
        }
1282

1283 1284 1285
        if (file->state == msifs_installed)
            WARN("removing installed file %s\n", debugstr_w(file->TargetPath));

1286
        TRACE("removing %s\n", debugstr_w(file->File) );
1287 1288

        SetFileAttributesW( file->TargetPath, FILE_ATTRIBUTE_NORMAL );
1289 1290
        if (!DeleteFileW( file->TargetPath ))
        {
1291
            WARN("failed to delete %s (%u)\n",  debugstr_w(file->TargetPath), GetLastError());
1292
        }
1293
        file->state = msifs_missing;
1294 1295 1296

        uirow = MSI_CreateRecord( 9 );
        MSI_RecordSetStringW( uirow, 1, file->FileName );
1297
        MSI_RecordSetStringW( uirow, 9, comp->Directory );
1298
        msi_ui_actiondata( package, szRemoveFiles, uirow );
1299
        msiobj_release( &uirow->hdr );
1300
    }
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
    {
        MSIFOLDER *folder;

        comp->Action = msi_get_component_action( package, comp );
        if (comp->Action != INSTALLSTATE_ABSENT) continue;

        if (comp->assembly && !comp->assembly->application) continue;

        if (comp->Attributes & msidbComponentAttributesPermanent)
        {
            TRACE("permanent component, not removing directory\n");
            continue;
        }
        folder = msi_get_loaded_folder( package, comp->Directory );
        remove_folder( folder );
    }
1318 1319
    return ERROR_SUCCESS;
}