github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/archive/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 "hash/crc32" 14 "io" 15 "os" 16 "time" 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), io.SeekStart); 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 func (z *Reader) RegisterDecompressor(method uint16, dcomp Decompressor) { 123 if z.decompressors == nil { 124 z.decompressors = make(map[uint16]Decompressor) 125 } 126 z.decompressors[method] = dcomp 127 } 128 129 func (z *Reader) decompressor(method uint16) Decompressor { 130 dcomp := z.decompressors[method] 131 if dcomp == nil { 132 dcomp = decompressor(method) 133 } 134 return dcomp 135 } 136 137 // Close closes the Zip file, rendering it unusable for I/O. 138 func (rc *ReadCloser) Close() error { 139 return rc.f.Close() 140 } 141 142 // DataOffset returns the offset of the file's possibly-compressed 143 // data, relative to the beginning of the zip file. 144 // 145 // Most callers should instead use Open, which transparently 146 // decompresses data and verifies checksums. 147 func (f *File) DataOffset() (offset int64, err error) { 148 bodyOffset, err := f.findBodyOffset() 149 if err != nil { 150 return 151 } 152 return f.headerOffset + bodyOffset, nil 153 } 154 155 // Open returns a ReadCloser that provides access to the File's contents. 156 // Multiple files may be read concurrently. 157 func (f *File) Open() (io.ReadCloser, error) { 158 bodyOffset, err := f.findBodyOffset() 159 if err != nil { 160 return nil, err 161 } 162 size := int64(f.CompressedSize64) 163 r := io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset, size) 164 dcomp := f.zip.decompressor(f.Method) 165 if dcomp == nil { 166 return nil, ErrAlgorithm 167 } 168 var rc io.ReadCloser = dcomp(r) 169 var desr io.Reader 170 if f.hasDataDescriptor() { 171 desr = io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset+size, dataDescriptorLen) 172 } 173 rc = &checksumReader{ 174 rc: rc, 175 hash: crc32.NewIEEE(), 176 f: f, 177 desr: desr, 178 } 179 return rc, nil 180 } 181 182 type checksumReader struct { 183 rc io.ReadCloser 184 hash hash.Hash32 185 nread uint64 // number of bytes read so far 186 f *File 187 desr io.Reader // if non-nil, where to read the data descriptor 188 err error // sticky error 189 } 190 191 func (r *checksumReader) Read(b []byte) (n int, err error) { 192 if r.err != nil { 193 return 0, r.err 194 } 195 n, err = r.rc.Read(b) 196 r.hash.Write(b[:n]) 197 r.nread += uint64(n) 198 if err == nil { 199 return 200 } 201 if err == io.EOF { 202 if r.nread != r.f.UncompressedSize64 { 203 return 0, io.ErrUnexpectedEOF 204 } 205 if r.desr != nil { 206 if err1 := readDataDescriptor(r.desr, r.f); err1 != nil { 207 if err1 == io.EOF { 208 err = io.ErrUnexpectedEOF 209 } else { 210 err = err1 211 } 212 } else if r.hash.Sum32() != r.f.CRC32 { 213 err = ErrChecksum 214 } 215 } else { 216 // If there's not a data descriptor, we still compare 217 // the CRC32 of what we've read against the file header 218 // or TOC's CRC32, if it seems like it was set. 219 if r.f.CRC32 != 0 && r.hash.Sum32() != r.f.CRC32 { 220 err = ErrChecksum 221 } 222 } 223 } 224 r.err = err 225 return 226 } 227 228 func (r *checksumReader) Close() error { return r.rc.Close() } 229 230 // findBodyOffset does the minimum work to verify the file has a header 231 // and returns the file body offset. 232 func (f *File) findBodyOffset() (int64, error) { 233 var buf [fileHeaderLen]byte 234 if _, err := f.zipr.ReadAt(buf[:], f.headerOffset); err != nil { 235 return 0, err 236 } 237 b := readBuf(buf[:]) 238 if sig := b.uint32(); sig != fileHeaderSignature { 239 return 0, ErrFormat 240 } 241 b = b[22:] // skip over most of the header 242 filenameLen := int(b.uint16()) 243 extraLen := int(b.uint16()) 244 return int64(fileHeaderLen + filenameLen + extraLen), nil 245 } 246 247 // readDirectoryHeader attempts to read a directory header from r. 248 // It returns io.ErrUnexpectedEOF if it cannot read a complete header, 249 // and ErrFormat if it doesn't find a valid header signature. 250 func readDirectoryHeader(f *File, r io.Reader) error { 251 var buf [directoryHeaderLen]byte 252 if _, err := io.ReadFull(r, buf[:]); err != nil { 253 return err 254 } 255 b := readBuf(buf[:]) 256 if sig := b.uint32(); sig != directoryHeaderSignature { 257 return ErrFormat 258 } 259 f.CreatorVersion = b.uint16() 260 f.ReaderVersion = b.uint16() 261 f.Flags = b.uint16() 262 f.Method = b.uint16() 263 f.ModifiedTime = b.uint16() 264 f.ModifiedDate = b.uint16() 265 f.CRC32 = b.uint32() 266 f.CompressedSize = b.uint32() 267 f.UncompressedSize = b.uint32() 268 f.CompressedSize64 = uint64(f.CompressedSize) 269 f.UncompressedSize64 = uint64(f.UncompressedSize) 270 filenameLen := int(b.uint16()) 271 extraLen := int(b.uint16()) 272 commentLen := int(b.uint16()) 273 b = b[4:] // skipped start disk number and internal attributes (2x uint16) 274 f.ExternalAttrs = b.uint32() 275 f.headerOffset = int64(b.uint32()) 276 d := make([]byte, filenameLen+extraLen+commentLen) 277 if _, err := io.ReadFull(r, d); err != nil { 278 return err 279 } 280 f.Name = string(d[:filenameLen]) 281 f.Extra = d[filenameLen : filenameLen+extraLen] 282 f.Comment = string(d[filenameLen+extraLen:]) 283 284 needUSize := f.UncompressedSize == ^uint32(0) 285 needCSize := f.CompressedSize == ^uint32(0) 286 needHeaderOffset := f.headerOffset == int64(^uint32(0)) 287 288 if len(f.Extra) > 0 { 289 // Best effort to find what we need. 290 // Other zip authors might not even follow the basic format, 291 // and we'll just ignore the Extra content in that case. 292 b := readBuf(f.Extra) 293 294 Extras: 295 for len(b) >= 4 { // need at least tag and size 296 tag := b.uint16() 297 size := b.uint16() 298 if int(size) > len(b) { 299 break 300 } 301 switch tag { 302 case 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 golang.org/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 Extras 331 332 case ntfsExtraId: 333 if size == 32 { 334 eb := readBuf(b[:size]) 335 eb.uint32() // reserved 336 eb.uint16() // tag1 337 size1 := eb.uint16() 338 if size1 == 24 { 339 sub := readBuf(eb[:size1]) 340 lo := sub.uint32() 341 hi := sub.uint32() 342 tick := (uint64(uint64(lo)|uint64(hi)<<32) - 116444736000000000) / 10000000 343 f.SetModTime(time.Unix(int64(tick), 0)) 344 } 345 } 346 break Extras 347 348 case unixExtraId: 349 if size >= 12 { 350 eb := readBuf(b[:size]) 351 eb.uint32() // AcTime 352 epoch := eb.uint32() // ModTime 353 f.SetModTime(time.Unix(int64(epoch), 0)) 354 break Extras 355 } 356 case exttsExtraId: 357 if size >= 3 { 358 eb := readBuf(b[:size]) 359 flags := eb.uint8() // Flags 360 epoch := eb.uint32() // AcTime/ModTime/CrTime 361 if flags&1 != 0 { 362 f.SetModTime(time.Unix(int64(epoch), 0)) 363 } 364 break Extras 365 } 366 } 367 b = b[size:] 368 } 369 } 370 371 // Assume that uncompressed size 2³²-1 could plausibly happen in 372 // an old zip32 file that was sharding inputs into the largest chunks 373 // possible (or is just malicious; search the web for 42.zip). 374 // If needUSize is true still, it means we didn't see a zip64 extension. 375 // As long as the compressed size is not also 2³²-1 (implausible) 376 // and the header is not also 2³²-1 (equally implausible), 377 // accept the uncompressed size 2³²-1 as valid. 378 // If nothing else, this keeps archive/zip working with 42.zip. 379 _ = needUSize 380 381 if needCSize || needHeaderOffset { 382 return ErrFormat 383 } 384 385 return nil 386 } 387 388 func readDataDescriptor(r io.Reader, f *File) error { 389 var buf [dataDescriptorLen]byte 390 391 // The spec says: "Although not originally assigned a 392 // signature, the value 0x08074b50 has commonly been adopted 393 // as a signature value for the data descriptor record. 394 // Implementers should be aware that ZIP files may be 395 // encountered with or without this signature marking data 396 // descriptors and should account for either case when reading 397 // ZIP files to ensure compatibility." 398 // 399 // dataDescriptorLen includes the size of the signature but 400 // first read just those 4 bytes to see if it exists. 401 if _, err := io.ReadFull(r, buf[:4]); err != nil { 402 return err 403 } 404 off := 0 405 maybeSig := readBuf(buf[:4]) 406 if maybeSig.uint32() != dataDescriptorSignature { 407 // No data descriptor signature. Keep these four 408 // bytes. 409 off += 4 410 } 411 if _, err := io.ReadFull(r, buf[off:12]); err != nil { 412 return err 413 } 414 b := readBuf(buf[:12]) 415 if b.uint32() != f.CRC32 { 416 return ErrChecksum 417 } 418 419 // The two sizes that follow here can be either 32 bits or 64 bits 420 // but the spec is not very clear on this and different 421 // interpretations has been made causing incompatibilities. We 422 // already have the sizes from the central directory so we can 423 // just ignore these. 424 425 return nil 426 } 427 428 func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err error) { 429 // look for directoryEndSignature in the last 1k, then in the last 65k 430 var buf []byte 431 var directoryEndOffset int64 432 for i, bLen := range []int64{1024, 65 * 1024} { 433 if bLen > size { 434 bLen = size 435 } 436 buf = make([]byte, int(bLen)) 437 if _, err := r.ReadAt(buf, size-bLen); err != nil && err != io.EOF { 438 return nil, err 439 } 440 if p := findSignatureInBlock(buf); p >= 0 { 441 buf = buf[p:] 442 directoryEndOffset = size - bLen + int64(p) 443 break 444 } 445 if i == 1 || bLen == size { 446 return nil, ErrFormat 447 } 448 } 449 450 // read header into struct 451 b := readBuf(buf[4:]) // skip signature 452 d := &directoryEnd{ 453 diskNbr: uint32(b.uint16()), 454 dirDiskNbr: uint32(b.uint16()), 455 dirRecordsThisDisk: uint64(b.uint16()), 456 directoryRecords: uint64(b.uint16()), 457 directorySize: uint64(b.uint32()), 458 directoryOffset: uint64(b.uint32()), 459 commentLen: b.uint16(), 460 } 461 l := int(d.commentLen) 462 if l > len(b) { 463 return nil, errors.New("zip: invalid comment length") 464 } 465 d.comment = string(b[:l]) 466 467 // These values mean that the file can be a zip64 file 468 if d.directoryRecords == 0xffff || d.directorySize == 0xffff || d.directoryOffset == 0xffffffff { 469 p, err := findDirectory64End(r, directoryEndOffset) 470 if err == nil && p >= 0 { 471 err = readDirectory64End(r, p, d) 472 } 473 if err != nil { 474 return nil, err 475 } 476 } 477 // Make sure directoryOffset points to somewhere in our file. 478 if o := int64(d.directoryOffset); o < 0 || o >= size { 479 return nil, ErrFormat 480 } 481 return d, nil 482 } 483 484 // findDirectory64End tries to read the zip64 locator just before the 485 // directory end and returns the offset of the zip64 directory end if 486 // found. 487 func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error) { 488 locOffset := directoryEndOffset - directory64LocLen 489 if locOffset < 0 { 490 return -1, nil // no need to look for a header outside the file 491 } 492 buf := make([]byte, directory64LocLen) 493 if _, err := r.ReadAt(buf, locOffset); err != nil { 494 return -1, err 495 } 496 b := readBuf(buf) 497 if sig := b.uint32(); sig != directory64LocSignature { 498 return -1, nil 499 } 500 if b.uint32() != 0 { // number of the disk with the start of the zip64 end of central directory 501 return -1, nil // the file is not a valid zip64-file 502 } 503 p := b.uint64() // relative offset of the zip64 end of central directory record 504 if b.uint32() != 1 { // total number of disks 505 return -1, nil // the file is not a valid zip64-file 506 } 507 return int64(p), nil 508 } 509 510 // readDirectory64End reads the zip64 directory end and updates the 511 // directory end with the zip64 directory end values. 512 func readDirectory64End(r io.ReaderAt, offset int64, d *directoryEnd) (err error) { 513 buf := make([]byte, directory64EndLen) 514 if _, err := r.ReadAt(buf, offset); err != nil { 515 return err 516 } 517 518 b := readBuf(buf) 519 if sig := b.uint32(); sig != directory64EndSignature { 520 return ErrFormat 521 } 522 523 b = b[12:] // skip dir size, version and version needed (uint64 + 2x uint16) 524 d.diskNbr = b.uint32() // number of this disk 525 d.dirDiskNbr = b.uint32() // number of the disk with the start of the central directory 526 d.dirRecordsThisDisk = b.uint64() // total number of entries in the central directory on this disk 527 d.directoryRecords = b.uint64() // total number of entries in the central directory 528 d.directorySize = b.uint64() // size of the central directory 529 d.directoryOffset = b.uint64() // offset of start of central directory with respect to the starting disk number 530 531 return nil 532 } 533 534 func findSignatureInBlock(b []byte) int { 535 for i := len(b) - directoryEndLen; i >= 0; i-- { 536 // defined from directoryEndSignature in struct.go 537 if b[i] == 'P' && b[i+1] == 'K' && b[i+2] == 0x05 && b[i+3] == 0x06 { 538 // n is length of comment 539 n := int(b[i+directoryEndLen-2]) | int(b[i+directoryEndLen-1])<<8 540 if n+directoryEndLen+i <= len(b) { 541 return i 542 } 543 } 544 } 545 return -1 546 } 547 548 type readBuf []byte 549 550 func (b *readBuf) uint8() uint8 { 551 v := uint8((*b)[0]) 552 *b = (*b)[1:] 553 return v 554 } 555 556 func (b *readBuf) uint16() uint16 { 557 v := binary.LittleEndian.Uint16(*b) 558 *b = (*b)[2:] 559 return v 560 } 561 562 func (b *readBuf) uint32() uint32 { 563 v := binary.LittleEndian.Uint32(*b) 564 *b = (*b)[4:] 565 return v 566 } 567 568 func (b *readBuf) uint64() uint64 { 569 v := binary.LittleEndian.Uint64(*b) 570 *b = (*b)[8:] 571 return v 572 }