From c3e070d981b4424349c09098832b399b0c849f1d Mon Sep 17 00:00:00 2001 From: KillzXGaming Date: Sun, 10 Nov 2019 11:14:09 -0500 Subject: [PATCH] Improve zlib decompression to support varied positions --- .../Compression/Formats/Zlib.cs | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/Switch_Toolbox_Library/Compression/Formats/Zlib.cs b/Switch_Toolbox_Library/Compression/Formats/Zlib.cs index 7203c831..a5e60246 100644 --- a/Switch_Toolbox_Library/Compression/Formats/Zlib.cs +++ b/Switch_Toolbox_Library/Compression/Formats/Zlib.cs @@ -19,26 +19,29 @@ namespace Toolbox.Library public bool Identify(Stream stream, string fileName) { + if (stream.Length < 16) return false; + using (var reader = new FileReader(stream, true)) { startPosition = stream.Position; reader.SetByteOrder(true); - ushort magicNumber = reader.ReadUInt16(); + bool IsValid = false; + for (int i = 0; i < 4; i++) + { + ushort magicNumber = reader.ReadUInt16(); + reader.ReadUInt16(); - reader.Position = startPosition + 4; - ushort magicNumber2 = reader.ReadUInt16(); + IsValid = magicNumber == 0x789C || magicNumber == 0x78DA; + if (IsValid) + { + startPosition = reader.Position - 4; + break; + } + } - //Check 2 cases which the file is zlibbed. - //One is that it is compressed with magic at start - //Another is a size (uint) then magic - bool IsValid = magicNumber == 0x789C || magicNumber == 0x78DA; - bool IsValid2 = magicNumber2 == 0x789C || magicNumber2 == 0x78DA; - if (IsValid2) - startPosition = stream.Position + 4; - - return IsValid || IsValid2; + return IsValid; } }