public CompressedStream(Stream innerStream) { InnerStream = innerStream; zOut = new ZStream(); zOut.deflateInit(5, true); zOut.next_out = new byte[4096]; zIn = new ZStream(); zIn.inflateInit(true); zIn.next_in = new byte[4096]; }
public void InitCrypto() { _dec = new Salsa20Engine(); _dec.Init(false, new ParametersWithIV(new KeyParameter(_salsaKey02), _salsaIV02)); _enc = new Salsa20Engine(); _enc.Init(true, new ParametersWithIV(new KeyParameter(_salsaKey01), _salsaIV01)); _dStream = new ZStream(); _dStream.deflateInit(-1, -15); _iStream = new ZStream(); _iStream.inflateInit(-15); }
private void StartDecompression() { if (this is NetworkClient) { throw new Exception("Trying to start decompression on Client connection!"); } if (zStream != null) { return; } zStream = new ZStream(); zStream.inflateInit(); }
/// <summary> /// /// </summary> /// <param name="Block"></param> /// <returns></returns> public byte[] ReadBlockDecompressed(uint Block) { if (Block >= NumberOfBlocks) { return(new byte[0]); } var In = ReadBlockCompressed(Block); // If block is not compressed, get the contents. if (!Blocks[Block].IsCompressed) { return(In); } var Out = new byte[this.Header.BlockSize]; In = In.Concat(new byte[] { 0x00 }); var ZStream = new ZStream(); if (ZStream.inflateInit(-15) != zlibConst.Z_OK) { throw (new InvalidProgramException("Can't initialize inflater")); } try { ZStream.next_in = In; ZStream.next_in_index = 0; ZStream.avail_in = In.Length; ZStream.next_out = Out; ZStream.next_out_index = 0; ZStream.avail_out = Out.Length; int Status = ZStream.inflate(zlibConst.Z_FULL_FLUSH); if (Status != zlibConst.Z_STREAM_END) { throw (new InvalidDataException("" + ZStream.msg)); } } finally { ZStream.inflateEnd(); } return(Out); }
public void InitCrypto() { Console.WriteLine("Initialized decrypters and inflaters!"); _dec01 = new Salsa20Engine(); _dec01.Init(false, new ParametersWithIV(new KeyParameter(Key02), IV02)); _dec02 = new Salsa20Engine(); _dec02.Init(false, new ParametersWithIV(new KeyParameter(Key01), IV01)); _iStream01 = new ZStream(); _iStream01.inflateInit(-15); _iStream02 = new ZStream(); _iStream02.inflateInit(-15); CryptoInit = true; }
public static byte[] Uncompress(byte[] compressed, int start, int size, int maxUncompressedSize) { ZStream stream = new ZStream(); stream.next_in = compressed; stream.next_in_index = start; stream.avail_in = compressed.Length; byte[] uncompressed = new byte[maxUncompressedSize]; stream.next_out = uncompressed; stream.next_out_index = 0; stream.avail_out = maxUncompressedSize; int err = stream.inflateInit(); if (err != zlibConst.Z_OK) { return(null); } err = stream.inflate(zlibConst.Z_FINISH); if (err != zlibConst.Z_STREAM_END) { stream.inflateEnd(); return(null); } int realSize = (int)stream.total_out; err = stream.inflateEnd(); if (err != zlibConst.Z_OK) { return(null); } if (realSize < maxUncompressedSize) { byte[] temp = new byte[realSize]; Array.Copy(uncompressed, temp, realSize); return(temp); } else { return(uncompressed); } }
public static PhpString gzdecode(byte[] data, int length = 0) { if (length < 0) { PhpException.Throw(PhpError.Warning, "length ({0}) must be greater or equal zero", length.ToString()); return(default(PhpString)); } if (data.Length == 0) { return(default(PhpString)); } if (data.Length < 10 || data[0] != GZIP_HEADER[0] || data[1] != GZIP_HEADER[1]) { PhpException.Throw(PhpError.Warning, "incorrect gzip header"); return(default(PhpString)); } var zs = new ZStream(); zs.next_in = data; zs.next_in_index = GZIP_HEADER_LENGTH; zs.avail_in = data.Length - GZIP_HEADER_LENGTH; zs.total_out = 0; // negative number omits the zlib header (undocumented feature of zlib) int status = zs.inflateInit(-MAX_WBITS); if (status == zlibConst.Z_OK) { status = zlib_inflate_rounds(zs, length, out byte[] output); if (status == zlibConst.Z_STREAM_END) { zs.inflateEnd(); return(new PhpString(output)); } } PhpException.Throw(PhpError.Warning, zError(status) ?? zs.msg); zs.inflateEnd(); return(default(PhpString)); }
internal Decompress(int wbits) { zst = new ZStream(); int err = zst.inflateInit(wbits); switch (err) { case ZlibModule.Z_OK: break; case ZlibModule.Z_STREAM_ERROR: throw PythonOps.ValueError("Invalid initialization option"); default: throw ZlibModule.zlib_error(this.zst, err, "while creating decompression object"); } _unused_data = string.Empty; _unconsumed_tail = string.Empty; }
/// <summary> /// Closes any open connections between the Tibia client and game server, and clears /// any pending packets to be sent. /// </summary> private void ResetConnection() { if (_isResettingConnection) { return; } _isResettingConnection = true; lock (_clientSendLock) { _isSendingToClient = false; _clientSendQueue.Clear(); } if (_clientSocket != null) { _clientSocket.Close(); } lock (_serverSendLock) { _isSendingToServer = false; _serverSendQueue.Clear(); } if (_serverSocket != null) { _serverSocket.Close(); } _zStream.deflateEnd(); _zStream.inflateEnd(); _zStream = new ZStream(); _zStream.deflateInit(zlibConst.Z_DEFAULT_COMPRESSION, -15); _zStream.inflateInit(-15); _clientSequenceNumber = 1; _serverSequenceNumber = 1; _xteaKey = null; _isResettingConnection = false; ConnectionState = ConnectionState.ConnectingStage1; }
/// <summary> /// Starts the <see cref="HttpListener"/> and <see cref="TcpListener"/> objects that listen for incoming /// connection requests from the Tibia client. /// </summary> /// <returns>Returns true on success, or if already started. Returns false if an exception is thrown.</returns> internal bool Start(int httpPort = 7171, string loginWebService = "") { if (_isStarted) { return(true); } try { if (_tcpListener == null) { _tcpListener = new TcpListener(IPAddress.Loopback, 0); } var uriPrefix = $"http://127.0.0.1:{httpPort}/"; if (!_httpListener.Prefixes.Contains(uriPrefix)) { _httpListener.Prefixes.Add(uriPrefix); } _zStream.deflateInit(zlibConst.Z_DEFAULT_COMPRESSION, -15); _zStream.inflateInit(-15); _httpListener.Start(); _httpListener.BeginGetContext(new AsyncCallback(BeginGetContextCallback), _httpListener); _tcpListener.Start(); _tcpListener.BeginAcceptSocket(new AsyncCallback(BeginAcceptTcpClientCallback), _tcpListener); _isStarted = true; _loginWebService = loginWebService; ConnectionState = ConnectionState.ConnectingStage1; } catch (Exception ex) { _isStarted = false; _client.Logger.Error(ex.ToString()); } return(_isStarted); }
private byte[] inflate_file(BinaryReader reader, long length) { byte[] uncompressed = new byte[length * 16]; ZStream strm = new ZStream(); strm.next_in = reader.ReadBytes((int)length); strm.avail_in = (int)length; strm.avail_out = 0; var code = strm.inflateInit(-15); var output = new System.Collections.Generic.List <byte>(); while (code == zlibConst.Z_OK && strm.avail_out == 0) { strm.next_out = uncompressed; strm.avail_out = uncompressed.Length; code = strm.inflate(zlibConst.Z_SYNC_FLUSH); switch (code) { case zlibConst.Z_OK: for (int i = 0; i < uncompressed.Length; i++) { output.Add(uncompressed[i]); } break; case zlibConst.Z_STREAM_END: for (int i = 0; i < uncompressed.Length - strm.avail_out; i++) { output.Add(uncompressed[i]); } break; } } return(output.ToArray()); }
/// <summary> /// Reimplements function from zlib (uncompress) that is not present in ZLIB.NET. /// </summary> /// <param name="dest">Destination array of bytes. May be trimmed if necessary.</param> /// <param name="source">Source array of bytes.</param> /// <param name="msg">Eventual message from zstream.</param> /// <returns>Zlib status code.</returns> static int ZlibUncompress(ref byte[] dest, byte[] source, out string msg) { var zs = new ZStream(); int err; zs.next_in = source; zs.avail_in = source.Length; zs.next_out = dest; zs.avail_out = dest.Length; err = zs.inflateInit(); if (err != zlibConst.Z_OK) { msg = zs.msg; return(err); } err = zs.inflate(zlibConst.Z_FINISH); if (err != zlibConst.Z_STREAM_END) { zs.inflateEnd(); msg = zs.msg; return(err == zlibConst.Z_OK ? zlibConst.Z_BUF_ERROR : err); } if (zs.total_out != dest.Length) { byte[] output = new byte[zs.total_out]; Buffer.BlockCopy(zs.next_out, 0, output, 0, (int)zs.total_out); dest = output; } msg = zs.msg; return(zs.inflateEnd()); }
protected override int InitZlibOperation(ZStream zs) { // -MAX_WBITS stands for absense of Zlib header and trailer (needed for GZIP compression and decompression) return(zs.inflateInit(-Zlib.MAX_WBITS)); }
public static void main(String[] arg) { int err; int comprLen = 40000; int uncomprLen = comprLen; byte[] uncompr = new byte[uncomprLen]; byte[] compr = new byte[comprLen]; long dictId; ZStream c_stream = new ZStream(); err = c_stream.deflateInit(JZlib.Z_BEST_COMPRESSION); CHECK_ERR(c_stream, err, "deflateInit"); err = c_stream.deflateSetDictionary(dictionary, dictionary.Length); CHECK_ERR(c_stream, err, "deflateSetDictionary"); dictId = c_stream.adler; c_stream.next_out = compr; c_stream.next_out_index = 0; c_stream.avail_out = comprLen; c_stream.next_in = hello; c_stream.next_in_index = 0; c_stream.avail_in = hello.Length; err = c_stream.deflate(JZlib.Z_FINISH); if (err != JZlib.Z_STREAM_END) { java.lang.SystemJ.outJ.println("deflate should report Z_STREAM_END"); java.lang.SystemJ.exit(1); } err = c_stream.deflateEnd(); CHECK_ERR(c_stream, err, "deflateEnd"); ZStream d_stream = new ZStream(); d_stream.next_in = compr; d_stream.next_in_index = 0; d_stream.avail_in = comprLen; err = d_stream.inflateInit(); CHECK_ERR(d_stream, err, "inflateInit"); d_stream.next_out = uncompr; d_stream.next_out_index = 0; d_stream.avail_out = uncomprLen; while (true) { err = d_stream.inflate(JZlib.Z_NO_FLUSH); if (err == JZlib.Z_STREAM_END) { break; } if (err == JZlib.Z_NEED_DICT) { if ((int)d_stream.adler != (int)dictId) { java.lang.SystemJ.outJ.println("unexpected dictionary"); java.lang.SystemJ.exit(1); } err = d_stream.inflateSetDictionary(dictionary, dictionary.Length); } CHECK_ERR(d_stream, err, "inflate with dict"); } err = d_stream.inflateEnd(); CHECK_ERR(d_stream, err, "inflateEnd"); int j = 0; for (; j < uncompr.Length; j++) { if (uncompr[j] == 0) { break; } } java.lang.SystemJ.outJ.println("after inflateSync(): hel" + new java.lang.StringJ(uncompr, 0, j)); }
internal static byte[] Decompress(byte[] input, int wbits = MAX_WBITS, int bufsize = DEFAULTALLOC) { byte[] outputBuffer = new byte[bufsize]; byte[] output = new byte[bufsize]; int outputOffset = 0; ZStream zst = new ZStream(); zst.next_in = input; zst.avail_in = input.Length; zst.next_out = outputBuffer; zst.avail_out = outputBuffer.Length; int err = zst.inflateInit(wbits); if (err != Z_OK) { zst.inflateEnd(); throw zlib_error(zst, err, "while preparing to decompress data"); } do { err = zst.inflate(FlushStrategy.Z_FINISH); if (err != Z_STREAM_END) { if (err == Z_BUF_ERROR && zst.avail_out > 0) { zst.inflateEnd(); throw zlib_error(zst, err, "while decompressing data"); } else if (err == Z_OK || (err == Z_BUF_ERROR && zst.avail_out == 0)) { // copy to the output and reset the buffer if (outputOffset + outputBuffer.Length > output.Length) { Array.Resize(ref output, output.Length * 2); } Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length); outputOffset += outputBuffer.Length; zst.next_out = outputBuffer; zst.avail_out = outputBuffer.Length; zst.next_out_index = 0; } else { zst.inflateEnd(); throw zlib_error(zst, err, "while decompressing data"); } } } while(err != Z_STREAM_END); err = zst.inflateEnd(); if (err != Z_OK) { throw zlib_error(zst, err, "while finishing data decompression"); } if (outputOffset + outputBuffer.Length - zst.avail_out > output.Length) { Array.Resize(ref output, output.Length * 2); } Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length - zst.avail_out); outputOffset += outputBuffer.Length - zst.avail_out; return(output.Take(outputOffset).ToArray()); }
/// <summary> /// Get the data of the entry linked by the specified path. /// All the data will be allocated in memory. It may fail. /// /// Return false if the entry does not exist. /// </summary> public Boolean GetEntryData(String Path, out Byte[] Data) { Data = null; if (Path.StartsWith("/") || Path.StartsWith("\\")) { return(false); } Entry Entry; lock (Entries) { if (!Entries.TryGetValue(Path.ToLowerInvariant().Replace('\\', '/'), out Entry)) { return(false); } } Data = new Byte[(Int32)Entry.UncompressedSize]; using (var Input = new FileStream(TpdFile.GetFilename(), FileMode.Open, FileAccess.Read, FileShare.Read)) { var Buffer = new Byte[Kernel.MAX_BUFFER_SIZE]; var Tmp = new Byte[Kernel.MAX_BUFFER_SIZE]; var Pos = 0; Input.Seek(Entry.Offset, SeekOrigin.Begin); { var Stream = new ZStream(); Stream.inflateInit(); var Result = 0; var Length = 0; do { Stream.avail_in = Input.Read(Buffer, 0, Kernel.MAX_BUFFER_SIZE); Stream.next_in = Buffer; Stream.next_in_index = 0; if (Stream.avail_in == 0) { break; } do { Stream.avail_out = Kernel.MAX_BUFFER_SIZE; Stream.next_out = Tmp; Stream.next_out_index = 0; Result = Stream.inflate(zlibConst.Z_NO_FLUSH); Length = Kernel.MAX_BUFFER_SIZE - Stream.avail_out; Array.Copy(Buffer, 0, Data, Pos, Length); Pos += Length; }while (Stream.avail_out == 0); }while (Result != zlibConst.Z_STREAM_END); Stream.inflateEnd(); } } return(true); }
IEnumerable <WebSocketsFrame> IExtension.ApplyIncoming(NetContext context, WebSocketConnection connection, WebSocketsFrame frame) { if (frame.Reserved1 && !frame.IsControlFrame) { BufferStream tmp = null; var payload = frame.Payload; payload.Position = 0; byte[] inBuffer = null, outBuffer = null; try { outBuffer = context.GetBuffer(); inBuffer = context.GetBuffer(); tmp = new BufferStream(context, 0); if (inbound == null) { inbound = new ZStream(); inbound.inflateInit(); // fake a zlib header with: // CMF: // CM = 8 (deflate) // CINFO = 7 (32k window) // FLG: // FCHECK: 26 (checksum of other bits) // FDICT: 0 (no dictionary) // FLEVEL: 3 (maximum) inBuffer[0] = 120; inBuffer[1] = 218; inbound.next_in = inBuffer; int chk = Inflate(tmp, outBuffer, 2); if (chk != 0) { throw new InvalidOperationException("Spoofed zlib header suggested data"); } } inbound.next_in = inBuffer; int remaining = frame.PayloadLength; //bool first = true; while (remaining > 0) { int readCount = payload.Read(inBuffer, 0, inBuffer.Length); if (readCount <= 0) { break; } remaining -= readCount; //if (first) //{ // kill the BFINAL flag from the first block, if set; we don't want zlib // // trying to verify the ADLER checksum; unfortunately, a frame can contain // // multiple blocks, and a *later* block could have BFINAL set. That sucks. // inBuffer[0] &= 254; // first = false; //} Inflate(tmp, outBuffer, readCount); } if (remaining != 0) { throw new EndOfStreamException(); } // spoof the missing 4 bytes from the tail inBuffer[0] = inBuffer[1] = 0x00; inBuffer[2] = inBuffer[3] = 0xFF; Inflate(tmp, outBuffer, 4); // set our final output tmp.Position = 0; frame.Payload = tmp; long bytesSaved = tmp.Length - frame.PayloadLength; frame.PayloadLength = (int)tmp.Length; frame.Reserved1 = false; tmp = payload as BufferStream; parent.RegisterInboundBytesSaved(bytesSaved); } #if DEBUG catch (Exception ex) { Debug.WriteLine(ex); throw; } #endif finally { if (inbound != null) { inbound.next_out = null; inbound.next_in = null; } if (tmp != null) { tmp.Dispose(); } if (inBuffer != null) { context.Recycle(inBuffer); } if (outBuffer != null) { context.Recycle(outBuffer); } if (parent.disableContextTakeover) { ClearContext(true, false); } } } yield return(frame); }
public static string decompress([BytesConversion] IList <byte> data, [DefaultParameterValue(MAX_WBITS)] int wbits, [DefaultParameterValue(DEFAULTALLOC)] int bufsize) { byte[] input = data.ToArray(); byte[] outputBuffer = new byte[bufsize]; byte[] output = new byte[bufsize]; int outputOffset = 0; ZStream zst = new ZStream(); zst.next_in = input; zst.avail_in = input.Length; zst.next_out = outputBuffer; zst.avail_out = outputBuffer.Length; int err = zst.inflateInit(wbits); if (err != Z_OK) { zst.inflateEnd(); throw zlib_error(zst, err, "while preparing to decompress data"); } do { err = zst.inflate(FlushStrategy.Z_FINISH); if (err != Z_STREAM_END) { if (err == Z_BUF_ERROR && zst.avail_out > 0) { zst.inflateEnd(); throw zlib_error(zst, err, "while decompressing data"); } else if (err == Z_OK || (err == Z_BUF_ERROR && zst.avail_out == 0)) { // copy to the output and reset the buffer if (outputOffset + outputBuffer.Length > output.Length) { Array.Resize(ref output, output.Length * 2); } Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length); outputOffset += outputBuffer.Length; zst.next_out = outputBuffer; zst.avail_out = outputBuffer.Length; zst.next_out_index = 0; } else { zst.inflateEnd(); throw zlib_error(zst, err, "while decompressing data"); } } } while(err != Z_STREAM_END); err = zst.inflateEnd(); if (err != Z_OK) { throw zlib_error(zst, err, "while finishing data decompression"); } if (outputOffset + outputBuffer.Length - zst.avail_out > output.Length) { Array.Resize(ref output, output.Length * 2); } Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length - zst.avail_out); outputOffset += outputBuffer.Length - zst.avail_out; return(PythonAsciiEncoding.Instance.GetString(output, 0, outputOffset)); }
/// <summary> /// Returns the spectrum-data (m/z and intensity) of the given scan number. The boundries /// for the scan number can be retrieved with <see cref="GetFirstSpectrumNumber"/> and /// <see cref="GetLastSpectrumNumber"/>. This method will throw an exception when the given /// scan number is outside these boundries. The spectrum data is returned as a 2-dimensional /// list of size (2, nrspectra) in emulation of the thermo RAW access DLL. /// </summary> /// <param name="scannumber">The scan number.</param> /// <returns>The scan-data.</returns> public double[,] GetMassListFromScanNum(int scannumber) { if (scannumber < minScanNumber || scannumber > maxScanNumber) { throw new Exception("Undefined scan number: " + scannumber + " outside (" + minScanNumber + "," + maxScanNumber + ")"); } int compressedLength = 0; string compressionType = null; int precision = -1; string byteOrder = null; string contentType = null; string data = null; string peakData = GetScanPeakData(scannumber); XmlTextReader xmlReader = new XmlTextReader(new StringReader(peakData)); while (xmlReader.Read()) { xmlReader.MoveToElement(); if (!xmlReader.IsStartElement("peaks")) { continue; } precision = Parser.Int(xmlReader.GetAttribute("precision")); byteOrder = xmlReader.GetAttribute("byteOrder"); contentType = xmlReader.GetAttribute("contentType"); if (string.IsNullOrEmpty(contentType)) { contentType = xmlReader.GetAttribute("pairOrder"); } compressionType = xmlReader.GetAttribute("compressionType"); string sCompressedLen = xmlReader.GetAttribute("compressedLen"); compressedLength = string.IsNullOrEmpty(sCompressedLen) ? -1 : Parser.Int(sCompressedLen); data = xmlReader.ReadElementContentAsString(); } if (byteOrder == null || contentType == null || data == null) { throw new Exception("Malformed mz-xml File."); } if (!contentType.Equals("m/z-int") && !contentType.Equals("mz-int")) { throw new Exception("Non-supported content type: ' " + contentType + "'."); } // convert from base64 encoding byte[] bytes = Convert.FromBase64String(data); // decompress if (compressionType != null && compressionType.Equals("zlib")) { if (compressedLength != bytes.Length) { throw new Exception("Attribute 'compressedLen' has a different value from the reconstructed data array."); } ZStream z = new ZStream(); const int bufferLen = 1024; z.next_in = bytes; z.next_in_index = 0; z.avail_in = bytes.Length; z.inflateInit(); int totalLength = 0; List <byte[]> pieces = new List <byte[]>(); while (true) { z.next_out = new byte[bufferLen]; z.next_out_index = 0; z.avail_out = bufferLen; pieces.Add(z.next_out); int err = z.inflate(zlibConst.Z_NO_FLUSH); totalLength += bufferLen - z.avail_out; if (err == zlibConst.Z_STREAM_END) { break; } if (err != zlibConst.Z_OK) { throw new ZStreamException(z.msg); } } z.inflateEnd(); bytes = new byte[totalLength]; int pos = 0; foreach (byte[] piece in pieces) { Buffer.BlockCopy(piece, 0, bytes, pos, totalLength - pos > 1024 ? bufferLen : totalLength - pos); pos += piece.Length; } } // convert from byte encoding double[] massintensities = ByteArray.ToDoubleArray(bytes, byteOrder.Equals("network") ? ByteArray.endianBig : ByteArray.endianLittle, precision); double[,] masslist = new double[2, massintensities.Length / 2]; for (int i = 0; i < massintensities.Length; i += 2) { masslist[0, i / 2] = massintensities[i]; masslist[1, i / 2] = massintensities[i + 1]; } return(masslist); }
public static void main(String[] arg) { int err; int comprLen = 40000; int uncomprLen = comprLen; byte[] compr = new byte[comprLen]; byte[] uncompr = new byte[uncomprLen]; ZStream c_stream = new ZStream(); err = c_stream.deflateInit(JZlib.Z_DEFAULT_COMPRESSION); CHECK_ERR(c_stream, err, "deflateInit"); c_stream.next_in = hello; c_stream.next_in_index = 0; c_stream.next_out = compr; c_stream.next_out_index = 0; while (c_stream.total_in != hello.Length && c_stream.total_out < comprLen) { c_stream.avail_in = c_stream.avail_out = 1; // force small buffers err = c_stream.deflate(JZlib.Z_NO_FLUSH); CHECK_ERR(c_stream, err, "deflate"); } while (true) { c_stream.avail_out = 1; err = c_stream.deflate(JZlib.Z_FINISH); if (err == JZlib.Z_STREAM_END) { break; } CHECK_ERR(c_stream, err, "deflate"); } err = c_stream.deflateEnd(); CHECK_ERR(c_stream, err, "deflateEnd"); ZStream d_stream = new ZStream(); d_stream.next_in = compr; d_stream.next_in_index = 0; d_stream.next_out = uncompr; d_stream.next_out_index = 0; err = d_stream.inflateInit(); CHECK_ERR(d_stream, err, "inflateInit"); while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) { d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ err = d_stream.inflate(JZlib.Z_NO_FLUSH); if (err == JZlib.Z_STREAM_END) { break; } CHECK_ERR(d_stream, err, "inflate"); } err = d_stream.inflateEnd(); CHECK_ERR(d_stream, err, "inflateEnd"); int i = 0; for (; i < hello.Length; i++) { if (hello[i] == 0) { break; } } int j = 0; for (; j < uncompr.Length; j++) { if (uncompr[j] == 0) { break; } } if (i == j) { for (i = 0; i < j; i++) { if (hello[i] != uncompr[i]) { break; } } if (i == j) { java.lang.SystemJ.outJ.println("inflate(): " + new java.lang.StringJ(uncompr, 0, j).ToString()); return; } } else { java.lang.SystemJ.outJ.println("bad inflate"); } }
public static void main(String[] arg) { int err; int comprLen = 40000; int uncomprLen = comprLen; byte[] compr = new byte[comprLen]; byte[] uncompr = new byte[uncomprLen]; int len = hello.Length; ZStream c_stream = new ZStream(); err = c_stream.deflateInit(JZlib.Z_DEFAULT_COMPRESSION); CHECK_ERR(c_stream, err, "deflate"); c_stream.next_in = hello; c_stream.next_in_index = 0; c_stream.next_out = compr; c_stream.next_out_index = 0; c_stream.avail_in = 3; c_stream.avail_out = comprLen; err = c_stream.deflate(JZlib.Z_FULL_FLUSH); CHECK_ERR(c_stream, err, "deflate"); compr[3]++; // force an error in first compressed block c_stream.avail_in = len - 3; err = c_stream.deflate(JZlib.Z_FINISH); if (err != JZlib.Z_STREAM_END) { CHECK_ERR(c_stream, err, "deflate"); } err = c_stream.deflateEnd(); CHECK_ERR(c_stream, err, "deflateEnd"); comprLen = (int)(c_stream.total_out); ZStream d_stream = new ZStream(); d_stream.next_in = compr; d_stream.next_in_index = 0; d_stream.avail_in = 2; err = d_stream.inflateInit(); CHECK_ERR(d_stream, err, "inflateInit"); d_stream.next_out = uncompr; d_stream.next_out_index = 0; d_stream.avail_out = uncomprLen; err = d_stream.inflate(JZlib.Z_NO_FLUSH); CHECK_ERR(d_stream, err, "inflate"); d_stream.avail_in = comprLen - 2; err = d_stream.inflateSync(); CHECK_ERR(d_stream, err, "inflateSync"); err = d_stream.inflate(JZlib.Z_FINISH); if (err != JZlib.Z_DATA_ERROR) { java.lang.SystemJ.outJ.println("inflate should report DATA_ERROR"); /* Because of incorrect adler32 */ java.lang.SystemJ.exit(1); } err = d_stream.inflateEnd(); CHECK_ERR(d_stream, err, "inflateEnd"); int j = 0; for (; j < uncompr.Length; j++) { if (uncompr[j] == 0) { break; } } java.lang.SystemJ.outJ.println("after inflateSync(): hel" + new java.lang.StringJ(uncompr, 0, j)); }
/// <summary> /// Get the data of the entry linked by the specified path. /// All the data will be allocated in memory. It may fail. /// /// Return false if the entry does not exist. /// </summary> public Boolean GetEntryData(String Path, Byte **pData, Int32 *pLength) { *pData = null; if (Path.StartsWith("/") || Path.StartsWith("\\")) { return(false); } Entry Entry; lock (Entries) { if (!Entries.TryGetValue(Path.ToLowerInvariant().Replace('\\', '/'), out Entry)) { return(false); } } *pData = (Byte *)Kernel.malloc((Int32)Entry.UncompressedSize); *pLength = (Int32)Entry.UncompressedSize; using (FileStream Input = new FileStream(TpdFile.GetFilename(), FileMode.Open, FileAccess.Read, FileShare.Read)) { Byte[] Buffer = new Byte[Kernel.MAX_BUFFER_SIZE]; Byte[] Tmp = new Byte[Kernel.MAX_BUFFER_SIZE]; Int32 Pos = 0; Input.Seek(Entry.Offset, SeekOrigin.Begin); { ZStream Stream = new ZStream(); Stream.inflateInit(); Int32 Result = 0; Int32 Length = 0; do { Stream.avail_in = Input.Read(Buffer, 0, Kernel.MAX_BUFFER_SIZE); Stream.next_in = Buffer; Stream.next_in_index = 0; if (Stream.avail_in == 0) { break; } do { Stream.avail_out = Kernel.MAX_BUFFER_SIZE; Stream.next_out = Tmp; Stream.next_out_index = 0; Result = Stream.inflate(zlibConst.Z_NO_FLUSH); Length = Kernel.MAX_BUFFER_SIZE - Stream.avail_out; Kernel.memcpy((*pData) + Pos, Tmp, Length); Pos += Length; }while (Stream.avail_out == 0); }while (Result != zlibConst.Z_STREAM_END); Stream.inflateEnd(); } } return(true); }
public static PhpString gzinflate(byte[] data, long length = 0) { uint factor = 1, maxfactor = 16; long ilength; var zs = new ZStream(); zs.avail_in = data.Length; zs.next_in = data; zs.total_out = 0; // -15 omits the header (undocumented feature of zlib) int status = zs.inflateInit(-15); if (status != zlibConst.Z_OK) { PhpException.Throw(PhpError.Warning, zError(status)); return(default(PhpString)); } do { ilength = length != 0 ? length : data.Length * (1 << (int)(factor++)); try { byte[] newOutput = new byte[ilength]; if (zs.next_out != null) { Buffer.BlockCopy(zs.next_out, 0, newOutput, 0, zs.next_out.Length); } zs.next_out = newOutput; } catch (OutOfMemoryException) { zs.inflateEnd(); return(default(PhpString)); } zs.next_out_index = (int)zs.total_out; zs.avail_out = unchecked ((int)(ilength - zs.total_out)); status = zs.inflate(zlibConst.Z_NO_FLUSH); }while ((status == zlibConst.Z_BUF_ERROR || (status == zlibConst.Z_OK && (zs.avail_in != 0 || zs.avail_out == 0))) && length == 0 && factor < maxfactor); zs.inflateEnd(); if ((length != 0 && status == zlibConst.Z_OK) || factor >= maxfactor) { status = zlibConst.Z_MEM_ERROR; } if (status == zlibConst.Z_STREAM_END || status == zlibConst.Z_OK) { byte[] result = new byte[zs.total_out]; Buffer.BlockCopy(zs.next_out, 0, result, 0, (int)zs.total_out); return(new PhpString(result)); } else { PhpException.Throw(PhpError.Warning, zError(status) ?? zs.msg); return(default(PhpString)); } }
/// <summary> /// Reads NBT data from the specified (compressed) stream. /// </summary> public static NBTNamedTag <INBTData> ReadChunk(Stream fs, Point <int> Pos) { // Read the chunk from the file. byte[] buf = new byte[5]; long seekOffset = 0; int sectorNumber = 0; int offset = 0; // Read the chunk offset. Point <int> chunkOffsetInRegion; chunkOffsetInRegion.X = Pos.X % 32; if (chunkOffsetInRegion.X < 0) { chunkOffsetInRegion.X += 32; } chunkOffsetInRegion.Y = Pos.Y % 32; if (chunkOffsetInRegion.Y < 0) { chunkOffsetInRegion.Y += 32; } seekOffset = 4 * (chunkOffsetInRegion.X + chunkOffsetInRegion.Y * 32); fs.Position = seekOffset; fs.Read(buf, 0, 4); sectorNumber = (int)buf[3]; offset = (int)buf[0] << 16 | (int)buf[1] << 8 | (int)buf[2]; if (offset == 0) { throw new ArithmeticException(); } // Get the chunk length and version. int chunkLength = 0; fs.Position = offset * 4096; fs.Read(buf, 0, 5); chunkLength = (int)buf[0] << 24 | (int)buf[1] << 14 | (int)buf[2] << 8 | (int)buf[3]; if (chunkLength > sectorNumber * 4096 || chunkLength > CHUNK_DEFLATE_MAX) { throw new ArithmeticException(); } if (buf[4] != 2) { throw new ArithmeticException(); } // Read compressed chunk data. byte[] inChunk = new byte[CHUNK_DEFLATE_MAX]; byte[] outChunk = new byte[CHUNK_INFLATE_MAX]; fs.Read(inChunk, 0, chunkLength - 1); fs.Close(); // Decompress it. ZStream z = new ZStream(); z.next_out = outChunk; z.avail_out = CHUNK_INFLATE_MAX; z.next_in = inChunk; z.avail_in = chunkLength - 1; z.inflateInit(); z.inflate(zlibConst.Z_NO_FLUSH); z.inflateEnd(); System.IO.MemoryStream msUncompressed = new System.IO.MemoryStream(outChunk); return(NBT.ReadUncompressed(msUncompressed)); }
public static BufLen BCGZipDecompressNew(BufLen buf) { var reader = new BufRefLen(buf); // Skip gzip header var gzheader = reader.ReadBufLen(10); var flag = gzheader.Peek8(3); if ((flag & 0x04) != 0) { reader.Seek(reader.Read16()); // "Extra" } if ((flag & 0x08) != 0) { while (reader.Read8() != 0) { ; // "Name" } } if ((flag & 0x10) != 0) { while (reader.Read8() != 0) { ; // "Comment" } } if ((flag & 0x02) != 0) { reader.Read16(); // "CRC16" } var z = new ZStream(); z.inflateInit(true); var dest = new byte[buf.Length * 2]; var destix = 0; z.next_in_index = reader.BaseArrayOffset; z.next_in = reader.BaseArray; z.avail_in = reader.Length - 8; bigger_dest: z.next_out = dest; z.next_out_index = destix; z.avail_out = dest.Length - destix; var err = z.inflate(JZlib.Z_FINISH); if (err != JZlib.Z_BUF_ERROR && err != JZlib.Z_OK && err != JZlib.Z_STREAM_END) { throw new IOException("inflating: " + z.msg); } if (z.avail_out == 0) { var newdest = new byte[dest.Length * 2]; Array.Copy(dest, newdest, dest.Length); destix = dest.Length; dest = newdest; goto bigger_dest; } var result = new BufLen(dest, 0, dest.Length - z.avail_out); z.inflateEnd(); return(result); }
public static void main(String[] arg) { int err; int comprLen = 40000; int uncomprLen = comprLen; byte[] compr = new byte[comprLen]; byte[] uncompr = new byte[uncomprLen]; ZStream c_stream = new ZStream(); err = c_stream.deflateInit(JZlib.Z_BEST_SPEED); CHECK_ERR(c_stream, err, "deflateInit"); c_stream.next_out = compr; c_stream.next_out_index = 0; c_stream.avail_out = comprLen; // At this point, uncompr is still mostly zeroes, so it should compress // very well: c_stream.next_in = uncompr; c_stream.avail_in = uncomprLen; err = c_stream.deflate(JZlib.Z_NO_FLUSH); CHECK_ERR(c_stream, err, "deflate"); if (c_stream.avail_in != 0) { java.lang.SystemJ.outJ.println("deflate not greedy"); java.lang.SystemJ.exit(1); } // Feed in already compressed data and switch to no compression: c_stream.deflateParams(JZlib.Z_NO_COMPRESSION, JZlib.Z_DEFAULT_STRATEGY); c_stream.next_in = compr; c_stream.next_in_index = 0; c_stream.avail_in = comprLen / 2; err = c_stream.deflate(JZlib.Z_NO_FLUSH); CHECK_ERR(c_stream, err, "deflate"); // Switch back to compressing mode: c_stream.deflateParams(JZlib.Z_BEST_COMPRESSION, JZlib.Z_FILTERED); c_stream.next_in = uncompr; c_stream.next_in_index = 0; c_stream.avail_in = uncomprLen; err = c_stream.deflate(JZlib.Z_NO_FLUSH); CHECK_ERR(c_stream, err, "deflate"); err = c_stream.deflate(JZlib.Z_FINISH); if (err != JZlib.Z_STREAM_END) { java.lang.SystemJ.outJ.println("deflate should report Z_STREAM_END"); java.lang.SystemJ.exit(1); } err = c_stream.deflateEnd(); CHECK_ERR(c_stream, err, "deflateEnd"); ZStream d_stream = new ZStream(); d_stream.next_in = compr; d_stream.next_in_index = 0; d_stream.avail_in = comprLen; err = d_stream.inflateInit(); CHECK_ERR(d_stream, err, "inflateInit"); while (true) { d_stream.next_out = uncompr; d_stream.next_out_index = 0; d_stream.avail_out = uncomprLen; err = d_stream.inflate(JZlib.Z_NO_FLUSH); if (err == JZlib.Z_STREAM_END) { break; } CHECK_ERR(d_stream, err, "inflate large"); } err = d_stream.inflateEnd(); CHECK_ERR(d_stream, err, "inflateEnd"); if (d_stream.total_out != 2 * uncomprLen + comprLen / 2) { java.lang.SystemJ.outJ.println("bad large inflate: " + d_stream.total_out); java.lang.SystemJ.exit(1); } else { java.lang.SystemJ.outJ.println("large_inflate(): OK"); } }