SetInput() public method

Sets the input. This should only be called, if needsInput() returns true.
public SetInput ( byte buffer ) : void
buffer byte /// the input. ///
return void
		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));
			}
		}
		/// <exception cref="Sharpen.DataFormatException"></exception>
		protected internal override int SetInput(int pos, Inflater inf)
		{
			ByteBuffer s = buffer.Slice();
			s.Position(pos);
			byte[] tmp = new byte[Math.Min(s.Remaining(), 512)];
			s.Get(tmp, 0, tmp.Length);
			inf.SetInput(tmp, 0, tmp.Length);
			return tmp.Length;
		}
Beispiel #3
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;
        }
Beispiel #4
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;
        }
Beispiel #5
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));
 }
Beispiel #7
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);
 }
        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;
        }
 protected 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;
 }
Beispiel #10
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;
        }
Beispiel #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();
			}
		}
Beispiel #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);
 }
Beispiel #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();
        }
Beispiel #14
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;
     }
        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;
        }
		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;
		}
		/// <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;
			}
		}
		/// <exception cref="Sharpen.DataFormatException"></exception>
		protected internal override int SetInput(int pos, Inflater inf)
		{
			int n = array.Length - pos;
			inf.SetInput(array, pos, n);
			return n;
		}
Beispiel #19
0
		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;
		}
Beispiel #20
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);
			}
		}
			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);
				}
			}
Beispiel #22
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;
        }
        /// <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);
                }
            }
        }
        /// <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);
                }
            }
        }
Beispiel #25
0
		/// <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);
					}
				}
			}
		}
 /// <summary>
 /// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents.
 /// </summary>
 /// <param name="inflater">The inflater to set input for.</param>
 public void SetInflaterInput(Inflater inflater)
 {
     if ( available > 0 ) {
         inflater.SetInput(clearText, clearTextLength - available, available);
         available = 0;
     }
 }
Beispiel #27
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);
        }
Beispiel #28
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;
 }
Beispiel #29
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);
 }
 public void SetInflaterInput(Inflater inflater)
 {
     if (this.available > 0)
     {
         inflater.SetInput(this.clearText, this.clearTextLength - this.available, this.available);
         this.available = 0;
     }
 }
Beispiel #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);
		}