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.
8 // - catch more errors (no first header, etc.)
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")
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.
36 nb int64 // number of unwritten bytes for current file entry
37 pad int64 // amount of padding to write after current file entry
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
45 type formatter struct {
46 err error // Last error seen
49 // NewWriter creates a new Writer writing to w.
50 func NewWriter(w io.Writer) *Writer { return &Writer{w: w, preferPax: true} }
52 // Flush finishes writing the current file (optional).
53 func (tw *Writer) Flush() error {
55 tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb)
60 for n > 0 && tw.err == nil {
66 nw, tw.err = tw.w.Write(zeroBlock[0:nr])
74 // Write s into b, terminating it with a NUL if there is room.
75 func (f *formatter) formatString(b []byte, s string) {
77 f.err = ErrFieldTooLong
82 if len(ascii) < len(b) {
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) {
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.
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)
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-- {
116 b[0] |= 0x80 // Highest bit indicates binary format
120 f.formatOctal(b, 0) // Last resort, just write zero
121 f.err = ErrFieldTooLong
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)
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)
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 {
144 return ErrWriteAfterClose
153 // a map to hold pax header records, if any are needed
154 paxHeaders := make(map[string]string)
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
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[:]
170 header = tw.paxHdrBuff[:]
172 copy(header, zeroBlock)
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)
180 paxHeaders[paxKeyword] = s
185 var formatNumeric = func(b []byte, x int64, paxKeyword string) {
187 s := strconv.FormatInt(x, 8)
193 // If it is too long for octal, and PAX is preferred, use a PAX header.
194 if paxKeyword != paxNone && tw.preferPax {
196 s := strconv.FormatInt(x, 10)
197 paxHeaders[paxKeyword] = s
202 f.formatNumeric(b, x)
204 var formatTime = func(b []byte, t time.Time, paxKeyword string) {
206 if !t.Before(minTime) && !t.After(maxTime) {
209 formatNumeric(b, unixTime, paxNone)
211 // Write a PAX header if the time didn't fit precisely.
212 if paxKeyword != "" && tw.preferPax && allowPax && (t.Nanosecond() != 0 || !t.Before(minTime) || !t.After(maxTime)) {
213 paxHeaders[paxKeyword] = formatPAXTime(t)
217 // keep a reference to the filename to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
218 pathHeaderBytes := s.next(fileNameSize)
220 formatString(pathHeaderBytes, hdr.Name, paxPath)
222 f.formatOctal(s.next(8), hdr.Mode) // 100:108
223 formatNumeric(s.next(8), int64(hdr.Uid), paxUid) // 108:116
224 formatNumeric(s.next(8), int64(hdr.Gid), paxGid) // 116:124
225 formatNumeric(s.next(12), hdr.Size, paxSize) // 124:136
226 formatTime(s.next(12), hdr.ModTime, paxMtime) // 136:148
227 s.next(8) // chksum (148:156)
228 s.next(1)[0] = hdr.Typeflag // 156:157
230 formatString(s.next(100), hdr.Linkname, paxLinkpath)
232 copy(s.next(8), []byte("ustar\x0000")) // 257:265
233 formatString(s.next(32), hdr.Uname, paxUname) // 265:297
234 formatString(s.next(32), hdr.Gname, paxGname) // 297:329
235 formatNumeric(s.next(8), hdr.Devmajor, paxNone) // 329:337
236 formatNumeric(s.next(8), hdr.Devminor, paxNone) // 337:345
238 // keep a reference to the prefix to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
239 prefixHeaderBytes := s.next(155)
240 formatString(prefixHeaderBytes, "", paxNone) // 345:500 prefix
242 // Use the GNU magic instead of POSIX magic if we used any GNU extensions.
244 copy(header[257:265], []byte("ustar \x00"))
247 _, paxPathUsed := paxHeaders[paxPath]
248 // try to use a ustar header when only the name is too long
249 if !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed {
250 prefix, suffix, ok := splitUSTARPath(hdr.Name)
252 // Since we can encode in USTAR format, disable PAX header.
253 delete(paxHeaders, paxPath)
255 // Update the path fields
256 formatString(pathHeaderBytes, suffix, paxNone)
257 formatString(prefixHeaderBytes, prefix, paxNone)
261 // The chksum field is terminated by a NUL and a space.
262 // This is different from the other octal fields.
263 chksum, _ := checksum(header)
264 f.formatOctal(header[148:155], chksum) // Never fails
267 // Check if there were any formatting errors.
274 if !hdr.AccessTime.IsZero() {
275 paxHeaders[paxAtime] = formatPAXTime(hdr.AccessTime)
277 if !hdr.ChangeTime.IsZero() {
278 paxHeaders[paxCtime] = formatPAXTime(hdr.ChangeTime)
280 if !hdr.CreationTime.IsZero() {
281 paxHeaders[paxCreationTime] = formatPAXTime(hdr.CreationTime)
283 for k, v := range hdr.Xattrs {
284 paxHeaders[paxXattr+k] = v
286 for k, v := range hdr.Winheaders {
287 paxHeaders[paxWindows+k] = v
291 if len(paxHeaders) > 0 {
293 return errInvalidHeader
295 if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
299 tw.nb = int64(hdr.Size)
300 tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
302 _, tw.err = tw.w.Write(header)
306 func formatPAXTime(t time.Time) string {
308 usec := t.Nanosecond()
309 s := strconv.FormatInt(sec, 10)
311 s = fmt.Sprintf("%s.%09d", s, usec)
316 // splitUSTARPath splits a path according to USTAR prefix and suffix rules.
317 // If the path is not splittable, then it will return ("", "", false).
318 func splitUSTARPath(name string) (prefix, suffix string, ok bool) {
320 if length <= fileNameSize || !isASCII(name) {
322 } else if length > fileNamePrefixSize+1 {
323 length = fileNamePrefixSize + 1
324 } else if name[length-1] == '/' {
328 i := strings.LastIndex(name[:length], "/")
329 nlen := len(name) - i - 1 // nlen is length of suffix
330 plen := i // plen is length of prefix
331 if i <= 0 || nlen > fileNameSize || nlen == 0 || plen > fileNamePrefixSize {
334 return name[:i], name[i+1:], true
337 // writePaxHeader writes an extended pax header to the
339 func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
340 // Prepare extended header
342 ext.Typeflag = TypeXHeader
343 // Setting ModTime is required for reader parsing to
344 // succeed, and seems harmless enough.
345 ext.ModTime = hdr.ModTime
346 // The spec asks that we namespace our pseudo files
347 // with the current pid. However, this results in differing outputs
348 // for identical inputs. As such, the constant 0 is now used instead.
349 // golang.org/issue/12358
350 dir, file := path.Split(hdr.Name)
351 fullName := path.Join(dir, "PaxHeaders.0", file)
353 ascii := toASCII(fullName)
354 if len(ascii) > 100 {
358 // Construct the body
361 // Keys are sorted before writing to body to allow deterministic output.
363 for k := range paxHeaders {
364 keys = append(keys, k)
368 for _, k := range keys {
369 fmt.Fprint(&buf, formatPAXRecord(k, paxHeaders[k]))
372 ext.Size = int64(len(buf.Bytes()))
373 if err := tw.writeHeader(ext, false); err != nil {
376 if _, err := tw.Write(buf.Bytes()); err != nil {
379 if err := tw.Flush(); err != nil {
385 // formatPAXRecord formats a single PAX record, prefixing it with the
386 // appropriate length.
387 func formatPAXRecord(k, v string) string {
388 const padding = 3 // Extra padding for ' ', '=', and '\n'
389 size := len(k) + len(v) + padding
390 size += len(strconv.Itoa(size))
391 record := fmt.Sprintf("%d %s=%s\n", size, k, v)
393 // Final adjustment if adding size field increased the record size.
394 if len(record) != size {
396 record = fmt.Sprintf("%d %s=%s\n", size, k, v)
401 // Write writes to the current entry in the tar archive.
402 // Write returns the error ErrWriteTooLong if more than
403 // hdr.Size bytes are written after WriteHeader.
404 func (tw *Writer) Write(b []byte) (n int, err error) {
406 err = ErrWriteAfterClose
410 if int64(len(b)) > tw.nb {
414 n, err = tw.w.Write(b)
416 if err == nil && overwrite {
417 err = ErrWriteTooLong
424 // Close closes the tar archive, flushing any unwritten
425 // data to the underlying writer.
426 func (tw *Writer) Close() error {
427 if tw.err != nil || tw.closed {
436 // trailer: two zero blocks
437 for i := 0; i < 2; i++ {
438 _, tw.err = tw.w.Write(zeroBlock)