本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

345 lines
9.5KB

  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. "encoding/binary"
  10. "errors"
  11. "io"
  12. "time"
  13. "github.com/klauspost/compress/flate"
  14. "github.com/klauspost/crc32"
  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 = errors.New("gzip: invalid checksum")
  29. // ErrHeader is returned when reading GZIP data that has an invalid header.
  30. ErrHeader = errors.New("gzip: invalid header")
  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. decompressor io.ReadCloser
  70. digest uint32 // CRC-32, IEEE polynomial (section 8)
  71. size uint32 // Uncompressed size (section 2.3.1)
  72. buf [512]byte
  73. err error
  74. multistream bool
  75. }
  76. // NewReader creates a new Reader reading the given reader.
  77. // If r does not also implement io.ByteReader,
  78. // the decompressor may read more data than necessary from r.
  79. //
  80. // It is the caller's responsibility to call Close on the Reader when done.
  81. //
  82. // The Reader.Header fields will be valid in the Reader returned.
  83. func NewReader(r io.Reader) (*Reader, error) {
  84. z := new(Reader)
  85. if err := z.Reset(r); err != nil {
  86. return nil, err
  87. }
  88. return z, nil
  89. }
  90. // Reset discards the Reader z's state and makes it equivalent to the
  91. // result of its original state from NewReader, but reading from r instead.
  92. // This permits reusing a Reader rather than allocating a new one.
  93. func (z *Reader) Reset(r io.Reader) error {
  94. *z = Reader{
  95. decompressor: z.decompressor,
  96. multistream: true,
  97. }
  98. if rr, ok := r.(flate.Reader); ok {
  99. z.r = rr
  100. } else {
  101. z.r = bufio.NewReader(r)
  102. }
  103. z.Header, z.err = z.readHeader()
  104. return z.err
  105. }
  106. // Multistream controls whether the reader supports multistream files.
  107. //
  108. // If enabled (the default), the Reader expects the input to be a sequence
  109. // of individually gzipped data streams, each with its own header and
  110. // trailer, ending at EOF. The effect is that the concatenation of a sequence
  111. // of gzipped files is treated as equivalent to the gzip of the concatenation
  112. // of the sequence. This is standard behavior for gzip readers.
  113. //
  114. // Calling Multistream(false) disables this behavior; disabling the behavior
  115. // can be useful when reading file formats that distinguish individual gzip
  116. // data streams or mix gzip data streams with other data streams.
  117. // In this mode, when the Reader reaches the end of the data stream,
  118. // Read returns io.EOF. If the underlying reader implements io.ByteReader,
  119. // it will be left positioned just after the gzip stream.
  120. // To start the next stream, call z.Reset(r) followed by z.Multistream(false).
  121. // If there is no next stream, z.Reset(r) will return io.EOF.
  122. func (z *Reader) Multistream(ok bool) {
  123. z.multistream = ok
  124. }
  125. // readString reads a NUL-terminated string from z.r.
  126. // It treats the bytes read as being encoded as ISO 8859-1 (Latin-1) and
  127. // will output a string encoded using UTF-8.
  128. // This method always updates z.digest with the data read.
  129. func (z *Reader) readString() (string, error) {
  130. var err error
  131. needConv := false
  132. for i := 0; ; i++ {
  133. if i >= len(z.buf) {
  134. return "", ErrHeader
  135. }
  136. z.buf[i], err = z.r.ReadByte()
  137. if err != nil {
  138. return "", err
  139. }
  140. if z.buf[i] > 0x7f {
  141. needConv = true
  142. }
  143. if z.buf[i] == 0 {
  144. // Digest covers the NUL terminator.
  145. z.digest = crc32.Update(z.digest, crc32.IEEETable, z.buf[:i+1])
  146. // Strings are ISO 8859-1, Latin-1 (RFC 1952, section 2.3.1).
  147. if needConv {
  148. s := make([]rune, 0, i)
  149. for _, v := range z.buf[:i] {
  150. s = append(s, rune(v))
  151. }
  152. return string(s), nil
  153. }
  154. return string(z.buf[:i]), nil
  155. }
  156. }
  157. }
  158. // readHeader reads the GZIP header according to section 2.3.1.
  159. // This method does not set z.err.
  160. func (z *Reader) readHeader() (hdr Header, err error) {
  161. if _, err = io.ReadFull(z.r, z.buf[:10]); err != nil {
  162. // RFC 1952, section 2.2, says the following:
  163. // A gzip file consists of a series of "members" (compressed data sets).
  164. //
  165. // Other than this, the specification does not clarify whether a
  166. // "series" is defined as "one or more" or "zero or more". To err on the
  167. // side of caution, Go interprets this to mean "zero or more".
  168. // Thus, it is okay to return io.EOF here.
  169. return hdr, err
  170. }
  171. if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate {
  172. return hdr, ErrHeader
  173. }
  174. flg := z.buf[3]
  175. hdr.ModTime = time.Unix(int64(le.Uint32(z.buf[4:8])), 0)
  176. // z.buf[8] is XFL and is currently ignored.
  177. hdr.OS = z.buf[9]
  178. z.digest = crc32.ChecksumIEEE(z.buf[:10])
  179. if flg&flagExtra != 0 {
  180. if _, err = io.ReadFull(z.r, z.buf[:2]); err != nil {
  181. return hdr, noEOF(err)
  182. }
  183. z.digest = crc32.Update(z.digest, crc32.IEEETable, z.buf[:2])
  184. data := make([]byte, le.Uint16(z.buf[:2]))
  185. if _, err = io.ReadFull(z.r, data); err != nil {
  186. return hdr, noEOF(err)
  187. }
  188. z.digest = crc32.Update(z.digest, crc32.IEEETable, data)
  189. hdr.Extra = data
  190. }
  191. var s string
  192. if flg&flagName != 0 {
  193. if s, err = z.readString(); err != nil {
  194. return hdr, err
  195. }
  196. hdr.Name = s
  197. }
  198. if flg&flagComment != 0 {
  199. if s, err = z.readString(); err != nil {
  200. return hdr, err
  201. }
  202. hdr.Comment = s
  203. }
  204. if flg&flagHdrCrc != 0 {
  205. if _, err = io.ReadFull(z.r, z.buf[:2]); err != nil {
  206. return hdr, noEOF(err)
  207. }
  208. digest := le.Uint16(z.buf[:2])
  209. if digest != uint16(z.digest) {
  210. return hdr, ErrHeader
  211. }
  212. }
  213. z.digest = 0
  214. if z.decompressor == nil {
  215. z.decompressor = flate.NewReader(z.r)
  216. } else {
  217. z.decompressor.(flate.Resetter).Reset(z.r, nil)
  218. }
  219. return hdr, nil
  220. }
  221. // Read implements io.Reader, reading uncompressed bytes from its underlying Reader.
  222. func (z *Reader) Read(p []byte) (n int, err error) {
  223. if z.err != nil {
  224. return 0, z.err
  225. }
  226. n, z.err = z.decompressor.Read(p)
  227. z.digest = crc32.Update(z.digest, crc32.IEEETable, p[:n])
  228. z.size += uint32(n)
  229. if z.err != io.EOF {
  230. // In the normal case we return here.
  231. return n, z.err
  232. }
  233. // Finished file; check checksum and size.
  234. if _, err := io.ReadFull(z.r, z.buf[:8]); err != nil {
  235. z.err = noEOF(err)
  236. return n, z.err
  237. }
  238. digest := le.Uint32(z.buf[:4])
  239. size := le.Uint32(z.buf[4:8])
  240. if digest != z.digest || size != z.size {
  241. z.err = ErrChecksum
  242. return n, z.err
  243. }
  244. z.digest, z.size = 0, 0
  245. // File is ok; check if there is another.
  246. if !z.multistream {
  247. return n, io.EOF
  248. }
  249. z.err = nil // Remove io.EOF
  250. if _, z.err = z.readHeader(); z.err != nil {
  251. return n, z.err
  252. }
  253. // Read from next file, if necessary.
  254. if n > 0 {
  255. return n, nil
  256. }
  257. return z.Read(p)
  258. }
  259. // Support the io.WriteTo interface for io.Copy and friends.
  260. func (z *Reader) WriteTo(w io.Writer) (int64, error) {
  261. total := int64(0)
  262. crcWriter := crc32.NewIEEE()
  263. for {
  264. if z.err != nil {
  265. if z.err == io.EOF {
  266. return total, nil
  267. }
  268. return total, z.err
  269. }
  270. // We write both to output and digest.
  271. mw := io.MultiWriter(w, crcWriter)
  272. n, err := z.decompressor.(io.WriterTo).WriteTo(mw)
  273. total += n
  274. z.size += uint32(n)
  275. if err != nil {
  276. z.err = err
  277. return total, z.err
  278. }
  279. // Finished file; check checksum + size.
  280. if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil {
  281. if err == io.EOF {
  282. err = io.ErrUnexpectedEOF
  283. }
  284. z.err = err
  285. return total, err
  286. }
  287. z.digest = crcWriter.Sum32()
  288. digest := le.Uint32(z.buf[:4])
  289. size := le.Uint32(z.buf[4:8])
  290. if digest != z.digest || size != z.size {
  291. z.err = ErrChecksum
  292. return total, z.err
  293. }
  294. z.digest, z.size = 0, 0
  295. // File is ok; check if there is another.
  296. if !z.multistream {
  297. return total, nil
  298. }
  299. crcWriter.Reset()
  300. z.err = nil // Remove io.EOF
  301. if _, z.err = z.readHeader(); z.err != nil {
  302. if z.err == io.EOF {
  303. return total, nil
  304. }
  305. return total, z.err
  306. }
  307. }
  308. }
  309. // Close closes the Reader. It does not close the underlying io.Reader.
  310. // In order for the GZIP checksum to be verified, the reader must be
  311. // fully consumed until the io.EOF.
  312. func (z *Reader) Close() error { return z.decompressor.Close() }
上海开阖软件有限公司 沪ICP备12045867号-1