LZipStream.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. using System;
  2. using System.IO;
  3. using SharpCompress.Converters;
  4. using SharpCompress.Crypto;
  5. using SharpCompress.IO;
  6. namespace SharpCompress.Compressors.LZMA
  7. {
  8. // TODO:
  9. // - Write as well as read
  10. // - Multi-volume support
  11. // - Use of the data size / member size values at the end of the stream
  12. /// <summary>
  13. /// Stream supporting the LZIP format, as documented at http://www.nongnu.org/lzip/manual/lzip_manual.html
  14. /// </summary>
  15. public class LZipStream : Stream
  16. {
  17. private readonly Stream _stream;
  18. private readonly CountingWritableSubStream _countingWritableSubStream;
  19. private bool _disposed;
  20. private bool _finished;
  21. private long _writeCount;
  22. public LZipStream(Stream stream, CompressionMode mode)
  23. {
  24. Mode = mode;
  25. if (mode == CompressionMode.Decompress)
  26. {
  27. int dSize = ValidateAndReadSize(stream);
  28. if (dSize == 0)
  29. {
  30. throw new IOException("Not an LZip stream");
  31. }
  32. byte[] properties = GetProperties(dSize);
  33. _stream = new LzmaStream(properties, stream);
  34. }
  35. else
  36. {
  37. //default
  38. int dSize = 104 * 1024;
  39. WriteHeaderSize(stream);
  40. _countingWritableSubStream = new CountingWritableSubStream(stream);
  41. _stream = new Crc32Stream(new LzmaStream(new LzmaEncoderProperties(true, dSize), false, _countingWritableSubStream));
  42. }
  43. }
  44. public void Finish()
  45. {
  46. if (!_finished)
  47. {
  48. if (Mode == CompressionMode.Compress)
  49. {
  50. var crc32Stream = (Crc32Stream)_stream;
  51. crc32Stream.WrappedStream.Dispose();
  52. crc32Stream.Dispose();
  53. var compressedCount = _countingWritableSubStream.Count;
  54. var bytes = DataConverter.LittleEndian.GetBytes(crc32Stream.Crc);
  55. _countingWritableSubStream.Write(bytes, 0, bytes.Length);
  56. bytes = DataConverter.LittleEndian.GetBytes(_writeCount);
  57. _countingWritableSubStream.Write(bytes, 0, bytes.Length);
  58. //total with headers
  59. bytes = DataConverter.LittleEndian.GetBytes(compressedCount + 6 + 20);
  60. _countingWritableSubStream.Write(bytes, 0, bytes.Length);
  61. }
  62. _finished = true;
  63. }
  64. }
  65. #region Stream methods
  66. protected override void Dispose(bool disposing)
  67. {
  68. if (_disposed)
  69. {
  70. return;
  71. }
  72. _disposed = true;
  73. if (disposing)
  74. {
  75. Finish();
  76. _stream.Dispose();
  77. }
  78. }
  79. public CompressionMode Mode { get; }
  80. public override bool CanRead => Mode == CompressionMode.Decompress;
  81. public override bool CanSeek => false;
  82. public override bool CanWrite => Mode == CompressionMode.Compress;
  83. public override void Flush()
  84. {
  85. _stream.Flush();
  86. }
  87. // TODO: Both Length and Position are sometimes feasible, but would require
  88. // reading the output length when we initialize.
  89. public override long Length => throw new NotImplementedException();
  90. public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
  91. public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count);
  92. public override int ReadByte() => _stream.ReadByte();
  93. public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
  94. public override void SetLength(long value) => throw new NotImplementedException();
  95. public override void Write(byte[] buffer, int offset, int count)
  96. {
  97. _stream.Write(buffer, offset, count);
  98. _writeCount += count;
  99. }
  100. public override void WriteByte(byte value)
  101. {
  102. _stream.WriteByte(value);
  103. ++_writeCount;
  104. }
  105. #endregion
  106. /// <summary>
  107. /// Determines if the given stream is positioned at the start of a v1 LZip
  108. /// file, as indicated by the ASCII characters "LZIP" and a version byte
  109. /// of 1, followed by at least one byte.
  110. /// </summary>
  111. /// <param name="stream">The stream to read from. Must not be null.</param>
  112. /// <returns><c>true</c> if the given stream is an LZip file, <c>false</c> otherwise.</returns>
  113. public static bool IsLZipFile(Stream stream) => ValidateAndReadSize(stream) != 0;
  114. /// <summary>
  115. /// Reads the 6-byte header of the stream, and returns 0 if either the header
  116. /// couldn't be read or it isn't a validate LZIP header, or the dictionary
  117. /// size if it *is* a valid LZIP file.
  118. /// </summary>
  119. public static int ValidateAndReadSize(Stream stream)
  120. {
  121. if (stream == null)
  122. {
  123. throw new ArgumentNullException(nameof(stream));
  124. }
  125. // Read the header
  126. byte[] header = new byte[6];
  127. int n = stream.Read(header, 0, header.Length);
  128. // TODO: Handle reading only part of the header?
  129. if (n != 6)
  130. {
  131. return 0;
  132. }
  133. if (header[0] != 'L' || header[1] != 'Z' || header[2] != 'I' || header[3] != 'P' || header[4] != 1 /* version 1 */)
  134. {
  135. return 0;
  136. }
  137. int basePower = header[5] & 0x1F;
  138. int subtractionNumerator = (header[5] & 0xE0) >> 5;
  139. return (1 << basePower) - subtractionNumerator * (1 << (basePower - 4));
  140. }
  141. public static void WriteHeaderSize(Stream stream)
  142. {
  143. if (stream == null)
  144. {
  145. throw new ArgumentNullException(nameof(stream));
  146. }
  147. // hard coding the dictionary size encoding
  148. byte[] header = new byte[6] {(byte)'L', (byte)'Z', (byte)'I', (byte)'P', 1, 113};
  149. stream.Write(header, 0, 6);
  150. }
  151. /// <summary>
  152. /// Creates a byte array to communicate the parameters and dictionary size to LzmaStream.
  153. /// </summary>
  154. private static byte[] GetProperties(int dictionarySize) =>
  155. new byte[]
  156. {
  157. // Parameters as per http://www.nongnu.org/lzip/manual/lzip_manual.html#Stream-format
  158. // but encoded as a single byte in the format LzmaStream expects.
  159. // literal_context_bits = 3
  160. // literal_pos_state_bits = 0
  161. // pos_state_bits = 2
  162. 93,
  163. // Dictionary size as 4-byte little-endian value
  164. (byte)(dictionarySize & 0xff),
  165. (byte)((dictionarySize >> 8) & 0xff),
  166. (byte)((dictionarySize >> 16) & 0xff),
  167. (byte)((dictionarySize >> 24) & 0xff)
  168. };
  169. }
  170. }