Beispiel #1
0
        public void Test_ReadString()
        {
            var raw = new[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}.Select(x => (byte) x).ToArray();
            var stream = new MemoryStream(raw);

            var string_ = stream.ReadString(4);
            Assert.AreEqual("abcd", string_);

            string_ = stream.ReadString(100);
            Assert.AreEqual(4, string_.Length);
            Assert.AreEqual("efgh", string_);

            stream.Dispose();
        }
Beispiel #2
0
 /// <summary>
 /// Serializes the specified object.
 /// </summary>
 /// <typeparam name="Type">The type of the <paramref name="objectToSerialize"/>.</typeparam>
 /// <param name="objectToSerialize">The object to be serialized.</param>
 /// <param name="stylesheetName">Name of the stylesheet.</param>
 /// <returns>System.String.</returns>
 public static string Serialize <Type>(Type objectToSerialize, string stylesheetName)
 {
     using (System.IO.MemoryStream _writer = new System.IO.MemoryStream())
     {
         DocumentsFactory.XmlFile.WriteXmlFile <Type>(objectToSerialize, _writer, stylesheetName);
         return(_writer.ReadString());
     }
 }
Beispiel #3
0
        KeyValuePair <string, long> _bytesToPair(byte[] bytes)
        {
            MemoryStream ms  = new MemoryStream(bytes);
            string       str = ms.ReadString();
            long         val = ms.ReadInt64();

            return(new KeyValuePair <string, long>(str, val));
        }
        public string Serialize(IList<HeaderInfo> headers)
        {
            var serializer = new XmlSerializer(typeof(HeaderInfo[]));
            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, headers.ToArray());
                var content = stream.ReadString();

                return content;
            }
        }
 public virtual void CopyHeaderInfo()
 {
     var serializer = new XmlSerializer(typeof(HeaderInfo[]));
     using (var stream = new MemoryStream())
     {
         var headers = new List<HeaderInfo>(Headers);
         serializer.Serialize(stream, headers.ToArray());
         var content = stream.ReadString();
         _clipboard.CopyTo(content);
     }
 }
        public string Sanitize(string source)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(source);

            HtmlNode node = doc.DocumentNode.SelectSingleNode("//body");

            // No body, try to select the html node directly
            if (node == null)
                node = doc.DocumentNode.SelectSingleNode("//html");

            // If body not found (html contains no body tag), use the DocumentNode
            if (node == null)
                node = doc.DocumentNode;

            using (MemoryStream ms = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8);

                writer.WriteStartElement("div");

                if (node.HasChildNodes)
                {
                    foreach (var childNode in node.ChildNodes)
                        WriteTo(writer, childNode);
                }
                else
                {
                    WriteTo(writer, node);
                }

                writer.WriteEndElement();
                writer.Flush();

                // our source html is allready double encoded, so the following decode
                // will put it in proper order
                return HttpUtility.HtmlDecode(ms.ReadString());
            }
        }
        public void TestStreamString()
        {
            String obj = "Hallo Welt!";

            using (MemoryStream ms = new MemoryStream())
            {
                ms.WriteString(obj);
                ms.Seek(0, SeekOrigin.Begin);
                String res = ms.ReadString();

                Assert.IsTrue(obj.Equals(res), "Streaming failed!");
            }
        }
Beispiel #8
0
 private void ReadNames(MemoryStream fs)
 {
     DebugOutput.PrintLn("Reading Names...");
     fs.Seek(NameOffset, SeekOrigin.Begin);
     Names = new List<string>();
     for (int i = 0; i < NameCount; i++)
     {
         int len = fs.ReadValueS32();
         string s = "";
         if (len > 0)
         {
             s = fs.ReadString((uint)(len - 1));
             fs.Seek(9, SeekOrigin.Current);
         }
         else
         {
             len *= -1;
             for (int j = 0; j < len - 1; j++)
             {
                 s += (char)fs.ReadByte();
                 fs.ReadByte();
             }
             fs.Seek(10, SeekOrigin.Current);
         }
         Names.Add(s);
     }
 }
Beispiel #9
0
        private void ParseData(GetDataEventArgs args)
        {
            try
            {
                PacketTypes packet = args.MsgID;
                using (var data = new MemoryStream(args.Msg.readBuffer, args.Index, args.Length))
                {
                    TSPlayer player = TShock.Players[args.Msg.whoAmI];
                    var name = player.Name;
                    if (player.IsLoggedIn)
                    {
                        name = player.UserAccountName;
                    }
                    switch (packet)
                    {
                        case PacketTypes.Tile:
                            {
                                byte type = data.ReadInt8();
                                int x = data.ReadInt32();
                                int y = data.ReadInt32();
                                bool fail = true;
                                Action act;
                                if (type == 0 || type == 2 || type == 4)
                                    act = Action.BREAK;
                                else if (type == 1 || type == 3)
                                    act = Action.PLACE;
                                else
                                    act = Action.ERROR;

                                byte tileType = 0;

                                if (act == Action.BREAK)
                                {
                                    tileType = Main.tile[x, y].type;
                                    fail = data.ReadBoolean();
                                }
                                else if (act == Action.PLACE)
                                {
                                    tileType = data.ReadInt8();
                                    fail = false;
                                }
                                if (act != Action.ERROR && !fail)
                                {
                                    TileEvent evt = new TileEvent(x, y, name, player.IP, act, tileType,
                                                                  LogTile.helper.GetTime());
                                    queue.Enqueue(evt);
                                }
                                break;
                            }
                        case PacketTypes.TileKill:
                            {
                                int x = data.ReadInt32();
                                int y = data.ReadInt32();
                                TileEvent evt = new TileEvent(x, y, name, player.IP, Action.BREAK, 0x15,
                                                              LogTile.helper.GetTime());
                                queue.Enqueue(evt);
                                break;
                            }
                        case PacketTypes.ChestOpen:
                            {
                                int chestID = data.ReadInt16();
                                int x = data.ReadInt32();
                                int y = data.ReadInt32();
                                int curChest = 0;
                                if (!chestMap.TryGetValue(player, out curChest)) // chest being opened
                                {
                                    chestMap.Add(player, chestID);
                                    itemMap.Add(player, Main.chest[chestID].item);
                                }
                                else // chest is being closed
                                {
                                    chestMap.Remove(player);
                                    itemMap.Remove(player);
                                }

                                break;
                            }
                        case PacketTypes.ChestItem:
                            {
                                int chestID = data.ReadInt16();
                                byte itemSlot = data.ReadInt8();
                                byte stack = data.ReadInt8();
                                int curChest = 0;
                                int type = itemMap[player][itemSlot].type;
                                if (LogTile.enableDebugOutput)
                                    Console.WriteLine(type);
                                Item[] curItems = Main.chest[chestID].item;
                                if (LogTile.enableDebugOutput)
                                    Console.WriteLine(curItems[itemSlot].type);
                                itemMap.Remove(player);
                                itemMap.Add(player, curItems);
                                break;
                            }
                        case PacketTypes.ChestGetContents:
                            {
                                int x = data.ReadInt32();
                                int y = data.ReadInt32();
                                if (LogTile.enableDebugOutput)
                                    Console.WriteLine("GETChestContents: (" + x + ", " + y + ")");
                                break;
                            }
                        case PacketTypes.SignNew:
                            {
                                int id = data.ReadInt16();
                                int x = data.ReadInt32();
                                int y = data.ReadInt32();
                                string text = data.ReadString();
                                break;
                            }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #10
0
 private async Task<IResponse> GetResponseAsync(Byte[] content)
 {
     var ms = new MemoryStream(content);
     var code = ms.ReadInt();
     var addr = ms.ReadString();
     var hdrs = ms.ReadDictionary();
     var ctnt = new MemoryStream();
     await ms.CopyToAsync(ctnt).ConfigureAwait(false);
     ctnt.Position = 0;
     return new Response
     {
         StatusCode = (HttpStatusCode)code,
         Address = new Url(addr),
         Headers = hdrs,
         Content = ctnt
     };
 }
        private static void Main(string[] args)
        {
            var paths = Directory.GetFiles("saves", "*.sav");

            var successes = 0;
            var failures = 0;

            foreach (var path in paths)
            {
                var name = Path.GetFileNameWithoutExtension(path);

                using (var input = File.OpenRead(path))
                {
                    var readHash = input.ReadBytes(20);
                    using (var data = input.ReadToMemoryStream(input.Length - 20))
                    {
                        byte[] computedHash;
                        using (var sha1 = new System.Security.Cryptography.SHA1Managed())
                        {
                            computedHash = sha1.ComputeHash(data);
                        }

                        if (readHash.SequenceEqual(computedHash) == false)
                        {
                            Console.WriteLine("{0}: failed (SHA1 mismatch)", name);
                            failures++;
                            continue;
                        }

                        data.Position = 0;
                        var uncompressedSize = data.ReadValueU32(Endian.Big);
                        var actualUncompressedSize = (int)uncompressedSize;
                        var uncompressedBytes = new byte[uncompressedSize];
                        var compressedSize = (int)(data.Length - 4);
                        var compressedBytes = data.ReadBytes(compressedSize);
                        var result = LZO.Decompress(compressedBytes,
                                                    0,
                                                    compressedSize,
                                                    uncompressedBytes,
                                                    0,
                                                    ref actualUncompressedSize);
                        if (result != LZO.ErrorCode.Success)
                        {
                            Console.WriteLine("{0}: failed (LZO error {1})", name, result);
                            failures++;
                            continue;
                        }

                        using (var outerData = new MemoryStream(uncompressedBytes))
                        {
                            var innerSize = outerData.ReadValueU32(Endian.Big);
                            var magic = outerData.ReadString(3);
                            if (magic != "WSG")
                            {
                                Console.WriteLine("{0}: failed (bad magic)", name);
                                failures++;
                                continue;
                            }

                            var version = outerData.ReadValueU32(Endian.Little);
                            if (version != 2 &&
                                version.Swap() != 2)
                            {
                                Console.WriteLine("{0}: failed (bad version)", name);
                                failures++;
                                continue;
                            }

                            var endian = version == 2 ? Endian.Little : Endian.Big;

                            var hash = outerData.ReadValueU32(endian);
                            var innerUncompressedSize = outerData.ReadValueS32(endian);

                            var innerCompressedBytes = outerData.ReadBytes(innerSize - 3 - 4 - 4 - 4);
                            var innerUncompressedBytes = Huffman.Decoder.Decode(innerCompressedBytes,
                                                                                innerUncompressedSize);
                            using (var innerUncompressedData = new MemoryStream(innerUncompressedBytes))
                            {
                                using (var output = File.Create("temp.bin"))
                                {
                                    output.WriteBytes(innerUncompressedBytes);
                                }

                                var save =
                                    Serializer.Deserialize<WillowTwoSave.WillowTwoPlayerSaveGame>(innerUncompressedData);

                                using (var testData = new MemoryStream())
                                {
                                    Serializer.Serialize(testData, save);

                                    testData.Position = 0;
                                    var testBytes = testData.ReadBytes((uint)testData.Length);
                                    if (innerUncompressedBytes.SequenceEqual(testBytes) == false)
                                    {
                                        Console.WriteLine("{0}: failed (reencode mismatch)", name);

                                        using (var output = File.Create(Path.Combine("failures", name + "_before.bin")))
                                        {
                                            output.WriteBytes(innerUncompressedBytes);
                                        }

                                        using (var output = File.Create(Path.Combine("failures", name + "_after.bin")))
                                        {
                                            output.WriteBytes(testBytes);
                                        }

                                        failures++;
                                        continue;
                                    }

                                    successes++;
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine("{0} processed ({1} failed, {2} succeeded).",
                              paths.Length,
                              failures,
                              successes);
        }
Beispiel #12
0
 private void ReadNames(MemoryStream fs)
 {
     DebugOutput.PrintLn("Reading Names...");
     fs.Seek(NameOffset, SeekOrigin.Begin);
     Names = new List<string>();
     for (int i = 0; i < NameCount; i++)
     {
         int len = fs.ReadValueS32();
         string s = fs.ReadString((uint)(len - 1));
         fs.Seek(5, SeekOrigin.Current);
         Names.Add(s);
     }
 }
        public static SaveFile Deserialize(Stream input, DeserializeSettings settings)
        {
            if (input.Position + 20 > input.Length)
            {
                throw new SaveCorruptionException("not enough data for save header");
            }

            var check = input.ReadValueU32(Endian.Big);
            if (check == 0x434F4E20)
            {
                throw new SaveFormatException("Xbox 360 save game loading is in the works");

            }
            input.Seek(-4, SeekOrigin.Current);

            var readSha1Hash = input.ReadBytes(20);
            using (var data = input.ReadToMemoryStream(input.Length - 20))
            {
                byte[] computedSha1Hash;
                using (var sha1 = new System.Security.Cryptography.SHA1Managed())
                {
                    computedSha1Hash = sha1.ComputeHash(data);
                }

                if ((settings & DeserializeSettings.IgnoreSha1Mismatch) == 0 &&
                    readSha1Hash.SequenceEqual(computedSha1Hash) == false)
                {
                    throw new SaveCorruptionException("invalid SHA1 hash");
                }

                data.Position = 0;
                var uncompressedSize = data.ReadValueU32(Endian.Big);

                var uncompressedBytes = new byte[uncompressedSize];
                if (uncompressedSize <= BlockSize)
                {
                    var actualUncompressedSize = (int)uncompressedSize;
                    var compressedSize = (uint)(data.Length - 4);
                    var compressedBytes = data.ReadBytes(compressedSize);
                    var result = LZO.Decompress(compressedBytes,
                                                0,
                                                (int)compressedSize,
                                                uncompressedBytes,
                                                0,
                                                ref actualUncompressedSize);
                    if (result != LZO.ErrorCode.Success)
                    {
                        throw new SaveCorruptionException(string.Format("LZO decompression failure ({0})", result));
                    }

                    if (actualUncompressedSize != (int)uncompressedSize)
                    {
                        throw new SaveCorruptionException("LZO decompression failure (uncompressed size mismatch)");
                    }
                }
                else
                {
                    var blockCount = data.ReadValueU32(Endian.Big);
                    var blockInfos = new List<Tuple<uint, uint>>();
                    for (uint i = 0; i < blockCount; i++)
                    {
                        var blockCompressedSize = data.ReadValueU32(Endian.Big);
                        var blockUncompressedSize = data.ReadValueU32(Endian.Big);
                        blockInfos.Add(new Tuple<uint, uint>(blockCompressedSize, blockUncompressedSize));
                    }

                    int uncompressedOffset = 0;
                    int uncompressedSizeLeft = (int)uncompressedSize;
                    foreach (var blockInfo in blockInfos)
                    {
                        var blockUncompressedSize = Math.Min((int)blockInfo.Item2, uncompressedSizeLeft);
                        var actualUncompressedSize = blockUncompressedSize;
                        var compressedSize = (int)blockInfo.Item1;
                        var compressedBytes = data.ReadBytes(compressedSize);
                        var result = LZO.Decompress(compressedBytes,
                                                    0,
                                                    compressedSize,
                                                    uncompressedBytes,
                                                    uncompressedOffset,
                                                    ref actualUncompressedSize);
                        if (result != LZO.ErrorCode.Success)
                        {
                            throw new SaveCorruptionException(string.Format("LZO decompression failure ({0})", result));
                        }

                        if (actualUncompressedSize != blockUncompressedSize)
                        {
                            throw new SaveCorruptionException("LZO decompression failure (uncompressed size mismatch)");
                        }

                        uncompressedOffset += blockUncompressedSize;
                        uncompressedSizeLeft -= blockUncompressedSize;
                    }

                    if (uncompressedSizeLeft != 0)
                    {
                        throw new SaveCorruptionException("LZO decompression failure (uncompressed size left != 0)");
                    }
                }

                using (var outerData = new MemoryStream(uncompressedBytes))
                {
                    var innerSize = outerData.ReadValueU32(Endian.Big);
                    var magic = outerData.ReadString(3);
                    if (magic != "WSG")
                    {
                        throw new SaveCorruptionException("invalid magic");
                    }

                    var version = outerData.ReadValueU32(Endian.Little);
                    if (version != 2 &&
                        version.Swap() != 2)
                    {
                        throw new SaveCorruptionException("invalid or unsupported version");
                    }
                    var endian = version == 2 ? Endian.Little : Endian.Big;

                    var readCRC32Hash = outerData.ReadValueU32(endian);
                    var innerUncompressedSize = outerData.ReadValueS32(endian);

                    var innerCompressedBytes = outerData.ReadBytes(innerSize - 3 - 4 - 4 - 4);
                    var innerUncompressedBytes = Huffman.Decoder.Decode(innerCompressedBytes,
                                                                        innerUncompressedSize);
                    if (innerUncompressedBytes.Length != innerUncompressedSize)
                    {
                        throw new SaveCorruptionException("huffman decompression failure");
                    }

                    var computedCRC32Hash = CRC32.Hash(innerUncompressedBytes, 0, innerUncompressedBytes.Length);
                    if ((settings & DeserializeSettings.IgnoreCrc32Mismatch) == 0 &&
                        computedCRC32Hash != readCRC32Hash)
                    {
                        throw new SaveCorruptionException("invalid CRC32 hash");
                    }

                    using (var innerUncompressedData = new MemoryStream(innerUncompressedBytes))
                    {
                        var saveGame =
                            ProtoBuf.Serializer.Deserialize<WillowTwoSave.WillowTwoPlayerSaveGame>(innerUncompressedData);

                        if ((settings & DeserializeSettings.IgnoreReencodeMismatch) == 0)
                        {
                            using (var testData = new MemoryStream())
                            {
                                ProtoBuf.Serializer.Serialize(testData, saveGame);

                                testData.Position = 0;
                                var testBytes = testData.ReadBytes((uint)testData.Length);
                                if (innerUncompressedBytes.SequenceEqual(testBytes) == false)
                                {
                                    throw new SaveCorruptionException("reencode mismatch");
                                }
                            }
                        }

                        saveGame.Decompose();
                        return new SaveFile()
                        {
                            Endian = endian,
                            SaveGame = saveGame,
                        };
                    }
                }
            }
        }
Beispiel #14
0
 void ReadNames(MemoryStream fs)
 {
     fs.Seek(NameOffset, SeekOrigin.Begin);
     names = new List<string>();
     for (int i = 0; i < NameCount; i++)
     {
         int len = fs.ReadValueS32();
         string s = fs.ReadString((uint)(len - 1));
         fs.Seek(5, SeekOrigin.Current);
         names.Add(s);
     }
 }
Beispiel #15
0
        private static void Main(string[] args)
        {
            bool showHelp = false;
            bool overwriteFiles = false;
            bool verbose = false;

            var options = new OptionSet()
            {
                {
                    "o|overwrite",
                    "overwrite existing files",
                    v => overwriteFiles = v != null
                    },
                {
                    "v|verbose",
                    "be verbose",
                    v => verbose = v != null
                    },
                {
                    "h|help",
                    "show this message and exit",
                    v => showHelp = v != null
                    },
            };

            List<string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || extras.Count > 2 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_tms [output_dir]", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            string inputPath = extras[0];
            string outputPath = extras.Count > 1 ? extras[1] : Path.ChangeExtension(inputPath, null) + "_unpack";

            var endian = Endian.Little;

            using (var input = File.OpenRead(inputPath))
            {
                var uncompressedSize3 = input.ReadValueU32(endian);
                var fileCount = input.ReadValueU32(endian);
                var magic = input.ReadValueU32(endian);
                var version = input.ReadValueU32(endian);

                if (magic != 0x9E2A83C1 ||
                    version != 0x00020000)
                {
                    throw new FormatException();
                }

                var compressedSize1 = input.ReadValueU32(endian);
                var uncompressedSize1 = input.ReadValueU32(endian);
                var compressedSize2 = input.ReadValueU32(endian);
                var uncompressedSize2 = input.ReadValueU32(endian);

                if (compressedSize1 != compressedSize2 ||
                    uncompressedSize1 != uncompressedSize2 ||
                    uncompressedSize1 != uncompressedSize3)
                {
                    throw new FormatException();
                }

                var compressedBytes = input.ReadBytes(compressedSize1);
                var uncompressedBytes = new byte[uncompressedSize1];

                var actualUncompressedSize = (int)uncompressedSize1;
                var result = LZO.Decompress(compressedBytes,
                                            0,
                                            (int)compressedSize1,
                                            uncompressedBytes,
                                            0,
                                            ref actualUncompressedSize);
                if (result != LZO.ErrorCode.Success)
                {
                    throw new FormatException();
                }

                if (actualUncompressedSize != uncompressedSize1)
                {
                    throw new FormatException();
                }

                using (var data = new MemoryStream(uncompressedBytes))
                {
                    for (uint i = 0; i < fileCount; i++)
                    {
                        var entryNameLength = data.ReadValueS32(endian);
                        if (entryNameLength < 0)
                        {
                            throw new NotImplementedException();
                        }

                        var entryName = data.ReadString(entryNameLength, true, Encoding.ASCII);
                        var entryTextLength = data.ReadValueS32(endian);

                        Encoding entryTextEncoding;
                        if (entryTextLength >= 0)
                        {
                            entryTextEncoding = Encoding.ASCII;
                        }
                        else
                        {
                            entryTextEncoding = Encoding.Unicode;
                            entryTextLength = (-entryTextLength) * 2;
                        }
                        var entryText = data.ReadString(entryTextLength, true, entryTextEncoding);

                        var entryPath = Path.Combine(outputPath, entryName);
                        if (overwriteFiles == false &&
                            File.Exists(entryPath) == true)
                        {
                            continue;
                        }

                        if (verbose == true)
                        {
                            Console.WriteLine(entryName);
                        }

                        var entryParentPath = Path.GetDirectoryName(entryPath);
                        if (string.IsNullOrEmpty(entryParentPath) == false)
                        {
                            Directory.CreateDirectory(entryParentPath);
                        }

                        using (var output = new StreamWriter(entryPath, false, entryTextEncoding))
                        {
                            output.Write(entryText);
                        }
                    }
                }
            }
        }