libgo: Update to Go 1.3 release.
[official-gcc.git] / libgo / go / archive / tar / writer.go
blob6eff6f6f84d8eaa903b87c135ec4f5f6684b4667
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.
5 package tar
7 // TODO(dsymonds):
8 // - catch more errors (no first header, etc.)
10 import (
11 "bytes"
12 "errors"
13 "fmt"
14 "io"
15 "os"
16 "path"
17 "strconv"
18 "strings"
19 "time"
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 errNameTooLong = errors.New("archive/tar: name too long")
27 errInvalidHeader = errors.New("archive/tar: header field too long or contains invalid values")
30 // A Writer provides sequential writing of a tar archive in POSIX.1 format.
31 // A tar archive consists of a sequence of files.
32 // Call WriteHeader to begin a new file, and then call Write to supply that file's data,
33 // writing at most hdr.Size bytes in total.
34 type Writer struct {
35 w io.Writer
36 err error
37 nb int64 // number of unwritten bytes for current file entry
38 pad int64 // amount of padding to write after current file entry
39 closed bool
40 usedBinary bool // whether the binary numeric field extension was used
41 preferPax bool // use pax header instead of binary numeric header
44 // NewWriter creates a new Writer writing to w.
45 func NewWriter(w io.Writer) *Writer { return &Writer{w: w} }
47 // Flush finishes writing the current file (optional).
48 func (tw *Writer) Flush() error {
49 if tw.nb > 0 {
50 tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb)
51 return tw.err
54 n := tw.nb + tw.pad
55 for n > 0 && tw.err == nil {
56 nr := n
57 if nr > blockSize {
58 nr = blockSize
60 var nw int
61 nw, tw.err = tw.w.Write(zeroBlock[0:nr])
62 n -= int64(nw)
64 tw.nb = 0
65 tw.pad = 0
66 return tw.err
69 // Write s into b, terminating it with a NUL if there is room.
70 // If the value is too long for the field and allowPax is true add a paxheader record instead
71 func (tw *Writer) cString(b []byte, s string, allowPax bool, paxKeyword string, paxHeaders map[string]string) {
72 needsPaxHeader := allowPax && len(s) > len(b) || !isASCII(s)
73 if needsPaxHeader {
74 paxHeaders[paxKeyword] = s
75 return
77 if len(s) > len(b) {
78 if tw.err == nil {
79 tw.err = ErrFieldTooLong
81 return
83 ascii := toASCII(s)
84 copy(b, ascii)
85 if len(ascii) < len(b) {
86 b[len(ascii)] = 0
90 // Encode x as an octal ASCII string and write it into b with leading zeros.
91 func (tw *Writer) octal(b []byte, x int64) {
92 s := strconv.FormatInt(x, 8)
93 // leading zeros, but leave room for a NUL.
94 for len(s)+1 < len(b) {
95 s = "0" + s
97 tw.cString(b, s, false, paxNone, nil)
100 // Write x into b, either as octal or as binary (GNUtar/star extension).
101 // If the value is too long for the field and writingPax is enabled both for the field and the add a paxheader record instead
102 func (tw *Writer) numeric(b []byte, x int64, allowPax bool, paxKeyword string, paxHeaders map[string]string) {
103 // Try octal first.
104 s := strconv.FormatInt(x, 8)
105 if len(s) < len(b) {
106 tw.octal(b, x)
107 return
110 // If it is too long for octal, and pax is preferred, use a pax header
111 if allowPax && tw.preferPax {
112 tw.octal(b, 0)
113 s := strconv.FormatInt(x, 10)
114 paxHeaders[paxKeyword] = s
115 return
118 // Too big: use binary (big-endian).
119 tw.usedBinary = true
120 for i := len(b) - 1; x > 0 && i >= 0; i-- {
121 b[i] = byte(x)
122 x >>= 8
124 b[0] |= 0x80 // highest bit indicates binary format
127 var (
128 minTime = time.Unix(0, 0)
129 // There is room for 11 octal digits (33 bits) of mtime.
130 maxTime = minTime.Add((1<<33 - 1) * time.Second)
133 // WriteHeader writes hdr and prepares to accept the file's contents.
134 // WriteHeader calls Flush if it is not the first header.
135 // Calling after a Close will return ErrWriteAfterClose.
136 func (tw *Writer) WriteHeader(hdr *Header) error {
137 return tw.writeHeader(hdr, true)
140 // WriteHeader writes hdr and prepares to accept the file's contents.
141 // WriteHeader calls Flush if it is not the first header.
142 // Calling after a Close will return ErrWriteAfterClose.
143 // As this method is called internally by writePax header to allow it to
144 // suppress writing the pax header.
145 func (tw *Writer) writeHeader(hdr *Header, allowPax bool) error {
146 if tw.closed {
147 return ErrWriteAfterClose
149 if tw.err == nil {
150 tw.Flush()
152 if tw.err != nil {
153 return tw.err
156 // a map to hold pax header records, if any are needed
157 paxHeaders := make(map[string]string)
159 // TODO(shanemhansen): we might want to use PAX headers for
160 // subsecond time resolution, but for now let's just capture
161 // too long fields or non ascii characters
163 header := make([]byte, blockSize)
164 s := slicer(header)
166 // keep a reference to the filename to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
167 pathHeaderBytes := s.next(fileNameSize)
169 tw.cString(pathHeaderBytes, hdr.Name, true, paxPath, paxHeaders)
171 // Handle out of range ModTime carefully.
172 var modTime int64
173 if !hdr.ModTime.Before(minTime) && !hdr.ModTime.After(maxTime) {
174 modTime = hdr.ModTime.Unix()
177 tw.octal(s.next(8), hdr.Mode) // 100:108
178 tw.numeric(s.next(8), int64(hdr.Uid), true, paxUid, paxHeaders) // 108:116
179 tw.numeric(s.next(8), int64(hdr.Gid), true, paxGid, paxHeaders) // 116:124
180 tw.numeric(s.next(12), hdr.Size, true, paxSize, paxHeaders) // 124:136
181 tw.numeric(s.next(12), modTime, false, paxNone, nil) // 136:148 --- consider using pax for finer granularity
182 s.next(8) // chksum (148:156)
183 s.next(1)[0] = hdr.Typeflag // 156:157
185 tw.cString(s.next(100), hdr.Linkname, true, paxLinkpath, paxHeaders)
187 copy(s.next(8), []byte("ustar\x0000")) // 257:265
188 tw.cString(s.next(32), hdr.Uname, true, paxUname, paxHeaders) // 265:297
189 tw.cString(s.next(32), hdr.Gname, true, paxGname, paxHeaders) // 297:329
190 tw.numeric(s.next(8), hdr.Devmajor, false, paxNone, nil) // 329:337
191 tw.numeric(s.next(8), hdr.Devminor, false, paxNone, nil) // 337:345
193 // keep a reference to the prefix to allow to overwrite it later if we detect that we can use ustar longnames instead of pax
194 prefixHeaderBytes := s.next(155)
195 tw.cString(prefixHeaderBytes, "", false, paxNone, nil) // 345:500 prefix
197 // Use the GNU magic instead of POSIX magic if we used any GNU extensions.
198 if tw.usedBinary {
199 copy(header[257:265], []byte("ustar \x00"))
202 _, paxPathUsed := paxHeaders[paxPath]
203 // try to use a ustar header when only the name is too long
204 if !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed {
205 suffix := hdr.Name
206 prefix := ""
207 if len(hdr.Name) > fileNameSize && isASCII(hdr.Name) {
208 var err error
209 prefix, suffix, err = tw.splitUSTARLongName(hdr.Name)
210 if err == nil {
211 // ok we can use a ustar long name instead of pax, now correct the fields
213 // remove the path field from the pax header. this will suppress the pax header
214 delete(paxHeaders, paxPath)
216 // update the path fields
217 tw.cString(pathHeaderBytes, suffix, false, paxNone, nil)
218 tw.cString(prefixHeaderBytes, prefix, false, paxNone, nil)
220 // Use the ustar magic if we used ustar long names.
221 if len(prefix) > 0 && !tw.usedBinary {
222 copy(header[257:265], []byte("ustar\x00"))
228 // The chksum field is terminated by a NUL and a space.
229 // This is different from the other octal fields.
230 chksum, _ := checksum(header)
231 tw.octal(header[148:155], chksum)
232 header[155] = ' '
234 if tw.err != nil {
235 // problem with header; probably integer too big for a field.
236 return tw.err
239 if allowPax {
240 for k, v := range hdr.Xattrs {
241 paxHeaders[paxXattr+k] = v
245 if len(paxHeaders) > 0 {
246 if !allowPax {
247 return errInvalidHeader
249 if err := tw.writePAXHeader(hdr, paxHeaders); err != nil {
250 return err
253 tw.nb = int64(hdr.Size)
254 tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize
256 _, tw.err = tw.w.Write(header)
257 return tw.err
260 // writeUSTARLongName splits a USTAR long name hdr.Name.
261 // name must be < 256 characters. errNameTooLong is returned
262 // if hdr.Name can't be split. The splitting heuristic
263 // is compatible with gnu tar.
264 func (tw *Writer) splitUSTARLongName(name string) (prefix, suffix string, err error) {
265 length := len(name)
266 if length > fileNamePrefixSize+1 {
267 length = fileNamePrefixSize + 1
268 } else if name[length-1] == '/' {
269 length--
271 i := strings.LastIndex(name[:length], "/")
272 // nlen contains the resulting length in the name field.
273 // plen contains the resulting length in the prefix field.
274 nlen := len(name) - i - 1
275 plen := i
276 if i <= 0 || nlen > fileNameSize || nlen == 0 || plen > fileNamePrefixSize {
277 err = errNameTooLong
278 return
280 prefix, suffix = name[:i], name[i+1:]
281 return
284 // writePaxHeader writes an extended pax header to the
285 // archive.
286 func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error {
287 // Prepare extended header
288 ext := new(Header)
289 ext.Typeflag = TypeXHeader
290 // Setting ModTime is required for reader parsing to
291 // succeed, and seems harmless enough.
292 ext.ModTime = hdr.ModTime
293 // The spec asks that we namespace our pseudo files
294 // with the current pid.
295 pid := os.Getpid()
296 dir, file := path.Split(hdr.Name)
297 fullName := path.Join(dir,
298 fmt.Sprintf("PaxHeaders.%d", pid), file)
300 ascii := toASCII(fullName)
301 if len(ascii) > 100 {
302 ascii = ascii[:100]
304 ext.Name = ascii
305 // Construct the body
306 var buf bytes.Buffer
308 for k, v := range paxHeaders {
309 fmt.Fprint(&buf, paxHeader(k+"="+v))
312 ext.Size = int64(len(buf.Bytes()))
313 if err := tw.writeHeader(ext, false); err != nil {
314 return err
316 if _, err := tw.Write(buf.Bytes()); err != nil {
317 return err
319 if err := tw.Flush(); err != nil {
320 return err
322 return nil
325 // paxHeader formats a single pax record, prefixing it with the appropriate length
326 func paxHeader(msg string) string {
327 const padding = 2 // Extra padding for space and newline
328 size := len(msg) + padding
329 size += len(strconv.Itoa(size))
330 record := fmt.Sprintf("%d %s\n", size, msg)
331 if len(record) != size {
332 // Final adjustment if adding size increased
333 // the number of digits in size
334 size = len(record)
335 record = fmt.Sprintf("%d %s\n", size, msg)
337 return record
340 // Write writes to the current entry in the tar archive.
341 // Write returns the error ErrWriteTooLong if more than
342 // hdr.Size bytes are written after WriteHeader.
343 func (tw *Writer) Write(b []byte) (n int, err error) {
344 if tw.closed {
345 err = ErrWriteTooLong
346 return
348 overwrite := false
349 if int64(len(b)) > tw.nb {
350 b = b[0:tw.nb]
351 overwrite = true
353 n, err = tw.w.Write(b)
354 tw.nb -= int64(n)
355 if err == nil && overwrite {
356 err = ErrWriteTooLong
357 return
359 tw.err = err
360 return
363 // Close closes the tar archive, flushing any unwritten
364 // data to the underlying writer.
365 func (tw *Writer) Close() error {
366 if tw.err != nil || tw.closed {
367 return tw.err
369 tw.Flush()
370 tw.closed = true
371 if tw.err != nil {
372 return tw.err
375 // trailer: two zero blocks
376 for i := 0; i < 2; i++ {
377 _, tw.err = tw.w.Write(zeroBlock)
378 if tw.err != nil {
379 break
382 return tw.err