GZipStream.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. // GZipStream.cs
  2. // ------------------------------------------------------------------
  3. //
  4. // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
  5. // All rights reserved.
  6. //
  7. // This code module is part of DotNetZip, a zipfile class library.
  8. //
  9. // ------------------------------------------------------------------
  10. //
  11. // This code is licensed under the Microsoft Public License.
  12. // See the file License.txt for the license details.
  13. // More info on: http://dotnetzip.codeplex.com
  14. //
  15. // ------------------------------------------------------------------
  16. //
  17. // last saved (in emacs):
  18. // Time-stamp: <2010-January-09 12:04:28>
  19. //
  20. // ------------------------------------------------------------------
  21. //
  22. // This module defines the GZipStream class, which can be used as a replacement for
  23. // the System.IO.Compression.GZipStream class in the .NET BCL. NB: The design is not
  24. // completely OO clean: there is some intelligence in the ZlibBaseStream that reads the
  25. // GZip header.
  26. //
  27. // ------------------------------------------------------------------
  28. using System;
  29. using System.IO;
  30. using SharpCompress.Common;
  31. using SharpCompress.Converters;
  32. using System.Text;
  33. namespace SharpCompress.Compressors.Deflate
  34. {
  35. public class GZipStream : Stream
  36. {
  37. internal static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  38. public DateTime? LastModified { get; set; }
  39. private string _comment;
  40. private string _fileName;
  41. internal ZlibBaseStream BaseStream;
  42. private bool _disposed;
  43. private bool _firstReadDone;
  44. private int _headerByteCount;
  45. private readonly Encoding _encoding;
  46. public GZipStream(Stream stream, CompressionMode mode)
  47. : this(stream, mode, CompressionLevel.Default, Encoding.UTF8)
  48. {
  49. }
  50. public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level)
  51. : this(stream, mode, level, Encoding.UTF8)
  52. {
  53. }
  54. public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, Encoding encoding)
  55. {
  56. BaseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, encoding);
  57. _encoding = encoding;
  58. }
  59. #region Zlib properties
  60. public virtual FlushType FlushMode
  61. {
  62. get => (BaseStream._flushMode);
  63. set
  64. {
  65. if (_disposed)
  66. {
  67. throw new ObjectDisposedException("GZipStream");
  68. }
  69. BaseStream._flushMode = value;
  70. }
  71. }
  72. public int BufferSize
  73. {
  74. get => BaseStream._bufferSize;
  75. set
  76. {
  77. if (_disposed)
  78. {
  79. throw new ObjectDisposedException("GZipStream");
  80. }
  81. if (BaseStream._workingBuffer != null)
  82. {
  83. throw new ZlibException("The working buffer is already set.");
  84. }
  85. if (value < ZlibConstants.WorkingBufferSizeMin)
  86. {
  87. throw new ZlibException(
  88. String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value,
  89. ZlibConstants.WorkingBufferSizeMin));
  90. }
  91. BaseStream._bufferSize = value;
  92. }
  93. }
  94. internal virtual long TotalIn => BaseStream._z.TotalBytesIn;
  95. internal virtual long TotalOut => BaseStream._z.TotalBytesOut;
  96. #endregion
  97. #region Stream methods
  98. /// <summary>
  99. /// Indicates whether the stream can be read.
  100. /// </summary>
  101. /// <remarks>
  102. /// The return value depends on whether the captive stream supports reading.
  103. /// </remarks>
  104. public override bool CanRead
  105. {
  106. get
  107. {
  108. if (_disposed)
  109. {
  110. throw new ObjectDisposedException("GZipStream");
  111. }
  112. return BaseStream._stream.CanRead;
  113. }
  114. }
  115. /// <summary>
  116. /// Indicates whether the stream supports Seek operations.
  117. /// </summary>
  118. /// <remarks>
  119. /// Always returns false.
  120. /// </remarks>
  121. public override bool CanSeek => false;
  122. /// <summary>
  123. /// Indicates whether the stream can be written.
  124. /// </summary>
  125. /// <remarks>
  126. /// The return value depends on whether the captive stream supports writing.
  127. /// </remarks>
  128. public override bool CanWrite
  129. {
  130. get
  131. {
  132. if (_disposed)
  133. {
  134. throw new ObjectDisposedException("GZipStream");
  135. }
  136. return BaseStream._stream.CanWrite;
  137. }
  138. }
  139. /// <summary>
  140. /// Reading this property always throws a <see cref="NotImplementedException"/>.
  141. /// </summary>
  142. public override long Length => throw new NotSupportedException();
  143. /// <summary>
  144. /// The position of the stream pointer.
  145. /// </summary>
  146. ///
  147. /// <remarks>
  148. /// Setting this property always throws a <see
  149. /// cref="NotImplementedException"/>. Reading will return the total bytes
  150. /// written out, if used in writing, or the total bytes read in, if used in
  151. /// reading. The count may refer to compressed bytes or uncompressed bytes,
  152. /// depending on how you've used the stream.
  153. /// </remarks>
  154. public override long Position
  155. {
  156. get
  157. {
  158. if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Writer)
  159. {
  160. return BaseStream._z.TotalBytesOut + _headerByteCount;
  161. }
  162. if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
  163. {
  164. return BaseStream._z.TotalBytesIn + BaseStream._gzipHeaderByteCount;
  165. }
  166. return 0;
  167. }
  168. set => throw new NotSupportedException();
  169. }
  170. /// <summary>
  171. /// Dispose the stream.
  172. /// </summary>
  173. /// <remarks>
  174. /// This may or may not result in a <c>Close()</c> call on the captive stream.
  175. /// </remarks>
  176. protected override void Dispose(bool disposing)
  177. {
  178. try
  179. {
  180. if (!_disposed)
  181. {
  182. if (disposing && (BaseStream != null))
  183. {
  184. BaseStream.Dispose();
  185. Crc32 = BaseStream.Crc32;
  186. }
  187. _disposed = true;
  188. }
  189. }
  190. finally
  191. {
  192. base.Dispose(disposing);
  193. }
  194. }
  195. /// <summary>
  196. /// Flush the stream.
  197. /// </summary>
  198. public override void Flush()
  199. {
  200. if (_disposed)
  201. {
  202. throw new ObjectDisposedException("GZipStream");
  203. }
  204. BaseStream.Flush();
  205. }
  206. /// <summary>
  207. /// Read and decompress data from the source stream.
  208. /// </summary>
  209. ///
  210. /// <remarks>
  211. /// With a <c>GZipStream</c>, decompression is done through reading.
  212. /// </remarks>
  213. ///
  214. /// <example>
  215. /// <code>
  216. /// byte[] working = new byte[WORKING_BUFFER_SIZE];
  217. /// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile))
  218. /// {
  219. /// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true))
  220. /// {
  221. /// using (var output = System.IO.File.Create(_DecompressedFile))
  222. /// {
  223. /// int n;
  224. /// while ((n= decompressor.Read(working, 0, working.Length)) !=0)
  225. /// {
  226. /// output.Write(working, 0, n);
  227. /// }
  228. /// }
  229. /// }
  230. /// }
  231. /// </code>
  232. /// </example>
  233. /// <param name="buffer">The buffer into which the decompressed data should be placed.</param>
  234. /// <param name="offset">the offset within that data array to put the first byte read.</param>
  235. /// <param name="count">the number of bytes to read.</param>
  236. /// <returns>the number of bytes actually read</returns>
  237. public override int Read(byte[] buffer, int offset, int count)
  238. {
  239. if (_disposed)
  240. {
  241. throw new ObjectDisposedException("GZipStream");
  242. }
  243. int n = BaseStream.Read(buffer, offset, count);
  244. // Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n);
  245. // Console.WriteLine( Util.FormatByteArray(buffer, offset, n) );
  246. if (!_firstReadDone)
  247. {
  248. _firstReadDone = true;
  249. FileName = BaseStream._GzipFileName;
  250. Comment = BaseStream._GzipComment;
  251. }
  252. return n;
  253. }
  254. /// <summary>
  255. /// Calling this method always throws a <see cref="NotImplementedException"/>.
  256. /// </summary>
  257. /// <param name="offset">irrelevant; it will always throw!</param>
  258. /// <param name="origin">irrelevant; it will always throw!</param>
  259. /// <returns>irrelevant!</returns>
  260. public override long Seek(long offset, SeekOrigin origin)
  261. {
  262. throw new NotSupportedException();
  263. }
  264. /// <summary>
  265. /// Calling this method always throws a <see cref="NotImplementedException"/>.
  266. /// </summary>
  267. /// <param name="value">irrelevant; this method will always throw!</param>
  268. public override void SetLength(long value)
  269. {
  270. throw new NotSupportedException();
  271. }
  272. /// <summary>
  273. /// Write data to the stream.
  274. /// </summary>
  275. ///
  276. /// <remarks>
  277. /// <para>
  278. /// If you wish to use the <c>GZipStream</c> to compress data while writing,
  279. /// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a
  280. /// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>,
  281. /// providing uncompressed data as input. The data sent to the output stream
  282. /// will be the compressed form of the data written.
  283. /// </para>
  284. ///
  285. /// <para>
  286. /// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not
  287. /// both. Writing implies compression. Reading implies decompression.
  288. /// </para>
  289. ///
  290. /// </remarks>
  291. /// <param name="buffer">The buffer holding data to write to the stream.</param>
  292. /// <param name="offset">the offset within that data array to find the first byte to write.</param>
  293. /// <param name="count">the number of bytes to write.</param>
  294. public override void Write(byte[] buffer, int offset, int count)
  295. {
  296. if (_disposed)
  297. {
  298. throw new ObjectDisposedException("GZipStream");
  299. }
  300. if (BaseStream._streamMode == ZlibBaseStream.StreamMode.Undefined)
  301. {
  302. //Console.WriteLine("GZipStream: First write");
  303. if (BaseStream._wantCompress)
  304. {
  305. // first write in compression, therefore, emit the GZIP header
  306. _headerByteCount = EmitHeader();
  307. }
  308. else
  309. {
  310. throw new InvalidOperationException();
  311. }
  312. }
  313. BaseStream.Write(buffer, offset, count);
  314. }
  315. #endregion Stream methods
  316. public String Comment
  317. {
  318. get => _comment;
  319. set
  320. {
  321. if (_disposed)
  322. {
  323. throw new ObjectDisposedException("GZipStream");
  324. }
  325. _comment = value;
  326. }
  327. }
  328. public string FileName
  329. {
  330. get => _fileName;
  331. set
  332. {
  333. if (_disposed)
  334. {
  335. throw new ObjectDisposedException("GZipStream");
  336. }
  337. _fileName = value;
  338. if (_fileName == null)
  339. {
  340. return;
  341. }
  342. if (_fileName.IndexOf("/") != -1)
  343. {
  344. _fileName = _fileName.Replace("/", "\\");
  345. }
  346. if (_fileName.EndsWith("\\"))
  347. {
  348. throw new InvalidOperationException("Illegal filename");
  349. }
  350. var index = _fileName.IndexOf("\\");
  351. if (index != -1)
  352. {
  353. // trim any leading path
  354. int length = _fileName.Length;
  355. int num = length;
  356. while (--num >= 0)
  357. {
  358. char c = _fileName[num];
  359. if (c == '\\')
  360. {
  361. _fileName = _fileName.Substring(num + 1, length - num - 1);
  362. }
  363. }
  364. }
  365. }
  366. }
  367. public int Crc32 { get; private set; }
  368. private int EmitHeader()
  369. {
  370. byte[] commentBytes = (Comment == null) ? null
  371. : _encoding.GetBytes(Comment);
  372. byte[] filenameBytes = (FileName == null) ? null
  373. : _encoding.GetBytes(FileName);
  374. int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1;
  375. int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1;
  376. int bufferLength = 10 + cbLength + fnLength;
  377. var header = new byte[bufferLength];
  378. int i = 0;
  379. // ID
  380. header[i++] = 0x1F;
  381. header[i++] = 0x8B;
  382. // compression method
  383. header[i++] = 8;
  384. byte flag = 0;
  385. if (Comment != null)
  386. {
  387. flag ^= 0x10;
  388. }
  389. if (FileName != null)
  390. {
  391. flag ^= 0x8;
  392. }
  393. // flag
  394. header[i++] = flag;
  395. // mtime
  396. if (!LastModified.HasValue)
  397. {
  398. LastModified = DateTime.Now;
  399. }
  400. TimeSpan delta = LastModified.Value - UNIX_EPOCH;
  401. var timet = (Int32)delta.TotalSeconds;
  402. DataConverter.LittleEndian.PutBytes(header, i, timet);
  403. i += 4;
  404. // xflg
  405. header[i++] = 0; // this field is totally useless
  406. // OS
  407. header[i++] = 0xFF; // 0xFF == unspecified
  408. // extra field length - only if FEXTRA is set, which it is not.
  409. //header[i++]= 0;
  410. //header[i++]= 0;
  411. // filename
  412. if (fnLength != 0)
  413. {
  414. Array.Copy(filenameBytes, 0, header, i, fnLength - 1);
  415. i += fnLength - 1;
  416. header[i++] = 0; // terminate
  417. }
  418. // comment
  419. if (cbLength != 0)
  420. {
  421. Array.Copy(commentBytes, 0, header, i, cbLength - 1);
  422. i += cbLength - 1;
  423. header[i++] = 0; // terminate
  424. }
  425. BaseStream._stream.Write(header, 0, header.Length);
  426. return header.Length; // bytes written
  427. }
  428. }
  429. }