files.c 37.1 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
        {
            file->state = msifs_installed;
218
            package->need_reboot_at_end = 1;
219 220 221 222 223 224
            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 254 255
static MSIFILE *find_file( MSIPACKAGE *package, const WCHAR *filename )
{
    MSIFILE *file;

    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
    {
256
        if (file->state != msifs_installed && !strcmpiW( filename, file->File )) return file;
257 258 259 260
    }
    return NULL;
}

261 262 263 264
static BOOL installfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
                            LPWSTR *path, DWORD *attrs, PVOID user)
{
    static MSIFILE *f = NULL;
265
    UINT_PTR disk_id = (UINT_PTR)user;
266 267 268

    if (action == MSICABEXTRACT_BEGINEXTRACT)
    {
269
        if (!(f = find_file( package, file )))
270
        {
271
            TRACE("unknown file in cabinet (%s)\n", debugstr_w(file));
272 273
            return FALSE;
        }
274
        if (f->disk_id != disk_id || (f->state != msifs_missing && f->state != msifs_overwrite))
275 276
            return FALSE;

277 278
        if (!f->Component->assembly || f->Component->assembly->application)
        {
279
            msi_create_directory(package, f->Component->Directory);
280
        }
281 282 283 284 285 286 287 288 289 290 291 292
        *path = strdupW(f->TargetPath);
        *attrs = f->Attributes;
    }
    else if (action == MSICABEXTRACT_FILEEXTRACTED)
    {
        f->state = msifs_installed;
        f = NULL;
    }

    return TRUE;
}

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
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;
}

314
/*
315 316 317 318 319
 * 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.
320
 */
321 322
UINT ACTION_InstallFiles(MSIPACKAGE *package)
{
323
    MSIMEDIAINFO *mi;
324
    MSICOMPONENT *comp;
325
    UINT rc = ERROR_SUCCESS;
326
    MSIFILE *file;
327

328
    schedule_install_files(package);
329
    mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );
330

331
    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
332
    {
333 334
        msi_file_update_ui( package, file, szInstallFiles );

335
        rc = msi_load_media_info( package, file->Sequence, mi );
336 337 338 339 340
        if (rc != ERROR_SUCCESS)
        {
            ERR("Unable to load media info for %s (%u)\n", debugstr_w(file->File), rc);
            return ERROR_FUNCTION_FAILED;
        }
341 342
        if (!file->Component->Enabled) continue;

343
        if (file->state != msifs_hashmatch &&
344 345
            file->state != msifs_skipped &&
            (file->state != msifs_present || !msi_get_property_int( package->db, szInstalled, 0 )) &&
346
            (rc = ready_media( package, file->IsCompressed, mi )))
347 348 349 350
        {
            ERR("Failed to ready media for %s\n", debugstr_w(file->File));
            goto done;
        }
351

352
        if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
353 354
            continue;

355 356
        if (file->Sequence > mi->last_sequence || mi->is_continuous ||
            (file->IsCompressed && !mi->is_extracted))
357
        {
358
            MSICABDATA data;
359 360 361

            data.mi = mi;
            data.package = package;
362
            data.cb = installfiles_cb;
363
            data.user = (PVOID)(UINT_PTR)mi->disk_id;
364 365

            if (file->IsCompressed &&
366
                !msi_cabextract(package, mi, &data))
367 368
            {
                ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
369
                rc = ERROR_INSTALL_FAILURE;
370
                goto done;
371
            }
372
        }
373

374
        if (!file->IsCompressed)
375
        {
376
            WCHAR *source = msi_resolve_file_source(package, file);
377

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

380 381
            if (!file->Component->assembly || file->Component->assembly->application)
            {
382
                msi_create_directory(package, file->Component->Directory);
383
            }
384
            rc = copy_install_file(package, file, source);
385
            if (rc != ERROR_SUCCESS)
386
            {
387
                ERR("Failed to copy %s to %s (%d)\n", debugstr_w(source),
388
                    debugstr_w(file->TargetPath), rc);
389
                rc = ERROR_INSTALL_FAILURE;
390
                msi_free(source);
391
                goto done;
392
            }
393
            msi_free(source);
394
        }
395
        else if (file->state != msifs_installed && !(file->Attributes & msidbFileAttributesPatchAdded))
396
        {
397
            ERR("compressed file wasn't installed (%s)\n", debugstr_w(file->TargetPath));
398
            rc = ERROR_INSTALL_FAILURE;
399 400 401 402 403
            goto done;
        }
    }
    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
    {
404 405
        comp->Action = msi_get_component_action( package, comp );
        if (comp->Action == INSTALLSTATE_LOCAL && comp->assembly && !comp->assembly->installed)
406
        {
407
            rc = msi_install_assembly( package, comp );
408 409 410 411 412 413
            if (rc != ERROR_SUCCESS)
            {
                ERR("Failed to install assembly\n");
                rc = ERROR_INSTALL_FAILURE;
                break;
            }
414
        }
415 416
    }

417
done:
418
    msi_free_media_info(mi);
419 420 421
    return rc;
}

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 450 451 452 453 454 455 456 457
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);

458
        p = msi_get_loaded_filepatch(package, file);
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 502 503 504 505 506 507 508 509
        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;
510
        MSICOMPONENT *comp = file->Component;
511 512 513 514 515 516 517

        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;
        }
518 519
        comp->Action = msi_get_component_action( package, comp );
        if (!comp->Enabled || comp->Action != INSTALLSTATE_LOCAL) continue;
520 521 522 523 524

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

525
            rc = ready_media( package, TRUE, mi );
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 559 560 561 562 563 564 565 566
            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;
}

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 680 681 682 683 684 685 686 687
#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)
    {
688
        if (strcmpW( source, file->source ) < 0)
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 759 760 761 762 763 764 765 766
        {
            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;
}

767 768 769 770 771 772
void msi_reduce_to_long_filename( WCHAR *filename )
{
    WCHAR *p = strchrW( filename, '|' );
    if (p) memmove( filename, p + 1, (strlenW( p + 1 ) + 1) * sizeof(WCHAR) );
}

773 774 775
static UINT ITERATE_MoveFiles( MSIRECORD *rec, LPVOID param )
{
    MSIPACKAGE *package = param;
776
    MSIRECORD *uirow;
777 778
    MSICOMPONENT *comp;
    LPCWSTR sourcename, component;
779
    LPWSTR sourcedir, destname = NULL, destdir = NULL, source = NULL, dest = NULL;
780 781 782 783 784
    int options;
    DWORD size;
    BOOL ret, wildcards;

    component = MSI_RecordGetString(rec, 2);
785
    comp = msi_get_loaded_component(package, component);
786 787 788
    if (!comp)
        return ERROR_SUCCESS;

789 790
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
791
    {
792
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
793 794 795
        return ERROR_SUCCESS;
    }

796 797 798
    sourcename = MSI_RecordGetString(rec, 3);
    options = MSI_RecordGetInteger(rec, 7);

799
    sourcedir = msi_dup_property(package->db, MSI_RecordGetString(rec, 5));
800 801 802
    if (!sourcedir)
        goto done;

803
    destdir = msi_dup_property(package->db, MSI_RecordGetString(rec, 6));
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 835 836 837 838 839 840 841 842
    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));
843
        if (destname) msi_reduce_to_long_filename(destname);
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    }

    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)
    {
864
        if (!(ret = msi_create_full_path(destdir)))
865
        {
866
            WARN("failed to create directory %u\n", GetLastError());
867
            goto done;
868 869 870 871 872 873 874 875 876
        }
    }

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

done:
877 878 879 880
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(rec, 1) );
    MSI_RecordSetInteger( uirow, 6, 1 ); /* FIXME */
    MSI_RecordSetStringW( uirow, 9, destdir );
881
    msi_ui_actiondata( package, szMoveFiles, uirow );
882 883
    msiobj_release( &uirow->hdr );

884 885 886 887 888 889 890 891 892 893 894
    msi_free(sourcedir);
    msi_free(destdir);
    msi_free(destname);
    msi_free(source);
    msi_free(dest);

    return ERROR_SUCCESS;
}

UINT ACTION_MoveFiles( MSIPACKAGE *package )
{
895 896 897
    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
        '`','M','o','v','e','F','i','l','e','`',0};
898
    MSIQUERY *view;
899
    UINT rc;
900

901
    rc = MSI_DatabaseOpenViewW(package->db, query, &view);
902 903 904 905 906 907 908 909
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;

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

910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
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 );
926
        msi_reduce_to_long_filename( dst_name );
927 928 929 930 931 932 933 934 935 936 937 938 939
    }

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

940
        dst_path = strdupW( msi_get_target_folder( package, dst_key ) );
941 942 943
        if (!dst_path)
        {
            /* try a property */
944
            dst_path = msi_dup_property( package->db, dst_key );
945 946 947 948 949 950 951 952 953
            if (!dst_path)
            {
                FIXME("Unable to get destination folder, try AppSearch properties\n");
                msi_free( dst_name );
                return NULL;
            }
        }
    }

954 955
    dst = msi_build_directory_name( 2, dst_path, dst_name );
    msi_create_full_path( dst_path );
956 957 958 959 960 961

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

962
static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
963
{
964
    MSIPACKAGE *package = param;
965
    LPWSTR dest;
966
    LPCWSTR file_key, component;
967
    MSICOMPONENT *comp;
968
    MSIRECORD *uirow;
969
    MSIFILE *file;
970

971
    component = MSI_RecordGetString(row,2);
972
    comp = msi_get_loaded_component(package, component);
973 974
    if (!comp)
        return ERROR_SUCCESS;
975

976 977
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_LOCAL)
978
    {
979
        TRACE("component not scheduled for installation %s\n", debugstr_w(component));
980 981 982
        return ERROR_SUCCESS;
    }

983 984
    file_key = MSI_RecordGetString(row,3);
    if (!file_key)
985
    {
986 987
        ERR("Unable to get file key\n");
        return ERROR_FUNCTION_FAILED;
988 989
    }

990
    file = msi_get_loaded_file( package, file_key );
991
    if (!file)
992
    {
993
        ERR("Original file unknown %s\n", debugstr_w(file_key));
994 995
        return ERROR_SUCCESS;
    }
996

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

1004 1005 1006
    TRACE("Duplicating file %s to %s\n", debugstr_w(file->TargetPath), debugstr_w(dest));

    if (!CopyFileW( file->TargetPath, dest, TRUE ))
1007
    {
1008 1009
        WARN("Failed to copy file %s -> %s (%u)\n",
             debugstr_w(file->TargetPath), debugstr_w(dest), GetLastError());
1010
    }
1011

1012
    FIXME("We should track these duplicate files as well\n");   
1013

1014 1015 1016 1017
    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 ) );
1018
    msi_ui_actiondata( package, szDuplicateFiles, uirow );
1019
    msiobj_release( &uirow->hdr );
1020

1021
    msi_free(dest);
1022 1023
    return ERROR_SUCCESS;
}
1024

1025 1026
UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
{
1027 1028 1029 1030
    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;
1031
    UINT rc;
1032

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

1037
    rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
1038 1039 1040
    msiobj_release(&view->hdr);
    return rc;
}
1041

1042 1043 1044 1045 1046 1047
static UINT ITERATE_RemoveDuplicateFiles( MSIRECORD *row, LPVOID param )
{
    MSIPACKAGE *package = param;
    LPWSTR dest;
    LPCWSTR file_key, component;
    MSICOMPONENT *comp;
1048
    MSIRECORD *uirow;
1049 1050 1051
    MSIFILE *file;

    component = MSI_RecordGetString( row, 2 );
1052
    comp = msi_get_loaded_component( package, component );
1053 1054 1055
    if (!comp)
        return ERROR_SUCCESS;

1056 1057
    comp->Action = msi_get_component_action( package, comp );
    if (comp->Action != INSTALLSTATE_ABSENT)
1058
    {
1059
        TRACE("component not scheduled for removal %s\n", debugstr_w(component));
1060 1061 1062
        return ERROR_SUCCESS;
    }

1063 1064 1065 1066 1067 1068 1069
    file_key = MSI_RecordGetString( row, 3 );
    if (!file_key)
    {
        ERR("Unable to get file key\n");
        return ERROR_FUNCTION_FAILED;
    }

1070
    file = msi_get_loaded_file( package, file_key );
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    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());
    }

1091 1092 1093
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString( row, 1 ) );
    MSI_RecordSetStringW( uirow, 9, MSI_RecordGetString( row, 5 ) );
1094
    msi_ui_actiondata( package, szRemoveDuplicateFiles, uirow );
1095
    msiobj_release( &uirow->hdr );
1096 1097 1098 1099 1100 1101 1102

    msi_free(dest);
    return ERROR_SUCCESS;
}

UINT ACTION_RemoveDuplicateFiles( MSIPACKAGE *package )
{
1103 1104 1105
    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};
1106
    MSIQUERY *view;
1107
    UINT rc;
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

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

1118 1119
static BOOL verify_comp_for_removal(MSICOMPONENT *comp, UINT install_mode)
{
1120
    /* special case */
1121
    if (comp->Action != INSTALLSTATE_SOURCE &&
1122 1123 1124 1125
        comp->Attributes & msidbComponentAttributesSourceOnly &&
        (install_mode == msidbRemoveFileInstallModeOnRemove ||
         install_mode == msidbRemoveFileInstallModeOnBoth)) return TRUE;

1126
    switch (comp->Action)
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    {
    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;
1138 1139 1140 1141 1142 1143
    }
    return FALSE;
}

static UINT ITERATE_RemoveFiles(MSIRECORD *row, LPVOID param)
{
1144
    MSIPACKAGE *package = param;
1145
    MSICOMPONENT *comp;
1146
    MSIRECORD *uirow;
1147
    LPCWSTR component, dirprop;
1148
    UINT install_mode;
1149
    LPWSTR dir = NULL, path = NULL, filename = NULL;
1150
    DWORD size;
1151
    UINT ret = ERROR_SUCCESS;
1152 1153 1154 1155 1156

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

1157
    comp = msi_get_loaded_component(package, component);
1158 1159 1160
    if (!comp)
        return ERROR_SUCCESS;

1161
    comp->Action = msi_get_component_action( package, comp );
1162 1163
    if (!verify_comp_for_removal(comp, install_mode))
    {
1164
        TRACE("Skipping removal due to install mode\n");
1165 1166
        return ERROR_SUCCESS;
    }
1167 1168 1169 1170
    if (comp->assembly && !comp->assembly->application)
    {
        return ERROR_SUCCESS;
    }
1171 1172 1173 1174 1175 1176
    if (comp->Attributes & msidbComponentAttributesPermanent)
    {
        TRACE("permanent component, not removing file\n");
        return ERROR_SUCCESS;
    }

1177
    dir = msi_dup_property(package->db, dirprop);
1178
    if (!dir)
1179 1180 1181 1182
    {
        WARN("directory property has no value\n");
        return ERROR_SUCCESS;
    }
1183
    size = 0;
1184
    if ((filename = strdupW( MSI_RecordGetString(row, 3) )))
1185
    {
1186
        msi_reduce_to_long_filename( filename );
1187 1188
        size = lstrlenW( filename );
    }
1189
    size += lstrlenW(dir) + 2;
1190 1191 1192
    path = msi_alloc(size * sizeof(WCHAR));
    if (!path)
    {
1193
        ret = ERROR_OUTOFMEMORY;
1194 1195 1196
        goto done;
    }

1197 1198
    if (filename)
    {
1199 1200
        lstrcpyW(path, dir);
        PathAddBackslashW(path);
1201 1202 1203 1204 1205 1206 1207
        lstrcatW(path, filename);

        TRACE("Deleting misc file: %s\n", debugstr_w(path));
        DeleteFileW(path);
    }
    else
    {
1208 1209
        TRACE("Removing misc directory: %s\n", debugstr_w(dir));
        RemoveDirectoryW(dir);
1210
    }
1211 1212

done:
1213 1214 1215
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, MSI_RecordGetString(row, 1) );
    MSI_RecordSetStringW( uirow, 9, dir );
1216
    msi_ui_actiondata( package, szRemoveFiles, uirow );
1217 1218
    msiobj_release( &uirow->hdr );

1219
    msi_free(filename);
1220 1221
    msi_free(path);
    msi_free(dir);
1222
    return ret;
1223 1224
}

1225
static void remove_folder( MSIFOLDER *folder )
1226
{
1227
    FolderList *fl;
1228

1229
    LIST_FOR_EACH_ENTRY( fl, &folder->children, FolderList, entry )
1230
    {
1231 1232 1233 1234 1235
        remove_folder( fl->folder );
    }
    if (!folder->persistent && folder->State != FOLDER_STATE_REMOVED)
    {
        if (RemoveDirectoryW( folder->ResolvedTarget )) folder->State = FOLDER_STATE_REMOVED;
1236 1237 1238
    }
}

1239 1240
UINT ACTION_RemoveFiles( MSIPACKAGE *package )
{
1241 1242 1243
    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};
1244
    MSIQUERY *view;
1245
    MSICOMPONENT *comp;
1246
    MSIFILE *file;
1247 1248 1249 1250 1251
    UINT r;

    r = MSI_DatabaseOpenViewW(package->db, query, &view);
    if (r == ERROR_SUCCESS)
    {
1252
        r = MSI_IterateRecords(view, NULL, ITERATE_RemoveFiles, package);
1253
        msiobj_release(&view->hdr);
1254 1255
        if (r != ERROR_SUCCESS)
            return r;
1256
    }
1257 1258 1259

    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
    {
1260
        MSIRECORD *uirow;
1261
        VS_FIXEDFILEINFO *ver;
1262

1263
        comp = file->Component;
1264 1265
        msi_file_update_ui( package, file, szRemoveFiles );

1266 1267 1268 1269 1270
        comp->Action = msi_get_component_action( package, comp );
        if (comp->Action != INSTALLSTATE_ABSENT || comp->Installed == INSTALLSTATE_SOURCE)
            continue;

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

1273
        if (comp->Attributes & msidbComponentAttributesPermanent)
1274 1275 1276 1277 1278
        {
            TRACE("permanent component, not removing file\n");
            continue;
        }

1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
        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 );
        }
1290

1291 1292 1293
        if (file->state == msifs_installed)
            WARN("removing installed file %s\n", debugstr_w(file->TargetPath));

1294
        TRACE("removing %s\n", debugstr_w(file->File) );
1295 1296

        SetFileAttributesW( file->TargetPath, FILE_ATTRIBUTE_NORMAL );
1297 1298
        if (!DeleteFileW( file->TargetPath ))
        {
1299
            WARN("failed to delete %s (%u)\n",  debugstr_w(file->TargetPath), GetLastError());
1300
        }
1301
        file->state = msifs_missing;
1302 1303 1304

        uirow = MSI_CreateRecord( 9 );
        MSI_RecordSetStringW( uirow, 1, file->FileName );
1305
        MSI_RecordSetStringW( uirow, 9, comp->Directory );
1306
        msi_ui_actiondata( package, szRemoveFiles, uirow );
1307
        msiobj_release( &uirow->hdr );
1308
    }
1309

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    LIST_FOR_EACH_ENTRY( comp, &package->components, MSICOMPONENT, entry )
    {
        comp->Action = msi_get_component_action( package, comp );
        if (comp->Action != INSTALLSTATE_ABSENT) continue;

        if (comp->Attributes & msidbComponentAttributesPermanent)
        {
            TRACE("permanent component, not removing directory\n");
            continue;
        }
1320 1321 1322 1323 1324 1325 1326
        if (comp->assembly && !comp->assembly->application)
            msi_uninstall_assembly( package, comp );
        else
        {
            MSIFOLDER *folder = msi_get_loaded_folder( package, comp->Directory );
            remove_folder( folder );
        }
1327
    }
1328 1329
    return ERROR_SUCCESS;
}