ZlibBaseStream.cs 22 KB

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