OSDN Git Service

a23e515e0e05cb7726d3b3d4c9433366f9f37b78
[pf3gnuchains/gcc-fork.git] / libgo / go / 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 )
17
18 // BUG(nigeltao): Comments and Names don't properly map UTF-8 character codes outside of
19 // the 0x00-0x7f range to ISO 8859-1 (Latin-1).
20
21 const (
22         gzipID1     = 0x1f
23         gzipID2     = 0x8b
24         gzipDeflate = 8
25         flagText    = 1 << 0
26         flagHdrCrc  = 1 << 1
27         flagExtra   = 1 << 2
28         flagName    = 1 << 3
29         flagComment = 1 << 4
30 )
31
32 func makeReader(r io.Reader) flate.Reader {
33         if rr, ok := r.(flate.Reader); ok {
34                 return rr
35         }
36         return bufio.NewReader(r)
37 }
38
39 var HeaderError = errors.New("invalid gzip header")
40 var ChecksumError = errors.New("gzip checksum error")
41
42 // The gzip file stores a header giving metadata about the compressed file.
43 // That header is exposed as the fields of the Compressor and Decompressor structs.
44 type Header struct {
45         Comment string // comment
46         Extra   []byte // "extra data"
47         Mtime   uint32 // modification time (seconds since January 1, 1970)
48         Name    string // file name
49         OS      byte   // operating system type
50 }
51
52 // An Decompressor 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 Decompressor
57 // return the concatenation of the uncompressed data of each.
58 // Only the first header is recorded in the Decompressor fields.
59 //
60 // Gzip files store a length and checksum of the uncompressed data.
61 // The Decompressor will return a ChecksumError 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 successful
65 // (zero length, nil error) Read marking the end of the data.
66 type Decompressor struct {
67         Header
68         r            flate.Reader
69         decompressor io.ReadCloser
70         digest       hash.Hash32
71         size         uint32
72         flg          byte
73         buf          [512]byte
74         err          error
75 }
76
77 // NewReader creates a new Decompressor reading the given reader.
78 // The implementation buffers input and may read more data than necessary from r.
79 // It is the caller's responsibility to call Close on the Decompressor when done.
80 func NewReader(r io.Reader) (*Decompressor, error) {
81         z := new(Decompressor)
82         z.r = makeReader(r)
83         z.digest = crc32.NewIEEE()
84         if err := z.readHeader(true); err != nil {
85                 z.err = err
86                 return nil, err
87         }
88         return z, nil
89 }
90
91 // GZIP (RFC 1952) is little-endian, unlike ZLIB (RFC 1950).
92 func get4(p []byte) uint32 {
93         return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24
94 }
95
96 func (z *Decompressor) readString() (string, error) {
97         var err error
98         for i := 0; ; i++ {
99                 if i >= len(z.buf) {
100                         return "", HeaderError
101                 }
102                 z.buf[i], err = z.r.ReadByte()
103                 if err != nil {
104                         return "", err
105                 }
106                 if z.buf[i] == 0 {
107                         // GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1).
108                         // TODO(nigeltao): Convert from ISO 8859-1 (Latin-1) to UTF-8.
109                         return string(z.buf[0:i]), nil
110                 }
111         }
112         panic("not reached")
113 }
114
115 func (z *Decompressor) read2() (uint32, error) {
116         _, err := io.ReadFull(z.r, z.buf[0:2])
117         if err != nil {
118                 return 0, err
119         }
120         return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil
121 }
122
123 func (z *Decompressor) readHeader(save bool) error {
124         _, err := io.ReadFull(z.r, z.buf[0:10])
125         if err != nil {
126                 return err
127         }
128         if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate {
129                 return HeaderError
130         }
131         z.flg = z.buf[3]
132         if save {
133                 z.Mtime = get4(z.buf[4:8])
134                 // z.buf[8] is xfl, ignored
135                 z.OS = z.buf[9]
136         }
137         z.digest.Reset()
138         z.digest.Write(z.buf[0:10])
139
140         if z.flg&flagExtra != 0 {
141                 n, err := z.read2()
142                 if err != nil {
143                         return err
144                 }
145                 data := make([]byte, n)
146                 if _, err = io.ReadFull(z.r, data); err != nil {
147                         return err
148                 }
149                 if save {
150                         z.Extra = data
151                 }
152         }
153
154         var s string
155         if z.flg&flagName != 0 {
156                 if s, err = z.readString(); err != nil {
157                         return err
158                 }
159                 if save {
160                         z.Name = s
161                 }
162         }
163
164         if z.flg&flagComment != 0 {
165                 if s, err = z.readString(); err != nil {
166                         return err
167                 }
168                 if save {
169                         z.Comment = s
170                 }
171         }
172
173         if z.flg&flagHdrCrc != 0 {
174                 n, err := z.read2()
175                 if err != nil {
176                         return err
177                 }
178                 sum := z.digest.Sum32() & 0xFFFF
179                 if n != sum {
180                         return HeaderError
181                 }
182         }
183
184         z.digest.Reset()
185         z.decompressor = flate.NewReader(z.r)
186         return nil
187 }
188
189 func (z *Decompressor) Read(p []byte) (n int, err error) {
190         if z.err != nil {
191                 return 0, z.err
192         }
193         if len(p) == 0 {
194                 return 0, nil
195         }
196
197         n, err = z.decompressor.Read(p)
198         z.digest.Write(p[0:n])
199         z.size += uint32(n)
200         if n != 0 || err != io.EOF {
201                 z.err = err
202                 return
203         }
204
205         // Finished file; check checksum + size.
206         if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil {
207                 z.err = err
208                 return 0, err
209         }
210         crc32, isize := get4(z.buf[0:4]), get4(z.buf[4:8])
211         sum := z.digest.Sum32()
212         if sum != crc32 || isize != z.size {
213                 z.err = ChecksumError
214                 return 0, z.err
215         }
216
217         // File is ok; is there another?
218         if err = z.readHeader(false); err != nil {
219                 z.err = err
220                 return
221         }
222
223         // Yes.  Reset and read from it.
224         z.digest.Reset()
225         z.size = 0
226         return z.Read(p)
227 }
228
229 // Calling Close does not close the wrapped io.Reader originally passed to NewReader.
230 func (z *Decompressor) Close() error { return z.decompressor.Close() }