files.c 36.7 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 334
        if (file->state != msifs_hashmatch &&
            (rc = ready_media( package, file->Sequence, file->IsCompressed, mi )))
335 336 337 338
        {
            ERR("Failed to ready media for %s\n", debugstr_w(file->File));
            goto done;
        }
339

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

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

            data.mi = mi;
            data.package = package;
350
            data.cb = installfiles_cb;
351
            data.user = (PVOID)(UINT_PTR)mi->disk_id;
352 353

            if (file->IsCompressed &&
354
                !msi_cabextract(package, mi, &data))
355 356
            {
                ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
357
                rc = ERROR_INSTALL_FAILURE;
358
                goto done;
359
            }
360
        }
361

362
        if (!file->IsCompressed)
363
        {
364
            WCHAR *source = msi_resolve_file_source(package, file);
365

366
            TRACE("copying %s to %s\n", debugstr_w(source), debugstr_w(file->TargetPath));
367

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

407
done:
408
    msi_free_media_info(mi);
409 410 411
    return rc;
}

412 413 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
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);

448
        p = msi_get_loaded_filepatch(package, file);
449 450 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
        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;
500
        MSICOMPONENT *comp = file->Component;
501 502 503 504 505 506 507

        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;
        }
508 509
        comp->Action = msi_get_component_action( package, comp );
        if (!comp->Enabled || comp->Action != INSTALLSTATE_LOCAL) continue;
510 511 512 513 514 515 516 517 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

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

            rc = ready_media( package, patch->Sequence, TRUE, mi );
            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;
}

557 558 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
#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)
    {
678
        if (strcmpW( source, file->source ) < 0)
679 680 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
        {
            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;
}

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

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

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

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

786 787 788
    sourcename = MSI_RecordGetString(rec, 3);
    options = MSI_RecordGetInteger(rec, 7);

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

793
    destdir = msi_dup_property(package->db, MSI_RecordGetString(rec, 6));
794 795 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
    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));
833
        if (destname) msi_reduce_to_long_filename(destname);
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
    }

    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)
    {
854
        if (!(ret = msi_create_full_path(destdir)))
855
        {
856
            WARN("failed to create directory %u\n", GetLastError());
857
            goto done;
858 859 860 861 862 863 864 865 866
        }
    }

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

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

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

    return ERROR_SUCCESS;
}

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

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

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

900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
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 );
916
        msi_reduce_to_long_filename( dst_name );
917 918 919 920 921 922 923 924 925 926 927 928 929
    }

    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 );

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

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

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

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

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

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

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

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

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

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

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

1002
    FIXME("We should track these duplicate files as well\n");   
1003

1004 1005 1006 1007
    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 ) );
1008
    msi_ui_actiondata( package, szDuplicateFiles, uirow );
1009
    msiobj_release( &uirow->hdr );
1010

1011
    msi_free(dest);
1012 1013
    return ERROR_SUCCESS;
}
1014

1015 1016
UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
{
1017 1018 1019 1020
    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;
1021
    UINT rc;
1022

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

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

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

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

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

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

1060
    file = msi_get_loaded_file( package, file_key );
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    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());
    }

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

    msi_free(dest);
    return ERROR_SUCCESS;
}

UINT ACTION_RemoveDuplicateFiles( MSIPACKAGE *package )
{
1093 1094 1095
    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};
1096
    MSIQUERY *view;
1097
    UINT rc;
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107

    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;
}

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

1116
    switch (comp->Action)
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
    {
    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;
1128 1129 1130 1131 1132 1133
    }
    return FALSE;
}

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

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

1147
    comp = msi_get_loaded_component(package, component);
1148 1149 1150
    if (!comp)
        return ERROR_SUCCESS;

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

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

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

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

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

1209
    msi_free(filename);
1210 1211
    msi_free(path);
    msi_free(dir);
1212
    return ret;
1213 1214
}

1215
static void remove_folder( MSIFOLDER *folder )
1216
{
1217
    FolderList *fl;
1218

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

1229 1230
UINT ACTION_RemoveFiles( MSIPACKAGE *package )
{
1231 1232 1233
    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};
1234
    MSIQUERY *view;
1235
    MSICOMPONENT *comp;
1236
    MSIFILE *file;
1237 1238 1239 1240 1241
    UINT r;

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

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

1253
        comp = file->Component;
1254 1255
        msi_file_update_ui( package, file, szRemoveFiles );

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

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

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

1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        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 );
        }
1280

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

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

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

        uirow = MSI_CreateRecord( 9 );
        MSI_RecordSetStringW( uirow, 1, file->FileName );
1295
        MSI_RecordSetStringW( uirow, 9, comp->Directory );
1296
        msi_ui_actiondata( package, szRemoveFiles, uirow );
1297
        msiobj_release( &uirow->hdr );
1298
    }
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    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 );
    }
1316 1317
    return ERROR_SUCCESS;
}