InflaterInputStream.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
  5. {
  6. /// <summary>
  7. /// An input buffer customised for use by <see cref="InflaterInputStream"/>
  8. /// </summary>
  9. /// <remarks>
  10. /// The buffer supports decryption of incoming data.
  11. /// </remarks>
  12. public class InflaterInputBuffer
  13. {
  14. #region Constructors
  15. /// <summary>
  16. /// Initialise a new instance of <see cref="InflaterInputBuffer"/> with a default buffer size
  17. /// </summary>
  18. /// <param name="stream">The stream to buffer.</param>
  19. public InflaterInputBuffer(Stream stream) : this(stream, 4096)
  20. {
  21. }
  22. /// <summary>
  23. /// Initialise a new instance of <see cref="InflaterInputBuffer"/>
  24. /// </summary>
  25. /// <param name="stream">The stream to buffer.</param>
  26. /// <param name="bufferSize">The size to use for the buffer</param>
  27. /// <remarks>A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB.</remarks>
  28. public InflaterInputBuffer(Stream stream, int bufferSize)
  29. {
  30. inputStream = stream;
  31. if (bufferSize < 1024)
  32. {
  33. bufferSize = 1024;
  34. }
  35. rawData = new byte[bufferSize];
  36. clearText = rawData;
  37. }
  38. #endregion Constructors
  39. /// <summary>
  40. /// Get the length of bytes bytes in the <see cref="RawData"/>
  41. /// </summary>
  42. public int RawLength
  43. {
  44. get
  45. {
  46. return rawLength;
  47. }
  48. }
  49. /// <summary>
  50. /// Get the contents of the raw data buffer.
  51. /// </summary>
  52. /// <remarks>This may contain encrypted data.</remarks>
  53. public byte[] RawData
  54. {
  55. get
  56. {
  57. return rawData;
  58. }
  59. }
  60. /// <summary>
  61. /// Get the number of useable bytes in <see cref="ClearText"/>
  62. /// </summary>
  63. public int ClearTextLength
  64. {
  65. get
  66. {
  67. return clearTextLength;
  68. }
  69. }
  70. /// <summary>
  71. /// Get the contents of the clear text buffer.
  72. /// </summary>
  73. public byte[] ClearText
  74. {
  75. get
  76. {
  77. return clearText;
  78. }
  79. }
  80. /// <summary>
  81. /// Get/set the number of bytes available
  82. /// </summary>
  83. public int Available
  84. {
  85. get { return available; }
  86. set { available = value; }
  87. }
  88. /// <summary>
  89. /// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents.
  90. /// </summary>
  91. /// <param name="inflater">The inflater to set input for.</param>
  92. public void SetInflaterInput(Inflater inflater)
  93. {
  94. if (available > 0)
  95. {
  96. inflater.SetInput(clearText, clearTextLength - available, available);
  97. available = 0;
  98. }
  99. }
  100. /// <summary>
  101. /// Fill the buffer from the underlying input stream.
  102. /// </summary>
  103. public void Fill()
  104. {
  105. rawLength = 0;
  106. int toRead = rawData.Length;
  107. while (toRead > 0 && inputStream.CanRead)
  108. {
  109. int count = inputStream.Read(rawData, rawLength, toRead);
  110. if (count <= 0)
  111. {
  112. break;
  113. }
  114. rawLength += count;
  115. toRead -= count;
  116. }
  117. if (cryptoTransform != null)
  118. {
  119. clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0);
  120. }
  121. else
  122. {
  123. clearTextLength = rawLength;
  124. }
  125. available = clearTextLength;
  126. }
  127. /// <summary>
  128. /// Read a buffer directly from the input stream
  129. /// </summary>
  130. /// <param name="buffer">The buffer to fill</param>
  131. /// <returns>Returns the number of bytes read.</returns>
  132. public int ReadRawBuffer(byte[] buffer)
  133. {
  134. return ReadRawBuffer(buffer, 0, buffer.Length);
  135. }
  136. /// <summary>
  137. /// Read a buffer directly from the input stream
  138. /// </summary>
  139. /// <param name="outBuffer">The buffer to read into</param>
  140. /// <param name="offset">The offset to start reading data into.</param>
  141. /// <param name="length">The number of bytes to read.</param>
  142. /// <returns>Returns the number of bytes read.</returns>
  143. public int ReadRawBuffer(byte[] outBuffer, int offset, int length)
  144. {
  145. if (length < 0)
  146. {
  147. throw new ArgumentOutOfRangeException(nameof(length));
  148. }
  149. int currentOffset = offset;
  150. int currentLength = length;
  151. while (currentLength > 0)
  152. {
  153. if (available <= 0)
  154. {
  155. Fill();
  156. if (available <= 0)
  157. {
  158. return 0;
  159. }
  160. }
  161. int toCopy = Math.Min(currentLength, available);
  162. System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy);
  163. currentOffset += toCopy;
  164. currentLength -= toCopy;
  165. available -= toCopy;
  166. }
  167. return length;
  168. }
  169. /// <summary>
  170. /// Read clear text data from the input stream.
  171. /// </summary>
  172. /// <param name="outBuffer">The buffer to add data to.</param>
  173. /// <param name="offset">The offset to start adding data at.</param>
  174. /// <param name="length">The number of bytes to read.</param>
  175. /// <returns>Returns the number of bytes actually read.</returns>
  176. public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length)
  177. {
  178. if (length < 0)
  179. {
  180. throw new ArgumentOutOfRangeException(nameof(length));
  181. }
  182. int currentOffset = offset;
  183. int currentLength = length;
  184. while (currentLength > 0)
  185. {
  186. if (available <= 0)
  187. {
  188. Fill();
  189. if (available <= 0)
  190. {
  191. return 0;
  192. }
  193. }
  194. int toCopy = Math.Min(currentLength, available);
  195. Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy);
  196. currentOffset += toCopy;
  197. currentLength -= toCopy;
  198. available -= toCopy;
  199. }
  200. return length;
  201. }
  202. /// <summary>
  203. /// Read a <see cref="byte"/> from the input stream.
  204. /// </summary>
  205. /// <returns>Returns the byte read.</returns>
  206. public int ReadLeByte()
  207. {
  208. if (available <= 0)
  209. {
  210. Fill();
  211. if (available <= 0)
  212. {
  213. throw new ZipException("EOF in header");
  214. }
  215. }
  216. byte result = rawData[rawLength - available];
  217. available -= 1;
  218. return result;
  219. }
  220. /// <summary>
  221. /// Read an <see cref="short"/> in little endian byte order.
  222. /// </summary>
  223. /// <returns>The short value read case to an int.</returns>
  224. public int ReadLeShort()
  225. {
  226. return ReadLeByte() | (ReadLeByte() << 8);
  227. }
  228. /// <summary>
  229. /// Read an <see cref="int"/> in little endian byte order.
  230. /// </summary>
  231. /// <returns>The int value read.</returns>
  232. public int ReadLeInt()
  233. {
  234. return ReadLeShort() | (ReadLeShort() << 16);
  235. }
  236. /// <summary>
  237. /// Read a <see cref="long"/> in little endian byte order.
  238. /// </summary>
  239. /// <returns>The long value read.</returns>
  240. public long ReadLeLong()
  241. {
  242. return (uint)ReadLeInt() | ((long)ReadLeInt() << 32);
  243. }
  244. /// <summary>
  245. /// Get/set the <see cref="ICryptoTransform"/> to apply to any data.
  246. /// </summary>
  247. /// <remarks>Set this value to null to have no transform applied.</remarks>
  248. public ICryptoTransform CryptoTransform
  249. {
  250. set
  251. {
  252. cryptoTransform = value;
  253. if (cryptoTransform != null)
  254. {
  255. if (rawData == clearText)
  256. {
  257. if (internalClearText == null)
  258. {
  259. internalClearText = new byte[rawData.Length];
  260. }
  261. clearText = internalClearText;
  262. }
  263. clearTextLength = rawLength;
  264. if (available > 0)
  265. {
  266. cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available);
  267. }
  268. }
  269. else
  270. {
  271. clearText = rawData;
  272. clearTextLength = rawLength;
  273. }
  274. }
  275. }
  276. #region Instance Fields
  277. private int rawLength;
  278. private byte[] rawData;
  279. private int clearTextLength;
  280. private byte[] clearText;
  281. private byte[] internalClearText;
  282. private int available;
  283. private ICryptoTransform cryptoTransform;
  284. private Stream inputStream;
  285. #endregion Instance Fields
  286. }
  287. /// <summary>
  288. /// This filter stream is used to decompress data compressed using the "deflate"
  289. /// format. The "deflate" format is described in RFC 1951.
  290. ///
  291. /// This stream may form the basis for other decompression filters, such
  292. /// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>.
  293. ///
  294. /// Author of the original java version : John Leuner.
  295. /// </summary>
  296. public class InflaterInputStream : Stream
  297. {
  298. #region Constructors
  299. /// <summary>
  300. /// Create an InflaterInputStream with the default decompressor
  301. /// and a default buffer size of 4KB.
  302. /// </summary>
  303. /// <param name = "baseInputStream">
  304. /// The InputStream to read bytes from
  305. /// </param>
  306. public InflaterInputStream(Stream baseInputStream)
  307. : this(baseInputStream, new Inflater(), 4096)
  308. {
  309. }
  310. /// <summary>
  311. /// Create an InflaterInputStream with the specified decompressor
  312. /// and a default buffer size of 4KB.
  313. /// </summary>
  314. /// <param name = "baseInputStream">
  315. /// The source of input data
  316. /// </param>
  317. /// <param name = "inf">
  318. /// The decompressor used to decompress data read from baseInputStream
  319. /// </param>
  320. public InflaterInputStream(Stream baseInputStream, Inflater inf)
  321. : this(baseInputStream, inf, 4096)
  322. {
  323. }
  324. /// <summary>
  325. /// Create an InflaterInputStream with the specified decompressor
  326. /// and the specified buffer size.
  327. /// </summary>
  328. /// <param name = "baseInputStream">
  329. /// The InputStream to read bytes from
  330. /// </param>
  331. /// <param name = "inflater">
  332. /// The decompressor to use
  333. /// </param>
  334. /// <param name = "bufferSize">
  335. /// Size of the buffer to use
  336. /// </param>
  337. public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize)
  338. {
  339. if (baseInputStream == null)
  340. {
  341. throw new ArgumentNullException(nameof(baseInputStream));
  342. }
  343. if (inflater == null)
  344. {
  345. throw new ArgumentNullException(nameof(inflater));
  346. }
  347. if (bufferSize <= 0)
  348. {
  349. throw new ArgumentOutOfRangeException(nameof(bufferSize));
  350. }
  351. this.baseInputStream = baseInputStream;
  352. this.inf = inflater;
  353. inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize);
  354. }
  355. #endregion Constructors
  356. /// <summary>
  357. /// Gets or sets a flag indicating ownership of underlying stream.
  358. /// When the flag is true <see cref="Stream.Dispose()" /> will close the underlying stream also.
  359. /// </summary>
  360. /// <remarks>The default value is true.</remarks>
  361. public bool IsStreamOwner { get; set; } = true;
  362. /// <summary>
  363. /// Skip specified number of bytes of uncompressed data
  364. /// </summary>
  365. /// <param name ="count">
  366. /// Number of bytes to skip
  367. /// </param>
  368. /// <returns>
  369. /// The number of bytes skipped, zero if the end of
  370. /// stream has been reached
  371. /// </returns>
  372. /// <exception cref="ArgumentOutOfRangeException">
  373. /// <paramref name="count">The number of bytes</paramref> to skip is less than or equal to zero.
  374. /// </exception>
  375. public long Skip(long count)
  376. {
  377. if (count <= 0)
  378. {
  379. throw new ArgumentOutOfRangeException(nameof(count));
  380. }
  381. // v0.80 Skip by seeking if underlying stream supports it...
  382. if (baseInputStream.CanSeek)
  383. {
  384. baseInputStream.Seek(count, SeekOrigin.Current);
  385. return count;
  386. }
  387. else
  388. {
  389. int length = 2048;
  390. if (count < length)
  391. {
  392. length = (int)count;
  393. }
  394. byte[] tmp = new byte[length];
  395. int readCount = 1;
  396. long toSkip = count;
  397. while ((toSkip > 0) && (readCount > 0))
  398. {
  399. if (toSkip < length)
  400. {
  401. length = (int)toSkip;
  402. }
  403. readCount = baseInputStream.Read(tmp, 0, length);
  404. toSkip -= readCount;
  405. }
  406. return count - toSkip;
  407. }
  408. }
  409. /// <summary>
  410. /// Clear any cryptographic state.
  411. /// </summary>
  412. protected void StopDecrypting()
  413. {
  414. inputBuffer.CryptoTransform = null;
  415. }
  416. /// <summary>
  417. /// Returns 0 once the end of the stream (EOF) has been reached.
  418. /// Otherwise returns 1.
  419. /// </summary>
  420. public virtual int Available
  421. {
  422. get
  423. {
  424. return inf.IsFinished ? 0 : 1;
  425. }
  426. }
  427. /// <summary>
  428. /// Fills the buffer with more data to decompress.
  429. /// </summary>
  430. /// <exception cref="SharpZipBaseException">
  431. /// Stream ends early
  432. /// </exception>
  433. protected void Fill()
  434. {
  435. // Protect against redundant calls
  436. if (inputBuffer.Available <= 0)
  437. {
  438. inputBuffer.Fill();
  439. if (inputBuffer.Available <= 0)
  440. {
  441. throw new SharpZipBaseException("Unexpected EOF");
  442. }
  443. }
  444. inputBuffer.SetInflaterInput(inf);
  445. }
  446. #region Stream Overrides
  447. /// <summary>
  448. /// Gets a value indicating whether the current stream supports reading
  449. /// </summary>
  450. public override bool CanRead
  451. {
  452. get
  453. {
  454. return baseInputStream.CanRead;
  455. }
  456. }
  457. /// <summary>
  458. /// Gets a value of false indicating seeking is not supported for this stream.
  459. /// </summary>
  460. public override bool CanSeek
  461. {
  462. get
  463. {
  464. return false;
  465. }
  466. }
  467. /// <summary>
  468. /// Gets a value of false indicating that this stream is not writeable.
  469. /// </summary>
  470. public override bool CanWrite
  471. {
  472. get
  473. {
  474. return false;
  475. }
  476. }
  477. /// <summary>
  478. /// A value representing the length of the stream in bytes.
  479. /// </summary>
  480. public override long Length
  481. {
  482. get
  483. {
  484. //return inputBuffer.RawLength;
  485. throw new NotSupportedException("InflaterInputStream Length is not supported");
  486. }
  487. }
  488. /// <summary>
  489. /// The current position within the stream.
  490. /// Throws a NotSupportedException when attempting to set the position
  491. /// </summary>
  492. /// <exception cref="NotSupportedException">Attempting to set the position</exception>
  493. public override long Position
  494. {
  495. get
  496. {
  497. return baseInputStream.Position;
  498. }
  499. set
  500. {
  501. throw new NotSupportedException("InflaterInputStream Position not supported");
  502. }
  503. }
  504. /// <summary>
  505. /// Flushes the baseInputStream
  506. /// </summary>
  507. public override void Flush()
  508. {
  509. baseInputStream.Flush();
  510. }
  511. /// <summary>
  512. /// Sets the position within the current stream
  513. /// Always throws a NotSupportedException
  514. /// </summary>
  515. /// <param name="offset">The relative offset to seek to.</param>
  516. /// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param>
  517. /// <returns>The new position in the stream.</returns>
  518. /// <exception cref="NotSupportedException">Any access</exception>
  519. public override long Seek(long offset, SeekOrigin origin)
  520. {
  521. throw new NotSupportedException("Seek not supported");
  522. }
  523. /// <summary>
  524. /// Set the length of the current stream
  525. /// Always throws a NotSupportedException
  526. /// </summary>
  527. /// <param name="value">The new length value for the stream.</param>
  528. /// <exception cref="NotSupportedException">Any access</exception>
  529. public override void SetLength(long value)
  530. {
  531. throw new NotSupportedException("InflaterInputStream SetLength not supported");
  532. }
  533. /// <summary>
  534. /// Writes a sequence of bytes to stream and advances the current position
  535. /// This method always throws a NotSupportedException
  536. /// </summary>
  537. /// <param name="buffer">Thew buffer containing data to write.</param>
  538. /// <param name="offset">The offset of the first byte to write.</param>
  539. /// <param name="count">The number of bytes to write.</param>
  540. /// <exception cref="NotSupportedException">Any access</exception>
  541. public override void Write(byte[] buffer, int offset, int count)
  542. {
  543. throw new NotSupportedException("InflaterInputStream Write not supported");
  544. }
  545. /// <summary>
  546. /// Writes one byte to the current stream and advances the current position
  547. /// Always throws a NotSupportedException
  548. /// </summary>
  549. /// <param name="value">The byte to write.</param>
  550. /// <exception cref="NotSupportedException">Any access</exception>
  551. public override void WriteByte(byte value)
  552. {
  553. throw new NotSupportedException("InflaterInputStream WriteByte not supported");
  554. }
  555. /// <summary>
  556. /// Closes the input stream. When <see cref="IsStreamOwner"></see>
  557. /// is true the underlying stream is also closed.
  558. /// </summary>
  559. protected override void Dispose(bool disposing)
  560. {
  561. if (!isClosed)
  562. {
  563. isClosed = true;
  564. if (IsStreamOwner)
  565. {
  566. baseInputStream.Dispose();
  567. }
  568. }
  569. }
  570. /// <summary>
  571. /// Reads decompressed data into the provided buffer byte array
  572. /// </summary>
  573. /// <param name ="buffer">
  574. /// The array to read and decompress data into
  575. /// </param>
  576. /// <param name ="offset">
  577. /// The offset indicating where the data should be placed
  578. /// </param>
  579. /// <param name ="count">
  580. /// The number of bytes to decompress
  581. /// </param>
  582. /// <returns>The number of bytes read. Zero signals the end of stream</returns>
  583. /// <exception cref="SharpZipBaseException">
  584. /// Inflater needs a dictionary
  585. /// </exception>
  586. public override int Read(byte[] buffer, int offset, int count)
  587. {
  588. if (inf.IsNeedingDictionary)
  589. {
  590. throw new SharpZipBaseException("Need a dictionary");
  591. }
  592. int remainingBytes = count;
  593. while (true)
  594. {
  595. int bytesRead = inf.Inflate(buffer, offset, remainingBytes);
  596. offset += bytesRead;
  597. remainingBytes -= bytesRead;
  598. if (remainingBytes == 0 || inf.IsFinished)
  599. {
  600. break;
  601. }
  602. if (inf.IsNeedingInput)
  603. {
  604. Fill();
  605. }
  606. else if (bytesRead == 0)
  607. {
  608. throw new ZipException("Invalid input data");
  609. }
  610. }
  611. return count - remainingBytes;
  612. }
  613. #endregion Stream Overrides
  614. #region Instance Fields
  615. /// <summary>
  616. /// Decompressor for this stream
  617. /// </summary>
  618. protected Inflater inf;
  619. /// <summary>
  620. /// <see cref="InflaterInputBuffer">Input buffer</see> for this stream.
  621. /// </summary>
  622. protected InflaterInputBuffer inputBuffer;
  623. /// <summary>
  624. /// Base stream the inflater reads from.
  625. /// </summary>
  626. private Stream baseInputStream;
  627. /// <summary>
  628. /// The compressed size
  629. /// </summary>
  630. protected long csize;
  631. /// <summary>
  632. /// Flag indicating wether this instance has been closed or not.
  633. /// </summary>
  634. private bool isClosed;
  635. #endregion Instance Fields
  636. }
  637. }