github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/klauspost/compress/zip/reader.go (about) 1 // Copyright 2010 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 zip 6 7 import ( 8 "bufio" 9 "encoding/binary" 10 "errors" 11 "fmt" 12 "hash" 13 "io" 14 "os" 15 16 "github.com/insionng/yougam/libraries/klauspost/crc32" 17 ) 18 19 var ( 20 ErrFormat = errors.New("zip: not a valid zip file") 21 ErrAlgorithm = errors.New("zip: unsupported compression algorithm") 22 ErrChecksum = errors.New("zip: checksum error") 23 ) 24 25 type Reader struct { 26 r io.ReaderAt 27 File []*File 28 Comment string 29 decompressors map[uint16]Decompressor 30 } 31 32 type ReadCloser struct { 33 f *os.File 34 Reader 35 } 36 37 type File struct { 38 FileHeader 39 zip *Reader 40 zipr io.ReaderAt 41 zipsize int64 42 headerOffset int64 43 } 44 45 func (f *File) hasDataDescriptor() bool { 46 return f.Flags&0x8 != 0 47 } 48 49 // OpenReader will open the Zip file specified by name and return a ReadCloser. 50 func OpenReader(name string) (*ReadCloser, error) { 51 f, err := os.Open(name) 52 if err != nil { 53 return nil, err 54 } 55 fi, err := f.Stat() 56 if err != nil { 57 f.Close() 58 return nil, err 59 } 60 r := new(ReadCloser) 61 if err := r.init(f, fi.Size()); err != nil { 62 f.Close() 63 return nil, err 64 } 65 r.f = f 66 return r, nil 67 } 68 69 // NewReader returns a new Reader reading from r, which is assumed to 70 // have the given size in bytes. 71 func NewReader(r io.ReaderAt, size int64) (*Reader, error) { 72 zr := new(Reader) 73 if err := zr.init(r, size); err != nil { 74 return nil, err 75 } 76 return zr, nil 77 } 78 79 func (z *Reader) init(r io.ReaderAt, size int64) error { 80 end, err := readDirectoryEnd(r, size) 81 if err != nil { 82 return err 83 } 84 if end.directoryRecords > uint64(size)/fileHeaderLen { 85 return fmt.Errorf("archive/zip: TOC declares impossible %d files in %d byte zip", end.directoryRecords, size) 86 } 87 z.r = r 88 z.File = make([]*File, 0, end.directoryRecords) 89 z.Comment = end.comment 90 rs := io.NewSectionReader(r, 0, size) 91 if _, err = rs.Seek(int64(end.directoryOffset), os.SEEK_SET); err != nil { 92 return err 93 } 94 buf := bufio.NewReader(rs) 95 96 // The count of files inside a zip is truncated to fit in a uint16. 97 // Gloss over this by reading headers until we encounter 98 // a bad one, and then only report a ErrFormat or UnexpectedEOF if 99 // the file count modulo 65536 is incorrect. 100 for { 101 f := &File{zip: z, zipr: r, zipsize: size} 102 err = readDirectoryHeader(f, buf) 103 if err == ErrFormat || err == io.ErrUnexpectedEOF { 104 break 105 } 106 if err != nil { 107 return err 108 } 109 z.File = append(z.File, f) 110 } 111 if uint16(len(z.File)) != uint16(end.directoryRecords) { // only compare 16 bits here 112 // Return the readDirectoryHeader error if we read 113 // the wrong number of directory entries. 114 return err 115 } 116 return nil 117 } 118 119 // RegisterDecompressor registers or overrides a custom decompressor for a 120 // specific method ID. If a decompressor for a given method is not found, 121 // Reader will default to looking up the decompressor at the package level. 122 // 123 // Must not be called concurrently with Open on any Files in the Reader. 124 func (z *Reader) RegisterDecompressor(method uint16, dcomp Decompressor) { 125 if z.decompressors == nil { 126 z.decompressors = make(map[uint16]Decompressor) 127 } 128 z.decompressors[method] = dcomp 129 } 130 131 func (z *Reader) decompressor(method uint16) Decompressor { 132 dcomp := z.decompressors[method] 133 if dcomp == nil { 134 dcomp = decompressor(method) 135 } 136 return dcomp 137 } 138 139 // Close closes the Zip file, rendering it unusable for I/O. 140 func (rc *ReadCloser) Close() error { 141 return rc.f.Close() 142 } 143 144 // DataOffset returns the offset of the file's possibly-compressed 145 // data, relative to the beginning of the zip file. 146 // 147 // Most callers should instead use Open, which transparently 148 // decompresses data and verifies checksums. 149 func (f *File) DataOffset() (offset int64, err error) { 150 bodyOffset, err := f.findBodyOffset() 151 if err != nil { 152 return 153 } 154 return f.headerOffset + bodyOffset, nil 155 } 156 157 // Open returns a ReadCloser that provides access to the File's contents. 158 // Multiple files may be read concurrently. 159 func (f *File) Open() (rc io.ReadCloser, err error) { 160 bodyOffset, err := f.findBodyOffset() 161 if err != nil { 162 return 163 } 164 size := int64(f.CompressedSize64) 165 r := io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset, size) 166 dcomp := f.zip.decompressor(f.Method) 167 if dcomp == nil { 168 err = ErrAlgorithm 169 return 170 } 171 rc = dcomp(r) 172 var desr io.Reader 173 if f.hasDataDescriptor() { 174 desr = io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset+size, dataDescriptorLen) 175 } 176 rc = &checksumReader{ 177 rc: rc, 178 hash: crc32.NewIEEE(), 179 f: f, 180 desr: desr, 181 } 182 return 183 } 184 185 type checksumReader struct { 186 rc io.ReadCloser 187 hash hash.Hash32 188 nread uint64 // number of bytes read so far 189 f *File 190 desr io.Reader // if non-nil, where to read the data descriptor 191 err error // sticky error 192 } 193 194 func (r *checksumReader) Read(b []byte) (n int, err error) { 195 if r.err != nil { 196 return 0, r.err 197 } 198 n, err = r.rc.Read(b) 199 r.hash.Write(b[:n]) 200 r.nread += uint64(n) 201 if err == nil { 202 return 203 } 204 if err == io.EOF { 205 if r.nread != r.f.UncompressedSize64 { 206 return 0, io.ErrUnexpectedEOF 207 } 208 if r.desr != nil { 209 if err1 := readDataDescriptor(r.desr, r.f); err1 != nil { 210 if err1 == io.EOF { 211 err = io.ErrUnexpectedEOF 212 } else { 213 err = err1 214 } 215 } else if r.hash.Sum32() != r.f.CRC32 { 216 err = ErrChecksum 217 } 218 } else { 219 // If there's not a data descriptor, we still compare 220 // the CRC32 of what we've read against the file header 221 // or TOC's CRC32, if it seems like it was set. 222 if r.f.CRC32 != 0 && r.hash.Sum32() != r.f.CRC32 { 223 err = ErrChecksum 224 } 225 } 226 } 227 r.err = err 228 return 229 } 230 231 func (r *checksumReader) Close() error { return r.rc.Close() } 232 233 // findBodyOffset does the minimum work to verify the file has a header 234 // and returns the file body offset. 235 func (f *File) findBodyOffset() (int64, error) { 236 var buf [fileHeaderLen]byte 237 if _, err := f.zipr.ReadAt(buf[:], f.headerOffset); err != nil { 238 return 0, err 239 } 240 b := readBuf(buf[:]) 241 if sig := b.uint32(); sig != fileHeaderSignature { 242 return 0, ErrFormat 243 } 244 b = b[22:] // skip over most of the header 245 filenameLen := int(b.uint16()) 246 extraLen := int(b.uint16()) 247 return int64(fileHeaderLen + filenameLen + extraLen), nil 248 } 249 250 // readDirectoryHeader attempts to read a directory header from r. 251 // It returns io.ErrUnexpectedEOF if it cannot read a complete header, 252 // and ErrFormat if it doesn't find a valid header signature. 253 func readDirectoryHeader(f *File, r io.Reader) error { 254 var buf [directoryHeaderLen]byte 255 if _, err := io.ReadFull(r, buf[:]); err != nil { 256 return err 257 } 258 b := readBuf(buf[:]) 259 if sig := b.uint32(); sig != directoryHeaderSignature { 260 return ErrFormat 261 } 262 f.CreatorVersion = b.uint16() 263 f.ReaderVersion = b.uint16() 264 f.Flags = b.uint16() 265 f.Method = b.uint16() 266 f.ModifiedTime = b.uint16() 267 f.ModifiedDate = b.uint16() 268 f.CRC32 = b.uint32() 269 f.CompressedSize = b.uint32() 270 f.UncompressedSize = b.uint32() 271 f.CompressedSize64 = uint64(f.CompressedSize) 272 f.UncompressedSize64 = uint64(f.UncompressedSize) 273 filenameLen := int(b.uint16()) 274 extraLen := int(b.uint16()) 275 commentLen := int(b.uint16()) 276 b = b[4:] // skipped start disk number and internal attributes (2x uint16) 277 f.ExternalAttrs = b.uint32() 278 f.headerOffset = int64(b.uint32()) 279 d := make([]byte, filenameLen+extraLen+commentLen) 280 if _, err := io.ReadFull(r, d); err != nil { 281 return err 282 } 283 f.Name = string(d[:filenameLen]) 284 f.Extra = d[filenameLen : filenameLen+extraLen] 285 f.Comment = string(d[filenameLen+extraLen:]) 286 287 needUSize := f.UncompressedSize == ^uint32(0) 288 needCSize := f.CompressedSize == ^uint32(0) 289 needHeaderOffset := f.headerOffset == int64(^uint32(0)) 290 291 if len(f.Extra) > 0 { 292 // Best effort to find what we need. 293 // Other zip authors might not even follow the basic format, 294 // and we'll just ignore the Extra content in that case. 295 b := readBuf(f.Extra) 296 for len(b) >= 4 { // need at least tag and size 297 tag := b.uint16() 298 size := b.uint16() 299 if int(size) > len(b) { 300 break 301 } 302 if tag == zip64ExtraId { 303 // update directory values from the zip64 extra block. 304 // They should only be consulted if the sizes read earlier 305 // are maxed out. 306 // See yougam/libraries/issue/13367. 307 eb := readBuf(b[:size]) 308 309 if needUSize { 310 needUSize = false 311 if len(eb) < 8 { 312 return ErrFormat 313 } 314 f.UncompressedSize64 = eb.uint64() 315 } 316 if needCSize { 317 needCSize = false 318 if len(eb) < 8 { 319 return ErrFormat 320 } 321 f.CompressedSize64 = eb.uint64() 322 } 323 if needHeaderOffset { 324 needHeaderOffset = false 325 if len(eb) < 8 { 326 return ErrFormat 327 } 328 f.headerOffset = int64(eb.uint64()) 329 } 330 break 331 } 332 b = b[size:] 333 } 334 } 335 336 if needUSize || needCSize || needHeaderOffset { 337 return ErrFormat 338 } 339 340 return nil 341 } 342 343 func readDataDescriptor(r io.Reader, f *File) error { 344 var buf [dataDescriptorLen]byte 345 346 // The spec says: "Although not originally assigned a 347 // signature, the value 0x08074b50 has commonly been adopted 348 // as a signature value for the data descriptor record. 349 // Implementers should be aware that ZIP files may be 350 // encountered with or without this signature marking data 351 // descriptors and should account for either case when reading 352 // ZIP files to ensure compatibility." 353 // 354 // dataDescriptorLen includes the size of the signature but 355 // first read just those 4 bytes to see if it exists. 356 if _, err := io.ReadFull(r, buf[:4]); err != nil { 357 return err 358 } 359 off := 0 360 maybeSig := readBuf(buf[:4]) 361 if maybeSig.uint32() != dataDescriptorSignature { 362 // No data descriptor signature. Keep these four 363 // bytes. 364 off += 4 365 } 366 if _, err := io.ReadFull(r, buf[off:12]); err != nil { 367 return err 368 } 369 b := readBuf(buf[:12]) 370 if b.uint32() != f.CRC32 { 371 return ErrChecksum 372 } 373 374 // The two sizes that follow here can be either 32 bits or 64 bits 375 // but the spec is not very clear on this and different 376 // interpretations has been made causing incompatibilities. We 377 // already have the sizes from the central directory so we can 378 // just ignore these. 379 380 return nil 381 } 382 383 func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err error) { 384 // look for directoryEndSignature in the last 1k, then in the last 65k 385 var buf []byte 386 var directoryEndOffset int64 387 for i, bLen := range []int64{1024, 65 * 1024} { 388 if bLen > size { 389 bLen = size 390 } 391 buf = make([]byte, int(bLen)) 392 if _, err := r.ReadAt(buf, size-bLen); err != nil && err != io.EOF { 393 return nil, err 394 } 395 if p := findSignatureInBlock(buf); p >= 0 { 396 buf = buf[p:] 397 directoryEndOffset = size - bLen + int64(p) 398 break 399 } 400 if i == 1 || bLen == size { 401 return nil, ErrFormat 402 } 403 } 404 405 // read header into struct 406 b := readBuf(buf[4:]) // skip signature 407 d := &directoryEnd{ 408 diskNbr: uint32(b.uint16()), 409 dirDiskNbr: uint32(b.uint16()), 410 dirRecordsThisDisk: uint64(b.uint16()), 411 directoryRecords: uint64(b.uint16()), 412 directorySize: uint64(b.uint32()), 413 directoryOffset: uint64(b.uint32()), 414 commentLen: b.uint16(), 415 } 416 l := int(d.commentLen) 417 if l > len(b) { 418 return nil, errors.New("zip: invalid comment length") 419 } 420 d.comment = string(b[:l]) 421 422 // These values mean that the file can be a zip64 file 423 if d.directoryRecords == 0xffff || d.directorySize == 0xffff || d.directoryOffset == 0xffffffff { 424 p, err := findDirectory64End(r, directoryEndOffset) 425 if err == nil && p >= 0 { 426 err = readDirectory64End(r, p, d) 427 } 428 if err != nil { 429 return nil, err 430 } 431 } 432 // Make sure directoryOffset points to somewhere in our file. 433 if o := int64(d.directoryOffset); o < 0 || o >= size { 434 return nil, ErrFormat 435 } 436 return d, nil 437 } 438 439 // findDirectory64End tries to read the zip64 locator just before the 440 // directory end and returns the offset of the zip64 directory end if 441 // found. 442 func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error) { 443 locOffset := directoryEndOffset - directory64LocLen 444 if locOffset < 0 { 445 return -1, nil // no need to look for a header outside the file 446 } 447 buf := make([]byte, directory64LocLen) 448 if _, err := r.ReadAt(buf, locOffset); err != nil { 449 return -1, err 450 } 451 b := readBuf(buf) 452 if sig := b.uint32(); sig != directory64LocSignature { 453 return -1, nil 454 } 455 if b.uint32() != 0 { // number of the disk with the start of the zip64 end of central directory 456 return -1, nil // the file is not a valid zip64-file 457 } 458 p := b.uint64() // relative offset of the zip64 end of central directory record 459 if b.uint32() != 1 { // total number of disks 460 return -1, nil // the file is not a valid zip64-file 461 } 462 return int64(p), nil 463 } 464 465 // readDirectory64End reads the zip64 directory end and updates the 466 // directory end with the zip64 directory end values. 467 func readDirectory64End(r io.ReaderAt, offset int64, d *directoryEnd) (err error) { 468 buf := make([]byte, directory64EndLen) 469 if _, err := r.ReadAt(buf, offset); err != nil { 470 return err 471 } 472 473 b := readBuf(buf) 474 if sig := b.uint32(); sig != directory64EndSignature { 475 return ErrFormat 476 } 477 478 b = b[12:] // skip dir size, version and version needed (uint64 + 2x uint16) 479 d.diskNbr = b.uint32() // number of this disk 480 d.dirDiskNbr = b.uint32() // number of the disk with the start of the central directory 481 d.dirRecordsThisDisk = b.uint64() // total number of entries in the central directory on this disk 482 d.directoryRecords = b.uint64() // total number of entries in the central directory 483 d.directorySize = b.uint64() // size of the central directory 484 d.directoryOffset = b.uint64() // offset of start of central directory with respect to the starting disk number 485 486 return nil 487 } 488 489 func findSignatureInBlock(b []byte) int { 490 for i := len(b) - directoryEndLen; i >= 0; i-- { 491 // defined from directoryEndSignature in struct.go 492 if b[i] == 'P' && b[i+1] == 'K' && b[i+2] == 0x05 && b[i+3] == 0x06 { 493 // n is length of comment 494 n := int(b[i+directoryEndLen-2]) | int(b[i+directoryEndLen-1])<<8 495 if n+directoryEndLen+i <= len(b) { 496 return i 497 } 498 } 499 } 500 return -1 501 } 502 503 type readBuf []byte 504 505 func (b *readBuf) uint16() uint16 { 506 v := binary.LittleEndian.Uint16(*b) 507 *b = (*b)[2:] 508 return v 509 } 510 511 func (b *readBuf) uint32() uint32 { 512 v := binary.LittleEndian.Uint32(*b) 513 *b = (*b)[4:] 514 return v 515 } 516 517 func (b *readBuf) uint64() uint64 { 518 v := binary.LittleEndian.Uint64(*b) 519 *b = (*b)[8:] 520 return v 521 }