MarkHeader.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.IO;
  3. namespace SharpCompress.Common.Rar.Headers
  4. {
  5. internal class MarkHeader : IRarHeader
  6. {
  7. private const int MAX_SFX_SIZE = 0x80000 - 16; //archive.cpp line 136
  8. internal bool OldNumberingFormat { get; private set; }
  9. public bool IsRar5 { get; }
  10. private MarkHeader(bool isRar5)
  11. {
  12. IsRar5 = isRar5;
  13. }
  14. public HeaderType HeaderType => HeaderType.Mark;
  15. private static byte GetByte(Stream stream)
  16. {
  17. var b = stream.ReadByte();
  18. if (b != -1)
  19. {
  20. return (byte)b;
  21. }
  22. throw new EndOfStreamException();
  23. }
  24. public static MarkHeader Read(Stream stream, bool leaveStreamOpen, bool lookForHeader)
  25. {
  26. int maxScanIndex = lookForHeader ? MAX_SFX_SIZE : 0;
  27. try
  28. {
  29. int start = -1;
  30. var b = GetByte(stream); start++;
  31. while (start <= maxScanIndex)
  32. {
  33. // Rar old signature: 52 45 7E 5E
  34. // Rar4 signature: 52 61 72 21 1A 07 00
  35. // Rar5 signature: 52 61 72 21 1A 07 01 00
  36. if (b == 0x52)
  37. {
  38. b = GetByte(stream); start++;
  39. if (b == 0x61)
  40. {
  41. b = GetByte(stream); start++;
  42. if (b != 0x72) continue;
  43. b = GetByte(stream); start++;
  44. if (b != 0x21) continue;
  45. b = GetByte(stream); start++;
  46. if (b != 0x1a) continue;
  47. b = GetByte(stream); start++;
  48. if (b != 0x07) continue;
  49. b = GetByte(stream); start++;
  50. if (b == 1)
  51. {
  52. b = GetByte(stream); start++;
  53. if (b != 0) continue;
  54. return new MarkHeader(true); // Rar5
  55. }
  56. else if (b == 0)
  57. {
  58. return new MarkHeader(false); // Rar4
  59. }
  60. }
  61. else if (b == 0x45)
  62. {
  63. b = GetByte(stream); start++;
  64. if (b != 0x7e) continue;
  65. b = GetByte(stream); start++;
  66. if (b != 0x5e) continue;
  67. throw new InvalidFormatException("Rar format version pre-4 is unsupported.");
  68. }
  69. }
  70. else
  71. {
  72. b = GetByte(stream); start++;
  73. }
  74. }
  75. }
  76. catch (Exception e)
  77. {
  78. if (!leaveStreamOpen)
  79. {
  80. stream.Dispose();
  81. }
  82. throw new InvalidFormatException("Error trying to read rar signature.", e);
  83. }
  84. throw new InvalidFormatException("Rar signature not found");
  85. }
  86. }
  87. }