gunzip.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package gzip implements reading and writing of gzip format compressed files,
  5. // as specified in RFC 1952.
  6. package gzip
  7. import (
  8. "bufio"
  9. "compress/gzip"
  10. "encoding/binary"
  11. "hash/crc32"
  12. "io"
  13. "time"
  14. "github.com/klauspost/compress/flate"
  15. )
  16. const (
  17. gzipID1 = 0x1f
  18. gzipID2 = 0x8b
  19. gzipDeflate = 8
  20. flagText = 1 << 0
  21. flagHdrCrc = 1 << 1
  22. flagExtra = 1 << 2
  23. flagName = 1 << 3
  24. flagComment = 1 << 4
  25. )
  26. var (
  27. // ErrChecksum is returned when reading GZIP data that has an invalid checksum.
  28. ErrChecksum = gzip.ErrChecksum
  29. // ErrHeader is returned when reading GZIP data that has an invalid header.
  30. ErrHeader = gzip.ErrHeader
  31. )
  32. var le = binary.LittleEndian
  33. // noEOF converts io.EOF to io.ErrUnexpectedEOF.
  34. func noEOF(err error) error {
  35. if err == io.EOF {
  36. return io.ErrUnexpectedEOF
  37. }
  38. return err
  39. }
  40. // The gzip file stores a header giving metadata about the compressed file.
  41. // That header is exposed as the fields of the Writer and Reader structs.
  42. //
  43. // Strings must be UTF-8 encoded and may only contain Unicode code points
  44. // U+0001 through U+00FF, due to limitations of the GZIP file format.
  45. type Header struct {
  46. Comment string // comment
  47. Extra []byte // "extra data"
  48. ModTime time.Time // modification time
  49. Name string // file name
  50. OS byte // operating system type
  51. }
  52. // A Reader is an io.Reader that can be read to retrieve
  53. // uncompressed data from a gzip-format compressed file.
  54. //
  55. // In general, a gzip file can be a concatenation of gzip files,
  56. // each with its own header. Reads from the Reader
  57. // return the concatenation of the uncompressed data of each.
  58. // Only the first header is recorded in the Reader fields.
  59. //
  60. // Gzip files store a length and checksum of the uncompressed data.
  61. // The Reader will return a ErrChecksum when Read
  62. // reaches the end of the uncompressed data if it does not
  63. // have the expected length or checksum. Clients should treat data
  64. // returned by Read as tentative until they receive the io.EOF
  65. // marking the end of the data.
  66. type Reader struct {
  67. Header // valid after NewReader or Reader.Reset
  68. r flate.Reader
  69. br *bufio.Reader
  70. decompressor io.ReadCloser
  71. digest uint32 // CRC-32, IEEE polynomial (section 8)
  72. size uint32 // Uncompressed size (section 2.3.1)
  73. buf [512]byte
  74. err error
  75. multistream bool
  76. }
  77. // NewReader creates a new Reader reading the given reader.
  78. // If r does not also implement io.ByteReader,
  79. // the decompressor may read more data than necessary from r.
  80. //
  81. // It is the caller's responsibility to call Close on the Reader when done.
  82. //
  83. // The Reader.Header fields will be valid in the Reader returned.
  84. func NewReader(r io.Reader) (*Reader, error) {
  85. z := new(Reader)
  86. if err := z.Reset(r); err != nil {
  87. return nil, err
  88. }
  89. return z, nil
  90. }
  91. // Reset discards the Reader z's state and makes it equivalent to the
  92. // result of its original state from NewReader, but reading from r instead.
  93. // This permits reusing a Reader rather than allocating a new one.
  94. func (z *Reader) Reset(r io.Reader) error {
  95. *z = Reader{
  96. decompressor: z.decompressor,
  97. multistream: true,
  98. br: z.br,
  99. }
  100. if rr, ok := r.(flate.Reader); ok {
  101. z.r = rr
  102. } else {
  103. // Reuse if we can.
  104. if z.br != nil {
  105. z.br.Reset(r)
  106. } else {
  107. z.br = bufio.NewReader(r)
  108. }
  109. z.r = z.br
  110. }
  111. z.Header, z.err = z.readHeader()
  112. return z.err
  113. }
  114. // Multistream controls whether the reader supports multistream files.
  115. //
  116. // If enabled (the default), the Reader expects the input to be a sequence
  117. // of individually gzipped data streams, each with its own header and
  118. // trailer, ending at EOF. The effect is that the concatenation of a sequence
  119. // of gzipped files is treated as equivalent to the gzip of the concatenation
  120. // of the sequence. This is standard behavior for gzip readers.
  121. //
  122. // Calling Multistream(false) disables this behavior; disabling the behavior
  123. // can be useful when reading file formats that distinguish individual gzip
  124. // data streams or mix gzip data streams with other data streams.
  125. // In this mode, when the Reader reaches the end of the data stream,
  126. // Read returns io.EOF. If the underlying reader implements io.ByteReader,
  127. // it will be left positioned just after the gzip stream.
  128. // To start the next stream, call z.Reset(r) followed by z.Multistream(false).
  129. // If there is no next stream, z.Reset(r) will return io.EOF.
  130. func (z *Reader) Multistream(ok bool) {
  131. z.multistream = ok
  132. }
  133. // readString reads a NUL-terminated string from z.r.
  134. // It treats the bytes read as being encoded as ISO 8859-1 (Latin-1) and
  135. // will output a string encoded using UTF-8.
  136. // This method always updates z.digest with the data read.
  137. func (z *Reader) readString() (string, error) {
  138. var err error
  139. needConv := false
  140. for i := 0; ; i++ {
  141. if i >= len(z.buf) {
  142. return "", ErrHeader
  143. }
  144. z.buf[i], err = z.r.ReadByte()
  145. if err != nil {
  146. return "", err
  147. }
  148. if z.buf[i] > 0x7f {
  149. needConv = true
  150. }
  151. if z.buf[i] == 0 {
  152. // Digest covers the NUL terminator.
  153. z.digest = crc32.Update(z.digest, crc32.IEEETable, z.buf[:i+1])
  154. // Strings are ISO 8859-1, Latin-1 (RFC 1952, section 2.3.1).
  155. if needConv {
  156. s := make([]rune, 0, i)
  157. for _, v := range z.buf[:i] {
  158. s = append(s, rune(v))
  159. }
  160. return string(s), nil
  161. }
  162. return string(z.buf[:i]), nil
  163. }
  164. }
  165. }
  166. // readHeader reads the GZIP header according to section 2.3.1.
  167. // This method does not set z.err.
  168. func (z *Reader) readHeader() (hdr Header, err error) {
  169. if _, err = io.ReadFull(z.r, z.buf[:10]); err != nil {
  170. // RFC 1952, section 2.2, says the following:
  171. // A gzip file consists of a series of "members" (compressed data sets).
  172. //
  173. // Other than this, the specification does not clarify whether a
  174. // "series" is defined as "one or more" or "zero or more". To err on the
  175. // side of caution, Go interprets this to mean "zero or more".
  176. // Thus, it is okay to return io.EOF here.
  177. return hdr, err
  178. }
  179. if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate {
  180. return hdr, ErrHeader
  181. }
  182. flg := z.buf[3]
  183. hdr.ModTime = time.Unix(int64(le.Uint32(z.buf[4:8])), 0)
  184. // z.buf[8] is XFL and is currently ignored.
  185. hdr.OS = z.buf[9]
  186. z.digest = crc32.ChecksumIEEE(z.buf[:10])
  187. if flg&flagExtra != 0 {
  188. if _, err = io.ReadFull(z.r, z.buf[:2]); err != nil {
  189. return hdr, noEOF(err)
  190. }
  191. z.digest = crc32.Update(z.digest, crc32.IEEETable, z.buf[:2])
  192. data := make([]byte, le.Uint16(z.buf[:2]))
  193. if _, err = io.ReadFull(z.r, data); err != nil {
  194. return hdr, noEOF(err)
  195. }
  196. z.digest = crc32.Update(z.digest, crc32.IEEETable, data)
  197. hdr.Extra = data
  198. }
  199. var s string
  200. if flg&flagName != 0 {
  201. if s, err = z.readString(); err != nil {
  202. return hdr, err
  203. }
  204. hdr.Name = s
  205. }
  206. if flg&flagComment != 0 {
  207. if s, err = z.readString(); err != nil {
  208. return hdr, err
  209. }
  210. hdr.Comment = s
  211. }
  212. if flg&flagHdrCrc != 0 {
  213. if _, err = io.ReadFull(z.r, z.buf[:2]); err != nil {
  214. return hdr, noEOF(err)
  215. }
  216. digest := le.Uint16(z.buf[:2])
  217. if digest != uint16(z.digest) {
  218. return hdr, ErrHeader
  219. }
  220. }
  221. // Reserved FLG bits must be zero.
  222. if flg>>5 != 0 {
  223. return hdr, ErrHeader
  224. }
  225. z.digest = 0
  226. if z.decompressor == nil {
  227. z.decompressor = flate.NewReader(z.r)
  228. } else {
  229. z.decompressor.(flate.Resetter).Reset(z.r, nil)
  230. }
  231. return hdr, nil
  232. }
  233. // Read implements io.Reader, reading uncompressed bytes from its underlying Reader.
  234. func (z *Reader) Read(p []byte) (n int, err error) {
  235. if z.err != nil {
  236. return 0, z.err
  237. }
  238. for n == 0 {
  239. n, z.err = z.decompressor.Read(p)
  240. z.digest = crc32.Update(z.digest, crc32.IEEETable, p[:n])
  241. z.size += uint32(n)
  242. if z.err != io.EOF {
  243. // In the normal case we return here.
  244. return n, z.err
  245. }
  246. // Finished file; check checksum and size.
  247. if _, err := io.ReadFull(z.r, z.buf[:8]); err != nil {
  248. z.err = noEOF(err)
  249. return n, z.err
  250. }
  251. digest := le.Uint32(z.buf[:4])
  252. size := le.Uint32(z.buf[4:8])
  253. if digest != z.digest || size != z.size {
  254. z.err = ErrChecksum
  255. return n, z.err
  256. }
  257. z.digest, z.size = 0, 0
  258. // File is ok; check if there is another.
  259. if !z.multistream {
  260. return n, io.EOF
  261. }
  262. z.err = nil // Remove io.EOF
  263. if _, z.err = z.readHeader(); z.err != nil {
  264. return n, z.err
  265. }
  266. }
  267. return n, nil
  268. }
  269. type crcer interface {
  270. io.Writer
  271. Sum32() uint32
  272. Reset()
  273. }
  274. type crcUpdater struct {
  275. z *Reader
  276. }
  277. func (c *crcUpdater) Write(p []byte) (int, error) {
  278. c.z.digest = crc32.Update(c.z.digest, crc32.IEEETable, p)
  279. return len(p), nil
  280. }
  281. func (c *crcUpdater) Sum32() uint32 {
  282. return c.z.digest
  283. }
  284. func (c *crcUpdater) Reset() {
  285. c.z.digest = 0
  286. }
  287. // WriteTo support the io.WriteTo interface for io.Copy and friends.
  288. func (z *Reader) WriteTo(w io.Writer) (int64, error) {
  289. total := int64(0)
  290. crcWriter := crcer(crc32.NewIEEE())
  291. if z.digest != 0 {
  292. crcWriter = &crcUpdater{z: z}
  293. }
  294. for {
  295. if z.err != nil {
  296. if z.err == io.EOF {
  297. return total, nil
  298. }
  299. return total, z.err
  300. }
  301. // We write both to output and digest.
  302. mw := io.MultiWriter(w, crcWriter)
  303. n, err := z.decompressor.(io.WriterTo).WriteTo(mw)
  304. total += n
  305. z.size += uint32(n)
  306. if err != nil {
  307. z.err = err
  308. return total, z.err
  309. }
  310. // Finished file; check checksum + size.
  311. if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil {
  312. if err == io.EOF {
  313. err = io.ErrUnexpectedEOF
  314. }
  315. z.err = err
  316. return total, err
  317. }
  318. z.digest = crcWriter.Sum32()
  319. digest := le.Uint32(z.buf[:4])
  320. size := le.Uint32(z.buf[4:8])
  321. if digest != z.digest || size != z.size {
  322. z.err = ErrChecksum
  323. return total, z.err
  324. }
  325. z.digest, z.size = 0, 0
  326. // File is ok; check if there is another.
  327. if !z.multistream {
  328. return total, nil
  329. }
  330. crcWriter.Reset()
  331. z.err = nil // Remove io.EOF
  332. if _, z.err = z.readHeader(); z.err != nil {
  333. if z.err == io.EOF {
  334. return total, nil
  335. }
  336. return total, z.err
  337. }
  338. }
  339. }
  340. // Close closes the Reader. It does not close the underlying io.Reader.
  341. // In order for the GZIP checksum to be verified, the reader must be
  342. // fully consumed until the io.EOF.
  343. func (z *Reader) Close() error { return z.decompressor.Close() }