Exemple #1
0
        /// <summary>
        /// </summary>
        /// <param name="fname">
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <typeparam name="TU">
        /// </typeparam>
        /// <returns>
        /// </returns>
        public static Dictionary <T, TU> UncompressData <T, TU>(string fname)
        {
            var    tempList   = new Dictionary <T, TU>();
            Stream fileStream = new FileStream(fname, FileMode.Open);

            ZlibStream inputStream = new ZlibStream(fileStream, CompressionMode.Decompress);

            inputStream.Seek(0, SeekOrigin.Begin);
            BinaryReader binaryReader  = new BinaryReader(inputStream);
            byte         versionlength = binaryReader.ReadByte();

            char[] version = new char[versionlength];
            version = binaryReader.ReadChars(versionlength);

            // TODO: Check version and print a warning if not same as config.xml's
            MessagePackSerializer <Dictionary <T, TU> > messagePackSerializer =
                MessagePackSerializer.Create <Dictionary <T, TU> >();

            var buffer = new byte[4];

            inputStream.Read(buffer, 0, 4);

            inputStream.Read(buffer, 0, 4);

            return(messagePackSerializer.Unpack(inputStream));
        }
Exemple #2
0
        public void SendTightPixelFormat()
        {
            TightEncoder encoder = new TightEncoder(Mock.Of <IVncServerSession>())
            {
                Compression = TightCompression.Basic,
            };

            byte[] raw = null;

            using (MemoryStream output = new MemoryStream())
            {
                var contents = new byte[]
                {
                    // A 2x2 framebuffer in
                    // BGRX format
                    0x01, 0x02, 0x03, 0x04,
                    0x01, 0x02, 0x03, 0x04,
                    0x01, 0x02, 0x03, 0x04,
                    0x01, 0x02, 0x03, 0x04,
                };

                encoder.Send(output, VncPixelFormat.RGB32, new VncRectangle(0, 0, 2, 2), contents);
                raw = output.ToArray();
            }

            // First byte:
            // - Basic compression
            // - Use stream 0
            // - Reset stream 0
            Assert.Equal(0b0000_0001, raw[0]);

            byte[] expectedZlibData = new byte[] { 0x78, 0x9c, 0x62, 0x66, 0x62, 0x64, 0x86, 0x20, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x62, 0x02, 0x00, 0x00, 0x00, 0xff, 0xff, 0x62, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff };

            byte[] actualZlibData = new byte[raw.Length - 2];
            Array.Copy(raw, 2, actualZlibData, 0, raw.Length - 2);

            Assert.Equal((byte)expectedZlibData.Length, raw[1]);
            Assert.Equal(expectedZlibData, actualZlibData);

            // Decompress the data and make sure the pixel format is correct (RGB, the 'VncPixelFormat.RGB32' actually represents BGRX)
            using (var compressedStream = new MemoryStream(actualZlibData))
                using (var stream = new ZlibStream(compressedStream, CompressionMode.Decompress))
                {
                    byte[] decompressed = new byte[0x09];
                    Assert.Equal(9, stream.Read(decompressed, 0, 9));

                    // Make sure all data was read
                    Assert.Equal(0, stream.Read(decompressed, 0, 0));

                    var expectedDecompressedData = new byte[]
                    {
                        0x03, 0x02, 0x01,
                        0x03, 0x02, 0x01,
                        0x03, 0x02, 0x01,
                    };

                    Assert.Equal(expectedDecompressedData, decompressed);
                }
        }
Exemple #3
0
 internal static void UncompressBuffer(Stream compressedStream, Stream outStream)
 {
     using (var decompressor = new ZlibStream(compressedStream, CompressionMode.Decompress))
         using (Leayal.ByteBuffer buffer = new Leayal.ByteBuffer(1024))
         {
             int read = decompressor.Read(buffer, 0, buffer.Length);
             while (read > 0)
             {
                 outStream.Write(buffer, 0, read);
                 read = decompressor.Read(buffer, 0, buffer.Length);
             }
         }
 }
        public Packfile(Stream stream, bool isStr2)
        {
            IsStr2 = isStr2;
            stream.Seek(0, SeekOrigin.Begin);
            FileData = stream.ReadStruct <PackfileFileData>();

            m_Files = new List <IPackfileEntry>();

            uint runningPosition = 0;
            List <PackfileEntryFileData> entryFileData = new List <PackfileEntryFileData>();

            for (int i = 0; i < FileData.NumFiles; i++)
            {
                PackfileEntryFileData data = stream.ReadStruct <PackfileEntryFileData>();

                if (IsCondensed && IsCompressed)
                {
                    data.Flags       = 0;
                    data.Start       = runningPosition;
                    runningPosition += data.Size;
                }
                else if (IsCondensed)
                {
                    data.Start       = runningPosition;
                    runningPosition += data.Size.Align(16);
                }

                entryFileData.Add(data);
            }

            for (int i = 0; i < FileData.NumFiles; i++)
            {
                stream.Align(2);
                string filename = stream.ReadAsciiNullTerminatedString();
                stream.Seek(1, SeekOrigin.Current);
                m_Files.Add(new PackfileEntry(this, entryFileData[i], filename));
                stream.Align(2);
            }

            if (IsCondensed && IsCompressed)
            {
                DataOffset = 0;
                byte[] compressedData = new byte[FileData.CompressedDataSize];
                stream.Read(compressedData, 0, (int)FileData.CompressedDataSize);
                using (MemoryStream tempStream = new MemoryStream(compressedData))
                {
                    using (Stream s = new ZlibStream(tempStream, CompressionMode.Decompress, true))
                    {
                        byte[] uncompressedData = new byte[FileData.DataSize];
                        s.Read(uncompressedData, 0, (int)FileData.DataSize);
                        DataStream = new MemoryStream(uncompressedData);
                    }
                }
            }
            else
            {
                DataStream = stream;
                DataOffset = stream.Position;
            }
        }
Exemple #5
0
        public static void Decompress(byte[] compressed, int compressedOffset, int compressedSize, byte[] uncompressed, int uncompressedOffset, int uncompressedSize, CompressionMethod method, FArchive?reader = null)
        {
            using var srcStream = new MemoryStream(compressed, compressedOffset, compressedSize, false)
                  {
                      Position = 0
                  };
            switch (method)
            {
            case CompressionMethod.None:
                Buffer.BlockCopy(compressed, compressedOffset, uncompressed, uncompressedOffset, compressedSize);
                return;

            case CompressionMethod.Zlib:
                var zlib = new ZlibStream(srcStream, CompressionMode.Decompress);
                zlib.Read(uncompressed, uncompressedOffset, uncompressedSize);
                zlib.Dispose();
                return;

            case CompressionMethod.Gzip:
                var gzip = new GZipStream(srcStream, CompressionMode.Decompress);
                gzip.Read(uncompressed, uncompressedOffset, uncompressedSize);
                gzip.Dispose();
                return;

            case CompressionMethod.Oodle:
                Oodle.Decompress(compressed, compressedOffset, compressedSize, uncompressed, uncompressedOffset, uncompressedSize, reader);
                return;

            case CompressionMethod.LZ4:
                var uncompressedBuffer = new byte[uncompressedSize + uncompressedSize / 255 + 16];     // LZ4_compressBound(uncompressedSize)
                int result;
#if USE_LZ4_NATIVE_LIB
                unsafe
                {
                    fixed(byte *compressedPtr = compressed, uncompressedBufferPtr = uncompressedBuffer)
                    {
                        result = LZ4.LZ4_decompress_safe(compressedPtr + compressedOffset, uncompressedBufferPtr, compressedSize, uncompressedBuffer.Length);
                    }
                }
#else
                result = LZ4Codec.Decode(compressed, compressedOffset, compressedSize, uncompressedBuffer, 0, uncompressedBuffer.Length);
#endif
                Buffer.BlockCopy(uncompressedBuffer, 0, uncompressed, uncompressedOffset, uncompressedSize);
                if (result != uncompressedSize)
                {
                    throw new FileLoadException($"Failed to decompress LZ4 data (Expected: {uncompressedSize}, Result: {result})");
                }
                return;

            default:
                if (reader != null)
                {
                    throw new UnknownCompressionMethodException(reader, $"Compression method \"{method}\" is unknown");
                }
                else
                {
                    throw new UnknownCompressionMethodException($"Compression method \"{method}\" is unknown");
                }
            }
        }
        void _dplay_GotMessage(Session sess, byte[] message)
        {
            // Decompress the message if it is compressed.
            if (message[0] == FLMsgType.MSG_TYPE_COMPRESSED)
            {
                using (var ms = new MemoryStream(message, 0, message.Length))
                {
                    using (var zs = new ZlibStream(ms, CompressionMode.Decompress))
                    {
                        var buf       = new byte[32767];
                        int msgLength = zs.Read(buf, 0, buf.Length);
                        Array.Resize(ref buf, msgLength);
                        message = buf;
                    }
                }
            }

            // Otherwise dispatch the message to the controller.
            if (message[0] != 0x01) //not a typo, log junk cleaning
            {
                _log.AddLog(LogType.FL_MSG, "c>s client={0} rx={1}", sess.Client, message);
            }

            //AddEvent(new DPSessionRxMessageFromClient(sess, message));


            if (!Players.ContainsKey(sess))
            {
                return;
            }
            var player = Players[sess];

            //player.Runner.AddEvent(new DPGameRunnerRxMsgEvent(player, message));
            player.OnRxMsgToRunner(message);
        }
        public void TestInvalidChecksum()
        {
            byte[] testData = Encoding.ASCII.GetBytes("This is a test string");

            MemoryStream compressedStream = new MemoryStream();

            using (ZlibStream zs = new ZlibStream(compressedStream, CompressionMode.Compress, true))
            {
                zs.Write(testData, 0, testData.Length);
            }

            compressedStream.Seek(-2, SeekOrigin.End);
            compressedStream.Write(new byte[] { 0, 0 }, 0, 2);

            compressedStream.Position = 0;
            Assert.Throws <InvalidDataException>(() =>
            {
                using (ZlibStream uzs = new ZlibStream(compressedStream, CompressionMode.Decompress, true))
                {
                    byte[] outData = new byte[testData.Length];
                    uzs.Read(outData, 0, outData.Length);
                    Assert.Equal(testData, outData);

                    // Should be end of stream
                    Assert.Equal(-1, uzs.ReadByte());
                }
            });
        }
Exemple #8
0
 /// <summary>
 /// Decompresses the provided data, returning the inflated result.
 /// </summary>
 /// <param name="data">the deflated picture data.</param>
 /// <returns>the inflated picture data.</returns>
 private static byte[] InflatePictureData(byte[] data)
 {
     using (MemoryStream out1 = new MemoryStream())
     {
         try
         {
             using (MemoryStream ms = new MemoryStream(data))
             {
                 using (ZlibStream in1 = new ZlibStream(ms, CompressionMode.Decompress))
                 {
                     byte[] buf = new byte[4096];
                     int    ReadBytes;
                     while ((ReadBytes = in1.Read(buf, 0, buf.Length)) > 0)
                     {
                         out1.Write(buf, 0, ReadBytes);
                     }
                     return(out1.ToArray());
                 }
             }
         }
         catch (IOException e)
         {
             log.Log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
             return(data);
         }
     }
 }
        //WARNING
        //The sender is DPlaySession
        public void Handle(byte[] message)
        {
            if (message[0] == FLMsgType.MSG_TYPE_COMPRESSED)
            {
                using (var ms = new MemoryStream(message, 0, message.Length))
                {
                    using (var zs = new ZlibStream(ms, CompressionMode.Decompress))
                    {
                        var buf       = new byte[32767];
                        var msgLength = zs.Read(buf, 0, buf.Length);
                        Array.Resize(ref buf, msgLength);
                        message = buf;
                    }
                }
            }

            // Otherwise dispatch the message to the controller.
            if (message[0] != 0x01) //not a typo, log junk cleaning
            {
                _log.Debug("rxMessage {0}: {1}", Sender.Path.Name, BitConverter.ToString(message));
            }

            //FLServer.DPServer._dplay_GotMessage
            _state.Tell(message, Sender);
        }
Exemple #10
0
        private void FillImageContent()
        {
            byte[] rawContent = GetRawContent();

            // HACK: Detect compressed images.  In reality there should be some way to determine
            //       this from the first 32 bytes, but I can't see any similarity between all the
            //       samples I have obtained, nor any similarity in the data block contents.
            if (MatchSignature(rawContent, COMPRESSED1, 32) || MatchSignature(rawContent, COMPRESSED2, 32))
            {
                try
                {
                    ZlibStream   gzip = new ZlibStream(new MemoryStream(rawContent, 33, rawContent.Length - 33), CompressionMode.Decompress);
                    MemoryStream out1 = new MemoryStream();
                    byte[]       buf  = new byte[4096];
                    int          readBytes;
                    while ((readBytes = gzip.Read(buf, 0, 4096)) > 0)
                    {
                        out1.Write(buf, 0, readBytes);
                    }
                    content = out1.ToArray();
                }
                catch (IOException)
                {
                    // Problems Reading from the actual MemoryStream should never happen
                    // so this will only ever be a ZipException.
                    //log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
                }
            }
            else
            {
                // Raw data is not compressed.
                content = rawContent;
            }
        }
Exemple #11
0
        /// <summary>
        ///     Receive a message from a freelancer client and dispatch it to a controller for processing.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="msg"></param>
        public void dps_Receive(Session session, byte[] msg)
        {
            // Decompress the message if it is compressed.
            if (msg[0] == FLMsgType.MSG_TYPE_COMPRESSED)
            {
                using (var ms = new MemoryStream(msg, 0, msg.Length))
                {
                    using (var zs = new ZlibStream(ms, CompressionMode.Decompress))
                    {
                        var buf       = new byte[32767];
                        int msgLength = zs.Read(buf, 0, buf.Length);
                        Array.Resize(ref buf, msgLength);
                        msg = buf;
                    }
                }
            }

            // Otherwise dispatch the message to the controller.
            if (msg[0] != 0x01)
            {
                _log.AddLog(LogType.FL_MSG, "c>s client={0} rx={1}", session.Client, msg);
            }

            AddEvent(new DPSessionRxMessageFromClient(session, msg));
        }
        public void Should_compress_and_decompress_both_ways()
        {
            var text = "Interoperability is so much fun!";

            using var output = new MemoryStream();
            using (var compressOutput = new DeflaterOutputStream(output))
            {
                compressOutput.Write(Encoding.UTF8.GetBytes(text));
                compressOutput.Flush();
            }

            output.Flush();

            var bytes = output.ToArray();

            using var input            = new MemoryStream(bytes);
            using var decompressStream = new ZlibStream(input, CompressionMode.Decompress);

            var buffer = new byte[16384];
            var length = decompressStream.Read(buffer, 0, buffer.Length);

            var result = Encoding.UTF8.GetString(buffer, 0, length);

            Assert.That(result, Is.EqualTo(text));
        }
Exemple #13
0
 internal static byte[] UncompressBuffer(byte[] compressed)
 {
     using (var input = new MemoryStream(compressed))
         using (var output = new RecyclableMemoryStream())
             using (var decompressor = new ZlibStream(input, CompressionMode.Decompress))
                 using (Leayal.ByteBuffer buffer = new Leayal.ByteBuffer(1024))
                 {
                     int read = decompressor.Read(buffer, 0, buffer.Length);
                     while (read > 0)
                     {
                         output.Write(buffer, 0, read);
                         read = decompressor.Read(buffer, 0, buffer.Length);
                     }
                     return(output.ToArray());
                 }
 }
        void _dplay_GotMessage(Session sess, byte[] message)
        {
            switch (message[0])
            {
            // Decompress the message if it is compressed.
            case FLMsgType.MsgTypeCompressed:
                using (var ms = new MemoryStream(message, 0, message.Length))
                {
                    // TODO: it should be slow
                    using (var zs = new ZlibStream(ms, CompressionMode.Decompress))
                    {
                        var buf       = new byte[32767];
                        int msgLength = zs.Read(buf, 0, buf.Length);
                        Array.Resize(ref buf, msgLength);
                        message = buf;
                    }
                }
                break;

            case 0x01:
                return;
                // Otherwise dispatch the message to the controller.
            }


            Logger.AddLog(LogType.FLMsg, "c>s client={0} rx={1}", sess.Client, message);


            _pump.MessageFromClient(sess.DPlayID, message);
        }
Exemple #15
0
 public static Action <byte[]> CreateCompressedBinaryTableProcess(Action <MemoryStream> create)
 {
     return(delegate(byte[] bytes)
     {
         //IL_001a: Unknown result type (might be due to invalid IL or missing references)
         //IL_001f: Expected O, but got Unknown
         MemoryStream memoryStream = new MemoryStream();
         using (MemoryStream memoryStream2 = new MemoryStream(bytes))
         {
             byte[] array = new byte[1024];
             ZlibStream val = new ZlibStream((Stream)memoryStream2, 1);
             try
             {
                 try
                 {
                     int count;
                     while ((count = val.Read(array, 0, array.Length)) != 0)
                     {
                         memoryStream.Write(array, 0, count);
                     }
                 }
                 finally
                 {
                     ((IDisposable)val)?.Dispose();
                 }
             }
             finally
             {
                 ((IDisposable)val)?.Dispose();
             }
         }
         memoryStream.Seek(0L, SeekOrigin.Begin);
         create(memoryStream);
     });
 }
Exemple #16
0
        /// <summary>
        /// Decompresses the provided data, returning the inflated result.
        /// </summary>
        /// <param name="data">the deflated picture data.</param>
        /// <returns>the inflated picture data.</returns>
        private static byte[] InflatePictureData(byte[] data)
        {
            MemoryStream out1 = new MemoryStream();
            ZlibStream   in1  = null;

            try
            {
                in1 = new ZlibStream(
                    new MemoryStream(data), CompressionMode.Decompress);

                byte[] buf = new byte[4096];
                int    ReadBytes;
                while ((ReadBytes = in1.Read(buf, 0, buf.Length)) > 0)
                {
                    out1.Write(buf, 0, ReadBytes);
                }
                return(out1.ToArray());
            }
            catch (IOException e)
            {
                log.Log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
                return(data);
            }
            finally
            {
                out1.Close();
                if (in1 != null)
                {
                    in1.Close();
                }
            }
        }
Exemple #17
0
            private T ConstructWrapper(int pos)
            {
                ReadOnlyMemorySlice <byte> slice = this._data.Slice(pos);
                var majorMeta = _package.MetaData.Constants.MajorRecord(slice);

                if (majorMeta.IsCompressed)
                {
                    uint   uncompressedLength = BinaryPrimitives.ReadUInt32LittleEndian(slice.Slice(majorMeta.HeaderLength));
                    byte[] buf = new byte[majorMeta.HeaderLength + checked ((int)uncompressedLength)];
                    // Copy major meta bytes over
                    slice.Span.Slice(0, majorMeta.HeaderLength).CopyTo(buf.AsSpan());
                    // Set length bytes
                    BinaryPrimitives.WriteUInt32LittleEndian(buf.AsSpan().Slice(Constants.HeaderLength), uncompressedLength);
                    // Remove compression flag
                    BinaryPrimitives.WriteInt32LittleEndian(buf.AsSpan().Slice(_package.MetaData.Constants.MajorConstants.FlagLocationOffset), majorMeta.MajorRecordFlags & ~Constants.CompressedFlag);
                    // Copy uncompressed data over
                    using (var stream = new ZlibStream(new ByteMemorySliceStream(slice.Slice(majorMeta.HeaderLength + 4)), CompressionMode.Decompress))
                    {
                        stream.Read(buf, majorMeta.HeaderLength, checked ((int)uncompressedLength));
                    }
                    slice = new MemorySlice <byte>(buf);
                }
                return(LoquiBinaryOverlayTranslation <T> .Create(
                           stream : new OverlayStream(this._data.Slice(pos), _package),
                           package : _package,
                           recordTypeConverter : null));
            }
Exemple #18
0
        // Decompresses the given buffer based on the compression style and algorithm currently used by the parser.
        // The result is placed back in the buffer that was sent to this method.
        private void Decompress(ref byte[] buffer)
        {
            if (CompressionAlgorithm == CompressionAlgorithm.None || CompressionStyle == CompressionStyle.None)
            {
                return;
            }

            byte[] readBuffer = new byte[65536];

            using (BlockAllocatedMemoryStream readStream = new BlockAllocatedMemoryStream())
            {
                int readAmount;

                // Faster here to use provided buffer as non-expandable memory stream
                using (MemoryStream bufferStream = new MemoryStream(buffer))
                {
                    using (ZlibStream inflater = new ZlibStream(bufferStream, CompressionMode.Decompress))
                    {
                        do
                        {
                            readAmount = inflater.Read(readBuffer, 0, readBuffer.Length);
                            readStream.Write(readBuffer, 0, readAmount);
                        }while (readAmount != 0);
                    }
                }

                buffer = readStream.ToArray();
            }
        }
Exemple #19
0
        public Stream GetStream()
        {
            byte[] data   = new byte[Data.Size];
            long   offset = Packfile.DataOffset + Data.Start;

            Packfile.DataStream.Seek(offset, SeekOrigin.Begin);
            if (Data.Flags.HasFlag(PackfileEntryFlags.Compressed))
            {
                byte[] compressedData = new byte[Data.CompressedSize];
                Packfile.DataStream.Read(compressedData, 0, (int)Data.CompressedSize);
                using (MemoryStream tempStream = new MemoryStream(compressedData))
                {
                    using (Stream s = new ZlibStream(tempStream, CompressionMode.Decompress, true))
                    {
                        s.Read(data, 0, (int)Data.Size);
                    }
                }
            }
            else
            {
                Packfile.DataStream.Read(data, 0, (int)Data.Size);
            }

            MemoryStream ms = new MemoryStream(data);

            return(ms);
        }
Exemple #20
0
        /// <summary>
        /// TODO : Zlib license.
        /// </summary>
        private void WriteImageBytes()
        {
            // make imagebytes
            int size = this.ImageSize + (this.ImageSize % 4);

            this.ImageBytes = new byte[size];
            for (int i = 0; i < size; i++)
            {
                this.ImageBytes[i] = 0xff;
            }

            byte[]       data = Convert.FromBase64String(this.Image);
            MemoryStream ms   = new MemoryStream(data, true);

            ZlibStream decomp = new ZlibStream(ms, CompressionMode.Decompress);

            try
            {
                decomp.Read(this.ImageBytes, 0, this.ImageSize);
            }
            catch (Exception)
            {
                // TODO.
                throw;
            }
        }
Exemple #21
0
        private byte[] InternalExtract()
        {
            _stream.Position = _manifest.Offset;

            var sizeBytes = new byte[4];

            _stream.Read(sizeBytes, 0, 4);

            int uncompressedSize = BitConverter.ToInt32(sizeBytes, 0);

            if (uncompressedSize <= 0)
            {
                return(new byte[0]);
            }

            _stream.Position += 4;

            var buffer = new byte[_manifest.UncompressedSize];

            var zlibStream = new ZlibStream(_stream, CompressionMode.Decompress, true);

            zlibStream.Read(buffer, 0, buffer.Length);

            zlibStream.Close();
            zlibStream.Dispose();

            return(buffer);
        }
Exemple #22
0
        public void Uncompress(string algorithm)
        {
            if (algorithm == CompressionAlgorithm.Zlib)
            {
                Position = 0;
                ZlibStream   deflateStream = new ZlibStream(_memoryStream, CompressionMode.Decompress, false);
                MemoryStream ms            = new MemoryStream();
                byte[]       buffer        = new byte[1024];
                // Chop off the first two bytes
                //int b = _memoryStream.ReadByte();
                //b = _memoryStream.ReadByte();
                while (true)
                {
                    int readCount = deflateStream.Read(buffer, 0, buffer.Length);
                    if (readCount > 0)
                    {
                        ms.Write(buffer, 0, readCount);
                    }
                    else
                    {
                        break;
                    }
                }
                deflateStream.Close();
                _memoryStream.Close();
                _memoryStream.Dispose();
                _memoryStream          = ms;
                _memoryStream.Position = 0;
            }
            if (algorithm == CompressionAlgorithm.Deflate)
            {
                Position = 0;
                DeflateStream deflateStream = new DeflateStream(_memoryStream, CompressionMode.Decompress, false);
                MemoryStream  ms            = new MemoryStream();
                byte[]        buffer        = new byte[1024];
                while (true)
                {
                    int readCount = deflateStream.Read(buffer, 0, buffer.Length);
                    if (readCount > 0)
                    {
                        ms.Write(buffer, 0, readCount);
                    }
                    else
                    {
                        break;
                    }
                }
                deflateStream.Close();
                _memoryStream.Close();
                _memoryStream.Dispose();
                _memoryStream          = ms;
                _memoryStream.Position = 0;
            }
            AMFReader amfReader = new AMFReader(_memoryStream);
            AMFWriter amfWriter = new AMFWriter(_memoryStream);

            _dataOutput = new DataOutput(amfWriter);
            _dataInput  = new DataInput(amfReader);
        }
Exemple #23
0
        /// <summary>
        /// Decompress a byte array into another byte array of the specified size
        /// </summary>
        /// <param name="to_decompress">Data to decompress</param>
        /// <param name="size_uncompressed">Size of the data once decompressed</param>
        /// <returns>Decompressed data as a byte array</returns>

        public static byte[] Decompress(byte[] to_decompress, int size_uncompressed)
        {
            ZlibStream stream = new ZlibStream(new System.IO.MemoryStream(to_decompress, false), CompressionMode.Decompress);

            byte[] packetData_decompressed = new byte[size_uncompressed];
            stream.Read(packetData_decompressed, 0, size_uncompressed);
            stream.Close();
            return(packetData_decompressed);
        }
Exemple #24
0
        /// <summary>
        /// Decompress a byte array into another byte array of the specified size
        /// </summary>
        /// <param name="toDecompress">Data to decompress</param>
        /// <param name="uncompressedSize">Size of the data once decompressed</param>
        /// <returns>Decompressed data as a byte array</returns>
        public static byte[] Decompress(byte[] toDecompress, int uncompressedSize)
        {
            ZlibStream stream = new ZlibStream(new MemoryStream(toDecompress, false), CompressionMode.Decompress);

            byte[] decompressed = new byte[uncompressedSize];
            stream.Read(decompressed, 0, uncompressedSize);
            stream.Close();
            return(decompressed);
        }
Exemple #25
0
 public static void Uncompress(ref byte[] bin, int size_uncompressed, ref byte[] bout)
 {
     using (MemoryStream ms = new MemoryStream(bin))
         using (ZlibStream zs = new ZlibStream(ms, Ionic.Zlib.CompressionMode.Decompress, Ionic.Zlib.CompressionLevel.Default))
         {
             bout = new byte[size_uncompressed];
             zs.Read(bout, 0, size_uncompressed);
         }
 }
Exemple #26
0
        public static void LogPacket(Packet packet)
        {
            Console.WriteLine("     Source: {0:X2}", packet.Source);
            Console.WriteLine("Destination: {0:X2}", packet.Destination);
            Console.WriteLine("       Type: {0}", (PacketType)(packet.TypeFlags & 7));
            Console.WriteLine("      Flags: {0}", (PacketFlags)(packet.TypeFlags & 248));
            Console.WriteLine("  SessionID: {0:X2}", packet.SessionID);
            Console.WriteLine("  PacketSig: {0}", BitConverter.ToString(packet.PacketSignature).Replace("-", string.Empty));
            Console.WriteLine(" SequenceID: {0}", packet.SequenceID.ToString());
            Console.WriteLine("SpecialData: {0}", BitConverter.ToString(packet.SpecialData).Replace("-", string.Empty));
            if (packet.IsType(PacketType.TYPE_CONNECT) || packet.IsType(PacketType.TYPE_SYN))
            {
                Console.WriteLine("    ConnSig: {0}", packet.ConnectionSignature.ToString());
            }
            if (packet.IsType(PacketType.TYPE_DATA))
            {
                Console.WriteLine(" FragmentID: {0}", packet.FragmentID.ToString());
            }
            if (packet.HasFlag(PacketFlags.FLAG_HAS_SIZE))
            {
                Console.WriteLine("PayloadSize: {0}", packet.PayloadSize);
            }
            Console.WriteLine("    Payload: {0}", BitConverter.ToString(packet.Payload).Replace("-", string.Empty));
            if (packet.PayloadSize >= 128 && !packet.HasFlag(PacketFlags.FLAG_RELIABLE))
            {
                Console.Write(" Decompress: ");
                using (MemoryStream ms = new MemoryStream(packet.Payload))
                    using (ZlibStream zs = new ZlibStream(ms, CompressionMode.Decompress))
                    {
                        try
                        {
                            Console.Write("{0:X2}-", (byte)ms.ReadByte());
                            byte[] buf = new byte[packet.PayloadSize];
                            zs.Read(buf, 0, packet.PayloadSize);
                            Console.WriteLine(BitConverter.ToString(buf).Replace("-", string.Empty));
                            //Console.WriteLine(Encoding.ASCII.GetString(buf));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
            }
            //if (packet.HasFlag(PacketFlags.FLAG_RELIABLE))
            //{
            //    byte[] decrypted = RC4.Decrypt(CryptKey, packet.Payload);
            //    Console.WriteLine("    Decrypt: {0}", BitConverter.ToString(decrypted).Replace("-", string.Empty));
            //}
            Console.WriteLine(" PayloadLen: {0}", packet.Payload.Length.ToString());
            Console.WriteLine("   Checksum: {0}", BitConverter.ToString(packet.Checksum).Replace("-", string.Empty));

            //byte[] dataWithoutChkSum = new byte[packet.RawData.Length - 4];
            //Array.Copy(packet.RawData, 0, dataWithoutChkSum, 0, dataWithoutChkSum.Length);
            //int chkSum = V0_CalcChecksum_32bit(dataWithoutChkSum, "cH0on9AsIXx7");
            //Console.WriteLine(" CalcChkSum: {0}", BitConverter.ToString(BitConverter.GetBytes(chkSum)).Replace("-", string.Empty));
        }
Exemple #27
0
    public void Load(
        byte [] _AssetData
        , ref GAFAnimationData _SharedData)
    {
#if !UNITY_PRO_LICENSE && GAF_SUPPORT_COMPRESSED && UNITY_EDITOR
        if (PlayerSettings.apiCompatibilityLevel == ApiCompatibilityLevel.NET_2_0_Subset &&
            Application.platform != RuntimePlatform.WindowsEditor &&
            Application.platform != RuntimePlatform.WindowsPlayer)
        {
            GAFUtils.Warning("GAF! You are using compressed 'gaf' in free unity. Set API compatibility level as '.NET'!");
        }
#endif // !UNITY_PRO_LICENSE && GAF_SUPPORT_COMPRESSED && UNITY_EDITOR

        GAFHeader header = new GAFHeader();

        MemoryStream fstream = new MemoryStream(_AssetData);
        using (BinaryReader freader = new BinaryReader(fstream))
        {
            if (freader.BaseStream.Length > GAFHeader.headerDataOffset)
            {
                header.Read(freader);
                if (header.isValid)
                {
                    _SharedData = new GAFAnimationData();

                    _SharedData.majorVersion = header.majorVersion;
                    _SharedData.minorVersion = header.minorVersion;

                    switch (header.compression)
                    {
                    case GAFHeader.CompressionType.CompressedNone:
                        Read(freader, ref _SharedData);
                        break;

                    case GAFHeader.CompressionType.CompressedZip:
#if GAF_SUPPORT_COMPRESSED
                        using (ZlibStream zlibStream = new ZlibStream(fstream, CompressionMode.Decompress))
                        {
                            byte [] uncompressedBuffer = new byte[header.fileLength];
                            zlibStream.Read(uncompressedBuffer, 0, uncompressedBuffer.Length);

                            using (BinaryReader reader = new BinaryReader(new MemoryStream(uncompressedBuffer)))
                            {
                                Read(reader, ref _SharedData);
                            }
                        }
                        break;
#else
                        GAFUtils.Assert(false, "GAF. Compressed gaf format is not supported in your plugin!");
                        break;
#endif // GAF_SUPPORT_COMPRESSED
                    }
                }
            }
        }
    }
Exemple #28
0
        public IFileDataWrapper GetCompressedData(int offset, int size, int uncompressedSize)
        {
            MemoryFileDataWrapper newData = FromArray(new byte[uncompressedSize]);

            using (MemoryStream ms = new MemoryStream(_bytes, offset, size))
                using (ZlibStream zlib = new ZlibStream(ms, CompressionMode.Decompress))
                    zlib.Read(newData._bytes, 0, uncompressedSize);

            return(newData);
        }
Exemple #29
0
        public static byte[] DeflateBuffer(byte[] input)
        {
            using (MemoryStream inputStream = new MemoryStream(input))
                using (ZlibStream deflater = new ZlibStream(inputStream, CompressionMode.Decompress))
                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        byte[] buff = new byte[512];
                        int    read = deflater.Read(buff, 0, buff.Length);

                        while (read > 0)
                        {
                            outputStream.Write(buff, 0, read);

                            read = deflater.Read(buff, 0, buff.Length);
                        }

                        return(outputStream.ToArray());
                    }
        }
Exemple #30
0
        /// <summary>
        /// Decompress a byte array into another byte array of the specified size
        /// </summary>
        /// <param name="to_decompress">Data to decompress</param>
        /// <param name="size_uncompressed">Size of the data once decompressed</param>
        /// <returns>Decompressed data as a byte array</returns>
        public static byte[] Decompress(byte[] to_decompress, int size_uncompressed)
        {
            using var stream = new ZlibStream(new MemoryStream(to_decompress, false), CompressionMode.Decompress, CompressionLevel.BestSpeed);
            byte[] packetData_decompressed = new byte[size_uncompressed];

            stream.Read(packetData_decompressed, 0, size_uncompressed);
            stream.Close();

            return(packetData_decompressed);
        }