writer.go 12 KB

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