Black Lives Matter. Support the Equal Justice Initiative.

Source file src/archive/zip/reader.go

Documentation: archive/zip

     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  	"sort"
    18  	"strings"
    19  	"sync"
    20  	"time"
    21  )
    22  
    23  var (
    24  	ErrFormat    = errors.New("zip: not a valid zip file")
    25  	ErrAlgorithm = errors.New("zip: unsupported compression algorithm")
    26  	ErrChecksum  = errors.New("zip: checksum error")
    27  )
    28  
    29  // A Reader serves content from a ZIP archive.
    30  type Reader struct {
    31  	r             io.ReaderAt
    32  	File          []*File
    33  	Comment       string
    34  	decompressors map[uint16]Decompressor
    35  
    36  	// fileList is a list of files sorted by ename,
    37  	// for use by the Open method.
    38  	fileListOnce sync.Once
    39  	fileList     []fileListEntry
    40  }
    41  
    42  // A ReadCloser is a Reader that must be closed when no longer needed.
    43  type ReadCloser struct {
    44  	f *os.File
    45  	Reader
    46  }
    47  
    48  // A File is a single file in a ZIP archive.
    49  // The file information is in the embedded FileHeader.
    50  // The file content can be accessed by calling Open.
    51  type File struct {
    52  	FileHeader
    53  	zip          *Reader
    54  	zipr         io.ReaderAt
    55  	zipsize      int64
    56  	headerOffset int64
    57  }
    58  
    59  func (f *File) hasDataDescriptor() bool {
    60  	return f.Flags&0x8 != 0
    61  }
    62  
    63  // OpenReader will open the Zip file specified by name and return a ReadCloser.
    64  func OpenReader(name string) (*ReadCloser, error) {
    65  	f, err := os.Open(name)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  	fi, err := f.Stat()
    70  	if err != nil {
    71  		f.Close()
    72  		return nil, err
    73  	}
    74  	r := new(ReadCloser)
    75  	if err := r.init(f, fi.Size()); err != nil {
    76  		f.Close()
    77  		return nil, err
    78  	}
    79  	r.f = f
    80  	return r, nil
    81  }
    82  
    83  // NewReader returns a new Reader reading from r, which is assumed to
    84  // have the given size in bytes.
    85  func NewReader(r io.ReaderAt, size int64) (*Reader, error) {
    86  	if size < 0 {
    87  		return nil, errors.New("zip: size cannot be negative")
    88  	}
    89  	zr := new(Reader)
    90  	if err := zr.init(r, size); err != nil {
    91  		return nil, err
    92  	}
    93  	return zr, nil
    94  }
    95  
    96  func (z *Reader) init(r io.ReaderAt, size int64) error {
    97  	end, err := readDirectoryEnd(r, size)
    98  	if err != nil {
    99  		return err
   100  	}
   101  	z.r = r
   102  	// Since the number of directory records is not validated, it is not
   103  	// safe to preallocate z.File without first checking that the specified
   104  	// number of files is reasonable, since a malformed archive may
   105  	// indicate it contains up to 1 << 128 - 1 files. Since each file has a
   106  	// header which will be _at least_ 30 bytes we can safely preallocate
   107  	// if (data size / 30) >= end.directoryRecords.
   108  	if (uint64(size)-end.directorySize)/30 >= end.directoryRecords {
   109  		z.File = make([]*File, 0, end.directoryRecords)
   110  	}
   111  	z.Comment = end.comment
   112  	rs := io.NewSectionReader(r, 0, size)
   113  	if _, err = rs.Seek(int64(end.directoryOffset), io.SeekStart); err != nil {
   114  		return err
   115  	}
   116  	buf := bufio.NewReader(rs)
   117  
   118  	// The count of files inside a zip is truncated to fit in a uint16.
   119  	// Gloss over this by reading headers until we encounter
   120  	// a bad one, and then only report an ErrFormat or UnexpectedEOF if
   121  	// the file count modulo 65536 is incorrect.
   122  	for {
   123  		f := &File{zip: z, zipr: r, zipsize: size}
   124  		err = readDirectoryHeader(f, buf)
   125  		if err == ErrFormat || err == io.ErrUnexpectedEOF {
   126  			break
   127  		}
   128  		if err != nil {
   129  			return err
   130  		}
   131  		z.File = append(z.File, f)
   132  	}
   133  	if uint16(len(z.File)) != uint16(end.directoryRecords) { // only compare 16 bits here
   134  		// Return the readDirectoryHeader error if we read
   135  		// the wrong number of directory entries.
   136  		return err
   137  	}
   138  	return nil
   139  }
   140  
   141  // RegisterDecompressor registers or overrides a custom decompressor for a
   142  // specific method ID. If a decompressor for a given method is not found,
   143  // Reader will default to looking up the decompressor at the package level.
   144  func (z *Reader) RegisterDecompressor(method uint16, dcomp Decompressor) {
   145  	if z.decompressors == nil {
   146  		z.decompressors = make(map[uint16]Decompressor)
   147  	}
   148  	z.decompressors[method] = dcomp
   149  }
   150  
   151  func (z *Reader) decompressor(method uint16) Decompressor {
   152  	dcomp := z.decompressors[method]
   153  	if dcomp == nil {
   154  		dcomp = decompressor(method)
   155  	}
   156  	return dcomp
   157  }
   158  
   159  // Close closes the Zip file, rendering it unusable for I/O.
   160  func (rc *ReadCloser) Close() error {
   161  	return rc.f.Close()
   162  }
   163  
   164  // DataOffset returns the offset of the file's possibly-compressed
   165  // data, relative to the beginning of the zip file.
   166  //
   167  // Most callers should instead use Open, which transparently
   168  // decompresses data and verifies checksums.
   169  func (f *File) DataOffset() (offset int64, err error) {
   170  	bodyOffset, err := f.findBodyOffset()
   171  	if err != nil {
   172  		return
   173  	}
   174  	return f.headerOffset + bodyOffset, nil
   175  }
   176  
   177  // Open returns a ReadCloser that provides access to the File's contents.
   178  // Multiple files may be read concurrently.
   179  func (f *File) Open() (io.ReadCloser, error) {
   180  	bodyOffset, err := f.findBodyOffset()
   181  	if err != nil {
   182  		return nil, err
   183  	}
   184  	size := int64(f.CompressedSize64)
   185  	r := io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset, size)
   186  	dcomp := f.zip.decompressor(f.Method)
   187  	if dcomp == nil {
   188  		return nil, ErrAlgorithm
   189  	}
   190  	var rc io.ReadCloser = dcomp(r)
   191  	var desr io.Reader
   192  	if f.hasDataDescriptor() {
   193  		desr = io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset+size, dataDescriptorLen)
   194  	}
   195  	rc = &checksumReader{
   196  		rc:   rc,
   197  		hash: crc32.NewIEEE(),
   198  		f:    f,
   199  		desr: desr,
   200  	}
   201  	return rc, nil
   202  }
   203  
   204  type checksumReader struct {
   205  	rc    io.ReadCloser
   206  	hash  hash.Hash32
   207  	nread uint64 // number of bytes read so far
   208  	f     *File
   209  	desr  io.Reader // if non-nil, where to read the data descriptor
   210  	err   error     // sticky error
   211  }
   212  
   213  func (r *checksumReader) Stat() (fs.FileInfo, error) {
   214  	return headerFileInfo{&r.f.FileHeader}, nil
   215  }
   216  
   217  func (r *checksumReader) Read(b []byte) (n int, err error) {
   218  	if r.err != nil {
   219  		return 0, r.err
   220  	}
   221  	n, err = r.rc.Read(b)
   222  	r.hash.Write(b[:n])
   223  	r.nread += uint64(n)
   224  	if err == nil {
   225  		return
   226  	}
   227  	if err == io.EOF {
   228  		if r.nread != r.f.UncompressedSize64 {
   229  			return 0, io.ErrUnexpectedEOF
   230  		}
   231  		if r.desr != nil {
   232  			if err1 := readDataDescriptor(r.desr, r.f); err1 != nil {
   233  				if err1 == io.EOF {
   234  					err = io.ErrUnexpectedEOF
   235  				} else {
   236  					err = err1
   237  				}
   238  			} else if r.hash.Sum32() != r.f.CRC32 {
   239  				err = ErrChecksum
   240  			}
   241  		} else {
   242  			// If there's not a data descriptor, we still compare
   243  			// the CRC32 of what we've read against the file header
   244  			// or TOC's CRC32, if it seems like it was set.
   245  			if r.f.CRC32 != 0 && r.hash.Sum32() != r.f.CRC32 {
   246  				err = ErrChecksum
   247  			}
   248  		}
   249  	}
   250  	r.err = err
   251  	return
   252  }
   253  
   254  func (r *checksumReader) Close() error { return r.rc.Close() }
   255  
   256  // findBodyOffset does the minimum work to verify the file has a header
   257  // and returns the file body offset.
   258  func (f *File) findBodyOffset() (int64, error) {
   259  	var buf [fileHeaderLen]byte
   260  	if _, err := f.zipr.ReadAt(buf[:], f.headerOffset); err != nil {
   261  		return 0, err
   262  	}
   263  	b := readBuf(buf[:])
   264  	if sig := b.uint32(); sig != fileHeaderSignature {
   265  		return 0, ErrFormat
   266  	}
   267  	b = b[22:] // skip over most of the header
   268  	filenameLen := int(b.uint16())
   269  	extraLen := int(b.uint16())
   270  	return int64(fileHeaderLen + filenameLen + extraLen), nil
   271  }
   272  
   273  // readDirectoryHeader attempts to read a directory header from r.
   274  // It returns io.ErrUnexpectedEOF if it cannot read a complete header,
   275  // and ErrFormat if it doesn't find a valid header signature.
   276  func readDirectoryHeader(f *File, r io.Reader) error {
   277  	var buf [directoryHeaderLen]byte
   278  	if _, err := io.ReadFull(r, buf[:]); err != nil {
   279  		return err
   280  	}
   281  	b := readBuf(buf[:])
   282  	if sig := b.uint32(); sig != directoryHeaderSignature {
   283  		return ErrFormat
   284  	}
   285  	f.CreatorVersion = b.uint16()
   286  	f.ReaderVersion = b.uint16()
   287  	f.Flags = b.uint16()
   288  	f.Method = b.uint16()
   289  	f.ModifiedTime = b.uint16()
   290  	f.ModifiedDate = b.uint16()
   291  	f.CRC32 = b.uint32()
   292  	f.CompressedSize = b.uint32()
   293  	f.UncompressedSize = b.uint32()
   294  	f.CompressedSize64 = uint64(f.CompressedSize)
   295  	f.UncompressedSize64 = uint64(f.UncompressedSize)
   296  	filenameLen := int(b.uint16())
   297  	extraLen := int(b.uint16())
   298  	commentLen := int(b.uint16())
   299  	b = b[4:] // skipped start disk number and internal attributes (2x uint16)
   300  	f.ExternalAttrs = b.uint32()
   301  	f.headerOffset = int64(b.uint32())
   302  	d := make([]byte, filenameLen+extraLen+commentLen)
   303  	if _, err := io.ReadFull(r, d); err != nil {
   304  		return err
   305  	}
   306  	f.Name = string(d[:filenameLen])
   307  	f.Extra = d[filenameLen : filenameLen+extraLen]
   308  	f.Comment = string(d[filenameLen+extraLen:])
   309  
   310  	// Determine the character encoding.
   311  	utf8Valid1, utf8Require1 := detectUTF8(f.Name)
   312  	utf8Valid2, utf8Require2 := detectUTF8(f.Comment)
   313  	switch {
   314  	case !utf8Valid1 || !utf8Valid2:
   315  		// Name and Comment definitely not UTF-8.
   316  		f.NonUTF8 = true
   317  	case !utf8Require1 && !utf8Require2:
   318  		// Name and Comment use only single-byte runes that overlap with UTF-8.
   319  		f.NonUTF8 = false
   320  	default:
   321  		// Might be UTF-8, might be some other encoding; preserve existing flag.
   322  		// Some ZIP writers use UTF-8 encoding without setting the UTF-8 flag.
   323  		// Since it is impossible to always distinguish valid UTF-8 from some
   324  		// other encoding (e.g., GBK or Shift-JIS), we trust the flag.
   325  		f.NonUTF8 = f.Flags&0x800 == 0
   326  	}
   327  
   328  	needUSize := f.UncompressedSize == ^uint32(0)
   329  	needCSize := f.CompressedSize == ^uint32(0)
   330  	needHeaderOffset := f.headerOffset == int64(^uint32(0))
   331  
   332  	// Best effort to find what we need.
   333  	// Other zip authors might not even follow the basic format,
   334  	// and we'll just ignore the Extra content in that case.
   335  	var modified time.Time
   336  parseExtras:
   337  	for extra := readBuf(f.Extra); len(extra) >= 4; { // need at least tag and size
   338  		fieldTag := extra.uint16()
   339  		fieldSize := int(extra.uint16())
   340  		if len(extra) < fieldSize {
   341  			break
   342  		}
   343  		fieldBuf := extra.sub(fieldSize)
   344  
   345  		switch fieldTag {
   346  		case zip64ExtraID:
   347  			// update directory values from the zip64 extra block.
   348  			// They should only be consulted if the sizes read earlier
   349  			// are maxed out.
   350  			// See golang.org/issue/13367.
   351  			if needUSize {
   352  				needUSize = false
   353  				if len(fieldBuf) < 8 {
   354  					return ErrFormat
   355  				}
   356  				f.UncompressedSize64 = fieldBuf.uint64()
   357  			}
   358  			if needCSize {
   359  				needCSize = false
   360  				if len(fieldBuf) < 8 {
   361  					return ErrFormat
   362  				}
   363  				f.CompressedSize64 = fieldBuf.uint64()
   364  			}
   365  			if needHeaderOffset {
   366  				needHeaderOffset = false
   367  				if len(fieldBuf) < 8 {
   368  					return ErrFormat
   369  				}
   370  				f.headerOffset = int64(fieldBuf.uint64())
   371  			}
   372  		case ntfsExtraID:
   373  			if len(fieldBuf) < 4 {
   374  				continue parseExtras
   375  			}
   376  			fieldBuf.uint32()        // reserved (ignored)
   377  			for len(fieldBuf) >= 4 { // need at least tag and size
   378  				attrTag := fieldBuf.uint16()
   379  				attrSize := int(fieldBuf.uint16())
   380  				if len(fieldBuf) < attrSize {
   381  					continue parseExtras
   382  				}
   383  				attrBuf := fieldBuf.sub(attrSize)
   384  				if attrTag != 1 || attrSize != 24 {
   385  					continue // Ignore irrelevant attributes
   386  				}
   387  
   388  				const ticksPerSecond = 1e7    // Windows timestamp resolution
   389  				ts := int64(attrBuf.uint64()) // ModTime since Windows epoch
   390  				secs := int64(ts / ticksPerSecond)
   391  				nsecs := (1e9 / ticksPerSecond) * int64(ts%ticksPerSecond)
   392  				epoch := time.Date(1601, time.January, 1, 0, 0, 0, 0, time.UTC)
   393  				modified = time.Unix(epoch.Unix()+secs, nsecs)
   394  			}
   395  		case unixExtraID, infoZipUnixExtraID:
   396  			if len(fieldBuf) < 8 {
   397  				continue parseExtras
   398  			}
   399  			fieldBuf.uint32()              // AcTime (ignored)
   400  			ts := int64(fieldBuf.uint32()) // ModTime since Unix epoch
   401  			modified = time.Unix(ts, 0)
   402  		case extTimeExtraID:
   403  			if len(fieldBuf) < 5 || fieldBuf.uint8()&1 == 0 {
   404  				continue parseExtras
   405  			}
   406  			ts := int64(fieldBuf.uint32()) // ModTime since Unix epoch
   407  			modified = time.Unix(ts, 0)
   408  		}
   409  	}
   410  
   411  	msdosModified := msDosTimeToTime(f.ModifiedDate, f.ModifiedTime)
   412  	f.Modified = msdosModified
   413  	if !modified.IsZero() {
   414  		f.Modified = modified.UTC()
   415  
   416  		// If legacy MS-DOS timestamps are set, we can use the delta between
   417  		// the legacy and extended versions to estimate timezone offset.
   418  		//
   419  		// A non-UTC timezone is always used (even if offset is zero).
   420  		// Thus, FileHeader.Modified.Location() == time.UTC is useful for
   421  		// determining whether extended timestamps are present.
   422  		// This is necessary for users that need to do additional time
   423  		// calculations when dealing with legacy ZIP formats.
   424  		if f.ModifiedTime != 0 || f.ModifiedDate != 0 {
   425  			f.Modified = modified.In(timeZone(msdosModified.Sub(modified)))
   426  		}
   427  	}
   428  
   429  	// Assume that uncompressed size 2³²-1 could plausibly happen in
   430  	// an old zip32 file that was sharding inputs into the largest chunks
   431  	// possible (or is just malicious; search the web for 42.zip).
   432  	// If needUSize is true still, it means we didn't see a zip64 extension.
   433  	// As long as the compressed size is not also 2³²-1 (implausible)
   434  	// and the header is not also 2³²-1 (equally implausible),
   435  	// accept the uncompressed size 2³²-1 as valid.
   436  	// If nothing else, this keeps archive/zip working with 42.zip.
   437  	_ = needUSize
   438  
   439  	if needCSize || needHeaderOffset {
   440  		return ErrFormat
   441  	}
   442  
   443  	return nil
   444  }
   445  
   446  func readDataDescriptor(r io.Reader, f *File) error {
   447  	var buf [dataDescriptorLen]byte
   448  
   449  	// The spec says: "Although not originally assigned a
   450  	// signature, the value 0x08074b50 has commonly been adopted
   451  	// as a signature value for the data descriptor record.
   452  	// Implementers should be aware that ZIP files may be
   453  	// encountered with or without this signature marking data
   454  	// descriptors and should account for either case when reading
   455  	// ZIP files to ensure compatibility."
   456  	//
   457  	// dataDescriptorLen includes the size of the signature but
   458  	// first read just those 4 bytes to see if it exists.
   459  	if _, err := io.ReadFull(r, buf[:4]); err != nil {
   460  		return err
   461  	}
   462  	off := 0
   463  	maybeSig := readBuf(buf[:4])
   464  	if maybeSig.uint32() != dataDescriptorSignature {
   465  		// No data descriptor signature. Keep these four
   466  		// bytes.
   467  		off += 4
   468  	}
   469  	if _, err := io.ReadFull(r, buf[off:12]); err != nil {
   470  		return err
   471  	}
   472  	b := readBuf(buf[:12])
   473  	if b.uint32() != f.CRC32 {
   474  		return ErrChecksum
   475  	}
   476  
   477  	// The two sizes that follow here can be either 32 bits or 64 bits
   478  	// but the spec is not very clear on this and different
   479  	// interpretations has been made causing incompatibilities. We
   480  	// already have the sizes from the central directory so we can
   481  	// just ignore these.
   482  
   483  	return nil
   484  }
   485  
   486  func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err error) {
   487  	// look for directoryEndSignature in the last 1k, then in the last 65k
   488  	var buf []byte
   489  	var directoryEndOffset int64
   490  	for i, bLen := range []int64{1024, 65 * 1024} {
   491  		if bLen > size {
   492  			bLen = size
   493  		}
   494  		buf = make([]byte, int(bLen))
   495  		if _, err := r.ReadAt(buf, size-bLen); err != nil && err != io.EOF {
   496  			return nil, err
   497  		}
   498  		if p := findSignatureInBlock(buf); p >= 0 {
   499  			buf = buf[p:]
   500  			directoryEndOffset = size - bLen + int64(p)
   501  			break
   502  		}
   503  		if i == 1 || bLen == size {
   504  			return nil, ErrFormat
   505  		}
   506  	}
   507  
   508  	// read header into struct
   509  	b := readBuf(buf[4:]) // skip signature
   510  	d := &directoryEnd{
   511  		diskNbr:            uint32(b.uint16()),
   512  		dirDiskNbr:         uint32(b.uint16()),
   513  		dirRecordsThisDisk: uint64(b.uint16()),
   514  		directoryRecords:   uint64(b.uint16()),
   515  		directorySize:      uint64(b.uint32()),
   516  		directoryOffset:    uint64(b.uint32()),
   517  		commentLen:         b.uint16(),
   518  	}
   519  	l := int(d.commentLen)
   520  	if l > len(b) {
   521  		return nil, errors.New("zip: invalid comment length")
   522  	}
   523  	d.comment = string(b[:l])
   524  
   525  	// These values mean that the file can be a zip64 file
   526  	if d.directoryRecords == 0xffff || d.directorySize == 0xffff || d.directoryOffset == 0xffffffff {
   527  		p, err := findDirectory64End(r, directoryEndOffset)
   528  		if err == nil && p >= 0 {
   529  			err = readDirectory64End(r, p, d)
   530  		}
   531  		if err != nil {
   532  			return nil, err
   533  		}
   534  	}
   535  	// Make sure directoryOffset points to somewhere in our file.
   536  	if o := int64(d.directoryOffset); o < 0 || o >= size {
   537  		return nil, ErrFormat
   538  	}
   539  	return d, nil
   540  }
   541  
   542  // findDirectory64End tries to read the zip64 locator just before the
   543  // directory end and returns the offset of the zip64 directory end if
   544  // found.
   545  func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error) {
   546  	locOffset := directoryEndOffset - directory64LocLen
   547  	if locOffset < 0 {
   548  		return -1, nil // no need to look for a header outside the file
   549  	}
   550  	buf := make([]byte, directory64LocLen)
   551  	if _, err := r.ReadAt(buf, locOffset); err != nil {
   552  		return -1, err
   553  	}
   554  	b := readBuf(buf)
   555  	if sig := b.uint32(); sig != directory64LocSignature {
   556  		return -1, nil
   557  	}
   558  	if b.uint32() != 0 { // number of the disk with the start of the zip64 end of central directory
   559  		return -1, nil // the file is not a valid zip64-file
   560  	}
   561  	p := b.uint64()      // relative offset of the zip64 end of central directory record
   562  	if b.uint32() != 1 { // total number of disks
   563  		return -1, nil // the file is not a valid zip64-file
   564  	}
   565  	return int64(p), nil
   566  }
   567  
   568  // readDirectory64End reads the zip64 directory end and updates the
   569  // directory end with the zip64 directory end values.
   570  func readDirectory64End(r io.ReaderAt, offset int64, d *directoryEnd) (err error) {
   571  	buf := make([]byte, directory64EndLen)
   572  	if _, err := r.ReadAt(buf, offset); err != nil {
   573  		return err
   574  	}
   575  
   576  	b := readBuf(buf)
   577  	if sig := b.uint32(); sig != directory64EndSignature {
   578  		return ErrFormat
   579  	}
   580  
   581  	b = b[12:]                        // skip dir size, version and version needed (uint64 + 2x uint16)
   582  	d.diskNbr = b.uint32()            // number of this disk
   583  	d.dirDiskNbr = b.uint32()         // number of the disk with the start of the central directory
   584  	d.dirRecordsThisDisk = b.uint64() // total number of entries in the central directory on this disk
   585  	d.directoryRecords = b.uint64()   // total number of entries in the central directory
   586  	d.directorySize = b.uint64()      // size of the central directory
   587  	d.directoryOffset = b.uint64()    // offset of start of central directory with respect to the starting disk number
   588  
   589  	return nil
   590  }
   591  
   592  func findSignatureInBlock(b []byte) int {
   593  	for i := len(b) - directoryEndLen; i >= 0; i-- {
   594  		// defined from directoryEndSignature in struct.go
   595  		if b[i] == 'P' && b[i+1] == 'K' && b[i+2] == 0x05 && b[i+3] == 0x06 {
   596  			// n is length of comment
   597  			n := int(b[i+directoryEndLen-2]) | int(b[i+directoryEndLen-1])<<8
   598  			if n+directoryEndLen+i <= len(b) {
   599  				return i
   600  			}
   601  		}
   602  	}
   603  	return -1
   604  }
   605  
   606  type readBuf []byte
   607  
   608  func (b *readBuf) uint8() uint8 {
   609  	v := (*b)[0]
   610  	*b = (*b)[1:]
   611  	return v
   612  }
   613  
   614  func (b *readBuf) uint16() uint16 {
   615  	v := binary.LittleEndian.Uint16(*b)
   616  	*b = (*b)[2:]
   617  	return v
   618  }
   619  
   620  func (b *readBuf) uint32() uint32 {
   621  	v := binary.LittleEndian.Uint32(*b)
   622  	*b = (*b)[4:]
   623  	return v
   624  }
   625  
   626  func (b *readBuf) uint64() uint64 {
   627  	v := binary.LittleEndian.Uint64(*b)
   628  	*b = (*b)[8:]
   629  	return v
   630  }
   631  
   632  func (b *readBuf) sub(n int) readBuf {
   633  	b2 := (*b)[:n]
   634  	*b = (*b)[n:]
   635  	return b2
   636  }
   637  
   638  // A fileListEntry is a File and its ename.
   639  // If file == nil, the fileListEntry describes a directory without metadata.
   640  type fileListEntry struct {
   641  	name  string
   642  	file  *File
   643  	isDir bool
   644  }
   645  
   646  type fileInfoDirEntry interface {
   647  	fs.FileInfo
   648  	fs.DirEntry
   649  }
   650  
   651  func (e *fileListEntry) stat() fileInfoDirEntry {
   652  	if !e.isDir {
   653  		return headerFileInfo{&e.file.FileHeader}
   654  	}
   655  	return e
   656  }
   657  
   658  // Only used for directories.
   659  func (f *fileListEntry) Name() string      { _, elem, _ := split(f.name); return elem }
   660  func (f *fileListEntry) Size() int64       { return 0 }
   661  func (f *fileListEntry) Mode() fs.FileMode { return fs.ModeDir | 0555 }
   662  func (f *fileListEntry) Type() fs.FileMode { return fs.ModeDir }
   663  func (f *fileListEntry) IsDir() bool       { return true }
   664  func (f *fileListEntry) Sys() interface{}  { return nil }
   665  
   666  func (f *fileListEntry) ModTime() time.Time {
   667  	if f.file == nil {
   668  		return time.Time{}
   669  	}
   670  	return f.file.FileHeader.Modified.UTC()
   671  }
   672  
   673  func (f *fileListEntry) Info() (fs.FileInfo, error) { return f, nil }
   674  
   675  // toValidName coerces name to be a valid name for fs.FS.Open.
   676  func toValidName(name string) string {
   677  	name = strings.ReplaceAll(name, `\`, `/`)
   678  	p := path.Clean(name)
   679  	if strings.HasPrefix(p, "/") {
   680  		p = p[len("/"):]
   681  	}
   682  	for strings.HasPrefix(p, "../") {
   683  		p = p[len("../"):]
   684  	}
   685  	return p
   686  }
   687  
   688  func (r *Reader) initFileList() {
   689  	r.fileListOnce.Do(func() {
   690  		dirs := make(map[string]bool)
   691  		knownDirs := make(map[string]bool)
   692  		for _, file := range r.File {
   693  			isDir := len(file.Name) > 0 && file.Name[len(file.Name)-1] == '/'
   694  			name := toValidName(file.Name)
   695  			for dir := path.Dir(name); dir != "."; dir = path.Dir(dir) {
   696  				dirs[dir] = true
   697  			}
   698  			entry := fileListEntry{
   699  				name:  name,
   700  				file:  file,
   701  				isDir: isDir,
   702  			}
   703  			r.fileList = append(r.fileList, entry)
   704  			if isDir {
   705  				knownDirs[name] = true
   706  			}
   707  		}
   708  		for dir := range dirs {
   709  			if !knownDirs[dir] {
   710  				entry := fileListEntry{
   711  					name:  dir,
   712  					file:  nil,
   713  					isDir: true,
   714  				}
   715  				r.fileList = append(r.fileList, entry)
   716  			}
   717  		}
   718  
   719  		sort.Slice(r.fileList, func(i, j int) bool { return fileEntryLess(r.fileList[i].name, r.fileList[j].name) })
   720  	})
   721  }
   722  
   723  func fileEntryLess(x, y string) bool {
   724  	xdir, xelem, _ := split(x)
   725  	ydir, yelem, _ := split(y)
   726  	return xdir < ydir || xdir == ydir && xelem < yelem
   727  }
   728  
   729  // Open opens the named file in the ZIP archive,
   730  // using the semantics of fs.FS.Open:
   731  // paths are always slash separated, with no
   732  // leading / or ../ elements.
   733  func (r *Reader) Open(name string) (fs.File, error) {
   734  	r.initFileList()
   735  
   736  	e := r.openLookup(name)
   737  	if e == nil || !fs.ValidPath(name) {
   738  		return nil, &fs.PathError{Op: "open", Path: name, Err: fs.ErrNotExist}
   739  	}
   740  	if e.isDir {
   741  		return &openDir{e, r.openReadDir(name), 0}, nil
   742  	}
   743  	rc, err := e.file.Open()
   744  	if err != nil {
   745  		return nil, err
   746  	}
   747  	return rc.(fs.File), nil
   748  }
   749  
   750  func split(name string) (dir, elem string, isDir bool) {
   751  	if name[len(name)-1] == '/' {
   752  		isDir = true
   753  		name = name[:len(name)-1]
   754  	}
   755  	i := len(name) - 1
   756  	for i >= 0 && name[i] != '/' {
   757  		i--
   758  	}
   759  	if i < 0 {
   760  		return ".", name, isDir
   761  	}
   762  	return name[:i], name[i+1:], isDir
   763  }
   764  
   765  var dotFile = &fileListEntry{name: "./", isDir: true}
   766  
   767  func (r *Reader) openLookup(name string) *fileListEntry {
   768  	if name == "." {
   769  		return dotFile
   770  	}
   771  
   772  	dir, elem, _ := split(name)
   773  	files := r.fileList
   774  	i := sort.Search(len(files), func(i int) bool {
   775  		idir, ielem, _ := split(files[i].name)
   776  		return idir > dir || idir == dir && ielem >= elem
   777  	})
   778  	if i < len(files) {
   779  		fname := files[i].name
   780  		if fname == name || len(fname) == len(name)+1 && fname[len(name)] == '/' && fname[:len(name)] == name {
   781  			return &files[i]
   782  		}
   783  	}
   784  	return nil
   785  }
   786  
   787  func (r *Reader) openReadDir(dir string) []fileListEntry {
   788  	files := r.fileList
   789  	i := sort.Search(len(files), func(i int) bool {
   790  		idir, _, _ := split(files[i].name)
   791  		return idir >= dir
   792  	})
   793  	j := sort.Search(len(files), func(j int) bool {
   794  		jdir, _, _ := split(files[j].name)
   795  		return jdir > dir
   796  	})
   797  	return files[i:j]
   798  }
   799  
   800  type openDir struct {
   801  	e      *fileListEntry
   802  	files  []fileListEntry
   803  	offset int
   804  }
   805  
   806  func (d *openDir) Close() error               { return nil }
   807  func (d *openDir) Stat() (fs.FileInfo, error) { return d.e.stat(), nil }
   808  
   809  func (d *openDir) Read([]byte) (int, error) {
   810  	return 0, &fs.PathError{Op: "read", Path: d.e.name, Err: errors.New("is a directory")}
   811  }
   812  
   813  func (d *openDir) ReadDir(count int) ([]fs.DirEntry, error) {
   814  	n := len(d.files) - d.offset
   815  	if count > 0 && n > count {
   816  		n = count
   817  	}
   818  	if n == 0 {
   819  		if count <= 0 {
   820  			return nil, nil
   821  		}
   822  		return nil, io.EOF
   823  	}
   824  	list := make([]fs.DirEntry, n)
   825  	for i := range list {
   826  		list[i] = d.files[d.offset+i].stat()
   827  	}
   828  	d.offset += n
   829  	return list, nil
   830  }
   831  

View as plain text