Ejemplo n.º 1
0
        /// <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>
        /// <returns>Zlib status code.</returns>
        static int ZlibUncompress(ref byte[] dest, byte[] source)
        {
            ZStream stream = new ZStream();
            int     err;

            stream.next_in   = source;
            stream.avail_in  = source.Length;
            stream.next_out  = dest;
            stream.avail_out = dest.Length;

            err = stream.inflateInit();
            if (err != zlibConst.Z_OK)
            {
                return(err);
            }

            err = stream.inflate(zlibConst.Z_FINISH);
            if (err != zlibConst.Z_STREAM_END)
            {
                stream.inflateEnd();
                return(err == zlibConst.Z_OK ? zlibConst.Z_BUF_ERROR : err);
            }

            if (stream.total_out != dest.Length)
            {
                byte[] output = new byte[stream.total_out];
                Buffer.BlockCopy(stream.next_out, 0, output, 0, (int)stream.total_out);
                dest = output;
            }

            return(stream.inflateEnd());
        }
Ejemplo n.º 2
0
        static void uncompress(ref byte[] dest, byte[] src)
        {
            ZStream stream = new ZStream();

            stream.next_in  = src;
            stream.avail_in = src.Length;

            stream.next_out  = dest;
            stream.avail_out = dest.Length;

            stream.inflateInit();

            int err = stream.inflate(zlibConst.Z_FINISH);

            if (err != zlibConst.Z_STREAM_END)
            {
                stream.inflateEnd();
                throw new ApplicationException();
            }

            Array.Resize <byte>(ref dest, (int)stream.total_out);

            err = stream.inflateEnd();
            if (err != zlibConst.Z_OK)
            {
                throw new ApplicationException();
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Uncompress a source byte array to a destination (old version)
        /// </summary>
        public static int UncompressOld(byte[] dest, ref ulong destLen, byte[] source, ref ulong sourceLen)
        {
            var stream = new ZStream
            {
                next_in   = source,
                avail_in  = (int)sourceLen,
                next_out  = dest,
                avail_out = (int)destLen,
            };

            destLen   = 0;
            sourceLen = 0;

            // make second parameter negative to disable checksum verification
            int err = stream.inflateInit(-Constants.MAX_WBITS);

            if (err != zlibConst.Z_OK)
            {
                return(err);
            }

            while (stream.avail_in > 1)
            {
                err = stream.inflate(Constants.Z_BLOCK);
                if (err != zlibConst.Z_OK)
                {
                    stream.inflateEnd();
                    return(err);
                }
            }

            destLen   = (ulong)stream.total_out;
            sourceLen = (ulong)stream.total_in;
            return(stream.inflateEnd());
        }
Ejemplo n.º 4
0
        private void ZIPCleanup()
        {
            base.TIFFPredictorCleanup();

            if ((m_state & ZSTATE_INIT_ENCODE) != 0)
            {
                m_stream.deflateEnd();
                m_state = 0;
            }
            else if ((m_state & ZSTATE_INIT_DECODE) != 0)
            {
                m_stream.inflateEnd();
                m_state = 0;
            }
        }
Ejemplo n.º 5
0
    public static byte[] Uncompress(byte[] buff, int offset = 0)
    {
        //using (MemoryStream md = new MemoryStream())
        //{
        //    Stream d = new ZOutputStream(md);
        //    d.Write(buff, offset, buff.Length - offset);
        //    d.Close();
        //    return md.ToArray();
        //}
        ZStream zs = new ZStream();

        zs.next_in   = buff;
        zs.avail_in  = buff.Length;
        zs.next_out  = _buffer;
        zs.avail_out = _buffer.Length;
        if (zlibConst.Z_OK != zs.inflateInit())
        {
            return(null);
        }
        if (zlibConst.Z_STREAM_END != zs.inflate(zlibConst.Z_FINISH))
        {
            return(null);
        }
        zs.inflateEnd();
        byte[] result = new byte[zs.total_out];
        System.Array.Copy(_buffer, result, zs.total_out);
        return(result);
    }
Ejemplo n.º 6
0
        public void Decompress()
        {
            byte[] numArray = new byte[this.data.Count];
            this.data.CopyTo(0, numArray, 0, this.data.Count);
            byte[]  numArray1 = new byte[800];
            ZStream zStream   = new ZStream()
            {
                avail_in = 0
            };

            zStream.inflateInit();
            zStream.next_in       = numArray;
            zStream.next_in_index = 2;
            zStream.avail_in      = (int)numArray.Length - 4;
            zStream.next_out      = numArray1;
            zStream.avail_out     = 800;
            if (zStream.inflate(4) != -3)
            {
                long totalOut = zStream.total_out;
                zStream.inflateEnd();
                zStream = null;
                this.data.Clear();
                this.data.Add(numArray[0]);
                this.data.Add(numArray[1]);
                for (int i = 0; (long)i < totalOut; i++)
                {
                    this.data.Add(numArray1[i]);
                }
                this.data.Add(numArray[(int)numArray.Length - 3]);
                this.data.Add(numArray[(int)numArray.Length - 2]);
                this.data.Add(numArray[(int)numArray.Length - 1]);
            }
        }
Ejemplo n.º 7
0
        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);
            }
        }
Ejemplo n.º 8
0
            /// <summary>
            /// Extract all files contained in the package in the folder pointed by the destination path.
            /// </summary>
            public void ExtractAll(String Destination)
            {
                Destination = Destination.Replace('/', '\\');
                if (!Destination.EndsWith("\\"))
                {
                    Destination += "\\";
                }

                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];

                    foreach (Entry Entry in Entries.Values)
                    {
                        String DestPath = Destination + Entry.Path.Replace("/", "\\");
                        if (!Directory.Exists(Path.GetDirectoryName(DestPath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(DestPath));
                        }

                        Input.Seek(Entry.Offset, SeekOrigin.Begin);
                        using (FileStream Output = new FileStream(DestPath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
                        {
                            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;
                                    Output.Write(Tmp, 0, Length);
                                }while (Stream.avail_out == 0);
                            }while (Result != zlibConst.Z_STREAM_END);

                            Stream.inflateEnd();
                        }
                    }
                }
            }
Ejemplo n.º 9
0
        private static (byte[] bytes, int res) DecompressZ(byte[] inbuf, int index = 0)
        {
            var z      = new ZStream();
            var ms     = new MemoryStream();
            var outbuf = new byte[1024];

            if (z.inflateInit() != zlibConst.Z_OK)
            {
                throw new InvalidOperationException("zlib.inflateInit Error");
            }

            z.next_in       = inbuf;
            z.avail_in      = inbuf.Length;
            z.next_in_index = index;

            z.next_out       = outbuf;
            z.avail_out      = outbuf.Length;
            z.next_out_index = 0;

            while (true)
            {
                int status = z.inflate(zlibConst.Z_NO_FLUSH); /* 展開 */
                if (status == zlibConst.Z_STREAM_END)
                {
                    break;
                }

                if (status != zlibConst.Z_OK)
                {
                    throw new InvalidOperationException("zlib.inflate Error");
                }

                if (z.avail_out == 0)
                {
                    ms.Write(outbuf, 0, outbuf.Length);
                    z.next_out       = outbuf;
                    z.avail_out      = outbuf.Length;
                    z.next_out_index = 0;
                }
            }

            if ((outbuf.Length - z.avail_out) != 0)
            {
                ms.Write(outbuf, 0, outbuf.Length - z.avail_out);
            }

            if (z.inflateEnd() != zlibConst.Z_OK)
            {
                throw new InvalidOperationException("zlib.inflateEnd Error");
            }

            int count = z.next_in_index - index;

            z.free();

            return(ms.ToArray(), count);
        }
Ejemplo n.º 10
0
        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));
        }
 public virtual void end()
 {
     if (compress)
     {
         z.deflateEnd();
     }
     else
     {
         z.inflateEnd();
     }
     z.free();
     z = null;
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Closes any open connections between the Tibia client and game server, and stops listening for any
        /// new incoming HTTP or TCP connection requests.
        /// </summary>
        internal void Stop()
        {
            if (!_isStarted)
            {
                return;
            }

            try
            {
                _zStream.deflateEnd();
                _zStream.inflateEnd();
                _httpListener.Close();

                if (_tcpListener != null)
                {
                    _tcpListener.Stop();
                }

                if (_clientSocket != null)
                {
                    _clientSocket.Close();
                }

                if (_serverSocket != null)
                {
                    _serverSocket.Close();
                }
            }
            catch (Exception ex)
            {
                _client.Logger.Error(ex.ToString());
            }

            _isStarted      = false;
            _xteaKey        = null;
            ConnectionState = ConnectionState.Disconnected;
        }
Ejemplo n.º 13
0
        /// <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());
        }
Ejemplo n.º 14
0
        /// <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);
        }
Ejemplo n.º 15
0
        internal void Decompress(int type)
        {
            if (this is NetworkClient)
            {
                throw new Exception("Trying to decompress data on Client connection!");
            }

            zStream_Length = 0;

            zStream.avail_in      = inMaxIndex - inIndex;
            zStream.next_in       = inData;
            zStream.next_in_index = inIndex;

            zStream.next_out       = zStream_Out;
            zStream.next_out_index = 0;
            zStream.avail_out      = zStream_Out.Length;

            switch (zStream.inflate(type))
            {
            case zlibConst.Z_OK:
                inIndex           = zStream.next_in_index;
                zStream_Length    = (int)zStream.total_out;
                zStream.total_out = 0;
                break;

            case zlibConst.Z_STREAM_END:
                inIndex        = zStream.next_in_index;
                zStream_Length = (int)zStream.total_out;
                zStream.inflateEnd();
                zStream.free();
                zStream = null;
                break;

            default:
                //case zlibConst.Z_STREAM_ERROR:
                throw new Exception("Error while decompressing: " + (zStream.msg ?? "unknown error") + "!");
            }
        }
Ejemplo n.º 16
0
        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));
            }
        }
Ejemplo n.º 17
0
        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));
        }
Ejemplo n.º 18
0
            /// <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);
            }
Ejemplo n.º 19
0
 protected override int EndZlibOperation(ZStream zs)
 {
     return(zs.inflateEnd());
 }
Ejemplo n.º 20
0
        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());
        }
Ejemplo n.º 21
0
            /// <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);
            }
Ejemplo n.º 22
0
        /// <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);
        }
Ejemplo n.º 23
0
        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));
        }
Ejemplo n.º 24
0
        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);
        }
Ejemplo n.º 25
0
        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));
        }
Ejemplo n.º 26
0
        /// <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));
        }
Ejemplo n.º 27
0
        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");
            }
        }
Ejemplo n.º 28
0
        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");
            }
        }