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
5package tar
6
7// TODO(dsymonds):
8// - catch more errors (no first header, etc.)
9
10import (
11	"bytes"
12	"errors"
13	"fmt"
14	"io"
15	"path"
16	"sort"
17	"strconv"
18	"strings"
19	"time"
20)
21
22var (
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.
33type 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    [blockSize]byte // buffer to use in writeHeader when writing a regular header
42	paxHdrBuff [blockSize]byte // buffer to use in writeHeader when writing a pax header
43}
44
45type formatter struct {
46	err error // Last error seen
47}
48
49// NewWriter creates a new Writer writing to w.
50func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
51
52// Flush finishes writing the current file (optional).
53func (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.
75func (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.
88func (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.
104func 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).
110func (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
124var (
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.
133func (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.
142func (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(shanemhansen): 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	var f formatter
161	var header []byte
162
163	// We need to select which scratch buffer to use carefully,
164	// since this method is called recursively to write PAX headers.
165	// If allowPax is true, this is the non-recursive call, and we will use hdrBuff.
166	// If allowPax is false, we are being called by writePAXHeader, and hdrBuff is
167	// already being used by the non-recursive call, so we must use paxHdrBuff.
168	header = tw.hdrBuff[:]
169	if !allowPax {
170		header = tw.paxHdrBuff[:]
171	}
172	copy(header, zeroBlock)
173	s := slicer(header)
174
175	// Wrappers around formatter that automatically sets paxHeaders if the
176	// argument extends beyond the capacity of the input byte slice.
177	var formatString = func(b []byte, s string, paxKeyword string) {
178		needsPaxHeader := paxKeyword != paxNone && len(s) > len(b) || !isASCII(s)
179		if needsPaxHeader {
180			paxHeaders[paxKeyword] = s
181			return
182		}
183		f.formatString(b, s)
184	}
185	var formatNumeric = func(b []byte, x int64, paxKeyword string) {
186		// Try octal first.
187		s := strconv.FormatInt(x, 8)
188		if len(s) < len(b) {
189			f.formatOctal(b, x)
190			return
191		}
192
193		// If it is too long for octal, and PAX is preferred, use a PAX header.
194		if paxKeyword != paxNone && tw.preferPax {
195			f.formatOctal(b, 0)
196			s := strconv.FormatInt(x, 10)
197			paxHeaders[paxKeyword] = s
198			return
199		}
200
201		tw.usedBinary = true
202		f.formatNumeric(b, x)
203	}
204
205	// keep a reference to the filename to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
206	pathHeaderBytes := s.next(fileNameSize)
207
208	formatString(pathHeaderBytes, hdr.Name, paxPath)
209
210	// Handle out of range ModTime carefully.
211	var modTime int64
212	if !hdr.ModTime.Before(minTime) && !hdr.ModTime.After(maxTime) {
213		modTime = hdr.ModTime.Unix()
214	}
215
216	f.formatOctal(s.next(8), hdr.Mode)               // 100:108
217	formatNumeric(s.next(8), int64(hdr.Uid), paxUid) // 108:116
218	formatNumeric(s.next(8), int64(hdr.Gid), paxGid) // 116:124
219	formatNumeric(s.next(12), hdr.Size, paxSize)     // 124:136
220	formatNumeric(s.next(12), modTime, paxNone)      // 136:148 --- consider using pax for finer granularity
221	s.next(8)                                        // chksum (148:156)
222	s.next(1)[0] = hdr.Typeflag                      // 156:157
223
224	formatString(s.next(100), hdr.Linkname, paxLinkpath)
225
226	copy(s.next(8), []byte("ustar\x0000"))          // 257:265
227	formatString(s.next(32), hdr.Uname, paxUname)   // 265:297
228	formatString(s.next(32), hdr.Gname, paxGname)   // 297:329
229	formatNumeric(s.next(8), hdr.Devmajor, paxNone) // 329:337
230	formatNumeric(s.next(8), hdr.Devminor, paxNone) // 337:345
231
232	// keep a reference to the prefix to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
233	prefixHeaderBytes := s.next(155)
234	formatString(prefixHeaderBytes, "", paxNone) // 345:500  prefix
235
236	// Use the GNU magic instead of POSIX magic if we used any GNU extensions.
237	if tw.usedBinary {
238		copy(header[257:265], []byte("ustar  \x00"))
239	}
240
241	_, paxPathUsed := paxHeaders[paxPath]
242	// try to use a ustar header when only the name is too long
243	if !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed {
244		prefix, suffix, ok := splitUSTARPath(hdr.Name)
245		if ok {
246			// Since we can encode in USTAR format, disable PAX header.
247			delete(paxHeaders, paxPath)
248
249			// Update the path fields
250			formatString(pathHeaderBytes, suffix, paxNone)
251			formatString(prefixHeaderBytes, prefix, paxNone)
252		}
253	}
254
255	// The chksum field is terminated by a NUL and a space.
256	// This is different from the other octal fields.
257	chksum, _ := checksum(header)
258	f.formatOctal(header[148:155], chksum) // Never fails
259	header[155] = ' '
260
261	// Check if there were any formatting errors.
262	if f.err != nil {
263		tw.err = f.err
264		return tw.err
265	}
266
267	if allowPax {
268		for k, v := range hdr.Xattrs {
269			paxHeaders[paxXattr+k] = v
270		}
271	}
272
273	if len(paxHeaders) > 0 {
274		if !allowPax {
275			return errInvalidHeader
276		}
277		if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
278			return err
279		}
280	}
281	tw.nb = int64(hdr.Size)
282	tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
283
284	_, tw.err = tw.w.Write(header)
285	return tw.err
286}
287
288// splitUSTARPath splits a path according to USTAR prefix and suffix rules.
289// If the path is not splittable, then it will return ("", "", false).
290func splitUSTARPath(name string) (prefix, suffix string, ok bool) {
291	length := len(name)
292	if length <= fileNameSize || !isASCII(name) {
293		return "", "", false
294	} else if length > fileNamePrefixSize+1 {
295		length = fileNamePrefixSize + 1
296	} else if name[length-1] == '/' {
297		length--
298	}
299
300	i := strings.LastIndex(name[:length], "/")
301	nlen := len(name) - i - 1 // nlen is length of suffix
302	plen := i                 // plen is length of prefix
303	if i <= 0 || nlen > fileNameSize || nlen == 0 || plen > fileNamePrefixSize {
304		return "", "", false
305	}
306	return name[:i], name[i+1:], true
307}
308
309// writePaxHeader writes an extended pax header to the
310// archive.
311func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
312	// Prepare extended header
313	ext := new(Header)
314	ext.Typeflag = TypeXHeader
315	// Setting ModTime is required for reader parsing to
316	// succeed, and seems harmless enough.
317	ext.ModTime = hdr.ModTime
318	// The spec asks that we namespace our pseudo files
319	// with the current pid.  However, this results in differing outputs
320	// for identical inputs.  As such, the constant 0 is now used instead.
321	// golang.org/issue/12358
322	dir, file := path.Split(hdr.Name)
323	fullName := path.Join(dir, "PaxHeaders.0", file)
324
325	ascii := toASCII(fullName)
326	if len(ascii) > 100 {
327		ascii = ascii[:100]
328	}
329	ext.Name = ascii
330	// Construct the body
331	var buf bytes.Buffer
332
333	// Keys are sorted before writing to body to allow deterministic output.
334	var keys []string
335	for k := range paxHeaders {
336		keys = append(keys, k)
337	}
338	sort.Strings(keys)
339
340	for _, k := range keys {
341		fmt.Fprint(&buf, formatPAXRecord(k, paxHeaders[k]))
342	}
343
344	ext.Size = int64(len(buf.Bytes()))
345	if err := tw.writeHeader(ext, false); err != nil {
346		return err
347	}
348	if _, err := tw.Write(buf.Bytes()); err != nil {
349		return err
350	}
351	if err := tw.Flush(); err != nil {
352		return err
353	}
354	return nil
355}
356
357// formatPAXRecord formats a single PAX record, prefixing it with the
358// appropriate length.
359func formatPAXRecord(k, v string) string {
360	const padding = 3 // Extra padding for ' ', '=', and '\n'
361	size := len(k) + len(v) + padding
362	size += len(strconv.Itoa(size))
363	record := fmt.Sprintf("%d %s=%s\n", size, k, v)
364
365	// Final adjustment if adding size field increased the record size.
366	if len(record) != size {
367		size = len(record)
368		record = fmt.Sprintf("%d %s=%s\n", size, k, v)
369	}
370	return record
371}
372
373// Write writes to the current entry in the tar archive.
374// Write returns the error ErrWriteTooLong if more than
375// hdr.Size bytes are written after WriteHeader.
376func (tw *Writer) Write(b []byte) (n int, err error) {
377	if tw.closed {
378		err = ErrWriteAfterClose
379		return
380	}
381	overwrite := false
382	if int64(len(b)) > tw.nb {
383		b = b[0:tw.nb]
384		overwrite = true
385	}
386	n, err = tw.w.Write(b)
387	tw.nb -= int64(n)
388	if err == nil && overwrite {
389		err = ErrWriteTooLong
390		return
391	}
392	tw.err = err
393	return
394}
395
396// Close closes the tar archive, flushing any unwritten
397// data to the underlying writer.
398func (tw *Writer) Close() error {
399	if tw.err != nil || tw.closed {
400		return tw.err
401	}
402	tw.Flush()
403	tw.closed = true
404	if tw.err != nil {
405		return tw.err
406	}
407
408	// trailer: two zero blocks
409	for i := 0; i < 2; i++ {
410		_, tw.err = tw.w.Write(zeroBlock)
411		if tw.err != nil {
412			break
413		}
414	}
415	return tw.err
416}
417