Example #1
0
        /// <summary>
        /// Decompresses the compressed data stored in one or more IDAT chunks.
        /// </summary>
        private byte[] Decompress()
        {
            Inflater     inf          = new Inflater();
            MemoryStream decompressed = new MemoryStream();
            MemoryStream compressed   = new MemoryStream();

            byte[] buf = new byte[1];

            // decompress the image data
            foreach (Chunk c in _image.Chunks)
            {
                if (c.Type == "IDAT")
                {
                    IDATChunk idat = c as IDATChunk;

                    compressed.Write(idat.Data, 0, idat.Data.Length);

                    if (compressed.Length > 15)
                    {
                        inf.SetInput(compressed.ToArray());

                        while (!inf.IsNeedingInput)
                        {
                            if (inf.Inflate(buf) == -1)
                            {
                                break;
                            }

                            decompressed.WriteByte(buf[0]);
                        }

                        compressed = new MemoryStream();
                    }
                }
            }

            inf.SetInput(compressed.ToArray());

            while (!inf.IsNeedingInput)
            {
                if (inf.Inflate(buf) == -1)
                {
                    break;
                }

                decompressed.WriteByte(buf[0]);
            }

            if (!inf.IsFinished)
            {
                throw new InvalidCompressedDataException("Inflater is not finished but there are no more IDAT chunks.");
            }

            byte[] arr = decompressed.ToArray();

            decompressed.Close();

            return(arr);
        }
Example #2
0
        /// <summary>
        /// Decode a zRIF encoded string to a RIF byte array.
        /// </summary>
        /// <param name="zrif">The zRIF string</param>
        /// <returns>The RIF byte array, or null on error</returns>
        public static byte[] Decode(string zrif)
        {
            byte[] input, output = new byte[1024];

            try
            {
                // Pad string if not a multiple of 4
                if (zrif.Length % 4 != 0)
                {
                    zrif += new string('=', 4 - (zrif.Length % 4));
                }
                input = Convert.FromBase64String(zrif);
            }
            catch (Exception e) when(e is System.FormatException || e is System.NullReferenceException)
            {
                Console.Error.WriteLine($"[ERROR] {e.Message}");
                return(null);
            }

            if (input.Length < 6)
            {
                Console.Error.WriteLine("[ERROR] zRIF length too short");
                return(null);
            }
            if (((input[0] << 8) + input[1]) % 31 != 0)
            {
                Console.Error.WriteLine("[ERROR] zRIF header is corrupted");
                return(null);
            }
            var inflater = new Inflater();

            inflater.SetInput(input);
            inflater.Inflate(output);
            if (inflater.IsNeedingDictionary)
            {
                inflater.SetDictionary(zrif_dict);
            }
            switch (inflater.Inflate(output))
            {
            case 1024:
                return(output);

            case 512:
                return(MemCpy(output, 0, 512));

            default:
                return(null);
            }
        }
Example #3
0
        private void ReadBlock()
        {
            this.currentBlock = this.reader.ReadBlock();

            if (this.currentBlock.IsEmpty)
            {
                this.readBuffer = new MemoryStream();
                return;
            }

            if (this.currentBlock.Compressed)
            {
                byte[] buffer = new byte[this.currentBlock.UncompressedLength];

                var inflater = new Inflater();

                inflater.SetInput(this.currentBlock.Content);
                inflater.Inflate(buffer);

                this.readBuffer = new MemoryStream(buffer);
            }
            else
            {
                this.readBuffer = new MemoryStream(this.currentBlock.Content);
            }
        }
Example #4
0
        public byte[] Send(byte[] payload)
        {
            // this doesn't need to be bigger than 1400, but meh, better safe than sorry
            byte[] result = new byte[1600];
            Locked = true;

            try
            {
                _aniDBSocket.SendTo(payload, _remoteIpEndPoint);
                EndPoint temp     = _remoteIpEndPoint;
                int      received = _aniDBSocket.ReceiveFrom(result, ref temp);

                if (received > 2 && result[0] == 0 && result[1] == 0)
                {
                    //deflate
                    byte[] buff  = new byte[65536];
                    byte[] input = new byte[received - 2];
                    Array.Copy(result, 2, input, 0, received - 2);
                    Inflater inf = new Inflater(false);
                    inf.SetInput(input);
                    inf.Inflate(buff);
                    result   = buff;
                    received = (int)inf.TotalOut;
                }

                Array.Resize(ref result, received);
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }

            Locked = false;
            return(result);
        }
Example #5
0
        private void TreatHeader(FileInArchive archFile)
        {
            MemoryStream memoryStream = new MemoryStream();

            byte[] buffer = new byte[4096];
            if ((int)archFile.descriptor.compressionMethod == 1)
            {
                try
                {
                    Inflater inflater = new Inflater();
                    inflater.SetInput(archFile.data_start_200);
                    inflater.Inflate(buffer);
                }
                catch (Exception ex)
                {
                    this.Error_FileTableEntry(archFile);
                }
                archFile.descriptor.extension = this.GetExtension(buffer);
            }
            else
            {
                if ((int)archFile.descriptor.compressionMethod != 0)
                {
                    return;
                }
                archFile.descriptor.extension = this.GetExtension(archFile.data_start_200);
            }
        }
Example #6
0
        public static BinaryReader Decompress(BinaryReader br, int size, int outsize)
        {
            if (input.Length < size)
            {
                input = new byte[size];
            }
            if (output.Length + 16 < outsize)
            {
                output = new byte[outsize + 16]; // Add 16 extra bytes to be able to detect uncompression overrun.
            }
            br.Read(input, 0, size);
            inf.Reset();
            inf.SetInput(input, 0, size);
            int decompressedSize = inf.Inflate(output);

            inf.Reset();

            ms.Position = 0;
            ms.Write(output, 0, outsize);
            ms.Position = 0;

            if (decompressedSize != outsize) // Check the size of the uncompressed data against what we expected
            {
                throw new Exception(String.Format("Unexpected Decompressed data size! CompressedSize={2:D} DecompressedSize={0:D} Expected Size={1:D}", decompressedSize, outsize, size));
            }

            return(compReader);
        }
Example #7
0
        public static int UnCompress(byte[] input, byte[] buffer, ref byte[] result)
        {
            var inflater = new Inflater();

            inflater.SetInput(input);

            buffer = buffer ?? new byte[BuffSize];
            MemoryStream ms;

            if (result != null)
            {
                ms = new MemoryStream(result);
            }
            else
            {
                ms = new MemoryStream(input.Length);
            }

            var length = 0;

            while (!inflater.IsFinished)
            {
                var count = inflater.Inflate(buffer);
                ms.Write(buffer, 0, count);
                length += count;
            }

            if (result == null)
            {
                result = ms.ToArray();
            }
            ms.Dispose();

            return(length);
        }
Example #8
0
 private void readChunkUnzip(Inflater inflater, byte[] buffer, int offset, int length)
 {
     try
     {
         do
         {
             int read = inflater.Inflate(buffer, offset, length);
             if (read <= 0)
             {
                 if (inflater.Finished())
                 {
                     throw new EOFException();
                 }
                 if (inflater.NeedsInput())
                 {
                     refillInflater(inflater);
                 }
                 else
                 {
                     throw new IOException("Can't inflate " + length + " bytes");
                 }
             }
             else
             {
                 offset += read;
                 length -= read;
             }
         } while (length > 0);
     }
     catch (DataFormatException ex)
     {
         throw (IOException)(new IOException("inflate error").InitCause(ex));
     }
 }
Example #9
0
        public static string Decompress(byte[] data)
        {
            if (data == null)
            {
                return("");
            }
            if (data.Length == 0)
            {
                return("");
            }
            Inflater inflater = new Inflater();

            inflater.SetInput(data);
            MemoryStream stream = new MemoryStream(data.Length);

            try
            {
                byte[] buf = new byte[0x400];
                while (!inflater.IsFinished)
                {
                    int count = inflater.Inflate(buf);
                    stream.Write(buf, 0, count);
                }
            }
            finally
            {
                stream.Close();
            }
            return(Encoding.Unicode.GetString(stream.ToArray()));
        }
Example #10
0
        /// <summary>
        /// Decompresses data into the byte array
        /// </summary>
        /// <param name ="b">
        /// The array to read and decompress data into
        /// </param>
        /// <param name ="off">
        /// The offset indicating where the data should be placed
        /// </param>
        /// <param name ="len">
        /// The number of bytes to decompress
        /// </param>
        /// <returns>The number of bytes read.  Zero signals the end of stream</returns>
        /// <exception cref="SharpZipBaseException">
        /// Inflater needs a dictionary
        /// </exception>
        public override int Read(byte[] b, int off, int len)
        {
            for (;;)
            {
                int count;
                try {
                    count = inf.Inflate(b, off, len);
                } catch (Exception e) {
                    throw new SharpZipBaseException(e.ToString());
                }

                if (count > 0)
                {
                    return(count);
                }

                if (inf.IsNeedingDictionary)
                {
                    throw new SharpZipBaseException("Need a dictionary");
                }
                else if (inf.IsFinished)
                {
                    return(0);
                }
                else if (inf.IsNeedingInput)
                {
                    Fill();
                }
                else
                {
                    throw new InvalidOperationException("Don't know what to do");
                }
            }
        }
Example #11
0
        /// <summary>
        /// 字符串解压缩
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Decompress(byte[] data)
        {
            if (data == null)
            {
                return("");
            }
            if (data.Length == 0)
            {
                return("");
            }

            Inflater f = new Inflater();

            f.SetInput(data);

            MemoryStream o = new MemoryStream(data.Length);

            try
            {
                byte[] buf = new byte[1024];
                while (!f.IsFinished)
                {
                    int got = f.Inflate(buf);
                    o.Write(buf, 0, got);
                }
            }
            finally
            {
                o.Close();
            }
            return(Encoding.Unicode.GetString(o.ToArray()));
        }
Example #12
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (inf.IsNeedingDictionary)
            {
                throw new SharpZipBaseException("Need a dictionary");
            }
            int num = count;

            while (true)
            {
                int num2 = inf.Inflate(buffer, offset, num);
                offset += num2;
                num    -= num2;
                if (num == 0 || inf.IsFinished)
                {
                    break;
                }
                if (inf.IsNeedingInput)
                {
                    Fill();
                }
                else if (num2 == 0)
                {
                    throw new ZipException("Dont know what to do");
                }
            }
            return(count - num);
        }
Example #13
0
        public static byte[] Decompress(byte[] input, int offset, int len)
        {
            byte[]   output     = new byte[1024];
            int      outputused = 0;
            Inflater inflater   = new Inflater();

            inflater.SetInput(input, offset, len);
            while (inflater.IsFinished == false)
            {
                if (inflater.IsNeedingInput)
                {
                    throw(new Exception("inflateData: input incomplete!"));
                }
                if (outputused == output.Length)
                {
                    byte[] newOutput = new byte[output.Length * 2];
                    Array.Copy(output, newOutput, output.Length);
                    output = newOutput;
                }
                try
                {
                    outputused += inflater.Inflate(output, outputused, output.Length - outputused);
                }
                catch (FormatException e)
                {
                    throw(new IOException(e.ToString()));
                }
            }
            inflater.Reset();
            byte[] realOutput = new byte[outputused];
            Array.Copy(output, realOutput, outputused);
            return(realOutput);
        }
            public void CopyTo(Stream output, Action <int> onProgress)
            {
                if (file.Flags.HasFlag(CABFlags.FileCompressed))
                {
                    var inf    = new Inflater(true);
                    var buffer = new byte[165535];
                    do
                    {
                        var bytesToExtract = currentVolume.ReadUInt16();
                        remainingInArchive -= 2;
                        toExtract          -= 2;
                        inf.SetInput(GetBytes(bytesToExtract));
                        toExtract -= bytesToExtract;
                        while (!inf.IsNeedingInput)
                        {
                            onProgress?.Invoke((int)(100 * output.Position / file.ExpandedSize));

                            var inflated = inf.Inflate(buffer);
                            output.Write(buffer, 0, inflated);
                        }

                        inf.Reset();
                    }while (toExtract > 0);
                }
                else
                {
                    do
                    {
                        onProgress?.Invoke((int)(100 * output.Position / file.ExpandedSize));

                        toExtract -= remainingInArchive;
                        output.Write(GetBytes(remainingInArchive), 0, (int)remainingInArchive);
                    }while (toExtract > 0);
                }
            }
        private int Decode(byte[] input, int inputLength, byte[] output, out Exception exception)
        {
            exception = null;
            if (_inflater == null)
            {
                if (input != null)
                {
                    // This is a non compressed stream, so simply copy over the bytes to the output
                    Array.Copy(input, output, input.Length);
                    return(input.Length);
                }

                return(0);
            }

            try {
                // If the input is null, it means keep processing the current input
                // (it could have filled the last output and still not be done)
                // Otherwise, set the new input
                if (input != null)
                {
                    _inflater.SetInput(input, 0, inputLength);
                }

                return(_inflater.Inflate(output));
            } catch (Exception e) {
                exception = e;
                Log.To.ChangeTracker.E(Tag, "Failed to read from changes feed, sending to callback...", e);
                return(-1);
            }
        }
Example #16
0
    public static int[] Inflate(byte[] compressed)
    {
        if (compressed == null)
        {
            throw new ArgumentNullException(nameof(compressed));
        }
        var inflater = new Inflater();

        inflater.SetInput(compressed);

        using var ms = new MemoryStream(compressed.Length);
        byte[] buf = new byte[1024];
        while (!inflater.IsFinished)
        {
            int count = inflater.Inflate(buf);
            ms.Write(buf, 0, count);
        }

        ms.Position = 0;

        var results = new int[(int)(ms.Length / 4)];

        using var br = new BinaryReader(ms);
        for (int i = 0; i < ms.Length >> 2; i++)
        {
            results[i] = br.ReadInt32();
        }
        return(results);
    }
Example #17
0
        private void ParseChapterTxtContents()
        {
            int destinationIndex = 0;

            byte[] bytes = new byte[this._TotalContentLen];
            byte[] buf   = new byte[32768];
            foreach (byte[] zippedContent in this._ZippedContentList)
            {
                Inflater inflater = new Inflater();
                inflater.SetInput(zippedContent);
                inflater.Inflate(buf);
                if (destinationIndex < bytes.Length)
                {
                    Array.Copy((Array)buf, 0, (Array)bytes, destinationIndex, (int)Math.Min(bytes.Length - destinationIndex, inflater.TotalOut));
                    destinationIndex += (int)inflater.TotalOut;
                }
            }
            for (int index1 = 0; index1 < this._ChaptersOff.Length; ++index1)
            {
                int    index2 = this._ChaptersOff[index1];
                int    count  = index1 >= this._ChaptersOff.Length - 1 ? bytes.Length - index2 : this._ChaptersOff[index1 + 1] - index2;
                string str    = this._Book.BookEncoding.GetString(bytes, index2, count);
                this._Book.Chapters[index1].Content = str.Replace("\x2029", "\r\n");
            }
            this._ZippedContentList.Clear();
        }
        /// <summary>
        /// Decompresses data into the byte array
        /// </summary>
        /// <param name ="b">
        /// the array to read and decompress data into
        /// </param>
        /// <param name ="off">
        /// the offset indicating where the data should be placed
        /// </param>
        /// <param name ="len">
        /// the number of bytes to decompress
        /// </param>
        public override int Read(byte[] b, int off, int len)
        {
            for (;;)
            {
                int count;
                try {
                    count = inf.Inflate(b, off, len);
                } catch (Exception dfe) {
                    throw new Exception(dfe.ToString());
                }

                if (count > 0)
                {
                    return(count);
                }

                if (inf.NeedsDictionary())
                {
                    throw new Exception("Need a dictionary");
                }
                else if (inf.Finished())
                {
                    return(-1);
                }
                else if (inf.NeedsInput())
                {
                    Fill();
                }
                else
                {
                    throw new Exception("Don't know what to do");
                }
            }
        }
Example #19
0
        public async ValueTask CopyDataToAsync(Stream output)
        {
            var bw = new BinaryWriter(output);

            WriteHeader(bw);

            using var fs = _bsa._streamFactory();
            using var br = new BinaryReader(fs);
            foreach (var chunk in _chunks)
            {
                var full         = new byte[chunk._fullSz];
                var isCompressed = chunk._packSz != 0;

                br.BaseStream.Seek((long)chunk._offset, SeekOrigin.Begin);

                if (!isCompressed)
                {
                    await br.BaseStream.ReadAsync(full, 0, full.Length);
                }
                else
                {
                    byte[] compressed = new byte[chunk._packSz];
                    await br.BaseStream.ReadAsync(compressed, 0, compressed.Length);

                    var inflater = new Inflater();
                    inflater.SetInput(compressed);
                    inflater.Inflate(full);
                }

                await bw.BaseStream.WriteAsync(full, 0, full.Length);
            }
        }
Example #20
0
        /// <summary>
        /// Reads the data.
        /// </summary>
        /// <param name="reader">Reader.</param>
        /// <param name="bitmapColorTableSize">Size of the bitmap color table.</param>
        /// <param name="bitmapWidth">Width of the bitmap.</param>
        /// <param name="bitmapHeight">Height of the bitmap.</param>
        /// <param name="toRead">To read.</param>
        public void ReadData(BufferedBinaryReader reader, byte bitmapColorTableSize,
                             ushort bitmapWidth, ushort bitmapHeight, int toRead)
        {
            int size = ((bitmapColorTableSize + 1) * 3) + (bitmapWidth * bitmapHeight);

            byte[] uncompressed = new byte[size];

            byte[]   compressed  = reader.ReadBytes(toRead);
            Inflater zipInflator = new Inflater();

            zipInflator.SetInput(compressed);
            zipInflator.Inflate(uncompressed, 0, size);

            int readed = 0;
            int offset = size;

            colorTableRGB = new RGB[bitmapColorTableSize + 1];
            for (int i = 0; i < bitmapColorTableSize + 1; i++)
            {
                byte red = uncompressed[readed];
                readed++;
                byte green = uncompressed[readed];
                readed++;
                byte blue = uncompressed[readed];
                readed++;
                colorTableRGB[i] = new RGB(red, green, blue);
                offset          -= 3;
            }

            colorMapPixelData = new byte[offset];
            for (int i = 0; i < offset; i++, readed++)
            {
                colorMapPixelData[i] = uncompressed[readed];
            }
        }
Example #21
0
    /// <summary>
    /// Runs the player logic.
    /// </summary>
    public async Task Run(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var bytesReceived =
                await Task.Factory.FromAsync(
                    (cb, s) => _socket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, 0, cb, s),
                    _socket.EndReceive,
                    null);

            if (bytesReceived == 0)
            {
                break;
            }

            Log.Debug("Received data from '{ClientIp}' ({Len} bytes)", Ip, bytesReceived);

            var packetSize = (_receiveBuffer[0] << 8) | _receiveBuffer[1];
            if (bytesReceived < (packetSize + 2))
            {
                continue;
            }

            var inflater = new Inflater();

            inflater.SetInput(_receiveBuffer, 2, packetSize);
            inflater.Inflate(_inflateBuffer, 0, 204800);

            /* Split the received data into packages, and handle them. */
            var messages = Encoding.UTF8.GetString(_inflateBuffer, 0, (int)inflater.TotalOut).Split((char)10);
            foreach (var message in messages)
            {
                if (message != string.Empty)
                {
                    Handle(message[0] - 32, message[1..]);
Example #22
0
        /// <summary>
        /// Performs inflate decompression on the given data.
        /// </summary>
        /// <param name="input">the data to decompress</param>
        /// <param name="output">the decompressed data</param>
        public static void DecompressZLib(byte[] input, byte[] output)
        {
            Inflater item = new Inflater();

            item.SetInput(input, 0, input.Length);
            item.Inflate(output, 0, output.Length);
        }
Example #23
0
        /// <summary>
        /// Decompress the byte array previously returned by
        ///  compress
        /// </summary>
        public static byte[] Decompress(sbyte[] value, int offset, int length)
        {
            // Create an expandable byte array to hold the decompressed data
            ByteArrayOutputStream bos = new ByteArrayOutputStream(length);

            Inflater decompressor = SharpZipLib.CreateInflater();

            try
            {
                decompressor.SetInput((byte[])(Array)value);

                // Decompress the data
                byte[] buf = new byte[1024];
                while (!decompressor.IsFinished)
                {
                    int count = decompressor.Inflate(buf);
                    bos.Write(buf, 0, count);
                }
            }
            finally
            {
            }

            return(bos.ToArray());
        }
Example #24
0
        public void CopyDataTo(Stream output)
        {
            var bw = new BinaryWriter(output);

            WriteHeader(bw);

            using (var fs = File.OpenRead(_bsa._filename))
                using (var br = new BinaryReader(fs))
                {
                    foreach (var chunk in _chunks)
                    {
                        var full         = new byte[chunk._fullSz];
                        var isCompressed = chunk._packSz != 0;

                        br.BaseStream.Seek((long)chunk._offset, SeekOrigin.Begin);

                        if (!isCompressed)
                        {
                            br.BaseStream.Read(full, 0, full.Length);
                        }
                        else
                        {
                            byte[] compressed = new byte[chunk._packSz];
                            br.BaseStream.Read(compressed, 0, compressed.Length);
                            var inflater = new Inflater();
                            inflater.SetInput(compressed);
                            inflater.Inflate(full);
                        }

                        bw.BaseStream.Write(full, 0, full.Length);
                    }
                }
        }
        /// <summary>Decompress the byte array previously returned by
        /// compress
        /// </summary>
        public static byte[] Decompress(byte[] value_Renamed)
        {
            // Create an expandable byte array to hold the decompressed data
            System.IO.MemoryStream bos = new System.IO.MemoryStream(value_Renamed.Length);

            Inflater decompressor = SharpZipLib.CreateInflater();

            try
            {
                decompressor.SetInput(value_Renamed);

                // Decompress the data
                byte[] buf = new byte[1024];
                while (!decompressor.IsFinished)
                {
                    int count = decompressor.Inflate(buf);
                    bos.Write(buf, 0, count);
                }
            }
            finally
            {
            }

            return(bos.ToArray());
        }
Example #26
0
 protected override void inflateVerify(int pos, Inflater inf)
 {
     while (!inf.IsFinished)
     {
         if (inf.IsNeedingInput)
         {
             inf.SetInput(_array, pos, _array.Length - pos);
             break;
         }
         inf.Inflate(VerifyGarbageBuffer, 0, VerifyGarbageBuffer.Length);
     }
     while (!inf.IsFinished && !inf.IsNeedingInput)
     {
         inf.Inflate(VerifyGarbageBuffer, 0, VerifyGarbageBuffer.Length);
     }
 }
Example #27
0
        public static byte[] Decompress(byte[] input, int offset, int len)
        {
            byte[]   sourceArray = new byte[0x400];
            int      num         = 0;
            Inflater inflater    = new Inflater();

            inflater.SetInput(input, offset, len);
            while (!inflater.IsFinished)
            {
                if (inflater.IsNeedingInput)
                {
                    throw new Exception("inflateData: input incomplete!");
                }
                if (num == sourceArray.Length)
                {
                    byte[] buffer2 = new byte[sourceArray.Length * 2];
                    Array.Copy(sourceArray, buffer2, sourceArray.Length);
                    sourceArray = buffer2;
                }
                try
                {
                    num += inflater.Inflate(sourceArray, num, sourceArray.Length - num);
                }
                catch (FormatException exception)
                {
                    throw new IOException(exception.ToString());
                }
            }
            inflater.Reset();
            byte[] destinationArray = new byte[num];
            Array.Copy(sourceArray, destinationArray, num);
            return(destinationArray);
        }
Example #28
0
        /// <summary>
        /// Reads decompressed data into the provided buffer byte array
        /// </summary>
        /// <param name ="buffer">
        /// The array to read and decompress data into
        /// </param>
        /// <param name ="offset">
        /// The offset indicating where the data should be placed
        /// </param>
        /// <param name ="count">
        /// The number of bytes to decompress
        /// </param>
        /// <returns>The number of bytes read.  Zero signals the end of stream</returns>
        /// <exception cref="SharpZipBaseException">
        /// Inflater needs a dictionary
        /// </exception>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (inf.IsNeedingDictionary)
            {
                throw new SharpZipBaseException("Need a dictionary");
            }

            int remainingBytes = count;

            while (true)
            {
                int bytesRead = inf.Inflate(buffer, offset, remainingBytes);
                offset         += bytesRead;
                remainingBytes -= bytesRead;

                if (remainingBytes == 0 || inf.IsFinished)
                {
                    break;
                }

                if (inf.IsNeedingInput)
                {
                    Fill();
                }
                else if (bytesRead == 0)
                {
                    throw new ZipException("Dont know what to do");
                }
            }
            return(count - remainingBytes);
        }
Example #29
0
 protected void Decompress()
 {
     byte[] data = this.Data;
     if (this.IsCompressed)
     {
         int      num2;
         Inflater inflater         = new Inflater();
         ushort   compressedOffset = this.CompressedOffset;
         inflater.SetInput(data, compressedOffset, data.Length - compressedOffset);
         List <KeyValuePair <byte[], int> > list = new List <KeyValuePair <byte[], int> >();
         int num3 = 0;
         do
         {
             byte[] buffer = new byte[0x28000];
             num2 = inflater.Inflate(buffer);
             list.Add(new KeyValuePair <byte[], int>(buffer, num2));
             num3 += num2;
         }while (num2 != 0);
         this.Data = new byte[num3 + compressedOffset];
         Array.Copy(data, 0, this.Data, 0, compressedOffset);
         int destinationIndex = compressedOffset;
         foreach (KeyValuePair <byte[], int> pair in list)
         {
             Array.Copy(pair.Key, 0, this.Data, destinationIndex, pair.Value);
             destinationIndex += pair.Value;
         }
         this.IsCompressed = false;
         Array.Copy(BitConverter.GetBytes(this.Data.Length), 0, this.Data, 0, 4);
     }
 }
Example #30
0
            public void CopyTo(Stream dest)
            {
                if ((fileDes.Flags & FileCompressed) != 0)
                {
                    var inf    = new Inflater(true);
                    var buffer = new byte[165535];
                    do
                    {
                        var bytesToExtract = cabFile.ReadUInt16();
                        RemainingArchiveStream -= 2u;
                        RemainingFileStream    -= 2u;
                        inf.SetInput(GetBytes(bytesToExtract));
                        RemainingFileStream -= bytesToExtract;
                        while (!inf.IsNeedingInput)
                        {
                            var inflated = inf.Inflate(buffer);
                            dest.Write(buffer, 0, inflated);
                        }

                        inf.Reset();
                    }while (RemainingFileStream > 0);
                }
                else
                {
                    do
                    {
                        RemainingFileStream -= RemainingArchiveStream;
                        dest.Write(GetBytes(RemainingArchiveStream), 0, (int)RemainingArchiveStream);
                    }while (RemainingFileStream > 0);
                }
            }
Example #31
0
        public static void ReadCompressed(Stream s, List<string> classnames)
        {
            long start = s.Position;
            BinaryReader br = new BinaryReader(s);
            byte[] mem = new byte[(int)s.Length + 8];
            byte[] buf = new byte[3];
            s.Read(buf, 0, 3);
            s.Seek(start+4, SeekOrigin.Begin);
            int size = br.ReadInt32();
            s.Seek(start+8, SeekOrigin.Begin);
            s.Read(mem, 0, (int)s.Length);
            s.Close();
            br.Close();

            try
            {
                s = new MemoryStream(mem);
                if (Encoding.Default.GetString(buf) == "CWS")
                {
                    Inflater i = new Inflater();
                    i.SetInput(mem);
                    byte[] mem2 = new byte[size + 8];
                    i.Inflate(mem2, 8, size);
                    s = new MemoryStream(mem2);
                    mem = new byte[0];
                }

                s.Seek(0x15, SeekOrigin.Begin);
                br = new BinaryReader(s);
                while (br.BaseStream.Position < br.BaseStream.Length)
                {
                    uint taglen = br.ReadUInt16();
                    uint len = taglen & 0x3f;
                    uint tag = (taglen - len) / 64;
                    if (len == 63)
                        len = br.ReadUInt32();
                    start = br.BaseStream.Position;

                    if (tag == 82)
                    {
                        FlashABC fabc = new FlashABC(br.BaseStream, len);
                        fabc.FindClasses(classnames);
                    }
                    br.BaseStream.Seek(start + len, SeekOrigin.Begin);
                }
                br.Close();
            }
            catch (Exception e)
            {
                Debug.Print(e.StackTrace);
                return;
            }
        }
Example #32
0
        public FlashReadFile(string file)
        {
            FileStream fs = new FileStream(file, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            byte[] mem = new byte[(int)fs.Length + 8];
            byte[] buf = new byte[3];
            fs.Read(buf, 0, 3);
            fs.Seek(4, SeekOrigin.Begin);
            int size = br.ReadInt32();
            fs.Seek(8, SeekOrigin.Begin);
            fs.Read(mem, 0, (int)fs.Length);
            fs.Close();
            br.Close();

            s = new MemoryStream(mem);
            if (Encoding.Default.GetString(buf) == "CWS")
            {
                Inflater i = new Inflater();
                i.SetInput(mem);
                byte[] mem2 = new byte[size + 8];
                i.Inflate(mem2, 8, size);
                s = new MemoryStream(mem2);
                mem = new byte[0];
            }
            s.Seek(0x15, SeekOrigin.Begin);
            br = new BinaryReader(s);
            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                uint taglen = br.ReadUInt16();
                uint len = taglen & 0x3f;
                uint tag = (taglen - len) / 64;
                if (len == 63)
                    len = br.ReadUInt32();
                long start = br.BaseStream.Position;

                if (tag == 82)
                {
                    FlashABC fabc = new FlashABC(br.BaseStream, len);
                    List<string> classnames = new List<string>();
                    classnames.Add("cPlayerData");
                    fabc.FindClasses(classnames);
                }
                //Debug.Print("{0} {1}", tag, len+2);
                br.BaseStream.Seek(start + len, SeekOrigin.Begin);
            }
            fClass.InitClasses();
            br.Close();
        }
Example #33
0
    static int Inflate(Inflater inf, byte [] src, byte [] dest)
    {
        int offset, length, remain;

        inf.Reset ();
        inf.SetInput (src);

        offset = 0;
        while (!inf.IsNeedingInput) {
            remain = Math.Min (dest.Length - offset, BlockSize);
            if (remain == 0)
                break;

            length = inf.Inflate (dest, offset, remain);
            offset += length;
        }

        return inf.TotalOut;
    }
Example #34
0
 public static byte[] Unzip(byte[] buffer)
 {
     Assembly callingAssembly = Assembly.GetCallingAssembly();
     Assembly executingAssembly = Assembly.GetExecutingAssembly();
     if ((callingAssembly != executingAssembly) && !PublicKeysMatch(executingAssembly, callingAssembly))
     {
         return null;
     }
     ZipStream stream = new ZipStream(buffer);
     byte[] buf = new byte[0];
     int num = stream.ReadInt();
     if (num == 0x4034b50)
     {
         short num2 = (short) stream.ReadShort();
         int num3 = stream.ReadShort();
         int num4 = stream.ReadShort();
         if (((num != 0x4034b50) || (num2 != 20)) || ((num3 != 0) || (num4 != 8)))
         {
             throw new FormatException("Wrong Header Signature");
         }
         stream.ReadInt();
         stream.ReadInt();
         stream.ReadInt();
         int num5 = stream.ReadInt();
         int count = stream.ReadShort();
         int num7 = stream.ReadShort();
         if (count > 0)
         {
             byte[] buffer3 = new byte[count];
             stream.Read(buffer3, 0, count);
         }
         if (num7 > 0)
         {
             byte[] buffer4 = new byte[num7];
             stream.Read(buffer4, 0, num7);
         }
         byte[] buffer5 = new byte[stream.Length - stream.Position];
         stream.Read(buffer5, 0, buffer5.Length);
         Inflater inflater = new Inflater(buffer5);
         buf = new byte[num5];
         inflater.Inflate(buf, 0, buf.Length);
         buffer5 = null;
     }
     else
     {
         int num8 = num >> 0x18;
         num -= num8 << 0x18;
         if (num == 0x7d7a7b)
         {
             switch (num8)
             {
                 case 1:
                 {
                     int num12;
                     int num9 = stream.ReadInt();
                     buf = new byte[num9];
                     for (int i = 0; i < num9; i += num12)
                     {
                         int num11 = stream.ReadInt();
                         num12 = stream.ReadInt();
                         byte[] buffer6 = new byte[num11];
                         stream.Read(buffer6, 0, buffer6.Length);
                         new Inflater(buffer6).Inflate(buf, i, num12);
                     }
                     break;
                 }
                 case 2:
                 {
                     byte[] buffer7 = new byte[] { 0x94, 0xad, 0xc3, 0x85, 0xa5, 0x2a, 0xbd, 9 };
                     byte[] buffer8 = new byte[] { 0xbf, 0x45, 3, 0x1a, 0x41, 80, 14, 0xbf };
                     using (ICryptoTransform transform = GetDesTransform(buffer7, buffer8, true))
                     {
                         buf = Unzip(transform.TransformFinalBlock(buffer, 4, buffer.Length - 4));
                     }
                     break;
                 }
             }
             if (num8 != 3)
             {
                 goto Label_026B;
             }
             byte[] key = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
             byte[] iv = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 };
             using (ICryptoTransform transform2 = GetAesTransform(key, iv, true))
             {
                 buf = Unzip(transform2.TransformFinalBlock(buffer, 4, buffer.Length - 4));
                 goto Label_026B;
             }
         }
         throw new FormatException("Unknown Header");
     }
 Label_026B:
     stream.Close();
     stream = null;
     return buf;
 }
Example #35
0
 private void decompress(AnyObjectId id, Inflater inf, int p)
 {
     try
     {
         while (!inf.IsFinished)
             p += inf.Inflate(bytes, p, objectSize - p);
     }
     catch (IOException dfe)
     {
         CorruptObjectException coe;
         coe = new CorruptObjectException(id, "bad stream", dfe);
         throw coe;
     }
     if (p != objectSize)
         throw new CorruptObjectException(id, "incorrect Length");
 }
Example #36
0
        public override void Read(hsStream s, hsResMgr mgr)
        {
            base.Read(s, mgr);

            // Cache it.
            fVersion = mgr.Version;

            // Cyan stores these values, but we're just going to
            //     save the stream and have fun with it...
            fBuffer = new byte[s.ReadInt()];
            Compression type = (Compression)s.ReadByte();
            uint len = s.ReadUInt();

            if (type == Compression.kZlib) {
                short streamType = s.ReadShort();
                byte[] buf = s.ReadBytes((int)len - 2);

                // Create a zlib-compatible inflator
                // Note: incoming has no zlib header/footer
                //       System.IO.Compression sucks.
                Inflater zlib = new Inflater(true);
                zlib.Inflate(buf);

                Buffer.BlockCopy(BitConverter.GetBytes(streamType), 0, fBuffer, 0, 2);
                Buffer.BlockCopy(buf, 0, fBuffer, 2, buf.Length);
            } else
                fBuffer = s.ReadBytes((int)len);
        }
Example #37
0
        void CheckReader()
        {
            if (reader == null) {
                if (!record.IsCompressed)
                    throw new InvalidOperationException();
                int compressedSize = checked((int)record.Size);
                int uncompressedSize = checked((int)compressedReader.ReadUInt32());

                byte[] compressedData = new byte[compressedSize];
                byte[] uncompressedData = new byte[uncompressedSize];

                int compressedRead = compressedReader.Read(compressedData, 0, compressedSize);
                Inflater inflater = new Inflater();
                inflater.SetInput(compressedData);
                int uncompressedRead = inflater.Inflate(uncompressedData, 0, uncompressedSize);
                reader = new BinaryReader(new MemoryStream(uncompressedData, false));
                endOffset = uncompressedSize;
            }
        }
        public static string Decompress(String str)
        {
            // Initialize decompressor.
            byte[] compressedBytes = Convert.FromBase64String(str);
            Inflater decompressor = new Inflater();
            decompressor.SetInput(compressedBytes); // Give the decompressor the
            // data to decompress.

            byte[] ret = null;

            using (MemoryStream memStream = new MemoryStream(compressedBytes.Length))
            {
                // Decompress the data
                byte[] buf = new byte[compressedBytes.Length + 100];
                while (!decompressor.IsFinished)
                {
                    memStream.Write(buf, 0, decompressor.Inflate(buf));
                }

                memStream.Close();
                ret = memStream.ToArray();
            }

            return ASCIIEncoding.UTF8.GetString(ret);
        }
Example #39
0
        private bool CheckSwf(bool is_comp)
        {
            this.format = MediaFormat.SWF;
            this.reader = new BinaryReader(this.stream);

            if (is_comp) {
                int size = -1;

                this.reader.BaseStream.Position = 4; // Skip head
                size = Convert.ToInt32(this.reader.ReadUInt32());

                // Read swf head
                byte[] uncompressed = new byte[size];
                this.reader.BaseStream.Position = 0;
                this.reader.Read(uncompressed, 0, 8);

                // Read compressed data
                byte[] compressed = this.reader.ReadBytes(size);
                this.stream.Close(); // Close the old stream

                // Uncompress
                Inflater zipInflator = new Inflater();
                zipInflator.SetInput(compressed);
                zipInflator.Inflate(uncompressed, 8, size - 8);

                // Setup new uncompressed reader
                this.reader = new BinaryReader(new MemoryStream(uncompressed));
                this.reader.BaseStream.Position = 0;
            }

            // Skip header signature/version etc etc
            this.reader.BaseStream.Position = 8;

            // Read rect
            uint bits = ReadUBits(5);
            ReadSBits(bits); // Read xmin
            this.width = ReadSBits(bits) / 20; // Read xmax
            ReadSBits(bits); // Read ymin
            this.height = ReadSBits(bits) / 20; // Read ymax

            return true;
        }