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