XZFooter.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System.IO;
  2. using System.Linq;
  3. using System.Text;
  4. using SharpCompress.IO;
  5. namespace SharpCompress.Compressors.Xz
  6. {
  7. public class XZFooter
  8. {
  9. private readonly BinaryReader _reader;
  10. private readonly byte[] _magicBytes = { 0x59, 0x5A };
  11. public long StreamStartPosition { get; private set; }
  12. public long BackwardSize { get; private set; }
  13. public byte[] StreamFlags { get; private set; }
  14. public XZFooter(BinaryReader reader)
  15. {
  16. _reader = reader;
  17. StreamStartPosition = reader.BaseStream.Position;
  18. }
  19. public static XZFooter FromStream(Stream stream)
  20. {
  21. var footer = new XZFooter(new BinaryReader(new NonDisposingStream(stream), Encoding.UTF8));
  22. footer.Process();
  23. return footer;
  24. }
  25. public void Process()
  26. {
  27. uint crc = _reader.ReadLittleEndianUInt32();
  28. byte[] footerBytes = _reader.ReadBytes(6);
  29. uint myCrc = Crc32.Compute(footerBytes);
  30. if (crc != myCrc)
  31. throw new InvalidDataException("Footer corrupt");
  32. using (var stream = new MemoryStream(footerBytes))
  33. using (var reader = new BinaryReader(stream))
  34. {
  35. BackwardSize = (reader.ReadLittleEndianUInt32() + 1) * 4;
  36. StreamFlags = reader.ReadBytes(2);
  37. }
  38. byte[] magBy = _reader.ReadBytes(2);
  39. if (!magBy.SequenceEqual(_magicBytes))
  40. {
  41. throw new InvalidDataException("Magic footer missing");
  42. }
  43. }
  44. }
  45. }