Пример #1
0
        public static void Read(BlobRequestOptions mapped, CloudBlob blob, ReaderDelegate reader)
        {
            blob.FetchAttributes(mapped);
            var props = MapFetchedAttrbitues(blob);

            var compression = blob.Properties.ContentEncoding ?? "";
            var md5 = blob.Metadata[LokadHashFieldName];

            switch (compression)
            {
                case "gzip":
                    using (var stream = blob.OpenRead(mapped))
                    {
                        ReadAndVerifyHash(stream, s =>
                            {
                                // important is not to flush the decompression stream
                                using (var decompress = new GZipStream(s, CompressionMode.Decompress, true))
                                {
                                    reader(props, decompress);
                                }
                            }, md5);
                    }

                    break;
                case "":
                    using (var stream = blob.OpenRead(mapped))
                    {
                        ReadAndVerifyHash(stream, s => reader(props, s), md5);
                    }
                    break;
                default:
                    var error = string.Format("Unsupported ContentEncoding '{0}'", compression);
                    throw new InvalidOperationException(error);
            }
        }
Пример #2
0
        /// <summary>
        /// UpdaterThread Thread
        /// </summary>
        private void Get(ArchiveInterval interval, URIDelegate URI, ReaderDelegate Reader,
                         Host host, IXenObject xenObject)
        {
            if (host == null)
            {
                return;
            }

            try
            {
                Session session = xenObject.Connection.Session;
                if (session == null)
                {
                    return;
                }
                using (Stream httpstream = HTTPHelper.GET(URI(session, host, interval, xenObject), xenObject.Connection, true))
                {
                    using (XmlReader reader = XmlReader.Create(httpstream))
                    {
                        SetsAdded = new List <DataSet>();
                        while (reader.Read())
                        {
                            Reader(reader, xenObject);
                        }
                    }
                }
            }
            catch (WebException)
            {
            }
            catch (Exception e)
            {
                log.Debug(string.Format("ArchiveMaintainer: Get updates for {0}: {1} Failed.", xenObject is Host ? "Host" : "VM", xenObject != null ? xenObject.opaque_ref : Helper.NullOpaqueRef), e);
            }
        }
Пример #3
0
 public void Reader(ReaderModuleDelegate readerModuleHandler)
 {
     ReaderHandler = new ReaderDelegate(readerHandlerP);
     _readerMsg    = new Thread(_reader);
     _readerMsg.Start();
     ReaderModuleHandler = new ReaderModuleDelegate(readerModuleHandler);
 }
Пример #4
0
 public override void Close()
 {
     this.internalReader = new ReaderDelegate(this.ReadingNotAvailable);
     this.crc            = null;
     this.entry          = null;
     base.Close();
 }
 public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true))
 {
     this.crc            = new Crc32();
     this.entry          = null;
     this.password       = null;
     this.internalReader = new ReaderDelegate(this.InitialRead);
 }
Пример #6
0
        /// <summary>
        /// Closes the zip input stream
        /// </summary>
        public override void Close()
        {
            internalReader = new ReaderDelegate(ReadingNotAvailable);
            crc            = null;
            entry          = null;

            base.Close();
        }
Пример #7
0
        public int v7()
        {
            CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), GetParserContext()), true, "StreamOverload3");

            CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), GetParserContext()), true, "TextOverload3");

            return(TEST_PASS);
        }
Пример #8
0
        /// <summary>
        /// Closes the zip input stream
        /// </summary>
        public override void Close()
        {
            internalReader = ReadingNotAvailable;
            crc            = null;
            entry          = null;

            base.Close();
        }
Пример #9
0
        // Perform the initial read on an entry which may include
        // reading encryption headers and setting up inflation.
        int InitialRead(byte[] destination, int offset, int count)
        {
            if (entry.Version > ZipConstants.VERSION_MADE_BY)
            {
                throw new ZipException("Libray cannot extract this entry version required (" + entry.Version.ToString() + ")");
            }

            // test for encryption
            if (entry.IsCrypted)
            {
                if (password == null)
                {
                    throw new ZipException("No password set.");
                }

                // Generate and set crypto transform...
                var managed = new PkzipClassicManaged();
                var key     = PkzipClassic.GenerateKeys(Encoding.ASCII.GetBytes(password));

                inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null);

                var cryptbuffer = new byte[ZipConstants.CRYPTO_HEADER_SIZE];
                inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CRYPTO_HEADER_SIZE);

                if ((flags & 8) == 0)
                {
                    if (cryptbuffer[ZipConstants.CRYPTO_HEADER_SIZE - 1] != (byte)(entry.Crc >> 24))
                    {
                        throw new ZipException("Invalid password");
                    }
                }
                else
                {
                    if (cryptbuffer[ZipConstants.CRYPTO_HEADER_SIZE - 1] != (byte)((entry.DosTime >> 8) & 0xff))
                    {
                        throw new ZipException("Invalid password");
                    }
                }

                if (csize >= ZipConstants.CRYPTO_HEADER_SIZE)
                {
                    csize -= ZipConstants.CRYPTO_HEADER_SIZE;
                }
            }
            else
            {
                inputBuffer.CryptoTransform = null;
            }

            if (method == (int)CompressionMethod.Deflated && inputBuffer.Available > 0)
            {
                inputBuffer.SetInflaterInput(inf);
            }

            internalReader = BodyRead;
            return(BodyRead(destination, offset, count));
        }
Пример #10
0
        /// <summary>
        /// Perform the initial read on an entry which may include
        /// reading encryption headers and setting up inflation.
        /// </summary>
        /// <param name="destination">The destination to fill with data read.</param>
        /// <param name="offset">The offset to start reading at.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <returns>The actual number of bytes read.</returns>
        int InitialRead(byte[] destination, int offset, int count)
        {
            if (!CanDecompressEntry)
            {
                throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")");
            }

            // Handle encryption if required.
            if (entry.IsCrypted)
            {
#if NETCF_1_0
                throw new ZipException("Encryption not supported for Compact Framework 1.0");
#else
                if (password == null)
                {
                    throw new ZipException("No password set.");
                }

                // Generate and set crypto transform...
                PkzipClassicManaged managed = new PkzipClassicManaged();
                byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password));

                inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null);

                byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize];
                inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize);

                if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue)
                {
                    throw new ZipException("Invalid password");
                }

                if (csize >= ZipConstants.CryptoHeaderSize)
                {
                    csize -= ZipConstants.CryptoHeaderSize;
                }
                else if ((entry.Flags & (int)GeneralBitFlags.Descriptor) == 0)
                {
                    throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize));
                }
#endif
            }
            else
            {
#if !NETCF_1_0
                inputBuffer.CryptoTransform = null;
#endif
            }

            if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0))
            {
                inputBuffer.SetInflaterInput(inf);
            }

            internalReader = new ReaderDelegate(BodyRead);
            return(BodyRead(destination, offset, count));
        }
Пример #11
0
        /// <summary>
        /// Attempts to read the storage item.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="condition">The condition.</param>
        /// <exception cref="StreamingItemNotFoundException">if the item does not exist.</exception>
        /// <exception cref="StreamingContainerNotFoundException">if the container for the item does not exist</exception>
        /// <exception cref="StreamingItemIntegrityException">when integrity check fails</exception>
        public void ReadInto(ReaderDelegate reader, StreamingCondition condition = new StreamingCondition())
        {
            ThrowIfContainerNotFound();
            ThrowIfItemNotFound();
            ThrowIfConditionFailed(condition);

            var props = GetUnconditionalInfo().Value;

            using (var stream = new MemoryStream(_content))
                reader(props, stream);
        }
Пример #12
0
        /// <summary>
        /// Perform the initial read on an entry which may include
        /// reading encryption headers and setting up inflation.
        /// </summary>
        /// <param name="destination">The destination to fill with data read.</param>
        /// <param name="offset">The offset to start reading at.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <returns>The actual number of bytes read.</returns>
        int InitialRead(byte[] destination, int offset, int count)
        {
            if (!CanDecompressEntry)
            {
                throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")");
            }

            // Handle encryption if required.
            if (entry.IsCrypted)
            {
#if COMPACT_FRAMEWORK_V10
                throw new ZipException("Encyptiong not supported for Compact Framework 1.0");
#else
                if (password == null)
                {
                    throw new ZipException("No password set.");
                }

                // Generate and set crypto transform...
                PkzipClassicManaged managed = new PkzipClassicManaged();
                byte[] key = PkzipClassic.GenerateKeys(Helper.ASCIIEncoding.GetBytes(password));

                inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null);

                byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize];
                inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize);

                if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue)
                {
                    throw new ZipException("Invalid password");
                }

                if (csize >= ZipConstants.CryptoHeaderSize)
                {
                    csize -= ZipConstants.CryptoHeaderSize;
                }
#endif
            }
            else
            {
#if !COMPACT_FRAMEWORK_V10
                inputBuffer.CryptoTransform = null;
#endif
            }

            if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0))
            {
                inputBuffer.SetInflaterInput(inf);
            }

            internalReader = new ReaderDelegate(BodyRead);
            return(BodyRead(destination, offset, count));
        }
Пример #13
0
        public int v3()
        {
            CError.Equals(ReaderDelegate.Create(GetStream(), null, GetParserContext()), true, "StreamOverload2");
            CError.Equals(ReaderDelegate.Create(GetStream(), null), true, "StreamOverload3");

            CError.Equals(ReaderDelegate.Create(GetUrl(), null), true, "URL Overload 1");
            CError.Equals(ReaderDelegate.Create(GetUrl(), null, GetParserContext()), true, "URL Overload 2");

            CError.Equals(ReaderDelegate.Create(GetTextReader(), null, GetParserContext()), true, "TextReader Overload2");
            CError.Equals(ReaderDelegate.Create(GetTextReader(), null), true, "TextReader Overload3");

            CError.Equals(ReaderDelegate.Create(GetXmlReader(), null), true, "XmlReader Overload1");
            return(TEST_PASS);
        }
Пример #14
0
        public int v6()
        {
            CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), (string)null), true, "StreamOverload2");
            CError.Equals(ReaderDelegate.Create(GetStream(), GetSettings(), (XmlParserContext)null), true, "StreamOverload2");

            CError.Equals(ReaderDelegate.Create(GetUrl(), GetSettings()), true, "URL Overload 1");
            CError.Equals(ReaderDelegate.Create(GetUrl(), GetSettings(), GetParserContext()), true, "URL Overload 2");

            CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), (string)null), true, "TextReader Overload2");
            CError.Equals(ReaderDelegate.Create(GetTextReader(), GetSettings(), (XmlParserContext)null), true, "TextReader Overload2");

            CError.Equals(ReaderDelegate.Create(GetXmlReader(), GetSettings()), true, "XmlReader Overload1");
            return(TEST_PASS);
        }
Пример #15
0
        /// <summary>
        /// Attempts to read the storage item.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="condition">The condition.</param>
        /// <exception cref="StreamingItemNotFoundException">if the item does not exist.</exception>
        /// <exception cref="StreamingContainerNotFoundException">if the container for the item does not exist</exception>
        /// <exception cref="StreamingItemIntegrityException">when integrity check fails</exception>
        public void ReadInto(ReaderDelegate reader, StreamingCondition condition)
        {
            Refresh();

            ThrowIfContainerNotFound();
            ThrowIfItemNotFound();
            ThrowIfConditionFailed(condition);

            var props = GetUnconditionalInfo().Value;

            using (var read = OpenForRead())
            {
                reader(props, read);
            }
        }
Пример #16
0
        public int v1()
        {
            CError.Equals(ReaderDelegate.Create((Stream)null), false, "Null Stream doesnt throw error1");
            CError.Equals(ReaderDelegate.Create((Stream)null, GetSettings(), GetBaseUri()), false, "Null Stream doesnt throw error2");
            CError.Equals(ReaderDelegate.Create((Stream)null, GetSettings()), false, "Null Stream doesnt throw error3");

            CError.Equals(ReaderDelegate.Create((string)null), false, "Null URL doesnt throw error1");
            CError.Equals(ReaderDelegate.Create((string)null, GetSettings()), false, "Null URL doesnt throw error2");
            CError.Equals(ReaderDelegate.Create((string)null, GetSettings(), GetParserContext()), false, "Null URL doesnt throw error3");

            CError.Equals(ReaderDelegate.Create((TextReader)null), false, "Null TextReader doesnt throw error1");
            CError.Equals(ReaderDelegate.Create((TextReader)null, GetSettings(), GetBaseUri()), false, "Null TextReader doesnt throw error2");
            CError.Equals(ReaderDelegate.Create((TextReader)null, GetSettings()), false, "Null TextReader doesnt throw error2");

            return(TEST_PASS);
        }
Пример #17
0
        public static List <T> ExecuteReaderList <T>(ReaderDelegate reader, string[] args, ref int errorNumber, Func <MethodBase> method)
        {
            DataTable dataTable  = new DataTable();;
            List <T>  returnList = new List <T>();
            T         newObject;

            try
            {
                dataTable = reader(args, ref errorNumber);

                if (dataTable == null || dataTable.Rows.Count == 0)
                {
                    return(returnList);
                }

                foreach (DataRow row in dataTable.Rows)
                {
                    newObject = (T)Activator.CreateInstance(typeof(T));

                    foreach (DataColumn column in dataTable.Columns)
                    {
                        if (!row.IsNull(column.ColumnName))
                        {
                            PropertyInfo objectProperty = typeof(T).GetProperty(column.ColumnName);
                            if (objectProperty == null)
                            {
                            }

                            objectProperty.SetValue(newObject, Convert.ChangeType(row[column.ColumnName], objectProperty.PropertyType), null);
                        }
                    }

                    returnList.Add(newObject);
                }
            }
            catch (Exception ex)
            {
                // log.Error("Error while executing, please confirm class properties against returned columns from table.", ex);
                returnList = null;
            }
            finally
            {
                Globals.DisposeDataTable(dataTable);
            }
            return(returnList);
        }
Пример #18
0
        /// <summary>
        /// Attempts to read the storage item.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="condition">The condition.</param>
        /// <exception cref="StreamingItemNotFoundException">if the item does not exist.</exception>
        /// <exception cref="StreamingContainerNotFoundException">if the container for the item does not exist</exception>
        /// <exception cref="StreamingItemIntegrityException">when integrity check fails</exception>
        public void ReadInto(ReaderDelegate reader, StreamingCondition condition)
        {
            try
            {
                var mapped = Map(condition);
                BlobStorageUtil.Read(mapped, _blob, reader);
            }
            catch (StreamingItemIntegrityException e)
            {
                throw StreamingErrors.IntegrityFailure(this, e);
            }
            catch (StorageClientException e)
            {
                switch (e.ErrorCode)
                {
                case StorageErrorCode.ContainerNotFound:
                    throw StreamingErrors.ContainerNotFound(this, e);

                case StorageErrorCode.ResourceNotFound:
                case StorageErrorCode.BlobNotFound:
                    throw StreamingErrors.ItemNotFound(this, e);

                case StorageErrorCode.ConditionFailed:
                    throw StreamingErrors.ConditionFailed(this, condition, e);

                case StorageErrorCode.ServiceIntegrityCheckFailed:
                    throw StreamingErrors.IntegrityFailure(this, e);

                case StorageErrorCode.BadRequest:
                    switch (e.StatusCode)
                    {
                    // for some reason Azure Storage happens to get here as well
                    case HttpStatusCode.PreconditionFailed:
                    case HttpStatusCode.NotModified:
                        throw StreamingErrors.ConditionFailed(this, condition, e);

                    default:
                        throw;
                    }

                default:
                    throw;
                }
            }
        }
Пример #19
0
 private int InitialRead(byte[] destination, int offset, int count)
 {
     if (!this.CanDecompressEntry)
     {
         throw new ZipException("Library cannot extract this entry. Version required is (" + this.entry.Version.ToString() + ")");
     }
     if (this.entry.IsCrypted)
     {
         if (this.password == null)
         {
             throw new ZipException("No password set.");
         }
         PkzipClassicManaged managed = new PkzipClassicManaged();
         byte[] rgbKey = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(this.password));
         base.inputBuffer.CryptoTransform = managed.CreateDecryptor(rgbKey, null);
         byte[] outBuffer = new byte[12];
         base.inputBuffer.ReadClearTextBuffer(outBuffer, 0, 12);
         if (outBuffer[11] != this.entry.CryptoCheckValue)
         {
             throw new ZipException("Invalid password");
         }
         if (base.csize < 12L)
         {
             if ((this.entry.Flags & 8) == 0)
             {
                 throw new ZipException($"Entry compressed size {base.csize} too small for encryption");
             }
         }
         else
         {
             base.csize -= 12L;
         }
     }
     else
     {
         base.inputBuffer.CryptoTransform = null;
     }
     if ((this.method == 8) && (base.inputBuffer.Available > 0))
     {
         base.inputBuffer.SetInflaterInput(base.inf);
     }
     this.internalReader = new ReaderDelegate(this.BodyRead);
     return(this.BodyRead(destination, offset, count));
 }
 private int InitialRead(byte[] destination, int offset, int count)
 {
     if (this.entry.Version > 20)
     {
         throw new ZipException("Libray cannot extract this entry version required (" + this.entry.Version.ToString() + ")");
     }
     if (this.entry.IsCrypted)
     {
         if (this.password == null)
         {
             throw new ZipException("No password set.");
         }
         PkzipClassicManaged managed = new PkzipClassicManaged();
         byte[] rgbKey = PkzipClassic.GenerateKeys(Encoding.ASCII.GetBytes(this.password));
         base.inputBuffer.CryptoTransform = managed.CreateDecryptor(rgbKey, null);
         byte[] outBuffer = new byte[12];
         base.inputBuffer.ReadClearTextBuffer(outBuffer, 0, 12);
         if ((this.flags & 8) == 0)
         {
             if (outBuffer[11] != ((byte)(this.entry.Crc >> 0x18)))
             {
                 throw new ZipException("Invalid password");
             }
         }
         else if (outBuffer[11] != ((byte)((this.entry.DosTime >> 8) & 0xffL)))
         {
             throw new ZipException("Invalid password");
         }
         if (base.csize >= 12L)
         {
             base.csize -= 12L;
         }
     }
     else
     {
         base.inputBuffer.CryptoTransform = null;
     }
     if ((this.method == 8) && (base.inputBuffer.Available > 0))
     {
         base.inputBuffer.SetInflaterInput(base.inf);
     }
     this.internalReader = new ReaderDelegate(this.BodyRead);
     return(this.BodyRead(destination, offset, count));
 }
Пример #21
0
        private static void test <T>(T value, WriterDelegate <T> w, ReaderDelegate <T> r)
        {
            Type type = value.GetType();

            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream, Encoding.UTF8, true))
                {
                    Logger.LogMessage("Writing {0}: {1}", type, value);
                    w(writer, value);
                }

                // Rewind
                stream.Position = 0;

                using (BinaryReader reader = new BinaryReader(stream, Encoding.UTF8, true))
                {
                    T readValue = r(reader);
                    Logger.LogMessage("Read {0}: {1}", type, readValue);
                    Assert.AreEqual(value, readValue);
                }
            }
        }
Пример #22
0
        public static void Read(BlobRequestOptions mapped, CloudBlob blob, ReaderDelegate reader)
        {
            blob.FetchAttributes(mapped);
            var props = MapFetchedAttrbitues(blob);

            var compression = blob.Properties.ContentEncoding ?? "";
            var md5         = blob.Metadata[LokadHashFieldName];

            switch (compression)
            {
            case "gzip":
                using (var stream = blob.OpenRead(mapped))
                {
                    ReadAndVerifyHash(stream, s =>
                    {
                        // important is not to flush the decompression stream
                        using (var decompress = new GZipStream(s, CompressionMode.Decompress, true))
                        {
                            reader(props, decompress);
                        }
                    }, md5);
                }

                break;

            case "":
                using (var stream = blob.OpenRead(mapped))
                {
                    ReadAndVerifyHash(stream, s => reader(props, s), md5);
                }
                break;

            default:
                var error = string.Format("Unsupported ContentEncoding '{0}'", compression);
                throw new InvalidOperationException(error);
            }
        }
Пример #23
0
        /// <summary>
        /// Attempts to read the storage item.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="condition">The condition.</param>
        /// <exception cref="StreamingItemNotFoundException">if the item does not exist.</exception>
        /// <exception cref="StreamingContainerNotFoundException">if the container for the item does not exist</exception>
        /// <exception cref="StreamingItemIntegrityException">when integrity check fails</exception>
        public void ReadInto(ReaderDelegate reader, StreamingCondition condition)
        {
            Refresh();

            ThrowIfContainerNotFound();
            ThrowIfItemNotFound();
            ThrowIfConditionFailed(condition);

            var props = GetUnconditionalInfo().Value;
            using (var read = OpenForRead())
            {
                reader(props, read);
            }
        }
Пример #24
0
        /// <summary>
        /// Perform the initial read on an entry which may include 
        /// reading encryption headers and setting up inflation.
        /// </summary>
        /// <param name="destination">The destination to fill with data read.</param>
        /// <param name="offset">The offset to start reading at.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <returns>The actual number of bytes read.</returns>
        int InitialRead(byte[] destination, int offset, int count)
        {
            if ( !CanDecompressEntry ) {
                throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")");
            }

            // Handle encryption if required.
            if (entry.IsCrypted) {
            #if NETCF_1_0
                throw new ZipException("Encryption not supported for Compact Framework 1.0");
            #else
                if (password == null) {
                    throw new ZipException("No password set.");
                }

                byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize];
                inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize);

                if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) {
                    throw new ZipException("Invalid password");
                }

                if (csize >= ZipConstants.CryptoHeaderSize) {
                    csize -= ZipConstants.CryptoHeaderSize;
                }
                else if ( (entry.Flags & (int)GeneralBitFlags.Descriptor) == 0 ) {
                    throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize));
                }
            #endif
            } else {
            #if !NETCF_1_0
                inputBuffer.CryptoTransform = null;
            #endif
            }

            if ( (method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0) ) {
                inputBuffer.SetInflaterInput(inf);
            }

            internalReader = new ReaderDelegate(BodyRead);
            return BodyRead(destination, offset, count);
        }
        EQXSerializer(Type type)
        {
            m_type = type;
            m_dynamicType = DynamicType.GetDynamicType(m_type);

            // build the functions here to pay the cost up front, once per type, instead of at runtime
            //  whenever an element is processed
            ReaderDelegate readAttributes = (XPathNavigator reader, ref object target) => { };
            ReaderDelegate readElements = (XPathNavigator reader, ref object target) => { };
            ReaderDelegate readArrays = (XPathNavigator reader, ref object target) => { };
            WriterDelegate writeAttributes = (XElement result, ref object target) => { };
            WriterDelegate writeElements = (XElement result, ref object target) => { };
            WriterDelegate writeArrays = (XElement result, ref object target) => { };
            for (int i = 0; i < m_dynamicType.Members.Count; i++)
            {
                // this goofy setup is to prevent the dynamic methods from acessing the wrong member
                int temp = i;
                DynamicMember member = m_dynamicType.Members[temp];

                object[] attributes = member.MemberInfo.GetCustomAttributes(false);
                EqXAttributeAttribute eqxAttribute = null;
                EqXElementAttribute eqxElement = null;
                EqXArrayAttribute eqxArray = null;
                DefaultValueAttribute defaultValue = null;
                foreach (object attr in attributes)
                {
                    eqxAttribute = eqxAttribute ?? attr as EqXAttributeAttribute;
                    eqxElement = eqxElement ?? attr as EqXElementAttribute;
                    eqxArray = eqxArray ?? attr as EqXArrayAttribute;
                    defaultValue = defaultValue ?? attr as DefaultValueAttribute;
                }

                // count how many of the eqx attributes are present
                int eqxCount = ((eqxAttribute != null) ? 1 : 0) + ((eqxElement != null) ? 1 : 0) + ((eqxArray != null) ? 1 : 0);
            #if DEBUG
                // check how many attributes are present in debug builds to sort out ambiguity
                if (eqxCount > 1)
                    Trace.TraceWarning(TooManyAttributes, m_type.Name, member.MemberName);
            #endif
                // don't process members that aren't marked
                if (eqxCount < 1) continue;

            #if DEBUG
                if (!member.CanWrite && !member.CanRead)
                {
                    Trace.TraceWarning("'{0}.{1}' has no way to be read or written, skipping it.", m_type.Name, member.MemberName);
                    continue;
                }
                else if (!member.CanRead)
                {
                    Trace.TraceWarning("'{0}.{1}' marked for serialization but can not be read, skipping it.", m_type.Name, member.MemberName);
                    continue;
                }
                else if (!member.CanWrite)
                {
                    Trace.TraceWarning("'{0}.{1}' marked for serialization but can not be written, skipping it.", m_type.Name, member.MemberName);
                    continue;
                }
            #endif
                // find the default value for the member
                object dvalue = null;
                if (defaultValue != null)
                    dvalue = defaultValue.Value;
                if (member.MemberType.IsValueType && dvalue == null)
                    dvalue = Activator.CreateInstance(member.MemberType);

                if (eqxAttribute != null)
                {
                    if (!member.MemberType.IsPrimitive && member.MemberType != typeof(string))
                        throw new InvalidOperationException(string.Format(OnlyPrimitivesXmlAttributes, m_type.Name, member.MemberName));

                    string name = eqxAttribute.Name ?? member.MemberName;
                    readAttributes += ReadPrimitive(member, string.Concat("@", name), dvalue);
                    writeAttributes += WritePrimitiveAttribute(member, name, dvalue, eqxAttribute.AlwaysWrite);
                }
                else if (eqxElement != null)
                {
                    string name = eqxElement.Name ?? member.MemberName;
                    if (member.MemberType.IsComplex() && member.MemberType != typeof(string))
                    {
                        readElements += ReadComplex(member, name, dvalue);
                        writeElements += WriteComplexElement(member, name, dvalue, eqxElement.AlwaysWrite);
                    }
                    else
                    {
                        readElements += ReadPrimitive(member, name, dvalue);
                        writeElements += WritePrimitiveElement(member, name, dvalue, eqxElement.AlwaysWrite);
                    }
                }
                else if (eqxArray != null)
                {
                    string name = eqxArray.Name ?? member.MemberName;
                    readElements += ReadArray(member, name, eqxArray.ItemName, dvalue);
                    writeElements += WriteArray(member, name, eqxArray.ItemName, dvalue, eqxArray.AlwaysWrite);
                }
            }

            m_reader = (XPathNavigator navigator, ref object target) =>
            {
                if (target == null)
                    target = m_dynamicType.CreateInstance();

                if (navigator.HasAttributes)
                    readAttributes(navigator, ref target);

                if (navigator.HasChildren)
                {
                    readElements(navigator, ref target);
                    readArrays(navigator, ref target);
                }
            };

            m_writer = (XElement result, ref object target) =>
            {
                if (target != null)
                {
                    writeAttributes(result, ref target);
                    writeElements(result, ref target);
                    writeArrays(result, ref target);
                }
            };
        }
Пример #26
0
 /// <summary>
 /// Creates a new Zip input stream, for reading a zip archive.
 /// </summary>
 public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true))
 {
     internalReader = new ReaderDelegate(InitialRead);
 }
Пример #27
0
		/// <summary>
		/// Advances to the next entry in the archive
		/// </summary>
		/// <returns>
		/// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries.
		/// </returns>
		/// <remarks>
		/// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called.
		/// </remarks>
		/// <exception cref="InvalidOperationException">
		/// Input stream is closed
		/// </exception>
		/// <exception cref="ZipException">
		/// Password is not set, password is invalid, compression method is invalid, 
		/// version required to extract is not supported
		/// </exception>
		public ZipEntry GetNextEntry()
		{
			if (crc == null) {
				throw new InvalidOperationException("Closed.");
			}
			
			if (entry != null) {
				CloseEntry();
			}

			int header = inputBuffer.ReadLeInt();

			if (header == ZipConstants.CENSIG || 
			    header == ZipConstants.ENDSIG || 
			    header == ZipConstants.CENDIGITALSIG || 
			    header == ZipConstants.CENSIG64) {
			    // No more individual entries exist
				Close();
				return null;
			}

			// -jr- 07-Dec-2003 Ignore spanning temporary signatures if found
			// SPANNINGSIG is same as descriptor signature and is untested as yet.
			if (header == ZipConstants.SPANTEMPSIG || header == ZipConstants.SPANNINGSIG) {
				header = inputBuffer.ReadLeInt();
			}
			
			if (header != ZipConstants.LOCSIG) {
				throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header));
			}
			
			short versionRequiredToExtract = (short)inputBuffer.ReadLeShort();
			
			flags          = inputBuffer.ReadLeShort();
			method         = inputBuffer.ReadLeShort();
			uint dostime   = (uint)inputBuffer.ReadLeInt();
			int crc2       = inputBuffer.ReadLeInt();
			csize          = inputBuffer.ReadLeInt();
			size           = inputBuffer.ReadLeInt();
			int nameLen    = inputBuffer.ReadLeShort();
			int extraLen   = inputBuffer.ReadLeShort();
			
			bool isCrypted = (flags & 1) == 1;
			
			byte[] buffer = new byte[nameLen];
			inputBuffer.ReadRawBuffer(buffer);
			
			string name = ZipConstants.ConvertToString(buffer);
			
			entry = new ZipEntry(name, versionRequiredToExtract);
			entry.Flags = flags;
			
			if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CRYPTO_HEADER_SIZE != size))) {
				throw new ZipException("Stored, but compressed != uncompressed");
			}
			
			if (method != (int)CompressionMethod.Stored && method != (int)CompressionMethod.Deflated) {
				throw new ZipException("Unknown compression method " + method);
			}
			
			entry.CompressionMethod = (CompressionMethod)method;
			
			if ((flags & 8) == 0) {
				entry.Crc  = crc2 & 0xFFFFFFFFL;
				entry.Size = size & 0xFFFFFFFFL;
				entry.CompressedSize = csize & 0xFFFFFFFFL;
			} else {
				
				// This allows for GNU, WinZip and possibly other archives, the PKZIP spec says these are zero
				// under these circumstances.
				if (crc2 != 0) {
					entry.Crc = crc2 & 0xFFFFFFFFL;
				}
				
				if (size != 0) {
					entry.Size = size & 0xFFFFFFFFL;
				}
				if (csize != 0) {
					entry.CompressedSize = csize & 0xFFFFFFFFL;
				}
			}
			
			entry.DosTime = dostime;
			
			if (extraLen > 0) {
				byte[] extra = new byte[extraLen];
				inputBuffer.ReadRawBuffer(extra);
				entry.ExtraData = extra;
			}

			internalReader = new ReaderDelegate(InitialRead);
			return entry;
		}
        public ZipEntry GetNextEntry()
        {
            if (this.crc == null)
            {
                throw new InvalidOperationException("Closed.");
            }
            if (this.entry != null)
            {
                this.CloseEntry();
            }
            int num = base.inputBuffer.ReadLeInt();

            switch (num)
            {
            case 0x2014b50:
            case 0x6054b50:
            case 0x5054b50:
            case 0x6064b50:
                this.Close();
                return(null);

            case 0x30304b50:
            case 0x8074b50:
                num = base.inputBuffer.ReadLeInt();
                break;
            }
            if (num != 0x4034b50)
            {
                throw new ZipException("Wrong Local header signature: 0x" + string.Format("{0:X}", num));
            }
            short versionRequiredToExtract = (short)base.inputBuffer.ReadLeShort();

            this.flags  = base.inputBuffer.ReadLeShort();
            this.method = base.inputBuffer.ReadLeShort();
            uint num3 = (uint)base.inputBuffer.ReadLeInt();
            int  num4 = base.inputBuffer.ReadLeInt();

            base.csize = base.inputBuffer.ReadLeInt();
            this.size  = base.inputBuffer.ReadLeInt();
            int  num5 = base.inputBuffer.ReadLeShort();
            int  num6 = base.inputBuffer.ReadLeShort();
            bool flag = (this.flags & 1) == 1;

            byte[] buffer = new byte[num5];
            base.inputBuffer.ReadRawBuffer(buffer);
            string name = ZipConstants.ConvertToString(buffer);

            this.entry       = new ZipEntry(name, versionRequiredToExtract);
            this.entry.Flags = this.flags;
            if ((this.method == 0) && ((!flag && (base.csize != this.size)) || (flag && ((base.csize - 12L) != this.size))))
            {
                throw new ZipException("Stored, but compressed != uncompressed");
            }
            if ((this.method != 0) && (this.method != 8))
            {
                throw new ZipException("Unknown compression method " + this.method);
            }
            this.entry.CompressionMethod = (CompressionMethod)this.method;
            if ((this.flags & 8) == 0)
            {
                this.entry.Crc            = num4 & ((long)0xffffffffL);
                this.entry.Size           = this.size & ((long)0xffffffffL);
                this.entry.CompressedSize = base.csize & ((long)0xffffffffL);
            }
            else
            {
                if (num4 != 0)
                {
                    this.entry.Crc = num4 & ((long)0xffffffffL);
                }
                if (this.size != 0L)
                {
                    this.entry.Size = this.size & ((long)0xffffffffL);
                }
                if (base.csize != 0L)
                {
                    this.entry.CompressedSize = base.csize & ((long)0xffffffffL);
                }
            }
            this.entry.DosTime = num3;
            if (num6 > 0)
            {
                byte[] buffer2 = new byte[num6];
                base.inputBuffer.ReadRawBuffer(buffer2);
                this.entry.ExtraData = buffer2;
            }
            this.internalReader = new ReaderDelegate(this.InitialRead);
            return(this.entry);
        }
 public static ReaderDelegate GetReader(Func <Type, ReaderDelegate> readersFactory, ReaderDelegate baseReader)
 {
     return((IntPtr data, ref int index, ref object result, ReaderContext context) =>
     {
         object type = null;
         readersFactory(typeof(string))(data, ref index, ref type, context);
         if ((string)type == typeof(C).Name)
         {
             result = new C();
         }
         else if ((string)type == typeof(D).Name)
         {
             result = new D();
         }
         else
         {
             throw new InvalidOperationException("Unknown type " + type);
         }
         readersFactory(result.GetType())(data, ref index, ref result, context);
     });
 }
Пример #30
0
        /// <summary>
        /// Attempts to read the storage item.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="condition">The condition.</param>
        /// <exception cref="StreamingItemNotFoundException">if the item does not exist.</exception>
        /// <exception cref="StreamingContainerNotFoundException">if the container for the item does not exist</exception>
        /// <exception cref="StreamingItemIntegrityException">when integrity check fails</exception>
        public void ReadInto(ReaderDelegate reader, StreamingCondition condition = new StreamingCondition())
        {
            ThrowIfContainerNotFound();
            ThrowIfItemNotFound();
            ThrowIfConditionFailed(condition);

            var props = GetUnconditionalInfo().Value;
            using (var stream = new MemoryStream(_content))
                reader(props, stream);
        }
Пример #31
0
        /// <summary>
        /// UpdaterThread Thread
        /// </summary>
        private void Get(ArchiveInterval interval, URIDelegate URI, ReaderDelegate Reader,
            Host host, IXenObject xenObject)
        {
            if (host == null)
                return;

            try
            {
                Session session = xenObject.Connection.Session;
                if (session == null)
                    return;
                using (Stream httpstream = HTTPHelper.GET(URI(session, host, interval, xenObject), xenObject.Connection, true, false))
                {
                    using (XmlReader reader = XmlReader.Create(httpstream))
                    {
                        SetsAdded = new List<DataSet>();
                        while (reader.Read())
                        {
                            Reader(reader, xenObject);
                        }
                    }
                }
            }
            catch (WebException)
            {
            }
            catch (Exception e)
            {
                log.Debug(string.Format("ArchiveMaintainer: Get updates for {0}: {1} Failed.", xenObject is Host ? "Host" : "VM", xenObject != null ? xenObject.opaque_ref : Helper.NullOpaqueRef), e);
            }
        }
Пример #32
0
 /// <summary>
 /// Creates a new Zip input stream, for reading a zip archive.
 /// </summary>
 public ZipInputStream(Stream baseInputStream)
     : base(baseInputStream, new Inflater(true))
 {
     internalReader = new ReaderDelegate(ReadingNotAvailable);
 }
Пример #33
0
        /// <summary>
        /// Advances to the next entry in the archive
        /// </summary>
        /// <returns>
        /// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries.
        /// </returns>
        /// <remarks>
        /// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called.
        /// </remarks>
        /// <exception cref="InvalidOperationException">
        /// Input stream is closed
        /// </exception>
        /// <exception cref="ZipException">
        /// Password is not set, password is invalid, compression method is invalid,
        /// version required to extract is not supported
        /// </exception>
        public ZipEntry GetNextEntry()
        {
            if (crc == null)
            {
                throw new InvalidOperationException("Closed.");
            }

            if (entry != null)
            {
                CloseEntry();
            }

            int header = inputBuffer.ReadLeInt();

            if (header == ZipConstants.CentralHeaderSignature ||
                header == ZipConstants.EndOfCentralDirectorySignature ||
                header == ZipConstants.CentralHeaderDigitalSignature ||
                header == ZipConstants.ArchiveExtraDataSignature ||
                header == ZipConstants.Zip64CentralFileHeaderSignature)
            {
                // No more individual entries exist
                Close();
                return(null);
            }

            // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found
            // Spanning signature is same as descriptor signature and is untested as yet.
            if ((header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature))
            {
                header = inputBuffer.ReadLeInt();
            }

            if (header != ZipConstants.LocalHeaderSignature)
            {
                throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header));
            }

            short versionRequiredToExtract = (short)inputBuffer.ReadLeShort();

            flags  = inputBuffer.ReadLeShort();
            method = inputBuffer.ReadLeShort();
            uint dostime = (uint)inputBuffer.ReadLeInt();
            int  crc2    = inputBuffer.ReadLeInt();

            csize = inputBuffer.ReadLeInt();
            size  = inputBuffer.ReadLeInt();
            int nameLen  = inputBuffer.ReadLeShort();
            int extraLen = inputBuffer.ReadLeShort();

            bool isCrypted = (flags & 1) == 1;

            byte[] buffer = new byte[nameLen];
            inputBuffer.ReadRawBuffer(buffer);

            string name = ZipConstants.ConvertToStringExt(flags, buffer);

            entry       = new ZipEntry(name, versionRequiredToExtract);
            entry.Flags = flags;

            entry.CompressionMethod = (CompressionMethod)method;

            if ((flags & 8) == 0)
            {
                entry.Crc            = crc2 & 0xFFFFFFFFL;
                entry.Size           = size & 0xFFFFFFFFL;
                entry.CompressedSize = csize & 0xFFFFFFFFL;

                entry.CryptoCheckValue = (byte)(crc2 >> 24);
            }
            else
            {
                // This allows for GNU, WinZip and possibly other archives, the PKZIP spec
                // says these values are zero under these circumstances.
                if (crc2 != 0)
                {
                    entry.Crc = crc2 & 0xFFFFFFFFL;
                }

                if (size != 0)
                {
                    entry.Size = size & 0xFFFFFFFFL;
                }

                if (csize != 0)
                {
                    entry.CompressedSize = csize & 0xFFFFFFFFL;
                }

                entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff);
            }

            entry.DosTime = dostime;

            // If local header requires Zip64 is true then the extended header should contain
            // both values.

            // Handle extra data if present.  This can set/alter some fields of the entry.
            if (extraLen > 0)
            {
                byte[] extra = new byte[extraLen];
                inputBuffer.ReadRawBuffer(extra);
                entry.ExtraData = extra;
            }

            entry.ProcessExtraData(true);
            if (entry.CompressedSize >= 0)
            {
                csize = entry.CompressedSize;
            }

            if (entry.Size >= 0)
            {
                size = entry.Size;
            }

            if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size)))
            {
                throw new ZipException("Stored, but compressed != uncompressed");
            }

            // Determine how to handle reading of data if this is attempted.
            if (entry.IsCompressionMethodSupported())
            {
                internalReader = new ReaderDelegate(InitialRead);
            }
            else
            {
                internalReader = new ReaderDelegate(ReadingNotSupported);
            }

            return(entry);
        }
Пример #34
0
        /// <summary>
        /// Closes the zip input stream
        /// </summary>
        public override void Close()
        {
            internalReader = new ReaderDelegate(ReadingNotAvailable);
            crc = null;
            entry = null;

            base.Close();
        }
Пример #35
0
        /// <summary>
        /// Perform the initial read on an entry which may include 
        /// reading encryption headers and setting up inflation.
        /// </summary>
        /// <param name="destination">The destination to fill with data read.</param>
        /// <param name="offset">The offset to start reading at.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <returns>The actual number of bytes read.</returns>
        int InitialRead(byte[] destination, int offset, int count)
        {
            if ( !CanDecompressEntry ) {
                throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")");
            }

            // Handle encryption if required.
            if (entry.IsCrypted) {
            #if COMPACT_FRAMEWORK_V10
                throw new ZipException("Encyptiong not supported for Compact Framework 1.0");
            #else
                if (password == null) {
                    throw new ZipException("No password set.");
                }

                // Generate and set crypto transform...
                PkzipClassicManaged managed = new PkzipClassicManaged();
                byte[] key = PkzipClassic.GenerateKeys(Encoding.ASCII.GetBytes(password));

                inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null);

                byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize];
                inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize);

                if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) {
                    throw new ZipException("Invalid password");
                }

                if (csize >= ZipConstants.CryptoHeaderSize) {
                    csize -= ZipConstants.CryptoHeaderSize;
                }
            #endif
            } else {
            #if !COMPACT_FRAMEWORK_V10
                inputBuffer.CryptoTransform = null;
            #endif
            }

            if ( (method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0) ) {
                inputBuffer.SetInflaterInput(inf);
            }

            internalReader = new ReaderDelegate(BodyRead);
            return BodyRead(destination, offset, count);
        }
Пример #36
0
 public GroBufCustomSerializerByAttribute(SizeCounterDelegate sizeCounter, WriterDelegate writerDelegate, ReaderDelegate readerDelegate)
 {
     this.sizeCounter    = sizeCounter;
     this.writerDelegate = writerDelegate;
     this.readerDelegate = readerDelegate;
 }
		/// <summary>
		/// Creates a new Zip input stream, for reading a zip archive.
		/// </summary>
		/// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param>
		public ZipInputStream(Stream baseInputStream)
			: base(baseInputStream, new Inflater(true))
		{
			internalReader = ReadingNotAvailable;
		}
Пример #38
0
 /// <summary>
 /// Creates a new Zip input stream, for reading a zip archive.
 /// </summary>
 public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true))
 {
     internalReader = InitialRead;
 }
Пример #39
0
 /// <summary>
 /// Creates a new Zip input stream, for reading a zip archive.
 /// </summary>
 public ZipInputStream(Stream baseInputStream)
     : base(baseInputStream, new Inflater(true))
 {
     internalReader = new ReaderDelegate(ReadingNotAvailable);
 }
Пример #40
0
        /// <summary>
        /// Advances to the next entry in the archive
        /// </summary>
        /// <returns>
        /// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries.
        /// </returns>
        /// <remarks>
        /// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called.
        /// </remarks>
        /// <exception cref="InvalidOperationException">
        /// Input stream is closed
        /// </exception>
        /// <exception cref="ZipException">
        /// Password is not set, password is invalid, compression method is invalid,
        /// version required to extract is not supported
        /// </exception>
        public ZipEntry GetNextEntry()
        {
            if (crc == null)
            {
                throw new InvalidOperationException("Closed.");
            }

            if (entry != null)
            {
                CloseEntry();
            }

            var header = inputBuffer.ReadLeInt();

            if (header == ZipConstants.CENSIG ||
                header == ZipConstants.ENDSIG ||
                header == ZipConstants.CENDIGITALSIG ||
                header == ZipConstants.CENSIG64)
            {
                // No more individual entries exist
                Close();
                return(null);
            }

            // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found
            // SPANNINGSIG is same as descriptor signature and is untested as yet.
            if (header == ZipConstants.SPANTEMPSIG || header == ZipConstants.SPANNINGSIG)
            {
                header = inputBuffer.ReadLeInt();
            }

            if (header != ZipConstants.LOCSIG)
            {
                throw new ZipException("Wrong Local header signature: 0x" + $"{header:X}");
            }

            var versionRequiredToExtract = (short)inputBuffer.ReadLeShort();

            flags  = inputBuffer.ReadLeShort();
            method = inputBuffer.ReadLeShort();
            var dostime = (uint)inputBuffer.ReadLeInt();
            var crc2    = inputBuffer.ReadLeInt();

            csize = inputBuffer.ReadLeInt();
            size  = inputBuffer.ReadLeInt();
            var nameLen  = inputBuffer.ReadLeShort();
            var extraLen = inputBuffer.ReadLeShort();

            var isCrypted = (flags & 1) == 1;

            var buffer = new byte[nameLen];

            inputBuffer.ReadRawBuffer(buffer);

            var name = ZipConstants.ConvertToString(buffer);

            entry       = new ZipEntry(name, versionRequiredToExtract);
            entry.Flags = flags;

            if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CRYPTO_HEADER_SIZE != size)))
            {
                throw new ZipException("Stored, but compressed != uncompressed");
            }

            if (method != (int)CompressionMethod.Stored && method != (int)CompressionMethod.Deflated)
            {
                throw new ZipException("Unknown compression method " + method);
            }

            entry.CompressionMethod = (CompressionMethod)method;

            if ((flags & 8) == 0)
            {
                entry.Crc            = crc2 & 0xFFFFFFFFL;
                entry.Size           = size & 0xFFFFFFFFL;
                entry.CompressedSize = csize & 0xFFFFFFFFL;
            }
            else
            {
                // This allows for GNU, WinZip and possibly other archives, the PKZIP spec says these are zero
                // under these circumstances.
                if (crc2 != 0)
                {
                    entry.Crc = crc2 & 0xFFFFFFFFL;
                }

                if (size != 0)
                {
                    entry.Size = size & 0xFFFFFFFFL;
                }
                if (csize != 0)
                {
                    entry.CompressedSize = csize & 0xFFFFFFFFL;
                }
            }

            entry.DosTime = dostime;

            if (extraLen > 0)
            {
                var extra = new byte[extraLen];
                inputBuffer.ReadRawBuffer(extra);
                entry.ExtraData = extra;
            }

            internalReader = InitialRead;
            return(entry);
        }
Пример #41
0
        /// <summary>
        /// Advances to the next entry in the archive
        /// </summary>
        /// <returns>
        /// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries.
        /// </returns>
        /// <remarks>
        /// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called.
        /// </remarks>
        /// <exception cref="InvalidOperationException">
        /// Input stream is closed
        /// </exception>
        /// <exception cref="ZipException">
        /// Password is not set, password is invalid, compression method is invalid,
        /// version required to extract is not supported
        /// </exception>
        public ZipEntry GetNextEntry()
        {
            if (crc == null) {
                throw new InvalidOperationException("Closed.");
            }

            if (entry != null) {
                CloseEntry();
            }

            int header = inputBuffer.ReadLeInt();

            if (header == ZipConstants.CentralHeaderSignature ||
                header == ZipConstants.EndOfCentralDirectorySignature ||
                header == ZipConstants.CentralHeaderDigitalSignature ||
                header == ZipConstants.ArchiveExtraDataSignature ||
                header == ZipConstants.Zip64CentralFileHeaderSignature) {
                // No more individual entries exist
                Close();
                return null;
            }

            // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found
            // Spanning signature is same as descriptor signature and is untested as yet.
            if ( (header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature) ) {
                header = inputBuffer.ReadLeInt();
            }

            if (header != ZipConstants.LocalHeaderSignature) {
                throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header));
            }

            short versionRequiredToExtract = (short)inputBuffer.ReadLeShort();

            flags          = inputBuffer.ReadLeShort();
            method         = inputBuffer.ReadLeShort();
            uint dostime   = (uint)inputBuffer.ReadLeInt();
            int crc2       = inputBuffer.ReadLeInt();
            csize          = inputBuffer.ReadLeInt();
            size           = inputBuffer.ReadLeInt();
            int nameLen    = inputBuffer.ReadLeShort();
            int extraLen   = inputBuffer.ReadLeShort();

            bool isCrypted = (flags & 1) == 1;

            byte[] buffer = new byte[nameLen];
            inputBuffer.ReadRawBuffer(buffer);

            string name = ZipConstants.ConvertToStringExt(flags, buffer);

            entry = new ZipEntry(name, versionRequiredToExtract);
            entry.Flags = flags;

            entry.CompressionMethod = (CompressionMethod)method;

            if ((flags & 8) == 0) {
                entry.Crc  = crc2 & 0xFFFFFFFFL;
                entry.Size = size & 0xFFFFFFFFL;
                entry.CompressedSize = csize & 0xFFFFFFFFL;

                entry.CryptoCheckValue = (byte)(crc2 >> 24);

            } else {

                // This allows for GNU, WinZip and possibly other archives, the PKZIP spec
                // says these values are zero under these circumstances.
                if (crc2 != 0) {
                    entry.Crc = crc2 & 0xFFFFFFFFL;
                }

                if (size != 0) {
                    entry.Size = size & 0xFFFFFFFFL;
                }

                if (csize != 0) {
                    entry.CompressedSize = csize & 0xFFFFFFFFL;
                }

                entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff);
            }

            entry.DosTime = dostime;

            // If local header requires Zip64 is true then the extended header should contain
            // both values.

            // Handle extra data if present.  This can set/alter some fields of the entry.
            if (extraLen > 0) {
                byte[] extra = new byte[extraLen];
                inputBuffer.ReadRawBuffer(extra);
                entry.ExtraData = extra;
            }

            entry.ProcessExtraData(true);
            if ( entry.CompressedSize >= 0 ) {
                csize = entry.CompressedSize;
            }

            if ( entry.Size >= 0 ) {
                size = entry.Size;
            }

            if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) {
                throw new ZipException("Stored, but compressed != uncompressed");
            }

            // Determine how to handle reading of data if this is attempted.
            if (entry.IsCompressionMethodSupported()) {
                internalReader = new ReaderDelegate(InitialRead);
            } else {
                internalReader = new ReaderDelegate(ReadingNotSupported);
            }

            return entry;
        }
Пример #42
0
 public static ReaderDelegate GetReader(Func <Type, ReaderDelegate> readersFactory, ReaderDelegate baseReader, Func <TAttribute, string> attributeKeySelector)
 {
     return((IntPtr data, ref int index, ref object result, ReaderContext context) =>
     {
         object textType = null;
         readersFactory(typeof(string))(data, ref index, ref textType, context);
         var type = GetTypeByTypeNameType((string)textType, attributeKeySelector) ?? typeof(string);
         readersFactory(type)(data, ref index, ref result, context);
     });
 }
Пример #43
0
		/// <summary>
		/// Creates a new Zip input stream, for reading a zip archive.
		/// </summary>
		public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true))
		{
			internalReader = new ReaderDelegate(InitialRead);
		}
Пример #44
0
        /// <summary>
        /// Perform the initial read on an entry which may include 
        /// reading encryption headers and setting up inflation.
        /// </summary>
        /// <param name="destination">The destination to fill with data read.</param>
        /// <param name="offset">The offset to start reading at.</param>
        /// <param name="count">The maximum number of bytes to read.</param>
        /// <returns>The actual number of bytes read.</returns>
        private int InitialRead(byte[] destination, int offset, int count)
        {
            if (!CanDecompressEntry)
            {
                throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version + ")");
            }

            // Handle encryption if required.
            if (entry.IsCrypted)
            {
                if (password == null)
                {
                    throw new ZipException("No password set.");
                }

                // Generate and set crypto transform...
                var managed = new PkzipClassicManaged();
                var key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password));

                inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null);

                var cryptbuffer = new byte[ZipConstants.CryptoHeaderSize];
                inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize);

                if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue)
                {
                    throw new ZipException("Invalid password");
                }

                if (csize >= ZipConstants.CryptoHeaderSize)
                {
                    csize -= ZipConstants.CryptoHeaderSize;
                }
                else if ((entry.Flags & (int) GeneralBitFlags.Descriptor) == 0)
                {
                    throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize));
                }
            }
            else
            {
                inputBuffer.CryptoTransform = null;
            }

            if ((method == (int) CompressionMethod.Deflated) && (inputBuffer.Available > 0))
            {
                inputBuffer.SetInflaterInput(inf);
            }

            internalReader = BodyRead;
            return BodyRead(destination, offset, count);
        }
Пример #45
0
		// Perform the initial read on an entry which may include 
		// reading encryption headers and setting up inflation.
		int InitialRead(byte[] destination, int offset, int count)
		{
			if (entry.Version > ZipConstants.VERSION_MADE_BY) {
				throw new ZipException("Libray cannot extract this entry version required (" + entry.Version.ToString() + ")");
			}
			
			// test for encryption
			if (entry.IsCrypted) {
		
				if (password == null) {
					throw new ZipException("No password set.");
				}
			
				// Generate and set crypto transform...
				PkzipClassicManaged managed = new PkzipClassicManaged();
				byte[] key = PkzipClassic.GenerateKeys(Encoding.ASCII.GetBytes(password));
					
				inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null);
			
				byte[] cryptbuffer = new byte[ZipConstants.CRYPTO_HEADER_SIZE];
				inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CRYPTO_HEADER_SIZE);
					
				if ((flags & 8) == 0) {
					if (cryptbuffer[ZipConstants.CRYPTO_HEADER_SIZE - 1] != (byte)(entry.Crc >> 24)) {
						throw new ZipException("Invalid password");
					}
				}
				else {
					if (cryptbuffer[ZipConstants.CRYPTO_HEADER_SIZE - 1] != (byte)((entry.DosTime >> 8) & 0xff)) {
						throw new ZipException("Invalid password");
					}
				}
					
				if (csize >= ZipConstants.CRYPTO_HEADER_SIZE) {
					csize -= ZipConstants.CRYPTO_HEADER_SIZE;
				}
			} 
			else {
				inputBuffer.CryptoTransform = null;
			}
			
			if (method == (int)CompressionMethod.Deflated && inputBuffer.Available > 0) {
				inputBuffer.SetInflaterInput(inf);
			}
			
			internalReader = new ReaderDelegate(BodyRead);
			return BodyRead(destination, offset, count);
		}
		/// <summary>
		/// Closes the zip input stream
		/// </summary>
		public override void Close()
		{
			internalReader = ReadingNotAvailable;
			crc = null;
			entry = null;

			base.Close();
		}