func (sfr *sparseFileReader) readHole(b []byte, endOffset int64) int {
	n64 := endOffset - sfr.pos
	if n64 > int64(len(b)) {
		n64 = int64(len(b))
	}
	n := int(n64)
	for i := 0; i < n; i++ {
		b[i] = 0
	}
	sfr.pos += n64
	return n
}
readHole reads a sparse hole ending at endOffset.
package tar
import (
	"bytes"
	"errors"
	"io"
	"io/ioutil"
	"math"
	"os"
	"strconv"
	"strings"
	"time"
)
var (
	ErrHeader = errors.New("archive/tar: invalid tar header")
)
const maxNanoSecondIntSize = 9
type Reader struct {
	r       io.Reader
	err     error
	pad     int64            
	curr    numBytesReader   
	hdrBuff [blockSize]byte  
	RawAccounting bool           
	rawBytes      *bytes.Buffer  
}
type parser struct {
	err error  
}
func (tr *Reader) RawBytes() []byte {
	if !tr.RawAccounting {
		return nil
	}
	if tr.rawBytes == nil {
		tr.rawBytes = bytes.NewBuffer(nil)
	}
	defer tr.rawBytes.Reset()
	return tr.rawBytes.Bytes()
}
type numBytesReader interface {
	io.Reader
	numBytes() int64
}
type regFileReader struct {
	r  io.Reader  
	nb int64      
}
type sparseFileReader struct {
	rfr   numBytesReader  
	sp    []sparseEntry   
	pos   int64           
	total int64           
}
type sparseEntry struct {
	offset   int64  
	numBytes int64  
}
const (
	paxGNUSparseNumBlocks = "GNU.sparse.numblocks"
	paxGNUSparseOffset    = "GNU.sparse.offset"
	paxGNUSparseNumBytes  = "GNU.sparse.numbytes"
	paxGNUSparseMap       = "GNU.sparse.map"
	paxGNUSparseName      = "GNU.sparse.name"
	paxGNUSparseMajor     = "GNU.sparse.major"
	paxGNUSparseMinor     = "GNU.sparse.minor"
	paxGNUSparseSize      = "GNU.sparse.size"
	paxGNUSparseRealSize  = "GNU.sparse.realsize"
)
const (
	oldGNUSparseMainHeaderOffset               = 386
	oldGNUSparseMainHeaderIsExtendedOffset     = 482
	oldGNUSparseMainHeaderNumEntries           = 4
	oldGNUSparseExtendedHeaderIsExtendedOffset = 504
	oldGNUSparseExtendedHeaderNumEntries       = 21
	oldGNUSparseOffsetSize                     = 12
	oldGNUSparseNumBytesSize                   = 12
)
func NewReader(r io.Reader) *Reader { return &Reader{r: r} }
func (tr *Reader) Next() (*Header, error) {
	if tr.RawAccounting {
		if tr.rawBytes == nil {
			tr.rawBytes = bytes.NewBuffer(nil)
		} else {
			tr.rawBytes.Reset()
		}
	}
	if tr.err != nil {
		return nil, tr.err
	}
	var hdr *Header
	var extHdrs map[string]string
loop:
	for {
		tr.err = tr.skipUnread()
		if tr.err != nil {
			return nil, tr.err
		}
		hdr = tr.readHeader()
		if tr.err != nil {
			return nil, tr.err
		}
		switch hdr.Typeflag {
		case TypeXHeader:
			extHdrs, tr.err = parsePAX(tr)
			if tr.err != nil {
				return nil, tr.err
			}
			continue loop  
		case TypeGNULongName, TypeGNULongLink:
			var realname []byte
			realname, tr.err = ioutil.ReadAll(tr)
			if tr.err != nil {
				return nil, tr.err
			}
			if tr.RawAccounting {
				if _, tr.err = tr.rawBytes.Write(realname); tr.err != nil {
					return nil, tr.err
				}
			}
			if extHdrs == nil {
				extHdrs = make(map[string]string)
			}
			var p parser
			switch hdr.Typeflag {
			case TypeGNULongName:
				extHdrs[paxPath] = p.parseString(realname)
			case TypeGNULongLink:
				extHdrs[paxLinkpath] = p.parseString(realname)
			}
			if p.err != nil {
				tr.err = p.err
				return nil, tr.err
			}
			continue loop  
		default:
			mergePAX(hdr, extHdrs)
			sp, err := tr.checkForGNUSparsePAXHeaders(hdr, extHdrs)
			if err != nil {
				tr.err = err
				return nil, err
			}
			if sp != nil {
				tr.curr, tr.err = newSparseFileReader(tr.curr, sp, hdr.Size)
				if tr.err != nil {
					return nil, tr.err
				}
			}
			break loop  
		}
	}
	return hdr, nil
}
func (tr *Reader) checkForGNUSparsePAXHeaders(hdr *Header, headers map[string]string) ([]sparseEntry, error) {
	var sparseFormat string
	major, majorOk := headers[paxGNUSparseMajor]
	minor, minorOk := headers[paxGNUSparseMinor]
	sparseName, sparseNameOk := headers[paxGNUSparseName]
	_, sparseMapOk := headers[paxGNUSparseMap]
	sparseSize, sparseSizeOk := headers[paxGNUSparseSize]
	sparseRealSize, sparseRealSizeOk := headers[paxGNUSparseRealSize]
	if majorOk && minorOk {
		sparseFormat = major + "." + minor
	} else if sparseNameOk && sparseMapOk {
		sparseFormat = "0.1"
	} else if sparseSizeOk {
		sparseFormat = "0.0"
	} else {
		return nil, nil
	}
	if sparseFormat != "0.0" && sparseFormat != "0.1" && sparseFormat != "1.0" {
		return nil, nil
	}
	if sparseNameOk {
		hdr.Name = sparseName
	}
	if sparseSizeOk {
		realSize, err := strconv.ParseInt(sparseSize, 10, 0)
		if err != nil {
			return nil, ErrHeader
		}
		hdr.Size = realSize
	} else if sparseRealSizeOk {
		realSize, err := strconv.ParseInt(sparseRealSize, 10, 0)
		if err != nil {
			return nil, ErrHeader
		}
		hdr.Size = realSize
	}
	var sp []sparseEntry
	var err error
	switch sparseFormat {
	case "0.0", "0.1":
		sp, err = readGNUSparseMap0x1(headers)
	case "1.0":
		sp, err = readGNUSparseMap1x0(tr.curr)
	}
	return sp, err
}
func mergePAX(hdr *Header, headers map[string]string) error {
	for k, v := range headers {
		switch k {
		case paxPath:
			hdr.Name = v
		case paxLinkpath:
			hdr.Linkname = v
		case paxGname:
			hdr.Gname = v
		case paxUname:
			hdr.Uname = v
		case paxUid:
			uid, err := strconv.ParseInt(v, 10, 0)
			if err != nil {
				return err
			}
			hdr.Uid = int(uid)
		case paxGid:
			gid, err := strconv.ParseInt(v, 10, 0)
			if err != nil {
				return err
			}
			hdr.Gid = int(gid)
		case paxAtime:
			t, err := parsePAXTime(v)
			if err != nil {
				return err
			}
			hdr.AccessTime = t
		case paxMtime:
			t, err := parsePAXTime(v)
			if err != nil {
				return err
			}
			hdr.ModTime = t
		case paxCtime:
			t, err := parsePAXTime(v)
			if err != nil {
				return err
			}
			hdr.ChangeTime = t
		case paxSize:
			size, err := strconv.ParseInt(v, 10, 0)
			if err != nil {
				return err
			}
			hdr.Size = int64(size)
		default:
			if strings.HasPrefix(k, paxXattr) {
				if hdr.Xattrs == nil {
					hdr.Xattrs = make(map[string]string)
				}
				hdr.Xattrs[k[len(paxXattr):]] = v
			}
		}
	}
	return nil
}
func parsePAXTime(t string) (time.Time, error) {
	buf := []byte(t)
	pos := bytes.IndexByte(buf, '.')
	var seconds, nanoseconds int64
	var err error
	if pos == -1 {
		seconds, err = strconv.ParseInt(t, 10, 0)
		if err != nil {
			return time.Time{}, err
		}
	} else {
		seconds, err = strconv.ParseInt(string(buf[:pos]), 10, 0)
		if err != nil {
			return time.Time{}, err
		}
		nano_buf := string(buf[pos+1:])
		if len(nano_buf) < maxNanoSecondIntSize {
			nano_buf += strings.Repeat("0", maxNanoSecondIntSize-len(nano_buf))
		} else if len(nano_buf) > maxNanoSecondIntSize {
			nano_buf = nano_buf[:maxNanoSecondIntSize]
		}
		nanoseconds, err = strconv.ParseInt(string(nano_buf), 10, 0)
		if err != nil {
			return time.Time{}, err
		}
	}
	ts := time.Unix(seconds, nanoseconds)
	return ts, nil
}
func parsePAX(r io.Reader) (map[string]string, error) {
	buf, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	if tr, ok := r.(*Reader); ok && tr.RawAccounting {
		if _, err = tr.rawBytes.Write(buf); err != nil {
			return nil, err
		}
	}
	sbuf := string(buf)
	var sparseMap bytes.Buffer
	headers := make(map[string]string)
	for len(sbuf) > 0 {
		key, value, residual, err := parsePAXRecord(sbuf)
		if err != nil {
			return nil, ErrHeader
		}
		sbuf = residual
		keyStr := string(key)
		if keyStr == paxGNUSparseOffset || keyStr == paxGNUSparseNumBytes {
			sparseMap.WriteString(value)
			sparseMap.Write([]byte{','})
		} else {
			headers[keyStr] = string(value)
		}
	}
	if sparseMap.Len() != 0 {
		sparseMap.Truncate(sparseMap.Len() - 1)
		headers[paxGNUSparseMap] = sparseMap.String()
	}
	return headers, nil
}
func parsePAXRecord(s string) (k, v, r string, err error) {
	sp := strings.IndexByte(s, ' ')
	if sp == -1 {
		return "", "", s, ErrHeader
	}
	n, perr := strconv.ParseInt(s[:sp], 10, 0)  
	if perr != nil || n < 5 || int64(len(s)) < n {
		return "", "", s, ErrHeader
	}
	rec, nl, rem := s[sp+1:n-1], s[n-1:n], s[n:]
	if nl != "\n" {
		return "", "", s, ErrHeader
	}
	eq := strings.IndexByte(rec, '=')
	if eq == -1 {
		return "", "", s, ErrHeader
	}
	return rec[:eq], rec[eq+1:], rem, nil
}
func (*parser) parseString(b []byte) string {
	n := 0
	for n < len(b) && b[n] != 0 {
		n++
	}
	return string(b[0:n])
}
func (p *parser) parseNumeric(b []byte) int64 {
	if len(b) > 0 && b[0]&0x80 != 0 {
		var inv byte  
		if b[0]&0x40 != 0 {
			inv = 0xff
		}
		var x uint64
		for i, c := range b {
			c ^= inv  
			if i == 0 {
				c &= 0x7f  
			}
			if (x >> 56) > 0 {
				p.err = ErrHeader  
				return 0
			}
			x = x<<8 | uint64(c)
		}
		if (x >> 63) > 0 {
			p.err = ErrHeader  
			return 0
		}
		if inv == 0xff {
			return ^int64(x)
		}
		return int64(x)
	}
	return p.parseOctal(b)
}
func (p *parser) parseOctal(b []byte) int64 {
	b = bytes.Trim(b, " \x00")
	if len(b) == 0 {
		return 0
	}
	x, perr := strconv.ParseUint(p.parseString(b), 8, 64)
	if perr != nil {
		p.err = ErrHeader
	}
	return int64(x)
}
func (tr *Reader) skipUnread() error {
	dataSkip := tr.numBytes()       
	totalSkip := dataSkip + tr.pad  
	tr.curr, tr.pad = nil, 0
	if tr.RawAccounting {
		_, tr.err = io.CopyN(tr.rawBytes, tr.r, totalSkip)
		return tr.err
	}
	var seekSkipped int64  
	if sr, ok := tr.r.(io.Seeker); ok && dataSkip > 1 {
		pos1, err := sr.Seek(0, os.SEEK_CUR)
		if err == nil {
			pos2, err := sr.Seek(dataSkip-1, os.SEEK_CUR)
			if err != nil {
				tr.err = err
				return tr.err
			}
			seekSkipped = pos2 - pos1
		}
	}
	var copySkipped int64  
	copySkipped, tr.err = io.CopyN(ioutil.Discard, tr.r, totalSkip-seekSkipped)
	if tr.err == io.EOF && seekSkipped+copySkipped < dataSkip {
		tr.err = io.ErrUnexpectedEOF
	}
	return tr.err
}
func (tr *Reader) verifyChecksum(header []byte) bool {
	if tr.err != nil {
		return false
	}
	var p parser
	given := p.parseOctal(header[148:156])
	unsigned, signed := checksum(header)
	return p.err == nil && (given == unsigned || given == signed)
}
func (tr *Reader) readHeader() *Header {
	header := tr.hdrBuff[:]
	copy(header, zeroBlock)
	if n, err := io.ReadFull(tr.r, header); err != nil {
		tr.err = err
		if tr.err == io.EOF && tr.RawAccounting {
			if _, err := tr.rawBytes.Write(header[:n]); err != nil {
				tr.err = err
			}
		}
		return nil  
	}
	if tr.RawAccounting {
		if _, tr.err = tr.rawBytes.Write(header); tr.err != nil {
			return nil
		}
	}
	if bytes.Equal(header, zeroBlock[0:blockSize]) {
		if n, err := io.ReadFull(tr.r, header); err != nil {
			tr.err = err
			if tr.err == io.EOF && tr.RawAccounting {
				if _, err := tr.rawBytes.Write(header[:n]); err != nil {
					tr.err = err
				}
			}
			return nil  
		}
		if tr.RawAccounting {
			if _, tr.err = tr.rawBytes.Write(header); tr.err != nil {
				return nil
			}
		}
		if bytes.Equal(header, zeroBlock[0:blockSize]) {
			tr.err = io.EOF
		} else {
			tr.err = ErrHeader  
		}
		return nil
	}
	if !tr.verifyChecksum(header) {
		tr.err = ErrHeader
		return nil
	}
	var p parser
	hdr := new(Header)
	s := slicer(header)
	hdr.Name = p.parseString(s.next(100))
	hdr.Mode = p.parseNumeric(s.next(8))
	hdr.Uid = int(p.parseNumeric(s.next(8)))
	hdr.Gid = int(p.parseNumeric(s.next(8)))
	hdr.Size = p.parseNumeric(s.next(12))
	hdr.ModTime = time.Unix(p.parseNumeric(s.next(12)), 0)
	s.next(8)  
	hdr.Typeflag = s.next(1)[0]
	hdr.Linkname = p.parseString(s.next(100))
	magic := string(s.next(8))  
	var format string
	switch {
	case magic[:6] == "ustar\x00":  
		if string(header[508:512]) == "tar\x00" {
			format = "star"
		} else {
			format = "posix"
		}
	case magic == "ustar  \x00":  
		format = "gnu"
	}
	switch format {
	case "posix", "gnu", "star":
		hdr.Uname = p.parseString(s.next(32))
		hdr.Gname = p.parseString(s.next(32))
		devmajor := s.next(8)
		devminor := s.next(8)
		if hdr.Typeflag == TypeChar || hdr.Typeflag == TypeBlock {
			hdr.Devmajor = p.parseNumeric(devmajor)
			hdr.Devminor = p.parseNumeric(devminor)
		}
		var prefix string
		switch format {
		case "posix", "gnu":
			prefix = p.parseString(s.next(155))
		case "star":
			prefix = p.parseString(s.next(131))
			hdr.AccessTime = time.Unix(p.parseNumeric(s.next(12)), 0)
			hdr.ChangeTime = time.Unix(p.parseNumeric(s.next(12)), 0)
		}
		if len(prefix) > 0 {
			hdr.Name = prefix + "/" + hdr.Name
		}
	}
	if p.err != nil {
		tr.err = p.err
		return nil
	}
	nb := hdr.Size
	if isHeaderOnlyType(hdr.Typeflag) {
		nb = 0
	}
	if nb < 0 {
		tr.err = ErrHeader
		return nil
	}
	tr.pad = -nb & (blockSize - 1)  
	tr.curr = &regFileReader{r: tr.r, nb: nb}
	if hdr.Typeflag == TypeGNUSparse {
		hdr.Size = p.parseNumeric(header[483:495])
		if p.err != nil {
			tr.err = p.err
			return nil
		}
		sp := tr.readOldGNUSparseMap(header)
		if tr.err != nil {
			return nil
		}
		tr.curr, tr.err = newSparseFileReader(tr.curr, sp, hdr.Size)
		if tr.err != nil {
			return nil
		}
	}
	return hdr
}
func (tr *Reader) readOldGNUSparseMap(header []byte) []sparseEntry {
	var p parser
	isExtended := header[oldGNUSparseMainHeaderIsExtendedOffset] != 0
	spCap := oldGNUSparseMainHeaderNumEntries
	if isExtended {
		spCap += oldGNUSparseExtendedHeaderNumEntries
	}
	sp := make([]sparseEntry, 0, spCap)
	s := slicer(header[oldGNUSparseMainHeaderOffset:])
	for i := 0; i < oldGNUSparseMainHeaderNumEntries; i++ {
		offset := p.parseNumeric(s.next(oldGNUSparseOffsetSize))
		numBytes := p.parseNumeric(s.next(oldGNUSparseNumBytesSize))
		if p.err != nil {
			tr.err = p.err
			return nil
		}
		if offset == 0 && numBytes == 0 {
			break
		}
		sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
	}
	for isExtended {
		sparseHeader := make([]byte, blockSize)
		if _, tr.err = io.ReadFull(tr.r, sparseHeader); tr.err != nil {
			return nil
		}
		if tr.RawAccounting {
			if _, tr.err = tr.rawBytes.Write(sparseHeader); tr.err != nil {
				return nil
			}
		}
		isExtended = sparseHeader[oldGNUSparseExtendedHeaderIsExtendedOffset] != 0
		s = slicer(sparseHeader)
		for i := 0; i < oldGNUSparseExtendedHeaderNumEntries; i++ {
			offset := p.parseNumeric(s.next(oldGNUSparseOffsetSize))
			numBytes := p.parseNumeric(s.next(oldGNUSparseNumBytesSize))
			if p.err != nil {
				tr.err = p.err
				return nil
			}
			if offset == 0 && numBytes == 0 {
				break
			}
			sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
		}
	}
	return sp
}
func readGNUSparseMap1x0(r io.Reader) ([]sparseEntry, error) {
	var cntNewline int64
	var buf bytes.Buffer
	var blk = make([]byte, blockSize)
	var feedTokens = func(cnt int64) error {
		for cntNewline < cnt {
			if _, err := io.ReadFull(r, blk); err != nil {
				if err == io.EOF {
					err = io.ErrUnexpectedEOF
				}
				return err
			}
			buf.Write(blk)
			for _, c := range blk {
				if c == '\n' {
					cntNewline++
				}
			}
		}
		return nil
	}
	var nextToken = func() string {
		cntNewline--
		tok, _ := buf.ReadString('\n')
		return tok[:len(tok)-1]  
	}
	if err := feedTokens(1); err != nil {
		return nil, err
	}
	numEntries, err := strconv.ParseInt(nextToken(), 10, 0)  
	if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
		return nil, ErrHeader
	}
	if err := feedTokens(2 * numEntries); err != nil {
		return nil, err
	}
	sp := make([]sparseEntry, 0, numEntries)
	for i := int64(0); i < numEntries; i++ {
		offset, err := strconv.ParseInt(nextToken(), 10, 64)
		if err != nil {
			return nil, ErrHeader
		}
		numBytes, err := strconv.ParseInt(nextToken(), 10, 64)
		if err != nil {
			return nil, ErrHeader
		}
		sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
	}
	return sp, nil
}
func readGNUSparseMap0x1(extHdrs map[string]string) ([]sparseEntry, error) {
	numEntriesStr := extHdrs[paxGNUSparseNumBlocks]
	numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0)  
	if err != nil || numEntries < 0 || int(2*numEntries) < int(numEntries) {
		return nil, ErrHeader
	}
	sparseMap := strings.Split(extHdrs[paxGNUSparseMap], ",")
	if int64(len(sparseMap)) != 2*numEntries {
		return nil, ErrHeader
	}
	sp := make([]sparseEntry, 0, numEntries)
	for i := int64(0); i < numEntries; i++ {
		offset, err := strconv.ParseInt(sparseMap[2*i], 10, 64)
		if err != nil {
			return nil, ErrHeader
		}
		numBytes, err := strconv.ParseInt(sparseMap[2*i+1], 10, 64)
		if err != nil {
			return nil, ErrHeader
		}
		sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes})
	}
	return sp, nil
}
func (tr *Reader) numBytes() int64 {
	if tr.curr == nil {
		return 0
	}
	return tr.curr.numBytes()
}
func (tr *Reader) Read(b []byte) (n int, err error) {
	if tr.err != nil {
		return 0, tr.err
	}
	if tr.curr == nil {
		return 0, io.EOF
	}
	n, err = tr.curr.Read(b)
	if err != nil && err != io.EOF {
		tr.err = err
	}
	return
}
func (rfr *regFileReader) Read(b []byte) (n int, err error) {
	if rfr.nb == 0 {
		return 0, io.EOF
	}
	if int64(len(b)) > rfr.nb {
		b = b[0:rfr.nb]
	}
	n, err = rfr.r.Read(b)
	rfr.nb -= int64(n)
	if err == io.EOF && rfr.nb > 0 {
		err = io.ErrUnexpectedEOF
	}
	return
}
func (rfr *regFileReader) numBytes() int64 {
	return rfr.nb
}
func newSparseFileReader(rfr numBytesReader, sp []sparseEntry, total int64) (*sparseFileReader, error) {
	if total < 0 {
		return nil, ErrHeader  
	}
	for i, s := range sp {
		switch {
		case s.offset < 0 || s.numBytes < 0:
			return nil, ErrHeader  
		case s.offset > math.MaxInt64-s.numBytes:
			return nil, ErrHeader  
		case s.offset+s.numBytes > total:
			return nil, ErrHeader  
		case i > 0 && sp[i-1].offset+sp[i-1].numBytes > s.offset:
			return nil, ErrHeader  
		}
	}
	return &sparseFileReader{rfr: rfr, sp: sp, total: total}, nil
}