Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

350 řádky
9.5 KiB

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