Example #1
0
        Stream BuildStreamOnUnderlyingIStream(
            IStream underlyingIStream,
            FileAccess access,
            StreamInfo parent)
        {
            Stream rawStream = new CFStream(underlyingIStream, access, parent);

            if (null == core.dataSpaceLabel)
            {
                // The stream is not transformed in any data space, add buffering and return
                return(new BufferedStream(rawStream));
            }
            else
            {
                // Pass raw stream to data space manager to get real stream
                return(parentStorage.Root.GetDataSpaceManager().CreateDataSpaceStream(
                           StreamReference, rawStream));
            }
        }
Example #2
0
        public void Test_ADD_LARGE_NUMBER_OF_ITEMS()
        {
            int ITEM_NUMBER = 10000;

            CompoundFile f = null;

            byte[] buffer = Helpers.GetBuffer(10, 0x0A);
            try
            {
                f = new CompoundFile();

                for (int i = 0; i < ITEM_NUMBER; i++)
                {
                    CFStream st = f.RootStorage.AddStream("Stream" + i.ToString());
                    st.Append(buffer);
                }


                if (File.Exists("$ItemsLargeNumber.cfs"))
                {
                    File.Delete("$ItemsLargeNumber.cfs");
                }

                f.Save("$ItemsLargeNumber.cfs");
                f.Close();

                f = new CompoundFile("$ItemsLargeNumber.cfs");
                CFStream cfs = f.RootStorage.GetStream("Stream" + (ITEM_NUMBER / 2).ToString());

                Assert.IsTrue(cfs != null, "Item is null");
                Assert.IsTrue(Helpers.CompareBuffer(cfs.GetData(), buffer), "Items are different");
                f.Close();
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                //if (File.Exists("$ItemsLargeNumber.cfs"))
                //    File.Delete("$ItemsLargeNumber.cfs");
            }
        }
Example #3
0
        /// <summary>
        /// Добавить поток с указанными зашифрованными данными в указанный каталог файла MCDF.
        /// </summary>
        /// <param name="dir">Каталог, в который необходимо добавить поток</param>
        /// <param name="data">Данные в виде массива байт</param>
        /// <param name="diskKey">Ключ</param>
        /// <param name="diskTable">Таблица</param>
        /// <returns></returns>
        private static CFStream AddStream(CFStorage dir, byte[] data, byte[] diskKey, byte[] diskTable)
        {
            // сгенерировать синхропосылку
            byte[] synchroArr = GenerateSynchro();
            byte[] imito;
            // зашифровать данные и получить от них хеш
            Mathdll.CryptData(diskKey, diskTable, synchroArr, ref data, out imito);
            // создать поток с именем, являющимся 16-тиричным представлением массива байт - imito
            CFStream stream = dir.AddStream(ReadKey.BinToHex(imito));

            // создать бефер для объединения данных и синхропосылки
            byte[] buffer = new byte[data.Length + synchroArr.Length];
            Array.Copy(data, 0, buffer, 0, data.Length);
            Array.Copy(synchroArr, 0, buffer, data.Length, synchroArr.Length);
            // записать данные в поток
            stream.SetData(buffer);
            //
            return(stream);
        }
Example #4
0
    static public byte[] SendFile(HttpListenerRequest request)
    {
        Console.WriteLine("Serving request from " + request.RemoteEndPoint.ToString() + " with user agent " + request.UserAgent);

        CompoundFile cf = null;

        try
        {
            cf = new CompoundFile(outFilename, CFSUpdateMode.Update, 0);
        }
        catch (Exception e)
        {
            Console.WriteLine("ERROR: Could not open file " + outFilename);
            Console.WriteLine("Please make sure this file exists and is .docm or .xlsm file or a .doc in the Office 97-2003 format.");
            Console.WriteLine();
            Console.WriteLine(e.Message);
        }

        CFStream streamData = cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT");

        byte[] streamBytes = streamData.GetData();

        string UACpu = "";

        if (request.Headers["UA-CPU"] != null)
        {
            UACpu = request.Headers["UA-CPU"];
        }

        string targetOfficeVersion = UserAgentToOfficeVersion(request.UserAgent, UACpu);

        ReplaceOfficeVersionInVBAProject(streamBytes, targetOfficeVersion);

        cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT").SetData(streamBytes);

        // Commit changes and close file
        cf.Commit();
        cf.Close();

        Console.WriteLine("Serving out file '" + outFilename + "'");
        return(File.ReadAllBytes(outFilename));
    }
Example #5
0
        public void Test_RESIZE_STREAM_NO_TRANSITION()
        {
            CompoundFile cf = null;

            //CFStream st = null;
            byte[] b = Helpers.GetBuffer(1024 * 1024 * 2); //2MB buffer

            cf = new CompoundFile(CFSVersion.Ver_3, CFSConfiguration.Default);
            cf.RootStorage.AddStream("AStream").SetData(b);
            cf.Save("$Test_RESIZE_STREAM.cfs");
            cf.Close();

            cf = new CompoundFile("$Test_RESIZE_STREAM.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            CFStream item = cf.RootStorage.GetStream("AStream");

            item.Resize(item.Size / 2);
            //cf.RootStorage.AddStream("BStream").SetData(b);
            cf.Commit(true);
            cf.Close();
        }
        /// <summary>
        /// Read each entry in the Entry Stream
        /// </summary>
        /// <returns></returns>
        private List <EntryStreamData> ReadEntryStream()
        {
            List <EntryStreamData> entries = new List <EntryStreamData>();
            CFStream entryStream           = _compoundFile.RootStorage.GetStorage(STORAGE_NAME).GetStream(EntryStreamData.STREAM_NAME);

            byte[] data            = entryStream.GetData();
            int    numberOfEntries = data.Length / 8;

            for (int i = 0; i < numberOfEntries; i++)
            {
                EntryStreamData es = new EntryStreamData();
                es.NameIdentifier = BitConverter.ToInt32(data, i * 8);
                es.GUIDIndex      = BitConverter.ToInt16(data, (i * 8) + 4);
                es.PropertyIndex  = BitConverter.ToInt16(data, (i * 8) + 6);
                es.IsString       = es.GUIDIndex % 2 == 1;      //is a string
                es.GUIDIndex      = (short)(es.GUIDIndex >> 1); //cut off the last bit
                entries.Add(es);
            }
            return(entries);
        }
Example #7
0
        /// <summary>
        /// Сформировать HTML разметку из данных, считанных и расшифрованных из файла MCDF.
        /// </summary>
        /// <param name="file">Файл источник (хранилище)</param>
        /// <param name="fileUri">Ссылка на поток в файле</param>
        /// <param name="diskKey">Ключ</param>
        /// <param name="diskTable">Таблица</param>
        /// <returns></returns>
        public static string GetHTML(CompoundFile file, string fileUri, byte[] diskKey, byte[] diskTable)
        {
            string[] uri = fileUri.Split(':');
            if (uri.Length != 2)
            {
                return(null);
            }
            string xslPath;

            switch (uri[0])
            {
            case "svd":
                xslPath = @"styles\svod_style";
                break;

            case "ops":
                xslPath = @"styles\szv_opis_style";
                break;

            case "ind":
                xslPath = @"styles\szv_style";
                break;

            default:
                xslPath = null;
                break;
            }
            if (xslPath == null)
            {
                return(null);
            }
            CFStream xmlStream = GetFileStream(file, uri[1]);
            CFStream xslStream = GetFileStream(file, xslPath);

            byte[] xmlData = DecryptStream(xmlStream, diskKey, diskTable);
            byte[] xslData = DecryptStream(xslStream, diskKey, diskTable);
            string resHTML = XmlData.GetHTML(xmlData, xslData);

            //
            return(resHTML);
        }
Example #8
0
        private void ChangeTreeViewNode(TreeNode newNode)
        {
            if (newNode == null)
            {
                return;
            }

            if (hexEditor.ByteProvider != null && hexEditor.ByteProvider.HasChanges())
            {
                if (MessageBox.Show("Do you want to save pending changes ?", "Save changes", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    hexEditor.ByteProvider.ApplyChanges();
                }
            }

            treeView1.SelectedNode = newNode;

            // The tag property contains the underlying CFItem.
            CFItem target = (CFItem)newNode.Tag;

            if (target.IsStream)
            {
                addStorageStripMenuItem1.Enabled    = false;
                addStreamToolStripMenuItem.Enabled  = false;
                importDataStripMenuItem1.Enabled    = true;
                exportDataToolStripMenuItem.Enabled = true;
            }
            else
            {
                addStorageStripMenuItem1.Enabled    = true;
                addStreamToolStripMenuItem.Enabled  = true;
                importDataStripMenuItem1.Enabled    = false;
                exportDataToolStripMenuItem.Enabled = false;
            }

            propertyGrid1.SelectedObject = newNode.Tag;

            CFStream targetStream = newNode.Tag as CFStream;

            hexEditor.ByteProvider = targetStream != null ? new StreamDataProvider(targetStream) : null;
        }
Example #9
0
        public void Test_DELETE_STREAM_SECTOR_REUSE()
        {
            CompoundFile cf = null;
            CFStream     st = null;

            byte[] b   = Helpers.GetBuffer(1024 * 1024 * 2); //2MB buffer
            byte[] cmp = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 };

            cf = new CompoundFile(CFSVersion.Ver_4, CFSConfiguration.Default);
            st = cf.RootStorage.AddStream("AStream");
            st.Append(b);
            cf.Save("SectorRecycle.cfs");
            cf.Close();


            cf = new CompoundFile("SectorRecycle.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.Delete("AStream");
            cf.Commit(true);
            cf.Close();

            cf = new CompoundFile("SectorRecycle.cfs", CFSUpdateMode.ReadOnly,
                                  CFSConfiguration.Default); //No sector recycle
            st = cf.RootStorage.AddStream("BStream");
            st.Append(Helpers.GetBuffer(1024 * 1024 * 1));
            cf.Save("SectorRecycleLarger.cfs");
            cf.Close();

            Assert.IsFalse((new FileInfo("SectorRecycle.cfs").Length) >=
                           (new FileInfo("SectorRecycleLarger.cfs").Length));

            cf = new CompoundFile("SectorRecycle.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.SectorRecycle);
            st = cf.RootStorage.AddStream("BStream");
            st.Append(Helpers.GetBuffer(1024 * 1024 * 1));
            cf.Save("SectorRecycleSmaller.cfs");
            cf.Close();
            long larger  = (new FileInfo("SectorRecycle.cfs").Length);
            long smaller = (new FileInfo("SectorRecycleSmaller.cfs").Length);

            Assert.IsTrue(larger >= smaller,
                          "Larger size:" + larger.ToString() + " - Smaller size:" + smaller.ToString());
        }
Example #10
0
        public void WriteDocument(string filePath, byte[] wbBytes)
        {
            CompoundFile cf = new CompoundFile();
            //Can be Book or Workbook
            CFStream workbookStream = cf.RootStorage.AddStream("Workbook");

            workbookStream.Write(wbBytes, 0);

            OLEPropertiesContainer dsiContainer = new OLEPropertiesContainer(1252, ContainerType.DocumentSummaryInfo);
            OLEPropertiesContainer siContainer  = new OLEPropertiesContainer(1252, ContainerType.SummaryInfo);

            //TODO [Stealth] Fill these streams with the expected data information, don't leave them empty
            CFStream dsiStream = cf.RootStorage.AddStream("\u0005DocumentSummaryInformation");

            byte[] cfStreamBytes = new byte[]
            {
                0xFE, 0xFF, 0x00, 0x00, 0x06, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xE0, 0x85, 0x9F, 0xF2, 0xF9, 0x4F,
                0x68, 0x10, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 0x30, 0x00, 0x00, 0x00, 0xB0, 0x00, 0x00,
                0x00, 0x07, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
                0x48, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x78,
                0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x9C, 0x00,
                0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0xA8, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xE4, 0x04, 0x00,
                0x00, 0x1E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x57, 0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x20,
                0x55, 0x73, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x57,
                0x69, 0x6E, 0x64, 0x6F, 0x77, 0x73, 0x20, 0x55, 0x73, 0x65, 0x72, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00,
                0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x20, 0x45,
                0x78, 0x63, 0x65, 0x6C, 0x00, 0x40, 0x00, 0x00, 0x00, 0x80, 0x45, 0xA1, 0x6B, 0x7B, 0x93, 0xD6, 0x01,
                0x40, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x32, 0xDA, 0x7C, 0x93, 0xD6, 0x01, 0x03, 0x00, 0x00, 0x00, 0x01,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };

            dsiContainer.Save(dsiStream);

            CFStream siStream = cf.RootStorage.AddStream("\u0005SummaryInformation");

            // siStream.SetData(cfStreamBytes);
            siContainer.Save(siStream);

            cf.Save(filePath);
        }
Example #11
0
 public bool CheckForVBAMacros(string path)
 {
     try {
         CompoundFile cf = new CompoundFile(path);
         // This line throws an exception if there is no _VBA_PROJECT_CUR/VBA/dir stream in the OLE.
         // _VBA_PROJECT_CUR/VBA/dir has to be in an OLE if it contains a VBA macro
         // https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ovba/005bffd7-cd96-4f25-b75f-54433a646b88
         if (path.ToLower().EndsWith(".xls"))
         {
             CFStream dirStream = cf.RootStorage.GetStorage("_VBA_PROJECT_CUR").GetStorage("VBA").GetStream("dir");
         }
         else
         {
             // .doc
             CFStream dirStream = cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("dir");
         }
         return(true);
     } catch (Exception) {
         return(false);
     }
 }
Example #12
0
        public static string GetText(ref CompoundFile cf, CFNode nodo)
        {
            string       a      = Path.GetExtension(nodo.Name).ToLower();
            CFStream     stream = CFUtil.GetStream(ref cf, nodo.Path, nodo.Name);
            MemoryStream input  = MSUtil.CFtoMStream(stream);
            MemoryStream stream2;

            if (a == "")
            {
                stream2 = MSUtil.RemoveTrailingSegment(input, 12);
            }
            else if (MSUtil.IsCompressedWithLW77(stream))
            {
                stream2 = MSUtil.UncompressLW77(input);
            }
            else
            {
                stream2 = MSUtil.RemoveTrailingSegment(input, 8);
            }
            return(new StreamReader(stream2, (a == ".csv") ? Encoding.ASCII : Encoding.Unicode).ReadToEnd());
        }
Example #13
0
 /// <summary>
 /// Indicates if a Compound File stream is an image.
 /// </summary>
 /// <param name="ms"></param>
 /// <returns>0: Unknown - 1: BMP - 2: JPEG</returns>
 public static int VerifyIfImage(CFStream ms)
 {
     byte[] buffer = new byte[20];
     ms.Read(buffer, 0L, 20);
     if (buffer[10] == 0xFF & buffer[11] == 0xD8 & buffer[12] == 0xFF & buffer[13] == 0xE0)
     {
         // It's BMP
         return(1);
     }
     else if (buffer[8] == 0xFF & buffer[9] == 0xD8 & buffer[10] == 0xFF & buffer[11] == 0xE0)
     {
         // It's JPEG
         return(2);
     }
     else if ((buffer[10] == 0x42) & (buffer[11] == 0x4D))
     {
         // It's BMP
         return(1);
     }
     return(0);
 }
Example #14
0
        public void WriteDocument(string filePath, byte[] wbBytes)
        {
            CompoundFile cf             = new CompoundFile();
            CFStream     workbookStream = cf.RootStorage.AddStream("Workbook");

            workbookStream.Write(wbBytes, 0);

            OLEPropertiesContainer dsiContainer = new OLEPropertiesContainer(1252, ContainerType.DocumentSummaryInfo);
            OLEPropertiesContainer siContainer  = new OLEPropertiesContainer(1252, ContainerType.SummaryInfo);

            //TODO [Stealth] Fill these streams with the expected data information, don't leave them empty
            CFStream dsiStream = cf.RootStorage.AddStream("\u0005DocumentSummaryInformation");

            dsiContainer.Save(dsiStream);

            CFStream siStream = cf.RootStorage.AddStream("\u0005SummaryInformation");

            siContainer.Save(siStream);

            cf.Save(filePath);
        }
Example #15
0
        private void importDataStripMenuItem1_Click(object sender, EventArgs e)
        {
            string fileName = String.Empty;

            if (openDataFileDialog.ShowDialog() == DialogResult.OK)
            {
                CFStream s = treeView1.SelectedNode.Tag as CFStream;

                if (s != null)
                {
                    FileStream f    = new FileStream(openDataFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                    byte[]     data = new byte[f.Length];
                    f.Read(data, 0, (int)f.Length);
                    f.Flush();
                    f.Close();
                    s.SetData(data);

                    RefreshTree();
                }
            }
        }
Example #16
0
        public void Test_APPEND_DATA_TO_STREAM()
        {
            MemoryStream ms = new MemoryStream();

            byte[] b  = new byte[] { 0x0, 0x1, 0x2, 0x3 };
            byte[] b2 = new byte[] { 0x4, 0x5, 0x6, 0x7 };

            CompoundFile cf = new CompoundFile();
            CFStream     st = cf.RootStorage.AddStream("MyMiniStream");

            st.SetData(b);
            st.Append(b2);

            cf.Save(ms);
            cf.Close();

            byte[] cmp = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 };
            cf = new CompoundFile(ms);
            byte[] data = cf.RootStorage.GetStream("MyMiniStream").GetData();
            Assert.IsTrue(Helpers.CompareBuffer(cmp, data));
        }
Example #17
0
        private ActionResult GetTemplateFile(HttpRequest request, string filename)
        {
            if (request.Headers.ContainsKey(HeaderNames.UserAgent))
            {
                Console.WriteLine("Serving request from " + request.HttpContext.Connection.RemoteIpAddress + " with user agent " + request.Headers[HeaderNames.UserAgent]);

                CompoundFile cf = null;
                try
                {
                    cf = new CompoundFile(filename, CFSUpdateMode.Update, 0);
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR: Could not open file " + filename);
                    Console.WriteLine("Please make sure this file exists and is .docm or .xlsm file or a .doc in the Office 97-2003 format.");
                    Console.WriteLine();
                    Console.WriteLine(e.Message);
                }

                CFStream streamData  = cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT");
                byte[]   streamBytes = streamData.GetData();

                string targetOfficeVersion = UserAgentToOfficeVersion(request.Headers[HeaderNames.UserAgent]);

                ReplaceOfficeVersionInVBAProject(streamBytes, targetOfficeVersion);

                cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT").SetData(streamBytes);

                // Commit changes and close file
                cf.Commit();
                cf.Close();

                Console.WriteLine("Serving out file '" + filename + "'");
                return(File(System.IO.File.ReadAllBytes(filename), GetMime(filename)));
            }
            else
            {
                return(NotFound());
            }
        }
Example #18
0
    static public byte[] SendFile(HttpListenerRequest request)
    {
        Console.WriteLine("Serving request from " + request.RemoteEndPoint.ToString() + " with user agent " + request.UserAgent);

        CompoundFile cf = new CompoundFile(filename, CFSUpdateMode.Update, 0);

        CFStream streamData = cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT");

        byte[] streamBytes = streamData.GetData();

        string targetOfficeVersion = UserAgentToOfficeVersion(request.UserAgent);

        ReplaceOfficeVersionInVBAProject(streamBytes, targetOfficeVersion);

        cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT").SetData(streamBytes);

        // Commit changes and close file
        cf.Commit();
        cf.Close();

        return(File.ReadAllBytes(filename));
    }
Example #19
0
        protected static void Visit(CFItem item)
        {
            Console.WriteLine(String.Format("Item: {0}. Is Storage: {1}. Is Stream: {2}", item.Name, item.IsStorage, item.IsStream));

            if (item.IsStorage)
            {
                CFStorage storage = (CFStorage)item;
                Console.WriteLine("Visiting Children of storage " + storage.Name);

                storage.VisitEntries(Visit, false);
            }

            if (item.IsStream && item.Name == "ThisWorkbook")
            {
                Console.WriteLine("Parsing ThisWorkbook");

                CFStream stream = (CFStream)item;
                byte[]   data   = stream.GetData();

                File.WriteAllBytes("ThisWorkbook.bin", data);
            }
        }
        public VbaStorage(CompoundFile VbaBinFile)
        {
            this.m_disposable = VbaBinFile;

            // _VBA_PROJECT stream
            var VBAStorage = VbaBinFile.RootStorage.GetStorage("VBA");

            this._VBA_PROJECTStream = ReadVbaProjectStream(VBAStorage);

            // DIR STREAM -------------------------
            CFStream thisWorkbookStream = VBAStorage.GetStream("dir");

            Byte[] compressedData = thisWorkbookStream.GetData();
            Byte[] uncompressed   = XlCompressionAlgorithm.Decompress(compressedData);

            var uncompressedDataReader = new XlBinaryReader(ref uncompressed);

            this.DirStream = new DirStream(uncompressedDataReader);

            // MODULE STREAMS ----------------------------------------
            this._ModuleStreams = new Dictionary <string, ModuleStream>(DirStream.ModulesRecord.Modules.Length);
            this.ModuleStreams  = new ReadOnlyDictionary <string, ModuleStream>(this._ModuleStreams);

            foreach (var module in DirStream.ModulesRecord.Modules)
            {
                var streamName  = module.StreamNameRecord.GetStreamNameAsString();
                var stream      = VBAStorage.GetStream(streamName).GetData();
                var localreader = new XlBinaryReader(ref stream);

                var moduleStream = new ModuleStream(DirStream.InformationRecord, module, localreader);

                this._ModuleStreams.Add(streamName, moduleStream);
            }

            // PROJECT stream
            CFStream ProjectStorage = VbaBinFile.RootStorage.GetStream("PROJECT");

            this.ProjectStream = ReadProjectStream(ProjectStorage, this.DirStream.InformationRecord.CodePageRecord);
        }
Example #21
0
        public void Test_FIX_BUG_GH_15()
        {
            String filename       = "MyFile.dat";
            String storageName    = "MyStorage";
            String streamName     = "MyStream";
            int    BUFFER_SIZE    = 800 * Mb;
            int    iterationCount = 6;
            int    streamCount    = 1;

            CompoundFile compoundFile = new CompoundFile(CFSVersion.Ver_4, CFSConfiguration.Default);
            CFStorage    st           = compoundFile.RootStorage.AddStorage(storageName);

            for (int streamId = 0; streamId < streamCount; ++streamId)
            {
                CFStream sm = st.AddStream(streamName + streamId);
                for (int iteration = 0; iteration < iterationCount; ++iteration)
                {
                    byte b = (byte)(0x0A + iteration);
                    sm.Append(Helpers.GetBuffer(BUFFER_SIZE, b));
                }
            }
            compoundFile.Save(filename);
            compoundFile.Close();

            byte[] readBuffer = new byte[15];
            compoundFile = new CompoundFile(filename);

            byte c = 0x0A;

            for (int i = 0; i < iterationCount; i++)
            {
                compoundFile.RootStorage.GetStorage(storageName).GetStream(streamName + 0.ToString()).Read(readBuffer, ((long)BUFFER_SIZE + ((long)BUFFER_SIZE * i)) - 15, 15);
                Assert.IsTrue(readBuffer.All(by => by == c));
                c++;
            }

            compoundFile.Close();
        }
Example #22
0
        public void Perf_SteamOfLargeFile()
        {
            if (!File.Exists(_fileName))
            {
                Helpers.CreateFile(_fileName);
            }

            using (var cf = new CompoundFile(_fileName))
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                CFStream s = cf.RootStorage.GetStream("Test1");
                sw.Stop();

                var executionTime = sw.ElapsedMilliseconds;
                for (int i = 0; i < sw.ElapsedMilliseconds; i++)
                {
                    _testCounter.Increment();
                }

                Console.WriteLine($"Took {executionTime} seconds");
            }
        }
Example #23
0
        public void Test_WRITE_READ_CFS_VERSION_4_STREAM()
        {
            String filename = "WRITE_COMMIT_READ_CFS_V4.cfs";

            CompoundFile cf = new CompoundFile(CFSVersion.Ver_4, CFSConfiguration.SectorRecycle | CFSConfiguration.EraseFreeSectors);

            CFStorage st = cf.RootStorage.AddStorage("MyStorage");
            CFStream sm = st.AddStream("MyStream");
            byte[] b = Helpers.GetBuffer(227);
            sm.SetData(b);

            cf.Save(filename);
            cf.Close();

            CompoundFile cf2 = new CompoundFile(filename);
            CFStorage st2 = cf2.RootStorage.GetStorage("MyStorage");
            CFStream sm2 = st2.GetStream("MyStream");

            Assert.IsNotNull(sm2);
            Assert.IsTrue(sm2.Size == b.Length);

            cf2.Close();
        }
Example #24
0
        public void Test_WRITE_AND_READ_CFS_VERSION_4()
        {
            String filename = "WRITE_AND_READ_CFS_V4.cfs";

            CompoundFile cf = new CompoundFile(CFSVersion.Ver_4, CFSConfiguration.EraseFreeSectors | CFSConfiguration.SectorRecycle);

            CFStorage st = cf.RootStorage.AddStorage("MyStorage");
            CFStream sm = st.AddStream("MyStream");
            byte[] b = new byte[220];
            sm.SetData(b);

            cf.Save(filename);
            cf.Close();

            CompoundFile cf2 = new CompoundFile(filename);
            CFStorage st2 = cf2.RootStorage.GetStorage("MyStorage");
            CFStream sm2 = st2.GetStream("MyStream");

            Assert.IsNotNull(sm2);
            Assert.IsTrue(sm2.Size == 220);

            cf2.Close();
        }
Example #25
0
        public void Test_FIX_BUG_31()
        {
            CompoundFile cf = new CompoundFile();

            cf.RootStorage.AddStorage("Level_1")
            .AddStream("Level2Stream")
            .SetData(Helpers.GetBuffer(100));

            cf.Save("$Hel1");

            cf.Close();

            CompoundFile cf1 = new CompoundFile("$Hel1");

            try
            {
                CFStream cs = cf1.RootStorage.GetStorage("Level_1").AddStream("Level2Stream");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex.GetType() == typeof(CFDuplicatedItemException));
            }
        }
    public OLECompoundFileInfo(string FileToScan, ref XMLParser raport)
    {
        CompoundFile      file = new CompoundFile(FileToScan);
        CFStream          summaryinformation = file.RootStorage.GetStream("\u0005SummaryInformation");
        PropertySetStream propertySetStream  = summaryinformation.AsOLEProperties();

        raport.InitializeOle();
        for (int i = 0; i < propertySetStream.PropertySet0.NumProperties; i++)
        {
            raport.AddSummInfoAtt(propertySetStream.PropertySet0.PropertyIdentifierAndOffsets.ElementAt(i).PropertyIdentifier, propertySetStream.PropertySet0.Properties[i].Value.ToString());
        }
        CFStream documentSummaryinformation = file.RootStorage.TryGetStream("\u0005DocumentSummaryInformation");

        if (documentSummaryinformation != null)
        {
            PropertySetStream propertyDSSetStream = documentSummaryinformation.AsOLEProperties();
            raport.InitializeDocOle();
            for (int i = 0; i < propertyDSSetStream.PropertySet0.NumProperties; i++)
            {
                raport.AddDocSummInfoAtt(propertyDSSetStream.PropertySet0.PropertyIdentifierAndOffsets.ElementAt(i).PropertyIdentifier, propertyDSSetStream.PropertySet0.Properties[i].Value.ToString());
            }
        }
    }
Example #27
0
        public static byte[] GetStructuredStorageStream(string filePath, string streamName)
        {
            logger.Debug(string.Format("Attempting to read \"{0}\" stream from structured storage file at \"{1}\"",
                                       streamName, filePath));
            int res = StgIsStorageFile(filePath);

            if (res == 0)
            {
                CompoundFile cf          = new CompoundFile(filePath);
                CFStream     foundStream = cf.RootStorage.TryGetStream(streamName);
                if (foundStream != null)
                {
                    byte[] streamData = foundStream.GetData();
                    cf.Close();
                    return(streamData);
                }
                return(null);
            }
            else
            {
                throw new NotSupportedException("File is not a structured storage file");
            }
        }
Example #28
0
        public void Test_DIFAT_CHECK()
        {
            CompoundFile f = null;

            try
            {
                f = new CompoundFile();
                CFStream st = f.RootStorage.AddStream("LargeStream");
                st.Append(Helpers.GetBuffer(20000000, 0x0A));       //Forcing creation of two DIFAT sectors
                byte[] b1 = Helpers.GetBuffer(3, 0x0B);
                st.Append(b1);                                      //Forcing creation of two DIFAT sectors

                f.Save("$OpenMcdf$LargeFile.cfs");

                f.Close();

                int cnt = 3;
                f = new CompoundFile("$OpenMcdf$LargeFile.cfs");

                byte[] b2 = new byte[cnt];
                cnt = f.RootStorage.GetStream("LargeStream").Read(b2, 20000000, cnt);
                f.Close();
                Assert.IsTrue(Helpers.CompareBuffer(b1, b2));
            }
            finally
            {
                if (f != null)
                {
                    f.Close();
                }

                if (File.Exists("$OpenMcdf$LargeFile.cfs"))
                {
                    File.Delete("$OpenMcdf$LargeFile.cfs");
                }
            }
        }
Example #29
0
        public void CreateResponseAuth()
        {
            CFHTTPMessage response             = null;
            var           done                 = false;
            var           taskCompletionSource = new TaskCompletionSource <CFHTTPMessage> ();

            // the following code has to be in a diff thread, else, we are blocking the current loop, not cool
            // perform a request so that we fail in the auth, then create the auth object and check the count
            TestRuntime.RunAsync(DateTime.Now.AddSeconds(30), async() => {
                using (var request = CFHTTPMessage.CreateRequest(
                           new Uri(NetworkResources.Httpbin.GetStatusCodeUrl(HttpStatusCode.Unauthorized)), "GET", null)) {
                    request.SetBody(Array.Empty <byte> ());                     // empty body, we are not interested
                    using (var stream = CFStream.CreateForHTTPRequest(request)) {
                        Assert.IsNotNull(stream, "Null stream");
                        // we are only interested in the completed event
                        stream.ClosedEvent += (sender, e) => {
                            taskCompletionSource.SetResult(stream.GetResponseHeader());
                            done = true;
                        };
                        // enable events and run in the current loop
                        stream.EnableEvents(CFRunLoop.Main, CFRunLoop.ModeDefault);
                        stream.Open();
                        response = await taskCompletionSource.Task;
                    }
                }
            }, () => done);
            if (!done)
            {
                TestRuntime.IgnoreInCI("Transient network failure - ignore in CI");
            }
            Assert.IsTrue(done, "Network request completed");
            using (var auth = CFHTTPAuthentication.CreateFromResponse(response)) {
                Assert.NotNull(auth, "Null Auth");
                Assert.IsTrue(auth.IsValid, "Auth is valid");
                Assert.That(TestRuntime.CFGetRetainCount(auth.Handle), Is.EqualTo((nint)1), "RetainCount");
            }
        }
Example #30
0
        static void SetSolutionConfigValue(CFStream cfStream, IEnumerable <string> startupProjectGuids)
        {
            var single   = Encoding.GetEncodings().Single(x => string.Equals(x.Name, "utf-16", StringComparison.OrdinalIgnoreCase));
            var encoding = single.GetEncoding();
            var nul      = '\u0000';
            var dc1      = '\u0011';
            var etx      = '\u0003';
            var soh      = '\u0001';

            var builder = new StringBuilder();

            builder.Append(dc1);
            builder.Append(nul);
            builder.Append("MultiStartupProj");
            builder.Append(nul);
            builder.Append('=');
            builder.Append(etx);
            builder.Append(soh);
            builder.Append(nul);
            builder.Append(';');
            foreach (var startupProjectGuid in startupProjectGuids)
            {
                builder.Append('4');
                builder.Append(nul);
                builder.AppendFormat("{{{0}}}.dwStartupOpt", startupProjectGuid);
                builder.Append(nul);
                builder.Append('=');
                builder.Append(etx);
                builder.Append(dc1);
                builder.Append(nul);
                builder.Append(';');
            }

            var newBytes = encoding.GetBytes(builder.ToString());

            cfStream.SetData(newBytes);
        }
Example #31
0
		void HandleErrorEvent (object sender, CFStream.StreamEventArgs e)
		{
			var stream = (CFHTTPStream)sender;

			StreamBucket bucket;
			if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
				return;

			bucket.Response.TrySetException (stream.GetError ());
			CloseStream (stream);
		}
Example #32
0
		void HandleClosedEvent (object sender, CFStream.StreamEventArgs e)
		{
			var stream = (CFHTTPStream)sender;
			CloseStream (stream);
		}
Example #33
0
		void HandleHasBytesAvailableEvent (object sender, CFStream.StreamEventArgs e)
		{
			var stream = (CFHTTPStream) sender;

			StreamBucket bucket;
			if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
				return;

			if (bucket.Response.Task.IsCompleted) {
				bucket.ContentStream.ReadStreamData ();
				return;
			}

			var header = stream.GetResponseHeader ();

			// Is this possible?
			if (!header.IsHeaderComplete)
				throw new NotImplementedException ();

			bucket.ContentStream = new CFContentStream (stream);
				
			var response_msg = new HttpResponseMessage (header.ResponseStatusCode);
			response_msg.RequestMessage = bucket.Request;
			response_msg.ReasonPhrase = header.ResponseStatusLine;
			response_msg.Content = bucket.ContentStream;

			var fields = header.GetAllHeaderFields ();
			if (fields != null) {
				foreach (var entry in fields) {
					if (entry.Key == null)
						continue;

					var key = entry.Key.ToString ();
					var value = entry.Value == null ? string.Empty : entry.Value.ToString ();
					HttpHeaders item_headers;
					if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content) {
						item_headers = response_msg.Content.Headers;
					} else {
						item_headers = response_msg.Headers;

						if (cookies != null && (key == "Set-Cookie" || key == "Set-Cookie2"))
							AddCookie (value, bucket.Request.RequestUri, key);
					}

					item_headers.TryAddWithoutValidation (key, value);
				}
			}

			bucket.Response.TrySetResult (response_msg);

			bucket.ContentStream.ReadStreamData ();
		}