/// <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; } }
public NbtNode Read(int x, int z) { lock (this) { MoveToHeaderPosition(x, z); var index = _filePointer.ReadInt32(); if (index == 0) return null; // Not yet generated int usedSectors = index & 0xFF; int sectorOffset = index >> 8; _filePointer.Seek(sectorOffset*4096, SeekOrigin.Begin); int chunkLength = _filePointer.ReadInt32(); if (chunkLength == -1) return null; // Not yet generated byte compressionMode = _filePointer.ReadByte(); MemoryStream decompressStream; if (compressionMode == 0) { } if (compressionMode == 1) { byte[] buffer = new byte[chunkLength]; _filePointer.Read(buffer, 0, buffer.Length); buffer = Decompress(buffer); decompressStream = new MemoryStream(buffer); } else { byte[] buffer = new byte[chunkLength]; _filePointer.Read(buffer, 0, buffer.Length); var def = new Inflater(); decompressStream = new MemoryStream(); def.setInput(buffer); int i = 0; buffer = new byte[1024*1024]; try { while (!def.finished() && (i = def.inflate(buffer)) > 0) { decompressStream.Write(buffer, 0, i); } } catch { return null; } decompressStream.Seek(0, SeekOrigin.Begin); } return new NbtReader().ReadNbtFile(decompressStream); } }
public static void ReadCompressed(Stream s, List<string> classnames) { long start = s.Position; BinaryReader br = new BinaryReader(s); byte[] mem = new byte[(int)s.Length + 8]; byte[] buf = new byte[3]; s.Read(buf, 0, 3); s.Seek(start+4, SeekOrigin.Begin); int size = br.ReadInt32(); s.Seek(start+8, SeekOrigin.Begin); s.Read(mem, 0, (int)s.Length); s.Close(); br.Close(); try { s = new MemoryStream(mem); if (Encoding.Default.GetString(buf) == "CWS") { Inflater i = new Inflater(); i.SetInput(mem); byte[] mem2 = new byte[size + 8]; i.Inflate(mem2, 8, size); s = new MemoryStream(mem2); mem = new byte[0]; } s.Seek(0x15, SeekOrigin.Begin); br = new BinaryReader(s); while (br.BaseStream.Position < br.BaseStream.Length) { uint taglen = br.ReadUInt16(); uint len = taglen & 0x3f; uint tag = (taglen - len) / 64; if (len == 63) len = br.ReadUInt32(); start = br.BaseStream.Position; if (tag == 82) { FlashABC fabc = new FlashABC(br.BaseStream, len); fabc.FindClasses(classnames); } br.BaseStream.Seek(start + len, SeekOrigin.Begin); } br.Close(); } catch (Exception e) { Debug.Print(e.StackTrace); return; } }
public static void Main(string [] args) { if (args.Length == 0 || args.Length > 3) { Console.WriteLine ("Usage: zipmark FILE [ITERATIONS] [BLOCKSIZE]"); return; } string filename = args [0]; FileInfo file = new FileInfo (filename); if (!file.Exists) { Console.WriteLine ("Couldn't find file {0}", filename); return; } FileStream fs = file.OpenRead (); byte [] raw = new byte [file.Length]; int count = fs.Read (raw, 0, (int)file.Length); fs.Close (); if (count != file.Length) { Console.WriteLine ("Couldn't read file {0}", filename); return; } Deflater def = new Deflater (Deflater.BEST_COMPRESSION, false); Inflater inf = new Inflater (false); // 1. Count deflated size int cooked_size = Deflate (def, raw, null); byte [] cooked = new byte [cooked_size]; // 2. Deflate & Inflate if (args.Length > 1) Iterations = Int32.Parse (args [1]); if (args.Length > 2) BlockSize = Int32.Parse (args [2]); for (int i = 0; i < Iterations; ++ i) { Deflate (def, raw, cooked); Inflate (inf, cooked, raw); } return; }
public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen) { if(stream == null) { throw new ArgumentNullException("stream"); } if(mode == CompressionMode.Decompress) { if(!stream.CanRead) { throw new ArgumentException (S._("IO_NotReadable"), "stream"); } } else if(mode == CompressionMode.Compress) { if(!stream.CanWrite) { throw new ArgumentException (S._("IO_NotWritable"), "stream"); } } else { throw new ArgumentException (S._("IO_CompressionMode"), "mode"); } this.stream = stream; this.mode = mode; this.leaveOpen = leaveOpen; this.buf = new byte [4096]; this.crc32 = new Crc32(); this.endOfStream = false; this.headerDone = false; if(mode == CompressionMode.Decompress) { inflater = new Inflater(true); } else { deflater = new Deflater(-1, true); } }
public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) { this.isClosed = false; this.isStreamOwner = true; if (baseInputStream == null) { throw new ArgumentNullException("InflaterInputStream baseInputStream is null"); } if (inflater == null) { throw new ArgumentNullException("InflaterInputStream Inflater is null"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } this.baseInputStream = baseInputStream; this.inf = inflater; this.inputBuffer = new InflaterInputBuffer(baseInputStream); }
public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) { if(stream == null) { throw new ArgumentNullException("stream"); } if(mode == CompressionMode.Decompress) { if(!stream.CanRead) { throw new ArgumentException (S._("IO_NotReadable"), "stream"); } } else if(mode == CompressionMode.Compress) { if(!stream.CanWrite) { throw new ArgumentException (S._("IO_NotWritable"), "stream"); } } else { throw new ArgumentException (S._("IO_CompressionMode"), "mode"); } this.stream = stream; this.mode = mode; this.leaveOpen = leaveOpen; this.buf = new byte [4096]; if(mode == CompressionMode.Decompress) { inflater = new Inflater(); } else { deflater = new Deflater(); } }
internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, bool usingGZip) { _stream = stream; _mode = mode; _leaveOpen = leaveOpen; if (_stream == null) { throw new ArgumentNullException("stream"); } switch (_mode) { case CompressionMode.Decompress: if (!(_stream.CanRead)) { throw new ArgumentException("SR.NotReadableStream"); } _inflater = new Inflater(usingGZip); _mCallBack = new AsyncCallback(ReadCallback); break; case CompressionMode.Compress: if (!(_stream.CanWrite)) { throw new ArgumentException("SR.NotWriteableStream"); } _deflater = new Deflater(usingGZip); _mAsyncWriterDelegate = new AsyncWriteDelegate(this.InternalWrite); _mCallBack = new AsyncCallback(WriteCallback); break; default: throw new ArgumentException("SR.ArgumentOutOfRange_Enum"); } _buffer = new byte[BufferSize]; }
public void SetInflaterInput(Inflater inflater) { if (this.available > 0) { inflater.SetInput(this.clearText, this.clearTextLength - this.available, this.available); this.available = 0; } }
/// <summary> /// Create an InflaterInputStream with the specified decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The source of input data /// </param> /// <param name = "inf"> /// The decompressor used to decompress data read from baseInputStream /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 4096) { }
/// <exception cref="ICSharpCode.SharpZipLib.SharpZipBaseException"></exception> internal int SetInput(long pos, Inflater inf) { return(SetInput((int)(pos - start), inf)); }
public InflaterSource(Source source, Inflater inflater) : this(EasyIO.Buffer(source), inflater) { }
/// <summary> /// Pump bytes into the supplied inflater as input. /// </summary> /// <param name="pos"> /// offset within the file to start supplying input from. /// </param> /// <param name="dstbuf"> /// destination buffer the inflater should output decompressed /// data to. /// </param> /// <param name="dstoff"> /// current offset within <paramref name="dstbuf"/> to inflate into. /// </param> /// <param name="inf"> /// the inflater to feed input to. The caller is responsible for /// initializing the inflater as multiple windows may need to /// supply data to the same inflater to completely decompress /// something. /// </param> /// <returns> /// Updated <paramref name="dstoff"/> based on the number of bytes /// successfully copied into <paramref name="dstbuf"/> by /// <paramref name="inf"/>. If the inflater is not yet finished then /// another window's data must still be supplied as input to finish /// decompression. /// </returns> /// <exception cref="InvalidOperationException"> /// the inflater encountered an invalid chunk of data. Data /// stream corruption is likely. /// </exception> protected abstract int Inflate(int pos, byte[] dstbuf, int dstoff, Inflater inf);
void CheckReader() { if (reader == null) { if (!record.IsCompressed) throw new InvalidOperationException(); int compressedSize = checked((int)record.Size); int uncompressedSize = checked((int)compressedReader.ReadUInt32()); byte[] compressedData = new byte[compressedSize]; byte[] uncompressedData = new byte[uncompressedSize]; int compressedRead = compressedReader.Read(compressedData, 0, compressedSize); Inflater inflater = new Inflater(); inflater.SetInput(compressedData); int uncompressedRead = inflater.Inflate(uncompressedData, 0, uncompressedSize); reader = new BinaryReader(new MemoryStream(uncompressedData, false)); endOffset = uncompressedSize; } }
public InflaterInputStream(InputStream s) { this.@in = s; this.inf = new Inflater(); base.Wrapped = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(s.GetWrappedStream(), this.inf); }
/// <summary> /// Obtain an Inflater for decompression. /// <para /> /// Inflaters obtained through this cache should be returned (if possible) by /// <see cref="release(Inflater)"/> to avoid garbage collection and reallocation. /// </summary> /// <returns>An available inflater. Never null.</returns> public Inflater get() { Inflater r = getImpl(); return(r ?? new Inflater(false)); }
/// <summary> /// This version of dump is a translation from the open office escher dump routine. /// </summary> /// <param name="maxLength">The number of bytes to Read</param> /// <param name="in1">An input stream to Read from.</param> public void DumpOld(long maxLength, Stream in1) { long remainingBytes = maxLength; short options; // 4 bits for the version and 12 bits for the instance short recordId; int recordBytesRemaining; // including enclosing records StringBuilder stringBuf = new StringBuilder(); short nDumpSize; string recordName; bool atEOF = false; while (!atEOF && (remainingBytes > 0)) { stringBuf = new StringBuilder(); options = LittleEndian.ReadShort(in1); recordId = LittleEndian.ReadShort(in1); recordBytesRemaining = LittleEndian.ReadInt(in1); remainingBytes -= 2 + 2 + 4; switch (recordId) { case unchecked ((short)0xF000): recordName = "MsofbtDggContainer"; break; case unchecked ((short)0xF006): recordName = "MsofbtDgg"; break; case unchecked ((short)0xF016): recordName = "MsofbtCLSID"; break; case unchecked ((short)0xF00B): recordName = "MsofbtOPT"; break; case unchecked ((short)0xF11A): recordName = "MsofbtColorMRU"; break; case unchecked ((short)0xF11E): recordName = "MsofbtSplitMenuColors"; break; case unchecked ((short)0xF001): recordName = "MsofbtBstoreContainer"; break; case unchecked ((short)0xF007): recordName = "MsofbtBSE"; break; case unchecked ((short)0xF002): recordName = "MsofbtDgContainer"; break; case unchecked ((short)0xF008): recordName = "MsofbtDg"; break; case unchecked ((short)0xF118): recordName = "MsofbtRegroupItem"; break; case unchecked ((short)0xF120): recordName = "MsofbtColorScheme"; break; case unchecked ((short)0xF003): recordName = "MsofbtSpgrContainer"; break; case unchecked ((short)0xF004): recordName = "MsofbtSpContainer"; break; case unchecked ((short)0xF009): recordName = "MsofbtSpgr"; break; case unchecked ((short)0xF00A): recordName = "MsofbtSp"; break; case unchecked ((short)0xF00C): recordName = "MsofbtTextbox"; break; case unchecked ((short)0xF00D): recordName = "MsofbtClientTextbox"; break; case unchecked ((short)0xF00E): recordName = "MsofbtAnchor"; break; case unchecked ((short)0xF00F): recordName = "MsofbtChildAnchor"; break; case unchecked ((short)0xF010): recordName = "MsofbtClientAnchor"; break; case unchecked ((short)0xF011): recordName = "MsofbtClientData"; break; case unchecked ((short)0xF11F): recordName = "MsofbtOleObject"; break; case unchecked ((short)0xF11D): recordName = "MsofbtDeletedPspl"; break; case unchecked ((short)0xF005): recordName = "MsofbtSolverContainer"; break; case unchecked ((short)0xF012): recordName = "MsofbtConnectorRule"; break; case unchecked ((short)0xF013): recordName = "MsofbtAlignRule"; break; case unchecked ((short)0xF014): recordName = "MsofbtArcRule"; break; case unchecked ((short)0xF015): recordName = "MsofbtClientRule"; break; case unchecked ((short)0xF017): recordName = "MsofbtCalloutRule"; break; case unchecked ((short)0xF119): recordName = "MsofbtSelection"; break; case unchecked ((short)0xF122): recordName = "MsofbtUDefProp"; break; default: if (recordId >= unchecked ((short)0xF018) && recordId <= unchecked ((short)0xF117)) { recordName = "MsofbtBLIP"; } else if ((options & (short)0x000F) == (short)0x000F) { recordName = "UNKNOWN container"; } else { recordName = "UNKNOWN ID"; } break; } stringBuf.Append(" "); stringBuf.Append(HexDump.ToHex(recordId)); stringBuf.Append(" ").Append(recordName).Append(" ["); stringBuf.Append(HexDump.ToHex(options)); stringBuf.Append(','); stringBuf.Append(HexDump.ToHex(recordBytesRemaining)); stringBuf.Append("] instance: "); stringBuf.Append(HexDump.ToHex(((short)(options >> 4)))); Console.WriteLine(stringBuf.ToString()); if (recordId == (unchecked ((short)0xF007)) && 36 <= remainingBytes && 36 <= recordBytesRemaining) // BSE, FBSE // ULONG nP = pIn->GetRecPos(); { byte n8; // short n16; // int n32; stringBuf = new StringBuilder(" btWin32: "); n8 = (byte)in1.ReadByte(); stringBuf.Append(HexDump.ToHex(n8)); stringBuf.Append(GetBlipType(n8)); stringBuf.Append(" btMacOS: "); n8 = (byte)in1.ReadByte(); stringBuf.Append(HexDump.ToHex(n8)); stringBuf.Append(GetBlipType(n8)); Console.WriteLine(stringBuf.ToString()); Console.WriteLine(" rgbUid:"); HexDump.Dump(in1, 0, 16); Console.Write(" tag: "); OutHex(2, in1); Console.WriteLine(); Console.Write(" size: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" cRef: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" offs: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" usage: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" cbName: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" unused2: "); OutHex(4, in1); Console.WriteLine(); Console.Write(" unused3: "); OutHex(4, in1); Console.WriteLine(); // subtract the number of bytes we've Read remainingBytes -= 36; //n -= pIn->GetRecPos() - nP; recordBytesRemaining = 0; // loop to MsofbtBLIP } else if (recordId == unchecked ((short)0xF010) && 0x12 <= remainingBytes && 0x12 <= recordBytesRemaining) // ClientAnchor //ULONG nP = pIn->GetRecPos(); // short n16; { Console.Write(" Flag: "); OutHex(2, in1); Console.WriteLine(); Console.Write(" Col1: "); OutHex(2, in1); Console.Write(" dX1: "); OutHex(2, in1); Console.Write(" Row1: "); OutHex(2, in1); Console.Write(" dY1: "); OutHex(2, in1); Console.WriteLine(); Console.Write(" Col2: "); OutHex(2, in1); Console.Write(" dX2: "); OutHex(2, in1); Console.Write(" Row2: "); OutHex(2, in1); Console.Write(" dY2: "); OutHex(2, in1); Console.WriteLine(); remainingBytes -= 18; recordBytesRemaining -= 18; } else if (recordId == unchecked ((short)0xF00B) || recordId == unchecked ((short)0xF122)) // OPT { int nComplex = 0; Console.WriteLine(" PROPID VALUE"); while (recordBytesRemaining >= 6 + nComplex && remainingBytes >= 6 + nComplex) { short n16; int n32; n16 = LittleEndian.ReadShort(in1); n32 = LittleEndian.ReadInt(in1); recordBytesRemaining -= 6; remainingBytes -= 6; Console.Write(" "); Console.Write(HexDump.ToHex(n16)); Console.Write(" ("); int propertyId = n16 & (short)0x3FFF; Console.Write(" " + propertyId); if ((n16 & unchecked ((short)0x8000)) == 0) { if ((n16 & (short)0x4000) != 0) { Console.Write(", fBlipID"); } Console.Write(") "); Console.Write(HexDump.ToHex(n32)); if ((n16 & (short)0x4000) == 0) { Console.Write(" ("); Console.Write(Dec1616(n32)); Console.Write(')'); Console.Write(" {" + PropertyName((short)propertyId) + "}"); } Console.WriteLine(); } else { Console.Write(", fComplex) "); Console.Write(HexDump.ToHex(n32)); Console.Write(" - Complex prop len"); Console.WriteLine(" {" + PropertyName((short)propertyId) + "}"); nComplex += n32; } } // complex property data while ((nComplex & remainingBytes) > 0) { nDumpSize = (nComplex > (int)remainingBytes) ? (short)remainingBytes : (short)nComplex; HexDump.Dump(in1, 0, nDumpSize); nComplex -= nDumpSize; recordBytesRemaining -= nDumpSize; remainingBytes -= nDumpSize; } } else if (recordId == (unchecked ((short)0xF012))) { Console.Write(" Connector rule: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" ShapeID A: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" ShapeID B: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" ShapeID connector: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" Connect pt A: "); Console.Write(LittleEndian.ReadInt(in1)); Console.Write(" Connect pt B: "); Console.WriteLine(LittleEndian.ReadInt(in1)); recordBytesRemaining -= 24; remainingBytes -= 24; } else if (recordId >= unchecked ((short)0xF018) && recordId < unchecked ((short)0xF117)) { Console.WriteLine(" Secondary UID: "); HexDump.Dump(in1, 0, 16); Console.WriteLine(" Cache of size: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary top: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary left: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary width: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Boundary height: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" X: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Y: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Cache of saved size: " + HexDump.ToHex(LittleEndian.ReadInt(in1))); Console.WriteLine(" Compression Flag: " + HexDump.ToHex((byte)in1.ReadByte())); Console.WriteLine(" Filter: " + HexDump.ToHex((byte)in1.ReadByte())); Console.WriteLine(" Data (after decompression): "); recordBytesRemaining -= 34 + 16; remainingBytes -= 34 + 16; nDumpSize = (recordBytesRemaining > (int)remainingBytes) ? (short)remainingBytes : (short)recordBytesRemaining; byte[] buf = new byte[nDumpSize]; int Read = in1.Read(buf, 0, buf.Length); while (Read != -1 && Read < nDumpSize) { Read += in1.Read(buf, Read, buf.Length); } using (MemoryStream bin = new MemoryStream(buf)) { Inflater inflater = new Inflater(false); using (InflaterInputStream zIn = new InflaterInputStream(bin, inflater)) { int bytesToDump = -1; HexDump.Dump(zIn, 0, bytesToDump); recordBytesRemaining -= nDumpSize; remainingBytes -= nDumpSize; } } } bool isContainer = (options & (short)0x000F) == (short)0x000F; if (isContainer && remainingBytes >= 0) // Container { if (recordBytesRemaining <= (int)remainingBytes) { Console.WriteLine(" completed within"); } else { Console.WriteLine(" continued elsewhere"); } } else if (remainingBytes >= 0) // -> 0x0000 ... 0x0FFF { nDumpSize = (recordBytesRemaining > (int)remainingBytes) ? (short)remainingBytes : (short)recordBytesRemaining; if (nDumpSize != 0) { HexDump.Dump(in1, 0, nDumpSize); remainingBytes -= nDumpSize; } } else { Console.WriteLine(" >> OVERRUN <<"); } } }
public static byte[] Inflate(byte[] data, Inflater inflater) { return(Inflate(data, 0, data.Length, inflater)); }
/// <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 + 1]; byte green = uncompressed[j + 2]; byte blue = uncompressed[j + 3]; byte alpha = uncompressed[j]; _alphaBitmapData.BitmapPixelData[i] = new RGBA(red, green, blue, alpha); } } }
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; AniDbRateLimiter.Instance.EnsureRate(); 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.Empty; string decodedstring = string.Empty; DateTime start = DateTime.Now; do { if (part > 0) { mcommandText = mcommandText.Replace("part=" + (part - 1).ToString(), "part=" + part.ToString()); AniDbRateLimiter.Instance.EnsureRate(); } if (commandType != enAniDBCommandType.Login) { string msg = string.Format("UDP_COMMAND: {0}", mcommandText); ShokoService.LogToSystem(Constants.DBLogType.APIAniDBUDP, msg); } else { //string msg = commandText.Replace(ShokoServer.settings.Username, "******"); //msg = msg.Replace(ShokoServer.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 { ShokoService.LastAniDBMessage = DateTime.Now; ShokoService.LastAniDBUDPMessage = DateTime.Now; if (commandType != enAniDBCommandType.Ping) { ShokoService.LastAniDBMessageNonPing = DateTime.Now; } else { ShokoService.LastAniDBPing = DateTime.Now; } soUDP.SendTo(SendByteAdd, remoteIpEndPoint); } catch (Exception ex) { logger.Error(ex, ex.ToString()); //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); ShokoService.LastAniDBMessage = DateTime.Now; ShokoService.LastAniDBUDPMessage = DateTime.Now; if (commandType != enAniDBCommandType.Ping) { ShokoService.LastAniDBMessageNonPing = DateTime.Now; } else { ShokoService.LastAniDBPing = DateTime.Now; } //MyAnimeLog.Write("Buffer length = {0}", received.ToString()); if ((received > 2) && (byReceivedAdd[0] == 0) && (byReceivedAdd[1] == 0)) { //deflate var buff = new byte[65536]; var input = new byte[received - 2]; Array.Copy(byReceivedAdd, 2, input, 0, received - 2); var 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.Error(sex, sex.ToString()); errorOccurred = true; errorMessage = sex.ToString(); } catch (Exception ex) { logger.Error(ex, ex.ToString()); 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); ShokoService.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); ShokoService.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 ShokoService.AnidbProcessor.IsUdpBanned = ResponseCode == 555; // 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 == 505) { ShokoService.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 = string.Empty; 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"); ShokoService.AnidbProcessor.ExtendPause(300, errormsg); } }
/// <summary> /// Create an InflaterInputStream with the specified decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The source of input data /// </param> /// <param name = "inf"> /// The decompressor used to decompress data read from baseInputStream /// </param> internal InflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 4096) { }
public InflaterInputStream(InputStream s, Inflater i, int bufferSize) { this.@in = s; this.inf = i; base.Wrapped = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(s.GetWrappedStream(), i, bufferSize); }
// Note: The .NET Framework SDK 2.0 version of this class does // not have BeginWrite and EndWrite for some inexplicable reason. // Close this stream. public override void Close() { if(stream != null) { if(deflater != null) { int temp; deflater.Finish(); while(!deflater.IsFinished) { temp = deflater.Deflate(buf, 0, buf.Length); if(temp <= 0) { if(!deflater.IsFinished) { throw new IOException (S._("IO_Compress_Input")); } break; } stream.Write(buf, 0, temp); } byte[] footer = new byte [8]; temp = (int)(crc32.Value); footer[0] = (byte)temp; footer[1] = (byte)(temp << 8); footer[2] = (byte)(temp << 16); footer[3] = (byte)(temp << 24); temp = deflater.TotalIn; footer[4] = (byte)temp; footer[5] = (byte)(temp << 8); footer[6] = (byte)(temp << 16); footer[7] = (byte)(temp << 24); stream.Write(footer, 0, 8); } if(!leaveOpen) { stream.Close(); } stream = null; inflater = null; deflater = null; buf = null; } }
public DeflateStream(InputStream @in, Inflater inflater) : base(@in, inflater) { }
private bool CheckSwf(bool is_comp) { this.format = MediaFormat.SWF; this.reader = new BinaryReader(this.stream); if (is_comp) { int size = -1; this.reader.BaseStream.Position = 4; // Skip head size = Convert.ToInt32(this.reader.ReadUInt32()); // Read swf head byte[] uncompressed = new byte[size]; this.reader.BaseStream.Position = 0; this.reader.Read(uncompressed, 0, 8); // Read compressed data byte[] compressed = this.reader.ReadBytes(size); this.stream.Close(); // Close the old stream // Uncompress Inflater zipInflator = new Inflater(); zipInflator.SetInput(compressed); zipInflator.Inflate(uncompressed, 8, size - 8); // Setup new uncompressed reader this.reader = new BinaryReader(new MemoryStream(uncompressed)); this.reader.BaseStream.Position = 0; } // Skip header signature/version etc etc this.reader.BaseStream.Position = 8; // Read rect uint bits = ReadUBits(5); ReadSBits(bits); // Read xmin this.width = ReadSBits(bits) / 20; // Read xmax ReadSBits(bits); // Read ymin this.height = ReadSBits(bits) / 20; // Read ymax return true; }
public static string Decompress(String str) { // Initialize decompressor. byte[] compressedBytes = Convert.FromBase64String(str); Inflater decompressor = new Inflater(); decompressor.SetInput(compressedBytes); // Give the decompressor the // data to decompress. byte[] ret = null; using (MemoryStream memStream = new MemoryStream(compressedBytes.Length)) { // Decompress the data byte[] buf = new byte[compressedBytes.Length + 100]; while (!decompressor.IsFinished) { memStream.Write(buf, 0, decompressor.Inflate(buf)); } memStream.Close(); ret = memStream.ToArray(); } return ASCIIEncoding.UTF8.GetString(ret); }
public InflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 0x1000) { }
private void decompress(AnyObjectId id, Inflater inf, int p) { try { while (!inf.IsFinished) p += inf.Inflate(bytes, p, objectSize - p); } catch (IOException dfe) { CorruptObjectException coe; coe = new CorruptObjectException(id, "bad stream", dfe); throw coe; } if (p != objectSize) throw new CorruptObjectException(id, "incorrect Length"); }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="NGit.Errors.StoredObjectRepresentationNotAvailableException"></exception> private void CopyAsIs2(PackOutputStream @out, LocalObjectToPack src, bool validate , WindowCursor curs) { CRC32 crc1 = validate ? new CRC32() : null; CRC32 crc2 = validate ? new CRC32() : null; byte[] buf = @out.GetCopyBuffer(); // Rip apart the header so we can discover the size. // ReadFully(src.offset, buf, 0, 20, curs); int c = buf[0] & unchecked ((int)(0xff)); int typeCode = (c >> 4) & 7; long inflatedLength = c & 15; int shift = 4; int headerCnt = 1; while ((c & unchecked ((int)(0x80))) != 0) { c = buf[headerCnt++] & unchecked ((int)(0xff)); inflatedLength += (c & unchecked ((int)(0x7f))) << shift; shift += 7; } if (typeCode == Constants.OBJ_OFS_DELTA) { do { c = buf[headerCnt++] & unchecked ((int)(0xff)); }while ((c & 128) != 0); if (validate) { crc1.Update(buf, 0, headerCnt); crc2.Update(buf, 0, headerCnt); } } else { if (typeCode == Constants.OBJ_REF_DELTA) { if (validate) { crc1.Update(buf, 0, headerCnt); crc2.Update(buf, 0, headerCnt); } ReadFully(src.offset + headerCnt, buf, 0, 20, curs); if (validate) { crc1.Update(buf, 0, 20); crc2.Update(buf, 0, 20); } headerCnt += 20; } else { if (validate) { crc1.Update(buf, 0, headerCnt); crc2.Update(buf, 0, headerCnt); } } } long dataOffset = src.offset + headerCnt; long dataLength = src.length; long expectedCRC; ByteArrayWindow quickCopy; // Verify the object isn't corrupt before sending. If it is, // we report it missing instead. // try { quickCopy = curs.QuickCopy(this, dataOffset, dataLength); if (validate && Idx().HasCRC32Support()) { // Index has the CRC32 code cached, validate the object. // expectedCRC = Idx().FindCRC32(src); if (quickCopy != null) { quickCopy.Crc32(crc1, dataOffset, (int)dataLength); } else { long pos = dataOffset; long cnt = dataLength; while (cnt > 0) { int n = (int)Math.Min(cnt, buf.Length); ReadFully(pos, buf, 0, n, curs); crc1.Update(buf, 0, n); pos += n; cnt -= n; } } if (crc1.GetValue() != expectedCRC) { SetCorrupt(src.offset); throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().objectAtHasBadZlibStream , src.offset, GetPackFile())); } } else { if (validate) { // We don't have a CRC32 code in the index, so compute it // now while inflating the raw data to get zlib to tell us // whether or not the data is safe. // Inflater inf = curs.Inflater(); byte[] tmp = new byte[1024]; if (quickCopy != null) { quickCopy.Check(inf, tmp, dataOffset, (int)dataLength); } else { long pos = dataOffset; long cnt = dataLength; while (cnt > 0) { int n = (int)Math.Min(cnt, buf.Length); ReadFully(pos, buf, 0, n, curs); crc1.Update(buf, 0, n); inf.SetInput(buf, 0, n); while (inf.Inflate(tmp, 0, tmp.Length) > 0) { continue; } pos += n; cnt -= n; } } if (!inf.IsFinished || inf.TotalIn != dataLength) { SetCorrupt(src.offset); throw new EOFException(MessageFormat.Format(JGitText.Get().shortCompressedStreamAt , src.offset)); } expectedCRC = crc1.GetValue(); } else { expectedCRC = -1; } } } catch (SharpZipBaseException dataFormat) { SetCorrupt(src.offset); CorruptObjectException corruptObject = new CorruptObjectException(MessageFormat.Format (JGitText.Get().objectAtHasBadZlibStream, src.offset, GetPackFile())); Sharpen.Extensions.InitCause(corruptObject, dataFormat); StoredObjectRepresentationNotAvailableException gone; gone = new StoredObjectRepresentationNotAvailableException(src); Sharpen.Extensions.InitCause(gone, corruptObject); throw gone; } catch (IOException ioError) { StoredObjectRepresentationNotAvailableException gone; gone = new StoredObjectRepresentationNotAvailableException(src); Sharpen.Extensions.InitCause(gone, ioError); throw gone; } if (quickCopy != null) { // The entire object fits into a single byte array window slice, // and we have it pinned. Write this out without copying. // @out.WriteHeader(src, inflatedLength); quickCopy.Write(@out, dataOffset, (int)dataLength, null); } else { if (dataLength <= buf.Length) { // Tiny optimization: Lots of objects are very small deltas or // deflated commits that are likely to fit in the copy buffer. // if (!validate) { long pos = dataOffset; long cnt = dataLength; while (cnt > 0) { int n = (int)Math.Min(cnt, buf.Length); ReadFully(pos, buf, 0, n, curs); pos += n; cnt -= n; } } @out.WriteHeader(src, inflatedLength); @out.Write(buf, 0, (int)dataLength); } else { // Now we are committed to sending the object. As we spool it out, // check its CRC32 code to make sure there wasn't corruption between // the verification we did above, and us actually outputting it. // @out.WriteHeader(src, inflatedLength); long pos = dataOffset; long cnt = dataLength; while (cnt > 0) { int n = (int)Math.Min(cnt, buf.Length); ReadFully(pos, buf, 0, n, curs); if (validate) { crc2.Update(buf, 0, n); } @out.Write(buf, 0, n); pos += n; cnt -= n; } if (validate && crc2.GetValue() != expectedCRC) { throw new CorruptObjectException(MessageFormat.Format(JGitText.Get().objectAtHasBadZlibStream , src.offset, GetPackFile())); } } } }
public static int DecompressBlock(byte[] inBuffer, int inLength, byte[] outBuffer, bool multi) { if (!multi) { return(DclCompression.DecompressBlock(inBuffer, 0, inLength, outBuffer)); } else // Examinate first byte for finding compression methods used { switch (inBuffer[0]) { case 0x01: // Huffman throw new MpqCompressionNotSupportedException(0x01, "Huffman"); case 0x02: // Zlib (Deflate/Inflate) Inflater.Reset(); // The first property read will initialize the field… inflater.SetInput(inBuffer, 1, inLength - 1); return(inflater.Inflate(outBuffer)); case 0x08: // PKWare DCL (Implode/Explode) return(DclCompression.DecompressBlock(inBuffer, 1, inLength - 1, outBuffer)); case 0x10: // BZip2 using (var inStream = new MemoryStream(inBuffer, 1, inLength - 1, false, false)) using (var outStream = new BZip2InputStream(inStream)) return(outStream.Read(outBuffer, 0, outBuffer.Length)); case 0x12: // LZMA using (var inStream = new MemoryStream(inBuffer, 1, inLength - 1, false, false)) using (var outStream = new MemoryStream(outBuffer, true)) { lzmaDecoder.Code(inStream, outStream, inStream.Length, outStream.Length, null); return(checked ((int)outStream.Position)); } case 0x20: // Sparse return(SparseCompression.DecompressBlock(inBuffer, 1, inLength - 1, outBuffer)); case 0x22: // Sparse + Deflate #if USE_SHARPZIPLIB // Use SharpZipLib's Deflate implementation Inflater.Reset(); // The first property read will initialize the field… inflater.SetInput(inBuffer, 1, inLength - 1); tempBuffer = CommonMethods.GetSharedBuffer(outBuffer.Length); return(SparseCompression.DecompressBlock(tempBuffer, 0, inflater.Inflate(tempBuffer), outBuffer)); #else // Use .NET 2.0's built-in inflate algorithm using (var inStream = new MemoryStream(inBuffer, 3, inLength - 7, false, false)) using (var inoutStream = new DeflateStream(inStream, CompressionMode.Decompress)) using (var outStream = new SparseInputStream(inoutStream)) return(outStream.Read(outBuffer, 0, outBuffer.Length)); #endif case 0x30: // Sparse + BZip2 using (var inStream = new MemoryStream(inBuffer, 1, inLength - 1, false, false)) using (var inoutStream = new BZip2InputStream(inStream)) using (var outStream = new SparseInputStream(inoutStream)) return(outStream.Read(outBuffer, 0, outBuffer.Length)); case 0x40: // Mono IMA ADPCM using (var inStream = new MemoryStream(inBuffer, 1, inLength - 1, false, false)) { var decompressedStream = MpqHuffman.Decompress(inStream); byte[] decompressed = MpqWavCompression.Decompress(decompressedStream, 1); Buffer.BlockCopy(decompressed, 0, outBuffer, 0, decompressed.Length); return(decompressed.Length); } case 0x41: // Mono IMA ADPCM + Huffman using (var inStream = new MemoryStream(inBuffer, 1, inLength - 1, false, false)) { var decompressedStream = MpqHuffman.Decompress(inStream); byte[] decompressed = MpqWavCompression.Decompress(decompressedStream, 1); Buffer.BlockCopy(decompressed, 0, outBuffer, 0, decompressed.Length); return(decompressed.Length); } case 0x48: // Mono IMA ADPCM + Implode throw new MpqCompressionNotSupportedException(0x48, "Mono IMA ADPCM + Implode"); case 0x80: // Stereo IMA ADPCM using (var inStream = new MemoryStream(inBuffer, 1, inLength - 1, false, false)) { byte[] decompressed = MpqWavCompression.Decompress(inStream, 2); Buffer.BlockCopy(decompressed, 0, outBuffer, 0, decompressed.Length); return(decompressed.Length); } case 0x81: // Stereo IMA ADPCM + Huffman using (var inStream = new MemoryStream(inBuffer, 1, inLength - 1, false, false)) { var decompressedStream = MpqHuffman.Decompress(inStream); byte[] decompressed = MpqWavCompression.Decompress(decompressedStream, 2); Buffer.BlockCopy(decompressed, 0, outBuffer, 0, decompressed.Length); return(decompressed.Length); } case 0x88: // Stereo IMA ADPCM + Implode throw new MpqCompressionNotSupportedException(0x88, "Stereo IMA ADPCM + Implode"); default: throw new MpqCompressionNotSupportedException(inBuffer[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)); } }
/// <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); } } } }
/// <exception cref="ICSharpCode.SharpZipLib.SharpZipBaseException"></exception> protected internal abstract int SetInput(int pos, Inflater inf);
private UnpackedObjectLoader(byte[] compressed, AnyObjectId id) { // Try to determine if this is a legacy format loose object or // a new style loose object. The legacy format was completely // compressed with zlib so the first byte must be 0x78 (15-bit // window size, deflated) and the first 16 bit word must be // evenly divisible by 31. Otherwise its a new style loose // object. // Inflater inflater = InflaterCache.Instance.get(); try { int fb = compressed[0] & 0xff; if (fb == 0x78 && (((fb << 8) | compressed[1] & 0xff) % 31) == 0) { inflater.SetInput(compressed); var hdr = new byte[64]; int avail = 0; while (!inflater.IsFinished && avail < hdr.Length) { try { avail += inflater.Inflate(hdr, avail, hdr.Length - avail); } catch (IOException dfe) { var coe = new CorruptObjectException(id, "bad stream", dfe); //inflater.end(); throw coe; } } if (avail < 5) { throw new CorruptObjectException(id, "no header"); } var p = new MutableInteger(); _objectType = Constants.decodeTypeString(id, hdr, (byte)' ', p); _objectSize = RawParseUtils.parseBase10(hdr, p.value, p); if (_objectSize < 0) { throw new CorruptObjectException(id, "negative size"); } if (hdr[p.value++] != 0) { throw new CorruptObjectException(id, "garbage after size"); } _bytes = new byte[_objectSize]; if (p.value < avail) { Array.Copy(hdr, p.value, _bytes, 0, avail - p.value); } Decompress(id, inflater, avail - p.value); } else { int p = 0; int c = compressed[p++] & 0xff; int typeCode = (c >> 4) & 7; int size = c & 15; int shift = 4; while ((c & 0x80) != 0) { c = compressed[p++] & 0xff; size += (c & 0x7f) << shift; shift += 7; } switch (typeCode) { case Constants.OBJ_COMMIT: case Constants.OBJ_TREE: case Constants.OBJ_BLOB: case Constants.OBJ_TAG: _objectType = typeCode; break; default: throw new CorruptObjectException(id, "invalid type"); } _objectSize = size; _bytes = new byte[_objectSize]; inflater.SetInput(compressed, p, compressed.Length - p); Decompress(id, inflater, 0); } } finally { InflaterCache.Instance.release(inflater); } }
public Decrypter3(ModuleDefMD module, MethodDef decryptMethod) { this.module = module; this.inflater = InflaterCreator.Create(decryptMethod, true); }
public ReadableDeflateChannel(int bits) { _inflater = new Inflater(bits); }
private static byte[] Inflate(BinaryReader aReader, long aLength) { Stream raw = aReader.BaseStream; Inflater inflater = new Inflater(); InflaterInputStream stream = new InflaterInputStream(raw, inflater); long position = raw.Position; byte[] bytes = new byte[aLength]; stream.Read(bytes, 0, (int)aLength); raw.Position = position + inflater.TotalIn + 4; // don't know why we add 4 but it works return (bytes); }
/// <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); } } }
// Close this stream. public override void Close() { if(stream != null) { if(deflater != null) { int temp; deflater.Finish(); while(!deflater.IsFinished) { temp = deflater.Deflate(buf, 0, buf.Length); if(temp <= 0) { if(!deflater.IsFinished) { throw new IOException (S._("IO_Compress_Input")); } break; } stream.Write(buf, 0, temp); } } if(!leaveOpen) { stream.Close(); } stream = null; inflater = null; deflater = null; buf = null; } }
public static byte[] Inflate(byte[] data, Inflater inflater) => Inflate(data, 0, data.Length, inflater);
public override void Read(hsStream s, hsResMgr mgr) { base.Read(s, mgr); // Cache it. fVersion = mgr.Version; // Cyan stores these values, but we're just going to // save the stream and have fun with it... fBuffer = new byte[s.ReadInt()]; Compression type = (Compression)s.ReadByte(); uint len = s.ReadUInt(); if (type == Compression.kZlib) { short streamType = s.ReadShort(); byte[] buf = s.ReadBytes((int)len - 2); // Create a zlib-compatible inflator // Note: incoming has no zlib header/footer // System.IO.Compression sucks. Inflater zlib = new Inflater(true); zlib.Inflate(buf); Buffer.BlockCopy(BitConverter.GetBytes(streamType), 0, fBuffer, 0, 2); Buffer.BlockCopy(buf, 0, fBuffer, 2, buf.Length); } else fBuffer = s.ReadBytes((int)len); }
public FlashReadFile(string file) { FileStream fs = new FileStream(file, FileMode.Open); BinaryReader br = new BinaryReader(fs); byte[] mem = new byte[(int)fs.Length + 8]; byte[] buf = new byte[3]; fs.Read(buf, 0, 3); fs.Seek(4, SeekOrigin.Begin); int size = br.ReadInt32(); fs.Seek(8, SeekOrigin.Begin); fs.Read(mem, 0, (int)fs.Length); fs.Close(); br.Close(); s = new MemoryStream(mem); if (Encoding.Default.GetString(buf) == "CWS") { Inflater i = new Inflater(); i.SetInput(mem); byte[] mem2 = new byte[size + 8]; i.Inflate(mem2, 8, size); s = new MemoryStream(mem2); mem = new byte[0]; } s.Seek(0x15, SeekOrigin.Begin); br = new BinaryReader(s); while (br.BaseStream.Position < br.BaseStream.Length) { uint taglen = br.ReadUInt16(); uint len = taglen & 0x3f; uint tag = (taglen - len) / 64; if (len == 63) len = br.ReadUInt32(); long start = br.BaseStream.Position; if (tag == 82) { FlashABC fabc = new FlashABC(br.BaseStream, len); List<string> classnames = new List<string>(); classnames.Add("cPlayerData"); fabc.FindClasses(classnames); } //Debug.Print("{0} {1}", tag, len+2); br.BaseStream.Seek(start + len, SeekOrigin.Begin); } fClass.InitClasses(); br.Close(); }
static int Inflate(Inflater inf, byte [] src, byte [] dest) { int offset, length, remain; inf.Reset (); inf.SetInput (src); offset = 0; while (!inf.IsNeedingInput) { remain = Math.Min (dest.Length - offset, BlockSize); if (remain == 0) break; length = inf.Inflate (dest, offset, remain); offset += length; } return inf.TotalOut; }
public static byte[] Unzip(byte[] buffer) { Assembly callingAssembly = Assembly.GetCallingAssembly(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); if ((callingAssembly != executingAssembly) && !PublicKeysMatch(executingAssembly, callingAssembly)) { return null; } ZipStream stream = new ZipStream(buffer); byte[] buf = new byte[0]; int num = stream.ReadInt(); if (num == 0x4034b50) { short num2 = (short) stream.ReadShort(); int num3 = stream.ReadShort(); int num4 = stream.ReadShort(); if (((num != 0x4034b50) || (num2 != 20)) || ((num3 != 0) || (num4 != 8))) { throw new FormatException("Wrong Header Signature"); } stream.ReadInt(); stream.ReadInt(); stream.ReadInt(); int num5 = stream.ReadInt(); int count = stream.ReadShort(); int num7 = stream.ReadShort(); if (count > 0) { byte[] buffer3 = new byte[count]; stream.Read(buffer3, 0, count); } if (num7 > 0) { byte[] buffer4 = new byte[num7]; stream.Read(buffer4, 0, num7); } byte[] buffer5 = new byte[stream.Length - stream.Position]; stream.Read(buffer5, 0, buffer5.Length); Inflater inflater = new Inflater(buffer5); buf = new byte[num5]; inflater.Inflate(buf, 0, buf.Length); buffer5 = null; } else { int num8 = num >> 0x18; num -= num8 << 0x18; if (num == 0x7d7a7b) { switch (num8) { case 1: { int num12; int num9 = stream.ReadInt(); buf = new byte[num9]; for (int i = 0; i < num9; i += num12) { int num11 = stream.ReadInt(); num12 = stream.ReadInt(); byte[] buffer6 = new byte[num11]; stream.Read(buffer6, 0, buffer6.Length); new Inflater(buffer6).Inflate(buf, i, num12); } break; } case 2: { byte[] buffer7 = new byte[] { 0x94, 0xad, 0xc3, 0x85, 0xa5, 0x2a, 0xbd, 9 }; byte[] buffer8 = new byte[] { 0xbf, 0x45, 3, 0x1a, 0x41, 80, 14, 0xbf }; using (ICryptoTransform transform = GetDesTransform(buffer7, buffer8, true)) { buf = Unzip(transform.TransformFinalBlock(buffer, 4, buffer.Length - 4)); } break; } } if (num8 != 3) { goto Label_026B; } byte[] key = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; byte[] iv = new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; using (ICryptoTransform transform2 = GetAesTransform(key, iv, true)) { buf = Unzip(transform2.TransformFinalBlock(buffer, 4, buffer.Length - 4)); goto Label_026B; } } throw new FormatException("Unknown Header"); } Label_026B: stream.Close(); stream = null; return buf; }
internal void inflateVerify(long pos, Inflater inf) { inflateVerify((int)(pos - _start), inf); }
protected override byte[] ProcessFile(string fileName, PresetParserMetadata preset) { var chunkData = base.ProcessFile(fileName, preset); var ms = new MemoryStream(chunkData); var parameterSize = ms.ReadInt32(); ms.Seek(parameterSize, SeekOrigin.Current); var metadataSize = ms.ReadInt32(); var metadataBuf = new byte[metadataSize]; ms.Read(metadataBuf, 0, metadataSize); var inflater = new Inflater(false); inflater.SetInput(metadataBuf); var size = inflater.Inflate(_decodeBuffer); var metadata = _decodeBuffer.GetRange(0, size).ToArray(); var metadataString = Encoding.UTF8.GetString(metadata); var tokens = metadataString.Split(','); var metadataDictionary = new Dictionary <string, string>(); var isKey = true; var key = ""; foreach (var token in tokens) { if (isKey) { key = token; } else { try { metadataDictionary.Add(key, token); } catch (ArgumentException) { // Do nothing } } isKey = !isKey; } if (metadataDictionary.ContainsKey("Comment")) { preset.Comment = metadataDictionary["Comment"]; } if (metadataDictionary.ContainsKey("Author")) { preset.Author = metadataDictionary["Author"]; } ApplyType(int.Parse(metadataDictionary["Type"]), preset); return(chunkData); }
protected abstract void inflateVerify(int pos, Inflater inf);
public ReadableDeflateTransform(int bits) { _inflater = new Inflater(bits); }
public void PackText(FileStream fileStream, uint off, uint zsize, uint size, Dictionary <ulong, string> dbd, uint hash2, uint hash1, int endtable, int somework) { BinaryReader binaryReader = new BinaryReader(fileStream); binaryReader.BaseStream.Position = off; binaryReader.ReadBytes(36); byte[] input = binaryReader.ReadBytes((int)zsize); byte[] buffer = new byte[size]; Inflater inflater = new Inflater(); inflater.SetInput(input); inflater.Inflate(buffer); BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer)); binaryReader2.ReadBytes(3); int num = binaryReader2.ReadInt32(); int num2 = num * 26 + 7; Dictionary <ulong, string> dictionary = new Dictionary <ulong, string>(); int num3 = 0; MemoryStream memoryStream = new MemoryStream(); BinaryWriter binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write((byte)1); binaryWriter.Write((byte)0); binaryWriter.Write((byte)0); binaryWriter.Write(num); while (num3 < num) { long num4 = binaryReader2.ReadInt64(); byte b = binaryReader2.ReadByte(); byte value = binaryReader2.ReadByte(); float value2 = binaryReader2.ReadSingle(); int num5 = binaryReader2.ReadInt32(); int num6 = binaryReader2.ReadInt32(); binaryReader2.ReadInt32(); long position = binaryReader2.BaseStream.Position; string change_value = "0"; if (num5 > 0) { binaryReader2.BaseStream.Seek(num6, SeekOrigin.Begin); byte[] bytes = binaryReader2.ReadBytes(num5); string text = Encoding.UTF8.GetString(bytes).Replace("\n", "\\n"); ulong key = uniqueId(num4, b); if (changes == "1") { if (dictionary_en.TryGetValue(key, out string _)) { if (dictionary_en[key] != text) { dbd.Remove(key); change_value = "1"; } else { change_value = "0"; } } } if (dbd.TryGetValue(key, out string _)) { dictionary.Add(key, dbd[key]); _ = dbd[key]; num5 = Encoding.UTF8.GetBytes(dbd[key].Replace("\\n", "\n")).Length; } else { transl_a = ""; if (ConfigurationManager.AppSettings["a_translate"] == "1" && somework == 1) { if (File.Exists(@"C:\\Program Files\\Mozilla Firefox\\firefox.exe") || File.Exists(@"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe")) { transl_a = Translator(text, "Deepl"); /*string instrrr = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(transl_a) + "','Deepl');"; * using (StreamWriter file_for_exam = new StreamWriter("db\\deepl_trans.txt", true)) * { * file_for_exam.WriteLine(instrrr); * } * transl_a = "";*/ } else { transl_a = Translator(text, "Promt"); } } if (transl_a == "") { dictionary.Add(key, text); dictionary_xml_m.Add(key, text); dictionary_xml_w.Add(key, text); dictionary_xml_translator_m.Add(key, "Deepl"); num5 = Encoding.UTF8.GetBytes(text.Replace("\\n", "\n")).Length; } else { dictionary.Add(key, transl_a); dictionary_xml_m.Add(key, transl_a); dictionary_xml_w.Add(key, transl_a); dictionary_xml_translator_m.Add(key, "Deepl"); num5 = Encoding.UTF8.GetBytes(transl_a.Replace("\\n", "\n")).Length; using (SQLiteConnection sqlite_conn = new SQLiteConnection("Data Source=db\\translate.db3; Version = 3; New = True; Compress = True; ")) { sqlite_conn.Open(); using (SQLiteCommand sqlite_cmd = new SQLiteCommand(sqlite_conn)) { if (change_value == "1") { sqlite_cmd.CommandText = "UPDATE Translated SET text_en='" + WebUtility.HtmlEncode(text) + "', text_ru_m='" + WebUtility.HtmlEncode(transl_a) + "',translator_m='Deepl',text_ru_w=NULL,translator_w=NULL WHERE key_unic ='" + key + "'"; } else { sqlite_cmd.CommandText = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(transl_a) + "','Deepl')"; } sqlite_cmd.ExecuteNonQuery(); } } } /*string xml_text = "<hash>" + hash1 + "</hash><key>" + key + "</key><text_en>" + WebUtility.HtmlEncode(text) + "</text_en>"; * using (StreamWriter file_for_exam = * new StreamWriter("db\\new_eng.txt", true)) * { * file_for_exam.WriteLine(xml_text); * } * * string xml_text = "<filesinfo></filesinfo><hash>" + hash1 + "</hash><key>" + key + "</key><text_en>" + WebUtility.HtmlEncode(text) + "</text_en><text_ru_m transl=\"3\">" + WebUtility.HtmlEncode(dbd[key]) + "</text_ru_m><text_ru_w transl=\"3\"></text_ru_w>"; * using (StreamWriter file_for_exam = * new StreamWriter(@"C:\Users\Tidus\source\repos\SWToR_RUS\bin\Debug\db\all2.txt", true, encoding: Encoding.UTF8)) * { * file_for_exam.WriteLine(xml_text); * } * SQLiteConnection sqlite_conn; * sqlite_conn = new SQLiteConnection("Data Source=db\\translate.db3; Version = 3; New = True; Compress = True; "); * sqlite_conn.Open(); * SQLiteCommand sqlite_cmd; * sqlite_cmd = sqlite_conn.CreateCommand(); * string sql_insert = "INSERT INTO Translated (hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1.ToString() + "','" + key.ToString() + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dbd[key]) + "','3')"; * sqlite_cmd.CommandText = sql_insert; * sqlite_cmd.ExecuteNonQuery(); * sqlite_conn.Close();*/ } /*if (somework == 1) * { * string tmp_base; * if (dictionary_xml_translator_w.TryGetValue(key, out string sdfg) && dictionary_xml_m[key] != dictionary_xml_w[key]) * { * tmp_base = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m,text_ru_w,translator_w) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dictionary_xml_m[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_m[key] + "','" + WebUtility.HtmlEncode(dictionary_xml_w[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_w[key] + "');"; * } * else * { * tmp_base = "INSERT INTO Translated (fileinfo,hash,key_unic,text_en,text_ru_m,translator_m) VALUES ('" + hash1 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dictionary_xml_m[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_m[key] + "');"; * } * tmp_base = "'" + nu88 + "','" + num4 + "','" + b + "','" + value + "','" + value2 + "','" + num6 + "','" + hash1 + "','" + key + "','" + WebUtility.HtmlEncode(text) + "','" + WebUtility.HtmlEncode(dictionary_xml_m[key]).Replace("\n \n", "\n\n").Replace("\n", "\\n") + "','" + dictionary_xml_translator_m[key] + "'"; * using (StreamWriter file_for_exam = new StreamWriter("db\\allbase.txt", true)) * { * file_for_exam.WriteLine(tmp_base); * } * }*/ } binaryReader2.BaseStream.Position = position; num3++; binaryWriter.Write(num4); binaryWriter.Write(b); binaryWriter.Write(value); binaryWriter.Write(value2); binaryWriter.Write(num5); binaryWriter.Write(num2); num2 += num5; binaryWriter.Write(num5); } foreach (KeyValuePair <ulong, string> item in dictionary) { Encoding.UTF8.GetBytes(item.Value.Replace("\\n", "\n")); binaryWriter.Write(Encoding.UTF8.GetBytes(item.Value.Replace("\\n", "\n"))); } MemoryStream memoryStream2 = new MemoryStream(); Deflater deflater = new Deflater(); deflater.SetInput(memoryStream.ToArray()); deflater.Finish(); byte[] array = new byte[size * 3]; while (!deflater.IsNeedingInput) { int count = deflater.Deflate(array); memoryStream2.Write(array, 0, count); if (deflater.IsFinished) { break; } } deflater.Reset(); int newsize = memoryStream.ToArray().Length; int newzsize = memoryStream2.ToArray().Length; byte[] array2 = new byte[36]; array2[0] = 2; array2[2] = 32; byte[] array3 = new byte[array2.Length + memoryStream2.ToArray().Length]; array2.CopyTo(array3, 0); memoryStream2.ToArray().CopyTo(array3, array2.Length); if (somework == 1) { using (StreamReader Hashes_Names = new StreamReader("db\\hashes_filename.txt", Encoding.Default)) { while (!Hashes_Names.EndOfStream) { string line = Hashes_Names.ReadLine(); if (line.IndexOf(hash1.ToString("X")) != -1) { string rez = line.Substring(line.IndexOf("/resources/en-us/str/") + 21); string rez2 = rez.Substring(0, rez.IndexOf("#")); if (File_Name_List.Contains(hash1.ToString())) { using (SQLiteConnection sqlite_conn = new SQLiteConnection("Data Source=db\\translate.db3; Version = 3; New = True; Compress = True; ")) { sqlite_conn.Open(); using (SQLiteCommand sqlite_cmd = new SQLiteCommand(sqlite_conn)) { sqlite_cmd.CommandText = "UPDATE Translated SET fileinfo='" + WebUtility.HtmlEncode(rez2) + "' WHERE hash ='" + hash1 + "'"; sqlite_cmd.ExecuteNonQuery(); } } } } } } } hhh(fileStream, array3, newzsize, newsize, hash2, hash1, endtable); }
public void Inflate_Init() { using (Inflater inf = new Inflater()) { } }
public static void Finish(this Inflater i) { }
/// <summary> /// Create an InflaterInputStream with the specified decompressor /// and the specified buffer size. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> /// <param name = "inflater"> /// The decompressor to use /// </param> /// <param name = "bufferSize"> /// Size of the buffer to use /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) { if (baseInputStream == null) { throw new ArgumentNullException("baseInputStream"); } if (inflater == null) { throw new ArgumentNullException("inflater"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } this.baseInputStream = baseInputStream; this.inf = inflater; inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize); }
/// <summary> /// Pump bytes into the supplied inflater as input. /// </summary> /// <param name="pos"> /// offset within the file to start supplying input from. /// </param> /// <param name="dstbuf"> /// destination buffer the inflater should output decompressed /// data to. /// </param> /// <param name="dstoff"> /// current offset within <paramref name="dstbuf"/> to inflate into. /// </param> /// <param name="inf"> /// the inflater to feed input to. The caller is responsible for /// initializing the inflater as multiple windows may need to /// supply data to the same inflater to completely decompress /// something. /// </param> /// <returns> /// Updated <paramref name="dstoff"/> based on the number of bytes /// successfully copied into <paramref name="dstbuf"/> by /// <paramref name="inf"/>. If the inflater is not yet finished then /// another window's data must still be supplied as input to finish /// decompression. /// </returns> /// <exception cref="InvalidOperationException"> /// the inflater encountered an invalid chunk of data. Data /// stream corruption is likely. /// </exception> internal int Inflate(long pos, byte[] dstbuf, int dstoff, Inflater inf) { return(Inflate((int)(pos - _start), dstbuf, dstoff, inf)); }