Debian Codegraph @

zip/reader.go

raw
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 "hash"
12 "hash/crc32"
13 "io"
14 "io/fs"
15 "os"
16 "path"
17 "path/filepath"
18 "sort"
19 "strings"
20 "sync"
21 "time"
22
23 "github.com/klauspost/compress/internal/godebug"
24 )
25
26 var (
27 ErrFormat = errors.New("zip: not a valid zip file")
28 ErrAlgorithm = errors.New("zip: unsupported compression algorithm")
29 ErrChecksum = errors.New("zip: checksum error")
30 ErrInsecurePath = errors.New("zip: insecure file path")
31 )
32
33 // A Reader serves content from a ZIP archive.
34 type Reader struct {
35 r io.ReaderAt
36 File []*File
37 Comment string
38 decompressors map[uint16]Decompressor
39
40 // nameDecoder, if non-nil, rewrites Name/Comment from a legacy encoding
41 // into UTF-8 before encoding detection runs. It is set via NewReaderWithOptions.
42 nameDecoder func(f *FileHeader) error
43
44 // Some JAR files are zip files with a prefix that is a bash script.
45 // The baseOffset field is the start of the zip file proper.
46 baseOffset int64
47
48 // fileList is a list of files sorted by ename,
49 // for use by the Open method.
50 fileListOnce sync.Once
51 fileList []fileListEntry
52 }
53
54 // A ReadCloser is a [Reader] that must be closed when no longer needed.
55 type ReadCloser struct {
56 f *os.File
57 Reader
58 }
59
60 // A File is a single file in a ZIP archive.
61 // The file information is in the embedded [FileHeader].
62 // The file content can be accessed by calling [File.Open].
63 type File struct {
64 FileHeader
65 zip *Reader
66 zipr io.ReaderAt
67 headerOffset int64 // includes overall ZIP archive baseOffset
68 zip64 bool // zip64 extended information extra field presence
69 }
70
71 // OpenReader will open the Zip file specified by name and return a ReadCloser.
72 //
73 // If any file inside the archive uses a non-local name
74 // (as defined by [filepath.IsLocal]) or a name containing backslashes
75 // and the GODEBUG environment variable contains `zipinsecurepath=0`,
76 // OpenReader returns the reader with an ErrInsecurePath error.
77 // A future version of Go may introduce this behavior by default.
78 // Programs that want to accept non-local names can ignore
79 // the ErrInsecurePath error and use the returned reader.
80 func OpenReader(name string) (*ReadCloser, error) {
81 f, err := os.Open(name)
82 if err != nil {
83 return nil, err
84 }
85 fi, err := f.Stat()
86 if err != nil {
87 f.Close()
88 return nil, err
89 }
90 r := new(ReadCloser)
91 if err = r.init(f, fi.Size()); err != nil && err != ErrInsecurePath {
92 f.Close()
93 return nil, err
94 }
95 r.f = f
96 return r, err
97 }
98
99 // NewReader returns a new [Reader] reading from r, which is assumed to
100 // have the given size in bytes.
101 //
102 // If any file inside the archive uses a non-local name
103 // (as defined by [filepath.IsLocal]) or a name containing backslashes
104 // and the GODEBUG environment variable contains `zipinsecurepath=0`,
105 // NewReader returns the reader with an [ErrInsecurePath] error.
106 // A future version of Go may introduce this behavior by default.
107 // Programs that want to accept non-local names can ignore
108 // the [ErrInsecurePath] error and use the returned reader.
109 func NewReader(r io.ReaderAt, size int64) (*Reader, error) {
110 if size < 0 {
111 return nil, errors.New("zip: size cannot be negative")
112 }
113 zr := new(Reader)
114 var err error
115 if err = zr.init(r, size); err != nil && err != ErrInsecurePath {
116 return nil, err
117 }
118 return zr, err
119 }
120
121 // ReaderOptions holds optional knobs for [NewReaderWithOptions]. The zero
122 // value is equivalent to calling [NewReader]. New fields may be added in the
123 // future; callers should set only the options they need.
124 type ReaderOptions struct {
125 // NameDecoder, if non-nil, is invoked for each entry as its directory
126 // header is read, before UTF-8 encoding detection runs. The callback may
127 // rewrite Name and Comment to convert from a legacy encoding into UTF-8.
128 // If NameDecoder returns a non-nil error, archive reading stops and the
129 // error is returned.
130 NameDecoder func(f *FileHeader) error
131 }
132
133 // NewReaderWithOptions is like [NewReader] but applies the supplied options.
134 func NewReaderWithOptions(r io.ReaderAt, size int64, opts ReaderOptions) (*Reader, error) {
135 if size < 0 {
136 return nil, errors.New("zip: size cannot be negative")
137 }
138 zr := &Reader{nameDecoder: opts.NameDecoder}
139 var err error
140 if err = zr.init(r, size); err != nil && err != ErrInsecurePath {
141 return nil, err
142 }
143 return zr, err
144 }
145
146 func (r *Reader) init(rdr io.ReaderAt, size int64) error {
147 end, baseOffset, err := readDirectoryEnd(rdr, size)
148 if err != nil {
149 return err
150 }
151 r.r = rdr
152 r.baseOffset = baseOffset
153 // Since the number of directory records is not validated, it is not
154 // safe to preallocate r.File without first checking that the specified
155 // number of files is reasonable, since a malformed archive may
156 // indicate it contains up to 1 << 128 - 1 files. Since each file has a
157 // header which will be _at least_ 30 bytes we can safely preallocate
158 // if (data size / 30) >= end.directoryRecords.
159 if end.directorySize < uint64(size) && (uint64(size)-end.directorySize)/30 >= end.directoryRecords {
160 r.File = make([]*File, 0, end.directoryRecords)
161 }
162 r.Comment = end.comment
163 rs := io.NewSectionReader(rdr, 0, size)
164 if _, err = rs.Seek(r.baseOffset+int64(end.directoryOffset), io.SeekStart); err != nil {
165 return err
166 }
167 buf := bufio.NewReader(rs)
168
169 // Get once
170 zipinsecurepath := godebug.Get("zipinsecurepath") == "0"
171
172 // The count of files inside a zip is truncated to fit in a uint16.
173 // Gloss over this by reading headers until we encounter
174 // a bad one, and then only report an ErrFormat or UnexpectedEOF if
175 // the file count modulo 65536 is incorrect.
176 for {
177 f := &File{zip: r, zipr: rdr}
178 err = readDirectoryHeader(f, buf)
179 if err == ErrFormat || err == io.ErrUnexpectedEOF {
180 break
181 }
182 if err != nil {
183 return err
184 }
185 f.headerOffset += r.baseOffset
186 r.File = append(r.File, f)
187 }
188 if uint16(len(r.File)) != uint16(end.directoryRecords) { // only compare 16 bits here
189 // Return the readDirectoryHeader error if we read
190 // the wrong number of directory entries.
191 return err
192 }
193 if zipinsecurepath {
194 for _, f := range r.File {
195 if f.Name == "" {
196 // Zip permits an empty file name field.
197 continue
198 }
199 // The zip specification states that names must use forward slashes,
200 // so consider any backslashes in the name insecure.
201 if !filepath.IsLocal(f.Name) || strings.Contains(f.Name, `\`) {
202 return ErrInsecurePath
203 }
204 }
205 }
206 return nil
207 }
208
209 // RegisterDecompressor registers or overrides a custom decompressor for a
210 // specific method ID. If a decompressor for a given method is not found,
211 // [Reader] will default to looking up the decompressor at the package level.
212 func (r *Reader) RegisterDecompressor(method uint16, dcomp Decompressor) {
213 if r.decompressors == nil {
214 r.decompressors = make(map[uint16]Decompressor)
215 }
216 r.decompressors[method] = dcomp
217 }
218
219 func (r *Reader) decompressor(method uint16) Decompressor {
220 dcomp := r.decompressors[method]
221 if dcomp == nil {
222 dcomp = decompressor(method)
223 }
224 return dcomp
225 }
226
227 // Close closes the Zip file, rendering it unusable for I/O.
228 func (rc *ReadCloser) Close() error {
229 return rc.f.Close()
230 }
231
232 // DataOffset returns the offset of the file's possibly-compressed
233 // data, relative to the beginning of the zip file.
234 //
235 // Most callers should instead use [File.Open], which transparently
236 // decompresses data and verifies checksums.
237 func (f *File) DataOffset() (offset int64, err error) {
238 bodyOffset, err := f.findBodyOffset()
239 if err != nil {
240 return
241 }
242 return f.headerOffset + bodyOffset, nil
243 }
244
245 // Open returns a [ReadCloser] that provides access to the [File]'s contents.
246 // Multiple files may be read concurrently.
247 func (f *File) Open() (io.ReadCloser, error) {
248 bodyOffset, err := f.findBodyOffset()
249 if err != nil {
250 return nil, err
251 }
252 if strings.HasSuffix(f.Name, "/") {
253 // The ZIP specification (APPNOTE.TXT) specifies that directories, which
254 // are technically zero-byte files, must not have any associated file
255 // data. We previously tried failing here if f.CompressedSize64 != 0,
256 // but it turns out that a number of implementations (namely, the Java
257 // jar tool) don't properly set the storage method on directories
258 // resulting in a file with compressed size > 0 but uncompressed size ==
259 // 0. We still want to fail when a directory has associated uncompressed
260 // data, but we are tolerant of cases where the uncompressed size is
261 // zero but compressed size is not.
262 if f.UncompressedSize64 != 0 {
263 return &dirReader{ErrFormat}, nil
264 } else {
265 return &dirReader{io.EOF}, nil
266 }
267 }
268 size := int64(f.CompressedSize64)
269 r := io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset, size)
270 dcomp := f.zip.decompressor(f.Method)
271 if dcomp == nil {
272 return nil, ErrAlgorithm
273 }
274 var rc io.ReadCloser = dcomp(r)
275 var desr io.Reader
276 if f.hasDataDescriptor() {
277 desr = io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset+size, dataDescriptorLen)
278 }
279 rc = &checksumReader{
280 rc: rc,
281 hash: crc32.NewIEEE(),
282 f: f,
283 desr: desr,
284 }
285 return rc, nil
286 }
287
288 // OpenRaw returns a [Reader] that provides access to the [File]'s contents without
289 // decompression.
290 func (f *File) OpenRaw() (io.Reader, error) {
291 bodyOffset, err := f.findBodyOffset()
292 if err != nil {
293 return nil, err
294 }
295 r := io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset, int64(f.CompressedSize64))
296 return r, nil
297 }
298
299 type dirReader struct {
300 err error
301 }
302
303 func (r *dirReader) Read([]byte) (int, error) {
304 return 0, r.err
305 }
306
307 func (r *dirReader) Close() error {
308 return nil
309 }
310
311 type checksumReader struct {
312 rc io.ReadCloser
313 hash hash.Hash32
314 nread uint64 // number of bytes read so far
315 f *File
316 desr io.Reader // if non-nil, where to read the data descriptor
317 err error // sticky error
318 }
319
320 func (r *checksumReader) Stat() (fs.FileInfo, error) {
321 return headerFileInfo{&r.f.FileHeader}, nil
322 }
323
324 func (r *checksumReader) Read(b []byte) (n int, err error) {
325 if r.err != nil {
326 return 0, r.err
327 }
328 n, err = r.rc.Read(b)
329 r.hash.Write(b[:n])
330 r.nread += uint64(n)
331 if r.nread > r.f.UncompressedSize64 {
332 return 0, ErrFormat
333 }
334 if err == nil {
335 return
336 }
337 if err == io.EOF {
338 if r.nread != r.f.UncompressedSize64 {
339 return 0, io.ErrUnexpectedEOF
340 }
341 if r.desr != nil {
342 if err1 := readDataDescriptor(r.desr, r.f); err1 != nil {
343 if err1 == io.EOF {
344 err = io.ErrUnexpectedEOF
345 } else {
346 err = err1
347 }
348 } else if r.hash.Sum32() != r.f.CRC32 {
349 err = ErrChecksum
350 }
351 } else {
352 // If there's not a data descriptor, we still compare
353 // the CRC32 of what we've read against the file header
354 // or TOC's CRC32, if it seems like it was set.
355 if r.f.CRC32 != 0 && r.hash.Sum32() != r.f.CRC32 {
356 err = ErrChecksum
357 }
358 }
359 }
360 r.err = err
361 return
362 }
363
364 func (r *checksumReader) Close() error { return r.rc.Close() }
365
366 // findBodyOffset does the minimum work to verify the file has a header
367 // and returns the file body offset.
368 func (f *File) findBodyOffset() (int64, error) {
369 var buf [fileHeaderLen]byte
370 if _, err := f.zipr.ReadAt(buf[:], f.headerOffset); err != nil {
371 return 0, err
372 }
373 b := readBuf(buf[:])
374 if sig := b.uint32(); sig != fileHeaderSignature {
375 return 0, ErrFormat
376 }
377 b = b[22:] // skip over most of the header
378 filenameLen := int(b.uint16())
379 extraLen := int(b.uint16())
380 return int64(fileHeaderLen + filenameLen + extraLen), nil
381 }
382
383 // readDirectoryHeader attempts to read a directory header from r.
384 // It returns io.ErrUnexpectedEOF if it cannot read a complete header,
385 // and ErrFormat if it doesn't find a valid header signature.
386 func readDirectoryHeader(f *File, r io.Reader) error {
387 var buf [directoryHeaderLen]byte
388 if _, err := io.ReadFull(r, buf[:]); err != nil {
389 return err
390 }
391 b := readBuf(buf[:])
392 if sig := b.uint32(); sig != directoryHeaderSignature {
393 return ErrFormat
394 }
395 f.CreatorVersion = b.uint16()
396 f.ReaderVersion = b.uint16()
397 f.Flags = b.uint16()
398 f.Method = b.uint16()
399 f.ModifiedTime = b.uint16()
400 f.ModifiedDate = b.uint16()
401 f.CRC32 = b.uint32()
402 f.CompressedSize = b.uint32()
403 f.UncompressedSize = b.uint32()
404 f.CompressedSize64 = uint64(f.CompressedSize)
405 f.UncompressedSize64 = uint64(f.UncompressedSize)
406 filenameLen := int(b.uint16())
407 extraLen := int(b.uint16())
408 commentLen := int(b.uint16())
409 b = b[4:] // skipped start disk number and internal attributes (2x uint16)
410 f.ExternalAttrs = b.uint32()
411 f.headerOffset = int64(b.uint32())
412 d := make([]byte, filenameLen+extraLen+commentLen)
413 if _, err := io.ReadFull(r, d); err != nil {
414 return err
415 }
416 f.Name = string(d[:filenameLen])
417 f.Extra = d[filenameLen : filenameLen+extraLen]
418 f.Comment = string(d[filenameLen+extraLen:])
419
420 // Allow the user to rewrite Name/Comment from a legacy encoding into
421 // UTF-8 before encoding detection runs.
422 if f.zip != nil && f.zip.nameDecoder != nil {
423 if err := f.zip.nameDecoder(&f.FileHeader); err != nil {
424 return err
425 }
426 }
427
428 // Determine the character encoding.
429 utf8Valid1, utf8Require1 := detectUTF8(f.Name)
430 utf8Valid2, utf8Require2 := detectUTF8(f.Comment)
431 switch {
432 case !utf8Valid1 || !utf8Valid2:
433 // Name and Comment definitely not UTF-8.
434 f.NonUTF8 = true
435 case !utf8Require1 && !utf8Require2:
436 // Name and Comment use only single-byte runes that overlap with UTF-8.
437 f.NonUTF8 = false
438 default:
439 // Might be UTF-8, might be some other encoding; preserve existing flag.
440 // Some ZIP writers use UTF-8 encoding without setting the UTF-8 flag.
441 // Since it is impossible to always distinguish valid UTF-8 from some
442 // other encoding (e.g., GBK or Shift-JIS), we trust the flag.
443 f.NonUTF8 = f.Flags&0x800 == 0
444 }
445
446 needUSize := f.UncompressedSize == ^uint32(0)
447 needCSize := f.CompressedSize == ^uint32(0)
448 needHeaderOffset := f.headerOffset == int64(^uint32(0))
449
450 // Best effort to find what we need.
451 // Other zip authors might not even follow the basic format,
452 // and we'll just ignore the Extra content in that case.
453 var modified time.Time
454 parseExtras:
455 for extra := readBuf(f.Extra); len(extra) >= 4; { // need at least tag and size
456 fieldTag := extra.uint16()
457 fieldSize := int(extra.uint16())
458 if len(extra) < fieldSize {
459 break
460 }
461 fieldBuf := extra.sub(fieldSize)
462
463 switch fieldTag {
464 case zip64ExtraID:
465 f.zip64 = true
466
467 // update directory values from the zip64 extra block.
468 // They should only be consulted if the sizes read earlier
469 // are maxed out.
470 // See golang.org/issue/13367.
471 if needUSize {
472 needUSize = false
473 if len(fieldBuf) < 8 {
474 return ErrFormat
475 }
476 f.UncompressedSize64 = fieldBuf.uint64()
477 }
478 if needCSize {
479 needCSize = false
480 if len(fieldBuf) < 8 {
481 return ErrFormat
482 }
483 f.CompressedSize64 = fieldBuf.uint64()
484 }
485 if needHeaderOffset {
486 needHeaderOffset = false
487 if len(fieldBuf) < 8 {
488 return ErrFormat
489 }
490 f.headerOffset = int64(fieldBuf.uint64())
491 }
492 case ntfsExtraID:
493 if len(fieldBuf) < 4 {
494 continue parseExtras
495 }
496 fieldBuf.uint32() // reserved (ignored)
497 for len(fieldBuf) >= 4 { // need at least tag and size
498 attrTag := fieldBuf.uint16()
499 attrSize := int(fieldBuf.uint16())
500 if len(fieldBuf) < attrSize {
501 continue parseExtras
502 }
503 attrBuf := fieldBuf.sub(attrSize)
504 if attrTag != 1 || attrSize != 24 {
505 continue // Ignore irrelevant attributes
506 }
507
508 const ticksPerSecond = 1e7 // Windows timestamp resolution
509 ts := int64(attrBuf.uint64()) // ModTime since Windows epoch
510 secs := ts / ticksPerSecond
511 nsecs := (1e9 / ticksPerSecond) * (ts % ticksPerSecond)
512 epoch := time.Date(1601, time.January, 1, 0, 0, 0, 0, time.UTC)
513 modified = time.Unix(epoch.Unix()+secs, nsecs)
514 }
515 case unixExtraID, infoZipUnixExtraID:
516 if len(fieldBuf) < 8 {
517 continue parseExtras
518 }
519 fieldBuf.uint32() // AcTime (ignored)
520 ts := int64(fieldBuf.uint32()) // ModTime since Unix epoch
521 modified = time.Unix(ts, 0)
522 case extTimeExtraID:
523 if len(fieldBuf) < 5 || fieldBuf.uint8()&1 == 0 {
524 continue parseExtras
525 }
526 ts := int64(fieldBuf.uint32()) // ModTime since Unix epoch
527 modified = time.Unix(ts, 0)
528 }
529 }
530
531 msdosModified := msDosTimeToTime(f.ModifiedDate, f.ModifiedTime)
532 f.Modified = msdosModified
533 if !modified.IsZero() {
534 f.Modified = modified.UTC()
535
536 // If legacy MS-DOS timestamps are set, we can use the delta between
537 // the legacy and extended versions to estimate timezone offset.
538 //
539 // A non-UTC timezone is always used (even if offset is zero).
540 // Thus, FileHeader.Modified.Location() == time.UTC is useful for
541 // determining whether extended timestamps are present.
542 // This is necessary for users that need to do additional time
543 // calculations when dealing with legacy ZIP formats.
544 if f.ModifiedTime != 0 || f.ModifiedDate != 0 {
545 f.Modified = modified.In(timeZone(msdosModified.Sub(modified)))
546 }
547 }
548
549 // Assume that uncompressed size 2³²-1 could plausibly happen in
550 // an old zip32 file that was sharding inputs into the largest chunks
551 // possible (or is just malicious; search the web for 42.zip).
552 // If needUSize is true still, it means we didn't see a zip64 extension.
553 // As long as the compressed size is not also 2³²-1 (implausible)
554 // and the header is not also 2³²-1 (equally implausible),
555 // accept the uncompressed size 2³²-1 as valid.
556 // If nothing else, this keeps archive/zip working with 42.zip.
557 _ = needUSize
558
559 if needCSize || needHeaderOffset {
560 return ErrFormat
561 }
562
563 return nil
564 }
565
566 func readDataDescriptor(r io.Reader, f *File) error {
567 var buf [dataDescriptorLen]byte
568 // The spec says: "Although not originally assigned a
569 // signature, the value 0x08074b50 has commonly been adopted
570 // as a signature value for the data descriptor record.
571 // Implementers should be aware that ZIP files may be
572 // encountered with or without this signature marking data
573 // descriptors and should account for either case when reading
574 // ZIP files to ensure compatibility."
575 //
576 // dataDescriptorLen includes the size of the signature but
577 // first read just those 4 bytes to see if it exists.
578 if _, err := io.ReadFull(r, buf[:4]); err != nil {
579 return err
580 }
581 off := 0
582 maybeSig := readBuf(buf[:4])
583 if maybeSig.uint32() != dataDescriptorSignature {
584 // No data descriptor signature. Keep these four
585 // bytes.
586 off += 4
587 }
588 if _, err := io.ReadFull(r, buf[off:12]); err != nil {
589 return err
590 }
591 b := readBuf(buf[:12])
592 if b.uint32() != f.CRC32 {
593 return ErrChecksum
594 }
595
596 // The two sizes that follow here can be either 32 bits or 64 bits
597 // but the spec is not very clear on this and different
598 // interpretations has been made causing incompatibilities. We
599 // already have the sizes from the central directory so we can
600 // just ignore these.
601
602 return nil
603 }
604
605 func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, baseOffset int64, err error) {
606 // look for directoryEndSignature in the last 1k, then in the last 65k
607 var buf []byte
608 var directoryEndOffset int64
609 for i, bLen := range []int64{1024, 65 * 1024} {
610 if bLen > size {
611 bLen = size
612 }
613 buf = make([]byte, int(bLen))
614 if _, err := r.ReadAt(buf, size-bLen); err != nil && err != io.EOF {
615 return nil, 0, err
616 }
617 if p := findSignatureInBlock(buf); p >= 0 {
618 buf = buf[p:]
619 directoryEndOffset = size - bLen + int64(p)
620 break
621 }
622 if i == 1 || bLen == size {
623 return nil, 0, ErrFormat
624 }
625 }
626
627 // read header into struct
628 b := readBuf(buf[4:]) // skip signature
629 d := &directoryEnd{
630 diskNbr: uint32(b.uint16()),
631 dirDiskNbr: uint32(b.uint16()),
632 dirRecordsThisDisk: uint64(b.uint16()),
633 directoryRecords: uint64(b.uint16()),
634 directorySize: uint64(b.uint32()),
635 directoryOffset: uint64(b.uint32()),
636 commentLen: b.uint16(),
637 }
638 l := int(d.commentLen)
639 if l > len(b) {
640 return nil, 0, errors.New("zip: invalid comment length")
641 }
642 d.comment = string(b[:l])
643
644 // These values mean that the file can be a zip64 file
645 if d.directoryRecords == 0xffff || d.directorySize == 0xffff || d.directoryOffset == 0xffffffff {
646 p, err := findDirectory64End(r, directoryEndOffset)
647 if err == nil && p >= 0 {
648 directoryEndOffset = p
649 err = readDirectory64End(r, p, d)
650 }
651 if err != nil {
652 return nil, 0, err
653 }
654 }
655
656 maxInt64 := uint64(1<<63 - 1)
657 if d.directorySize > maxInt64 || d.directoryOffset > maxInt64 {
658 return nil, 0, ErrFormat
659 }
660
661 baseOffset = directoryEndOffset - int64(d.directorySize) - int64(d.directoryOffset)
662
663 // Make sure directoryOffset points to somewhere in our file.
664 if o := baseOffset + int64(d.directoryOffset); o < 0 || o >= size {
665 return nil, 0, ErrFormat
666 }
667
668 // If the directory end data tells us to use a non-zero baseOffset,
669 // but we would find a valid directory entry if we assume that the
670 // baseOffset is 0, then just use a baseOffset of 0.
671 // We've seen files in which the directory end data gives us
672 // an incorrect baseOffset.
673 if baseOffset > 0 {
674 off := int64(d.directoryOffset)
675 rs := io.NewSectionReader(r, off, size-off)
676 if readDirectoryHeader(&File{}, rs) == nil {
677 baseOffset = 0
678 }
679 }
680
681 return d, baseOffset, nil
682 }
683
684 // findDirectory64End tries to read the zip64 locator just before the
685 // directory end and returns the offset of the zip64 directory end if
686 // found.
687 func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error) {
688 locOffset := directoryEndOffset - directory64LocLen
689 if locOffset < 0 {
690 return -1, nil // no need to look for a header outside the file
691 }
692 buf := make([]byte, directory64LocLen)
693 if _, err := r.ReadAt(buf, locOffset); err != nil {
694 return -1, err
695 }
696 b := readBuf(buf)
697 if sig := b.uint32(); sig != directory64LocSignature {
698 return -1, nil
699 }
700 if b.uint32() != 0 { // number of the disk with the start of the zip64 end of central directory
701 return -1, nil // the file is not a valid zip64-file
702 }
703 p := b.uint64() // relative offset of the zip64 end of central directory record
704 if b.uint32() != 1 { // total number of disks
705 return -1, nil // the file is not a valid zip64-file
706 }
707 return int64(p), nil
708 }
709
710 // readDirectory64End reads the zip64 directory end and updates the
711 // directory end with the zip64 directory end values.
712 func readDirectory64End(r io.ReaderAt, offset int64, d *directoryEnd) (err error) {
713 buf := make([]byte, directory64EndLen)
714 if _, err := r.ReadAt(buf, offset); err != nil {
715 return err
716 }
717
718 b := readBuf(buf)
719 if sig := b.uint32(); sig != directory64EndSignature {
720 return ErrFormat
721 }
722
723 b = b[12:] // skip dir size, version and version needed (uint64 + 2x uint16)
724 d.diskNbr = b.uint32() // number of this disk
725 d.dirDiskNbr = b.uint32() // number of the disk with the start of the central directory
726 d.dirRecordsThisDisk = b.uint64() // total number of entries in the central directory on this disk
727 d.directoryRecords = b.uint64() // total number of entries in the central directory
728 d.directorySize = b.uint64() // size of the central directory
729 d.directoryOffset = b.uint64() // offset of start of central directory with respect to the starting disk number
730
731 return nil
732 }
733
734 func findSignatureInBlock(b []byte) int {
735 for i := len(b) - directoryEndLen; i >= 0; i-- {
736 // defined from directoryEndSignature in struct.go
737 if b[i] == 'P' && b[i+1] == 'K' && b[i+2] == 0x05 && b[i+3] == 0x06 {
738 // n is length of comment
739 n := int(b[i+directoryEndLen-2]) | int(b[i+directoryEndLen-1])<<8
740 if n+directoryEndLen+i > len(b) {
741 // Truncated comment.
742 // Some parsers (such as Info-ZIP) ignore the truncated comment
743 // rather than treating it as a hard error.
744 return -1
745 }
746 return i
747 }
748 }
749 return -1
750 }
751
752 type readBuf []byte
753
754 func (b *readBuf) uint8() uint8 {
755 v := (*b)[0]
756 *b = (*b)[1:]
757 return v
758 }
759
760 func (b *readBuf) uint16() uint16 {
761 v := binary.LittleEndian.Uint16(*b)
762 *b = (*b)[2:]
763 return v
764 }
765
766 func (b *readBuf) uint32() uint32 {
767 v := binary.LittleEndian.Uint32(*b)
768 *b = (*b)[4:]
769 return v
770 }
771
772 func (b *readBuf) uint64() uint64 {
773 v := binary.LittleEndian.Uint64(*b)
774 *b = (*b)[8:]
775 return v
776 }
777
778 func (b *readBuf) sub(n int) readBuf {
779 b2 := (*b)[:n]
780 *b = (*b)[n:]
781 return b2
782 }
783
784 // A fileListEntry is a File and its ename.
785 // If file == nil, the fileListEntry describes a directory without metadata.
786 type fileListEntry struct {
787 name string
788 file *File
789 isDir bool
790 isDup bool
791 }
792
793 type fileInfoDirEntry interface {
794 fs.FileInfo
795 fs.DirEntry
796 }
797
798 func (f *fileListEntry) stat() (fileInfoDirEntry, error) {
799 if f.isDup {
800 return nil, errors.New(f.name + ": duplicate entries in zip file")
801 }
802 if !f.isDir {
803 return headerFileInfo{&f.file.FileHeader}, nil
804 }
805 return f, nil
806 }
807
808 // Only used for directories.
809 func (f *fileListEntry) Name() string { _, elem, _ := split(f.name); return elem }
810 func (f *fileListEntry) Size() int64 { return 0 }
811 func (f *fileListEntry) Mode() fs.FileMode { return fs.ModeDir | 0555 }
812 func (f *fileListEntry) Type() fs.FileMode { return fs.ModeDir }
813 func (f *fileListEntry) IsDir() bool { return true }
814 func (f *fileListEntry) Sys() any { return nil }
815
816 func (f *fileListEntry) ModTime() time.Time {
817 if f.file == nil {
818 return time.Time{}
819 }
820 return f.file.FileHeader.Modified.UTC()
821 }
822
823 func (f *fileListEntry) Info() (fs.FileInfo, error) { return f, nil }
824
825 func (f *fileListEntry) String() string {
826 return formatDirEntry(f)
827 }
828
829 // formatDirEntry returns a formatted version of dir for human readability.
830 // Implementations of [DirEntry] can call this from a String method.
831 // The outputs for a directory named subdir and a file named hello.go are:
832 //
833 // d subdir/
834 // - hello.go
835 //
836 // TODO: Use fs.FormatDirEntry when Go 1.20 is no longer supported
837 func formatDirEntry(dir fs.DirEntry) string {
838 name := dir.Name()
839 b := make([]byte, 0, 5+len(name))
840
841 // The Type method does not return any permission bits,
842 // so strip them from the string.
843 mode := dir.Type().String()
844 mode = mode[:len(mode)-9]
845
846 b = append(b, mode...)
847 b = append(b, ' ')
848 b = append(b, name...)
849 if dir.IsDir() {
850 b = append(b, '/')
851 }
852 return string(b)
853 }
854
855 // formatFileInfo returns a formatted version of info for human readability.
856 // Implementations of [FileInfo] can call this from a String method.
857 // The output for a file named "hello.go", 100 bytes, mode 0o644, created
858 // January 1, 1970 at noon is
859 //
860 // -rw-r--r-- 100 1970-01-01 12:00:00 hello.go
861 //
862 // TODO: Use fs.FormatFileInfo when Go 1.20 is no longer supported
863 func formatFileInfo(info fs.FileInfo) string {
864 name := info.Name()
865 b := make([]byte, 0, 40+len(name))
866 b = append(b, info.Mode().String()...)
867 b = append(b, ' ')
868
869 size := info.Size()
870 var usize uint64
871 if size >= 0 {
872 usize = uint64(size)
873 } else {
874 b = append(b, '-')
875 usize = uint64(-size)
876 }
877 var buf [20]byte
878 i := len(buf) - 1
879 for usize >= 10 {
880 q := usize / 10
881 buf[i] = byte('0' + usize - q*10)
882 i--
883 usize = q
884 }
885 buf[i] = byte('0' + usize)
886 b = append(b, buf[i:]...)
887 b = append(b, ' ')
888
889 b = append(b, info.ModTime().Format(time.DateTime)...)
890 b = append(b, ' ')
891
892 b = append(b, name...)
893 if info.IsDir() {
894 b = append(b, '/')
895 }
896
897 return string(b)
898 }
899
900 // toValidName coerces name to be a valid name for fs.FS.Open.
901 func toValidName(name string) string {
902 name = strings.ReplaceAll(name, `\`, `/`)
903 p := path.Clean(name)
904
905 p = strings.TrimPrefix(p, "/")
906
907 for strings.HasPrefix(p, "../") {
908 p = p[len("../"):]
909 }
910
911 return p
912 }
913
914 func (r *Reader) initFileList() {
915 r.fileListOnce.Do(func() {
916 // files and knownDirs map from a file/directory name
917 // to an index into the r.fileList entry that we are
918 // building. They are used to mark duplicate entries.
919 files := make(map[string]int)
920 knownDirs := make(map[string]int)
921
922 // dirs[name] is true if name is known to be a directory,
923 // because it appears as a prefix in a path.
924 dirs := make(map[string]bool)
925
926 for _, file := range r.File {
927 isDir := len(file.Name) > 0 && file.Name[len(file.Name)-1] == '/'
928 name := toValidName(file.Name)
929 if name == "" {
930 continue
931 }
932
933 if idx, ok := files[name]; ok {
934 r.fileList[idx].isDup = true
935 continue
936 }
937 if idx, ok := knownDirs[name]; ok {
938 r.fileList[idx].isDup = true
939 continue
940 }
941
942 dir := name
943 for {
944 if idx := strings.LastIndex(dir, "/"); idx < 0 {
945 break
946 } else {
947 dir = dir[:idx]
948 }
949 if dirs[dir] {
950 break
951 }
952 dirs[dir] = true
953 }
954
955 idx := len(r.fileList)
956 entry := fileListEntry{
957 name: name,
958 file: file,
959 isDir: isDir,
960 }
961 r.fileList = append(r.fileList, entry)
962 if isDir {
963 knownDirs[name] = idx
964 } else {
965 files[name] = idx
966 }
967 }
968 for dir := range dirs {
969 if _, ok := knownDirs[dir]; !ok {
970 if idx, ok := files[dir]; ok {
971 r.fileList[idx].isDup = true
972 } else {
973 entry := fileListEntry{
974 name: dir,
975 file: nil,
976 isDir: true,
977 }
978 r.fileList = append(r.fileList, entry)
979 }
980 }
981 }
982
983 sort.Slice(r.fileList, func(i, j int) bool { return fileEntryLess(r.fileList[i].name, r.fileList[j].name) })
984 })
985 }
986
987 func fileEntryLess(x, y string) bool {
988 xdir, xelem, _ := split(x)
989 ydir, yelem, _ := split(y)
990 return xdir < ydir || xdir == ydir && xelem < yelem
991 }
992
993 // Open opens the named file in the ZIP archive,
994 // using the semantics of fs.FS.Open:
995 // paths are always slash separated, with no
996 // leading / or ../ elements.
997 func (r *Reader) Open(name string) (fs.File, error) {
998 r.initFileList()
999
1000 if !fs.ValidPath(name) {
1001 return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrInvalid}
1002 }
1003 e := r.openLookup(name)
1004 if e == nil {
1005 return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
1006 }
1007 if e.isDir {
1008 return &openDir{e, r.openReadDir(name), 0}, nil
1009 }
1010 rc, err := e.file.Open()
1011 if err != nil {
1012 return nil, err
1013 }
1014 return rc.(fs.File), nil
1015 }
1016
1017 func split(name string) (dir, elem string, isDir bool) {
1018 if len(name) > 0 && name[len(name)-1] == '/' {
1019 isDir = true
1020 name = name[:len(name)-1]
1021 }
1022 i := len(name) - 1
1023 for i >= 0 && name[i] != '/' {
1024 i--
1025 }
1026 if i < 0 {
1027 return ".", name, isDir
1028 }
1029 return name[:i], name[i+1:], isDir
1030 }
1031
1032 var dotFile = &fileListEntry{name: "./", isDir: true}
1033
1034 func (r *Reader) openLookup(name string) *fileListEntry {
1035 if name == "." {
1036 return dotFile
1037 }
1038
1039 dir, elem, _ := split(name)
1040 files := r.fileList
1041 i := sort.Search(len(files), func(i int) bool {
1042 idir, ielem, _ := split(files[i].name)
1043 return idir > dir || idir == dir && ielem >= elem
1044 })
1045 if i < len(files) {
1046 fname := files[i].name
1047 if fname == name || len(fname) == len(name)+1 && fname[len(name)] == '/' && fname[:len(name)] == name {
1048 return &files[i]
1049 }
1050 }
1051 return nil
1052 }
1053
1054 func (r *Reader) openReadDir(dir string) []fileListEntry {
1055 files := r.fileList
1056 i := sort.Search(len(files), func(i int) bool {
1057 idir, _, _ := split(files[i].name)
1058 return idir >= dir
1059 })
1060 j := sort.Search(len(files), func(j int) bool {
1061 jdir, _, _ := split(files[j].name)
1062 return jdir > dir
1063 })
1064 return files[i:j]
1065 }
1066
1067 type openDir struct {
1068 e *fileListEntry
1069 files []fileListEntry
1070 offset int
1071 }
1072
1073 func (d *openDir) Close() error { return nil }
1074 func (d *openDir) Stat() (fs.FileInfo, error) { return d.e.stat() }
1075
1076 func (d *openDir) Read([]byte) (int, error) {
1077 return 0, &fs.PathError{Op: "read", Path: d.e.name, Err: errors.New("is a directory")}
1078 }
1079
1080 func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error) {
1081 n := len(d.files) - d.offset
1082 if count > 0 && n > count {
1083 n = count
1084 }
1085 if n == 0 {
1086 if count <= 0 {
1087 return nil, nil
1088 }
1089 return nil, io.EOF
1090 }
1091 list := make([]fs.DirEntry, n)
1092 for i := range list {
1093 s, err := d.files[d.offset+i].stat()
1094 if err != nil {
1095 return nil, err
1096 }
1097 list[i] = s
1098 }
1099 d.offset += n
1100 return list, nil
1101 }