Inflate() 공개 메소드

Inflates the compressed stream to the output buffer. If this returns 0, you should check, whether IsNeedingDictionary(), IsNeedingInput() or IsFinished() returns true, to determine why no further output is produced.
/// if buffer has length 0. /// /// if deflated stream is invalid. ///
public Inflate ( byte buffer ) : int
buffer byte /// the output buffer. ///
리턴 int
예제 #1
0
		protected override int Inflate(int pos, byte[] dstbuf, int dstoff, Inflater inf)
        {
            while (!inf.IsFinished)
            {
                if (inf.IsNeedingInput)
                {
                    inf.SetInput(_array, pos, _array.Length - pos);
                    break;
                }
                dstoff += inf.Inflate(dstbuf, dstoff, dstbuf.Length - dstoff);
            }
            while (!inf.IsFinished && !inf.IsNeedingInput)
                dstoff += inf.Inflate(dstbuf, dstoff, dstbuf.Length - dstoff);
            return dstoff;
        }
예제 #2
0
 internal override int inflate(int pos, byte[] b, int o, Inflater inf)
 {
     while (!inf.IsFinished)
     {
         if (inf.IsNeedingInput)
         {
             inf.SetInput(array, pos, array.Length - pos);
             break;
         }
         o += inf.Inflate(b, o, b.Length - o);
     }
     while (!inf.IsFinished && !inf.IsNeedingInput)
         o += inf.Inflate(b, o, b.Length - o);
     return o;
 }
예제 #3
0
		byte[] Decrypt(byte[] encryptedData) {
			var reader = new BinaryReader(new MemoryStream(encryptedData));
			int headerMagic = reader.ReadInt32();
			if (headerMagic == 0x04034B50)
				throw new NotImplementedException("Not implemented yet since I haven't seen anyone use it.");

			byte encryption = (byte)(headerMagic >> 24);
			if ((headerMagic & 0x00FFFFFF) != 0x007D7A7B)	// Check if "{z}"
				throw new ApplicationException(string.Format("Invalid SA header magic 0x{0:X8}", headerMagic));

			switch (encryption) {
			case 1:
				int totalInflatedLength = reader.ReadInt32();
				if (totalInflatedLength < 0)
					throw new ApplicationException("Invalid length");
				var inflatedBytes = new byte[totalInflatedLength];
				int partInflatedLength;
				for (int inflateOffset = 0; inflateOffset < totalInflatedLength; inflateOffset += partInflatedLength) {
					int partLength = reader.ReadInt32();
					partInflatedLength = reader.ReadInt32();
					if (partLength < 0 || partInflatedLength < 0)
						throw new ApplicationException("Invalid length");
					var inflater = new Inflater(true);
					inflater.SetInput(encryptedData, checked((int)reader.BaseStream.Position), partLength);
					reader.BaseStream.Seek(partLength, SeekOrigin.Current);
					int realInflatedLen = inflater.Inflate(inflatedBytes, inflateOffset, inflatedBytes.Length - inflateOffset);
					if (realInflatedLen != partInflatedLength)
						throw new ApplicationException("Could not inflate");
				}
				return inflatedBytes;

			case 2:
				if (resourceDecrypterInfo.DES_Key == null || resourceDecrypterInfo.DES_IV == null)
					throw new ApplicationException("DES key / iv have not been set yet");
				using (var provider = new DESCryptoServiceProvider()) {
					provider.Key = resourceDecrypterInfo.DES_Key;
					provider.IV  = resourceDecrypterInfo.DES_IV;
					using (var transform = provider.CreateDecryptor()) {
						return Decrypt(transform.TransformFinalBlock(encryptedData, 4, encryptedData.Length - 4));
					}
				}

			case 3:
				if (resourceDecrypterInfo.AES_Key == null || resourceDecrypterInfo.AES_IV == null)
					throw new ApplicationException("AES key / iv have not been set yet");
				using (var provider = new RijndaelManaged()) {
					provider.Key = resourceDecrypterInfo.AES_Key;
					provider.IV  = resourceDecrypterInfo.AES_IV;
					using (var transform = provider.CreateDecryptor()) {
						return Decrypt(transform.TransformFinalBlock(encryptedData, 4, encryptedData.Length - 4));
					}
				}

			default:
				throw new ApplicationException(string.Format("Unknown encryption type 0x{0:X2}", encryption));
			}
		}
예제 #4
0
 	protected override int Inflate(int pos, byte[] dstbuf, int dstoff, Inflater inf)
     {
         var tmp = new byte[512];
         var s = _stream;
         s.Position=pos;
         while ((s.Length-s.Position) > 0 && !inf.IsFinished)
         {
             if (inf.IsNeedingInput)
             {
                 var n = (int)Math.Min((s.Length - s.Position), tmp.Length);
                 s.Read(tmp, 0, n);
                 inf.SetInput(tmp, 0, n);
             }
             dstoff += inf.Inflate(dstbuf, dstoff, dstbuf.Length - dstoff);
         }
         while (!inf.IsFinished && !inf.IsNeedingInput)
             dstoff += inf.Inflate(dstbuf, dstoff, dstbuf.Length - dstoff);
         return dstoff;
     }
예제 #5
0
        public static byte[] DecompressAlphaValues(byte[] alphaValues, int width, int height)
        {
            var data = new byte[width * height];
            var inflater = new Inflater();
            inflater.SetInput(alphaValues);
            if (inflater.Inflate(data) != data.Length)
                throw new ArgumentException("Alpha values are not in valid compressed format!");

            return data;
        }
예제 #6
0
        public static byte[] DecompressDeflate(byte[] data, int decompSize)
        {
            var decompData = new byte[decompSize];

            var inflater = new Inflater(true);
            inflater.SetInput(data);
            inflater.Inflate(decompData);

            return decompData;
        }
예제 #7
0
 public static byte[] Decompress(byte[] compressed, uint unzippedSize)
 {
     byte[] result = new byte[unzippedSize];
     Inflater inf = new Inflater();
     inf.SetInput(compressed);
     int error = inf.Inflate(result, 0, (int)unzippedSize);
     if (error == 0)
     {
         throw new FileLoadException("The a section of the swf file could not be decompressed.");
     }
     return result;
 }
 public static void HandleReqUpdateAccountData(Packet packet)
 {
     packet.ReadEnum<AccountDataType>("Type");
     packet.ReadTime("Time");
     int inflatedSize = packet.ReadInt32("Size");
     byte[] compressedData = packet.ReadBytes((int)packet.GetLength() - (int)packet.GetPosition());
     byte[] data = new byte[inflatedSize];
     var inflater = new Inflater();
     inflater.SetInput(compressedData, 0, compressedData.Length);
     inflater.Inflate(data, 0, inflatedSize);
     Console.WriteLine("Data: {0}", encoder.GetString(data));
 }
예제 #9
0
 public CodecInputStream(Stream baseStream)
 {
     BinaryReader br = new BinaryReader(baseStream);
     decompressedSize = br.ReadInt32();
     compressedSize = br.ReadInt32();
     byte[] inbuf = new byte[compressedSize];
     baseStream.Read(inbuf, 0, compressedSize);
     Inflater inflater = new Inflater(false);
     inflater.SetInput(inbuf);
     byte[] buf = new byte[decompressedSize];
     inflater.Inflate(buf);
     this.iis = new MemoryStream(buf);
 }
예제 #10
0
        public static byte[] Decompress(byte[] input, int uncompressedLength, bool header = true)
        {
            Contract.Requires(input != null);
            Contract.Requires(uncompressedLength >= 0);
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == uncompressedLength);

            var inflater = new Inflater(!header);
            var output = new byte[uncompressedLength];

            inflater.SetInput(input, 0, input.Length);
            inflater.Inflate(output);

            return output;
        }
예제 #11
0
		public static byte[] Decompress(byte[] content, int offset, int count)
		{
			//return content;
			Inflater decompressor = new Inflater();
			decompressor.SetInput(content, offset, count);

			using (MemoryStream bos = new MemoryStream(content.Length))
			{
				var buf = new byte[1024];
				while (!decompressor.IsFinished)
				{
					int n = decompressor.Inflate(buf);
					bos.Write(buf, 0, n);
				}
				return bos.ToArray();
			}
		}
예제 #12
0
 public Stream Open(Stream stream)
 {
     stream.Seek(DataOffset, SeekOrigin.Begin);
     byte[] data;
     if (DataCompression == 0)
     {
         data = stream.ReadBytes(DataSize);
     }
     else
     {
         var dataBuffer = stream.ReadBytes(DataCompressedSize);
         var inflater = new Inflater(false);
         inflater.SetInput(dataBuffer);
         data = new Byte[DataSize];
         inflater.Inflate(data);
     }
     return new MemoryStream(data);
 }
예제 #13
0
        public byte[] Uncompress(byte[] input)
        {
            Inflater decompressor = new Inflater();
            decompressor.SetInput(input);

            // Create an expandable byte array to hold the decompressed data
            MemoryStream bos = new MemoryStream(input.Length);

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

            // Get the decompressed data
            return bos.ToArray();
        }
		public byte[] Unpack() {
			if (peImage.PEImage.Win32Resources == null)
				return null;
			var dataEntry = peImage.PEImage.Win32Resources.Find(10, "__", 0);
			if (dataEntry == null)
				return null;

			var encryptedData = dataEntry.Data.ReadAllBytes();

			var keyData = GetKeyData();
			if (keyData == null)
				return null;
			var decrypter = new NativeFileDecrypter(keyData);
			decrypter.Decrypt(encryptedData, 0, encryptedData.Length);

			byte[] inflatedData;
			if (isNet1x)
				inflatedData = DeobUtils.Inflate(encryptedData, false);
			else {
				int inflatedSize = BitConverter.ToInt32(encryptedData, 0);
				inflatedData = new byte[inflatedSize];
				var inflater = new Inflater(false);
				inflater.SetInput(encryptedData, 4, encryptedData.Length - 4);
				int count = inflater.Inflate(inflatedData);
				if (count != inflatedSize)
					return null;
			}

			// CLR 1.x or DNR v4.0 - v4.4
			if (BitConverter.ToInt16(inflatedData, 0) == 0x5A4D)
				return inflatedData;

			// DNR v4.5
			if (BitConverter.ToInt16(inflatedData, loaderHeaderSizeV45) == 0x5A4D)
				return UnpackLoader(inflatedData);

			return null;
		}
예제 #15
0
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void ReadData(byte version, BufferedBinaryReader binaryReader)
        {
            RecordHeader rh = new RecordHeader();
            rh.ReadData(binaryReader);

            int beforePos = (int)binaryReader.BaseStream.Position;
            int toReaded = (int)rh.TagLength - 7;

            _characterId = binaryReader.ReadUInt16();
            _bitmapFormat = binaryReader.ReadByte();
            _bitmapWidth = binaryReader.ReadUInt16();
            _bitmapHeight = binaryReader.ReadUInt16();
            _bitmapColorTableSize = 0;

            if (_bitmapFormat == 3)
            {
                _bitmapColorTableSize = binaryReader.ReadByte();
                toReaded--;
            }

            if (_bitmapFormat == 3)
            {
                _colorMapData = new ColorMapData();
                _colorMapData.ReadData(binaryReader, _bitmapColorTableSize, _bitmapWidth, _bitmapHeight, toReaded);
            }
            else if (_bitmapFormat == 4 || _bitmapFormat == 5)
            {
                int imageSize = _bitmapWidth * _bitmapHeight;
                int uncompressedSize = imageSize;
                if (_bitmapFormat == 4)
                    uncompressedSize *= 2;
                else
                    uncompressedSize *= 4;

                byte[] uncompressed = new byte[uncompressedSize];
                byte[] compressed = binaryReader.ReadBytes(toReaded);
                Inflater zipInflator = 	new Inflater();
                zipInflator.SetInput(compressed);
                zipInflator.Inflate(uncompressed, 0, uncompressedSize);

                _bitmapColorData = null;
                if (_bitmapFormat == 4)
                {
                    Pix15[] bitmapPixelData = new Pix15[imageSize];
                    for (int i = 0, j = 0; i < imageSize; i++, j += 2)
                    {
                        byte[] data = new byte[2] {uncompressed[j], uncompressed[j+1]};
                        bitmapPixelData[i] = new Pix15(data);
                    }
                    _bitmapColorData = new BitmapColorData(bitmapPixelData);
                }
                else
                {
                    Pix24[] bitmapPixelData = new Pix24[imageSize];
                    for (int i = 0, j = 0; i < imageSize; i++, j += 4)
                    {
                        byte reserved = uncompressed[j];
                        byte red = uncompressed[j + 1];
                        byte green = uncompressed[j + 2];
                        byte blue = uncompressed[j + 3];
                        bitmapPixelData[i] = new Pix24(red, green, blue);
                    }
                    _bitmapColorData = new BitmapColorData(bitmapPixelData);
                }
            }
        }
예제 #16
0
        protected bool Load(SwfStream stream, uint length, bool hasAlpha)
        {
            CharacterID = stream.ReadUShort();

            byte format = stream.ReadByte();
            Width = stream.ReadUShort();
            Height = stream.ReadUShort();
            byte table = (format == 3) ? stream.ReadByte() : (byte)0;
            byte[] compressed = stream.ReadByteArray(length - stream.TagPosition);
            byte[] data;
            var inflater = new Inflater();
            inflater.SetInput(compressed);

            if (format == 3)
            {
                int rem = Width % 4;
                data = new byte[((rem == 0) ? Width : (Width + 4 - rem)) * Height * 4];
                if (inflater.Inflate(data) != data.Length)
                    throw new SwfCorruptedException("Bitmap data are not valid ZLIB stream!");
                Pixels = BitmapUtils.UnpackIndexed(data, Width, Height, table, hasAlpha);
            }
            else if (format == 4 && !hasAlpha)
            {
                data = new byte[(Width + Width & 0x01) * Height * 2];
                if (inflater.Inflate(data) != data.Length)
                    throw new SwfCorruptedException("Bitmap data are not valid ZLIB stream!");
                Pixels = BitmapUtils.UnpackPIX15(data, Width, Height);
            }
            else if (format == 5)
            {
                data = new byte[Width * Height * 4];
                if (inflater.Inflate(data) != data.Length)
                    return true;
                Pixels = BitmapUtils.UnpackPIX24(data, Width, Height, hasAlpha);
            }
            else
                throw new SwfCorruptedException("Invalid lossless bitmap format found!");

            return true;
        }
예제 #17
0
        public Packet Inflate(int inflatedSize)
        {
            var arr = ReadToEnd();
            var newarr = new byte[inflatedSize];
            var inflater = new Inflater();
            inflater.SetInput(arr, 0, arr.Length);
            inflater.Inflate(newarr, 0, inflatedSize);

            var pkt = new Packet(newarr, Opcode, Time, Direction, Number, Writer);
            return pkt;
        }
예제 #18
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);
				}
			}
예제 #19
0
		/// <exception cref="Sharpen.DataFormatException"></exception>
		internal void Check(Inflater inf, byte[] tmp, long pos, int cnt)
		{
			inf.SetInput(array, (int)(pos - start), cnt);
			while (inf.Inflate(tmp, 0, tmp.Length) > 0)
			{
				continue;
			}
		}
예제 #20
0
파일: MPK.cs 프로젝트: mynew4/DOLSharp
		private static byte[] ReadDirectory(BinaryReader rdr, ref long totalin)
		{
			int totalout = 0;
			var input = new byte[1024];
			var output = new byte[1024];
			var inf = new Inflater();
			totalin = 0;

			while (!inf.IsFinished)
			{
				while (inf.IsNeedingInput)
				{
					int count;
					if ((count = rdr.Read(input, 0, 1024)) <= 0)
					{
						throw new Exception("EOF");
					}

					inf.SetInput(input, 0, count);
					totalin += count;
				}

				if (totalout == output.Length)
				{
					var newOutput = new byte[output.Length*2];
					Buffer.BlockCopy(output, 0, newOutput, 0, output.Length);
					output = newOutput;
				}

				totalout += inf.Inflate(output, totalout, output.Length - totalout);
			}

			var final = new byte[totalout];
			Buffer.BlockCopy(output, 0, final, 0, totalout);
			rdr.BaseStream.Position = rdr.BaseStream.Position - inf.RemainingInput;
			totalin -= inf.RemainingInput;

			return final;
		}
예제 #21
0
파일: MPK.cs 프로젝트: mynew4/DOLSharp
		/// <summary>
		/// Reads a MPK from a binary reader
		/// </summary>
		/// <param name="rdr">The binary reader pointing to the MPK</param>
		private void ReadArchive(BinaryReader rdr)
		{
			_files.Clear();

			_crc.Value = 0;
			_sizeDir = 0;
			_sizeName = 0;
			_numFiles = 0;

			var buf = new byte[16];
			rdr.Read(buf, 0, 16);

			for (byte i = 0; i < 16; ++i)
			{
				buf[i] ^= i;
			}

			_crc.Value = ((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]);
			_sizeDir = ((buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7]);
			_sizeName = ((buf[8] << 24) | (buf[9] << 16) | (buf[10] << 8) | buf[11]);
			_numFiles = ((buf[12] << 24) | (buf[13] << 16) | (buf[14] << 8) | buf[15]);

			buf = new byte[_sizeName];
			rdr.Read(buf, 0, _sizeName);

			var inf = new Inflater();
			inf.SetInput(buf);
			buf = new byte[1024];
			inf.Inflate(buf);
			buf[inf.TotalOut] = 0;

			_name = Marshal.ConvertToString(buf);

			long totalin = 0;
			buf = ReadDirectory(rdr, ref totalin);

			using (var directory = new MemoryStream(buf))
			{
				long pos = rdr.BaseStream.Position;
				long len = rdr.BaseStream.Seek(0, SeekOrigin.End);
				rdr.BaseStream.Position = pos;

				buf = new byte[len - pos];
				rdr.Read(buf, 0, buf.Length);

				using (var files = new MemoryStream(buf))
				{
					rdr.BaseStream.Position = pos - totalin;
					buf = new byte[totalin];
					rdr.Read(buf, 0, buf.Length);

					var crc = new Crc32();
					crc.Reset();
					crc.Update(buf);

					if (crc.Value != _crc.Value)
					{
						throw new Exception("Invalid or corrupt MPK");
					}

					while (directory.Position < directory.Length && files.Position < files.Length)
					{
						crc.Reset();

						buf = new byte[MPKFileHeader.MaxSize];
						directory.Read(buf, 0, MPKFileHeader.MaxSize);

						MPKFileHeader hdr;

						using (var hdrStream = new MemoryStream(buf))
						{
							using (var hdrRdr = new BinaryReader(hdrStream, Encoding.UTF8))
							{
								hdr = new MPKFileHeader(hdrRdr);
							}
						}

						var compbuf = new byte[hdr.CompressedSize];
						files.Read(compbuf, 0, compbuf.Length);

						crc.Update(compbuf, 0, compbuf.Length);

						inf.Reset();
						inf.SetInput(compbuf, 0, compbuf.Length);
						buf = new byte[hdr.UncompressedSize];
						inf.Inflate(buf, 0, buf.Length);

						var file = new MPKFile(compbuf, buf, hdr);

						if (crc.Value != hdr.CRC.Value)
						{
							OnInvalidFile(file);
							continue;
						}

						_files.Add(hdr.Name.ToLower(), file);
					}
				}
			}
		}
예제 #22
0
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void ReadData(byte version, BufferedBinaryReader binaryReader)
        {
            RecordHeader rh = new RecordHeader();
            rh.ReadData(binaryReader);

            int beforePos = (int)binaryReader.BaseStream.Position;
            int toReaded = (int)rh.TagLength - 7;

            _characterId = binaryReader.ReadUInt16();
            _bitmapFormat = binaryReader.ReadByte();
            _bitmapWidth = binaryReader.ReadUInt16();
            _bitmapHeight = binaryReader.ReadUInt16();
            _bitmapColorTableSize = 0;

            if (_bitmapFormat == 3)
            {
                _bitmapColorTableSize = binaryReader.ReadByte();
                toReaded--;
            }

            int imageSize = _bitmapWidth * _bitmapHeight;

            if (_bitmapFormat == 3)
            {
                int uncompressedSize = imageSize + ((_bitmapColorTableSize + 1) * 4);
                byte[] uncompressed = new byte[uncompressedSize];
                byte[] compressed = binaryReader.ReadBytes(toReaded);
                Inflater zipInflator = 	new Inflater();
                zipInflator.SetInput(compressed);
                zipInflator.Inflate(uncompressed, 0, uncompressedSize);

                _alphaColorMapData = new AlphaColorMapData();
                _alphaColorMapData.ColorTableRgb = new RGBA[_bitmapColorTableSize + 1];
                int offset = 0;
                for (int i = 0; i < _bitmapColorTableSize + 1; i++, offset += 4)
                {
                    byte red = uncompressed[offset];
                    byte green = uncompressed[offset + 1];
                    byte blue = uncompressed[offset + 2];
                    byte alpha = uncompressed[offset + 3];
                    _alphaColorMapData.ColorTableRgb[i] = new RGBA(red, green, blue, alpha);
                }
                _alphaColorMapData.ColorMapPixelData = new byte[uncompressedSize - offset];
                for (int i = 0; i < uncompressedSize - offset; i++, offset++)
                    _alphaColorMapData.ColorMapPixelData[i] = uncompressed[offset];
            }
            else if (_bitmapFormat == 4 || _bitmapFormat == 5)
            {
                int uncompressedSize = imageSize * 4;
                byte[] uncompressed = new byte[uncompressedSize];
                byte[] compressed = binaryReader.ReadBytes(toReaded);
                Inflater zipInflator = 	new Inflater();
                zipInflator.SetInput(compressed);
                zipInflator.Inflate(uncompressed, 0, uncompressedSize);

                _alphaBitmapData = new AlphaBitmapData();
                _alphaBitmapData.BitmapPixelData = new RGBA[imageSize];
                for (int i = 0, j = 0; i < imageSize; i++, j += 4)
                {
                    byte red = uncompressed[j];
                    byte green = uncompressed[j + 1];
                    byte blue = uncompressed[j + 2];
                    byte alpha = uncompressed[j + 3];
                    _alphaBitmapData.BitmapPixelData[i] = new RGBA(red, green, blue, alpha);
                }
            }
        }
예제 #23
0
        //...........................................................

        /// <summary>
        /// Get an uncompressed blob from PAK_STREAM using the meta-data in ENTRY.
        /// </summary>
        /// <returns>A MemoryStream if possible, otherwise a FileStream to a auto-delete temp file.</returns>
        protected Stream Decompress(Stream PAK_STREAM, cmk.NMS.PAK.Item.Info ENTRY)
        {
            if (PAK_STREAM == null)
            {
                return(null);
            }

            Stream entry;

            if (ENTRY.Length < Int32.MaxValue)
            {
                entry = new MemoryStream((int)ENTRY.Length);
            }
            else
            {
                var temp = System.IO.Path.GetTempFileName();
                entry = new FileStream(temp,
                                       FileMode.Open,
                                       FileAccess.ReadWrite,
                                       FileShare.None,
                                       m_block_size,
                                       FileOptions.DeleteOnClose
                                       );
            }

            // m_block_size is the max decompressed size of a block.
            // each compressed block will be this size or smaller.
            var compressed   = new byte [m_block_size];
            var decompressed = new byte [m_block_size];
            var inflater     = new zlib.Inflater();
            // using System.IO.Compression.DeflateStream.Read fails to parse the data,
            // even though it supposidly uses zlib behind the scenes.
            // todo: assume used it incorrectly, would prefer using built-in API instead of nuget zlib.

            var index  = ENTRY.Index;               // index of first block for ENTRY
            var offset = ENTRY.Offset;              // where the first block ( m_blocks[index]) starts

            // e.g. ENTRY: Index = 7, Offset = 123456, Length = 123456:
            // - m_blocks[7] = 12345, m_blocks[8] = 6789  (example compressed sizes)
            //   these would (likely) decompress to: 65536 and 57920 bytes = 123456 bytes Length.
            // - offset = 123456 is where m_blocks[7] 12345 bytes of compressed data starts,
            //   m_blocks[8]  6789 bytes of compressed data will immediately follow
            //   m_blocks[7] 12345 bytes, and so on.

            for ( ; entry.Length < ENTRY.Length; ++index)
            {
                PAK_STREAM.Position = offset;

                // current block is uncompressed full block, just copy to output
                if (m_blocks[index] == 0)
                {
                    PAK_STREAM.Read(compressed, 0, m_block_size);
                    entry.Write(compressed, 0, m_block_size);
                    offset += m_block_size;
                    continue;
                }

                PAK_STREAM.Read(compressed, 0, (int)m_blocks[index]);                  // read compressed data for current block
                offset += m_blocks[index];                                             // update offset for next block

                // if it's not an uncompressed full block we MUST assume it's a 'compressed' block (has compression header).
                // we have no way to differentiate a compression header from valid uncompressed data.
                //
                // original psarc.exe code assumes that if the compressed block does not
                // start with 0x78da then it's an uncompressed partial block - ugghhh.
                //
                // https://stackoverflow.com/questions/9050260/what-does-a-zlib-header-look-like
                // Level | ZLIB  | GZIP
                // 1     | 78 01 | 1F 8B - No Compression/low
                // 2     | 78 5E | 1F 8B - Fastest Compression
                // 3     | 78 5E | 1F 8B
                // 4     | 78 5E | 1F 8B
                // 5     | 78 5E | 1F 8B
                // 6     | 78 9C | 1F 8B - Default Compression
                // 7     | 78 DA | 1F 8B - Best Compression (Slowest)
                // 8     | 78 DA | 1F 8B
                // 9     | 78 DA | 1F 8B
                //
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(compressed, 0x00, 2);
                }
                var is_compressed = BitConverter.ToUInt16(compressed, 0);
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(compressed, 0x00, 2);
                }

                if (is_compressed != 0x7801 &&
                    is_compressed != 0x785e &&
                    is_compressed != 0x789c &&
                    is_compressed != 0x78da
                    )
                {
                    // MessageBox.Show("Surprise, uncompressed partial ... maybe");
                    // ... turns out these exist
                    entry.Write(compressed, 0, (int)m_blocks[index]);
                    continue;
                }

                // ??? wtf ???
                // for blocks that inflate to a full block size (65536) we end up with 4 bytes
                // in RemainingInput after first Inflate call, the second call results in 0 bytes inflated.
                // the resulting data in uncompressed_file seems good though, no missing data.
                // if there was padding added by Deflate i'd expect it to be consumed by first Inflate.
                // maybe it's the 4 byte adler checksum ???
                inflater.SetInput(compressed, 0, (int)m_blocks[index]);

                var length = inflater.Inflate(decompressed);
                entry.Write(decompressed, 0, length);

                inflater.Reset();
            }

            entry.Position = 0;
            return(entry);
        }
예제 #24
0
		/// <exception cref="System.IO.IOException"></exception>
		/// <exception cref="NGit.Errors.CorruptObjectException"></exception>
		private static void CheckValidEndOfStream(InputStream @in, Inflater inf, AnyObjectId
			 id, byte[] buf)
		{
			for (; ; )
			{
				int r;
				try
				{
					r = inf.Inflate(buf);
				}
				catch (SharpZipBaseException)
				{
					throw new CorruptObjectException(id, JGitText.Get().corruptObjectBadStream);
				}
				if (r != 0)
				{
					throw new CorruptObjectException(id, JGitText.Get().corruptObjectIncorrectLength);
				}
				if (inf.IsFinished)
				{
					if (inf.RemainingInput != 0 || @in.Read() != -1)
					{
						throw new CorruptObjectException(id, JGitText.Get().corruptObjectBadStream);
					}
					break;
				}
				if (!inf.IsNeedingInput)
				{
					throw new CorruptObjectException(id, JGitText.Get().corruptObjectBadStream);
				}
				r = @in.Read(buf);
				if (r <= 0)
				{
					throw new CorruptObjectException(id, JGitText.Get().corruptObjectBadStream);
				}
				inf.SetInput(buf, 0, r);
			}
		}
예제 #25
0
 internal override void inflateVerify(int pos, Inflater inf)
 {
     byte[] tmp = new byte[512];
     var s = _stream;
     s.Position=(pos);
     while ((s.Length - s.Position) > 0 && !inf.IsFinished)
     {
         if (inf.IsNeedingInput)
         {
             int n = (int)Math.Min((s.Length - s.Position), tmp.Length);
             s.Read(tmp, 0, n);
             inf.SetInput(tmp, 0, n);
         }
         inf.Inflate(verifyGarbageBuffer, 0, verifyGarbageBuffer.Length);
     }
     while (!inf.IsFinished && !inf.IsNeedingInput)
         inf.Inflate(verifyGarbageBuffer, 0, verifyGarbageBuffer.Length);
 }
예제 #26
0
		public void ProcessCommand(ref Socket soUDP,
			ref IPEndPoint remoteIpEndPoint, string sessionID, Encoding enc)
		{
			this.sessionID = sessionID;
			Encoding changeencoding = null;
			encoding = enc;
			EndPoint RemotePoint = (remoteIpEndPoint);
			mcommandText = commandText;
			errorOccurred = false;

			if (commandType != enAniDBCommandType.Ping)
			{
				if (commandType != enAniDBCommandType.Login)
				{
					if (commandType != enAniDBCommandType.Logout && commandType != enAniDBCommandType.GetMyListStats)
					{
						mcommandText += "&";
					}
					mcommandText += "s=" + sessionID;
				}
				else
				{
					encoding = System.Text.Encoding.ASCII;
					changeencoding = enc;
					string encod = changeencoding.EncodingName;
					if (changeencoding.EncodingName.StartsWith("Unicode"))
						encod = "utf-16";
					mcommandText += "&enc=" + encod;
				}
			}
			bool multipart = false;
			int part = 0;
			int maxpart = 1;
			string fulldesc = "";
			string decodedstring = "";
			DateTime start = DateTime.Now;

			do
			{
				
				if (part > 0)
				{
					mcommandText = mcommandText.Replace("part=" + (part - 1).ToString(), "part=" + part.ToString());
					Thread.Sleep(2300);
				}
				if (commandType != enAniDBCommandType.Login)
				{
					string msg = string.Format("UDP_COMMAND: {0}", mcommandText);
					JMMService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg);
				}
				else
				{
					//string msg = commandText.Replace(MainWindow.settings.Username, "******");
					//msg = msg.Replace(MainWindow.settings.Password, "******");
					//MyAnimeLog.Write("commandText: {0}", msg);
				}
				bool repeatcmd;
				int received;
				Byte[] byReceivedAdd = new Byte[2000]; // max length should actually be 1400
				do
				{
					repeatcmd = false;
					// Send Message
					Byte[] SendByteAdd = Encoding.GetBytes(mcommandText.ToCharArray());

					try
					{
						JMMService.LastAniDBMessage = DateTime.Now;
						JMMService.LastAniDBUDPMessage = DateTime.Now;
						if (commandType != enAniDBCommandType.Ping)
							JMMService.LastAniDBMessageNonPing = DateTime.Now;
						else
							JMMService.LastAniDBPing = DateTime.Now;

						soUDP.SendTo(SendByteAdd, remoteIpEndPoint);
					}
					catch (Exception ex)
					{
						logger.ErrorException(ex.ToString(), ex);
						//MyAnimeLog.Write(ex.ToString());
						errorOccurred = true;
						errorMessage = ex.ToString();
					}


					// Receive Response
					received = 0;
					try
					{
						//MyAnimeLog.Write("soUDP.ReceiveTimeout = {0}", soUDP.ReceiveTimeout.ToString());


						received = soUDP.ReceiveFrom(byReceivedAdd, ref RemotePoint);
						JMMService.LastAniDBMessage = DateTime.Now;
						JMMService.LastAniDBUDPMessage = DateTime.Now;
						if (commandType != enAniDBCommandType.Ping)
							JMMService.LastAniDBMessageNonPing = DateTime.Now;
						else
							JMMService.LastAniDBPing = DateTime.Now;

						//MyAnimeLog.Write("Buffer length = {0}", received.ToString());
						if ((received > 2) && ((byReceivedAdd[0] == 0) && (byReceivedAdd[1] == 0)))
						{
							//deflate
							Byte[] buff = new byte[65536];
							Byte[] input = new byte[received - 2];
							Array.Copy(byReceivedAdd, 2, input, 0, received - 2);
							Inflater inf = new Inflater(false);
							inf.SetInput(input);
							inf.Inflate(buff);
							byReceivedAdd = buff;
							received = (int)inf.TotalOut;
						}
					}
					catch (SocketException sex)
					{
						// most likely we have timed out
						logger.ErrorException(sex.ToString(), sex);
						errorOccurred = true;
						errorMessage = sex.ToString();
					}
					catch (Exception ex)
					{
						logger.ErrorException(ex.ToString(), ex);
						errorOccurred = true;
						errorMessage = ex.ToString();
					}
					if ((commandType == enAniDBCommandType.Login) && (byReceivedAdd[0] == 0xFE) && (byReceivedAdd[1] == 0xFF) && (byReceivedAdd[3] == 53) && (byReceivedAdd[5] != 53) && (!Encoding.EncodingName.ToLower().StartsWith("unicode")) && (changeencoding != null) && (changeencoding.EncodingName.ToLower().StartsWith("unicode")))
					{
						//Previous Session used utf-16 and was not logged out, AniDB was not yet issued a timeout.
						//AUTH command was not understand because it was encoded in ASCII.
						encoding = changeencoding;
						repeatcmd = true;
					}

				} while (repeatcmd);

				if (!errorOccurred)
				{
					if (changeencoding != null)
						encoding = changeencoding;
					System.Text.Encoding enco;
					if ((byReceivedAdd[0] == 0xFE) && (byReceivedAdd[1] == 0xFF))
						enco = encoding;
					else
						enco = Encoding.ASCII;
					decodedstring = enco.GetString(byReceivedAdd, 0, received);

					if (decodedstring[0] == 0xFEFF) // remove BOM
						decodedstring = decodedstring.Substring(1);
					if (commandType == enAniDBCommandType.GetAnimeDescription || commandType == enAniDBCommandType.GetReview)
					{
						//Lets handle multipart
						part++;
						string[] sp1 = decodedstring.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

						if (sp1[0].StartsWith("233 ANIMEDESC") || sp1[0].StartsWith("233  ANIMEDESC"))
						{
							string[] sp2 = sp1[1].Split('|');
							fulldesc += sp2[2];
							maxpart = int.Parse(sp2[1]);
						}

						if (sp1[0].StartsWith("234 REVIEW") || sp1[0].StartsWith("234  REVIEW"))
						{
							string[] sp2 = sp1[1].Split('|');

							if (sp2.Length == 3)
								fulldesc += sp2[2];
							else
							{
								for (int i = 2; i < sp2.Length; i++)
									fulldesc += "|" + sp2[i];
							}


							maxpart = int.Parse(sp2[1]);
						}
						multipart = true;
						if (part == maxpart)
						{
							decodedstring = sp1[0] + "\n0|1|" + fulldesc + "\n";
							multipart = false;
						}
					}
				}
			} while ((multipart) && (!errorOccurred));

			if (errorOccurred)
			{
				socketResponse = string.Empty;
			}
			else
			{
				// there should be 2 newline characters in each response
				// the first is after the command .e.g "220 FILE"
				// the second is at the end of the data
				int i = 0, ipos = 0, foundpos = 0;
				foreach (char c in decodedstring)
				{
					if (c == '\n')
					{
						//MyAnimeLog.Write("NEWLINE FOUND AT: {0}", ipos);
						i++;
						foundpos = ipos;
					}
					ipos++;
				}

				if (i != 2)
				{
					socketResponse = decodedstring;

					TimeSpan ts = DateTime.Now - start;
					string msg = string.Format("UDP_RESPONSE in {0} ms - {1} ", ts.TotalMilliseconds, socketResponse);
					JMMService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg);
				}
				else
				{
					socketResponse = decodedstring.Substring(0, foundpos + 1);

					TimeSpan ts = DateTime.Now - start;
					string msg = string.Format("UDP_RESPONSE_TRUNC in {0}ms - {1} ", ts.TotalMilliseconds, socketResponse);
					JMMService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg);
				}
			}
			int val = 0;
			if (socketResponse.Length > 2)
				int.TryParse(socketResponse.Substring(0, 3), out val);
			this.ResponseCode = val;

			// if we get banned pause the command processor for a while
			// so we don't make the ban worse
			if (ResponseCode == 555)
			{
				JMMService.AnidbProcessor.IsBanned = true;
				JMMService.AnidbProcessor.BanOrigin = "UDP";
			}
			else
			{
				JMMService.AnidbProcessor.IsBanned = false;
				JMMService.AnidbProcessor.BanOrigin = "";
			}

			// 598 UNKNOWN COMMAND usually means we had connections issue
			// 506 INVALID SESSION
			// 505 ILLEGAL INPUT OR ACCESS DENIED
			// reset login status to start again
			if (ResponseCode == 598 || ResponseCode == 506 || ResponseCode == 506)
			{
				JMMService.AnidbProcessor.IsInvalidSession = true;
				logger.Trace("FORCING Logout because of invalid session");
				ForceReconnection();
			}

			// 600 INTERNAL SERVER ERROR
			// 601 ANIDB OUT OF SERVICE - TRY AGAIN LATER
			// 602 SERVER BUSY - TRY AGAIN LATER
			// 604 TIMEOUT - DELAY AND RESUBMIT
			if (ResponseCode == 600 || ResponseCode == 601 || ResponseCode == 602 || ResponseCode == 604)
			{
				string errormsg = "";
				switch (ResponseCode)
				{
					case 600: errormsg = "600 INTERNAL SERVER ERROR"; break;
					case 601: errormsg = "601 ANIDB OUT OF SERVICE - TRY AGAIN LATER"; break;
					case 602: errormsg = "602 SERVER BUSY - TRY AGAIN LATER"; break;
					case 604: errormsg = "TIMEOUT - DELAY AND RESUBMIT"; break;
				}
				logger.Trace("FORCING Logout because of invalid session");
				JMMService.AnidbProcessor.ExtendPause(300, errormsg);
			}
			
		}
예제 #27
0
		/// <summary>
		/// Inflate compressed swf
		/// </summary>
		protected void inflate() {
			
			// read size
			br.BaseStream.Position = 4; // skip signature
			int size = Convert.ToInt32(br.ReadUInt32());
			
			// read swf head
			byte[] uncompressed = new byte[size];			
			br.BaseStream.Position = 0;
			br.Read(uncompressed,0,8); // header data is not compre											
			
			// un-zip
			byte[] compressed = br.ReadBytes(size);	
			Inflater zipInflator = 	new Inflater();
			zipInflator.SetInput(compressed);
			zipInflator.Inflate(uncompressed,8,size-8);						
			
			// new memory stream for uncompressed swf
			MemoryStream m = new MemoryStream(uncompressed);
			br = new BinaryReader(m);
			br.BaseStream.Position = 0;
		}
예제 #28
0
            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)
                        {
                            if (onProgress != null)
                                onProgress((int)(100 * output.Position / file.ExpandedSize));

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

                        inf.Reset();
                    } while (toExtract > 0);
                }
                else
                {
                    do
                    {
                        if (onProgress != null)
                            onProgress((int)(100 * output.Position / file.ExpandedSize));

                        toExtract -= remainingInArchive;
                        output.Write(GetBytes(remainingInArchive), 0, (int)remainingInArchive);
                    } while (toExtract > 0);
                }
            }
예제 #29
0
        public byte[] unpack()
        {
            var resources = peImage.Resources;
            var dir = resources.getRoot();
            if ((dir = dir.getDirectory(10)) == null)
                return null;
            if ((dir = dir.getDirectory("__")) == null)
                return null;
            var dataEntry = dir.getData(0);
            if (dataEntry == null)
                return null;

            var encryptedData = peImage.readBytes(dataEntry.RVA, (int)dataEntry.Size);
            if (encryptedData.Length != dataEntry.Size)
                return null;

            var keyData = getKeyData();
            if (keyData == null)
                return null;
            var decrypter = new NativeFileDecrypter(keyData);
            decrypter.decrypt(encryptedData, 0, encryptedData.Length);

            byte[] inflatedData;
            if (isNet1x)
                inflatedData = DeobUtils.inflate(encryptedData, false);
            else {
                int inflatedSize = BitConverter.ToInt32(encryptedData, 0);
                inflatedData = new byte[inflatedSize];
                var inflater = new Inflater(false);
                inflater.SetInput(encryptedData, 4, encryptedData.Length - 4);
                int count = inflater.Inflate(inflatedData);
                if (count != inflatedSize)
                    return null;
            }

            if (BitConverter.ToInt16(inflatedData, 0) != 0x5A4D)
                return null;

            return inflatedData;
        }
예제 #30
0
 internal override int inflate(int pos, byte[] b, int o, Inflater inf)
 {
     byte[] tmp = new byte[512];
     var s = _stream;
     s.Position=pos;
     while ((s.Length-s.Position) > 0 && !inf.IsFinished)
     {
         if (inf.IsNeedingInput)
         {
             int n = (int)Math.Min((s.Length - s.Position), tmp.Length);
             s.Read(tmp, 0, n);
             inf.SetInput(tmp, 0, n);
         }
         o += inf.Inflate(b, o, b.Length - o);
     }
     while (!inf.IsFinished && !inf.IsNeedingInput)
         o += inf.Inflate(b, o, b.Length - o);
     return o;
 }
예제 #31
-11
		/// <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);
		}