Ejemplo n.º 1
0
        public static void Deserialize(Stream stream, PiaFile piaFile)
        {
            if (stream == null)
                throw new ArgumentNullException("Stream");

            if (piaFile == null)
                throw new ArgumentNullException("PiaFile");

            try
            {
                // Header
                var headerBytes = new Byte[48]; // Ignore 12 byte checksum
                stream.Read(headerBytes, 0, headerBytes.Length);
                var headerString = Encoding.Default.GetString(headerBytes);
                piaFile.Header = new PiaHeader(headerString);

                // Inflation
                string inflatedString;
                stream.Seek(60, SeekOrigin.Begin);
                using (var zStream = new InflaterInputStream(stream))
                {
                    var sr = new StreamReader(zStream, Encoding.Default);
                    inflatedString = sr.ReadToEnd();
                }

                // Nodes
                piaFile.Owner = piaFile;
                _deserializeNode(piaFile, inflatedString);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 2
0
        private static byte[] Inflate(MemoryStream ms, int length)
        {
            ms.Seek(0L, SeekOrigin.Begin);
            Inflater            inflater            = new Inflater(false);
            InflaterInputStream inflaterInputStream = new InflaterInputStream(ms, inflater);

            byte[] array = new byte[length];
            int    num   = 0;
            int    num2  = array.Length;

            try
            {
                for (;;)
                {
                    int num3 = inflaterInputStream.Read(array, num, num2);
                    if (num3 <= 0)
                    {
                        break;
                    }
                    num  += num3;
                    num2 -= num3;
                }
            }
            catch (Exception ex)
            {
                LocalStorageAPI.s_log.LogWarning("EXCEPTION (Inflate): {0}", new object[]
                {
                    ex.Message
                });
                return(null);
            }
            if (num != length)
            {
                LocalStorageAPI.s_log.LogWarning("Decompressed size does not equal expected size.");
                return(null);
            }
            return(array);
        }
Ejemplo n.º 3
0
 public static void Decrypt(string sourcePath, string destPath)
 {
     var(tmpName, tmp) = CreateTempFile();
     using (var fs = new FileStream(sourcePath, FileMode.Open, FileAccess.ReadWrite))
         using (var ofs = new FileStream(destPath, FileMode.Create, FileAccess.Write))
             using (var br = new BinaryReader(fs))
             {
                 ulong compressedSize   = 0;
                 ulong decompressedSize = 0;
                 fs.Seek(0, SeekOrigin.End);
                 compressedSize = (ulong)fs.Position - 4;
                 fs.Seek(0, SeekOrigin.Begin);
                 decompressedSize = br.ReadUInt32();
                 //decompressedSize = BitConverter.ToUInt64(bytes);
                 //var bytes = new byte[compressedSize];
                 //fs.Read(bytes, 4, (int) compressedSize);
                 var chars = br.ReadBytes((int)compressedSize);
                 //.Select(x=> (byte)x).ToArray();
                 Span <byte> uncompressedData;
                 using (var output = new MemoryStream())
                 {
                     using (var input = new MemoryStream(chars))
                         using (var zlib = new InflaterInputStream(input))
                         {
                             zlib.CopyTo(output);
                         }
                     uncompressedData = output.ToArray().AsSpan();
                 }
                 if (uncompressedData.Length == (int)decompressedSize)
                 {
                     tmp.Write(uncompressedData);
                     tmp.Seek(0, SeekOrigin.Begin);
                     ProcessUncompressedData(tmp, ofs);
                 }
             }
     tmp.Dispose();
     File.Delete(tmpName);
 }
Ejemplo n.º 4
0
        public void CloseInflatorWithNestedUsing()
        {
            string tempFile = null;

            try
            {
                tempFile = Path.GetTempPath();
            }
            catch (SecurityException)
            {
            }

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
            using (FileStream diskFile = File.Create(tempFile))
                using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile))
                    using (StreamWriter textWriter = new StreamWriter(deflator))
                    {
                        textWriter.Write("Hello");
                        textWriter.Flush();
                    }

            using (FileStream diskFile = File.OpenRead(tempFile))
                using (InflaterInputStream deflator = new InflaterInputStream(diskFile))
                    using (StreamReader textReader = new StreamReader(deflator))
                    {
                        char[] buffer    = new char[5];
                        int    readCount = textReader.Read(buffer, 0, 5);
                        Assert.AreEqual(5, readCount);

                        var b = new StringBuilder();
                        b.Append(buffer);
                        Assert.AreEqual("Hello", b.ToString());
                    }

            File.Delete(tempFile);
        }
Ejemplo n.º 5
0
        public static string Decompress(string b64pressed)
        {
            byte[] cleanData = null;
            string cleanText = null;

            byte[] compressedData = Convert.FromBase64String(b64pressed);

            using (MemoryStream decompressedStream = new MemoryStream()) {
                using (MemoryStream compressedStream = new MemoryStream(compressedData)) {
                    using (InflaterInputStream decompressionStream = new InflaterInputStream(compressedStream, new Inflater(true))) {
                        StreamUtils.Copy(decompressionStream, decompressedStream, new byte[4096]);
                        cleanData = decompressedStream.ToArray();
                    }
                }
            }

            if (cleanData != null)
            {
                cleanText = Encoding.UTF8.GetString(cleanData, 0, cleanData.Length);
            }

            return(cleanText);
        }
Ejemplo n.º 6
0
 public static void Decomress(byte[] input, out byte[] output)
 {
     using (MemoryStream fs = new MemoryStream(input))
     {
         using (InflaterInputStream ds = new InflaterInputStream(fs))
         {
             MemoryStream fso = new MemoryStream();
             fso.Seek(0, SeekOrigin.Begin);
             byte[] data = new byte[256];
             while (true)
             {
                 int rs = ds.Read(data, 0, data.Length);
                 fso.Write(data, 0, rs);
                 if (rs == 0)
                 {
                     break;
                 }
             }
             output = fso.ToArray();
             fso.Close();
         }
     }
 }
Ejemplo n.º 7
0
        public static byte[] Decompress(byte[] bytes)
        {
            using (var stream = new InflaterInputStream(new MemoryStream(bytes), new Inflater(true)))
            {
                MemoryStream memory    = new MemoryStream();
                byte[]       writeData = new byte[4096];
                int          size;

                while (true)
                {
                    size = stream.Read(writeData, 0, writeData.Length);
                    if (size > 0)
                    {
                        memory.Write(writeData, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }
                return(memory.ToArray());
            }
        }
Ejemplo n.º 8
0
        public static void Decompress(ref GenericReader gr)
        {
            int uncompressedLength = gr.ReadInt32();

            byte[] output = new byte[gr.ReadInt32()];
            byte[] temp   = gr.ReadBytes((int)gr.Remaining);
            gr.Close();
            Stream s      = new InflaterInputStream(new MemoryStream(temp));
            int    offset = 0;

            while (true)
            {
                int size = s.Read(output, offset, uncompressedLength);
                if (size == uncompressedLength)
                {
                    break;
                }
                offset             += size;
                uncompressedLength -= size;
            }
            gr = new GenericReader(new MemoryStream(output));
            //gr.BaseStream.Position = 0;
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Decompresses the provided data, returning the inflated result.
 /// </summary>
 /// <param name="data">the deflated picture data.</param>
 /// <returns>the inflated picture data.</returns>
 private static byte[] InflatePictureData(byte[] data)
 {
     using (MemoryStream out1 = new MemoryStream()) {
         try {
             using (MemoryStream ms = new MemoryStream(data)) {
                 Inflater inflater = new Inflater(false);
                 using (InflaterInputStream in1 = new InflaterInputStream(ms, inflater)) {
                     byte[] buf = new byte[4096];
                     int    ReadBytes;
                     while ((ReadBytes = in1.Read(buf, 0, buf.Length)) > 0)
                     {
                         out1.Write(buf, 0, ReadBytes);
                     }
                     return(out1.ToArray());
                 }
             }
         }
         catch (IOException e) {
             log.Log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
             return(data);
         }
     }
 }
Ejemplo n.º 10
0
        public static byte[] DeCompress(byte[] pBytes)
        {
            MemoryStream mMemory = new MemoryStream();

            using (InflaterInputStream mStream = new InflaterInputStream(new MemoryStream(pBytes)))
            {
                Int32  mSize;
                byte[] mWriteData = new byte[4096];
                while (true)
                {
                    mSize = mStream.Read(mWriteData, 0, mWriteData.Length);
                    if (mSize > 0)
                    {
                        mMemory.Write(mWriteData, 0, mSize);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return(mMemory.ToArray());
        }
Ejemplo n.º 11
0
        public static int Decompress(byte[] bytes, byte[] outbuf)
        {
            using (var stream = new InflaterInputStream(new MemoryStream(bytes), new Inflater(true)))
            {
                MemoryStream memory    = new MemoryStream(outbuf);
                byte[]       writeData = new byte[4096];
                int          size;

                while (true)
                {
                    size = stream.Read(writeData, 0, writeData.Length);
                    if (size > 0)
                    {
                        memory.Write(writeData, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }
                return((int)memory.Position);
            }
        }
Ejemplo n.º 12
0
        public static byte[] DeCompress(byte [] b)
        {
            Stream s2 = new InflaterInputStream(new MemoryStream(b));

            try
            {
                byte [] dest = null;
                int     size = s2.Read(writeData, 0, writeData.Length);
                if (size > 0)
                {
                    dest = new byte[size];
                    Buffer.BlockCopy(writeData, 0, dest, 0, size);
                }
                s2.Flush();
                s2.Close();
                return(dest);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Ejemplo n.º 13
0
        public string Decompress(byte[] baseBytes)
        {
            string resultStr = string.Empty;

            using (MemoryStream memoryStream = new MemoryStream(baseBytes))
            {
                using (InflaterInputStream inf = new InflaterInputStream(memoryStream))
                {
                    using (MemoryStream buffer = new MemoryStream())
                    {
                        byte[] result = new byte[1024];

                        int resLen;
                        while ((resLen = inf.Read(result, 0, result.Length)) > 0)
                        {
                            buffer.Write(result, 0, resLen);
                        }
                        resultStr = Encoding.Default.GetString(result);
                    }
                }
            }
            return(resultStr);
        }
Ejemplo n.º 14
0
        public static byte[] Inflate(byte[] buffer)
        {
            byte[]       block        = new byte[256];
            MemoryStream outputStream = new MemoryStream();

            Inflater inflater = new Inflater();

            using (MemoryStream memoryStream = new MemoryStream(buffer))
                using (InflaterInputStream inflaterInputStream = new InflaterInputStream(memoryStream, inflater))
                {
                    while (true)
                    {
                        int numBytes = inflaterInputStream.Read(block, 0, block.Length);
                        if (numBytes < 1)
                        {
                            break;
                        }
                        outputStream.Write(block, 0, numBytes);
                    }
                }

            return(outputStream.ToArray());
        }
Ejemplo n.º 15
0
        private SgaRawFile ReadFile(SgaFileEntry file)
        {
            byte[] data;

            lock (this.reader)
            {
                this.reader.BaseStream.Seek(Convert.ToInt32(this.header.DataOffset) + file.Info.DataOffset, SeekOrigin.Begin);

                data = this.reader.ReadBytes(Convert.ToInt32(file.Info.DataLengthCompressed));
            }

            if (file.Info.DataLength != file.Info.DataLengthCompressed)
            {
                var outputStream = new MemoryStream();
                using (var inputStream = new InflaterInputStream(new MemoryStream(data)))
                {
                    inputStream.CopyTo(outputStream);
                }
                data = outputStream.ToArray();
            }

            return(new SgaRawFile(file.Name, data));
        }
Ejemplo n.º 16
0
        private static byte[] ZlibDecompress(Stream Data, int ExpectedLength)
        {
            // This assumes that Zlib won't be used in combination with another compression type
            var Output = new byte[ExpectedLength];
            var s      = new InflaterInputStream(Data);
            var Offset = 0;

            while (true)
            {
                if (ExpectedLength == 0)
                {
                    break;
                }
                var size = s.Read(Output, Offset, ExpectedLength);
                if (size == 0)
                {
                    break;
                }
                Offset         += size;
                ExpectedLength -= size;
            }
            return(Output);
        }
        private static byte[] Decompress(byte[] data)
        {
            byte[]       numArray;
            MemoryStream memoryStream       = new MemoryStream(data, FileUtil.BNET_COMPRESSED_HEADER_SIZE, (int)data.Length - FileUtil.BNET_COMPRESSED_HEADER_SIZE);
            int          decompressedLength = (int)FileUtil.GetDecompressedLength(data);

            memoryStream.Seek((long)0, SeekOrigin.Begin);
            InflaterInputStream inflaterInputStream = new InflaterInputStream(memoryStream, new Inflater(false));

            byte[] numArray1 = new byte[decompressedLength];
            int    num       = 0;
            int    length    = (int)numArray1.Length;

            try
            {
                while (true)
                {
                    int num1 = inflaterInputStream.Read(numArray1, num, length);
                    if (num1 <= 0)
                    {
                        break;
                    }
                    num    += num1;
                    length -= num1;
                }
                if (num != decompressedLength)
                {
                    return(null);
                }
                return(numArray1);
            }
            catch (Exception exception)
            {
                numArray = null;
            }
            return(numArray);
        }
        private static byte[] Inflate(MemoryStream ms, int length)
        {
            byte[] numArray;
            ms.Seek((long)0, SeekOrigin.Begin);
            InflaterInputStream inflaterInputStream = new InflaterInputStream(ms, new Inflater(false));

            byte[] numArray1 = new byte[length];
            int    num       = 0;
            int    num1      = (int)numArray1.Length;

            try
            {
                while (true)
                {
                    int num2 = inflaterInputStream.Read(numArray1, num, num1);
                    if (num2 <= 0)
                    {
                        break;
                    }
                    num  += num2;
                    num1 -= num2;
                }
                if (num == length)
                {
                    return(numArray1);
                }
                LocalStorageAPI.s_log.LogWarning("Decompressed size does not equal expected size.");
                return(null);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                LocalStorageAPI.s_log.LogWarning("EXCEPTION (Inflate): {0}", new object[] { exception.Message });
                numArray = null;
            }
            return(numArray);
        }
Ejemplo n.º 19
0
        public zTXtChunk(byte[] data, PNGImage image)
            : base(data, image)
        {
            int i = 0;

            while (data[i + 4] != 0)
            {
                i++;
            }

            this.Keyword           = ASCIIEncoding.ASCII.GetString(data, 4, i);
            this.CompressionMethod = (CompressionMethod)data[i + 5];

            ByteStreamReader bs = new ByteStreamReader(data);

            bs.Seek(i + 6, SeekOrigin.Begin);

            InflaterInputStream iis = new InflaterInputStream(bs, new Inflater(), data.Length - 4 - i - 2);
            StringBuilder       sb  = new StringBuilder();

            while (iis.Available == 1)
            {
                int b = iis.ReadByte();

                if (b == -1)
                {
                    break;
                }

                sb.Append(System.Text.ASCIIEncoding.ASCII.GetChars(new byte[] { (byte)b })[0]);
            }

            this.Text = sb.ToString();

            iis.Close();
            bs.Close();
        }
    private static byte[] Inflate(MemoryStream ms, int length)
    {
        ms.Seek(0L, SeekOrigin.Begin);
        Inflater            inf    = new Inflater(false);
        InflaterInputStream stream = new InflaterInputStream(ms, inf);

        byte[] buffer = new byte[length];
        int    offset = 0;
        int    count  = buffer.Length;

        try
        {
            while (true)
            {
                int num3 = stream.Read(buffer, offset, count);
                if (num3 <= 0)
                {
                    goto Label_0084;
                }
                offset += num3;
                count  -= num3;
            }
        }
        catch (Exception exception)
        {
            object[] args = new object[] { exception.Message };
            s_log.LogWarning("EXCEPTION (Inflate): {0}", args);
            return(null);
        }
Label_0084:
        if (offset != length)
        {
            s_log.LogWarning("Decompressed size does not equal expected size.");
            return(null);
        }
        return(buffer);
    }
        private static byte[] Decompress(byte[] data)
        {
            MemoryStream memoryStream = new MemoryStream(data, FileUtil.BNET_COMPRESSED_HEADER_SIZE, data.Length - FileUtil.BNET_COMPRESSED_HEADER_SIZE);
            int          num          = (int)FileUtil.GetDecompressedLength(data);

            memoryStream.Seek(0L, 0);
            Inflater            inflater            = new Inflater(false);
            InflaterInputStream inflaterInputStream = new InflaterInputStream(memoryStream, inflater);

            byte[] array = new byte[num];
            int    num2  = 0;
            int    num3  = array.Length;

            try
            {
                while (true)
                {
                    int num4 = inflaterInputStream.Read(array, num2, num3);
                    if (num4 <= 0)
                    {
                        break;
                    }
                    num2 += num4;
                    num3 -= num4;
                }
            }
            catch (Exception)
            {
                byte[] result = null;
                return(result);
            }
            if (num2 != num)
            {
                return(null);
            }
            return(array);
        }
Ejemplo n.º 22
0
        public Stream GetDataStream(bool decompress)
        {
            if (Size == 0 && CompressedSize == 0)
            {
                return(null);
            }

            var io = _index.GetResourceIO(PatchFileNumber);

            if (io == null)
            {
                return(null);
            }

            io.Stream.Position = Offset;
            Stream dataStream = io.Stream;

            if (IsCompressed && decompress)
            {
                dataStream = new InflaterInputStream(io.Stream, new ICSharpCode.SharpZipLib.Zip.Compression.Inflater(true), 4096);
            }

            return(dataStream);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Decompresses the specified data.
        /// </summary>
        /// <param name="data">The compressed byte array.</param>
        /// <param name="pos">The starting position into the byte array.</param>
        /// <param name="Length">The number of compressed bytes to decompress.</param>
        /// <returns>An uncompressed byte array</returns>
        public static byte[] Decompress(byte[] data, int pos, int Length)
        {
            byte[] compressedData = new byte[Length];
            Array.Copy(data, pos + 50, compressedData, 0, Length);
            using (MemoryStream ms = new MemoryStream(compressedData)) {
                Inflater inflater = new Inflater(false);

                using (InflaterInputStream zIn = new InflaterInputStream(ms, inflater)) {
                    using (MemoryStream out1 = new MemoryStream()) {
                        int c;
                        try {
                            while ((c = zIn.ReadByte()) != -1)
                            {
                                out1.WriteByte((byte)c);
                            }
                            return(out1.ToArray());
                        }
                        catch (IOException e) {
                            throw new RecordFormatException(e.ToString());
                        }
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public byte[] GetData(GrfFile file)
        {
            //not a file
            if (file.IsDir())
            {
                return(null);
            }

            //empty file
            if (file.real_len == 0)
            {
                return(null);
            }

            //check if data was already extracted
            if (file.data != null)
            {
                return(file.data);
            }

            /* Retrieve the unencrypted block */
            byte[] zbuf = getFileZBlock(file);
            if (zbuf == null)
            {
                return(null);
            }

            using (var stream = new InflaterInputStream(new MemoryStream(zbuf)))
            {
                file.data = new byte[file.real_len];

                stream.Read(file.data, 0, file.data.Length);
            }

            return(file.data);
        }
Ejemplo n.º 25
0
        private byte[] DeREC(MemoryStream ms)
        {
            ms.Seek(0, SeekOrigin.Begin);
            Inflater            inflater = new Inflater(true);
            InflaterInputStream inStream = new InflaterInputStream(ms, inflater);

            byte[] buf = new byte[5000000];

            int buf_pos = 0;
            int count   = buf.Length;

            while (true)
            {
                int numRead = inStream.Read(buf, buf_pos, count);
                if (numRead <= 0)
                {
                    break;
                }
                buf_pos += numRead;
                count   -= numRead;
            }
            File.WriteAllBytes("test.txt", buf);
            return(buf);
        }
Ejemplo n.º 26
0
        public MemoryStream GetTarStream(string password = "")
        {
            if (this.Attributes.EncryptionType == EncryptionType.AES256 && string.IsNullOrWhiteSpace(password))
            {
                throw new NoPasswordProvidedException();
            }

            this._backupFileStream.Position = 0;

            // Skip android backup headers (not encrypted 4, encrypted 9 lines)
            var skip = this.Attributes.EncryptionType == EncryptionType.None ? 4 : 9;

            for (var i = 0; i < skip; i++)
            {
                this._backupFileStream.ReadOneLine();
            }

            MemoryStream inputStream;

            if (this.Attributes.EncryptionType == EncryptionType.AES256)
            {
                inputStream = DecryptedStream(password);
            }
            else
            {
                inputStream = this._backupFileStream;
            }

            var inflaterInputStream = new InflaterInputStream(inputStream);
            var outputMemoryStream  = new MemoryStream();

            inflaterInputStream.CopyTo(outputMemoryStream);

            outputMemoryStream.Position = 0;
            return(outputMemoryStream);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Saves data and closes the dump
        /// </summary>
        /// <returns>true if succeed</returns>
        internal bool SaveData()
        {
            if (_writer != null)
            {
                if (_writer != null)
                {
                    _writer.Close();
                }
                _outputStream = null;
                _writer       = null;
            }

            if (_reader != null)
            {
                if (_reader != null)
                {
                    _reader.Close();
                }
                _inputStream = null;
                _reader      = null;
            }

            return(true);
        }
Ejemplo n.º 28
0
        public void TestInflateDeflate()
        {
            MemoryStream         ms        = new MemoryStream();
            Deflater             deflater  = new Deflater(6);
            DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater);

            byte[]        buf = new byte[1000000];
            System.Random rnd = new Random();
            rnd.NextBytes(buf);

            outStream.Write(buf, 0, buf.Length);
            outStream.Flush();
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            InflaterInputStream inStream = new InflaterInputStream(ms);

            byte[] buf2 = new byte[buf.Length];
            int    pos  = 0;

            while (true)
            {
                int numRead = inStream.Read(buf2, pos, 4096);
                if (numRead <= 0)
                {
                    break;
                }
                pos += numRead;
            }

            for (int i = 0; i < buf.Length; ++i)
            {
                Assertion.AssertEquals(buf2[i], buf[i]);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Inflater解压
        /// </summary>
        /// <param name="baseBytes"></param>
        /// <returns></returns>
        public static byte[] Decompress(byte[] baseBytes)
        {
            string resultStr = string.Empty;

            using (MemoryStream memoryStream = new MemoryStream(baseBytes))
            {
                using (InflaterInputStream inf = new InflaterInputStream(memoryStream))
                {
                    using (MemoryStream buffer = new MemoryStream())
                    {
                        byte[] result = new byte[1024];
                        int    resLen;
                        while ((resLen = inf.Read(result, 0, result.Length)) > 0)
                        {
                            buffer.Write(result, 0, resLen);
                        }
                        //resultStr = Encoding.UTF8.GetString(result);
                        byte[] bytes = buffer.ToArray();
                        //resultStr = Encoding.UTF8.GetString(bytes);
                        return(bytes);
                    }
                }
            }
        }
Ejemplo n.º 30
0
        public static JsonParse openConnection()
        {
            //Dictionary<string, string> cookie = new Dictionary<string, string>();
            List <string> cookie  = new List <string>();
            string        sCookie = "";

            //从xml文件中读取用户的账户名和密码并进行base64编码
            readUserInfo();
            Dictionary <string, string> loginMessage = new Dictionary <string, string>();

            loginMessage.Add("username", username.ToString());
            loginMessage.Add("password", password.ToString());
            String          finalURL    = buildUrl(username, password);
            HttpWebResponse webResponse = CreatePostHttpResponse(finalURL, null, false, loginMessage);
            Stream          inf         = new InflaterInputStream(webResponse.GetResponseStream());
            StreamReader    readStr     = new StreamReader(inf, Encoding.GetEncoding("UTF-8"));

            sCookie = webResponse.Headers.Get("Set-Cookie");
            sCookie = parseCookie(sCookie, cookie);
            //UID = getUID(readStr.ReadToEnd());

            url_init = "http://s" + (serverID + 2) + ".jr.moefantasy.com/api/initGame";
            String urlString = url_init + "?&crazy=1&t=" + getCurrentMillis() + 1;

            urlString += "&e=" + Encryption.getMD5(urlString) + market;
            finalURL   = urlString;
            //webQuest.Headers.Add(HttpRequestHeader.UserAgent, "Dalvik/2.1.0 (Linux; U; Android 7.0; KNT-AL20 Build/HUAWEIKNT-AL20)");
            webResponse = CreateGetHttpResponse(finalURL, sCookie);
            inf         = new InflaterInputStream(webResponse.GetResponseStream());
            readStr     = new StreamReader(inf, Encoding.GetEncoding("UTF-8"));
            String response = readStr.ReadToEnd();

            //MessageBox.Show(response);
            webResponse.Close();
            return(parseExplore(response));
        }
Ejemplo n.º 31
0
        public void DecompressWorkItem(CompressedWorkItem compressedWorkItem)
        {
            Debug.Assert(!compressedWorkItem.WasDecompressed);

            AllocateUncompressedBuffer(compressedWorkItem);
            var decompressedLength = 0;

            using (var memory = new MemoryStream(compressedWorkItem.CompressedBuffer))
            {
                using var inflater = new InflaterInputStream(memory);
                decompressedLength = inflater.Read(compressedWorkItem.UncompressedBuffer, 0,
                                                   compressedWorkItem.UncompressedSize);
            }

            compressedWorkItem.WasDecompressed = true;

            if (decompressedLength != compressedWorkItem.UncompressedSize)
            {
                throw new InvalidDataException("incorrect decompressed data size");
            }

            // after this function, compressedWorkItem.CompressedBuffer is no longer needed.
            // but, leave it allocated so future runs can re-use that buffer.
        }
Ejemplo n.º 32
0
        private InputStream GetStream(DownloadedContent downloadedContent,
                    List<NameValuePair> headers)
        {

            InputStream stream = downloadedContent_.InputStream;
            if (stream == null)
            {
                return null;
            }

            if (downloadedContent.IsEmpty())
            {
                return stream;
            }

            String encoding = GetHeader(headers, "content-encoding");
            if (encoding != null)
            {
                if (StringUtils.contains(encoding, "gzip"))
                {
                    stream = new GZIPInputStream(stream);
                }
                else if (StringUtils.contains(encoding, "deflate"))
                {
                    bool zlibHeader = false;
                    if (stream.MarkSupported)
                    { // should be always the case as the content is in a byte[] or in a file
                        stream.Mark(2);
                        byte[] buffer = new byte[2];
                        stream.Read(buffer, 0, 2);
                        zlibHeader = (((buffer[0] & 0xff) << 8) | (buffer[1] & 0xff)) == 0x789c;
                        stream.Reset();
                    }
                    if (zlibHeader)
                    {
                        stream = new InflaterInputStream(stream);
                    }
                    else
                    {
                        stream = new InflaterInputStream(stream, new Inflater(true));
                    }
                }
            }
            return stream;
        }
Ejemplo n.º 33
0
            public void process_AsyncChartSnapshot(IAsyncResult asyncResult)
            {

                try
                {


                    // Get the RequestState object from the asyncresult
                    RequestState rs = (RequestState)asyncResult.AsyncState;

                    if (rs.lNewStockSymbol == true)
                    {
                        rs.CloseStream(rs);

                        return;

                    }


                    if (rs.Request.ServicePoint.CurrentConnections > 0)
                    {

                        List<String> cSortedLines = new List<string>();


                        // Pull out the ResponseStream that was set in RespCallback
                        Stream responseStream = rs.ResponseStream;

                        // At this point rs.BufferRead should have some data in it.
                        // Read will tell us if there is any data there

                        int read = responseStream.EndRead(asyncResult);


                        if (read > 0)
                        {
                            // Make sure we store all the incoming data until we reach the end.

                            Array.Copy(rs.BufferRead, 0, ChartByteArray2, ChartByteArray2NDx, read);
                            ChartByteArray2NDx = ChartByteArray2NDx + read;

                            // Make another call so that we continue retrieving any all incoming data                                    
                            IAsyncResult ar = responseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);

                        }
                        else
                        {

                            ChartByteArray2NDx = 0;

                            // If we have not more bytes read, then the server has finished sending us data.
                            if (read == 0)
                            {

                                string compressedText = Convert.ToBase64String(ChartByteArray2);
                                byte[] gzBuffer = Convert.FromBase64String(compressedText);


                                MemoryStream ms = new MemoryStream();


                                int nFieldNDX = 0;
                                int nStartPos = 21;
                                int msgLength = BitConverter.ToInt32(gzBuffer, 0);
                                ms.Write(gzBuffer, 64, gzBuffer.Length - 64);


                                byte[] nMsg = new byte[sizeof(Int32)];


                                /*/
                                 * S = Streaming
                                 * N = Snapshot
                                /*/

                                nMsg[0] = gzBuffer[nFieldNDX++];
                                string cRequestType = System.Text.Encoding.ASCII.GetString(nMsg, 0, 1);

                                // Skip these next 4 bytes
                                nFieldNDX = nFieldNDX + 4;


                                // Get message length
                                nMsg = new byte[sizeof(Int32)];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[2] = gzBuffer[nFieldNDX++];
                                nMsg[3] = gzBuffer[nFieldNDX++];
                                Array.Reverse(nMsg);
                                string nTotalMessageLength = TD_GetResponseValue(100, nMsg, nStartPos, 0);


                                /*/
                                 * 52 / 82 - NASDAQ Chart
                                 * 53 / 83 - NYSE Chart
                                 * 55 / 85 - Indices Chart
                                /*/

                                nMsg = new byte[sizeof(short)];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                int nSID = BitConverter.ToInt16(nMsg, 0);
                                string cStreamingRequestChart = string.Empty;
                                switch (nSID)
                                {

                                    case 82:
                                        cStreamingRequestChart = " NASDAQ Chart";

                                        break;
                                    case 83:
                                        cStreamingRequestChart = " NYSE Chart";

                                        break;
                                    case 85:
                                        cStreamingRequestChart = " Indices Chart";

                                        break;
                                }


                                // Get stock symbol length
                                nMsg = new byte[sizeof(short)];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                int nSymbolLength = BitConverter.ToInt16(nMsg, 0);


                                // Get stock symbol
                                nStartPos = nFieldNDX;
                                nMsg = new byte[nSymbolLength];
                                Array.Copy(gzBuffer, nStartPos, nMsg, 0, nSymbolLength);
                                string cSymbol = TD_GetResponseValue(0, nMsg, 0, nSymbolLength);

                                nFieldNDX = nFieldNDX + nSymbolLength;


                                // Get status
                                nMsg = new byte[sizeof(short)];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                int nStatus = BitConverter.ToInt16(nMsg, 0);


                                // Get length of compressed data
                                nMsg = new byte[sizeof(Int32)];
                                nMsg[0] = gzBuffer[nFieldNDX++];
                                nMsg[1] = gzBuffer[nFieldNDX++];
                                nMsg[2] = gzBuffer[nFieldNDX++];
                                nMsg[3] = gzBuffer[nFieldNDX++];
                                Array.Reverse(nMsg);
                                string nTotalLenOfCompressedData = TD_GetResponseValue(100, nMsg, nStartPos, 0);


                                ms.Close();

                                byte[] CompressedData = new byte[Convert.ToInt32(nTotalLenOfCompressedData)];
                                Array.Copy(gzBuffer, nFieldNDX, CompressedData, 0, Convert.ToInt32(nTotalLenOfCompressedData));


                                StringBuilder cTempData = new StringBuilder();
                                int totalLength = 0;
                                byte[] writeData = new byte[BUFFER_SIZE];
                                Stream s2 = new InflaterInputStream(new MemoryStream(CompressedData));

                                try
                                {
                                    while (true)
                                    {
                                        int size = s2.Read(writeData, 0, writeData.Length);
                                        if (size > 0)
                                        {
                                            totalLength += size;
                                            cTempData.Append(System.Text.Encoding.ASCII.GetString(writeData, 0, size));
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    s2.Close();

                                    string[] cLines = cTempData.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                                    foreach (string cs in cLines)
                                    {
                                        cSortedLines.Add(cs);
                                    }

                                    rs.SendHistoricalChartData(cSortedLines, rs.stockSymbol, rs.ServiceName);

                                }
                                catch (Exception)
                                {
                                    s2.Close();
                                }

                            }
                        }
                    }
                }
                catch (Exception exc) { }
            }
Ejemplo n.º 34
0
        public List<String> TD_Request_NonAsyncChart_Snapshot(string _streamStockSymbol, string chartSource, int nDays)
        {

            List<String> cSortedLines = new List<string>();

            try
            {
                string _streamerCommand = "S=" + chartSource.ToUpper() + "&C=GET&P=" + _streamStockSymbol.ToUpper() + ",0,610," + nDays.ToString() + "d,1m";

                if (this.TD_loginStatus == true)
                {

                    XMLHTTP xmlHttp_ = new XMLHTTP();
                    StringBuilder cpostdata = new StringBuilder();
                    string lcPostUrl = string.Empty;

                    cpostdata.Append("!U=" + _accountid);
                    cpostdata.Append("&W=" + _token);
                    cpostdata.Append("&A=userid=" + _accountid);
                    cpostdata.Append("&token=" + _token);
                    cpostdata.Append("&company=" + _company);
                    cpostdata.Append("&segment=" + _segment);
                    cpostdata.Append("&cddomain=" + _cdDomain);
                    cpostdata.Append("&usergroup=" + _usergroup);
                    cpostdata.Append("&accesslevel=" + _accesslevel);
                    cpostdata.Append("&authorized=" + _authorized);
                    cpostdata.Append("&acl=" + _acl);
                    cpostdata.Append("&timestamp=" + _timestamp);
                    cpostdata.Append("&appid=" + _appid);
                    cpostdata.Append("|" + _streamerCommand);

                    string encodedString = Encode_URL(cpostdata.ToString());
                    cpostdata = new StringBuilder();
                    cpostdata.Append(encodedString);

                    lcPostUrl = "http://" + this._streamerurl + "/" + cpostdata;


                    /*/
                     *   Read the response and decompress the chart data
                     * 
                    /*/


                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(lcPostUrl);
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Accept = "Accept image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";
                    req.Method = "GET";
                    req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    req.Timeout = 60000;
                    req.ServicePoint.ConnectionLimit = 50;



                    //req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                    Stream respStream = resp.GetResponseStream();


                    byte[] chunk = new byte[65535 * 10];
                    byte[] ChartByteArray = new byte[65535 * 10];

                    int bytesRead = respStream.Read(ChartByteArray, 0, ChartByteArray.Length);
                    string compressedText = Convert.ToBase64String(ChartByteArray);
                    byte[] gzBuffer = Convert.FromBase64String(compressedText);

                    respStream.Flush();
                    resp.Close();
                    respStream.Close();


                    MemoryStream ms = new MemoryStream();


                    int nFieldNDX = 0;
                    int nStartPos = 21;
                    int msgLength = BitConverter.ToInt32(gzBuffer, 0);
                    ms.Write(gzBuffer, 64, gzBuffer.Length - 64);


                    byte[] nMsg = new byte[sizeof(Int32)];


                    /*/
                     * S = Streaming
                     * N = Snapshot
                    /*/

                    nMsg[0] = gzBuffer[nFieldNDX++];
                    string cRequestType = System.Text.Encoding.ASCII.GetString(nMsg, 0, 1);

                    // Skip these next 4 bytes
                    nFieldNDX = nFieldNDX + 4;


                    // Get message length
                    nMsg = new byte[sizeof(Int32)];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[2] = gzBuffer[nFieldNDX++];
                    nMsg[3] = gzBuffer[nFieldNDX++];
                    Array.Reverse(nMsg);
                    string nTotalMessageLength = TD_GetResponseValue(100, nMsg, nStartPos, 0);


                    /*/
                     * 52 / 82 - NASDAQ Chart
                     * 53 / 83 - NYSE Chart
                     * 55 / 85 - Indices Chart
                    /*/
                    nMsg = new byte[sizeof(short)];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    int nSID = BitConverter.ToInt16(nMsg, 0);
                    string cStreamingRequestChart = string.Empty;
                    switch (nSID)
                    {

                        case 82:
                            cStreamingRequestChart = " NASDAQ Chart";
                            break;
                        case 83:
                            cStreamingRequestChart = " NYSE Chart";
                            break;
                        case 85:
                            cStreamingRequestChart = " Indices Chart";
                            break;
                    }


                    // Get stock symbol length
                    nMsg = new byte[sizeof(short)];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    int nSymbolLength = BitConverter.ToInt16(nMsg, 0);


                    // Get stock symbol
                    nStartPos = nFieldNDX;
                    nMsg = new byte[nSymbolLength];
                    Array.Copy(gzBuffer, nStartPos, nMsg, 0, nSymbolLength);
                    string cSymbol = TD_GetResponseValue(0, nMsg, 0, nSymbolLength);

                    nFieldNDX = nFieldNDX + nSymbolLength;


                    // Get status
                    nMsg = new byte[sizeof(short)];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    int nStatus = BitConverter.ToInt16(nMsg, 0);


                    // Get length of compressed data
                    nMsg = new byte[sizeof(Int32)];
                    nMsg[0] = gzBuffer[nFieldNDX++];
                    nMsg[1] = gzBuffer[nFieldNDX++];
                    nMsg[2] = gzBuffer[nFieldNDX++];
                    nMsg[3] = gzBuffer[nFieldNDX++];
                    Array.Reverse(nMsg);
                    string nTotalLenOfCompressedData = TD_GetResponseValue(100, nMsg, nStartPos, 0);

                    ms.Close();

                    byte[] CompressedData = new byte[Convert.ToInt32(nTotalLenOfCompressedData)];
                    Array.Copy(gzBuffer, nFieldNDX, CompressedData, 0, Convert.ToInt32(nTotalLenOfCompressedData));


                    StringBuilder cTempData = new StringBuilder();
                    int totalLength = 0;
                    byte[] writeData = new byte[65535 * 10];
                    Stream s2 = new InflaterInputStream(new MemoryStream(CompressedData));

                    try
                    {
                        while (true)
                        {
                            int size = s2.Read(writeData, 0, writeData.Length);
                            if (size > 0)
                            {
                                totalLength += size;
                                cTempData.Append(System.Text.Encoding.ASCII.GetString(writeData, 0, size));
                            }
                            else
                            {
                                break;
                            }
                        }
                        s2.Close();

                        string[] cLines = cTempData.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string cs in cLines)
                        {
                            cSortedLines.Add(cs);
                        }


                    }
                    catch (Exception) { s2.Close(); return cSortedLines; }

                }


                GC.Collect();
            }
            catch (Exception) { }


            return cSortedLines;
        }