github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/klauspost/compress/gzip/gunzip.go (about)

     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  
     5  // Package gzip implements reading and writing of gzip format compressed files,
     6  // as specified in RFC 1952.
     7  package gzip
     8  
     9  import (
    10  	"bufio"
    11  	"errors"
    12  	"hash"
    13  	"io"
    14  	"time"
    15  
    16  	"github.com/insionng/yougam/libraries/klauspost/compress/flate"
    17  	"github.com/insionng/yougam/libraries/klauspost/crc32"
    18  )
    19  
    20  const (
    21  	gzipID1     = 0x1f
    22  	gzipID2     = 0x8b
    23  	gzipDeflate = 8
    24  	flagText    = 1 << 0
    25  	flagHdrCrc  = 1 << 1
    26  	flagExtra   = 1 << 2
    27  	flagName    = 1 << 3
    28  	flagComment = 1 << 4
    29  )
    30  
    31  func makeReader(r io.Reader) flate.Reader {
    32  	if rr, ok := r.(flate.Reader); ok {
    33  		return rr
    34  	}
    35  	return bufio.NewReader(r)
    36  }
    37  
    38  var (
    39  	// ErrChecksum is returned when reading GZIP data that has an invalid checksum.
    40  	ErrChecksum = errors.New("gzip: invalid checksum")
    41  	// ErrHeader is returned when reading GZIP data that has an invalid header.
    42  	ErrHeader = errors.New("gzip: invalid header")
    43  )
    44  
    45  // The gzip file stores a header giving metadata about the compressed file.
    46  // That header is exposed as the fields of the Writer and Reader structs.
    47  type Header struct {
    48  	Comment string    // comment
    49  	Extra   []byte    // "extra data"
    50  	ModTime time.Time // modification time
    51  	Name    string    // file name
    52  	OS      byte      // operating system type
    53  }
    54  
    55  // A Reader is an io.Reader that can be read to retrieve
    56  // uncompressed data from a gzip-format compressed file.
    57  //
    58  // In general, a gzip file can be a concatenation of gzip files,
    59  // each with its own header.  Reads from the Reader
    60  // return the concatenation of the uncompressed data of each.
    61  // Only the first header is recorded in the Reader fields.
    62  //
    63  // Gzip files store a length and checksum of the uncompressed data.
    64  // The Reader will return a ErrChecksum when Read
    65  // reaches the end of the uncompressed data if it does not
    66  // have the expected length or checksum.  Clients should treat data
    67  // returned by Read as tentative until they receive the io.EOF
    68  // marking the end of the data.
    69  type Reader struct {
    70  	Header
    71  	r            flate.Reader
    72  	decompressor io.ReadCloser
    73  	digest       hash.Hash32
    74  	size         uint32
    75  	flg          byte
    76  	buf          [512]byte
    77  	err          error
    78  	multistream  bool
    79  }
    80  
    81  // NewReader creates a new Reader reading the given reader.
    82  // If r does not also implement io.ByteReader,
    83  // the decompressor may read more data than necessary from r.
    84  // It is the caller's responsibility to call Close on the Reader when done.
    85  func NewReader(r io.Reader) (*Reader, error) {
    86  	z := new(Reader)
    87  	z.r = makeReader(r)
    88  	z.multistream = true
    89  	z.digest = crc32.NewIEEE()
    90  	if err := z.readHeader(true); err != nil {
    91  		return nil, err
    92  	}
    93  	return z, nil
    94  }
    95  
    96  // Reset discards the Reader z's state and makes it equivalent to the
    97  // result of its original state from NewReader, but reading from r instead.
    98  // This permits reusing a Reader rather than allocating a new one.
    99  func (z *Reader) Reset(r io.Reader) error {
   100  	z.r = makeReader(r)
   101  	if z.digest == nil {
   102  		z.digest = crc32.NewIEEE()
   103  	} else {
   104  		z.digest.Reset()
   105  	}
   106  	z.size = 0
   107  	z.err = nil
   108  	z.multistream = true
   109  	return z.readHeader(true)
   110  }
   111  
   112  // Multistream controls whether the reader supports multistream files.
   113  //
   114  // If enabled (the default), the Reader expects the input to be a sequence
   115  // of individually gzipped data streams, each with its own header and
   116  // trailer, ending at EOF. The effect is that the concatenation of a sequence
   117  // of gzipped files is treated as equivalent to the gzip of the concatenation
   118  // of the sequence. This is standard behavior for gzip readers.
   119  //
   120  // Calling Multistream(false) disables this behavior; disabling the behavior
   121  // can be useful when reading file formats that distinguish individual gzip
   122  // data streams or mix gzip data streams with other data streams.
   123  // In this mode, when the Reader reaches the end of the data stream,
   124  // Read returns io.EOF. If the underlying reader implements io.ByteReader,
   125  // it will be left positioned just after the gzip stream.
   126  // To start the next stream, call z.Reset(r) followed by z.Multistream(false).
   127  // If there is no next stream, z.Reset(r) will return io.EOF.
   128  func (z *Reader) Multistream(ok bool) {
   129  	z.multistream = ok
   130  }
   131  
   132  // GZIP (RFC 1952) is little-endian, unlike ZLIB (RFC 1950).
   133  func get4(p []byte) uint32 {
   134  	return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24
   135  }
   136  
   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  			// GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1).
   153  			if needconv {
   154  				s := make([]rune, 0, i)
   155  				for _, v := range z.buf[0:i] {
   156  					s = append(s, rune(v))
   157  				}
   158  				return string(s), nil
   159  			}
   160  			return string(z.buf[0:i]), nil
   161  		}
   162  	}
   163  }
   164  
   165  func (z *Reader) read2() (uint32, error) {
   166  	_, err := io.ReadFull(z.r, z.buf[0:2])
   167  	if err != nil {
   168  		return 0, err
   169  	}
   170  	return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil
   171  }
   172  
   173  func (z *Reader) readHeader(save bool) error {
   174  	_, err := io.ReadFull(z.r, z.buf[0:10])
   175  	if err != nil {
   176  		return err
   177  	}
   178  	if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate {
   179  		return ErrHeader
   180  	}
   181  	z.flg = z.buf[3]
   182  	if save {
   183  		z.ModTime = time.Unix(int64(get4(z.buf[4:8])), 0)
   184  		// z.buf[8] is xfl, ignored
   185  		z.OS = z.buf[9]
   186  	}
   187  	z.digest.Reset()
   188  	z.digest.Write(z.buf[0:10])
   189  
   190  	if z.flg&flagExtra != 0 {
   191  		n, err := z.read2()
   192  		if err != nil {
   193  			return err
   194  		}
   195  		data := make([]byte, n)
   196  		if _, err = io.ReadFull(z.r, data); err != nil {
   197  			return err
   198  		}
   199  		if save {
   200  			z.Extra = data
   201  		}
   202  	}
   203  
   204  	var s string
   205  	if z.flg&flagName != 0 {
   206  		if s, err = z.readString(); err != nil {
   207  			return err
   208  		}
   209  		if save {
   210  			z.Name = s
   211  		}
   212  	}
   213  
   214  	if z.flg&flagComment != 0 {
   215  		if s, err = z.readString(); err != nil {
   216  			return err
   217  		}
   218  		if save {
   219  			z.Comment = s
   220  		}
   221  	}
   222  
   223  	if z.flg&flagHdrCrc != 0 {
   224  		n, err := z.read2()
   225  		if err != nil {
   226  			return err
   227  		}
   228  		sum := z.digest.Sum32() & 0xFFFF
   229  		if n != sum {
   230  			return ErrHeader
   231  		}
   232  	}
   233  
   234  	z.digest.Reset()
   235  	if z.decompressor == nil {
   236  		z.decompressor = flate.NewReader(z.r)
   237  	} else {
   238  		z.decompressor.(flate.Resetter).Reset(z.r, nil)
   239  	}
   240  	return nil
   241  }
   242  
   243  func (z *Reader) Read(p []byte) (n int, err error) {
   244  	if z.err != nil {
   245  		return 0, z.err
   246  	}
   247  	if len(p) == 0 {
   248  		return 0, nil
   249  	}
   250  
   251  	n, err = z.decompressor.Read(p)
   252  	z.digest.Write(p[0:n])
   253  	z.size += uint32(n)
   254  	if n != 0 || err != io.EOF {
   255  		z.err = err
   256  		return
   257  	}
   258  
   259  	// Finished file; check checksum + size.
   260  	if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil {
   261  		z.err = err
   262  		return 0, err
   263  	}
   264  	crc32, isize := get4(z.buf[0:4]), get4(z.buf[4:8])
   265  	sum := z.digest.Sum32()
   266  	if sum != crc32 || isize != z.size {
   267  		z.err = ErrChecksum
   268  		return 0, z.err
   269  	}
   270  
   271  	// File is ok; is there another?
   272  	if !z.multistream {
   273  		return 0, io.EOF
   274  	}
   275  
   276  	if err = z.readHeader(false); err != nil {
   277  		z.err = err
   278  		return
   279  	}
   280  
   281  	// Yes.  Reset and read from it.
   282  	z.digest.Reset()
   283  	z.size = 0
   284  	return z.Read(p)
   285  }
   286  
   287  // 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  	for {
   291  		if z.err != nil {
   292  			if z.err == io.EOF {
   293  				return total, nil
   294  			}
   295  			return total, z.err
   296  		}
   297  
   298  		// We write both to output and digest.
   299  		mw := io.MultiWriter(w, z.digest)
   300  		n, err := z.decompressor.(io.WriterTo).WriteTo(mw)
   301  		total += n
   302  		z.size += uint32(n)
   303  		if err != nil {
   304  			z.err = err
   305  			return total, z.err
   306  		}
   307  
   308  		// Finished file; check checksum + size.
   309  		if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil {
   310  			z.err = err
   311  			return 0, err
   312  		}
   313  		crc32, isize := get4(z.buf[0:4]), get4(z.buf[4:8])
   314  		sum := z.digest.Sum32()
   315  		if sum != crc32 || isize != z.size {
   316  			z.err = ErrChecksum
   317  			return 0, z.err
   318  		}
   319  
   320  		// File is ok; is there another?
   321  		if !z.multistream {
   322  			return total, nil
   323  		}
   324  
   325  		err = z.readHeader(false)
   326  		// There was not more
   327  		if err == io.EOF {
   328  			return total, nil
   329  		}
   330  		if err != nil {
   331  			z.err = err
   332  			return total, err
   333  		}
   334  
   335  		// Yes.  Reset and read from it.
   336  		z.digest.Reset()
   337  		z.size = 0
   338  	}
   339  }
   340  
   341  // Close closes the Reader. It does not close the underlying io.Reader.
   342  func (z *Reader) Close() error { return z.decompressor.Close() }