github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/src/archive/tar/writer.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  // TODO(dsymonds):
     8  // - catch more errors (no first header, etc.)
     9  
    10  import (
    11  	"bytes"
    12  	"errors"
    13  	"fmt"
    14  	"io"
    15  	"path"
    16  	"sort"
    17  	"strconv"
    18  	"strings"
    19  	"time"
    20  )
    21  
    22  var (
    23  	ErrWriteTooLong    = errors.New("archive/tar: write too long")
    24  	ErrFieldTooLong    = errors.New("archive/tar: header field too long")
    25  	ErrWriteAfterClose = errors.New("archive/tar: write after close")
    26  	errInvalidHeader   = errors.New("archive/tar: header field too long or contains invalid values")
    27  )
    28  
    29  // A Writer provides sequential writing of a tar archive in POSIX.1 format.
    30  // A tar archive consists of a sequence of files.
    31  // Call WriteHeader to begin a new file, and then call Write to supply that file's data,
    32  // writing at most hdr.Size bytes in total.
    33  type Writer struct {
    34  	w          io.Writer
    35  	err        error
    36  	nb         int64 // number of unwritten bytes for current file entry
    37  	pad        int64 // amount of padding to write after current file entry
    38  	closed     bool
    39  	usedBinary bool  // whether the binary numeric field extension was used
    40  	preferPax  bool  // use PAX header instead of binary numeric header
    41  	hdrBuff    block // buffer to use in writeHeader when writing a regular header
    42  	paxHdrBuff block // buffer to use in writeHeader when writing a PAX header
    43  }
    44  
    45  // NewWriter creates a new Writer writing to w.
    46  func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
    47  
    48  // Flush finishes writing the current file (optional).
    49  func (tw *Writer) Flush() error {
    50  	if tw.nb > 0 {
    51  		tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb)
    52  		return tw.err
    53  	}
    54  
    55  	n := tw.nb + tw.pad
    56  	for n > 0 && tw.err == nil {
    57  		nr := n
    58  		if nr > blockSize {
    59  			nr = blockSize
    60  		}
    61  		var nw int
    62  		nw, tw.err = tw.w.Write(zeroBlock[0:nr])
    63  		n -= int64(nw)
    64  	}
    65  	tw.nb = 0
    66  	tw.pad = 0
    67  	return tw.err
    68  }
    69  
    70  var (
    71  	minTime = time.Unix(0, 0)
    72  	// There is room for 11 octal digits (33 bits) of mtime.
    73  	maxTime = minTime.Add((1<<33 - 1) * time.Second)
    74  )
    75  
    76  // WriteHeader writes hdr and prepares to accept the file's contents.
    77  // WriteHeader calls Flush if it is not the first header.
    78  // Calling after a Close will return ErrWriteAfterClose.
    79  func (tw *Writer) WriteHeader(hdr *Header) error {
    80  	return tw.writeHeader(hdr, true)
    81  }
    82  
    83  // WriteHeader writes hdr and prepares to accept the file's contents.
    84  // WriteHeader calls Flush if it is not the first header.
    85  // Calling after a Close will return ErrWriteAfterClose.
    86  // As this method is called internally by writePax header to allow it to
    87  // suppress writing the pax header.
    88  func (tw *Writer) writeHeader(hdr *Header, allowPax bool) error {
    89  	if tw.closed {
    90  		return ErrWriteAfterClose
    91  	}
    92  	if tw.err == nil {
    93  		tw.Flush()
    94  	}
    95  	if tw.err != nil {
    96  		return tw.err
    97  	}
    98  
    99  	// a map to hold pax header records, if any are needed
   100  	paxHeaders := make(map[string]string)
   101  
   102  	// TODO(dsnet): we might want to use PAX headers for
   103  	// subsecond time resolution, but for now let's just capture
   104  	// too long fields or non ascii characters
   105  
   106  	// We need to select which scratch buffer to use carefully,
   107  	// since this method is called recursively to write PAX headers.
   108  	// If allowPax is true, this is the non-recursive call, and we will use hdrBuff.
   109  	// If allowPax is false, we are being called by writePAXHeader, and hdrBuff is
   110  	// already being used by the non-recursive call, so we must use paxHdrBuff.
   111  	header := &tw.hdrBuff
   112  	if !allowPax {
   113  		header = &tw.paxHdrBuff
   114  	}
   115  	copy(header[:], zeroBlock[:])
   116  
   117  	// Wrappers around formatter that automatically sets paxHeaders if the
   118  	// argument extends beyond the capacity of the input byte slice.
   119  	var f formatter
   120  	var formatString = func(b []byte, s string, paxKeyword string) {
   121  		needsPaxHeader := paxKeyword != paxNone && len(s) > len(b) || !isASCII(s)
   122  		if needsPaxHeader {
   123  			paxHeaders[paxKeyword] = s
   124  		}
   125  
   126  		// Write string in a best-effort manner to satisfy readers that expect
   127  		// the field to be non-empty.
   128  		s = toASCII(s)
   129  		if len(s) > len(b) {
   130  			s = s[:len(b)]
   131  		}
   132  		f.formatString(b, s) // Should never error
   133  	}
   134  	var formatNumeric = func(b []byte, x int64, paxKeyword string) {
   135  		// Try octal first.
   136  		s := strconv.FormatInt(x, 8)
   137  		if len(s) < len(b) {
   138  			f.formatOctal(b, x)
   139  			return
   140  		}
   141  
   142  		// If it is too long for octal, and PAX is preferred, use a PAX header.
   143  		if paxKeyword != paxNone && tw.preferPax {
   144  			f.formatOctal(b, 0)
   145  			s := strconv.FormatInt(x, 10)
   146  			paxHeaders[paxKeyword] = s
   147  			return
   148  		}
   149  
   150  		tw.usedBinary = true
   151  		f.formatNumeric(b, x)
   152  	}
   153  
   154  	// Handle out of range ModTime carefully.
   155  	var modTime int64
   156  	if !hdr.ModTime.Before(minTime) && !hdr.ModTime.After(maxTime) {
   157  		modTime = hdr.ModTime.Unix()
   158  	}
   159  
   160  	v7 := header.V7()
   161  	formatString(v7.Name(), hdr.Name, paxPath)
   162  	// TODO(dsnet): The GNU format permits the mode field to be encoded in
   163  	// base-256 format. Thus, we can use formatNumeric instead of formatOctal.
   164  	f.formatOctal(v7.Mode(), hdr.Mode)
   165  	formatNumeric(v7.UID(), int64(hdr.Uid), paxUid)
   166  	formatNumeric(v7.GID(), int64(hdr.Gid), paxGid)
   167  	formatNumeric(v7.Size(), hdr.Size, paxSize)
   168  	// TODO(dsnet): Consider using PAX for finer time granularity.
   169  	formatNumeric(v7.ModTime(), modTime, paxNone)
   170  	v7.TypeFlag()[0] = hdr.Typeflag
   171  	formatString(v7.LinkName(), hdr.Linkname, paxLinkpath)
   172  
   173  	ustar := header.USTAR()
   174  	formatString(ustar.UserName(), hdr.Uname, paxUname)
   175  	formatString(ustar.GroupName(), hdr.Gname, paxGname)
   176  	formatNumeric(ustar.DevMajor(), hdr.Devmajor, paxNone)
   177  	formatNumeric(ustar.DevMinor(), hdr.Devminor, paxNone)
   178  
   179  	// TODO(dsnet): The logic surrounding the prefix field is broken when trying
   180  	// to encode the header as GNU format. The challenge with the current logic
   181  	// is that we are unsure what format we are using at any given moment until
   182  	// we have processed *all* of the fields. The problem is that by the time
   183  	// all fields have been processed, some work has already been done to handle
   184  	// each field under the assumption that it is for one given format or
   185  	// another. In some situations, this causes the Writer to be confused and
   186  	// encode a prefix field when the format being used is GNU. Thus, producing
   187  	// an invalid tar file.
   188  	//
   189  	// As a short-term fix, we disable the logic to use the prefix field, which
   190  	// will force the badly generated GNU files to become encoded as being
   191  	// the PAX format.
   192  	//
   193  	// As an alternative fix, we could hard-code preferPax to be true. However,
   194  	// this is problematic for the following reasons:
   195  	//	* The preferPax functionality is not tested at all.
   196  	//	* This can result in headers that try to use both the GNU and PAX
   197  	//	features at the same time, which is also wrong.
   198  	//
   199  	// The proper fix for this is to use a two-pass method:
   200  	//	* The first pass simply determines what set of formats can possibly
   201  	//	encode the given header.
   202  	//	* The second pass actually encodes the header as that given format
   203  	//	without worrying about violating the format.
   204  	//
   205  	// See the following:
   206  	//	https://golang.org/issue/12594
   207  	//	https://golang.org/issue/17630
   208  	//	https://golang.org/issue/9683
   209  	const usePrefix = false
   210  
   211  	// try to use a ustar header when only the name is too long
   212  	_, paxPathUsed := paxHeaders[paxPath]
   213  	if usePrefix && !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed {
   214  		prefix, suffix, ok := splitUSTARPath(hdr.Name)
   215  		if ok {
   216  			// Since we can encode in USTAR format, disable PAX header.
   217  			delete(paxHeaders, paxPath)
   218  
   219  			// Update the path fields
   220  			formatString(v7.Name(), suffix, paxNone)
   221  			formatString(ustar.Prefix(), prefix, paxNone)
   222  		}
   223  	}
   224  
   225  	if tw.usedBinary {
   226  		header.SetFormat(formatGNU)
   227  	} else {
   228  		header.SetFormat(formatUSTAR)
   229  	}
   230  
   231  	// Check if there were any formatting errors.
   232  	if f.err != nil {
   233  		tw.err = f.err
   234  		return tw.err
   235  	}
   236  
   237  	if allowPax {
   238  		for k, v := range hdr.Xattrs {
   239  			paxHeaders[paxXattr+k] = v
   240  		}
   241  	}
   242  
   243  	if len(paxHeaders) > 0 {
   244  		if !allowPax {
   245  			return errInvalidHeader
   246  		}
   247  		if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
   248  			return err
   249  		}
   250  	}
   251  	tw.nb = hdr.Size
   252  	tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
   253  
   254  	_, tw.err = tw.w.Write(header[:])
   255  	return tw.err
   256  }
   257  
   258  // splitUSTARPath splits a path according to USTAR prefix and suffix rules.
   259  // If the path is not splittable, then it will return ("", "", false).
   260  func splitUSTARPath(name string) (prefix, suffix string, ok bool) {
   261  	length := len(name)
   262  	if length <= nameSize || !isASCII(name) {
   263  		return "", "", false
   264  	} else if length > prefixSize+1 {
   265  		length = prefixSize + 1
   266  	} else if name[length-1] == '/' {
   267  		length--
   268  	}
   269  
   270  	i := strings.LastIndex(name[:length], "/")
   271  	nlen := len(name) - i - 1 // nlen is length of suffix
   272  	plen := i                 // plen is length of prefix
   273  	if i <= 0 || nlen > nameSize || nlen == 0 || plen > prefixSize {
   274  		return "", "", false
   275  	}
   276  	return name[:i], name[i+1:], true
   277  }
   278  
   279  // writePaxHeader writes an extended pax header to the
   280  // archive.
   281  func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
   282  	// Prepare extended header
   283  	ext := new(Header)
   284  	ext.Typeflag = TypeXHeader
   285  	// Setting ModTime is required for reader parsing to
   286  	// succeed, and seems harmless enough.
   287  	ext.ModTime = hdr.ModTime
   288  	// The spec asks that we namespace our pseudo files
   289  	// with the current pid. However, this results in differing outputs
   290  	// for identical inputs. As such, the constant 0 is now used instead.
   291  	// golang.org/issue/12358
   292  	dir, file := path.Split(hdr.Name)
   293  	fullName := path.Join(dir, "PaxHeaders.0", file)
   294  
   295  	ascii := toASCII(fullName)
   296  	if len(ascii) > nameSize {
   297  		ascii = ascii[:nameSize]
   298  	}
   299  	ext.Name = ascii
   300  	// Construct the body
   301  	var buf bytes.Buffer
   302  
   303  	// Keys are sorted before writing to body to allow deterministic output.
   304  	keys := make([]string, 0, len(paxHeaders))
   305  	for k := range paxHeaders {
   306  		keys = append(keys, k)
   307  	}
   308  	sort.Strings(keys)
   309  
   310  	for _, k := range keys {
   311  		fmt.Fprint(&buf, formatPAXRecord(k, paxHeaders[k]))
   312  	}
   313  
   314  	ext.Size = int64(len(buf.Bytes()))
   315  	if err := tw.writeHeader(ext, false); err != nil {
   316  		return err
   317  	}
   318  	if _, err := tw.Write(buf.Bytes()); err != nil {
   319  		return err
   320  	}
   321  	if err := tw.Flush(); err != nil {
   322  		return err
   323  	}
   324  	return nil
   325  }
   326  
   327  // Write writes to the current entry in the tar archive.
   328  // Write returns the error ErrWriteTooLong if more than
   329  // hdr.Size bytes are written after WriteHeader.
   330  func (tw *Writer) Write(b []byte) (n int, err error) {
   331  	if tw.closed {
   332  		err = ErrWriteAfterClose
   333  		return
   334  	}
   335  	overwrite := false
   336  	if int64(len(b)) > tw.nb {
   337  		b = b[0:tw.nb]
   338  		overwrite = true
   339  	}
   340  	n, err = tw.w.Write(b)
   341  	tw.nb -= int64(n)
   342  	if err == nil && overwrite {
   343  		err = ErrWriteTooLong
   344  		return
   345  	}
   346  	tw.err = err
   347  	return
   348  }
   349  
   350  // Close closes the tar archive, flushing any unwritten
   351  // data to the underlying writer.
   352  func (tw *Writer) Close() error {
   353  	if tw.err != nil || tw.closed {
   354  		return tw.err
   355  	}
   356  	tw.Flush()
   357  	tw.closed = true
   358  	if tw.err != nil {
   359  		return tw.err
   360  	}
   361  
   362  	// trailer: two zero blocks
   363  	for i := 0; i < 2; i++ {
   364  		_, tw.err = tw.w.Write(zeroBlock[:])
   365  		if tw.err != nil {
   366  			break
   367  		}
   368  	}
   369  	return tw.err
   370  }