Beispiel #1
0
        public static byte[] GetAddonInfoData(CharacterSession session, byte[] packedData, int packedSize, int unpackedSize)
        {
            // Check ZLib header (normal mode)
            if (packedData[0] == 0x78 && packedData[1] == 0x9C)
            {
                var unpackedAddonData = new byte[unpackedSize];

                if (packedSize > 0)
                {
                    using (var inflate = new DeflateStream(new MemoryStream(packedData, 2, packedSize - 6), CompressionMode.Decompress))
                    {
                        var decompressed = new MemoryStream();
                        inflate.CopyTo(decompressed);

                        decompressed.Seek(0, SeekOrigin.Begin);

                        for (int i = 0; i < unpackedSize; i++)
                            unpackedAddonData[i] = (byte)decompressed.ReadByte();
                    }
                }

                return unpackedAddonData;
            }
            else
            {
                Log.Error($"Wrong AddonInfo for Client '{session.GetClientInfo()}'.");

                session.Dispose();
            }

            return null;
        }
Beispiel #2
0
		/// <summary>
		/// Returns decompressed version of given string.
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static string Decompress(string str)
		{
			if (str.Length < 12) // zlib header + checksum
				throw new InvalidDataException("Compressed data seems too short.");

			// Strip length and zlib header
			var pos = str.IndexOf(';');
			if (pos == -1)
				pos = str.IndexOf("S");
			str = str.Substring((pos > -1 ? 4 + pos + 1 : 4));

			// Hex string to byte array
			int len = str.Length;
			var barr = new byte[len >> 1];
			for (int i = 0; i < len; i += 2)
				barr[i >> 1] = Convert.ToByte(str.Substring(i, 2), 16);

			// Decompress and return
			using (var mout = new MemoryStream())
			using (var min = new MemoryStream(barr))
			using (var df = new DeflateStream(min, CompressionMode.Decompress))
			{
				df.CopyTo(mout);
				return Encoding.Unicode.GetString(mout.ToArray());
			}
		}
Beispiel #3
0
		public WebSocket(DiscordClient client, JsonSerializer serializer, Logger logger)
		{
            _client = client;
            Logger = logger;
            _serializer = serializer;

            _lock = new AsyncLock();
            _taskManager = new TaskManager(Cleanup);
            CancelToken = new CancellationToken(true);
			_connectedEvent = new ManualResetEventSlim(false);

#if !DOTNET5_4
			_engine = new WS4NetEngine(client.Config, _taskManager);
#else
			_engine = new BuiltInEngine(client.Config);
#endif
            _engine.BinaryMessage += (s, e) =>
            {
	            using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2))
	            using (var decompressed = new MemoryStream())
	            {
		            using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
			            zlib.CopyTo(decompressed);
		            decompressed.Position = 0;
                    using (var reader = new StreamReader(decompressed))
			            ProcessMessage(reader.ReadToEnd()).GetAwaiter().GetResult();
	            }
            };
			_engine.TextMessage += (s, e) => ProcessMessage(e.Message).Wait(); 
		}
Beispiel #4
0
 // Methods
 public static Map FromId(int id)
 {
     lock (MapsManager.CheckLock)
     {
         if (MapsManager.MapId_Map.ContainsKey(id))
         {
             return MapsManager.MapId_Map[id];
         }
         string str = ((id % 10).ToString() + "/" + id.ToString() + ".dlm");
         if (MapsManager.D2pFileManager.MapExists(str))
         {
             MemoryStream stream = new MemoryStream(MapsManager.D2pFileManager.method_1(str)) { Position = 2 };
             DeflateStream stream2 = new DeflateStream(stream, CompressionMode.Decompress);
             byte[] buffer = new byte[50001];
             MemoryStream destination = new MemoryStream(buffer);
             stream2.CopyTo(destination);
             destination.Position = 0;
             BigEndianReader reader = new BigEndianReader(destination);
             Map map2 = new Map();
             map2.Init(reader);
             MapsManager.MapId_Map.Add(id, map2);
             if ((MapsManager.MapId_Map.Count > 1000))
             {
                 MapsManager.MapId_Map.Remove(MapsManager.MapId_Map.Keys.First());
             }
             return map2;
         }
         MapsManager.MapId_Map.Add(id, null);
         if ((MapsManager.MapId_Map.Count > 1000))
         {
             MapsManager.MapId_Map.Remove(MapsManager.MapId_Map.Keys.First());
         }
         return null;
     }
 }
        public static void LoadAddonInfoData(RealmSession session, byte[] packedData, int packedSize, int unpackedSize)
        {
            // Check ZLib header (normal mode)
            if (packedData[0] == 0x78 && packedData[1] == 0x9C)
            {
                var unpackedAddonData = new byte[unpackedSize];

                if (packedSize > 0)
                {
                    using (var inflate = new DeflateStream(new MemoryStream(packedData, 2, packedSize - 6), CompressionMode.Decompress))
                    {
                        var decompressed = new MemoryStream();
                        inflate.CopyTo(decompressed);

                        decompressed.Seek(0, SeekOrigin.Begin);

                        for (int i = 0; i < unpackedSize; i++)
                            unpackedAddonData[i] = (byte)decompressed.ReadByte();
                    }
                }

                HandleAddonInfo(session, unpackedAddonData);
            }
            else
            {
                Log.Message(LogType.Error, "Wrong AddonInfo for Client '{0}'.", session.GetClientIP());

                session.Dispose();
            }
        }
        public override UnbindResult Unbind(HttpRequestData request, IOptions options)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var payload = Convert.FromBase64String(request.QueryString["SAMLRequest"].First());
            using (var compressed = new MemoryStream(payload))
            {
                using (var decompressedStream = new DeflateStream(compressed, CompressionMode.Decompress, true))
                {
                    using (var deCompressed = new MemoryStream())
                    {
                        decompressedStream.CopyTo(deCompressed);

                        var xml = new XmlDocument()
                        {
                            PreserveWhitespace = true
                        };

                        xml.LoadXml(Encoding.UTF8.GetString(deCompressed.GetBuffer()));

                        return new UnbindResult(
                            xml.DocumentElement,
                            request.QueryString["RelayState"].SingleOrDefault());
                    }
                }
            }
        }
Beispiel #7
0
		public WebSocket(DiscordWSClient client)
		{
			_client = client;
			_logLevel = client.Config.LogLevel;

			_loginTimeout = client.Config.ConnectionTimeout;
			_cancelToken = new CancellationToken(true);
			_connectedEvent = new ManualResetEventSlim(false);
			
			_engine = new WebSocketSharpEngine(this, client.Config);
			_engine.BinaryMessage += (s, e) =>
			{
				using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2))
				using (var decompressed = new MemoryStream())
				{
					using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress))
						zlib.CopyTo(decompressed);
					decompressed.Position = 0;
                    using (var reader = new StreamReader(decompressed))
						ProcessMessage(reader.ReadToEnd()).Wait();
				}
            };
			_engine.TextMessage += (s, e) =>
			{
				/*await*/ ProcessMessage(e.Message).Wait();
			};
		}
 /// <summary>
 /// Decode the content
 /// </summary>
 /// <param name="data">Content to decode</param>
 /// <returns>Decoded content</returns>
 public byte[] Decode(byte[] data)
 {
     var output = new MemoryStream();
     var input = new MemoryStream(data);
     using (var stream = new DeflateStream(input, CompressionMode.Decompress))
         stream.CopyTo(output);
     return output.ToArray();
 }
 /// <summary>
 /// Decompresses the specified input.
 /// </summary>
 /// <param name="input">The input.</param>
 /// <returns>The decompressed data.</returns>
 public static byte[] Decompress(this byte[] input)
 {
     var inflatedStream = new MemoryStream(input);
     var outputStream = new MemoryStream();
     var decompressor = new DeflateStream(inflatedStream, CompressionMode.Decompress);
     decompressor.CopyTo(outputStream);
     decompressor.Close();
     return outputStream.ToArray();
 }
Beispiel #10
0
 /// <summary>解压缩数据流</summary>
 /// <param name="inStream">输入流</param>
 /// <param name="outStream">输出流</param>
 public static void Decompress(this Stream inStream, Stream outStream)
 {
     // 第三个参数为true,保持数据流打开,内部不应该干涉外部,不要关闭外部的数据流
     using (Stream stream = new DeflateStream(inStream, CompressionMode.Decompress, true))
     {
         stream.CopyTo(outStream);
         stream.Close();
     }
 }
Beispiel #11
0
        public static byte[] DecompressData(byte[] data)
        {
            MemoryStream ms = new MemoryStream();
            MemoryStream stream = new MemoryStream(data, 2, data.Length - 2);
            DeflateStream s = new DeflateStream(stream, CompressionMode.Decompress);
            s.CopyTo(ms);
            return ms.ToArray();

        }
 /// <summary>
 /// Decompresses the given data.
 /// </summary>
 /// <param name="data">The data to decompress.</param>
 /// <returns>The decompressed version of the data.</returns>
 public static byte[] Decompress(byte[] data)
 {
     using (var streamData = new MemoryStream(data))
     using (var streamDecompressed = new MemoryStream())
     using (var deflate = new DeflateStream(streamData, CompressionMode.Decompress))
     {
         deflate.CopyTo(streamDecompressed);
         return streamDecompressed.ToArray();
     }
 }
Beispiel #13
0
 public byte[] Decompress(byte[] input)
 {
     using (var inputStream = new MemoryStream(input))
     using (var decompressionStream = new DeflateStream(inputStream, CompressionMode.Decompress))
     using (var outputStream = new MemoryStream())
     {
         decompressionStream.CopyTo(outputStream);
         return outputStream.ToArray();
     }
 }
Beispiel #14
0
 public static byte[] Decompress(byte[] compressedData)
 {
     using (MemoryStream compressedStream = new MemoryStream(compressedData))
     using (MemoryStream decompressedStream = new MemoryStream())
     using (DeflateStream decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
     {
         decompressionStream.CopyTo(decompressedStream);
         return decompressedStream.GetBuffer();
     }
 }
Beispiel #15
0
 public byte[] Decompress(byte[] data)
 {
     using (MemoryStream destination = new MemoryStream())
     using (MemoryStream source = new MemoryStream(data))
     {
         DeflateStream deflate = new DeflateStream(source, CompressionMode.Decompress);
         deflate.CopyTo(destination);
         return destination.GetBuffer();
     }
 }
 public byte[] WindowDecompress(byte[] byteArray)
 {
     var compressedStream = new MemoryStream(byteArray);
     using (var inflateStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
     using (var decompressedStream = new MemoryStream())
     {
         inflateStream.CopyTo(decompressedStream);
         byte[] decompressed = decompressedStream.ToArray();
         return decompressed;
     }
 }
Beispiel #17
0
 public void decompress(ByteBuffer @in, ByteBuffer @out)
 {
     using (ByteBufferInputStream input = new ByteBufferInputStream(@in.duplicate()))
     using (DeflateStream inflater = new DeflateStream(input, CompressionMode.Decompress))
     using (ByteBufferOutputStream output = new ByteBufferOutputStream(@out))
     {
         inflater.CopyTo(output);
     }
     @out.flip();
     @in.position(@in.limit());
 }
 private static byte[] DecompressZippedData(byte[] compressedData)
 {
     using (var decompressedStream = new MemoryStream())
     {
         using (var compressedStream = new MemoryStream(compressedData))
         using (var decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
         {
             decompressionStream.CopyTo(decompressedStream);
         }
         return decompressedStream.ToArray();
     }
 }
	    /// <summary>
	    /// Decompress the contents of the stream into a byte array.
	    /// </summary>
	    /// <param name="inputStream">The stream to decompress.</param>
	    /// <returns>The decompressed byte array.</returns>
	    public byte[] Decompress(Stream inputStream)
		{
			if (inputStream == null) throw new ArgumentNullException("inputStream");
			using (var outputStream = new MemoryStream())
			{
				using (var deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress, true))
				{
					deflateStream.CopyTo(outputStream);
				}

				return outputStream.ToArray();
			}
		}
Beispiel #20
0
 public static byte[] Decompress(byte[] data)
 {
     using (var compressedStream = new MemoryStream(data))
     {
         compressedStream.Position = 2; //skip RFC1950 flags
         using (var zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
         using (var resultStream = new MemoryStream())
         {
             zipStream.CopyTo(resultStream);
             return resultStream.ToArray();
         }
     }
 }
Beispiel #21
0
        private static void PreloadUnmanagedLibraries()
        {
            // Preload correct library
            var bittyness = "x86";
            if (IntPtr.Size == 8)
                bittyness = "x64";

            var assemblyName = Assembly.GetExecutingAssembly().GetName();

            var libraries = Assembly.GetExecutingAssembly().GetManifestResourceNames()
                .Where(s => s.StartsWith(String.Format("{1}.{2}.{0}.", bittyness, assemblyName.Name, LibsFolder)))
                .ToArray();

            var dirName = Path.Combine(Path.GetTempPath(), String.Format("{2}.{1}.{0}", assemblyName.Version, bittyness, assemblyName.Name));
            if (!Directory.Exists(dirName))
                Directory.CreateDirectory(dirName);

            foreach (var lib in libraries)
            {
                string dllPath = Path.Combine(dirName, String.Join(".", lib.Split('.').Skip(3)));

                if (!File.Exists(dllPath))
                {
                    using (Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(lib))
                    using (var decompress = new DeflateStream(stm, CompressionMode.Decompress))
                    {
                        // Copy the assembly to the temporary file
                        try
                        {
                            using (Stream outFile = File.Create(dllPath))
                            {
                                decompress.CopyTo(outFile);
                            }
                        }
                        catch
                        {
                            // This may happen if another process has already created and loaded the file.
                            // Since the directory includes the version number of this assembly we can
                            // assume that it's the same bits, so we just ignore the excecption here and
                            // load the DLL.
                        }
                    }
                }

                // We must explicitly load the DLL here because the temporary directory
                // is not in the PATH.
                // Once it is loaded, the DllImport directives that use the DLL will use
                // the one that is already loaded into the process.
                LoadLibrary(dllPath);
            }
        }
Beispiel #22
0
        Boolean IAccessor.ReadComplete(IReader reader, Boolean success)
        {
            var ms = new MemoryStream();
            // 读取消息。对剩下的数据流,进行解压缩后,读取成为另一个消息
            using (var stream = new DeflateStream(reader.Stream, CompressionMode.Decompress, true))
            {
                //Message = Read(stream);
                // 必须全部复制到内存流,然后再读取,否则可能因为加密流不能读取位置和长度而导致消息读取失败
                stream.CopyTo(ms);
            }
            Message = Read(ms);

            return success;
        }
Beispiel #23
0
 public byte[] Decompress(byte[] bytes)
 {
     using (MemoryStream ms = new MemoryStream(bytes))
     {
         using (DeflateStream zip = new System.IO.Compression.DeflateStream(ms, CompressionMode.Decompress, false))
         {
             using (MemoryStream ms2 = new MemoryStream())
             {
                 zip.CopyTo(ms2);
                 return ms2.ToArray();
             }
         }
     }
 }
Beispiel #24
0
 public static byte[] Decompress(byte[] data, int startPos)
 {
     using (MemoryStream os = new MemoryStream())
     {
         using (MemoryStream ms = new MemoryStream(data, startPos, data.Length - startPos))
         {
             using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
             {
                 ds.CopyTo(os);
             }
         }
         return os.ToArray();
     }
 }
Beispiel #25
0
        public void Parse(FileV8Reader fileV8Reader, V8FileSystem fileSystem, string output, int threads = 1)
        {
            foreach (var reference in fileSystem.References)
            {
                fileV8Reader.Seek(reference.RefToData, SeekOrigin.Begin);
                string path = output + reference.FileHeader.FileName;

                using (MemoryStream memStream = new MemoryStream())
                {
                    using (MemoryStream memReader = new MemoryStream(fileV8Reader.ReadBytes(fileV8Reader.ReadBlockHeader())))
                    {
                        if (reference.IsInFlated)
                        {
                            using (DeflateStream deflateStream = new DeflateStream(memReader, CompressionMode.Decompress))
                            {
                                deflateStream.CopyTo(memStream);
                            }
                        }
                        else
                        {
                            memReader.CopyTo(memStream);
                        }
                    }

                    if (fileV8Reader.IsV8FileSystem(memStream))
                    {
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        memStream.Seek(0, SeekOrigin.Begin);
                        using (FileV8Reader tmpV8Reader = new FileV8Reader(new BinaryReader(memStream, Encoding.Default, true)))
                        {
                            reference.Folder = tmpV8Reader.ReadV8FileSystem(false);
                            Parse(tmpV8Reader, reference.Folder, path + "\\");
                        }
                    }
                    else
                    {
                        using (FileStream fileStream = File.Create(path))
                        {
                            memStream.Seek(0, SeekOrigin.Begin);
                            memStream.CopyTo(fileStream);
                        }
                    }
                }
            }
        }
Beispiel #26
0
		public void Decompress(ref byte[] buffer, ref int length)
		{
			using (MemoryStream inS = new MemoryStream(buffer.Take(length).ToArray()), outS = new MemoryStream())
			{
				using (DeflateStream ds = new DeflateStream(inS, CompressionMode.Decompress))
				{
					ds.CopyTo(outS);

					outS.Position = 0;
				}

				buffer = outS.ToArray();
				length = buffer.Length;
			}
		}
        public byte[] Decompress(byte[] compressedText)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (MemoryStream compressedStream = new MemoryStream(compressedText))
                {
                    using (DeflateStream deflater = new DeflateStream(compressedStream, CompressionMode.Decompress))
                    {
                        deflater.CopyTo(ms);
                    }
                }

                return ms.ToArray();
            }
        }
 public static void DecompressFile(string fileName)
 {
     FileStream inputStream = File.OpenRead(fileName);
     using (MemoryStream outputStream = new MemoryStream())
     using (var compressStream = new DeflateStream(inputStream, CompressionMode.Decompress))
     {
         compressStream.CopyTo(outputStream);
         outputStream.Seek(0, SeekOrigin.Begin);
         using (var reader = new StreamReader(outputStream, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4096, leaveOpen: true))
         {
             string result = reader.ReadToEnd();
             WriteLine(result);
         }
     }
 }
        public void WhenIIssueARequestTo(string httpMethod, string url)
        {
            var client = _context.GetHttpClient();
            _context.RequestMessage.RequestUri = IsAbsoluteUrl(url) ? new Uri(url) : new Uri(client.BaseAddress, url);
            _context.RequestMessage.Method = new HttpMethod(httpMethod);
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            var task = client.SendAsync(_context.RequestMessage);
            Task.WaitAll(task);
            stopWatch.Stop();

            _context.TimeTaken = stopWatch.Elapsed;
            _context.ResponseMessage = task.Result;

            var responseContentTask = _context.ResponseMessage.Content.ReadAsByteArrayAsync();
            Task.WaitAll(responseContentTask);
            using (var inStream = new MemoryStream(responseContentTask.Result))
            {
                if (_context.ResponseMessage.Content.Headers.ContentEncoding.Contains("gzip"))
                {

                    using (var bigStream = new GZipStream(inStream, CompressionMode.Decompress))
                    using (var bigStreamOut = new MemoryStream())
                    {
                        bigStream.CopyTo(bigStreamOut);
                        _context.ResponseContent = Encoding.UTF8.GetString(bigStreamOut.ToArray());
                        _context.DecompressionMethod = DecompressionMethods.GZip;
                    }

                }
                else if (_context.ResponseMessage.Content.Headers.ContentEncoding.Contains("deflate"))
                {
                    using (var bigStream = new DeflateStream(inStream, CompressionMode.Decompress))
                    using (var bigStreamOut = new MemoryStream())
                    {
                        bigStream.CopyTo(bigStreamOut);
                        _context.ResponseContent = Encoding.UTF8.GetString(bigStreamOut.ToArray());
                        _context.DecompressionMethod = DecompressionMethods.Deflate;
                    }
                }
                else
                {
                    _context.ResponseContent = Encoding.UTF8.GetString(inStream.ToArray());
                    _context.DecompressionMethod = DecompressionMethods.None;
                }
            }
        }
        public TraceData DeserializeTraceData(Stream stream)
        {

            /* Read the magic/version off the raw stream */
            byte[] magicBytes = new byte[sizeof(uint)];
            stream.Read(magicBytes, 0, sizeof(uint));
            byte[] versionBytes = new byte[sizeof(uint)];
            stream.Read(versionBytes, 0, sizeof(uint));

            using (DeflateStream deflate = new DeflateStream(stream,CompressionMode.Decompress))
            {
                deflate.CopyTo(ms);
            }
            ms.Seek(0, SeekOrigin.Begin);
            /* decompressed file is in ms */

            /* Read Magic */
            var magic = ReadUint();

            if (magic != MAGIC)
            {
                throw new DeSerializationError("Invalid Magic");
            }

            var version = ReadUint();
            if (version != VERSION)
            {
                throw new DeSerializationError("Invalid Version - Built with " + version + " deserializing with " + VERSION);
            }

            DeserializeStatisticItems();

            DeserializeStackTraces();

            DeserializeSQLStatements();

            DeserializeExecutionCalls();

            ResolveDependencies();

            RebuildExecutionPath();

            RebuildSQLCollections();

            Data.MaxCallDepth = ReadLong();

            return Data;
        }
        public void CompressorNotClosed_DecompressorStillSuccessful(bool closeCompressorBeforeDecompression)
        {
            const string Input = "example";

            var ms = new MemoryStream();

            using (var compressor = new DeflateStream(ms, CompressionLevel.Optimal, leaveOpen: closeCompressorBeforeDecompression))
            {
                compressor.Write(Encoding.ASCII.GetBytes(Input));
                compressor.Flush();
                if (closeCompressorBeforeDecompression)
                {
                    compressor.Dispose();
                }

                ms.Position = 0;
                using (var decompressor = new DeflateStream(ms, CompressionMode.Decompress, leaveOpen: true))
                {
                    var decompressed = new MemoryStream();
                    decompressor.CopyTo(decompressed);
                    Assert.Equal(Input, Encoding.ASCII.GetString(decompressed.ToArray()));
                }
            }
        }