public static byte[] DeflateByte(byte[] str) {

            if (str == null) {

                return null;

            }

            using (var output = new MemoryStream()) {

                using (

                var compressor = new Ionic.Zlib.GZipStream(

                output, Ionic.Zlib.CompressionMode.Compress,

                Ionic.Zlib.CompressionLevel.BestSpeed)) {

                    compressor.Write(str, 0, str.Length);

                }

                return output.ToArray();

            }

        }  
		/// <summary>
		/// Gets the response stream with HTTP decompression.
		/// </summary>
		/// <param name="response">The response.</param>
		/// <returns></returns>
		public static Stream GetResponseStreamWithHttpDecompression(this WebResponse response)
		{
			var stream = response.GetResponseStream();
			var encoding = response.Headers["Content-Encoding"];
			if (encoding != null && encoding.Contains("gzip"))
				stream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress);
			else if (encoding != null && encoding.Contains("deflate"))
				stream = new Ionic.Zlib.DeflateStream(stream, Ionic.Zlib.CompressionMode.Decompress);
			return stream;
		}
Example #3
0
 public static byte[] IonicCompress(byte[] bytes)
 {
     using (var ms = new MemoryStream()) {
     using (var gs = new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, true)) {
        gs.Write(bytes, 0, bytes.Length);
     }
     ms.Position = 0L;
     return ToByteArray(ms);
      }
 }
Example #4
0
 public static byte[] IonicDecompress(byte[] bytes)
 {
     byte[] result;
      using (var ms = new MemoryStream()) {
     ms.Write(bytes, 0, bytes.Length);
     using (var gs = new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Decompress, true)) {
        ms.Position = 0L;
        result = ToByteArray(gs);
     }
      }
      return result;
 }
Example #5
0
        public static byte[] CompressGzip(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (Ionic.Zlib.GZipStream zip = new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
                {
                    zip.Write(bytes, 0, bytes.Length);
                }

                return ms.ToArray();
            }
        }
 public static void Compress( FileStream fs, string outpath )
 {
     fs.Position = 0;
     var outfile = new FileStream( outpath, System.IO.FileMode.Create );
     using ( var compressed = new Ionic.Zlib.GZipStream( outfile, Ionic.Zlib.CompressionMode.Compress ) ) {
         byte[] buffer = new byte[4096];
         int numRead;
         while ( ( numRead = fs.Read( buffer, 0, buffer.Length ) ) != 0 ) {
             compressed.Write( buffer, 0, numRead );
         }
     }
     outfile.Close();
 }
Example #7
0
        public static byte[] CompressGzip(string ResponseData, Encoding e)
        {
            Byte[] bytes = e.GetBytes(ResponseData);

            using (MemoryStream ms = new MemoryStream())
            {
                using (Ionic.Zlib.GZipStream zip = new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, true))
                {
                    zip.Write(bytes, 0, bytes.Length);
                }

                return ms.ToArray();

            }
        }
        public static async Task<byte[]> CompressionByteAsync(byte[] str, CompressionType compressionType)
        {
            if (str == null)
            {
                return null;
            }

            using (var output = new MemoryStream())
            {
                switch (compressionType)
                {
                    case CompressionType.Deflate:
                        using (
                            var compressor = new Ionic.Zlib.DeflateStream(
                            output, Ionic.Zlib.CompressionMode.Compress,
                            Ionic.Zlib.CompressionLevel.BestSpeed))
                        {
                            await compressor.WriteAsync(str, 0, str.Length);
                            //compressor.Write(str, 0, str.Length);
                        }
                        break;
                    case CompressionType.GZip:
                        using (
                            var compressor = new Ionic.Zlib.GZipStream(
                            output, Ionic.Zlib.CompressionMode.Compress,
                            Ionic.Zlib.CompressionLevel.BestSpeed))
                        {
                            await compressor.WriteAsync(str, 0, str.Length);
                            //compressor.Write(str, 0, str.Length);
                        }
                        break;
                    case CompressionType.Zlib:
                        using (
                            var compressor = new Ionic.Zlib.ZlibStream(
                            output, Ionic.Zlib.CompressionMode.Compress,
                            Ionic.Zlib.CompressionLevel.BestSpeed))
                        {
                            await compressor.WriteAsync(str, 0, str.Length);
                            //compressor.Write(str, 0, str.Length);
                        }
                        break;
                }

                return output.ToArray();
            }
        }
        public static byte[] GzipCompression(byte[] response)
        {
            if (response == null)
            {
                return response;
            }

            using (var outPut = new MemoryStream())
            {
                using (var compressor = new Ionic.Zlib.GZipStream(outPut, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestSpeed))
                {
                    compressor.Write(response, 0, response.Length);
                }
                response = outPut.ToArray();
            }
            return response;
        }
Example #10
0
        public static KPTranslation LoadFromFile(string strFile,
			IXmlSerializerEx xs)
        {
            if(xs == null) throw new ArgumentNullException("xs");

            FileStream fs = new FileStream(strFile, FileMode.Open,
                FileAccess.Read, FileShare.Read);

            #if !KeePassLibSD
            Ionic.Zlib.GZipStream gz = new Ionic.Zlib.GZipStream(fs, Ionic.Zlib.CompressionMode.Decompress);
            #else
            GZipInputStream gz = new GZipInputStream(fs);
            #endif

            KPTranslation kpTrl = (xs.Deserialize(gz) as KPTranslation);

            gz.Close();
            fs.Close();
            return kpTrl;
        }
Example #11
0
        private void ReadAsBase64(NanoXMLNode dataNode)
        {
            // get a stream to the decoded Base64 text
            Stream data = new MemoryStream(Convert.FromBase64String(dataNode.Value), false);

            // figure out what, if any, compression we're using. the compression determines
            // if we need to wrap our data stream in a decompression stream
            if (dataNode.GetAttribute("compression") != null)
            {
                string compression = dataNode.GetAttribute("compression").Value;

                if (compression == "gzip")
                {
                    data = new Ionic.Zlib.GZipStream(data, Ionic.Zlib.CompressionMode.Decompress, false);
                }
                else if (compression == "zlib")
                {
                    data = new Ionic.Zlib.ZlibStream(data, Ionic.Zlib.CompressionMode.Decompress, false);
                }
                else
                {
                    throw new InvalidOperationException("Unknown compression: " + compression);
                }
            }

            // simply read in all the integers
            using (data)
            {
                using (BinaryReader reader = new BinaryReader(data))
                {
                    for (int i = 0; i < Data.Length; i++)
                    {
                        Data[i] = reader.ReadUInt32();
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        /// Load a KDB file from a stream.
        /// </summary>
        /// <param name="sSource">Stream to read the data from. Must contain
        /// a KDBX stream.</param>
        /// <param name="kdbFormat">Format specifier.</param>
        /// <param name="slLogger">Status logger (optional).</param>
        public void Load(Stream sSource, KdbxFormat kdbFormat, IStatusLogger slLogger)
        {
            Debug.Assert(sSource != null);
            if(sSource == null) throw new ArgumentNullException("sSource");

            m_format = kdbFormat;
            m_slLogger = slLogger;

            HashingStreamEx hashedStream = new HashingStreamEx(sSource, false, null);

            UTF8Encoding encNoBom = StrUtil.Utf8;
            try
            {
                BinaryReaderEx br = null;
                BinaryReaderEx brDecrypted = null;
                Stream readerStream = null;

                if(kdbFormat == KdbxFormat.Default || kdbFormat == KdbxFormat.ProtocolBuffers)
                {
                    br = new BinaryReaderEx(hashedStream, encNoBom, KLRes.FileCorrupted);
                    ReadHeader(br);

                    Stream sDecrypted = AttachStreamDecryptor(hashedStream);
                    if((sDecrypted == null) || (sDecrypted == hashedStream))
                        throw new SecurityException(KLRes.CryptoStreamFailed);

                    if (m_slLogger != null)
                        m_slLogger.SetText("KP2AKEY_TransformingKey", LogStatusType.AdditionalInfo);

                    brDecrypted = new BinaryReaderEx(sDecrypted, encNoBom, KLRes.FileCorrupted);
                    byte[] pbStoredStartBytes = brDecrypted.ReadBytes(32);

                    if((m_pbStreamStartBytes == null) || (m_pbStreamStartBytes.Length != 32))
                        throw new InvalidDataException();

                    if (m_slLogger != null)
                        m_slLogger.SetText("KP2AKEY_DecodingDatabase", LogStatusType.AdditionalInfo);

                    for(int iStart = 0; iStart < 32; ++iStart)
                    {
                        if(pbStoredStartBytes[iStart] != m_pbStreamStartBytes[iStart])
                            throw new InvalidCompositeKeyException();
                    }

                    Stream sHashed = new HashedBlockStream(sDecrypted, false, 0,
                        !m_bRepairMode);

                    if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip)
                        readerStream = new Ionic.Zlib.GZipStream(sHashed, Ionic.Zlib.CompressionMode.Decompress);
                    else readerStream = sHashed;
                }
                else if(kdbFormat == KdbxFormat.PlainXml)
                    readerStream = hashedStream;
                else { Debug.Assert(false); throw new FormatException("KdbFormat"); }

                if(kdbFormat != KdbxFormat.PlainXml) // Is an encrypted format
                {
                    if(m_pbProtectedStreamKey == null)
                    {
                        Debug.Assert(false);
                        throw new SecurityException("Invalid protected stream key!");
                    }

                    m_randomStream = new CryptoRandomStream(m_craInnerRandomStream,
                        m_pbProtectedStreamKey);
                }
                else m_randomStream = null; // No random stream for plain-text files
                if (m_slLogger != null)
                    m_slLogger.SetText("KP2AKEY_ParsingDatabase", LogStatusType.AdditionalInfo);
                var stopWatch = Stopwatch.StartNew();

                if (kdbFormat == KdbxFormat.ProtocolBuffers)
                {
                    KdbpFile.ReadDocument(m_pwDatabase, readerStream, m_pbProtectedStreamKey, m_pbHashOfHeader);

                    Kp2aLog.Log(String.Format("KdbpFile.ReadDocument: {0}ms", stopWatch.ElapsedMilliseconds));

                }
                else
                {
                    ReadXmlStreamed(readerStream, hashedStream);

                    Kp2aLog.Log(String.Format("ReadXmlStreamed: {0}ms", stopWatch.ElapsedMilliseconds));
                }

                readerStream.Close();
                // GC.KeepAlive(br);
                // GC.KeepAlive(brDecrypted);
            }
            catch(CryptographicException) // Thrown on invalid padding
            {
                throw new CryptographicException(KLRes.FileCorrupted);
            }
            finally { CommonCleanUpRead(sSource, hashedStream); }
        }
 public GZipHttpContent(Stream stream)
 {
     m_stream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress);
 }
Example #14
0
        private IEnumerator Post(CallRequestContainer reqContainer)
        {
#if PLAYFAB_REQUEST_TIMING
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif

            var www = new UnityWebRequest(reqContainer.FullUrl)
            {
                uploadHandler   = new UploadHandlerRaw(reqContainer.Payload),
                downloadHandler = new DownloadHandlerBuffer(),
                method          = "POST"
            };

            foreach (var headerPair in reqContainer.RequestHeaders)
            {
                www.SetRequestHeader(headerPair.Key, headerPair.Value);
            }

            yield return(www.Send());

#if PLAYFAB_REQUEST_TIMING
            stopwatch.Stop();
            var timing = new PlayFabHttp.RequestTiming {
                StartTimeUtc        = startTime,
                ApiEndpoint         = reqContainer.ApiEndpoint,
                WorkerRequestMs     = (int)stopwatch.ElapsedMilliseconds,
                MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
            };
            PlayFabHttp.SendRequestTiming(timing);
#endif

            if (!string.IsNullOrEmpty(www.error))
            {
                OnError(www.error, reqContainer);
            }
            else
            {
                try
                {
#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
                    string encoding;
                    if (www.GetResponseHeaders().TryGetValue("Content-Encoding", out encoding) && encoding.ToLower() == "gzip")
                    {
                        var stream = new MemoryStream(www.downloadHandler.data);
                        using (var gZipStream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress, false))
                        {
                            var buffer = new byte[4096];
                            using (var output = new MemoryStream())
                            {
                                int read;
                                while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    output.Write(buffer, 0, read);
                                }
                                output.Seek(0, SeekOrigin.Begin);
                                var streamReader = new StreamReader(output);
                                var jsonResponse = streamReader.ReadToEnd();
                                //Debug.Log(jsonResponse);
                                OnResponse(jsonResponse, reqContainer);
                            }
                        }
                    }
                    else
#endif
                    {
                        OnResponse(www.downloadHandler.text, reqContainer);
                    }
                }
                catch (Exception e)
                {
                    OnError("Unhandled error in PlayFabWWW: " + e, reqContainer);
                }
            }
        }
Example #15
0
            /// <summary>
            /// Deserializes a block.
            /// </summary>
            /// <param name="blockIdx"></param>
            private void DeserializeBlock(int blockIdx)
            {
                // calculate current bounds.
                _currentBlockMin = (uint)(blockIdx * _blockSize);

                // move stream to correct position.
                int blockOffset = 0;
                if (blockIdx > 0)
                {
                    blockOffset = _blockPositions[blockIdx - 1];
                }

                // seek stream.
                _stream.Seek(blockOffset + _begin, SeekOrigin.Begin);

                // deserialize this block.
                Ionic.Zlib.GZipStream gzipStream = new Ionic.Zlib.GZipStream(_stream, Ionic.Zlib.CompressionMode.Decompress);
                _currentBlock = TagIndexSerializer.Deserialize(gzipStream);
            }
Example #16
0
        private void WatchTimer(object state)
        {
            if (_isWatching)
            {
                return;
            }
            _isWatching = true;

            try
            {
                var ipv4AddressSet      = new HashSet <uint>();
                var ipv4AddressRangeSet = new HashSet <SearchRange <uint> >();

                foreach (var ipv4AddressFilter in _serviceManager.Config.Catharsis.Ipv4AddressFilters)
                {
                    // path
                    {
                        foreach (var path in ipv4AddressFilter.Paths)
                        {
                            using (var stream = new FileStream(Path.Combine(_serviceManager.Paths["Configuration"], path), FileMode.OpenOrCreate))
                                using (var reader = new StreamReader(stream, new UTF8Encoding(false)))
                                {
                                    string line;

                                    while ((line = reader.ReadLine()) != null)
                                    {
                                        var index = line.LastIndexOf(':');
                                        if (index == -1)
                                        {
                                            continue;
                                        }

                                        var ips = CatharsisManager.GetStringToIpv4(line.Substring(index + 1));
                                        if (ips == null)
                                        {
                                            continue;
                                        }

                                        if (ips[0] == ips[1])
                                        {
                                            ipv4AddressSet.Add(ips[0]);
                                        }
                                        else if (ips[0] < ips[1])
                                        {
                                            var range = new SearchRange <uint>(ips[0], ips[1]);
                                            ipv4AddressRangeSet.Add(range);
                                        }
                                        else
                                        {
                                            var range = new SearchRange <uint>(ips[1], ips[0]);
                                            ipv4AddressRangeSet.Add(range);
                                        }
                                    }
                                }
                        }
                    }

                    // Url
                    if (!string.IsNullOrWhiteSpace(ipv4AddressFilter.ProxyUri))
                    {
                        string proxyScheme = null;
                        string proxyHost   = null;
                        int    proxyPort   = -1;

                        {
                            var match = _regex.Match(ipv4AddressFilter.ProxyUri);

                            if (match.Success)
                            {
                                proxyScheme = match.Groups[1].Value;
                                proxyHost   = match.Groups[2].Value;
                                proxyPort   = int.Parse(match.Groups[3].Value);
                            }
                            else
                            {
                                var match2 = _regex2.Match(ipv4AddressFilter.ProxyUri);

                                if (match2.Success)
                                {
                                    proxyScheme = match2.Groups[1].Value;
                                    proxyHost   = match2.Groups[2].Value;
                                    proxyPort   = 80;
                                }
                            }
                        }

                        if (proxyHost == null)
                        {
                            goto End;
                        }

                        var proxy = new WebProxy(proxyHost, proxyPort);

                        foreach (var url in ipv4AddressFilter.Urls)
                        {
                            for (int i = 0; i < 3; i++)
                            {
                                try
                                {
                                    using (var stream = CatharsisManager.GetStream(url, proxy))
                                        using (var gzipStream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress))
                                            using (var reader = new StreamReader(gzipStream))
                                            {
                                                string line;

                                                while ((line = reader.ReadLine()) != null)
                                                {
                                                    var index = line.LastIndexOf(':');
                                                    if (index == -1)
                                                    {
                                                        continue;
                                                    }

                                                    var ips = CatharsisManager.GetStringToIpv4(line.Substring(index + 1));
                                                    if (ips == null)
                                                    {
                                                        continue;
                                                    }

                                                    if (ips[0] == ips[1])
                                                    {
                                                        ipv4AddressSet.Add(ips[0]);
                                                    }
                                                    else if (ips[0] < ips[1])
                                                    {
                                                        var range = new SearchRange <uint>(ips[0], ips[1]);
                                                        ipv4AddressRangeSet.Add(range);
                                                    }
                                                    else
                                                    {
                                                        var range = new SearchRange <uint>(ips[1], ips[0]);
                                                        ipv4AddressRangeSet.Add(range);
                                                    }
                                                }
                                            }

                                    break;
                                }
                                catch (Exception e)
                                {
                                    Log.Warning(e);
                                }
                            }
                        }

                        End :;
                    }
                }

                lock (_thisLock)
                {
                    _settings.Ipv4AddressSet.Clear();
                    _settings.Ipv4AddressSet.UnionWith(ipv4AddressSet);

                    _settings.Ipv4AddressRangeSet.Clear();
                    _settings.Ipv4AddressRangeSet.UnionWith(ipv4AddressRangeSet);
                }
            }
            finally
            {
                _isWatching = false;
            }
        }
Example #17
0
        static MemoryStream compress(string value)
        {
            byte[] data = Encoding.UTF8.GetBytes(value);
            using (MemoryStream outStream = new MemoryStream())
            {
                using (Ionic.Zlib.GZipStream gzipStream = new Ionic.Zlib.GZipStream(outStream, Ionic.Zlib.CompressionMode.Compress))
                using (MemoryStream srcStream = new MemoryStream(data))
                    srcStream.CopyTo(gzipStream);

                return outStream;//.ToArray();
            }
        }
Example #18
0
        public string requestMM()
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            try
            {
                request             = (HttpWebRequest)HttpWebRequest.Create("https://mms.pinduoduo.com/express_waybill/shop/orderList");
                request.Method      = "Post";
                request.ContentType = "application/json; charset=UTF-8";
                request.UserAgent   = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3942.0 Safari/537.36 Edg/79.0.305.0";
                //request.AllowAutoRedirect = true;
                //request.CookieContainer = container;//获取验证码时候取到的cookie 会附加到这个容器里面
                request.KeepAlive = true;//建立持久性链接
                request.Accept    = "application/json, text/javascript, */*; q=0.01";
                request.Referer   = "https://mms.pinduoduo.com/order.html";
                request.Host      = "mms.pinduoduo.com";

                //Accept-Encoding
                //Accept-Language
                //Origin
                CookieContainer co     = new CookieContainer();
                string          cookie = "JSESSIONID=43A36356B6E5E3A343AB88ABC68C54C3; PASS_ID=1-iHuRrOQq/tnIiIgIkAOI4zM06lG/nTjdLCxqjdjwpAdVyOs8FbKtOuSOKuXUpAZKyzyaLIlreaSgkt2TCqB8Nw_240505030_28686518; _nano_fp=XpdJlp9qnpXbn0doX9_7qedY3JvCGkow4efVvIiA; api_uid=rBQR2V62wksnBA1JFdKBAg==";
                //co.SetCookies(new Uri("https://mms.pinduoduo.com"), "JSESSIONID=43A36356B6E5E3A343AB88ABC68C54C3");
                //co.SetCookies(new Uri("https://mms.pinduoduo.com"), "");
                //request.CookieContainer = co;
                request.Headers.Add("Cookie", cookie);
                request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
                request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
                //request.Headers.Add("Connection", "Keep-Alive");
                //request.Connection = "Keep-Alive";
                //Common.NetHelper.SetHeaderValue(request.Headers, "Connection", "Keep-Alive");

                long dt1 = DateTime.Now.ToTimeStamp();              //当前时间时间戳
                long dt2 = DateTime.Now.AddDays(-30).ToTimeStamp(); //30天前时间戳

                //数据
                //string postData = "{ 'orderOnlineType':0,'groupEndTime':"+dt1.ToString()+",'groupStartTime':"+dt2.ToString()+",'pageNumber':1,'pageSize':50,'afterSaleType':1}";
                string        postData     = "{\"orderOnlineType\":0,\"groupEndTime\":" + dt1.ToString() + ",\"groupStartTime\":" + dt2.ToString() + ",\"pageNumber\":1,\"pageSize\":50,\"afterSaleType\":1}";
                ASCIIEncoding encoding     = new ASCIIEncoding();
                byte[]        bytepostDate = encoding.GetBytes(postData);
                request.ContentLength = bytepostDate.Length;

                //发送数据 using结束时释放代码
                using (Stream requestS = request.GetRequestStream())
                {
                    requestS.Write(bytepostDate, 0, bytepostDate.Length);
                }

                ////响应
                //response = (HttpWebResponse)request.GetResponse();
                //string text = string.Empty;
                //using (Stream responseS = response.GetResponseStream())
                //{
                //    StreamReader reader = new StreamReader(responseS, Encoding.UTF8);
                //    text = reader.ReadToEnd();
                //}

                string text = string.Empty;
                response = (HttpWebResponse)request.GetResponse();
                Stream getStream = response.GetResponseStream();
                //如果是使用Gzip的流的方式
                var ce = response.ContentEncoding;
                if (ce.ToLower() == "gzip")
                {
                    getStream = new Ionic.Zlib.GZipStream(getStream, Ionic.Zlib.CompressionMode.Decompress);
                }
                StreamReader streamReader = new StreamReader(getStream, Encoding.UTF8);
                //StreamReader streamReader = new StreamReader(getStream, Encoding.GetEncoding("gb2312"));
                text = streamReader.ReadToEnd();
                streamReader.Close();
                getStream.Close();

                return(text);
            }
            catch (Exception e)
            {
                e.ToShow();
            }
            return("");
        }
Example #19
0
        public static void SaveToFile(KPTranslation kpTrl, string strFileName,
			IXmlSerializerEx xs)
        {
            if(xs == null) throw new ArgumentNullException("xs");

            FileStream fs = new FileStream(strFileName, FileMode.Create,
                FileAccess.Write, FileShare.None);

            #if !KeePassLibSD
            Ionic.Zlib.GZipStream gz = new Ionic.Zlib.GZipStream(fs, Ionic.Zlib.CompressionMode.Compress);
            #else
            GZipOutputStream gz = new GZipOutputStream(fs);
            #endif

            XmlWriterSettings xws = new XmlWriterSettings();
            xws.CheckCharacters = true;
            xws.Encoding = StrUtil.Utf8;
            xws.Indent = true;
            xws.IndentChars = "\t";

            XmlWriter xw = XmlWriter.Create(gz, xws);

            xs.Serialize(xw, kpTrl);

            xw.Close();
            gz.Close();
            fs.Close();
        }
        private IEnumerator Post(CallRequestContainer reqContainer)
        {
#if PLAYFAB_REQUEST_TIMING
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var startTime = DateTime.UtcNow;
#endif

            var www = new UnityWebRequest(reqContainer.FullUrl)
            {
                uploadHandler   = new UploadHandlerRaw(reqContainer.Payload),
                downloadHandler = new DownloadHandlerBuffer(),
                method          = "POST"
            };

            foreach (var headerPair in reqContainer.RequestHeaders)
            {
                if (!string.IsNullOrEmpty(headerPair.Key) && !string.IsNullOrEmpty(headerPair.Value))
                {
                    www.SetRequestHeader(headerPair.Key, headerPair.Value);
                }
                else
                {
                    Debug.LogWarning("Null header: " + headerPair.Key + " = " + headerPair.Value);
                }
            }

#if UNITY_2017_2_OR_NEWER
            yield return(www.SendWebRequest());
#else
            yield return(www.Send());
#endif

#if PLAYFAB_REQUEST_TIMING
            stopwatch.Stop();
            var timing = new PlayFabHttp.RequestTiming {
                StartTimeUtc        = startTime,
                ApiEndpoint         = reqContainer.ApiEndpoint,
                WorkerRequestMs     = (int)stopwatch.ElapsedMilliseconds,
                MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
            };
            PlayFabHttp.SendRequestTiming(timing);
#endif

            if (!string.IsNullOrEmpty(www.error))
            {
                OnError(www.error, reqContainer);
            }
            else
            {
                try
                {
                    byte[] responseBytes    = www.downloadHandler.data;
                    bool   isGzipCompressed = responseBytes != null && responseBytes[0] == 31 && responseBytes[1] == 139;
                    string responseText     = "Unexpected error: cannot decompress GZIP stream.";
                    if (!isGzipCompressed && responseBytes != null)
                    {
                        responseText = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length);
                    }
#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
                    if (isGzipCompressed)
                    {
                        var stream = new MemoryStream(responseBytes);
                        using (var gZipStream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress, false))
                        {
                            var buffer = new byte[4096];
                            using (var output = new MemoryStream())
                            {
                                int read;
                                while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    output.Write(buffer, 0, read);
                                }
                                output.Seek(0, SeekOrigin.Begin);
                                var streamReader = new StreamReader(output);
                                var jsonResponse = streamReader.ReadToEnd();
                                //Debug.Log(jsonResponse);
                                OnResponse(jsonResponse, reqContainer);
                                //Debug.Log("Successful UnityHttp decompress for: " + www.url);
                            }
                        }
                    }
                    else
#endif
                    {
                        OnResponse(responseText, reqContainer);
                    }
                }
                catch (Exception e)
                {
                    OnError("Unhandled error in PlayFabUnityHttp: " + e, reqContainer);
                }
            }
            www.Dispose();
        }
Example #21
0
        // public void Save(string strFile, PwGroup pgDataSource, KdbxFormat format,
        //    IStatusLogger slLogger)
        // {
        //    bool bMadeUnhidden = UrlUtil.UnhideFile(strFile);
        //
        //    IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
        //    this.Save(IOConnection.OpenWrite(ioc), pgDataSource, format, slLogger);
        //
        //    if(bMadeUnhidden) UrlUtil.HideFile(strFile, true); // Hide again
        // }
        /// <summary>
        /// Save the contents of the current <c>PwDatabase</c> to a KDBX file.
        /// </summary>
        /// <param name="sSaveTo">Stream to write the KDBX file into.</param>
        /// <param name="pgDataSource">Group containing all groups and
        /// entries to write. If <c>null</c>, the complete database will
        /// be written.</param>
        /// <param name="format">Format of the file to create.</param>
        /// <param name="slLogger">Logger that recieves status information.</param>
        public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat format,
			IStatusLogger slLogger)
        {
            Debug.Assert(sSaveTo != null);
            if(sSaveTo == null) throw new ArgumentNullException("sSaveTo");

            m_format = format;
            m_slLogger = slLogger;

            HashingStreamEx hashedStream = new HashingStreamEx(sSaveTo, true, null);

            UTF8Encoding encNoBom = StrUtil.Utf8;
            CryptoRandom cr = CryptoRandom.Instance;

            try
            {
                m_pbMasterSeed = cr.GetRandomBytes(32);
                m_pbTransformSeed = cr.GetRandomBytes(32);
                m_pbEncryptionIV = cr.GetRandomBytes(16);

                m_pbProtectedStreamKey = cr.GetRandomBytes(32);
                m_craInnerRandomStream = CrsAlgorithm.Salsa20;
                m_randomStream = new CryptoRandomStream(m_craInnerRandomStream,
                    m_pbProtectedStreamKey);

                m_pbStreamStartBytes = cr.GetRandomBytes(32);

                Stream writerStream;
                if(m_format == KdbxFormat.Default || m_format == KdbxFormat.ProtocolBuffers)
                {
                    WriteHeader(hashedStream); // Also flushes the stream

                    Stream sEncrypted = AttachStreamEncryptor(hashedStream);
                    if((sEncrypted == null) || (sEncrypted == hashedStream))
                        throw new SecurityException(KLRes.CryptoStreamFailed);

                    sEncrypted.Write(m_pbStreamStartBytes, 0, m_pbStreamStartBytes.Length);

                    Stream sHashed = new HashedBlockStream(sEncrypted, true);

                    if(m_pwDatabase.Compression == PwCompressionAlgorithm.GZip)
                        writerStream = new Ionic.Zlib.GZipStream(sHashed, Ionic.Zlib.CompressionMode.Compress);
                    else
                        writerStream = sHashed;
                }
                else if(m_format == KdbxFormat.PlainXml)
                    writerStream = hashedStream;
                else { Debug.Assert(false); throw new FormatException("KdbFormat"); }

                var stopWatch = Stopwatch.StartNew();

                if (m_format == KdbxFormat.ProtocolBuffers)
                {
                    KdbpFile.WriteDocument(m_pwDatabase, writerStream, m_pbProtectedStreamKey, m_pbHashOfHeader);
                }
                else
                {
                    m_xmlWriter = new XmlTextWriter(writerStream, encNoBom);
                    WriteDocument(pgDataSource);

                    m_xmlWriter.Flush();
                    m_xmlWriter.Close();
                }

                writerStream.Close();

                Kp2aLog.Log(String.Format("{1}: {0}ms", stopWatch.ElapsedMilliseconds, m_format == KdbxFormat.ProtocolBuffers ? "KdbpFile.WriteDocument" : "Xml WriteDocument"));
            }
            finally { CommonCleanUpWrite(sSaveTo, hashedStream); }
        }