ZlibBaseStream.cs 22 KB

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