github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/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  type formatter struct {
    46  	err error // Last error seen
    47  }
    48  
    49  // NewWriter creates a new Writer writing to w.
    50  func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
    51  
    52  // Flush finishes writing the current file (optional).
    53  func (tw *Writer) Flush() error {
    54  	if tw.nb > 0 {
    55  		tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb)
    56  		return tw.err
    57  	}
    58  
    59  	n := tw.nb + tw.pad
    60  	for n > 0 && tw.err == nil {
    61  		nr := n
    62  		if nr > blockSize {
    63  			nr = blockSize
    64  		}
    65  		var nw int
    66  		nw, tw.err = tw.w.Write(zeroBlock[0:nr])
    67  		n -= int64(nw)
    68  	}
    69  	tw.nb = 0
    70  	tw.pad = 0
    71  	return tw.err
    72  }
    73  
    74  // Write s into b, terminating it with a NUL if there is room.
    75  func (f *formatter) formatString(b []byte, s string) {
    76  	if len(s) > len(b) {
    77  		f.err = ErrFieldTooLong
    78  		return
    79  	}
    80  	ascii := toASCII(s)
    81  	copy(b, ascii)
    82  	if len(ascii) < len(b) {
    83  		b[len(ascii)] = 0
    84  	}
    85  }
    86  
    87  // Encode x as an octal ASCII string and write it into b with leading zeros.
    88  func (f *formatter) formatOctal(b []byte, x int64) {
    89  	s := strconv.FormatInt(x, 8)
    90  	// leading zeros, but leave room for a NUL.
    91  	for len(s)+1 < len(b) {
    92  		s = "0" + s
    93  	}
    94  	f.formatString(b, s)
    95  }
    96  
    97  // fitsInBase256 reports whether x can be encoded into n bytes using base-256
    98  // encoding. Unlike octal encoding, base-256 encoding does not require that the
    99  // string ends with a NUL character. Thus, all n bytes are available for output.
   100  //
   101  // If operating in binary mode, this assumes strict GNU binary mode; which means
   102  // that the first byte can only be either 0x80 or 0xff. Thus, the first byte is
   103  // equivalent to the sign bit in two's complement form.
   104  func fitsInBase256(n int, x int64) bool {
   105  	var binBits = uint(n-1) * 8
   106  	return n >= 9 || (x >= -1<<binBits && x < 1<<binBits)
   107  }
   108  
   109  // Write x into b, as binary (GNUtar/star extension).
   110  func (f *formatter) formatNumeric(b []byte, x int64) {
   111  	if fitsInBase256(len(b), x) {
   112  		for i := len(b) - 1; i >= 0; i-- {
   113  			b[i] = byte(x)
   114  			x >>= 8
   115  		}
   116  		b[0] |= 0x80 // Highest bit indicates binary format
   117  		return
   118  	}
   119  
   120  	f.formatOctal(b, 0) // Last resort, just write zero
   121  	f.err = ErrFieldTooLong
   122  }
   123  
   124  var (
   125  	minTime = time.Unix(0, 0)
   126  	// There is room for 11 octal digits (33 bits) of mtime.
   127  	maxTime = minTime.Add((1<<33 - 1) * time.Second)
   128  )
   129  
   130  // WriteHeader writes hdr and prepares to accept the file's contents.
   131  // WriteHeader calls Flush if it is not the first header.
   132  // Calling after a Close will return ErrWriteAfterClose.
   133  func (tw *Writer) WriteHeader(hdr *Header) error {
   134  	return tw.writeHeader(hdr, true)
   135  }
   136  
   137  // WriteHeader writes hdr and prepares to accept the file's contents.
   138  // WriteHeader calls Flush if it is not the first header.
   139  // Calling after a Close will return ErrWriteAfterClose.
   140  // As this method is called internally by writePax header to allow it to
   141  // suppress writing the pax header.
   142  func (tw *Writer) writeHeader(hdr *Header, allowPax bool) error {
   143  	if tw.closed {
   144  		return ErrWriteAfterClose
   145  	}
   146  	if tw.err == nil {
   147  		tw.Flush()
   148  	}
   149  	if tw.err != nil {
   150  		return tw.err
   151  	}
   152  
   153  	// a map to hold pax header records, if any are needed
   154  	paxHeaders := make(map[string]string)
   155  
   156  	// TODO(dsnet): we might want to use PAX headers for
   157  	// subsecond time resolution, but for now let's just capture
   158  	// too long fields or non ascii characters
   159  
   160  	// We need to select which scratch buffer to use carefully,
   161  	// since this method is called recursively to write PAX headers.
   162  	// If allowPax is true, this is the non-recursive call, and we will use hdrBuff.
   163  	// If allowPax is false, we are being called by writePAXHeader, and hdrBuff is
   164  	// already being used by the non-recursive call, so we must use paxHdrBuff.
   165  	header := &tw.hdrBuff
   166  	if !allowPax {
   167  		header = &tw.paxHdrBuff
   168  	}
   169  	copy(header[:], zeroBlock[:])
   170  
   171  	// Wrappers around formatter that automatically sets paxHeaders if the
   172  	// argument extends beyond the capacity of the input byte slice.
   173  	var f formatter
   174  	var formatString = func(b []byte, s string, paxKeyword string) {
   175  		needsPaxHeader := paxKeyword != paxNone && len(s) > len(b) || !isASCII(s)
   176  		if needsPaxHeader {
   177  			paxHeaders[paxKeyword] = s
   178  			return
   179  		}
   180  		f.formatString(b, s)
   181  	}
   182  	var formatNumeric = func(b []byte, x int64, paxKeyword string) {
   183  		// Try octal first.
   184  		s := strconv.FormatInt(x, 8)
   185  		if len(s) < len(b) {
   186  			f.formatOctal(b, x)
   187  			return
   188  		}
   189  
   190  		// If it is too long for octal, and PAX is preferred, use a PAX header.
   191  		if paxKeyword != paxNone && tw.preferPax {
   192  			f.formatOctal(b, 0)
   193  			s := strconv.FormatInt(x, 10)
   194  			paxHeaders[paxKeyword] = s
   195  			return
   196  		}
   197  
   198  		tw.usedBinary = true
   199  		f.formatNumeric(b, x)
   200  	}
   201  
   202  	// Handle out of range ModTime carefully.
   203  	var modTime int64
   204  	if !hdr.ModTime.Before(minTime) && !hdr.ModTime.After(maxTime) {
   205  		modTime = hdr.ModTime.Unix()
   206  	}
   207  
   208  	v7 := header.V7()
   209  	formatString(v7.Name(), hdr.Name, paxPath)
   210  	// TODO(dsnet): The GNU format permits the mode field to be encoded in
   211  	// base-256 format. Thus, we can use formatNumeric instead of formatOctal.
   212  	f.formatOctal(v7.Mode(), hdr.Mode)
   213  	formatNumeric(v7.UID(), int64(hdr.Uid), paxUid)
   214  	formatNumeric(v7.GID(), int64(hdr.Gid), paxGid)
   215  	formatNumeric(v7.Size(), hdr.Size, paxSize)
   216  	// TODO(dsnet): Consider using PAX for finer time granularity.
   217  	formatNumeric(v7.ModTime(), modTime, paxNone)
   218  	v7.TypeFlag()[0] = hdr.Typeflag
   219  	formatString(v7.LinkName(), hdr.Linkname, paxLinkpath)
   220  
   221  	ustar := header.USTAR()
   222  	formatString(ustar.UserName(), hdr.Uname, paxUname)
   223  	formatString(ustar.GroupName(), hdr.Gname, paxGname)
   224  	formatNumeric(ustar.DevMajor(), hdr.Devmajor, paxNone)
   225  	formatNumeric(ustar.DevMinor(), hdr.Devminor, paxNone)
   226  
   227  	// try to use a ustar header when only the name is too long
   228  	_, paxPathUsed := paxHeaders[paxPath]
   229  	if !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed {
   230  		prefix, suffix, ok := splitUSTARPath(hdr.Name)
   231  		if ok {
   232  			// Since we can encode in USTAR format, disable PAX header.
   233  			delete(paxHeaders, paxPath)
   234  
   235  			// Update the path fields
   236  			formatString(v7.Name(), suffix, paxNone)
   237  			formatString(ustar.Prefix(), prefix, paxNone)
   238  		}
   239  	}
   240  
   241  	if tw.usedBinary {
   242  		header.SetFormat(formatGNU)
   243  	} else {
   244  		header.SetFormat(formatUSTAR)
   245  	}
   246  
   247  	// Check if there were any formatting errors.
   248  	if f.err != nil {
   249  		tw.err = f.err
   250  		return tw.err
   251  	}
   252  
   253  	if allowPax {
   254  		for k, v := range hdr.Xattrs {
   255  			paxHeaders[paxXattr+k] = v
   256  		}
   257  	}
   258  
   259  	if len(paxHeaders) > 0 {
   260  		if !allowPax {
   261  			return errInvalidHeader
   262  		}
   263  		if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
   264  			return err
   265  		}
   266  	}
   267  	tw.nb = hdr.Size
   268  	tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
   269  
   270  	_, tw.err = tw.w.Write(header[:])
   271  	return tw.err
   272  }
   273  
   274  // splitUSTARPath splits a path according to USTAR prefix and suffix rules.
   275  // If the path is not splittable, then it will return ("", "", false).
   276  func splitUSTARPath(name string) (prefix, suffix string, ok bool) {
   277  	length := len(name)
   278  	if length <= nameSize || !isASCII(name) {
   279  		return "", "", false
   280  	} else if length > prefixSize+1 {
   281  		length = prefixSize + 1
   282  	} else if name[length-1] == '/' {
   283  		length--
   284  	}
   285  
   286  	i := strings.LastIndex(name[:length], "/")
   287  	nlen := len(name) - i - 1 // nlen is length of suffix
   288  	plen := i                 // plen is length of prefix
   289  	if i <= 0 || nlen > nameSize || nlen == 0 || plen > prefixSize {
   290  		return "", "", false
   291  	}
   292  	return name[:i], name[i+1:], true
   293  }
   294  
   295  // writePaxHeader writes an extended pax header to the
   296  // archive.
   297  func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
   298  	// Prepare extended header
   299  	ext := new(Header)
   300  	ext.Typeflag = TypeXHeader
   301  	// Setting ModTime is required for reader parsing to
   302  	// succeed, and seems harmless enough.
   303  	ext.ModTime = hdr.ModTime
   304  	// The spec asks that we namespace our pseudo files
   305  	// with the current pid. However, this results in differing outputs
   306  	// for identical inputs. As such, the constant 0 is now used instead.
   307  	// golang.org/issue/12358
   308  	dir, file := path.Split(hdr.Name)
   309  	fullName := path.Join(dir, "PaxHeaders.0", file)
   310  
   311  	ascii := toASCII(fullName)
   312  	if len(ascii) > nameSize {
   313  		ascii = ascii[:nameSize]
   314  	}
   315  	ext.Name = ascii
   316  	// Construct the body
   317  	var buf bytes.Buffer
   318  
   319  	// Keys are sorted before writing to body to allow deterministic output.
   320  	var keys []string
   321  	for k := range paxHeaders {
   322  		keys = append(keys, k)
   323  	}
   324  	sort.Strings(keys)
   325  
   326  	for _, k := range keys {
   327  		fmt.Fprint(&buf, formatPAXRecord(k, paxHeaders[k]))
   328  	}
   329  
   330  	ext.Size = int64(len(buf.Bytes()))
   331  	if err := tw.writeHeader(ext, false); err != nil {
   332  		return err
   333  	}
   334  	if _, err := tw.Write(buf.Bytes()); err != nil {
   335  		return err
   336  	}
   337  	if err := tw.Flush(); err != nil {
   338  		return err
   339  	}
   340  	return nil
   341  }
   342  
   343  // formatPAXRecord formats a single PAX record, prefixing it with the
   344  // appropriate length.
   345  func formatPAXRecord(k, v string) string {
   346  	const padding = 3 // Extra padding for ' ', '=', and '\n'
   347  	size := len(k) + len(v) + padding
   348  	size += len(strconv.Itoa(size))
   349  	record := fmt.Sprintf("%d %s=%s\n", size, k, v)
   350  
   351  	// Final adjustment if adding size field increased the record size.
   352  	if len(record) != size {
   353  		size = len(record)
   354  		record = fmt.Sprintf("%d %s=%s\n", size, k, v)
   355  	}
   356  	return record
   357  }
   358  
   359  // Write writes to the current entry in the tar archive.
   360  // Write returns the error ErrWriteTooLong if more than
   361  // hdr.Size bytes are written after WriteHeader.
   362  func (tw *Writer) Write(b []byte) (n int, err error) {
   363  	if tw.closed {
   364  		err = ErrWriteAfterClose
   365  		return
   366  	}
   367  	overwrite := false
   368  	if int64(len(b)) > tw.nb {
   369  		b = b[0:tw.nb]
   370  		overwrite = true
   371  	}
   372  	n, err = tw.w.Write(b)
   373  	tw.nb -= int64(n)
   374  	if err == nil && overwrite {
   375  		err = ErrWriteTooLong
   376  		return
   377  	}
   378  	tw.err = err
   379  	return
   380  }
   381  
   382  // Close closes the tar archive, flushing any unwritten
   383  // data to the underlying writer.
   384  func (tw *Writer) Close() error {
   385  	if tw.err != nil || tw.closed {
   386  		return tw.err
   387  	}
   388  	tw.Flush()
   389  	tw.closed = true
   390  	if tw.err != nil {
   391  		return tw.err
   392  	}
   393  
   394  	// trailer: two zero blocks
   395  	for i := 0; i < 2; i++ {
   396  		_, tw.err = tw.w.Write(zeroBlock[:])
   397  		if tw.err != nil {
   398  			break
   399  		}
   400  	}
   401  	return tw.err
   402  }