Example #1
0
 private static string GetTargetDirectory(string rootDirectory, MsiDirectory relativePath)
 {
     LessIO.Path fullPath = LessIO.Path.Combine(rootDirectory, relativePath.GetPath());
     if (!FileSystem.Exists(fullPath))
     {
         FileSystem.CreateDirectory(fullPath);
     }
     return(fullPath.PathString);
 }
Example #2
0
        public static void ExtractCabFromPackage(Path destCabPath, string cabName, Database inputDatabase, LessIO.Path msiPath)
        {
            //NOTE: checking inputDatabase.TableExists("_Streams") here is not accurate. It reports that it doesn't exist at times when it is perfectly queryable. So we actually try it and look for a specific exception:
            //NOTE: we do want to tryStreams. It is more reliable when available and AFAICT it always /should/ be there according to the docs but isn't.
            const bool tryStreams = true;

            if (tryStreams)
            {
                try
                {
                    ExtractCabFromPackageTraditionalWay(destCabPath, cabName, inputDatabase);
                    // as long as TraditionalWay didn't throw, we'll leave it at that...
                    return;
                }
                catch (Exception e)
                {
                    Debug.WriteLine("ExtractCabFromPackageTraditionalWay Exception: {0}", e);
                    // According to issue #78 (https://github.com/activescott/lessmsi/issues/78), WIX installers sometimes (always?)
                    // don't have _Streams table yet they still install. Since it appears that msi files generally (BUT NOT ALWAYS - see X86 Debuggers And Tools-x86_en-us.msi) will have only one cab file, we'll try to just find it in the sterams and use it instead:
                    Trace.WriteLine("MSI File has no _Streams table. Attempting alternate cab file extraction process...");
                }
            }

            using (var stg = new OleStorageFile(msiPath))
            {
                // MSIs do exist with >1. If we use the ExtractCabFromPackageTraditionalWay (via _Streams table) then it handles that. If we are using this fallback approach, multiple cabs is a bad sign!
                Debug.Assert(CountCabs(stg) == 1, string.Format("Expected 1 cab, but found {0}.", CountCabs(stg)));
                foreach (var strm in stg.GetStreams())
                {
                    using (var bits = strm.GetStream(FileMode.Open, FileAccess.Read))
                    {
                        if (OleStorageFile.IsCabStream(bits))
                        {
                            Trace.WriteLine(String.Format("Found CAB bits in stream. Assuming it is for cab {0}.", destCabPath));
                            Func <byte[], int> streamReader = destBuffer => bits.Read(destBuffer, 0, destBuffer.Length);
                            CopyStreamToFile(streamReader, destCabPath);
                        }
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// Extracts the compressed files from the specified MSI file to the specified output directory.
        /// If specified, the list of <paramref name="filesToExtract"/> objects are the only files extracted.
        /// </summary>
        /// <param name="filesToExtract">The files to extract or null or empty to extract all files.</param>
        /// <param name="progressCallback">Will be called during during the operation with progress information, and upon completion. The argument will be of type <see cref="ExtractionProgress"/>.</param>
        public static void ExtractFiles(Path msi, string outputDir, MsiFile[] filesToExtract, AsyncCallback progressCallback)
        {
            if (msi.IsEmpty)
            {
                throw new ArgumentNullException("msi");
            }
            if (string.IsNullOrEmpty(outputDir))
            {
                throw new ArgumentNullException("outputDir");
            }

            int filesExtractedSoFar = 0;
            //Refrence on Embedding files: https://msdn.microsoft.com/en-us/library/aa369279.aspx
            ExtractionProgress progress = null;
            Database           msidb    = new Database(msi.PathString, OpenDatabase.ReadOnly);

            try
            {
                if (filesToExtract == null || filesToExtract.Length < 1)
                {
                    filesToExtract = MsiFile.CreateMsiFilesFromMSI(msidb);
                }

                progress = new ExtractionProgress(progressCallback, filesToExtract.Length);

                if (!FileSystem.Exists(msi))
                {
                    Trace.WriteLine("File \'" + msi + "\' not found.");
                    progress.ReportProgress(ExtractionActivity.Complete, "", filesExtractedSoFar);
                    return;
                }

                progress.ReportProgress(ExtractionActivity.Initializing, "", filesExtractedSoFar);
                FileSystem.CreateDirectory(new Path(outputDir));

                //map short file names to the msi file entry
                var fileEntryMap = new Dictionary <string, MsiFile>(filesToExtract.Length, StringComparer.InvariantCulture);
                foreach (var fileEntry in filesToExtract)
                {
                    MsiFile existingFile = null;
                    if (fileEntryMap.TryGetValue(fileEntry.File, out existingFile))
                    {                   //NOTE: This used to be triggered when we ignored case of file, but now we don't ignore case so this is unlikely to occur.
                        // Differing only by case is not compliant with the msi specification but some installers do it (e.g. python, see issue 28).
                        Debug.Print("!!Found duplicate file using key {0}. The existing key was {1}", fileEntry.File, existingFile.File);
                    }
                    else
                    {
                        fileEntryMap.Add(fileEntry.File, fileEntry);
                    }
                }

                Debug.Assert(fileEntryMap.Count == filesToExtract.Length, "Duplicate files must have caused some files to not be in the map.");

                var cabInfos         = CabsFromMsiToDisk(msi, msidb, outputDir);
                var cabDecompressors = MergeCabs(cabInfos);
                try
                {
                    foreach (MSCabinet decompressor in cabDecompressors)
                    {
                        foreach (var compressedFile in decompressor.GetFiles())
                        {
                            // if the user didn't select this in the UI for extraction, skip it.
                            if (!fileEntryMap.ContainsKey(compressedFile.Filename))
                            {
                                continue;
                            }
                            var entry = fileEntryMap[compressedFile.Filename];
                            progress.ReportProgress(ExtractionActivity.ExtractingFile, entry.LongFileName, filesExtractedSoFar);
                            string      targetDirectoryForFile = GetTargetDirectory(outputDir, entry.Directory);
                            LessIO.Path destName = LessIO.Path.Combine(targetDirectoryForFile, entry.LongFileName);
                            if (FileSystem.Exists(destName))
                            {
                                Debug.Fail("output file already exists. We'll make it unique, but this is probably a strange msi or a bug in this program.");
                                //make unique
                                // ReSharper disable HeuristicUnreachableCode
                                Trace.WriteLine(string.Concat("Duplicate file found \'", destName, "\'"));
                                int  duplicateCount = 0;
                                Path uniqueName;
                                do
                                {
                                    uniqueName = new Path(destName + "." + "duplicate" + ++duplicateCount);
                                } while (FileSystem.Exists(uniqueName));
                                destName = uniqueName;
                                // ReSharper restore HeuristicUnreachableCode
                            }
                            Trace.WriteLine(string.Concat("Extracting File \'", compressedFile.Filename, "\' to \'", destName, "\'"));
                            compressedFile.ExtractTo(destName.PathString);
                            filesExtractedSoFar++;
                        }
                    }
                }
                finally
                {               //cleanup the decompressors allocated in MergeCabs
                    foreach (var decomp in cabDecompressors)
                    {
                        decomp.Close(false);
                        DeleteFileForcefully(new Path(decomp.LocalFilePath));
                    }
                }
            }
            finally
            {
                if (msidb != null)
                {
                    msidb.Close();
                }
                if (progress != null)
                {
                    progress.ReportProgress(ExtractionActivity.Complete, "", filesExtractedSoFar);
                }
            }
        }