github.com/pachyderm/pachyderm@v1.13.4/src/server/pkg/tar/reader.go (about)

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