gunzip.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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/flate"
  10. "errors"
  11. "hash"
  12. "hash/crc32"
  13. "io"
  14. "time"
  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. func makeReader(r io.Reader) flate.Reader {
  27. if rr, ok := r.(flate.Reader); ok {
  28. return rr
  29. }
  30. return bufio.NewReader(r)
  31. }
  32. var (
  33. // ErrChecksum is returned when reading GZIP data that has an invalid checksum.
  34. ErrChecksum = errors.New("gzip: invalid checksum")
  35. // ErrHeader is returned when reading GZIP data that has an invalid header.
  36. ErrHeader = errors.New("gzip: invalid header")
  37. )
  38. // The gzip file stores a header giving metadata about the compressed file.
  39. // That header is exposed as the fields of the Writer and Reader structs.
  40. type Header struct {
  41. Comment string // comment
  42. Extra []byte // "extra data"
  43. ModTime time.Time // modification time
  44. Name string // file name
  45. OS byte // operating system type
  46. }
  47. // A Reader is an io.Reader that can be read to retrieve
  48. // uncompressed data from a gzip-format compressed file.
  49. //
  50. // In general, a gzip file can be a concatenation of gzip files,
  51. // each with its own header. Reads from the Reader
  52. // return the concatenation of the uncompressed data of each.
  53. // Only the first header is recorded in the Reader fields.
  54. //
  55. // Gzip files store a length and checksum of the uncompressed data.
  56. // The Reader will return a ErrChecksum when Read
  57. // reaches the end of the uncompressed data if it does not
  58. // have the expected length or checksum. Clients should treat data
  59. // returned by Read as tentative until they receive the io.EOF
  60. // marking the end of the data.
  61. type Reader struct {
  62. Header
  63. r flate.Reader
  64. decompressor io.ReadCloser
  65. digest hash.Hash32
  66. size uint32
  67. flg byte
  68. buf [512]byte
  69. err error
  70. multistream bool
  71. }
  72. // NewReader creates a new Reader reading the given reader.
  73. // If r does not also implement io.ByteReader,
  74. // the decompressor may read more data than necessary from r.
  75. // It is the caller's responsibility to call Close on the Reader when done.
  76. func NewReader(r io.Reader) (*Reader, error) {
  77. z := new(Reader)
  78. z.r = makeReader(r)
  79. z.multistream = true
  80. z.digest = crc32.NewIEEE()
  81. if err := z.readHeader(true); err != nil {
  82. return nil, err
  83. }
  84. return z, nil
  85. }
  86. // Reset discards the Reader z's state and makes it equivalent to the
  87. // result of its original state from NewReader, but reading from r instead.
  88. // This permits reusing a Reader rather than allocating a new one.
  89. func (z *Reader) Reset(r io.Reader) error {
  90. z.r = makeReader(r)
  91. if z.digest == nil {
  92. z.digest = crc32.NewIEEE()
  93. } else {
  94. z.digest.Reset()
  95. }
  96. z.size = 0
  97. z.err = nil
  98. z.multistream = true
  99. return z.readHeader(true)
  100. }
  101. // Multistream controls whether the reader supports multistream files.
  102. //
  103. // If enabled (the default), the Reader expects the input to be a sequence
  104. // of individually gzipped data streams, each with its own header and
  105. // trailer, ending at EOF. The effect is that the concatenation of a sequence
  106. // of gzipped files is treated as equivalent to the gzip of the concatenation
  107. // of the sequence. This is standard behavior for gzip readers.
  108. //
  109. // Calling Multistream(false) disables this behavior; disabling the behavior
  110. // can be useful when reading file formats that distinguish individual gzip
  111. // data streams or mix gzip data streams with other data streams.
  112. // In this mode, when the Reader reaches the end of the data stream,
  113. // Read returns io.EOF. If the underlying reader implements io.ByteReader,
  114. // it will be left positioned just after the gzip stream.
  115. // To start the next stream, call z.Reset(r) followed by z.Multistream(false).
  116. // If there is no next stream, z.Reset(r) will return io.EOF.
  117. func (z *Reader) Multistream(ok bool) {
  118. z.multistream = ok
  119. }
  120. // GZIP (RFC 1952) is little-endian, unlike ZLIB (RFC 1950).
  121. func get4(p []byte) uint32 {
  122. return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24
  123. }
  124. func (z *Reader) readString() (string, error) {
  125. var err error
  126. needconv := false
  127. for i := 0; ; i++ {
  128. if i >= len(z.buf) {
  129. return "", ErrHeader
  130. }
  131. z.buf[i], err = z.r.ReadByte()
  132. if err != nil {
  133. return "", err
  134. }
  135. if z.buf[i] > 0x7f {
  136. needconv = true
  137. }
  138. if z.buf[i] == 0 {
  139. // GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1).
  140. if needconv {
  141. s := make([]rune, 0, i)
  142. for _, v := range z.buf[0:i] {
  143. s = append(s, rune(v))
  144. }
  145. return string(s), nil
  146. }
  147. return string(z.buf[0:i]), nil
  148. }
  149. }
  150. }
  151. func (z *Reader) read2() (uint32, error) {
  152. _, err := io.ReadFull(z.r, z.buf[0:2])
  153. if err != nil {
  154. return 0, err
  155. }
  156. return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil
  157. }
  158. func (z *Reader) readHeader(save bool) error {
  159. _, err := io.ReadFull(z.r, z.buf[0:10])
  160. if err != nil {
  161. return err
  162. }
  163. if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate {
  164. return ErrHeader
  165. }
  166. z.flg = z.buf[3]
  167. if save {
  168. z.ModTime = time.Unix(int64(get4(z.buf[4:8])), 0)
  169. // z.buf[8] is xfl, ignored
  170. z.OS = z.buf[9]
  171. }
  172. z.digest.Reset()
  173. z.digest.Write(z.buf[0:10])
  174. if z.flg&flagExtra != 0 {
  175. n, err := z.read2()
  176. if err != nil {
  177. return err
  178. }
  179. data := make([]byte, n)
  180. if _, err = io.ReadFull(z.r, data); err != nil {
  181. return err
  182. }
  183. if save {
  184. z.Extra = data
  185. }
  186. }
  187. var s string
  188. if z.flg&flagName != 0 {
  189. if s, err = z.readString(); err != nil {
  190. return err
  191. }
  192. if save {
  193. z.Name = s
  194. }
  195. }
  196. if z.flg&flagComment != 0 {
  197. if s, err = z.readString(); err != nil {
  198. return err
  199. }
  200. if save {
  201. z.Comment = s
  202. }
  203. }
  204. if z.flg&flagHdrCrc != 0 {
  205. n, err := z.read2()
  206. if err != nil {
  207. return err
  208. }
  209. sum := z.digest.Sum32() & 0xFFFF
  210. if n != sum {
  211. return ErrHeader
  212. }
  213. }
  214. z.digest.Reset()
  215. if z.decompressor == nil {
  216. z.decompressor = flate.NewReader(z.r)
  217. } else {
  218. z.decompressor.(flate.Resetter).Reset(z.r, nil)
  219. }
  220. return nil
  221. }
  222. func (z *Reader) Read(p []byte) (n int, err error) {
  223. if z.err != nil {
  224. return 0, z.err
  225. }
  226. if len(p) == 0 {
  227. return 0, nil
  228. }
  229. n, err = z.decompressor.Read(p)
  230. z.digest.Write(p[0:n])
  231. z.size += uint32(n)
  232. if n != 0 || err != io.EOF {
  233. z.err = err
  234. return
  235. }
  236. // Finished file; check checksum + size.
  237. if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil {
  238. z.err = err
  239. return 0, err
  240. }
  241. crc32, isize := get4(z.buf[0:4]), get4(z.buf[4:8])
  242. sum := z.digest.Sum32()
  243. if sum != crc32 || isize != z.size {
  244. z.err = ErrChecksum
  245. return 0, z.err
  246. }
  247. // File is ok; is there another?
  248. if !z.multistream {
  249. return 0, io.EOF
  250. }
  251. if err = z.readHeader(false); err != nil {
  252. z.err = err
  253. return
  254. }
  255. // Yes. Reset and read from it.
  256. z.digest.Reset()
  257. z.size = 0
  258. return z.Read(p)
  259. }
  260. // Close closes the Reader. It does not close the underlying io.Reader.
  261. func (z *Reader) Close() error { return z.decompressor.Close() }