GzipInputStream.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using System.Net.ApiService.Compression.Checksum;
  2. using System.Net.ApiService.Compression.Zip.Compression;
  3. using System.Net.ApiService.Compression.Zip.Compression.Streams;
  4. using System;
  5. using System.IO;
  6. namespace System.Net.ApiService.Compression.GZip {
  7. /// <summary>
  8. /// This filter stream is used to decompress a "GZIP" format stream.
  9. /// The "GZIP" format is described baseInputStream RFC 1952.
  10. ///
  11. /// author of the original java version : John Leuner
  12. /// </summary>
  13. /// <example> This sample shows how to unzip a gzipped file
  14. /// <code>
  15. /// using System;
  16. /// using System.IO;
  17. ///
  18. /// using ICSharpCode.SharpZipLib.Core;
  19. /// using ICSharpCode.SharpZipLib.GZip;
  20. ///
  21. /// class MainClass
  22. /// {
  23. /// public static void Main(string[] args)
  24. /// {
  25. /// using (Stream inStream = new GZipInputStream(File.OpenRead(args[0])))
  26. /// using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) {
  27. /// byte[] buffer = new byte[4096];
  28. /// StreamUtils.Copy(inStream, outStream, buffer);
  29. /// }
  30. /// }
  31. /// }
  32. /// </code>
  33. /// </example>
  34. public class GZipInputStream : InflaterInputStream
  35. {
  36. #region Instance Fields
  37. /// <summary>
  38. /// CRC-32 value for uncompressed data
  39. /// </summary>
  40. protected Crc32 crc;
  41. /// <summary>
  42. /// Flag to indicate if we've read the GZIP header yet for the current member (block of compressed data).
  43. /// This is tracked per-block as the file is parsed.
  44. /// </summary>
  45. private bool readGZIPHeader;
  46. /// <summary>
  47. /// Flag to indicate if at least one block in a stream with concatenated blocks was read successfully.
  48. /// This allows us to exit gracefully if downstream data is not in gzip format.
  49. /// </summary>
  50. private bool completedLastBlock;
  51. #endregion Instance Fields
  52. #region Constructors
  53. /// <summary>
  54. /// Creates a GZipInputStream with the default buffer size
  55. /// </summary>
  56. /// <param name="baseInputStream">
  57. /// The stream to read compressed data from (baseInputStream GZIP format)
  58. /// </param>
  59. public GZipInputStream(Stream baseInputStream)
  60. : this(baseInputStream, 4096)
  61. {
  62. }
  63. /// <summary>
  64. /// Creates a GZIPInputStream with the specified buffer size
  65. /// </summary>
  66. /// <param name="baseInputStream">
  67. /// The stream to read compressed data from (baseInputStream GZIP format)
  68. /// </param>
  69. /// <param name="size">
  70. /// Size of the buffer to use
  71. /// </param>
  72. public GZipInputStream(Stream baseInputStream, int size)
  73. : base(baseInputStream, new Inflater(true), size)
  74. {
  75. }
  76. #endregion Constructors
  77. #region Stream overrides
  78. /// <summary>
  79. /// Reads uncompressed data into an array of bytes
  80. /// </summary>
  81. /// <param name="buffer">
  82. /// The buffer to read uncompressed data into
  83. /// </param>
  84. /// <param name="offset">
  85. /// The offset indicating where the data should be placed
  86. /// </param>
  87. /// <param name="count">
  88. /// The number of uncompressed bytes to be read
  89. /// </param>
  90. /// <returns>Returns the number of bytes actually read.</returns>
  91. public override int Read(byte[] buffer, int offset, int count)
  92. {
  93. // A GZIP file can contain multiple blocks of compressed data, although this is quite rare.
  94. // A compressed block could potentially be empty, so we need to loop until we reach EOF or
  95. // we find data.
  96. while (true)
  97. {
  98. // If we haven't read the header for this block, read it
  99. if (!readGZIPHeader)
  100. {
  101. // Try to read header. If there is no header (0 bytes available), this is EOF. If there is
  102. // an incomplete header, this will throw an exception.
  103. try
  104. {
  105. if (!ReadHeader())
  106. {
  107. return 0;
  108. }
  109. }
  110. catch (Exception ex) when (completedLastBlock && (ex is GZipException || ex is EndOfStreamException))
  111. {
  112. // if we completed the last block (i.e. we're in a stream that has multiple blocks concatenated
  113. // we want to return gracefully from any header parsing exceptions since sometimes there may
  114. // be trailing garbage on a stream
  115. return 0;
  116. }
  117. }
  118. // Try to read compressed data
  119. int bytesRead = base.Read(buffer, offset, count);
  120. if (bytesRead > 0)
  121. {
  122. crc.Update(new ArraySegment<byte>(buffer, offset, bytesRead));
  123. }
  124. // If this is the end of stream, read the footer
  125. if (inf.IsFinished)
  126. {
  127. ReadFooter();
  128. }
  129. // Attempting to read 0 bytes will never yield any bytesRead, so we return instead of looping forever
  130. if (bytesRead > 0 || count == 0)
  131. {
  132. return bytesRead;
  133. }
  134. }
  135. }
  136. #endregion Stream overrides
  137. #region Support routines
  138. private bool ReadHeader()
  139. {
  140. // Initialize CRC for this block
  141. crc = new Crc32();
  142. // Make sure there is data in file. We can't rely on ReadLeByte() to fill the buffer, as this could be EOF,
  143. // which is fine, but ReadLeByte() throws an exception if it doesn't find data, so we do this part ourselves.
  144. if (inputBuffer.Available <= 0)
  145. {
  146. inputBuffer.Fill();
  147. if (inputBuffer.Available <= 0)
  148. {
  149. // No header, EOF.
  150. return false;
  151. }
  152. }
  153. // 1. Check the two magic bytes
  154. var headCRC = new Crc32();
  155. int magic = inputBuffer.ReadLeByte();
  156. if (magic < 0)
  157. {
  158. throw new EndOfStreamException("EOS reading GZIP header");
  159. }
  160. headCRC.Update(magic);
  161. if (magic != (GZipConstants.GZIP_MAGIC >> 8))
  162. {
  163. throw new GZipException("Error GZIP header, first magic byte doesn't match");
  164. }
  165. //magic = baseInputStream.ReadByte();
  166. magic = inputBuffer.ReadLeByte();
  167. if (magic < 0)
  168. {
  169. throw new EndOfStreamException("EOS reading GZIP header");
  170. }
  171. if (magic != (GZipConstants.GZIP_MAGIC & 0xFF))
  172. {
  173. throw new GZipException("Error GZIP header, second magic byte doesn't match");
  174. }
  175. headCRC.Update(magic);
  176. // 2. Check the compression type (must be 8)
  177. int compressionType = inputBuffer.ReadLeByte();
  178. if (compressionType < 0)
  179. {
  180. throw new EndOfStreamException("EOS reading GZIP header");
  181. }
  182. if (compressionType != 8)
  183. {
  184. throw new GZipException("Error GZIP header, data not in deflate format");
  185. }
  186. headCRC.Update(compressionType);
  187. // 3. Check the flags
  188. int flags = inputBuffer.ReadLeByte();
  189. if (flags < 0)
  190. {
  191. throw new EndOfStreamException("EOS reading GZIP header");
  192. }
  193. headCRC.Update(flags);
  194. /* This flag byte is divided into individual bits as follows:
  195. bit 0 FTEXT
  196. bit 1 FHCRC
  197. bit 2 FEXTRA
  198. bit 3 FNAME
  199. bit 4 FCOMMENT
  200. bit 5 reserved
  201. bit 6 reserved
  202. bit 7 reserved
  203. */
  204. // 3.1 Check the reserved bits are zero
  205. if ((flags & 0xE0) != 0)
  206. {
  207. throw new GZipException("Reserved flag bits in GZIP header != 0");
  208. }
  209. // 4.-6. Skip the modification time, extra flags, and OS type
  210. for (int i = 0; i < 6; i++)
  211. {
  212. int readByte = inputBuffer.ReadLeByte();
  213. if (readByte < 0)
  214. {
  215. throw new EndOfStreamException("EOS reading GZIP header");
  216. }
  217. headCRC.Update(readByte);
  218. }
  219. // 7. Read extra field
  220. if ((flags & GZipConstants.FEXTRA) != 0)
  221. {
  222. // XLEN is total length of extra subfields, we will skip them all
  223. int len1, len2;
  224. len1 = inputBuffer.ReadLeByte();
  225. len2 = inputBuffer.ReadLeByte();
  226. if ((len1 < 0) || (len2 < 0))
  227. {
  228. throw new EndOfStreamException("EOS reading GZIP header");
  229. }
  230. headCRC.Update(len1);
  231. headCRC.Update(len2);
  232. int extraLen = (len2 << 8) | len1; // gzip is LSB first
  233. for (int i = 0; i < extraLen; i++)
  234. {
  235. int readByte = inputBuffer.ReadLeByte();
  236. if (readByte < 0)
  237. {
  238. throw new EndOfStreamException("EOS reading GZIP header");
  239. }
  240. headCRC.Update(readByte);
  241. }
  242. }
  243. // 8. Read file name
  244. if ((flags & GZipConstants.FNAME) != 0)
  245. {
  246. int readByte;
  247. while ((readByte = inputBuffer.ReadLeByte()) > 0)
  248. {
  249. headCRC.Update(readByte);
  250. }
  251. if (readByte < 0)
  252. {
  253. throw new EndOfStreamException("EOS reading GZIP header");
  254. }
  255. headCRC.Update(readByte);
  256. }
  257. // 9. Read comment
  258. if ((flags & GZipConstants.FCOMMENT) != 0)
  259. {
  260. int readByte;
  261. while ((readByte = inputBuffer.ReadLeByte()) > 0)
  262. {
  263. headCRC.Update(readByte);
  264. }
  265. if (readByte < 0)
  266. {
  267. throw new EndOfStreamException("EOS reading GZIP header");
  268. }
  269. headCRC.Update(readByte);
  270. }
  271. // 10. Read header CRC
  272. if ((flags & GZipConstants.FHCRC) != 0)
  273. {
  274. int tempByte;
  275. int crcval = inputBuffer.ReadLeByte();
  276. if (crcval < 0)
  277. {
  278. throw new EndOfStreamException("EOS reading GZIP header");
  279. }
  280. tempByte = inputBuffer.ReadLeByte();
  281. if (tempByte < 0)
  282. {
  283. throw new EndOfStreamException("EOS reading GZIP header");
  284. }
  285. crcval = (crcval << 8) | tempByte;
  286. if (crcval != ((int)headCRC.Value & 0xffff))
  287. {
  288. throw new GZipException("Header CRC value mismatch");
  289. }
  290. }
  291. readGZIPHeader = true;
  292. return true;
  293. }
  294. private void ReadFooter()
  295. {
  296. byte[] footer = new byte[8];
  297. // End of stream; reclaim all bytes from inf, read the final byte count, and reset the inflator
  298. long bytesRead = inf.TotalOut & 0xffffffff;
  299. inputBuffer.Available += inf.RemainingInput;
  300. inf.Reset();
  301. // Read footer from inputBuffer
  302. int needed = 8;
  303. while (needed > 0)
  304. {
  305. int count = inputBuffer.ReadClearTextBuffer(footer, 8 - needed, needed);
  306. if (count <= 0)
  307. {
  308. throw new EndOfStreamException("EOS reading GZIP footer");
  309. }
  310. needed -= count; // Jewel Jan 16
  311. }
  312. // Calculate CRC
  313. int crcval = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8) | ((footer[2] & 0xff) << 16) | (footer[3] << 24);
  314. if (crcval != (int)crc.Value)
  315. {
  316. throw new GZipException("GZIP crc sum mismatch, theirs \"" + crcval + "\" and ours \"" + (int)crc.Value);
  317. }
  318. // NOTE The total here is the original total modulo 2 ^ 32.
  319. uint total =
  320. (uint)((uint)footer[4] & 0xff) |
  321. (uint)(((uint)footer[5] & 0xff) << 8) |
  322. (uint)(((uint)footer[6] & 0xff) << 16) |
  323. (uint)((uint)footer[7] << 24);
  324. if (bytesRead != total)
  325. {
  326. throw new GZipException("Number of bytes mismatch in footer");
  327. }
  328. // Mark header read as false so if another header exists, we'll continue reading through the file
  329. readGZIPHeader = false;
  330. // Indicate that we succeeded on at least one block so we can exit gracefully if there is trailing garbage downstream
  331. completedLastBlock = true;
  332. }
  333. #endregion Support routines
  334. }
  335. }