ZlibBaseStream.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. // ZlibBaseStream.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: <2011-August-06 21:22:38>
  19. //
  20. // ------------------------------------------------------------------
  21. //
  22. // This module defines the ZlibBaseStream class, which is an intnernal
  23. // base class for DeflateStream, ZlibStream and GZipStream.
  24. //
  25. // ------------------------------------------------------------------
  26. using Best.HTTP.Shared.Extensions;
  27. using Best.HTTP.Shared.PlatformSupport.Memory;
  28. using System;
  29. using System.IO;
  30. namespace Best.HTTP.Shared.Compression.Zlib
  31. {
  32. internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 }
  33. internal class ZlibBaseStream : System.IO.Stream
  34. {
  35. protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec();
  36. protected internal StreamMode _streamMode = StreamMode.Undefined;
  37. protected internal FlushType _flushMode;
  38. protected internal ZlibStreamFlavor _flavor;
  39. protected internal CompressionMode _compressionMode;
  40. protected internal CompressionLevel _level;
  41. protected internal bool _leaveOpen;
  42. protected internal byte[] _workingBuffer;
  43. protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault;
  44. protected internal int windowBitsMax;
  45. protected internal byte[] _buf1 = new byte[1];
  46. protected internal System.IO.Stream _stream;
  47. protected internal CompressionStrategy Strategy = CompressionStrategy.Default;
  48. // workitem 7159
  49. Best.HTTP.Shared.Compression.Crc.CRC32 crc;
  50. protected internal string _GzipFileName;
  51. protected internal string _GzipComment;
  52. protected internal DateTime _GzipMtime;
  53. protected internal int _gzipHeaderByteCount;
  54. internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } }
  55. public ZlibBaseStream(System.IO.Stream stream,
  56. CompressionMode compressionMode,
  57. CompressionLevel level,
  58. ZlibStreamFlavor flavor,
  59. bool leaveOpen)
  60. :this(stream, compressionMode, level, flavor,leaveOpen, ZlibConstants.WindowBitsDefault)
  61. { }
  62. public ZlibBaseStream(System.IO.Stream stream,
  63. CompressionMode compressionMode,
  64. CompressionLevel level,
  65. ZlibStreamFlavor flavor,
  66. bool leaveOpen,
  67. int windowBits)
  68. : base()
  69. {
  70. this._flushMode = FlushType.None;
  71. //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT];
  72. this._stream = stream;
  73. this._leaveOpen = leaveOpen;
  74. this._compressionMode = compressionMode;
  75. this._flavor = flavor;
  76. this._level = level;
  77. this.windowBitsMax = windowBits;
  78. // workitem 7159
  79. if (flavor == ZlibStreamFlavor.GZIP)
  80. {
  81. this.crc = new Best.HTTP.Shared.Compression.Crc.CRC32();
  82. }
  83. }
  84. protected internal bool _wantCompress
  85. {
  86. get
  87. {
  88. return (this._compressionMode == CompressionMode.Compress);
  89. }
  90. }
  91. private ZlibCodec z
  92. {
  93. get
  94. {
  95. if (_z == null)
  96. {
  97. bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB);
  98. _z = new ZlibCodec();
  99. if (this._compressionMode == CompressionMode.Decompress)
  100. {
  101. _z.InitializeInflate(this.windowBitsMax, wantRfc1950Header);
  102. }
  103. else
  104. {
  105. _z.Strategy = Strategy;
  106. _z.InitializeDeflate(this._level, this.windowBitsMax, wantRfc1950Header);
  107. }
  108. }
  109. return _z;
  110. }
  111. }
  112. private byte[] workingBuffer
  113. {
  114. get
  115. {
  116. if (_workingBuffer == null)
  117. _workingBuffer = BufferPool.Get(_bufferSize, true);
  118. return _workingBuffer;
  119. }
  120. }
  121. public override void Write(System.Byte[] buffer, int offset, int count)
  122. {
  123. // workitem 7159
  124. // calculate the CRC on the unccompressed data (before writing)
  125. if (crc != null)
  126. crc.SlurpBlock(buffer, offset, count);
  127. if (_streamMode == StreamMode.Undefined)
  128. _streamMode = StreamMode.Writer;
  129. else if (_streamMode != StreamMode.Writer)
  130. throw new ZlibException("Cannot Write after Reading.");
  131. if (count == 0)
  132. return;
  133. // first reference of z property will initialize the private var _z
  134. z.InputBuffer = buffer;
  135. _z.NextIn = offset;
  136. _z.AvailableBytesIn = count;
  137. bool done = false;
  138. do
  139. {
  140. _z.OutputBuffer = workingBuffer;
  141. _z.NextOut = 0;
  142. _z.AvailableBytesOut = _workingBuffer.Length;
  143. int rc = (_wantCompress)
  144. ? _z.Deflate(_flushMode)
  145. : _z.Inflate(_flushMode);
  146. if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
  147. throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message);
  148. //if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
  149. _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
  150. done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
  151. // If GZIP and de-compress, we're done when 8 bytes remain.
  152. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
  153. done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
  154. }
  155. while (!done);
  156. }
  157. private void finish()
  158. {
  159. if (_z == null) return;
  160. if (_streamMode == StreamMode.Writer)
  161. {
  162. bool done = false;
  163. do
  164. {
  165. _z.OutputBuffer = workingBuffer;
  166. _z.NextOut = 0;
  167. _z.AvailableBytesOut = _workingBuffer.Length;
  168. int rc = (_wantCompress)
  169. ? _z.Deflate(FlushType.Finish)
  170. : _z.Inflate(FlushType.Finish);
  171. if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
  172. {
  173. string verb = (_wantCompress ? "de" : "in") + "flating";
  174. if (_z.Message == null)
  175. throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc));
  176. else
  177. throw new ZlibException(verb + ": " + _z.Message);
  178. }
  179. if (_workingBuffer.Length - _z.AvailableBytesOut > 0)
  180. {
  181. _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut);
  182. }
  183. done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0;
  184. // If GZIP and de-compress, we're done when 8 bytes remain.
  185. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress)
  186. done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0);
  187. }
  188. while (!done);
  189. Flush();
  190. // workitem 7159
  191. if (_flavor == ZlibStreamFlavor.GZIP)
  192. {
  193. if (_wantCompress)
  194. {
  195. // Emit the GZIP trailer: CRC32 and size mod 2^32
  196. int c1 = crc.Crc32Result;
  197. _stream.Write(BitConverter.GetBytes(c1), 0, 4);
  198. int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF);
  199. _stream.Write(BitConverter.GetBytes(c2), 0, 4);
  200. }
  201. else
  202. {
  203. throw new ZlibException("Writing with decompression is not supported.");
  204. }
  205. }
  206. }
  207. // workitem 7159
  208. else if (_streamMode == StreamMode.Reader)
  209. {
  210. if (_flavor == ZlibStreamFlavor.GZIP)
  211. {
  212. if (!_wantCompress)
  213. {
  214. // workitem 8501: handle edge case (decompress empty stream)
  215. if (_z.TotalBytesOut == 0L)
  216. return;
  217. // Read and potentially verify the GZIP trailer:
  218. // CRC32 and size mod 2^32
  219. byte[] trailer = BufferPool.Get(8, true);
  220. using var _ = trailer.AsAutoRelease();
  221. // workitems 8679 & 12554
  222. if (_z.AvailableBytesIn < 8)
  223. {
  224. // Make sure we have read to the end of the stream
  225. Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn);
  226. int bytesNeeded = 8 - _z.AvailableBytesIn;
  227. int bytesRead = _stream.Read(trailer,
  228. _z.AvailableBytesIn,
  229. bytesNeeded);
  230. if (bytesNeeded != bytesRead)
  231. throw new ZlibException(String.Format("Missing or incomplete GZIP trailer. Expected 8 bytes, got {0}.",
  232. _z.AvailableBytesIn + bytesRead));
  233. }
  234. else
  235. {
  236. Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, 8);
  237. }
  238. Int32 crc32_expected = BitConverter.ToInt32(trailer, 0);
  239. Int32 crc32_actual = crc.Crc32Result;
  240. Int32 isize_expected = BitConverter.ToInt32(trailer, 4);
  241. Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF);
  242. if (crc32_actual != crc32_expected)
  243. throw new ZlibException(String.Format("Bad CRC32 in GZIP trailer. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected));
  244. if (isize_actual != isize_expected)
  245. throw new ZlibException(String.Format("Bad size in GZIP trailer. (actual({0})!=expected({1}))", isize_actual, isize_expected));
  246. }
  247. else
  248. {
  249. throw new ZlibException("Reading with compression is not supported.");
  250. }
  251. }
  252. }
  253. }
  254. private void end()
  255. {
  256. if (z == null)
  257. return;
  258. if (_wantCompress)
  259. {
  260. _z.EndDeflate();
  261. }
  262. else
  263. {
  264. _z.EndInflate();
  265. }
  266. _z = null;
  267. BufferPool.Release(_workingBuffer);
  268. _workingBuffer = null;
  269. }
  270. public override void Close()
  271. {
  272. if (_stream == null) return;
  273. try
  274. {
  275. finish();
  276. }
  277. finally
  278. {
  279. end();
  280. if (!_leaveOpen) _stream.Dispose();
  281. _stream = null;
  282. }
  283. }
  284. public override void Flush()
  285. {
  286. _stream.Flush();
  287. }
  288. public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin)
  289. {
  290. throw new NotImplementedException();
  291. //_outStream.Seek(offset, origin);
  292. }
  293. public override void SetLength(System.Int64 value)
  294. {
  295. _stream.SetLength(value);
  296. nomoreinput = false;
  297. }
  298. #if NOT
  299. public int Read()
  300. {
  301. if (Read(_buf1, 0, 1) == 0)
  302. return 0;
  303. // calculate CRC after reading
  304. if (crc!=null)
  305. crc.SlurpBlock(_buf1,0,1);
  306. return (_buf1[0] & 0xFF);
  307. }
  308. #endif
  309. private bool nomoreinput = false;
  310. private string ReadZeroTerminatedString()
  311. {
  312. var list = new System.Collections.Generic.List<byte>();
  313. bool done = false;
  314. do
  315. {
  316. // workitem 7740
  317. int n = _stream.Read(_buf1, 0, 1);
  318. if (n != 1)
  319. throw new ZlibException("Unexpected EOF reading GZIP header.");
  320. else
  321. {
  322. if (_buf1[0] == 0)
  323. done = true;
  324. else
  325. list.Add(_buf1[0]);
  326. }
  327. } while (!done);
  328. byte[] a = list.ToArray();
  329. return GZipStream.iso8859dash1.GetString(a, 0, a.Length);
  330. }
  331. private int _ReadAndValidateGzipHeader()
  332. {
  333. int totalBytesRead = 0;
  334. // read the header on the first read
  335. byte[] header = BufferPool.Get(10, true);
  336. int n = _stream.Read(header, 0, 10);
  337. // workitem 8501: handle edge case (decompress empty stream)
  338. if (n == 0)
  339. {
  340. BufferPool.Release(header);
  341. return 0;
  342. }
  343. if (n != 10)
  344. {
  345. BufferPool.Release(header);
  346. throw new ZlibException("Not a valid GZIP stream.");
  347. }
  348. if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8)
  349. {
  350. BufferPool.Release(header);
  351. throw new ZlibException("Bad GZIP header.");
  352. }
  353. Int32 timet = BitConverter.ToInt32(header, 4);
  354. _GzipMtime = GZipStream._unixEpoch.AddSeconds(timet);
  355. totalBytesRead += n;
  356. if ((header[3] & 0x04) == 0x04)
  357. {
  358. // read and discard extra field
  359. n = _stream.Read(header, 0, 2); // 2-byte length field
  360. totalBytesRead += n;
  361. Int16 extraLength = (Int16)(header[0] + header[1] * 256);
  362. byte[] extra = BufferPool.Get(extraLength, true);
  363. n = _stream.Read(extra, 0, extraLength);
  364. if (n != extraLength)
  365. {
  366. BufferPool.Release(extra);
  367. BufferPool.Release(header);
  368. throw new ZlibException("Unexpected end-of-file reading GZIP header.");
  369. }
  370. totalBytesRead += n;
  371. }
  372. if ((header[3] & 0x08) == 0x08)
  373. _GzipFileName = ReadZeroTerminatedString();
  374. if ((header[3] & 0x10) == 0x010)
  375. _GzipComment = ReadZeroTerminatedString();
  376. if ((header[3] & 0x02) == 0x02)
  377. Read(_buf1, 0, 1); // CRC16, ignore
  378. BufferPool.Release(header);
  379. return totalBytesRead;
  380. }
  381. public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
  382. {
  383. // According to MS documentation, any implementation of the IO.Stream.Read function must:
  384. // (a) throw an exception if offset & count reference an invalid part of the buffer,
  385. // or if count < 0, or if buffer is null
  386. // (b) return 0 only upon EOF, or if count = 0
  387. // (c) if not EOF, then return at least 1 byte, up to <count> bytes
  388. if (_streamMode == StreamMode.Undefined)
  389. {
  390. if (!this._stream.CanRead) throw new ZlibException("The stream is not readable.");
  391. // for the first read, set up some controls.
  392. _streamMode = StreamMode.Reader;
  393. // (The first reference to _z goes through the private accessor which
  394. // may initialize it.)
  395. z.AvailableBytesIn = 0;
  396. if (_flavor == ZlibStreamFlavor.GZIP)
  397. {
  398. _gzipHeaderByteCount = _ReadAndValidateGzipHeader();
  399. // workitem 8501: handle edge case (decompress empty stream)
  400. if (_gzipHeaderByteCount == 0)
  401. return 0;
  402. }
  403. }
  404. if (_streamMode != StreamMode.Reader)
  405. throw new ZlibException("Cannot Read after Writing.");
  406. if (count == 0) return 0;
  407. if (nomoreinput && _wantCompress) return 0; // workitem 8557
  408. if (buffer == null) throw new ArgumentNullException("buffer");
  409. if (count < 0) throw new ArgumentOutOfRangeException("count");
  410. if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset");
  411. if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count");
  412. int rc = 0;
  413. // set up the output of the deflate/inflate codec:
  414. _z.OutputBuffer = buffer;
  415. _z.NextOut = offset;
  416. _z.AvailableBytesOut = count;
  417. // This is necessary in case _workingBuffer has been resized. (new byte[])
  418. // (The first reference to _workingBuffer goes through the private accessor which
  419. // may initialize it.)
  420. _z.InputBuffer = workingBuffer;
  421. do
  422. {
  423. // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any.
  424. if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
  425. {
  426. // No data available, so try to Read data from the captive stream.
  427. _z.NextIn = 0;
  428. _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
  429. if (_z.AvailableBytesIn == 0)
  430. nomoreinput = true;
  431. }
  432. // we have data in InputBuffer; now compress or decompress as appropriate
  433. rc = (_wantCompress)
  434. ? _z.Deflate(_flushMode)
  435. : _z.Inflate(_flushMode);
  436. if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
  437. return 0;
  438. if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
  439. throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message));
  440. if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
  441. break; // nothing more to read
  442. }
  443. //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
  444. while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);
  445. // workitem 8557
  446. // is there more room in output?
  447. if (_z.AvailableBytesOut > 0)
  448. {
  449. if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
  450. {
  451. // deferred
  452. }
  453. // are we completely done reading?
  454. if (nomoreinput)
  455. {
  456. // and in compression?
  457. if (_wantCompress)
  458. {
  459. // no more input data available; therefore we flush to
  460. // try to complete the read
  461. rc = _z.Deflate(FlushType.Finish);
  462. if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
  463. throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message));
  464. }
  465. }
  466. }
  467. rc = (count - _z.AvailableBytesOut);
  468. // calculate CRC after reading
  469. if (crc != null)
  470. crc.SlurpBlock(buffer, offset, rc);
  471. return rc;
  472. }
  473. public override System.Boolean CanRead
  474. {
  475. get { return this._stream.CanRead; }
  476. }
  477. public override System.Boolean CanSeek
  478. {
  479. get { return this._stream.CanSeek; }
  480. }
  481. public override System.Boolean CanWrite
  482. {
  483. get { return this._stream.CanWrite; }
  484. }
  485. public override System.Int64 Length
  486. {
  487. get { return _stream.Length; }
  488. }
  489. public override long Position
  490. {
  491. get { throw new NotImplementedException(); }
  492. set { throw new NotImplementedException(); }
  493. }
  494. internal enum StreamMode
  495. {
  496. Writer,
  497. Reader,
  498. Undefined,
  499. }
  500. }
  501. }