Tizen_4.0 base
[platform/upstream/docker-engine.git] / vendor / github.com / Microsoft / go-winio / archive / tar / writer.go
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    [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
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, preferPax: true} }
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(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         var formatTime = func(b []byte, t time.Time, paxKeyword string) {
205                 var unixTime int64
206                 if !t.Before(minTime) && !t.After(maxTime) {
207                         unixTime = t.Unix()
208                 }
209                 formatNumeric(b, unixTime, paxNone)
210
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)
214                 }
215         }
216
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)
219
220         formatString(pathHeaderBytes, hdr.Name, paxPath)
221
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
229
230         formatString(s.next(100), hdr.Linkname, paxLinkpath)
231
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
237
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
241
242         // Use the GNU magic instead of POSIX magic if we used any GNU extensions.
243         if tw.usedBinary {
244                 copy(header[257:265], []byte("ustar  \x00"))
245         }
246
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)
251                 if ok {
252                         // Since we can encode in USTAR format, disable PAX header.
253                         delete(paxHeaders, paxPath)
254
255                         // Update the path fields
256                         formatString(pathHeaderBytes, suffix, paxNone)
257                         formatString(prefixHeaderBytes, prefix, paxNone)
258                 }
259         }
260
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
265         header[155] = ' '
266
267         // Check if there were any formatting errors.
268         if f.err != nil {
269                 tw.err = f.err
270                 return tw.err
271         }
272
273         if allowPax {
274                 if !hdr.AccessTime.IsZero() {
275                         paxHeaders[paxAtime] = formatPAXTime(hdr.AccessTime)
276                 }
277                 if !hdr.ChangeTime.IsZero() {
278                         paxHeaders[paxCtime] = formatPAXTime(hdr.ChangeTime)
279                 }
280                 if !hdr.CreationTime.IsZero() {
281                         paxHeaders[paxCreationTime] = formatPAXTime(hdr.CreationTime)
282                 }
283                 for k, v := range hdr.Xattrs {
284                         paxHeaders[paxXattr+k] = v
285                 }
286                 for k, v := range hdr.Winheaders {
287                         paxHeaders[paxWindows+k] = v
288                 }
289         }
290
291         if len(paxHeaders) > 0 {
292                 if !allowPax {
293                         return errInvalidHeader
294                 }
295                 if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
296                         return err
297                 }
298         }
299         tw.nb = int64(hdr.Size)
300         tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
301
302         _, tw.err = tw.w.Write(header)
303         return tw.err
304 }
305
306 func formatPAXTime(t time.Time) string {
307         sec := t.Unix()
308         usec := t.Nanosecond()
309         s := strconv.FormatInt(sec, 10)
310         if usec != 0 {
311                 s = fmt.Sprintf("%s.%09d", s, usec)
312         }
313         return s
314 }
315
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) {
319         length := len(name)
320         if length <= fileNameSize || !isASCII(name) {
321                 return "", "", false
322         } else if length > fileNamePrefixSize+1 {
323                 length = fileNamePrefixSize + 1
324         } else if name[length-1] == '/' {
325                 length--
326         }
327
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 {
332                 return "", "", false
333         }
334         return name[:i], name[i+1:], true
335 }
336
337 // writePaxHeader writes an extended pax header to the
338 // archive.
339 func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
340         // Prepare extended header
341         ext := new(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)
352
353         ascii := toASCII(fullName)
354         if len(ascii) > 100 {
355                 ascii = ascii[:100]
356         }
357         ext.Name = ascii
358         // Construct the body
359         var buf bytes.Buffer
360
361         // Keys are sorted before writing to body to allow deterministic output.
362         var keys []string
363         for k := range paxHeaders {
364                 keys = append(keys, k)
365         }
366         sort.Strings(keys)
367
368         for _, k := range keys {
369                 fmt.Fprint(&buf, formatPAXRecord(k, paxHeaders[k]))
370         }
371
372         ext.Size = int64(len(buf.Bytes()))
373         if err := tw.writeHeader(ext, false); err != nil {
374                 return err
375         }
376         if _, err := tw.Write(buf.Bytes()); err != nil {
377                 return err
378         }
379         if err := tw.Flush(); err != nil {
380                 return err
381         }
382         return nil
383 }
384
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)
392
393         // Final adjustment if adding size field increased the record size.
394         if len(record) != size {
395                 size = len(record)
396                 record = fmt.Sprintf("%d %s=%s\n", size, k, v)
397         }
398         return record
399 }
400
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) {
405         if tw.closed {
406                 err = ErrWriteAfterClose
407                 return
408         }
409         overwrite := false
410         if int64(len(b)) > tw.nb {
411                 b = b[0:tw.nb]
412                 overwrite = true
413         }
414         n, err = tw.w.Write(b)
415         tw.nb -= int64(n)
416         if err == nil && overwrite {
417                 err = ErrWriteTooLong
418                 return
419         }
420         tw.err = err
421         return
422 }
423
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 {
428                 return tw.err
429         }
430         tw.Flush()
431         tw.closed = true
432         if tw.err != nil {
433                 return tw.err
434         }
435
436         // trailer: two zero blocks
437         for i := 0; i < 2; i++ {
438                 _, tw.err = tw.w.Write(zeroBlock)
439                 if tw.err != nil {
440                         break
441                 }
442         }
443         return tw.err
444 }