sync msi to wine 1.1.31
[reactos.git] / reactos / dll / win32 / msi / files.c
index 81c5ac4..d9cc0ff 100644 (file)
 #include "fdi.h"
 #include "msi.h"
 #include "msidefs.h"
-#include "msvcrt/fcntl.h"
 #include "msipriv.h"
 #include "winuser.h"
 #include "winreg.h"
 #include "shlwapi.h"
 #include "wine/unicode.h"
-#include "action.h"
 
 WINE_DEFAULT_DEBUG_CHANNEL(msi);
 
@@ -56,133 +54,6 @@ 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};
-
-extern LPCWSTR msi_download_file( LPCWSTR szUrl, LPWSTR filename );
-
-/*
- * 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);
-
-    track_tempfile(package,strrchrW(source,'\\'), source);
-    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);
-    TRACE("wrote %li bytes to %s\n",write,debugstr_w(source));
-end:
-    msi_free(data);
-    return rc;
-}
-
-
-/* Support functions for FDI functions */
-typedef struct
-{
-    MSIPACKAGE* package;
-    LPCSTR cab_path;
-} CabData;
-
-static void * cabinet_alloc(ULONG cb)
-{
-    return msi_alloc(cb);
-}
-
-static void cabinet_free(void *pv)
-{
-    msi_free(pv);
-}
-
-static INT_PTR cabinet_open(char *pszFile, int oflag, int pmode)
-{
-    HANDLE handle;
-    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;
-    handle = CreateFileA( pszFile, dwAccess, dwShareMode, NULL, 
-                          dwCreateDisposition, 0, NULL );
-    if (handle == INVALID_HANDLE_VALUE)
-        return 0;
-    return (INT_PTR) handle;
-}
-
-static UINT cabinet_read(INT_PTR hf, void *pv, UINT cb)
-{
-    HANDLE handle = (HANDLE) hf;
-    DWORD dwRead;
-    if (ReadFile(handle, pv, cb, &dwRead, NULL))
-        return dwRead;
-    return 0;
-}
-
-static UINT cabinet_write(INT_PTR hf, void *pv, UINT cb)
-{
-    HANDLE handle = (HANDLE) hf;
-    DWORD dwWritten;
-    if (WriteFile(handle, pv, cb, &dwWritten, NULL))
-        return dwWritten;
-    return 0;
-}
-
-static int cabinet_close(INT_PTR hf)
-{
-    HANDLE handle = (HANDLE) hf;
-    return CloseHandle(handle) ? 0 : -1;
-}
-
-static long cabinet_seek(INT_PTR hf, long dist, int seektype)
-{
-    HANDLE handle = (HANDLE) hf;
-    /* flags are compatible and so are passed straight through */
-    return SetFilePointer(handle, dist, NULL, seektype);
-}
-
 static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *action )
 {
     MSIRECORD *uirow;
@@ -203,391 +74,179 @@ static void msi_file_update_ui( MSIPACKAGE *package, MSIFILE *f, const WCHAR *ac
     ui_progress( package, 2, f->FileSize, 0, 0);
 }
 
-static INT_PTR cabinet_notify(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
+/* 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)
 {
-    switch (fdint)
-    {
-    case fdintCOPY_FILE:
-    {
-        CabData *data = (CabData*) pfdin->pv;
-        HANDLE handle;
-        LPWSTR file;
-        MSIFILE *f;
-        DWORD attrs;
-
-        file = strdupAtoW(pfdin->psz1);
-        f = get_loaded_file(data->package, file);
-        msi_free(file);
-
-        if (!f)
-        {
-            WARN("unknown file in cabinet (%s)\n",debugstr_a(pfdin->psz1));
-            return 0;
-        }
-
-        if (f->state != msifs_missing && f->state != msifs_overwrite)
-        {
-            TRACE("Skipping extraction of %s\n",debugstr_a(pfdin->psz1));
-            return 0;
-        }
-
-        msi_file_update_ui( data->package, f, szInstallFiles );
-
-        TRACE("extracting %s\n", debugstr_w(f->TargetPath) );
-
-        attrs = f->Attributes & (FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
-        if (!attrs) attrs = FILE_ATTRIBUTE_NORMAL;
-
-        handle = CreateFileW( f->TargetPath, GENERIC_READ | GENERIC_WRITE, 0,
-                              NULL, CREATE_ALWAYS, attrs, NULL );
-        if ( handle == INVALID_HANDLE_VALUE )
-        {
-            ERR("failed to create %s (error %ld)\n",
-                debugstr_w( f->TargetPath ), GetLastError() );
-            return 0;
-        }
+    WCHAR version[MAX_PATH];
+    DWORD size;
+    UINT r;
 
-        f->state = msifs_installed;
-        return (INT_PTR) handle;
-    }
-    case fdintCLOSE_FILE_INFO:
-    {
-        FILETIME ft;
-        FILETIME ftLocal;
-        HANDLE handle = (HANDLE) pfdin->hf;
-
-        if (!DosDateTimeToFileTime(pfdin->date, pfdin->time, &ft))
-            return -1;
-        if (!LocalFileTimeToFileTime(&ft, &ftLocal))
-            return -1;
-        if (!SetFileTime(handle, &ftLocal, 0, &ftLocal))
-            return -1;
-        CloseHandle(handle);
-        return 1;
-    }
-    default:
+    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);
 }
 
-/***********************************************************************
- *            extract_cabinet_file
- *
- * Extract files from a cab file.
- */
-static BOOL extract_cabinet_file(MSIPACKAGE* package, LPCWSTR source, 
-                                 LPCWSTR path)
+static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
+                            MSIFILE** file)
 {
-    HFDI hfdi;
-    ERF erf;
-    BOOL ret;
-    char *cabinet;
-    char *cab_path;
-    static CHAR empty[] = "";
-    CabData data;
-
-    TRACE("Extracting %s to %s\n",debugstr_w(source), debugstr_w(path));
-
-    hfdi = FDICreate(cabinet_alloc,
-                     cabinet_free,
-                     cabinet_open,
-                     cabinet_read,
-                     cabinet_write,
-                     cabinet_close,
-                     cabinet_seek,
-                     0,
-                     &erf);
-    if (!hfdi)
-    {
-        ERR("FDICreate failed\n");
-        return FALSE;
-    }
-
-    if (!(cabinet = strdupWtoA( source )))
-    {
-        FDIDestroy(hfdi);
-        return FALSE;
-    }
-    if (!(cab_path = strdupWtoA( path )))
+    LIST_FOR_EACH_ENTRY( *file, &package->files, MSIFILE, entry )
     {
-        FDIDestroy(hfdi);
-        msi_free(cabinet);
-        return FALSE;
+        if (lstrcmpW( file_key, (*file)->File )==0)
+        {
+            if ((*file)->state >= msifs_overwrite)
+                return ERROR_SUCCESS;
+            else
+                return ERROR_FILE_NOT_FOUND;
+        }
     }
 
-    data.package = package;
-    data.cab_path = cab_path;
-
-    ret = FDICopy(hfdi, cabinet, empty, 0, cabinet_notify, NULL, &data);
-
-    if (!ret)
-        ERR("FDICopy failed\n");
-
-    FDIDestroy(hfdi);
-
-    msi_free(cabinet);
-    msi_free(cab_path);
-
-    return ret;
+    return ERROR_FUNCTION_FAILED;
 }
 
-static VOID set_file_source(MSIPACKAGE* package, MSIFILE* file, MSICOMPONENT*
-        comp, LPCWSTR path)
+static void schedule_install_files(MSIPACKAGE *package)
 {
-    if (!file->IsCompressed)
+    MSIFILE *file;
+
+    LIST_FOR_EACH_ENTRY(file, &package->files, MSIFILE, entry)
     {
-        LPWSTR p, path;
-        p = resolve_folder(package, comp->Directory, TRUE, FALSE, NULL);
-        path = build_directory_name(2, p, file->ShortName);
-        if (INVALID_FILE_ATTRIBUTES == GetFileAttributesW( path ))
+        if (!ACTION_VerifyComponentForAction(file->Component, INSTALLSTATE_LOCAL))
         {
-            msi_free(path);
-            path = build_directory_name(2, p, file->LongName);
+            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;
         }
-        file->SourcePath = path;
-        msi_free(p);
     }
-    else
-        file->SourcePath = build_directory_name(2, path, file->File);
 }
 
-struct media_info {
-    UINT last_sequence; 
-    LPWSTR last_volume;
-    LPWSTR last_path;
-    DWORD count;
-    WCHAR source[MAX_PATH];
-};
-
-static struct media_info *create_media_info( void )
+static UINT copy_file(MSIFILE *file, LPWSTR source)
 {
-    struct media_info *mi;
+    BOOL ret;
 
-    mi = msi_alloc( sizeof *mi  );
-    if (mi)
-    {
-        mi->last_sequence = 0; 
-        mi->last_volume = NULL;
-        mi->last_path = NULL;
-        mi->count = 0;
-        mi->source[0] = 0;
-    }
+    ret = CopyFileW(source, file->TargetPath, FALSE);
+    if (!ret)
+        return GetLastError();
 
-    return mi;
-}
+    SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
 
-static void free_media_info( struct media_info *mi )
-{
-    msi_free( mi->last_path );
-    msi_free( mi );
+    file->state = msifs_installed;
+    return ERROR_SUCCESS;
 }
 
-/* downloads a remote cabinet and extracts it if it exists */
-static UINT msi_extract_remote_cabinet( MSIPACKAGE *package, struct media_info *mi )
+static UINT copy_install_file(MSIPACKAGE *package, MSIFILE *file, LPWSTR source)
 {
-    FDICABINETINFO cabinfo;
-    WCHAR temppath[MAX_PATH];
-    WCHAR src[MAX_PATH];
-    LPSTR cabpath;
-    LPCWSTR file;
-    LPWSTR ptr;
-    HFDI hfdi;
-    ERF erf;
-    int hf;
-
-    /* the URL is the path prefix of the package URL and the filename
-     * of the file to download
-     */
-    ptr = strrchrW(package->PackagePath, '/');
-    lstrcpynW(src, package->PackagePath, ptr - package->PackagePath + 2);
-    ptr = strrchrW(mi->source, '\\');
-    lstrcatW(src, ptr + 1);
-
-    file = msi_download_file( src, temppath );
-    lstrcpyW(mi->source, file);
-
-    /* check if the remote cabinet still exists, ignore if it doesn't */
-    hfdi = FDICreate(cabinet_alloc, cabinet_free, cabinet_open, cabinet_read,
-                     cabinet_write, cabinet_close, cabinet_seek, 0, &erf);
-    if (!hfdi)
-    {
-        ERR("FDICreate failed\n");
-        return ERROR_FUNCTION_FAILED;
-    }
-
-    cabpath = strdupWtoA(mi->source);
-    hf = cabinet_open(cabpath, _O_RDONLY, 0);
-    if (!FDIIsCabinet(hfdi, hf, &cabinfo))
-    {
-        WARN("Remote cabinet %s does not exist.\n", debugstr_w(mi->source));
-        msi_free(cabpath);
-        return ERROR_SUCCESS;
-    }
+    UINT gle;
 
-    msi_free(cabpath);
-    return !extract_cabinet_file(package, mi->source, mi->last_path);
-}
+    TRACE("Copying %s to %s\n", debugstr_w(source),
+          debugstr_w(file->TargetPath));
 
-static UINT ready_media_for_file( MSIPACKAGE *package, struct media_info *mi,
-                                  MSIFILE *file )
-{
-    UINT rc = ERROR_SUCCESS;
-    MSIRECORD * row = 0;
-    static const WCHAR ExecSeqQuery[] =
-        {'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',' ','O','R','D','E','R',' ','B','Y',' ',
-         '`','L','a','s','t','S','e','q','u','e','n','c','e','`',0};
-    LPCWSTR cab, volume;
-    DWORD sz;
-    INT seq;
-    LPCWSTR prompt;
-    MSICOMPONENT *comp = file->Component;
+    gle = copy_file(file, source);
+    if (gle == ERROR_SUCCESS)
+        return gle;
 
-    if (file->Sequence <= mi->last_sequence)
+    if (gle == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
     {
-        set_file_source(package,file,comp,mi->last_path);
-        TRACE("Media already ready (%u, %u)\n",file->Sequence,mi->last_sequence);
+        TRACE("overwriting existing file\n");
         return ERROR_SUCCESS;
     }
-
-    mi->count ++;
-    row = MSI_QueryGetRecord(package->db, ExecSeqQuery, file->Sequence);
-    if (!row)
+    else if (gle == ERROR_ACCESS_DENIED)
     {
-        TRACE("Unable to query row\n");
-        return ERROR_FUNCTION_FAILED;
-    }
-
-    volume = MSI_RecordGetString(row, 5);
-    prompt = MSI_RecordGetString(row, 3);
+        SetFileAttributesW(file->TargetPath, FILE_ATTRIBUTE_NORMAL);
 
-    msi_free(mi->last_path);
-    mi->last_path = NULL;
-
-    if (!file->IsCompressed)
-    {
-        mi->last_path = resolve_folder(package, comp->Directory, TRUE, FALSE, NULL);
-        set_file_source(package,file,comp,mi->last_path);
-
-        MsiSourceListAddMediaDiskW(package->ProductCode, NULL, 
-            MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count, volume,
-            prompt);
-
-        MsiSourceListSetInfoW(package->ProductCode, NULL, 
-                MSIINSTALLCONTEXT_USERMANAGED, 
-                MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
-                INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
-        msiobj_release(&row->hdr);
-        return rc;
+        gle = copy_file(file, source);
+        TRACE("Overwriting existing file: %d\n", gle);
     }
-
-    seq = MSI_RecordGetInteger(row,2);
-    mi->last_sequence = seq;
-
-    cab = MSI_RecordGetString(row,4);
-    if (cab)
+    if (gle == ERROR_SHARING_VIOLATION)
     {
-        TRACE("Source is CAB %s\n",debugstr_w(cab));
-        /* the stream does not contain the # character */
-        if (cab[0]=='#')
-        {
-            LPWSTR path;
-
-            writeout_cabinet_stream(package,&cab[1],mi->source);
-            mi->last_path = strdupW(mi->source);
-            *(strrchrW(mi->last_path,'\\')+1)=0;
+        static const WCHAR msiW[] = {'m','s','i',0};
+        static const WCHAR slashW[] = {'\\',0};
+        WCHAR tmpfileW[MAX_PATH], *pathW, *p;
+        DWORD len;
 
-            path = msi_dup_property( package, cszSourceDir );
+        TRACE("file in use, scheduling rename operation\n");
 
-            MsiSourceListAddMediaDiskW(package->ProductCode, NULL, 
-                MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count,
-                volume, prompt);
+        GetTempFileNameW(slashW, msiW, 0, tmpfileW);
+        len = strlenW(file->TargetPath) + strlenW(tmpfileW) + 1;
+        if (!(pathW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR))))
+            return ERROR_OUTOFMEMORY;
 
-            MsiSourceListSetInfoW(package->ProductCode, NULL,
-                MSIINSTALLCONTEXT_USERMANAGED,
-                MSICODE_PRODUCT|MSISOURCETYPE_NETWORK,
-                INSTALLPROPERTY_LASTUSEDSOURCEW, path);
+        strcpyW(pathW, file->TargetPath);
+        if ((p = strrchrW(pathW, '\\'))) *p = 0;
+        strcatW(pathW, tmpfileW);
 
-            msi_free(path);
-        }
-        else
+        if (CopyFileW(source, pathW, FALSE) &&
+            MoveFileExW(file->TargetPath, NULL, MOVEFILE_DELAY_UNTIL_REBOOT) &&
+            MoveFileExW(pathW, file->TargetPath, MOVEFILE_DELAY_UNTIL_REBOOT))
         {
-            sz = MAX_PATH;
-            mi->last_path = msi_alloc(MAX_PATH*sizeof(WCHAR));
-            if (MSI_GetPropertyW(package, cszSourceDir, mi->source, &sz))
-            {
-                ERR("No Source dir defined\n");
-                rc = ERROR_FUNCTION_FAILED;
-            }
-            else
-            {
-                strcpyW(mi->last_path,mi->source);
-                strcatW(mi->source,cab);
-
-                MsiSourceListSetInfoW(package->ProductCode, NULL,
-                            MSIINSTALLCONTEXT_USERMANAGED,
-                            MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
-                            INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
-
-                /* extract the cab file into a folder in the temp folder */
-                sz = MAX_PATH;
-                if (MSI_GetPropertyW(package, cszTempFolder,mi->last_path, &sz) 
-                                    != ERROR_SUCCESS)
-                    GetTempPathW(MAX_PATH,mi->last_path);
-            }
-        }
-
-        /* only download the remote cabinet file if a local copy does not exist */
-        if (GetFileAttributesW(mi->source) == INVALID_FILE_ATTRIBUTES &&
-            UrlIsW(package->PackagePath, URLIS_URL))
-        {
-            rc = msi_extract_remote_cabinet(package, mi);
+            file->state = msifs_installed;
+            package->need_reboot = 1;
+            gle = ERROR_SUCCESS;
         }
         else
         {
-            rc = !extract_cabinet_file(package, mi->source, mi->last_path);
+            gle = GetLastError();
+            WARN("failed to schedule rename operation: %d)\n", gle);
         }
+        HeapFree(GetProcessHeap(), 0, pathW);
     }
-    else
-    {
-        sz = MAX_PATH;
-        mi->last_path = msi_alloc(MAX_PATH*sizeof(WCHAR));
-        MSI_GetPropertyW(package,cszSourceDir,mi->source,&sz);
-        strcpyW(mi->last_path,mi->source);
-
-        MsiSourceListSetInfoW(package->ProductCode, NULL,
-                    MSIINSTALLCONTEXT_USERMANAGED,
-                    MSICODE_PRODUCT|MSISOURCETYPE_MEDIA,
-                    INSTALLPROPERTY_LASTUSEDSOURCEW, mi->last_path);
-    }
-    set_file_source(package, file, comp, mi->last_path);
 
-    MsiSourceListAddMediaDiskW(package->ProductCode, NULL,
-            MSIINSTALLCONTEXT_USERMANAGED, MSICODE_PRODUCT, mi->count, volume,
-            prompt);
+    return gle;
+}
+
+static BOOL check_dest_hash_matches(MSIFILE *file)
+{
+    MSIFILEHASHINFO hash;
+    UINT r;
+
+    if (!file->hash.dwFileHashInfoSize)
+        return FALSE;
 
-    msiobj_release(&row->hdr);
+    hash.dwFileHashInfoSize = sizeof(MSIFILEHASHINFO);
+    r = MsiGetFileHashW(file->TargetPath, 0, &hash);
+    if (r != ERROR_SUCCESS)
+        return FALSE;
 
-    return rc;
+    return !memcmp(&hash, &file->hash, sizeof(MSIFILEHASHINFO));
 }
 
-static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key, 
-                            MSIFILE** file)
+static BOOL installfiles_cb(MSIPACKAGE *package, LPCWSTR file, DWORD action,
+                            LPWSTR *path, DWORD *attrs, PVOID user)
 {
-    LIST_FOR_EACH_ENTRY( *file, &package->files, MSIFILE, entry )
+    static MSIFILE *f = NULL;
+
+    if (action == MSICABEXTRACT_BEGINEXTRACT)
     {
-        if (lstrcmpW( file_key, (*file)->File )==0)
+        f = get_loaded_file(package, file);
+        if (!f)
         {
-            if ((*file)->state >= msifs_overwrite)
-                return ERROR_SUCCESS;
-            else
-                return ERROR_FILE_NOT_FOUND;
+            WARN("unknown file in cabinet (%s)\n", debugstr_w(file));
+            return FALSE;
         }
+
+        if (f->state != msifs_missing && f->state != msifs_overwrite)
+        {
+            TRACE("Skipping extraction of %s\n", debugstr_w(file));
+            return FALSE;
+        }
+
+        msi_file_update_ui(package, f, szInstallFiles);
+
+        *path = strdupW(f->TargetPath);
+        *attrs = f->Attributes;
+    }
+    else if (action == MSICABEXTRACT_FILEEXTRACTED)
+    {
+        f->state = msifs_installed;
+        f = NULL;
     }
 
-    return ERROR_FUNCTION_FAILED;
+    return TRUE;
 }
 
 /*
@@ -599,38 +258,14 @@ static UINT get_file_target(MSIPACKAGE *package, LPCWSTR file_key,
  */
 UINT ACTION_InstallFiles(MSIPACKAGE *package)
 {
-    struct media_info *mi;
+    MSIMEDIAINFO *mi;
     UINT rc = ERROR_SUCCESS;
-    LPWSTR ptr;
     MSIFILE *file;
 
     /* increment progress bar each time action data is sent */
     ui_progress(package,1,1,0,0);
 
-    /* handle the keys for the SourceList */
-    ptr = strrchrW(package->PackagePath,'\\');
-    if (ptr)
-    {
-        ptr ++;
-        MsiSourceListSetInfoW(package->ProductCode, NULL,
-                MSIINSTALLCONTEXT_USERMANAGED,
-                MSICODE_PRODUCT,
-                INSTALLPROPERTY_PACKAGENAMEW, ptr);
-    }
-    /* FIXME("Write DiskPrompt\n"); */
-    
-    /* Pass 1 */
-    LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
-    {
-        if (!ACTION_VerifyComponentForAction( file->Component, INSTALLSTATE_LOCAL ))
-        {
-            ui_progress(package,2,file->FileSize,0,0);
-            TRACE("File %s is not scheduled for install\n",
-                   debugstr_w(file->File));
-
-            file->state = msifs_skipped;
-        }
-    }
+    schedule_install_files(package);
 
     /*
      * Despite MSDN specifying that the CreateFolders action
@@ -640,75 +275,88 @@ UINT ACTION_InstallFiles(MSIPACKAGE *package)
      */
     msi_create_component_directories( package );
 
-    mi = create_media_info();
+    mi = msi_alloc_zero( sizeof(MSIMEDIAINFO) );
 
-    /* Pass 2 */
     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
     {
-        if (file->state != msifs_missing && file->state != msifs_overwrite)
+        if (file->state != msifs_missing && !mi->is_continuous && file->state != msifs_overwrite)
             continue;
 
-        TRACE("Pass 2: %s\n",debugstr_w(file->File));
-
-        rc = ready_media_for_file( package, mi, file );
-        if (rc != ERROR_SUCCESS)
+        if (check_dest_hash_matches(file))
         {
-            ERR("Unable to ready media\n");
-            rc = ERROR_FUNCTION_FAILED;
-            break;
-        }
-
-        TRACE("file paths %s to %s\n",debugstr_w(file->SourcePath),
-              debugstr_w(file->TargetPath));
-
-        if (file->state != msifs_missing && file->state != msifs_overwrite)
+            TRACE("File hashes match, not overwriting\n");
             continue;
+        }
 
-        /* compressed files are extracted in ready_media_for_file */
-        if (file->IsCompressed)
+        if (MsiGetFileVersionW(file->TargetPath, NULL, NULL, NULL, NULL) == ERROR_SUCCESS &&
+            msi_compare_file_version(file) >= 0)
         {
-            if (INVALID_FILE_ATTRIBUTES == GetFileAttributesW(file->TargetPath))
-                ERR("compressed file wasn't extracted (%s)\n",
-                    debugstr_w(file->TargetPath));
+            TRACE("Destination file version greater, not overwriting\n");
             continue;
         }
 
-        rc = CopyFileW(file->SourcePath,file->TargetPath,FALSE);
-        if (!rc)
+        if (file->Sequence > mi->last_sequence || mi->is_continuous ||
+            (file->IsCompressed && !mi->is_extracted))
         {
-            rc = GetLastError();
-            ERR("Unable to copy file (%s -> %s) (error %d)\n",
-                debugstr_w(file->SourcePath), debugstr_w(file->TargetPath), rc);
-            if (rc == ERROR_ALREADY_EXISTS && file->state == msifs_overwrite)
+            MSICABDATA data;
+
+            rc = ready_media(package, file, mi);
+            if (rc != ERROR_SUCCESS)
             {
-                rc = 0;
+                ERR("Failed to ready media\n");
+                break;
             }
-            else if (rc == ERROR_FILE_NOT_FOUND)
+
+            data.mi = mi;
+            data.package = package;
+            data.cb = installfiles_cb;
+            data.user = NULL;
+
+            if (file->IsCompressed &&
+                !msi_cabextract(package, mi, &data))
             {
-                ERR("Source File Not Found!  Continuing\n");
-                rc = 0;
+                ERR("Failed to extract cabinet: %s\n", debugstr_w(mi->cabinet));
+                rc = ERROR_FUNCTION_FAILED;
+                break;
             }
-            else if (file->Attributes & msidbFileAttributesVital)
+        }
+
+        if (!file->IsCompressed)
+        {
+            LPWSTR source = resolve_file_source(package, file);
+
+            TRACE("file paths %s to %s\n", debugstr_w(source),
+                  debugstr_w(file->TargetPath));
+
+            msi_file_update_ui(package, file, szInstallFiles);
+            rc = copy_install_file(package, file, source);
+            if (rc != ERROR_SUCCESS)
             {
-                ERR("Ignoring Error and continuing (nonvital file)...\n");
-                rc = 0;
+                ERR("Failed to copy %s to %s (%d)\n", debugstr_w(source),
+                    debugstr_w(file->TargetPath), rc);
+                rc = ERROR_INSTALL_FAILURE;
+                msi_free(source);
+                break;
             }
+
+            msi_free(source);
         }
-        else
+        else if (file->state != msifs_installed)
         {
-            file->state = msifs_installed;
-            rc = ERROR_SUCCESS;
+            ERR("compressed file wasn't extracted (%s)\n",
+                debugstr_w(file->TargetPath));
+            rc = ERROR_INSTALL_FAILURE;
+            break;
         }
     }
 
-    /* cleanup */
-    free_media_info( mi );
+    msi_free_media_info(mi);
     return rc;
 }
 
 static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
 {
-    MSIPACKAGE *package = (MSIPACKAGE*)param;
+    MSIPACKAGE *package = param;
     WCHAR dest_name[0x100];
     LPWSTR dest_path, dest;
     LPCWSTR file_key, component;
@@ -769,7 +417,7 @@ static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
     {
         LPCWSTR destkey;
         destkey = MSI_RecordGetString(row,5);
-        dest_path = resolve_folder(package, destkey, FALSE,FALSE,NULL);
+        dest_path = resolve_folder(package, destkey, FALSE, FALSE, TRUE, NULL);
         if (!dest_path)
         {
             /* try a Property */
@@ -783,6 +431,7 @@ static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
     }
 
     dest = build_directory_name(2, dest_path, dest_name);
+    create_full_pathW(dest_path);
 
     TRACE("Duplicating file %s to %s\n",debugstr_w(file->TargetPath),
                     debugstr_w(dest)); 
@@ -793,7 +442,7 @@ static UINT ITERATE_DuplicateFiles(MSIRECORD *row, LPVOID param)
         rc = ERROR_SUCCESS;
 
     if (rc != ERROR_SUCCESS)
-        ERR("Failed to copy file %s -> %s, last error %ld\n",
+        ERR("Failed to copy file %s -> %s, last error %d\n",
             debugstr_w(file->TargetPath), debugstr_w(dest_path), GetLastError());
 
     FIXME("We should track these duplicate files as well\n");   
@@ -824,53 +473,134 @@ UINT ACTION_DuplicateFiles(MSIPACKAGE *package)
     return rc;
 }
 
-/* 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 )
+static BOOL verify_comp_for_removal(MSICOMPONENT *comp, UINT install_mode)
 {
-    WCHAR version[MAX_PATH];
+    INSTALLSTATE request = comp->ActionRequest;
+
+    if (request == INSTALLSTATE_UNKNOWN)
+        return FALSE;
+
+    if (install_mode == msidbRemoveFileInstallModeOnInstall &&
+        (request == INSTALLSTATE_LOCAL || request == INSTALLSTATE_SOURCE))
+        return TRUE;
+
+    if (request == INSTALLSTATE_ABSENT)
+    {
+        if (!comp->ComponentId)
+            return FALSE;
+
+        if (install_mode == msidbRemoveFileInstallModeOnRemove)
+            return TRUE;
+    }
+
+    if (install_mode == msidbRemoveFileInstallModeOnBoth)
+        return TRUE;
+
+    return FALSE;
+}
+
+static UINT ITERATE_RemoveFiles(MSIRECORD *row, LPVOID param)
+{
+    MSIPACKAGE *package = param;
+    MSICOMPONENT *comp;
+    LPCWSTR component, filename, dirprop;
+    UINT install_mode;
+    LPWSTR dir = NULL, path = NULL;
     DWORD size;
     UINT r;
 
-    size = MAX_PATH;
-    version[0] = '\0';
-    r = MsiGetFileVersionW( file->TargetPath, version, &size, NULL, NULL );
-    if ( r != ERROR_SUCCESS )
-        return 0;
+    component = MSI_RecordGetString(row, 2);
+    filename = MSI_RecordGetString(row, 3);
+    dirprop = MSI_RecordGetString(row, 4);
+    install_mode = MSI_RecordGetInteger(row, 5);
+
+    comp = get_loaded_component(package, component);
+    if (!comp)
+    {
+        ERR("Invalid component: %s\n", debugstr_w(component));
+        return ERROR_FUNCTION_FAILED;
+    }
+
+    if (!verify_comp_for_removal(comp, install_mode))
+    {
+        TRACE("Skipping removal due to missing conditions\n");
+        comp->Action = comp->Installed;
+        return ERROR_SUCCESS;
+    }
+
+    dir = msi_dup_property(package, dirprop);
+    if (!dir)
+        return ERROR_OUTOFMEMORY;
+
+    size = (filename != NULL) ? lstrlenW(filename) : 0;
+    size += lstrlenW(dir) + 2;
+    path = msi_alloc(size * sizeof(WCHAR));
+    if (!path)
+    {
+        r = ERROR_OUTOFMEMORY;
+        goto done;
+    }
+
+    lstrcpyW(path, dir);
+    PathAddBackslashW(path);
 
-    return lstrcmpW( version, file->Version );
+    if (filename)
+    {
+        lstrcatW(path, filename);
+
+        TRACE("Deleting misc file: %s\n", debugstr_w(path));
+        DeleteFileW(path);
+    }
+    else
+    {
+        TRACE("Removing misc directory: %s\n", debugstr_w(path));
+        RemoveDirectoryW(path);
+    }
+
+done:
+    msi_free(path);
+    msi_free(dir);
+    return ERROR_SUCCESS;
 }
 
 UINT ACTION_RemoveFiles( MSIPACKAGE *package )
 {
+    MSIQUERY *view;
     MSIFILE *file;
+    UINT r;
+
+    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};
+
+    r = MSI_DatabaseOpenViewW(package->db, query, &view);
+    if (r == ERROR_SUCCESS)
+    {
+        MSI_IterateRecords(view, NULL, ITERATE_RemoveFiles, package);
+        msiobj_release(&view->hdr);
+    }
 
     LIST_FOR_EACH_ENTRY( file, &package->files, MSIFILE, entry )
     {
         MSIRECORD *uirow;
         LPWSTR uipath, p;
 
-        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 )
+        if ( file->Component->ActionRequest != INSTALLSTATE_ABSENT ||
+             file->Component->Installed == INSTALLSTATE_SOURCE )
             continue;
 
-        /* only remove a file if the version to be installed
-         * is strictly newer than the old file
+        /* don't remove a file if the old file
+         * is strictly newer than the version to be installed
          */
-        if ( msi_compare_file_version( file ) >= 0 )
+        if ( msi_compare_file_version( file ) < 0 )
             continue;
 
         TRACE("removing %s\n", debugstr_w(file->File) );
         if ( !DeleteFileW( file->TargetPath ) )
-            ERR("failed to delete %s\n",  debugstr_w(file->TargetPath) );
+            TRACE("failed to delete %s\n",  debugstr_w(file->TargetPath));
         file->state = msifs_missing;
 
         /* the UI chunk */