files.c 27 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 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 */


/*
 * Actions dealing with files These are
 *
 * InstallFiles
 * DuplicateFiles
 * MoveFiles (TODO)
 * PatchFiles (TODO)
 * RemoveDuplicateFiles(TODO)
 * RemoveFiles(TODO)
 */

#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 44
#include "msidefs.h"
#include "msvcrt/fcntl.h"
#include "msipriv.h"
#include "winuser.h"
45 46
#include "winreg.h"
#include "shlwapi.h"
47 48 49 50 51 52 53 54 55 56 57 58 59
#include "wine/unicode.h"

WINE_DEFAULT_DEBUG_CHANNEL(msi);

extern const WCHAR szInstallFiles[];
extern const WCHAR szDuplicateFiles[];
extern const WCHAR szMoveFiles[];
extern const WCHAR szPatchFiles[];
extern const WCHAR szRemoveDuplicateFiles[];
extern const WCHAR szRemoveFiles[];

static const WCHAR cszTempFolder[]= {'T','e','m','p','F','o','l','d','e','r',0};

60
struct media_info {
61
    UINT disk_id;
62
    UINT last_sequence;
63 64 65 66
    LPWSTR disk_prompt;
    LPWSTR cabinet;
    LPWSTR volume_label;
    BOOL is_continuous;
67
    BOOL is_extracted;
68 69 70
    WCHAR source[MAX_PATH];
};

71 72 73 74 75 76 77 78 79 80 81 82 83 84
static BOOL source_matches_volume(struct media_info *mi, LPWSTR source_root)
{
    WCHAR volume_name[MAX_PATH + 1];

    if (!GetVolumeInformationW(source_root, volume_name, MAX_PATH + 1,
                               NULL, NULL, NULL, NULL, 0))
    {
        ERR("Failed to get volume information\n");
        return FALSE;
    }

    return !lstrcmpW(mi->volume_label, volume_name);
}

85 86
static UINT msi_change_media( MSIPACKAGE *package, struct media_info *mi )
{
87
    LPSTR msg;
88
    LPWSTR error, error_dialog;
89
    LPWSTR source_dir;
90 91 92 93 94
    UINT r = ERROR_SUCCESS;

    static const WCHAR szUILevel[] = {'U','I','L','e','v','e','l',0};
    static const WCHAR error_prop[] = {'E','r','r','o','r','D','i','a','l','o','g',0};

95
    if ( (msi_get_property_int(package, szUILevel, 0) & INSTALLUILEVEL_MASK) == INSTALLUILEVEL_NONE && !gUIHandlerA )
96 97 98 99
        return ERROR_SUCCESS;

    error = generate_error_string( package, 1302, 1, mi->disk_prompt );
    error_dialog = msi_dup_property( package, error_prop );
100 101
    source_dir = msi_dup_property( package, cszSourceDir );
    PathStripToRootW(source_dir);
102

103 104
    while ( r == ERROR_SUCCESS &&
            !source_matches_volume(mi, source_dir) )
105
    {
106 107
        r = msi_spawn_error_dialog( package, error_dialog, error );

108 109 110 111 112 113 114 115
        if (gUIHandlerA)
        {
            msg = strdupWtoA( error );
            gUIHandlerA( gUIContext, MB_RETRYCANCEL | INSTALLMESSAGE_ERROR, msg );
            msi_free(msg);
        }
    }

116 117
    msi_free( error );
    msi_free( error_dialog );
118
    msi_free( source_dir );
119 120 121 122

    return r;
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
/*
 * This is a helper function for handling embedded cabinet media
 */
static UINT writeout_cabinet_stream(MSIPACKAGE *package, LPCWSTR stream_name,
                                    WCHAR* source)
{
    UINT rc;
    USHORT* data;
    UINT    size;
    DWORD   write;
    HANDLE  the_file;
    WCHAR tmp[MAX_PATH];

    rc = read_raw_stream_data(package->db,stream_name,&data,&size); 
    if (rc != ERROR_SUCCESS)
        return rc;

    write = MAX_PATH;
    if (MSI_GetPropertyW(package, cszTempFolder, tmp, &write))
        GetTempPathW(MAX_PATH,tmp);

    GetTempFileNameW(tmp,stream_name,0,source);

146
    track_tempfile(package, source);
147 148 149 150 151 152 153 154 155 156 157 158
    the_file = CreateFileW(source, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
                           FILE_ATTRIBUTE_NORMAL, NULL);

    if (the_file == INVALID_HANDLE_VALUE)
    {
        ERR("Unable to create file %s\n",debugstr_w(source));
        rc = ERROR_FUNCTION_FAILED;
        goto end;
    }

    WriteFile(the_file,data,size,&write,NULL);
    CloseHandle(the_file);
159
    TRACE("wrote %i bytes to %s\n",write,debugstr_w(source));
160
end:
161
    msi_free(data);
162 163 164 165 166 167 168 169
    return rc;
}


/* Support functions for FDI functions */
typedef struct
{
    MSIPACKAGE* package;
170
    struct media_info *mi;
171 172 173 174
} CabData;

static void * cabinet_alloc(ULONG cb)
{
175
    return msi_alloc(cb);
176 177 178 179
}

static void cabinet_free(void *pv)
{
180
    msi_free(pv);
181 182 183 184
}

static INT_PTR cabinet_open(char *pszFile, int oflag, int pmode)
{
185
    HANDLE handle;
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    DWORD dwAccess = 0;
    DWORD dwShareMode = 0;
    DWORD dwCreateDisposition = OPEN_EXISTING;
    switch (oflag & _O_ACCMODE)
    {
    case _O_RDONLY:
        dwAccess = GENERIC_READ;
        dwShareMode = FILE_SHARE_READ | FILE_SHARE_DELETE;
        break;
    case _O_WRONLY:
        dwAccess = GENERIC_WRITE;
        dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
        break;
    case _O_RDWR:
        dwAccess = GENERIC_READ | GENERIC_WRITE;
        dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
        break;
    }
    if ((oflag & (_O_CREAT | _O_EXCL)) == (_O_CREAT | _O_EXCL))
        dwCreateDisposition = CREATE_NEW;
    else if (oflag & _O_CREAT)
        dwCreateDisposition = CREATE_ALWAYS;
208 209 210 211 212
    handle = CreateFileA( pszFile, dwAccess, dwShareMode, NULL, 
                          dwCreateDisposition, 0, NULL );
    if (handle == INVALID_HANDLE_VALUE)
        return 0;
    return (INT_PTR) handle;
213 214 215 216
}

static UINT cabinet_read(INT_PTR hf, void *pv, UINT cb)
{
217
    HANDLE handle = (HANDLE) hf;
218
    DWORD dwRead;
219
    if (ReadFile(handle, pv, cb, &dwRead, NULL))
220 221 222 223 224 225
        return dwRead;
    return 0;
}

static UINT cabinet_write(INT_PTR hf, void *pv, UINT cb)
{
226
    HANDLE handle = (HANDLE) hf;
227
    DWORD dwWritten;
228
    if (WriteFile(handle, pv, cb, &dwWritten, NULL))
229 230 231 232 233 234
        return dwWritten;
    return 0;
}

static int cabinet_close(INT_PTR hf)
{
235 236
    HANDLE handle = (HANDLE) hf;
    return CloseHandle(handle) ? 0 : -1;
237 238 239 240
}

static long cabinet_seek(INT_PTR hf, long dist, int seektype)
{
241
    HANDLE handle = (HANDLE) hf;
242
    /* flags are compatible and so are passed straight through */
243
    return SetFilePointer(handle, dist, NULL, seektype);
244 245
}

246
static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *action )
247 248 249 250 251 252 253 254 255 256 257 258 259
{
    MSIRECORD *uirow;
    LPWSTR uipath, p;

    /* the UI chunk */
    uirow = MSI_CreateRecord( 9 );
    MSI_RecordSetStringW( uirow, 1, f->FileName );
    uipath = strdupW( f->TargetPath );
    p = strrchrW(uipath,'\\');
    if (p)
        p[1]=0;
    MSI_RecordSetStringW( uirow, 9, uipath);
    MSI_RecordSetInteger( uirow, 6, f->FileSize );
260
    ui_actiondata( package, action, uirow);
261 262 263 264 265
    msiobj_release( &uirow->hdr );
    msi_free( uipath );
    ui_progress( package, 2, f->FileSize, 0, 0);
}

266
static UINT msi_media_get_disk_info( MSIPACKAGE *package, struct media_info *mi )
267 268 269 270 271 272 273 274 275
{
    MSIRECORD *row;
    LPWSTR ptr;

    static const WCHAR query[] =
        {'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
         '`','M','e','d','i','a','`',' ','W','H','E','R','E',' ',
         '`','D','i','s','k','I','d','`',' ','=',' ','%','i',0};

276
    row = MSI_QueryGetRecord(package->db, query, mi->disk_id);
277 278 279 280 281 282
    if (!row)
    {
        TRACE("Unable to query row\n");
        return ERROR_FUNCTION_FAILED;
    }

283 284
    mi->disk_prompt = strdupW(MSI_RecordGetString(row, 3));
    mi->cabinet = strdupW(MSI_RecordGetString(row, 4));
285
    mi->volume_label = strdupW(MSI_RecordGetString(row, 5));
286

287 288
    ptr = strrchrW(mi->source, '\\') + 1;
    lstrcpyW(ptr, mi->cabinet);
289
    msiobj_release(&row->hdr);
290 291 292 293

    return ERROR_SUCCESS;
}

294 295
static INT_PTR cabinet_notify(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
{
296 297
    TRACE("(%d)\n", fdint);

298 299
    switch (fdint)
    {
300 301 302 303 304 305 306 307 308 309 310 311 312 313
    case fdintPARTIAL_FILE:
    {
        CabData *data = (CabData *)pfdin->pv;
        data->mi->is_continuous = FALSE;
        return 0;
    }
    case fdintNEXT_CABINET:
    {
        CabData *data = (CabData *)pfdin->pv;
        struct media_info *mi = data->mi;
        LPWSTR cab = strdupAtoW(pfdin->psz1);
        UINT rc;

        msi_free(mi->disk_prompt);
314 315
        msi_free(mi->cabinet);
        msi_free(mi->volume_label);
316 317 318 319

        mi->disk_id++;
        mi->is_continuous = TRUE;

320
        rc = msi_media_get_disk_info(data->package, mi);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
        if (rc != ERROR_SUCCESS)
        {
            ERR("Failed to get next cabinet information: %d\n", rc);
            return -1;
        }

        if (lstrcmpiW(mi->cabinet, cab))
        {
            msi_free(cab);
            ERR("Continuous cabinet does not match the next cabinet in the Media table\n");
            return -1;
        }

        msi_free(cab);

        TRACE("Searching for %s\n", debugstr_w(mi->source));

        if (GetFileAttributesW(mi->source) == INVALID_FILE_ATTRIBUTES)
            rc = msi_change_media(data->package, mi);

        if (rc != ERROR_SUCCESS)
            return -1;

        return 0;
    }
346 347 348
    case fdintCOPY_FILE:
    {
        CabData *data = (CabData*) pfdin->pv;
349 350
        HANDLE handle;
        LPWSTR file;
351
        MSIFILE *f;
352
        DWORD attrs;
353

354 355 356
        file = strdupAtoW(pfdin->psz1);
        f = get_loaded_file(data->package, file);
        msi_free(file);
357

358
        if (!f)
359
        {
360
            WARN("unknown file in cabinet (%s)\n",debugstr_a(pfdin->psz1));
361 362 363
            return 0;
        }

364
        if (f->state != msifs_missing && f->state != msifs_overwrite)
365
        {
366
            TRACE("Skipping extraction of %s\n",debugstr_a(pfdin->psz1));
367 368 369
            return 0;
        }

370
        msi_file_update_ui( data->package, f, szInstallFiles );
371

372
        TRACE("extracting %s\n", debugstr_w(f->TargetPath) );
373

374 375 376
        attrs = f->Attributes & (FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
        if (!attrs) attrs = FILE_ATTRIBUTE_NORMAL;

377
        handle = CreateFileW( f->TargetPath, GENERIC_READ | GENERIC_WRITE, 0,
378
                              NULL, CREATE_ALWAYS, attrs, NULL );
379 380
        if ( handle == INVALID_HANDLE_VALUE )
        {
381 382 383 384 385 386
            if ( GetFileAttributesW( f->TargetPath ) != INVALID_FILE_ATTRIBUTES )
                f->state = msifs_installed;
            else
                ERR("failed to create %s (error %d)\n",
                    debugstr_w( f->TargetPath ), GetLastError() );

387 388
            return 0;
        }
389

390
        f->state = msifs_installed;
391
        return (INT_PTR) handle;
392 393 394 395
    }
    case fdintCLOSE_FILE_INFO:
    {
        FILETIME ft;
396 397 398
        FILETIME ftLocal;
        HANDLE handle = (HANDLE) pfdin->hf;

399 400 401 402
        if (!DosDateTimeToFileTime(pfdin->date, pfdin->time, &ft))
            return -1;
        if (!LocalFileTimeToFileTime(&ft, &ftLocal))
            return -1;
403
        if (!SetFileTime(handle, &ftLocal, 0, &ftLocal))
404
            return -1;
405
        CloseHandle(handle);
406 407 408 409 410 411 412 413 414 415 416 417
        return 1;
    }
    default:
        return 0;
    }
}

/***********************************************************************
 *            extract_cabinet_file
 *
 * Extract files from a cab file.
 */
418
static BOOL extract_cabinet_file(MSIPACKAGE* package, struct media_info *mi)
419
{
420 421
    LPSTR cabinet, cab_path = NULL;
    LPWSTR ptr;
422 423
    HFDI hfdi;
    ERF erf;
424
    BOOL ret = FALSE;
425 426
    CabData data;

427 428 429 430
    TRACE("Extracting %s\n", debugstr_w(mi->source));

    hfdi = FDICreate(cabinet_alloc, cabinet_free, cabinet_open, cabinet_read,
                     cabinet_write, cabinet_close, cabinet_seek, 0, &erf);
431 432 433 434 435 436
    if (!hfdi)
    {
        ERR("FDICreate failed\n");
        return FALSE;
    }

437 438 439 440
    ptr = strrchrW(mi->source, '\\') + 1;
    cabinet = strdupWtoA(ptr);
    if (!cabinet)
        goto done;
441

442 443 444
    cab_path = strdupWtoA(mi->source);
    if (!cab_path)
        goto done;
445

446 447 448 449
    cab_path[ptr - mi->source] = '\0';

    data.package = package;
    data.mi = mi;
450

451
    ret = FDICopy(hfdi, cabinet, cab_path, 0, cabinet_notify, NULL, &data);
452 453 454
    if (!ret)
        ERR("FDICopy failed\n");

455
done:
456
    FDIDestroy(hfdi);
457 458
    msi_free(cabinet);
    msi_free(cab_path);
459

460 461 462
    if (ret)
        mi->is_extracted = TRUE;

463 464 465
    return ret;
}

466
static VOID set_file_source(MSIPACKAGE* package, MSIFILE* file, LPCWSTR path)
467
{
468
    if (!file->IsCompressed)
469
    {
470
        LPWSTR p, path;
471
        p = resolve_folder(package, file->Component->Directory, TRUE, FALSE, TRUE, NULL);
472
        path = build_directory_name(2, p, file->ShortName);
473 474
        if (file->LongName &&
            INVALID_FILE_ATTRIBUTES == GetFileAttributesW( path ))
475 476 477 478 479
        {
            msi_free(path);
            path = build_directory_name(2, p, file->LongName);
        }
        file->SourcePath = path;
480
        msi_free(p);
481 482 483 484 485
    }
    else
        file->SourcePath = build_directory_name(2, path, file->File);
}

486 487
static void free_media_info( struct media_info *mi )
{
488 489 490
    msi_free( mi->disk_prompt );
    msi_free( mi->cabinet );
    msi_free( mi->volume_label );
491 492 493
    msi_free( mi );
}

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
static UINT download_remote_cabinet(MSIPACKAGE *package, struct media_info *mi)
{
    WCHAR temppath[MAX_PATH];
    LPWSTR src, ptr;
    LPCWSTR cab;

    src = strdupW(package->BaseURL);
    if (!src)
        return ERROR_OUTOFMEMORY;

    ptr = strrchrW(src, '/');
    if (!ptr)
    {
        msi_free(src);
        return ERROR_FUNCTION_FAILED;
    }

    *(ptr + 1) = '\0';
    ptr = strrchrW(mi->source, '\\');
513 514 515
    if (!ptr)
        ptr = mi->source;

516 517 518 519
    src = msi_realloc(src, (lstrlenW(src) + lstrlenW(ptr)) * sizeof(WCHAR));
    if (!src)
        return ERROR_OUTOFMEMORY;

520 521
    lstrcatW(src, ptr + 1);

522
    temppath[0] = '\0';
523 524 525 526 527 528 529
    cab = msi_download_file(src, temppath);
    lstrcpyW(mi->source, cab);

    msi_free(src);
    return ERROR_SUCCESS;
}

530
static UINT load_media_info(MSIPACKAGE *package, MSIFILE *file, struct media_info *mi)
531
{
532
    MSIRECORD *row;
533
    LPWSTR source_dir;
534 535 536 537 538 539 540 541 542 543 544 545
    UINT r;

    static const WCHAR query[] = {
        'S','E','L','E','C','T',' ','*',' ', 'F','R','O','M',' ',
        '`','M','e','d','i','a','`',' ','W','H','E','R','E',' ',
        '`','L','a','s','t','S','e','q','u','e','n','c','e','`',' ','>','=',
        ' ','%','i',' ','A','N','D',' ','`','D','i','s','k','I','d','`',' ','>','=',
        ' ','%','i',' ','O','R','D','E','R',' ','B','Y',' ',
        '`','D','i','s','k','I','d','`',0
    };

    row = MSI_QueryGetRecord(package->db, query, file->Sequence, mi->disk_id);
546
    if (!row)
547 548
    {
        TRACE("Unable to query row\n");
549
        return ERROR_FUNCTION_FAILED;
550
    }
551

552
    mi->is_extracted = FALSE;
553 554
    mi->disk_id = MSI_RecordGetInteger(row, 1);
    mi->last_sequence = MSI_RecordGetInteger(row, 2);
555
    msi_free(mi->disk_prompt);
556
    mi->disk_prompt = strdupW(MSI_RecordGetString(row, 3));
557
    msi_free(mi->cabinet);
558
    mi->cabinet = strdupW(MSI_RecordGetString(row, 4));
559
    msi_free(mi->volume_label);
560 561
    mi->volume_label = strdupW(MSI_RecordGetString(row, 5));
    msiobj_release(&row->hdr);
562

563
    source_dir = msi_dup_property(package, cszSourceDir);
564

565 566 567 568 569 570 571 572 573 574
    if (mi->cabinet && mi->cabinet[0] == '#')
    {
        r = writeout_cabinet_stream(package, &mi->cabinet[1], mi->source);
        if (r != ERROR_SUCCESS)
        {
            ERR("Failed to extract cabinet stream\n");
            return ERROR_FUNCTION_FAILED;
        }
    }
    else
575
    {
576
        lstrcpyW(mi->source, source_dir);
577 578


579 580
        if (mi->cabinet)
            lstrcatW(mi->source, mi->cabinet);
581 582
    }

583 584
    msi_package_add_media_disk(package, MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT,
                               mi->disk_id, mi->volume_label, mi->disk_prompt);
585

586 587 588
    msi_package_add_info(package, MSIINSTALLCONTEXT_USERMANAGED,
                         MSICODE_PRODUCT | MSISOURCETYPE_MEDIA,
                         INSTALLPROPERTY_LASTUSEDSOURCEW, mi->source);
589

590 591 592
    msi_free(source_dir);
    return ERROR_SUCCESS;
}
593

594
static UINT ready_media(MSIPACKAGE *package, MSIFILE *file, struct media_info *mi)
595
{
596 597 598
    UINT rc = ERROR_SUCCESS, type;
    BOOL found = TRUE;
    LPWSTR source_dir;
599

600 601 602 603
    /* media info for continuous cabinet is already loaded */
    if (mi->is_continuous)
        return ERROR_SUCCESS;

604 605 606 607 608 609
    rc = load_media_info(package, file, mi);
    if (rc != ERROR_SUCCESS)
    {
        ERR("Unable to load media info\n");
        return ERROR_FUNCTION_FAILED;
    }
610

611
    if (mi->volume_label && mi->disk_id > 1)
612 613 614 615 616 617 618 619
    {
        source_dir = msi_dup_property(package, cszSourceDir);
        PathStripToRootW(source_dir);
        type = GetDriveTypeW(source_dir);

        if (type == DRIVE_CDROM || type == DRIVE_REMOVABLE)
            found = source_matches_volume(mi, source_dir);

620 621 622
        if (!found)
            found = GetFileAttributesW(mi->cabinet) != INVALID_FILE_ATTRIBUTES;

623 624 625
        msi_free(source_dir);
    }

626 627
    if (file->IsCompressed &&
        GetFileAttributesW(mi->source) == INVALID_FILE_ATTRIBUTES)
628
    {
629 630
        found = FALSE;

631
        if (package->BaseURL && UrlIsW(package->BaseURL, URLIS_URL))
632
        {
633
            rc = download_remote_cabinet(package, mi);
634 635
            if (rc == ERROR_SUCCESS &&
                GetFileAttributesW(mi->source) != INVALID_FILE_ATTRIBUTES)
636
            {
637
                found = TRUE;
638 639
            }
        }
640
    }
641

642 643 644
    if (!found)
        rc = msi_change_media(package, mi);

645 646 647
    return rc;
}

648
static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
649
                            MSIFILE** file)
650
{
651
    LIST_FOR_EACH_ENTRY( *file, &package->files, MSIFILE, entry )
652
    {
653
        if (lstrcmpW( file_key, (*file)->File )==0)
654
        {
655
            if ((*file)->state >= msifs_overwrite)
656 657 658 659 660 661 662 663 664
                return ERROR_SUCCESS;
            else
                return ERROR_FILE_NOT_FOUND;
        }
    }

    return ERROR_FUNCTION_FAILED;
}

665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
static void schedule_install_files(MSIPACKAGE *package)
{
    MSIFILE *file;

    LIST_FOR_EACH_ENTRY(file, &package->files, MSIFILE, entry)
    {
        if (!ACTION_VerifyComponentForAction(file->Component, INSTALLSTATE_LOCAL))
        {
            TRACE("File %s is not scheduled for install\n", debugstr_w(file->File));

            ui_progress(package,2,file->FileSize,0,0);
            file->state = msifs_skipped;
        }
    }
}

681
static UINT copy_file(MSIFILE *file)
682 683 684 685 686 687 688 689 690 691
{
    BOOL ret;

    ret = CopyFileW(file->SourcePath, file->TargetPath, FALSE);
    if (ret)
    {
        file->state = msifs_installed;
        return ERROR_SUCCESS;
    }

692 693 694 695 696 697 698 699 700 701 702 703 704 705
    return GetLastError();
}

static UINT copy_install_file(MSIFILE *file)
{
    UINT gle;

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

    gle = copy_file(file);
    if (gle == ERROR_SUCCESS)
        return gle;

706 707 708 709 710 711 712 713 714 715 716
    if (gle == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
    {
        TRACE("overwriting existing file\n");
        gle = ERROR_SUCCESS;
    }
    else if (gle == ERROR_FILE_NOT_FOUND)
    {
        /* FIXME: this needs to be tested, I'm pretty sure it fails */
        TRACE("Source file not found\n");
        gle = ERROR_SUCCESS;
    }
717 718 719 720 721 722 723
    else if (gle == ERROR_ACCESS_DENIED)
    {
        SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);

        gle = copy_file(file);
        TRACE("Overwriting existing file: %d\n", gle);
    }
724 725 726 727 728 729 730 731 732
    else if (!(file->Attributes & msidbFileAttributesVital))
    {
        TRACE("Ignoring error for nonvital\n");
        gle = ERROR_SUCCESS;
    }

    return gle;
}

733
/*
734 735 736 737 738
 * 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.
739
 */
740 741
UINT ACTION_InstallFiles(MSIPACKAGE *package)
{
742
    struct media_info *mi;
743
    UINT rc = ERROR_SUCCESS;
744
    LPWSTR ptr;
745
    MSIFILE *file;
746 747 748 749

    /* increment progress bar each time action data is sent */
    ui_progress(package,1,1,0,0);

750
    /* handle the keys for the SourceList */
751 752 753
    ptr = strrchrW(package->PackagePath,'\\');
    if (ptr)
    {
754
        ptr++;
755 756
        msi_package_add_info(package, MSIINSTALLCONTEXT_USERMANAGED,
                             MSICODE_PRODUCT, INSTALLPROPERTY_PACKAGENAMEW, ptr);
757
    }
758

759
    schedule_install_files(package);
760

761 762 763 764 765 766 767 768
    /*
     * Despite MSDN specifying that the CreateFolders action
     * should be called before InstallFiles, some installers don't
     * do that, and they seem to work correctly.  We need to create
     * directories here to make sure that the files can be copied.
     */
    msi_create_component_directories( package );

769
    mi = msi_alloc_zero( sizeof(struct media_info) );
770

771
    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
772
    {
773
        if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
774 775
            continue;

776 777
        if (file->Sequence > mi->last_sequence || mi->is_continuous ||
            (file->IsCompressed && !mi->is_extracted))
778
        {
779
            rc = ready_media(package, file, mi);
780 781 782 783 784 785
            if (rc != ERROR_SUCCESS)
            {
                ERR("Failed to ready media\n");
                rc = ERROR_FUNCTION_FAILED;
                break;
            }
786 787 788 789 790 791 792

            if (file->IsCompressed && !extract_cabinet_file(package, mi))
            {
                ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
                rc = ERROR_FUNCTION_FAILED;
                break;
            }
793
        }
794

795 796
        set_file_source(package, file, mi->source);

797 798
        TRACE("file paths %s to %s\n",debugstr_w(file->SourcePath),
              debugstr_w(file->TargetPath));
799

800
        if (!file->IsCompressed)
801
        {
802
            msi_file_update_ui(package, file, szInstallFiles);
803 804
            rc = copy_install_file(file);
            if (rc != ERROR_SUCCESS)
805
            {
806 807
                ERR("Failed to copy %s to %s (%d)\n", debugstr_w(file->SourcePath),
                    debugstr_w(file->TargetPath), rc);
808 809 810
                rc = ERROR_INSTALL_FAILURE;
                break;
            }
811
        }
812
        else if (file->state != msifs_installed)
813
        {
814
            ERR("compressed file wasn't extracted (%s)\n", debugstr_w(file->TargetPath));
815 816
            rc = ERROR_INSTALL_FAILURE;
            break;
817
        }
818 819
    }

820
    free_media_info( mi );
821 822 823
    return rc;
}

824
static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
825
{
826 827 828 829 830 831
    MSIPACKAGE *package = (MSIPACKAGE*)param;
    WCHAR dest_name[0x100];
    LPWSTR dest_path, dest;
    LPCWSTR file_key, component;
    DWORD sz;
    DWORD rc;
832
    MSICOMPONENT *comp;
833
    MSIFILE *file;
834

835
    component = MSI_RecordGetString(row,2);
836
    comp = get_loaded_component(package,component);
837

838
    if (!ACTION_VerifyComponentForAction( comp, INSTALLSTATE_LOCAL ))
839 840 841 842 843
    {
        TRACE("Skipping copy due to disabled component %s\n",
                        debugstr_w(component));

        /* the action taken was the same as the current install state */        
844
        comp->Action = comp->Installed;
845 846

        return ERROR_SUCCESS;
847
    }
848

849
    comp->Action = INSTALLSTATE_LOCAL;
850 851 852

    file_key = MSI_RecordGetString(row,3);
    if (!file_key)
853
    {
854 855
        ERR("Unable to get file key\n");
        return ERROR_FUNCTION_FAILED;
856 857
    }

858
    rc = get_file_target(package,file_key,&file);
859 860

    if (rc != ERROR_SUCCESS)
861
    {
862 863 864
        ERR("Original file unknown %s\n",debugstr_w(file_key));
        return ERROR_SUCCESS;
    }
865

866
    if (MSI_RecordIsNull(row,4))
867
        strcpyW(dest_name,strrchrW(file->TargetPath,'\\')+1);
868 869 870 871 872
    else
    {
        sz=0x100;
        MSI_RecordGetStringW(row,4,dest_name,&sz);
        reduce_to_longfilename(dest_name);
873
    }
874

875 876 877
    if (MSI_RecordIsNull(row,5))
    {
        LPWSTR p;
878
        dest_path = strdupW(file->TargetPath);
879 880 881 882 883 884 885 886
        p = strrchrW(dest_path,'\\');
        if (p)
            *p=0;
    }
    else
    {
        LPCWSTR destkey;
        destkey = MSI_RecordGetString(row,5);
887
        dest_path = resolve_folder(package, destkey, FALSE, FALSE, TRUE, NULL);
888
        if (!dest_path)
889
        {
890
            /* try a Property */
891
            dest_path = msi_dup_property( package, destkey );
892 893 894 895 896
            if (!dest_path)
            {
                FIXME("Unable to get destination folder, try AppSearch properties\n");
                return ERROR_SUCCESS;
            }
897
        }
898
    }
899

900
    dest = build_directory_name(2, dest_path, dest_name);
901

902
    TRACE("Duplicating file %s to %s\n",debugstr_w(file->TargetPath),
903 904
                    debugstr_w(dest)); 

905 906
    CreateDirectoryW(dest_path, NULL);

907 908
    if (strcmpW(file->TargetPath,dest))
        rc = !CopyFileW(file->TargetPath,dest,TRUE);
909 910
    else
        rc = ERROR_SUCCESS;
911

912
    if (rc != ERROR_SUCCESS)
913
        ERR("Failed to copy file %s -> %s, last error %d\n",
914
            debugstr_w(file->TargetPath), debugstr_w(dest_path), GetLastError());
915

916
    FIXME("We should track these duplicate files as well\n");   
917

918 919
    msi_free(dest_path);
    msi_free(dest);
920 921

    msi_file_update_ui(package, file, szDuplicateFiles);
922

923 924
    return ERROR_SUCCESS;
}
925

926 927 928 929 930 931 932
UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
{
    UINT rc;
    MSIQUERY * view;
    static const WCHAR ExecSeqQuery[] =
        {'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
         '`','D','u','p','l','i','c','a','t','e','F','i','l','e','`',0};
933

934 935 936
    rc = MSI_DatabaseOpenViewW(package->db, ExecSeqQuery, &view);
    if (rc != ERROR_SUCCESS)
        return ERROR_SUCCESS;
937

938
    rc = MSI_IterateRecords(view, NULL, ITERATE_DuplicateFiles, package);
939
    msiobj_release(&view->hdr);
940

941 942
    return rc;
}
943

944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
/* compares the version of a file read from the filesystem and
 * the version specified in the File table
 */
static int msi_compare_file_version( MSIFILE *file )
{
    WCHAR version[MAX_PATH];
    DWORD size;
    UINT r;

    size = MAX_PATH;
    version[0] = '\0';
    r = MsiGetFileVersionW( file->TargetPath, version, &size, NULL, NULL );
    if ( r != ERROR_SUCCESS )
        return 0;

    return lstrcmpW( version, file->Version );
}

962 963 964 965 966 967
UINT ACTION_RemoveFiles( MSIPACKAGE *package )
{
    MSIFILE *file;

    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
    {
968 969 970
        MSIRECORD *uirow;
        LPWSTR uipath, p;

971 972 973 974 975 976 977 978 979 980 981
        if ( !file->Component )
            continue;
        if ( file->Component->Installed == INSTALLSTATE_LOCAL )
            continue;

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

        if ( file->state != msifs_present )
            continue;

982 983 984 985 986 987
        /* only remove a file if the version to be installed
         * is strictly newer than the old file
         */
        if ( msi_compare_file_version( file ) >= 0 )
            continue;

988 989 990 991
        TRACE("removing %s\n", debugstr_w(file->File) );
        if ( !DeleteFileW( file->TargetPath ) )
            ERR("failed to delete %s\n",  debugstr_w(file->TargetPath) );
        file->state = msifs_missing;
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004

        /* the UI chunk */
        uirow = MSI_CreateRecord( 9 );
        MSI_RecordSetStringW( uirow, 1, file->FileName );
        uipath = strdupW( file->TargetPath );
        p = strrchrW(uipath,'\\');
        if (p)
            p[1]=0;
        MSI_RecordSetStringW( uirow, 9, uipath);
        ui_actiondata( package, szRemoveFiles, uirow);
        msiobj_release( &uirow->hdr );
        msi_free( uipath );
        /* FIXME: call ui_progress here? */
1005 1006 1007 1008
    }

    return ERROR_SUCCESS;
}