Source file src/archive/tar/reader.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tar
     6  
     7  import (
     8  	"bytes"
     9  	"io"
    10  	"path/filepath"
    11  	"strconv"
    12  	"strings"
    13  	"time"
    14  )
    15  
    16  // Reader provides sequential access to the contents of a tar archive.
    17  // Reader.Next advances to the next file in the archive (including the first),
    18  // and then Reader can be treated as an io.Reader to access the file's data.
    19  type Reader struct {
    20  	r    io.Reader
    21  	pad  int64      // Amount of padding (ignored) after current file entry
    22  	curr fileReader // Reader for current file entry
    23  	blk  block      // Buffer to use as temporary local storage
    24  
    25  	// err is a persistent error.
    26  	// It is only the responsibility of every exported method of Reader to
    27  	// ensure that this error is sticky.
    28  	err error
    29  }
    30  
    31  type fileReader interface {
    32  	io.Reader
    33  	fileState
    34  
    35  	WriteTo(io.Writer) (int64, error)
    36  }
    37  
    38  // NewReader creates a new [Reader] reading from r.
    39  func NewReader(r io.Reader) *Reader {
    40  	return &Reader{r: r, curr: &regFileReader{r, 0}}
    41  }
    42  
    43  // Next advances to the next entry in the tar archive.
    44  // The Header.Size determines how many bytes can be read for the next file.
    45  // Any remaining data in the current file is automatically discarded.
    46  // At the end of the archive, Next returns the error io.EOF.
    47  //
    48  // If Next encounters a non-local name (as defined by [filepath.IsLocal])
    49  // and the GODEBUG environment variable contains `tarinsecurepath=0`,
    50  // Next returns the header with an [ErrInsecurePath] error.
    51  // A future version of Go may introduce this behavior by default.
    52  // Programs that want to accept non-local names can ignore
    53  // the [ErrInsecurePath] error and use the returned header.
    54  func (tr *Reader) Next() (*Header, error) {
    55  	if tr.err != nil {
    56  		return nil, tr.err
    57  	}
    58  	hdr, err := tr.next()
    59  	tr.err = err
    60  	if err == nil && !filepath.IsLocal(hdr.Name) {
    61  		if tarinsecurepath.Value() == "0" {
    62  			tarinsecurepath.IncNonDefault()
    63  			err = ErrInsecurePath
    64  		}
    65  	}
    66  	return hdr, err
    67  }
    68  
    69  func (tr *Reader) next() (*Header, error) {
    70  	var paxHdrs map[string]string
    71  	var gnuLongName, gnuLongLink string
    72  
    73  	// Externally, Next iterates through the tar archive as if it is a series of
    74  	// files. Internally, the tar format often uses fake "files" to add meta
    75  	// data that describes the next file. These meta data "files" should not
    76  	// normally be visible to the outside. As such, this loop iterates through
    77  	// one or more "header files" until it finds a "normal file".
    78  	format := FormatUSTAR | FormatPAX | FormatGNU
    79  	for {
    80  		// Discard the remainder of the file and any padding.
    81  		if err := discard(tr.r, tr.curr.physicalRemaining()); err != nil {
    82  			return nil, err
    83  		}
    84  		if _, err := tryReadFull(tr.r, tr.blk[:tr.pad]); err != nil {
    85  			return nil, err
    86  		}
    87  		tr.pad = 0
    88  
    89  		hdr, rawHdr, err := tr.readHeader()
    90  		if err != nil {
    91  			return nil, err
    92  		}
    93  		if err := tr.handleRegularFile(hdr); err != nil {
    94  			return nil, err
    95  		}
    96  		format.mayOnlyBe(hdr.Format)
    97  
    98  		// Check for PAX/GNU special headers and files.
    99  		switch hdr.Typeflag {
   100  		case TypeXHeader, TypeXGlobalHeader:
   101  			format.mayOnlyBe(FormatPAX)
   102  			paxHdrs, err = parsePAX(tr)
   103  			if err != nil {
   104  				return nil, err
   105  			}
   106  			if hdr.Typeflag == TypeXGlobalHeader {
   107  				mergePAX(hdr, paxHdrs)
   108  				return &Header{
   109  					Name:       hdr.Name,
   110  					Typeflag:   hdr.Typeflag,
   111  					Xattrs:     hdr.Xattrs,
   112  					PAXRecords: hdr.PAXRecords,
   113  					Format:     format,
   114  				}, nil
   115  			}
   116  			continue // This is a meta header affecting the next header
   117  		case TypeGNULongName, TypeGNULongLink:
   118  			format.mayOnlyBe(FormatGNU)
   119  			realname, err := readSpecialFile(tr)
   120  			if err != nil {
   121  				return nil, err
   122  			}
   123  
   124  			var p parser
   125  			switch hdr.Typeflag {
   126  			case TypeGNULongName:
   127  				gnuLongName = p.parseString(realname)
   128  			case TypeGNULongLink:
   129  				gnuLongLink = p.parseString(realname)
   130  			}
   131  			continue // This is a meta header affecting the next header
   132  		default:
   133  			// The old GNU sparse format is handled here since it is technically
   134  			// just a regular file with additional attributes.
   135  
   136  			if err := mergePAX(hdr, paxHdrs); err != nil {
   137  				return nil, err
   138  			}
   139  			if gnuLongName != "" {
   140  				hdr.Name = gnuLongName
   141  			}
   142  			if gnuLongLink != "" {
   143  				hdr.Linkname = gnuLongLink
   144  			}
   145  			if hdr.Typeflag == TypeRegA {
   146  				if strings.HasSuffix(hdr.Name, "/") {
   147  					hdr.Typeflag = TypeDir // Legacy archives use trailing slash for directories
   148  				} else {
   149  					hdr.Typeflag = TypeReg
   150  				}
   151  			}
   152  
   153  			// The extended headers may have updated the size.
   154  			// Thus, setup the regFileReader again after merging PAX headers.
   155  			if err := tr.handleRegularFile(hdr); err != nil {
   156  				return nil, err
   157  			}
   158  
   159  			// Sparse formats rely on being able to read from the logical data
   160  			// section; there must be a preceding call to handleRegularFile.
   161  			if err := tr.handleSparseFile(hdr, rawHdr); err != nil {
   162  				return nil, err
   163  			}
   164  
   165  			// Set the final guess at the format.
   166  			if format.has(FormatUSTAR) && format.has(FormatPAX) {
   167  				format.mayOnlyBe(FormatUSTAR)
   168  			}
   169  			hdr.Format = format
   170  			return hdr, nil // This is a file, so stop
   171  		}
   172  	}
   173  }
   174  
   175  // handleRegularFile sets up the current file reader and padding such that it
   176  // can only read the following logical data section. It will properly handle
   177  // special headers that contain no data section.
   178  func (tr *Reader) handleRegularFile(hdr *Header) error {
   179  	nb := hdr.Size
   180  	if isHeaderOnlyType(hdr.Typeflag) {
   181  		nb = 0
   182  	}
   183  	if nb < 0 {
   184  		return ErrHeader
   185  	}
   186  
   187  	tr.pad = blockPadding(nb)
   188  	tr.curr = &regFileReader{r: tr.r, nb: nb}
   189  	return nil
   190  }
   191  
   192  // handleSparseFile checks if the current file is a sparse format of any type
   193  // and sets the curr reader appropriately.
   194  func (tr *Reader) handleSparseFile(hdr *Header, rawHdr *block) error {
   195  	var spd sparseDatas
   196  	var err error
   197  	if hdr.Typeflag == TypeGNUSparse {
   198  		spd, err = tr.readOldGNUSparseMap(hdr, rawHdr)
   199  	} else {
   200  		spd, err = tr.readGNUSparsePAXHeaders(hdr)
   201  	}
   202  
   203  	// If sp is non-nil, then this is a sparse file.
   204  	// Note that it is possible for len(sp) == 0.
   205  	if err == nil && spd != nil {
   206  		if isHeaderOnlyType(hdr.Typeflag) || !validateSparseEntries(spd, hdr.Size) {
   207  			return ErrHeader
   208  		}
   209  		sph := invertSparseEntries(spd, hdr.Size)
   210  		tr.curr = &sparseFileReader{tr.curr, sph, 0}
   211  	}
   212  	return err
   213  }
   214  
   215  // readGNUSparsePAXHeaders checks the PAX headers for GNU sparse headers.
   216  // If they are found, then this function reads the sparse map and returns it.
   217  // This assumes that 0.0 headers have already been converted to 0.1 headers
   218  // by the PAX header parsing logic.
   219  func (tr *Reader) readGNUSparsePAXHeaders(hdr *Header) (sparseDatas, error) {
   220  	// Identify the version of GNU headers.
   221  	var is1x0 bool
   222  	major, minor := hdr.PAXRecords[paxGNUSparseMajor], hdr.PAXRecords[paxGNUSparseMinor]
   223  	switch {
   224  	case major == "0" && (minor == "0" || minor == "1"):
   225  		is1x0 = false
   226  	case major == "1" && minor == "0":
   227  		is1x0 = true
   228  	case major != "" || minor != "":
   229  		return nil, nil // Unknown GNU sparse PAX version
   230  	case hdr.PAXRecords[paxGNUSparseMap] != "":
   231  		is1x0 = false // 0.0 and 0.1 did not have explicit version records, so guess
   232  	default:
   233  		return nil, nil // Not a PAX format GNU sparse file.
   234  	}
   235  	hdr.Format.mayOnlyBe(FormatPAX)
   236  
   237  	// Update hdr from GNU sparse PAX headers.
   238  	if name := hdr.PAXRecords[paxGNUSparseName]; name != "" {
   239  		hdr.Name = name
   240  	}
   241  	size := hdr.PAXRecords[paxGNUSparseSize]
   242  	if size == "" {
   243  		size = hdr.PAXRecords[paxGNUSparseRealSize]
   244  	}
   245  	if size != "" {
   246  		n, err := strconv.ParseInt(size, 10, 64)
   247  		if err != nil {
   248  			return nil, ErrHeader
   249  		}
   250  		hdr.Size = n
   251  	}
   252  
   253  	// Read the sparse map according to the appropriate format.
   254  	if is1x0 {
   255  		return readGNUSparseMap1x0(tr.curr)
   256  	}
   257  	return readGNUSparseMap0x1(hdr.PAXRecords)
   258  }
   259  
   260  // mergePAX merges paxHdrs into hdr for all relevant fields of Header.
   261  func mergePAX(hdr *Header, paxHdrs map[string]string) (err error) {
   262  	for k, v := range paxHdrs {
   263  		if v == "" {
   264  			continue // Keep the original USTAR value
   265  		}
   266  		var id64 int64
   267  		switch k {
   268  		case paxPath:
   269  			hdr.Name = v
   270  		case paxLinkpath:
   271  			hdr.Linkname = v
   272  		case paxUname:
   273  			hdr.Uname = v
   274  		case paxGname:
   275  			hdr.Gname = v
   276  		case paxUid:
   277  			id64, err = strconv.ParseInt(v, 10, 64)
   278  			hdr.Uid = int(id64) // Integer overflow possible
   279  		case paxGid:
   280  			id64, err = strconv.ParseInt(v, 10, 64)
   281  			hdr.Gid = int(id64) // Integer overflow possible
   282  		case paxAtime:
   283  			hdr.AccessTime, err = parsePAXTime(v)
   284  		case paxMtime:
   285  			hdr.ModTime, err = parsePAXTime(v)
   286  		case paxCtime:
   287  			hdr.ChangeTime, err = parsePAXTime(v)
   288  		case paxSize:
   289  			hdr.Size, err = strconv.ParseInt(v, 10, 64)
   290  		default:
   291  			if strings.HasPrefix(k, paxSchilyXattr) {
   292  				if hdr.Xattrs == nil {
   293  					hdr.Xattrs = make(map[string]string)
   294  				}
   295  				hdr.Xattrs[k[len(paxSchilyXattr):]] = v
   296  			}
   297  		}
   298  		if err != nil {
   299  			return ErrHeader
   300  		}
   301  	}
   302  	hdr.PAXRecords = paxHdrs
   303  	return nil
   304  }
   305  
   306  // parsePAX parses PAX headers.
   307  // If an extended header (type 'x') is invalid, ErrHeader is returned.
   308  func parsePAX(r io.Reader) (map[string]string, error) {
   309  	buf, err := readSpecialFile(r)
   310  	if err != nil {
   311  		return nil, err
   312  	}
   313  	sbuf := string(buf)
   314  
   315  	// For GNU PAX sparse format 0.0 support.
   316  	// This function transforms the sparse format 0.0 headers into format 0.1
   317  	// headers since 0.0 headers were not PAX compliant.
   318  	var sparseMap []string
   319  
   320  	paxHdrs := make(map[string]string)
   321  	for len(sbuf) > 0 {
   322  		key, value, residual, err := parsePAXRecord(sbuf)
   323  		if err != nil {
   324  			return nil, ErrHeader
   325  		}
   326  		sbuf = residual
   327  
   328  		switch key {
   329  		case paxGNUSparseOffset, paxGNUSparseNumBytes:
   330  			// Validate sparse header order and value.
   331  			if (len(sparseMap)%2 == 0 && key != paxGNUSparseOffset) ||
   332  				(len(sparseMap)%2 == 1 && key != paxGNUSparseNumBytes) ||
   333  				strings.Contains(value, ",") {
   334  				return nil, ErrHeader
   335  			}
   336  			sparseMap = append(sparseMap, value)
   337  		default:
   338  			paxHdrs[key] = value
   339  		}
   340  	}
   341  	if len(sparseMap) > 0 {
   342  		paxHdrs[paxGNUSparseMap] = strings.Join(sparseMap, ",")
   343  	}
   344  	return paxHdrs, nil
   345  }
   346  
   347  // readHeader reads the next block header and assumes that the underlying reader
   348  // is already aligned to a block boundary. It returns the raw block of the
   349  // header in case further processing is required.
   350  //
   351  // The err will be set to io.EOF only when one of the following occurs:
   352  //   - Exactly 0 bytes are read and EOF is hit.
   353  //   - Exactly 1 block of zeros is read and EOF is hit.
   354  //   - At least 2 blocks of zeros are read.
   355  func (tr *Reader) readHeader() (*Header, *block, error) {
   356  	// Two blocks of zero bytes marks the end of the archive.
   357  	if _, err := io.ReadFull(tr.r, tr.blk[:]); err != nil {
   358  		return nil, nil, err // EOF is okay here; exactly 0 bytes read
   359  	}
   360  	if bytes.Equal(tr.blk[:], zeroBlock[:]) {
   361  		if _, err := io.ReadFull(tr.r, tr.blk[:]); err != nil {
   362  			return nil, nil, err // EOF is okay here; exactly 1 block of zeros read
   363  		}
   364  		if bytes.Equal(tr.blk[:], zeroBlock[:]) {
   365  			return nil, nil, io.EOF // normal EOF; exactly 2 block of zeros read
   366  		}
   367  		return nil, nil, ErrHeader // Zero block and then non-zero block
   368  	}
   369  
   370  	// Verify the header matches a known format.
   371  	format := tr.blk.getFormat()
   372  	if format == FormatUnknown {
   373  		return nil, nil, ErrHeader
   374  	}
   375  
   376  	var p parser
   377  	hdr := new(Header)
   378  
   379  	// Unpack the V7 header.
   380  	v7 := tr.blk.toV7()
   381  	hdr.Typeflag = v7.typeFlag()[0]
   382  	hdr.Name = p.parseString(v7.name())
   383  	hdr.Linkname = p.parseString(v7.linkName())
   384  	hdr.Size = p.parseNumeric(v7.size())
   385  	hdr.Mode = p.parseNumeric(v7.mode())
   386  	hdr.Uid = int(p.parseNumeric(v7.uid()))
   387  	hdr.Gid = int(p.parseNumeric(v7.gid()))
   388  	hdr.ModTime = time.Unix(p.parseNumeric(v7.modTime()), 0)
   389  
   390  	// Unpack format specific fields.
   391  	if format > formatV7 {
   392  		ustar := tr.blk.toUSTAR()
   393  		hdr.Uname = p.parseString(ustar.userName())
   394  		hdr.Gname = p.parseString(ustar.groupName())
   395  		hdr.Devmajor = p.parseNumeric(ustar.devMajor())
   396  		hdr.Devminor = p.parseNumeric(ustar.devMinor())
   397  
   398  		var prefix string
   399  		switch {
   400  		case format.has(FormatUSTAR | FormatPAX):
   401  			hdr.Format = format
   402  			ustar := tr.blk.toUSTAR()
   403  			prefix = p.parseString(ustar.prefix())
   404  
   405  			// For Format detection, check if block is properly formatted since
   406  			// the parser is more liberal than what USTAR actually permits.
   407  			notASCII := func(r rune) bool { return r >= 0x80 }
   408  			if bytes.IndexFunc(tr.blk[:], notASCII) >= 0 {
   409  				hdr.Format = FormatUnknown // Non-ASCII characters in block.
   410  			}
   411  			nul := func(b []byte) bool { return int(b[len(b)-1]) == 0 }
   412  			if !(nul(v7.size()) && nul(v7.mode()) && nul(v7.uid()) && nul(v7.gid()) &&
   413  				nul(v7.modTime()) && nul(ustar.devMajor()) && nul(ustar.devMinor())) {
   414  				hdr.Format = FormatUnknown // Numeric fields must end in NUL
   415  			}
   416  		case format.has(formatSTAR):
   417  			star := tr.blk.toSTAR()
   418  			prefix = p.parseString(star.prefix())
   419  			hdr.AccessTime = time.Unix(p.parseNumeric(star.accessTime()), 0)
   420  			hdr.ChangeTime = time.Unix(p.parseNumeric(star.changeTime()), 0)
   421  		case format.has(FormatGNU):
   422  			hdr.Format = format
   423  			var p2 parser
   424  			gnu := tr.blk.toGNU()
   425  			if b := gnu.accessTime(); b[0] != 0 {
   426  				hdr.AccessTime = time.Unix(p2.parseNumeric(b), 0)
   427  			}
   428  			if b := gnu.changeTime(); b[0] != 0 {
   429  				hdr.ChangeTime = time.Unix(p2.parseNumeric(b), 0)
   430  			}
   431  
   432  			// Prior to Go1.8, the Writer had a bug where it would output
   433  			// an invalid tar file in certain rare situations because the logic
   434  			// incorrectly believed that the old GNU format had a prefix field.
   435  			// This is wrong and leads to an output file that mangles the
   436  			// atime and ctime fields, which are often left unused.
   437  			//
   438  			// In order to continue reading tar files created by former, buggy
   439  			// versions of Go, we skeptically parse the atime and ctime fields.
   440  			// If we are unable to parse them and the prefix field looks like
   441  			// an ASCII string, then we fallback on the pre-Go1.8 behavior
   442  			// of treating these fields as the USTAR prefix field.
   443  			//
   444  			// Note that this will not use the fallback logic for all possible
   445  			// files generated by a pre-Go1.8 toolchain. If the generated file
   446  			// happened to have a prefix field that parses as valid
   447  			// atime and ctime fields (e.g., when they are valid octal strings),
   448  			// then it is impossible to distinguish between a valid GNU file
   449  			// and an invalid pre-Go1.8 file.
   450  			//
   451  			// See https://golang.org/issues/12594
   452  			// See https://golang.org/issues/21005
   453  			if p2.err != nil {
   454  				hdr.AccessTime, hdr.ChangeTime = time.Time{}, time.Time{}
   455  				ustar := tr.blk.toUSTAR()
   456  				if s := p.parseString(ustar.prefix()); isASCII(s) {
   457  					prefix = s
   458  				}
   459  				hdr.Format = FormatUnknown // Buggy file is not GNU
   460  			}
   461  		}
   462  		if len(prefix) > 0 {
   463  			hdr.Name = prefix + "/" + hdr.Name
   464  		}
   465  	}
   466  	return hdr, &tr.blk, p.err
   467  }
   468  
   469  // readOldGNUSparseMap reads the sparse map from the old GNU sparse format.
   470  // The sparse map is stored in the tar header if it's small enough.
   471  // If it's larger than four entries, then one or more extension headers are used
   472  // to store the rest of the sparse map.
   473  //
   474  // The Header.Size does not reflect the size of any extended headers used.
   475  // Thus, this function will read from the raw io.Reader to fetch extra headers.
   476  // This method mutates blk in the process.
   477  func (tr *Reader) readOldGNUSparseMap(hdr *Header, blk *block) (sparseDatas, error) {
   478  	// Make sure that the input format is GNU.
   479  	// Unfortunately, the STAR format also has a sparse header format that uses
   480  	// the same type flag but has a completely different layout.
   481  	if blk.getFormat() != FormatGNU {
   482  		return nil, ErrHeader
   483  	}
   484  	hdr.Format.mayOnlyBe(FormatGNU)
   485  
   486  	var p parser
   487  	hdr.Size = p.parseNumeric(blk.toGNU().realSize())
   488  	if p.err != nil {
   489  		return nil, p.err
   490  	}
   491  	s := blk.toGNU().sparse()
   492  	spd := make(sparseDatas, 0, s.maxEntries())
   493  	totalSize := len(s)
   494  	for totalSize < maxSpecialFileSize {
   495  		for i := 0; i < s.maxEntries(); i++ {
   496  			// This termination condition is identical to GNU and BSD tar.
   497  			if s.entry(i).offset()[0] == 0x00 {
   498  				break // Don't return, need to process extended headers (even if empty)
   499  			}
   500  			offset := p.parseNumeric(s.entry(i).offset())
   501  			length := p.parseNumeric(s.entry(i).length())
   502  			if p.err != nil {
   503  				return nil, p.err
   504  			}
   505  			var err error
   506  			spd, err = appendSparseEntry(spd, sparseEntry{Offset: offset, Length: length})
   507  			if err != nil {
   508  				return nil, err
   509  			}
   510  		}
   511  
   512  		if s.isExtended()[0] > 0 {
   513  			// There are more entries. Read an extension header and parse its entries.
   514  			if _, err := mustReadFull(tr.r, blk[:]); err != nil {
   515  				return nil, err
   516  			}
   517  			s = blk.toSparse()
   518  			totalSize += len(s)
   519  			continue
   520  		}
   521  		return spd, nil // Done
   522  	}
   523  	return nil, errSparseTooLong
   524  }
   525  
   526  // readGNUSparseMap1x0 reads the sparse map as stored in GNU's PAX sparse format
   527  // version 1.0. The format of the sparse map consists of a series of
   528  // newline-terminated numeric fields. The first field is the number of entries
   529  // and is always present. Following this are the entries, consisting of two
   530  // fields (offset, length). This function must stop reading at the end
   531  // boundary of the block containing the last newline.
   532  //
   533  // Note that the GNU manual says that numeric values should be encoded in octal
   534  // format. However, the GNU tar utility itself outputs these values in decimal.
   535  // As such, this library treats values as being encoded in decimal.
   536  func readGNUSparseMap1x0(r io.Reader) (sparseDatas, error) {
   537  	var (
   538  		cntNewline int64
   539  		buf        bytes.Buffer
   540  		blk        block
   541  		totalSize  int
   542  	)
   543  
   544  	// feedTokens copies data in blocks from r into buf until there are
   545  	// at least cnt newlines in buf. It will not read more blocks than needed.
   546  	feedTokens := func(n int64) error {
   547  		for cntNewline < n {
   548  			totalSize += len(blk)
   549  			if totalSize > maxSpecialFileSize {
   550  				return errSparseTooLong
   551  			}
   552  			if _, err := mustReadFull(r, blk[:]); err != nil {
   553  				return err
   554  			}
   555  			buf.Write(blk[:])
   556  			for _, c := range blk {
   557  				if c == '\n' {
   558  					cntNewline++
   559  				}
   560  			}
   561  		}
   562  		return nil
   563  	}
   564  
   565  	// nextToken gets the next token delimited by a newline. This assumes that
   566  	// at least one newline exists in the buffer.
   567  	nextToken := func() string {
   568  		cntNewline--
   569  		tok, _ := buf.ReadString('\n')
   570  		return strings.TrimRight(tok, "\n")
   571  	}
   572  
   573  	// Parse for the number of entries.
   574  	// Use integer overflow resistant math to check this.
   575  	if err := feedTokens(1); err != nil {
   576  		return nil, err
   577  	}
   578  	numEntries, err := strconv.ParseInt(nextToken(), 10, 0) // Intentionally parse as native int
   579  	if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
   580  		return nil, ErrHeader
   581  	}
   582  
   583  	// Parse for all member entries.
   584  	// numEntries is trusted after this since feedTokens limits the number of
   585  	// tokens based on maxSpecialFileSize.
   586  	if err := feedTokens(2 * numEntries); err != nil {
   587  		return nil, err
   588  	}
   589  	spd := make(sparseDatas, 0, numEntries)
   590  	for i := int64(0); i < numEntries; i++ {
   591  		offset, err1 := strconv.ParseInt(nextToken(), 10, 64)
   592  		length, err2 := strconv.ParseInt(nextToken(), 10, 64)
   593  		if err1 != nil || err2 != nil {
   594  			return nil, ErrHeader
   595  		}
   596  		spd, err = appendSparseEntry(spd, sparseEntry{Offset: offset, Length: length})
   597  		if err != nil {
   598  			return nil, err
   599  		}
   600  	}
   601  	return spd, nil
   602  }
   603  
   604  // readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse format
   605  // version 0.1. The sparse map is stored in the PAX headers.
   606  func readGNUSparseMap0x1(paxHdrs map[string]string) (sparseDatas, error) {
   607  	// Get number of entries.
   608  	// Use integer overflow resistant math to check this.
   609  	numEntriesStr := paxHdrs[paxGNUSparseNumBlocks]
   610  	numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0) // Intentionally parse as native int
   611  	if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
   612  		return nil, ErrHeader
   613  	}
   614  
   615  	// There should be two numbers in sparseMap for each entry.
   616  	sparseMap := strings.Split(paxHdrs[paxGNUSparseMap], ",")
   617  	if len(sparseMap) == 1 && sparseMap[0] == "" {
   618  		sparseMap = sparseMap[:0]
   619  	}
   620  	if int64(len(sparseMap)) != 2*numEntries {
   621  		return nil, ErrHeader
   622  	}
   623  
   624  	// Loop through the entries in the sparse map.
   625  	// numEntries is trusted now.
   626  	spd := make(sparseDatas, 0, numEntries)
   627  	for len(sparseMap) >= 2 {
   628  		offset, err1 := strconv.ParseInt(sparseMap[0], 10, 64)
   629  		length, err2 := strconv.ParseInt(sparseMap[1], 10, 64)
   630  		if err1 != nil || err2 != nil {
   631  			return nil, ErrHeader
   632  		}
   633  		spd, err = appendSparseEntry(spd, sparseEntry{Offset: offset, Length: length})
   634  		if err != nil {
   635  			return nil, err
   636  		}
   637  		sparseMap = sparseMap[2:]
   638  	}
   639  	return spd, nil
   640  }
   641  
   642  func appendSparseEntry(spd sparseDatas, ent sparseEntry) (sparseDatas, error) {
   643  	if len(spd) >= maxSparseFileEntries {
   644  		return nil, errSparseTooLong
   645  	}
   646  	return append(spd, ent), nil
   647  }
   648  
   649  // Read reads from the current file in the tar archive.
   650  // It returns (0, io.EOF) when it reaches the end of that file,
   651  // until [Next] is called to advance to the next file.
   652  //
   653  // If the current file is sparse, then the regions marked as a hole
   654  // are read back as NUL-bytes.
   655  //
   656  // Calling Read on special types like [TypeLink], [TypeSymlink], [TypeChar],
   657  // [TypeBlock], [TypeDir], and [TypeFifo] returns (0, [io.EOF]) regardless of what
   658  // the [Header.Size] claims.
   659  func (tr *Reader) Read(b []byte) (int, error) {
   660  	if tr.err != nil {
   661  		return 0, tr.err
   662  	}
   663  	n, err := tr.curr.Read(b)
   664  	if err != nil && err != io.EOF {
   665  		tr.err = err
   666  	}
   667  	return n, err
   668  }
   669  
   670  // writeTo writes the content of the current file to w.
   671  // The bytes written matches the number of remaining bytes in the current file.
   672  //
   673  // If the current file is sparse and w is an io.WriteSeeker,
   674  // then writeTo uses Seek to skip past holes defined in Header.SparseHoles,
   675  // assuming that skipped regions are filled with NULs.
   676  // This always writes the last byte to ensure w is the right size.
   677  //
   678  // TODO(dsnet): Re-export this when adding sparse file support.
   679  // See https://golang.org/issue/22735
   680  func (tr *Reader) writeTo(w io.Writer) (int64, error) {
   681  	if tr.err != nil {
   682  		return 0, tr.err
   683  	}
   684  	n, err := tr.curr.WriteTo(w)
   685  	if err != nil {
   686  		tr.err = err
   687  	}
   688  	return n, err
   689  }
   690  
   691  // regFileReader is a fileReader for reading data from a regular file entry.
   692  type regFileReader struct {
   693  	r  io.Reader // Underlying Reader
   694  	nb int64     // Number of remaining bytes to read
   695  }
   696  
   697  func (fr *regFileReader) Read(b []byte) (n int, err error) {
   698  	if int64(len(b)) > fr.nb {
   699  		b = b[:fr.nb]
   700  	}
   701  	if len(b) > 0 {
   702  		n, err = fr.r.Read(b)
   703  		fr.nb -= int64(n)
   704  	}
   705  	switch {
   706  	case err == io.EOF && fr.nb > 0:
   707  		return n, io.ErrUnexpectedEOF
   708  	case err == nil && fr.nb == 0:
   709  		return n, io.EOF
   710  	default:
   711  		return n, err
   712  	}
   713  }
   714  
   715  func (fr *regFileReader) WriteTo(w io.Writer) (int64, error) {
   716  	return io.Copy(w, struct{ io.Reader }{fr})
   717  }
   718  
   719  // logicalRemaining implements fileState.logicalRemaining.
   720  func (fr regFileReader) logicalRemaining() int64 {
   721  	return fr.nb
   722  }
   723  
   724  // physicalRemaining implements fileState.physicalRemaining.
   725  func (fr regFileReader) physicalRemaining() int64 {
   726  	return fr.nb
   727  }
   728  
   729  // sparseFileReader is a fileReader for reading data from a sparse file entry.
   730  type sparseFileReader struct {
   731  	fr  fileReader  // Underlying fileReader
   732  	sp  sparseHoles // Normalized list of sparse holes
   733  	pos int64       // Current position in sparse file
   734  }
   735  
   736  func (sr *sparseFileReader) Read(b []byte) (n int, err error) {
   737  	finished := int64(len(b)) >= sr.logicalRemaining()
   738  	if finished {
   739  		b = b[:sr.logicalRemaining()]
   740  	}
   741  
   742  	b0 := b
   743  	endPos := sr.pos + int64(len(b))
   744  	for endPos > sr.pos && err == nil {
   745  		var nf int // Bytes read in fragment
   746  		holeStart, holeEnd := sr.sp[0].Offset, sr.sp[0].endOffset()
   747  		if sr.pos < holeStart { // In a data fragment
   748  			bf := b[:min(int64(len(b)), holeStart-sr.pos)]
   749  			nf, err = tryReadFull(sr.fr, bf)
   750  		} else { // In a hole fragment
   751  			bf := b[:min(int64(len(b)), holeEnd-sr.pos)]
   752  			nf, err = tryReadFull(zeroReader{}, bf)
   753  		}
   754  		b = b[nf:]
   755  		sr.pos += int64(nf)
   756  		if sr.pos >= holeEnd && len(sr.sp) > 1 {
   757  			sr.sp = sr.sp[1:] // Ensure last fragment always remains
   758  		}
   759  	}
   760  
   761  	n = len(b0) - len(b)
   762  	switch {
   763  	case err == io.EOF:
   764  		return n, errMissData // Less data in dense file than sparse file
   765  	case err != nil:
   766  		return n, err
   767  	case sr.logicalRemaining() == 0 && sr.physicalRemaining() > 0:
   768  		return n, errUnrefData // More data in dense file than sparse file
   769  	case finished:
   770  		return n, io.EOF
   771  	default:
   772  		return n, nil
   773  	}
   774  }
   775  
   776  func (sr *sparseFileReader) WriteTo(w io.Writer) (n int64, err error) {
   777  	ws, ok := w.(io.WriteSeeker)
   778  	if ok {
   779  		if _, err := ws.Seek(0, io.SeekCurrent); err != nil {
   780  			ok = false // Not all io.Seeker can really seek
   781  		}
   782  	}
   783  	if !ok {
   784  		return io.Copy(w, struct{ io.Reader }{sr})
   785  	}
   786  
   787  	var writeLastByte bool
   788  	pos0 := sr.pos
   789  	for sr.logicalRemaining() > 0 && !writeLastByte && err == nil {
   790  		var nf int64 // Size of fragment
   791  		holeStart, holeEnd := sr.sp[0].Offset, sr.sp[0].endOffset()
   792  		if sr.pos < holeStart { // In a data fragment
   793  			nf = holeStart - sr.pos
   794  			nf, err = io.CopyN(ws, sr.fr, nf)
   795  		} else { // In a hole fragment
   796  			nf = holeEnd - sr.pos
   797  			if sr.physicalRemaining() == 0 {
   798  				writeLastByte = true
   799  				nf--
   800  			}
   801  			_, err = ws.Seek(nf, io.SeekCurrent)
   802  		}
   803  		sr.pos += nf
   804  		if sr.pos >= holeEnd && len(sr.sp) > 1 {
   805  			sr.sp = sr.sp[1:] // Ensure last fragment always remains
   806  		}
   807  	}
   808  
   809  	// If the last fragment is a hole, then seek to 1-byte before EOF, and
   810  	// write a single byte to ensure the file is the right size.
   811  	if writeLastByte && err == nil {
   812  		_, err = ws.Write([]byte{0})
   813  		sr.pos++
   814  	}
   815  
   816  	n = sr.pos - pos0
   817  	switch {
   818  	case err == io.EOF:
   819  		return n, errMissData // Less data in dense file than sparse file
   820  	case err != nil:
   821  		return n, err
   822  	case sr.logicalRemaining() == 0 && sr.physicalRemaining() > 0:
   823  		return n, errUnrefData // More data in dense file than sparse file
   824  	default:
   825  		return n, nil
   826  	}
   827  }
   828  
   829  func (sr sparseFileReader) logicalRemaining() int64 {
   830  	return sr.sp[len(sr.sp)-1].endOffset() - sr.pos
   831  }
   832  func (sr sparseFileReader) physicalRemaining() int64 {
   833  	return sr.fr.physicalRemaining()
   834  }
   835  
   836  type zeroReader struct{}
   837  
   838  func (zeroReader) Read(b []byte) (int, error) {
   839  	clear(b)
   840  	return len(b), nil
   841  }
   842  
   843  // mustReadFull is like io.ReadFull except it returns
   844  // io.ErrUnexpectedEOF when io.EOF is hit before len(b) bytes are read.
   845  func mustReadFull(r io.Reader, b []byte) (int, error) {
   846  	n, err := tryReadFull(r, b)
   847  	if err == io.EOF {
   848  		err = io.ErrUnexpectedEOF
   849  	}
   850  	return n, err
   851  }
   852  
   853  // tryReadFull is like io.ReadFull except it returns
   854  // io.EOF when it is hit before len(b) bytes are read.
   855  func tryReadFull(r io.Reader, b []byte) (n int, err error) {
   856  	for len(b) > n && err == nil {
   857  		var nn int
   858  		nn, err = r.Read(b[n:])
   859  		n += nn
   860  	}
   861  	if len(b) == n && err == io.EOF {
   862  		err = nil
   863  	}
   864  	return n, err
   865  }
   866  
   867  // readSpecialFile is like io.ReadAll except it returns
   868  // ErrFieldTooLong if more than maxSpecialFileSize is read.
   869  func readSpecialFile(r io.Reader) ([]byte, error) {
   870  	buf, err := io.ReadAll(io.LimitReader(r, maxSpecialFileSize+1))
   871  	if len(buf) > maxSpecialFileSize {
   872  		return nil, ErrFieldTooLong
   873  	}
   874  	return buf, err
   875  }
   876  
   877  // discard skips n bytes in r, reporting an error if unable to do so.
   878  func discard(r io.Reader, n int64) error {
   879  	// If possible, Seek to the last byte before the end of the data section.
   880  	// Do this because Seek is often lazy about reporting errors; this will mask
   881  	// the fact that the stream may be truncated. We can rely on the
   882  	// io.CopyN done shortly afterwards to trigger any IO errors.
   883  	var seekSkipped int64 // Number of bytes skipped via Seek
   884  	if sr, ok := r.(io.Seeker); ok && n > 1 {
   885  		// Not all io.Seeker can actually Seek. For example, os.Stdin implements
   886  		// io.Seeker, but calling Seek always returns an error and performs
   887  		// no action. Thus, we try an innocent seek to the current position
   888  		// to see if Seek is really supported.
   889  		pos1, err := sr.Seek(0, io.SeekCurrent)
   890  		if pos1 >= 0 && err == nil {
   891  			// Seek seems supported, so perform the real Seek.
   892  			pos2, err := sr.Seek(n-1, io.SeekCurrent)
   893  			if pos2 < 0 || err != nil {
   894  				return err
   895  			}
   896  			seekSkipped = pos2 - pos1
   897  		}
   898  	}
   899  
   900  	copySkipped, err := io.CopyN(io.Discard, r, n-seekSkipped)
   901  	if err == io.EOF && seekSkipped+copySkipped < n {
   902  		err = io.ErrUnexpectedEOF
   903  	}
   904  	return err
   905  }
   906  

View as plain text