...
Run Format

Source file src/pkg/compress/gzip/gunzip.go

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

View as plain text