archive.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. package archive // import "github.com/docker/docker/pkg/archive"
  2. import (
  3. "archive/tar"
  4. "bufio"
  5. "bytes"
  6. "compress/bzip2"
  7. "compress/gzip"
  8. "context"
  9. "encoding/binary"
  10. "fmt"
  11. "io"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "syscall"
  18. "time"
  19. "github.com/containerd/containerd/pkg/userns"
  20. "github.com/docker/docker/pkg/fileutils"
  21. "github.com/docker/docker/pkg/idtools"
  22. "github.com/docker/docker/pkg/ioutils"
  23. "github.com/docker/docker/pkg/pools"
  24. "github.com/docker/docker/pkg/system"
  25. "github.com/klauspost/compress/zstd"
  26. "github.com/moby/sys/sequential"
  27. "github.com/pkg/errors"
  28. "github.com/sirupsen/logrus"
  29. exec "golang.org/x/sys/execabs"
  30. )
  31. type (
  32. // Compression is the state represents if compressed or not.
  33. Compression int
  34. // WhiteoutFormat is the format of whiteouts unpacked
  35. WhiteoutFormat int
  36. // TarOptions wraps the tar options.
  37. TarOptions struct {
  38. IncludeFiles []string
  39. ExcludePatterns []string
  40. Compression Compression
  41. NoLchown bool
  42. IDMap idtools.IdentityMapping
  43. ChownOpts *idtools.Identity
  44. IncludeSourceDir bool
  45. // WhiteoutFormat is the expected on disk format for whiteout files.
  46. // This format will be converted to the standard format on pack
  47. // and from the standard format on unpack.
  48. WhiteoutFormat WhiteoutFormat
  49. // When unpacking, specifies whether overwriting a directory with a
  50. // non-directory is allowed and vice versa.
  51. NoOverwriteDirNonDir bool
  52. // For each include when creating an archive, the included name will be
  53. // replaced with the matching name from this map.
  54. RebaseNames map[string]string
  55. InUserNS bool
  56. }
  57. )
  58. // Archiver implements the Archiver interface and allows the reuse of most utility functions of
  59. // this package with a pluggable Untar function. Also, to facilitate the passing of specific id
  60. // mappings for untar, an Archiver can be created with maps which will then be passed to Untar operations.
  61. type Archiver struct {
  62. Untar func(io.Reader, string, *TarOptions) error
  63. IDMapping idtools.IdentityMapping
  64. }
  65. // NewDefaultArchiver returns a new Archiver without any IdentityMapping
  66. func NewDefaultArchiver() *Archiver {
  67. return &Archiver{Untar: Untar}
  68. }
  69. // breakoutError is used to differentiate errors related to breaking out
  70. // When testing archive breakout in the unit tests, this error is expected
  71. // in order for the test to pass.
  72. type breakoutError error
  73. const (
  74. // Uncompressed represents the uncompressed.
  75. Uncompressed Compression = iota
  76. // Bzip2 is bzip2 compression algorithm.
  77. Bzip2
  78. // Gzip is gzip compression algorithm.
  79. Gzip
  80. // Xz is xz compression algorithm.
  81. Xz
  82. // Zstd is zstd compression algorithm.
  83. Zstd
  84. )
  85. const (
  86. // AUFSWhiteoutFormat is the default format for whiteouts
  87. AUFSWhiteoutFormat WhiteoutFormat = iota
  88. // OverlayWhiteoutFormat formats whiteout according to the overlay
  89. // standard.
  90. OverlayWhiteoutFormat
  91. )
  92. // IsArchivePath checks if the (possibly compressed) file at the given path
  93. // starts with a tar file header.
  94. func IsArchivePath(path string) bool {
  95. file, err := os.Open(path)
  96. if err != nil {
  97. return false
  98. }
  99. defer file.Close()
  100. rdr, err := DecompressStream(file)
  101. if err != nil {
  102. return false
  103. }
  104. defer rdr.Close()
  105. r := tar.NewReader(rdr)
  106. _, err = r.Next()
  107. return err == nil
  108. }
  109. const (
  110. zstdMagicSkippableStart = 0x184D2A50
  111. zstdMagicSkippableMask = 0xFFFFFFF0
  112. )
  113. var (
  114. bzip2Magic = []byte{0x42, 0x5A, 0x68}
  115. gzipMagic = []byte{0x1F, 0x8B, 0x08}
  116. xzMagic = []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}
  117. zstdMagic = []byte{0x28, 0xb5, 0x2f, 0xfd}
  118. )
  119. type matcher = func([]byte) bool
  120. func magicNumberMatcher(m []byte) matcher {
  121. return func(source []byte) bool {
  122. return bytes.HasPrefix(source, m)
  123. }
  124. }
  125. // zstdMatcher detects zstd compression algorithm.
  126. // Zstandard compressed data is made of one or more frames.
  127. // There are two frame formats defined by Zstandard: Zstandard frames and Skippable frames.
  128. // See https://tools.ietf.org/id/draft-kucherawy-dispatch-zstd-00.html#rfc.section.2 for more details.
  129. func zstdMatcher() matcher {
  130. return func(source []byte) bool {
  131. if bytes.HasPrefix(source, zstdMagic) {
  132. // Zstandard frame
  133. return true
  134. }
  135. // skippable frame
  136. if len(source) < 8 {
  137. return false
  138. }
  139. // magic number from 0x184D2A50 to 0x184D2A5F.
  140. if binary.LittleEndian.Uint32(source[:4])&zstdMagicSkippableMask == zstdMagicSkippableStart {
  141. return true
  142. }
  143. return false
  144. }
  145. }
  146. // DetectCompression detects the compression algorithm of the source.
  147. func DetectCompression(source []byte) Compression {
  148. compressionMap := map[Compression]matcher{
  149. Bzip2: magicNumberMatcher(bzip2Magic),
  150. Gzip: magicNumberMatcher(gzipMagic),
  151. Xz: magicNumberMatcher(xzMagic),
  152. Zstd: zstdMatcher(),
  153. }
  154. for _, compression := range []Compression{Bzip2, Gzip, Xz, Zstd} {
  155. fn := compressionMap[compression]
  156. if fn(source) {
  157. return compression
  158. }
  159. }
  160. return Uncompressed
  161. }
  162. func xzDecompress(ctx context.Context, archive io.Reader) (io.ReadCloser, error) {
  163. args := []string{"xz", "-d", "-c", "-q"}
  164. return cmdStream(exec.CommandContext(ctx, args[0], args[1:]...), archive)
  165. }
  166. func gzDecompress(ctx context.Context, buf io.Reader) (io.ReadCloser, error) {
  167. if noPigzEnv := os.Getenv("MOBY_DISABLE_PIGZ"); noPigzEnv != "" {
  168. noPigz, err := strconv.ParseBool(noPigzEnv)
  169. if err != nil {
  170. logrus.WithError(err).Warn("invalid value in MOBY_DISABLE_PIGZ env var")
  171. }
  172. if noPigz {
  173. logrus.Debugf("Use of pigz is disabled due to MOBY_DISABLE_PIGZ=%s", noPigzEnv)
  174. return gzip.NewReader(buf)
  175. }
  176. }
  177. unpigzPath, err := exec.LookPath("unpigz")
  178. if err != nil {
  179. logrus.Debugf("unpigz binary not found, falling back to go gzip library")
  180. return gzip.NewReader(buf)
  181. }
  182. logrus.Debugf("Using %s to decompress", unpigzPath)
  183. return cmdStream(exec.CommandContext(ctx, unpigzPath, "-d", "-c"), buf)
  184. }
  185. func wrapReadCloser(readBuf io.ReadCloser, cancel context.CancelFunc) io.ReadCloser {
  186. return ioutils.NewReadCloserWrapper(readBuf, func() error {
  187. cancel()
  188. return readBuf.Close()
  189. })
  190. }
  191. // DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive.
  192. func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
  193. p := pools.BufioReader32KPool
  194. buf := p.Get(archive)
  195. bs, err := buf.Peek(10)
  196. if err != nil && err != io.EOF {
  197. // Note: we'll ignore any io.EOF error because there are some odd
  198. // cases where the layer.tar file will be empty (zero bytes) and
  199. // that results in an io.EOF from the Peek() call. So, in those
  200. // cases we'll just treat it as a non-compressed stream and
  201. // that means just create an empty layer.
  202. // See Issue 18170
  203. return nil, err
  204. }
  205. compression := DetectCompression(bs)
  206. switch compression {
  207. case Uncompressed:
  208. readBufWrapper := p.NewReadCloserWrapper(buf, buf)
  209. return readBufWrapper, nil
  210. case Gzip:
  211. ctx, cancel := context.WithCancel(context.Background())
  212. gzReader, err := gzDecompress(ctx, buf)
  213. if err != nil {
  214. cancel()
  215. return nil, err
  216. }
  217. readBufWrapper := p.NewReadCloserWrapper(buf, gzReader)
  218. return wrapReadCloser(readBufWrapper, cancel), nil
  219. case Bzip2:
  220. bz2Reader := bzip2.NewReader(buf)
  221. readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader)
  222. return readBufWrapper, nil
  223. case Xz:
  224. ctx, cancel := context.WithCancel(context.Background())
  225. xzReader, err := xzDecompress(ctx, buf)
  226. if err != nil {
  227. cancel()
  228. return nil, err
  229. }
  230. readBufWrapper := p.NewReadCloserWrapper(buf, xzReader)
  231. return wrapReadCloser(readBufWrapper, cancel), nil
  232. case Zstd:
  233. zstdReader, err := zstd.NewReader(buf)
  234. if err != nil {
  235. return nil, err
  236. }
  237. readBufWrapper := p.NewReadCloserWrapper(buf, zstdReader)
  238. return readBufWrapper, nil
  239. default:
  240. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  241. }
  242. }
  243. // CompressStream compresses the dest with specified compression algorithm.
  244. func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) {
  245. p := pools.BufioWriter32KPool
  246. buf := p.Get(dest)
  247. switch compression {
  248. case Uncompressed:
  249. writeBufWrapper := p.NewWriteCloserWrapper(buf, buf)
  250. return writeBufWrapper, nil
  251. case Gzip:
  252. gzWriter := gzip.NewWriter(dest)
  253. writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter)
  254. return writeBufWrapper, nil
  255. case Bzip2, Xz:
  256. // archive/bzip2 does not support writing, and there is no xz support at all
  257. // However, this is not a problem as docker only currently generates gzipped tars
  258. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  259. default:
  260. return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
  261. }
  262. }
  263. // TarModifierFunc is a function that can be passed to ReplaceFileTarWrapper to
  264. // modify the contents or header of an entry in the archive. If the file already
  265. // exists in the archive the TarModifierFunc will be called with the Header and
  266. // a reader which will return the files content. If the file does not exist both
  267. // header and content will be nil.
  268. type TarModifierFunc func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error)
  269. // ReplaceFileTarWrapper converts inputTarStream to a new tar stream. Files in the
  270. // tar stream are modified if they match any of the keys in mods.
  271. func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModifierFunc) io.ReadCloser {
  272. pipeReader, pipeWriter := io.Pipe()
  273. go func() {
  274. tarReader := tar.NewReader(inputTarStream)
  275. tarWriter := tar.NewWriter(pipeWriter)
  276. defer inputTarStream.Close()
  277. defer tarWriter.Close()
  278. modify := func(name string, original *tar.Header, modifier TarModifierFunc, tarReader io.Reader) error {
  279. header, data, err := modifier(name, original, tarReader)
  280. switch {
  281. case err != nil:
  282. return err
  283. case header == nil:
  284. return nil
  285. }
  286. if header.Name == "" {
  287. header.Name = name
  288. }
  289. header.Size = int64(len(data))
  290. if err := tarWriter.WriteHeader(header); err != nil {
  291. return err
  292. }
  293. if len(data) != 0 {
  294. if _, err := tarWriter.Write(data); err != nil {
  295. return err
  296. }
  297. }
  298. return nil
  299. }
  300. var err error
  301. var originalHeader *tar.Header
  302. for {
  303. originalHeader, err = tarReader.Next()
  304. if err == io.EOF {
  305. break
  306. }
  307. if err != nil {
  308. pipeWriter.CloseWithError(err)
  309. return
  310. }
  311. modifier, ok := mods[originalHeader.Name]
  312. if !ok {
  313. // No modifiers for this file, copy the header and data
  314. if err := tarWriter.WriteHeader(originalHeader); err != nil {
  315. pipeWriter.CloseWithError(err)
  316. return
  317. }
  318. if _, err := pools.Copy(tarWriter, tarReader); err != nil {
  319. pipeWriter.CloseWithError(err)
  320. return
  321. }
  322. continue
  323. }
  324. delete(mods, originalHeader.Name)
  325. if err := modify(originalHeader.Name, originalHeader, modifier, tarReader); err != nil {
  326. pipeWriter.CloseWithError(err)
  327. return
  328. }
  329. }
  330. // Apply the modifiers that haven't matched any files in the archive
  331. for name, modifier := range mods {
  332. if err := modify(name, nil, modifier, nil); err != nil {
  333. pipeWriter.CloseWithError(err)
  334. return
  335. }
  336. }
  337. pipeWriter.Close()
  338. }()
  339. return pipeReader
  340. }
  341. // Extension returns the extension of a file that uses the specified compression algorithm.
  342. func (compression *Compression) Extension() string {
  343. switch *compression {
  344. case Uncompressed:
  345. return "tar"
  346. case Bzip2:
  347. return "tar.bz2"
  348. case Gzip:
  349. return "tar.gz"
  350. case Xz:
  351. return "tar.xz"
  352. case Zstd:
  353. return "tar.zst"
  354. }
  355. return ""
  356. }
  357. // nosysFileInfo hides the system-dependent info of the wrapped FileInfo to
  358. // prevent tar.FileInfoHeader from introspecting it and potentially calling into
  359. // glibc.
  360. type nosysFileInfo struct {
  361. os.FileInfo
  362. }
  363. func (fi nosysFileInfo) Sys() interface{} {
  364. // A Sys value of type *tar.Header is safe as it is system-independent.
  365. // The tar.FileInfoHeader function copies the fields into the returned
  366. // header without performing any OS lookups.
  367. if sys, ok := fi.FileInfo.Sys().(*tar.Header); ok {
  368. return sys
  369. }
  370. return nil
  371. }
  372. // sysStat, if non-nil, populates hdr from system-dependent fields of fi.
  373. var sysStat func(fi os.FileInfo, hdr *tar.Header) error
  374. // FileInfoHeaderNoLookups creates a partially-populated tar.Header from fi.
  375. //
  376. // Compared to the archive/tar.FileInfoHeader function, this function is safe to
  377. // call from a chrooted process as it does not populate fields which would
  378. // require operating system lookups. It behaves identically to
  379. // tar.FileInfoHeader when fi is a FileInfo value returned from
  380. // tar.Header.FileInfo().
  381. //
  382. // When fi is a FileInfo for a native file, such as returned from os.Stat() and
  383. // os.Lstat(), the returned Header value differs from one returned from
  384. // tar.FileInfoHeader in the following ways. The Uname and Gname fields are not
  385. // set as OS lookups would be required to populate them. The AccessTime and
  386. // ChangeTime fields are not currently set (not yet implemented) although that
  387. // is subject to change. Callers which require the AccessTime or ChangeTime
  388. // fields to be zeroed should explicitly zero them out in the returned Header
  389. // value to avoid any compatibility issues in the future.
  390. func FileInfoHeaderNoLookups(fi os.FileInfo, link string) (*tar.Header, error) {
  391. hdr, err := tar.FileInfoHeader(nosysFileInfo{fi}, link)
  392. if err != nil {
  393. return nil, err
  394. }
  395. if sysStat != nil {
  396. return hdr, sysStat(fi, hdr)
  397. }
  398. return hdr, nil
  399. }
  400. // FileInfoHeader creates a populated Header from fi.
  401. //
  402. // Compared to the archive/tar package, this function fills in less information
  403. // but is safe to call from a chrooted process. The AccessTime and ChangeTime
  404. // fields are not set in the returned header, ModTime is truncated to one-second
  405. // precision, and the Uname and Gname fields are only set when fi is a FileInfo
  406. // value returned from tar.Header.FileInfo().
  407. func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, error) {
  408. hdr, err := FileInfoHeaderNoLookups(fi, link)
  409. if err != nil {
  410. return nil, err
  411. }
  412. hdr.Format = tar.FormatPAX
  413. hdr.ModTime = hdr.ModTime.Truncate(time.Second)
  414. hdr.AccessTime = time.Time{}
  415. hdr.ChangeTime = time.Time{}
  416. hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))
  417. hdr.Name = canonicalTarName(name, fi.IsDir())
  418. return hdr, nil
  419. }
  420. // ReadSecurityXattrToTarHeader reads security.capability xattr from filesystem
  421. // to a tar header
  422. func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error {
  423. const (
  424. // Values based on linux/include/uapi/linux/capability.h
  425. xattrCapsSz2 = 20
  426. versionOffset = 3
  427. vfsCapRevision2 = 2
  428. vfsCapRevision3 = 3
  429. )
  430. capability, _ := system.Lgetxattr(path, "security.capability")
  431. if capability != nil {
  432. length := len(capability)
  433. if capability[versionOffset] == vfsCapRevision3 {
  434. // Convert VFS_CAP_REVISION_3 to VFS_CAP_REVISION_2 as root UID makes no
  435. // sense outside the user namespace the archive is built in.
  436. capability[versionOffset] = vfsCapRevision2
  437. length = xattrCapsSz2
  438. }
  439. hdr.Xattrs = make(map[string]string)
  440. hdr.Xattrs["security.capability"] = string(capability[:length])
  441. }
  442. return nil
  443. }
  444. type tarWhiteoutConverter interface {
  445. ConvertWrite(*tar.Header, string, os.FileInfo) (*tar.Header, error)
  446. ConvertRead(*tar.Header, string) (bool, error)
  447. }
  448. type tarAppender struct {
  449. TarWriter *tar.Writer
  450. Buffer *bufio.Writer
  451. // for hardlink mapping
  452. SeenFiles map[uint64]string
  453. IdentityMapping idtools.IdentityMapping
  454. ChownOpts *idtools.Identity
  455. // For packing and unpacking whiteout files in the
  456. // non standard format. The whiteout files defined
  457. // by the AUFS standard are used as the tar whiteout
  458. // standard.
  459. WhiteoutConverter tarWhiteoutConverter
  460. }
  461. func newTarAppender(idMapping idtools.IdentityMapping, writer io.Writer, chownOpts *idtools.Identity) *tarAppender {
  462. return &tarAppender{
  463. SeenFiles: make(map[uint64]string),
  464. TarWriter: tar.NewWriter(writer),
  465. Buffer: pools.BufioWriter32KPool.Get(nil),
  466. IdentityMapping: idMapping,
  467. ChownOpts: chownOpts,
  468. }
  469. }
  470. // CanonicalTarNameForPath canonicalizes relativePath to a POSIX-style path using
  471. // forward slashes. It is an alias for filepath.ToSlash, which is a no-op on
  472. // Linux and Unix.
  473. func CanonicalTarNameForPath(relativePath string) string {
  474. return filepath.ToSlash(relativePath)
  475. }
  476. // canonicalTarName provides a platform-independent and consistent POSIX-style
  477. // path for files and directories to be archived regardless of the platform.
  478. func canonicalTarName(name string, isDir bool) string {
  479. name = filepath.ToSlash(name)
  480. // suffix with '/' for directories
  481. if isDir && !strings.HasSuffix(name, "/") {
  482. name += "/"
  483. }
  484. return name
  485. }
  486. // addTarFile adds to the tar archive a file from `path` as `name`
  487. func (ta *tarAppender) addTarFile(path, name string) error {
  488. fi, err := os.Lstat(path)
  489. if err != nil {
  490. return err
  491. }
  492. var link string
  493. if fi.Mode()&os.ModeSymlink != 0 {
  494. var err error
  495. link, err = os.Readlink(path)
  496. if err != nil {
  497. return err
  498. }
  499. }
  500. hdr, err := FileInfoHeader(name, fi, link)
  501. if err != nil {
  502. return err
  503. }
  504. if err := ReadSecurityXattrToTarHeader(path, hdr); err != nil {
  505. return err
  506. }
  507. // if it's not a directory and has more than 1 link,
  508. // it's hard linked, so set the type flag accordingly
  509. if !fi.IsDir() && hasHardlinks(fi) {
  510. inode, err := getInodeFromStat(fi.Sys())
  511. if err != nil {
  512. return err
  513. }
  514. // a link should have a name that it links too
  515. // and that linked name should be first in the tar archive
  516. if oldpath, ok := ta.SeenFiles[inode]; ok {
  517. hdr.Typeflag = tar.TypeLink
  518. hdr.Linkname = oldpath
  519. hdr.Size = 0 // This Must be here for the writer math to add up!
  520. } else {
  521. ta.SeenFiles[inode] = name
  522. }
  523. }
  524. // check whether the file is overlayfs whiteout
  525. // if yes, skip re-mapping container ID mappings.
  526. isOverlayWhiteout := fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0
  527. // handle re-mapping container ID mappings back to host ID mappings before
  528. // writing tar headers/files. We skip whiteout files because they were written
  529. // by the kernel and already have proper ownership relative to the host
  530. if !isOverlayWhiteout && !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && !ta.IdentityMapping.Empty() {
  531. fileIDPair, err := getFileUIDGID(fi.Sys())
  532. if err != nil {
  533. return err
  534. }
  535. hdr.Uid, hdr.Gid, err = ta.IdentityMapping.ToContainer(fileIDPair)
  536. if err != nil {
  537. return err
  538. }
  539. }
  540. // explicitly override with ChownOpts
  541. if ta.ChownOpts != nil {
  542. hdr.Uid = ta.ChownOpts.UID
  543. hdr.Gid = ta.ChownOpts.GID
  544. }
  545. if ta.WhiteoutConverter != nil {
  546. wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, path, fi)
  547. if err != nil {
  548. return err
  549. }
  550. // If a new whiteout file exists, write original hdr, then
  551. // replace hdr with wo to be written after. Whiteouts should
  552. // always be written after the original. Note the original
  553. // hdr may have been updated to be a whiteout with returning
  554. // a whiteout header
  555. if wo != nil {
  556. if err := ta.TarWriter.WriteHeader(hdr); err != nil {
  557. return err
  558. }
  559. if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 {
  560. return fmt.Errorf("tar: cannot use whiteout for non-empty file")
  561. }
  562. hdr = wo
  563. }
  564. }
  565. if err := ta.TarWriter.WriteHeader(hdr); err != nil {
  566. return err
  567. }
  568. if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 {
  569. // We use sequential file access to avoid depleting the standby list on
  570. // Windows. On Linux, this equates to a regular os.Open.
  571. file, err := sequential.Open(path)
  572. if err != nil {
  573. return err
  574. }
  575. ta.Buffer.Reset(ta.TarWriter)
  576. defer ta.Buffer.Reset(nil)
  577. _, err = io.Copy(ta.Buffer, file)
  578. file.Close()
  579. if err != nil {
  580. return err
  581. }
  582. err = ta.Buffer.Flush()
  583. if err != nil {
  584. return err
  585. }
  586. }
  587. return nil
  588. }
  589. func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *idtools.Identity, inUserns bool) error {
  590. // hdr.Mode is in linux format, which we can use for sycalls,
  591. // but for os.Foo() calls we need the mode converted to os.FileMode,
  592. // so use hdrInfo.Mode() (they differ for e.g. setuid bits)
  593. hdrInfo := hdr.FileInfo()
  594. switch hdr.Typeflag {
  595. case tar.TypeDir:
  596. // Create directory unless it exists as a directory already.
  597. // In that case we just want to merge the two
  598. if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) {
  599. if err := os.Mkdir(path, hdrInfo.Mode()); err != nil {
  600. return err
  601. }
  602. }
  603. case tar.TypeReg, tar.TypeRegA:
  604. // Source is regular file. We use sequential file access to avoid depleting
  605. // the standby list on Windows. On Linux, this equates to a regular os.OpenFile.
  606. file, err := sequential.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
  607. if err != nil {
  608. return err
  609. }
  610. if _, err := io.Copy(file, reader); err != nil {
  611. file.Close()
  612. return err
  613. }
  614. file.Close()
  615. case tar.TypeBlock, tar.TypeChar:
  616. if inUserns { // cannot create devices in a userns
  617. return nil
  618. }
  619. // Handle this is an OS-specific way
  620. if err := handleTarTypeBlockCharFifo(hdr, path); err != nil {
  621. return err
  622. }
  623. case tar.TypeFifo:
  624. // Handle this is an OS-specific way
  625. if err := handleTarTypeBlockCharFifo(hdr, path); err != nil {
  626. return err
  627. }
  628. case tar.TypeLink:
  629. // #nosec G305 -- The target path is checked for path traversal.
  630. targetPath := filepath.Join(extractDir, hdr.Linkname)
  631. // check for hardlink breakout
  632. if !strings.HasPrefix(targetPath, extractDir) {
  633. return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname))
  634. }
  635. if err := os.Link(targetPath, path); err != nil {
  636. return err
  637. }
  638. case tar.TypeSymlink:
  639. // path -> hdr.Linkname = targetPath
  640. // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file
  641. targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) // #nosec G305 -- The target path is checked for path traversal.
  642. // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because
  643. // that symlink would first have to be created, which would be caught earlier, at this very check:
  644. if !strings.HasPrefix(targetPath, extractDir) {
  645. return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname))
  646. }
  647. if err := os.Symlink(hdr.Linkname, path); err != nil {
  648. return err
  649. }
  650. case tar.TypeXGlobalHeader:
  651. logrus.Debug("PAX Global Extended Headers found and ignored")
  652. return nil
  653. default:
  654. return fmt.Errorf("unhandled tar header type %d", hdr.Typeflag)
  655. }
  656. // Lchown is not supported on Windows.
  657. if Lchown && runtime.GOOS != "windows" {
  658. if chownOpts == nil {
  659. chownOpts = &idtools.Identity{UID: hdr.Uid, GID: hdr.Gid}
  660. }
  661. if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil {
  662. msg := "failed to Lchown %q for UID %d, GID %d"
  663. if errors.Is(err, syscall.EINVAL) && userns.RunningInUserNS() {
  664. msg += " (try increasing the number of subordinate IDs in /etc/subuid and /etc/subgid)"
  665. }
  666. return errors.Wrapf(err, msg, path, hdr.Uid, hdr.Gid)
  667. }
  668. }
  669. var errors []string
  670. for key, value := range hdr.Xattrs {
  671. if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil {
  672. if err == syscall.ENOTSUP || err == syscall.EPERM {
  673. // We ignore errors here because not all graphdrivers support
  674. // xattrs *cough* old versions of AUFS *cough*. However only
  675. // ENOTSUP should be emitted in that case, otherwise we still
  676. // bail.
  677. // EPERM occurs if modifying xattrs is not allowed. This can
  678. // happen when running in userns with restrictions (ChromeOS).
  679. errors = append(errors, err.Error())
  680. continue
  681. }
  682. return err
  683. }
  684. }
  685. if len(errors) > 0 {
  686. logrus.WithFields(logrus.Fields{
  687. "errors": errors,
  688. }).Warn("ignored xattrs in archive: underlying filesystem doesn't support them")
  689. }
  690. // There is no LChmod, so ignore mode for symlink. Also, this
  691. // must happen after chown, as that can modify the file mode
  692. if err := handleLChmod(hdr, path, hdrInfo); err != nil {
  693. return err
  694. }
  695. aTime := hdr.AccessTime
  696. if aTime.Before(hdr.ModTime) {
  697. // Last access time should never be before last modified time.
  698. aTime = hdr.ModTime
  699. }
  700. // system.Chtimes doesn't support a NOFOLLOW flag atm
  701. if hdr.Typeflag == tar.TypeLink {
  702. if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) {
  703. if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil {
  704. return err
  705. }
  706. }
  707. } else if hdr.Typeflag != tar.TypeSymlink {
  708. if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil {
  709. return err
  710. }
  711. } else {
  712. ts := []syscall.Timespec{timeToTimespec(aTime), timeToTimespec(hdr.ModTime)}
  713. if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform {
  714. return err
  715. }
  716. }
  717. return nil
  718. }
  719. // Tar creates an archive from the directory at `path`, and returns it as a
  720. // stream of bytes.
  721. func Tar(path string, compression Compression) (io.ReadCloser, error) {
  722. return TarWithOptions(path, &TarOptions{Compression: compression})
  723. }
  724. // TarWithOptions creates an archive from the directory at `path`, only including files whose relative
  725. // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`.
  726. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) {
  727. // Fix the source path to work with long path names. This is a no-op
  728. // on platforms other than Windows.
  729. srcPath = fixVolumePathPrefix(srcPath)
  730. pm, err := fileutils.NewPatternMatcher(options.ExcludePatterns)
  731. if err != nil {
  732. return nil, err
  733. }
  734. pipeReader, pipeWriter := io.Pipe()
  735. compressWriter, err := CompressStream(pipeWriter, options.Compression)
  736. if err != nil {
  737. return nil, err
  738. }
  739. whiteoutConverter, err := getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS)
  740. if err != nil {
  741. return nil, err
  742. }
  743. go func() {
  744. ta := newTarAppender(
  745. options.IDMap,
  746. compressWriter,
  747. options.ChownOpts,
  748. )
  749. ta.WhiteoutConverter = whiteoutConverter
  750. defer func() {
  751. // Make sure to check the error on Close.
  752. if err := ta.TarWriter.Close(); err != nil {
  753. logrus.Errorf("Can't close tar writer: %s", err)
  754. }
  755. if err := compressWriter.Close(); err != nil {
  756. logrus.Errorf("Can't close compress writer: %s", err)
  757. }
  758. if err := pipeWriter.Close(); err != nil {
  759. logrus.Errorf("Can't close pipe writer: %s", err)
  760. }
  761. }()
  762. // this buffer is needed for the duration of this piped stream
  763. defer pools.BufioWriter32KPool.Put(ta.Buffer)
  764. // In general we log errors here but ignore them because
  765. // during e.g. a diff operation the container can continue
  766. // mutating the filesystem and we can see transient errors
  767. // from this
  768. stat, err := os.Lstat(srcPath)
  769. if err != nil {
  770. return
  771. }
  772. if !stat.IsDir() {
  773. // We can't later join a non-dir with any includes because the
  774. // 'walk' will error if "file/." is stat-ed and "file" is not a
  775. // directory. So, we must split the source path and use the
  776. // basename as the include.
  777. if len(options.IncludeFiles) > 0 {
  778. logrus.Warn("Tar: Can't archive a file with includes")
  779. }
  780. dir, base := SplitPathDirEntry(srcPath)
  781. srcPath = dir
  782. options.IncludeFiles = []string{base}
  783. }
  784. if len(options.IncludeFiles) == 0 {
  785. options.IncludeFiles = []string{"."}
  786. }
  787. seen := make(map[string]bool)
  788. for _, include := range options.IncludeFiles {
  789. rebaseName := options.RebaseNames[include]
  790. var (
  791. parentMatchInfo []fileutils.MatchInfo
  792. parentDirs []string
  793. )
  794. walkRoot := getWalkRoot(srcPath, include)
  795. filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error {
  796. if err != nil {
  797. logrus.Errorf("Tar: Can't stat file %s to tar: %s", srcPath, err)
  798. return nil
  799. }
  800. relFilePath, err := filepath.Rel(srcPath, filePath)
  801. if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) {
  802. // Error getting relative path OR we are looking
  803. // at the source directory path. Skip in both situations.
  804. return nil
  805. }
  806. if options.IncludeSourceDir && include == "." && relFilePath != "." {
  807. relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator))
  808. }
  809. skip := false
  810. // If "include" is an exact match for the current file
  811. // then even if there's an "excludePatterns" pattern that
  812. // matches it, don't skip it. IOW, assume an explicit 'include'
  813. // is asking for that file no matter what - which is true
  814. // for some files, like .dockerignore and Dockerfile (sometimes)
  815. if include != relFilePath {
  816. for len(parentDirs) != 0 {
  817. lastParentDir := parentDirs[len(parentDirs)-1]
  818. if strings.HasPrefix(relFilePath, lastParentDir+string(os.PathSeparator)) {
  819. break
  820. }
  821. parentDirs = parentDirs[:len(parentDirs)-1]
  822. parentMatchInfo = parentMatchInfo[:len(parentMatchInfo)-1]
  823. }
  824. var matchInfo fileutils.MatchInfo
  825. if len(parentMatchInfo) != 0 {
  826. skip, matchInfo, err = pm.MatchesUsingParentResults(relFilePath, parentMatchInfo[len(parentMatchInfo)-1])
  827. } else {
  828. skip, matchInfo, err = pm.MatchesUsingParentResults(relFilePath, fileutils.MatchInfo{})
  829. }
  830. if err != nil {
  831. logrus.Errorf("Error matching %s: %v", relFilePath, err)
  832. return err
  833. }
  834. if f.IsDir() {
  835. parentDirs = append(parentDirs, relFilePath)
  836. parentMatchInfo = append(parentMatchInfo, matchInfo)
  837. }
  838. }
  839. if skip {
  840. // If we want to skip this file and its a directory
  841. // then we should first check to see if there's an
  842. // excludes pattern (e.g. !dir/file) that starts with this
  843. // dir. If so then we can't skip this dir.
  844. // Its not a dir then so we can just return/skip.
  845. if !f.IsDir() {
  846. return nil
  847. }
  848. // No exceptions (!...) in patterns so just skip dir
  849. if !pm.Exclusions() {
  850. return filepath.SkipDir
  851. }
  852. dirSlash := relFilePath + string(filepath.Separator)
  853. for _, pat := range pm.Patterns() {
  854. if !pat.Exclusion() {
  855. continue
  856. }
  857. if strings.HasPrefix(pat.String()+string(filepath.Separator), dirSlash) {
  858. // found a match - so can't skip this dir
  859. return nil
  860. }
  861. }
  862. // No matching exclusion dir so just skip dir
  863. return filepath.SkipDir
  864. }
  865. if seen[relFilePath] {
  866. return nil
  867. }
  868. seen[relFilePath] = true
  869. // Rename the base resource.
  870. if rebaseName != "" {
  871. var replacement string
  872. if rebaseName != string(filepath.Separator) {
  873. // Special case the root directory to replace with an
  874. // empty string instead so that we don't end up with
  875. // double slashes in the paths.
  876. replacement = rebaseName
  877. }
  878. relFilePath = strings.Replace(relFilePath, include, replacement, 1)
  879. }
  880. if err := ta.addTarFile(filePath, relFilePath); err != nil {
  881. logrus.Errorf("Can't add file %s to tar: %s", filePath, err)
  882. // if pipe is broken, stop writing tar stream to it
  883. if err == io.ErrClosedPipe {
  884. return err
  885. }
  886. }
  887. return nil
  888. })
  889. }
  890. }()
  891. return pipeReader, nil
  892. }
  893. // Unpack unpacks the decompressedArchive to dest with options.
  894. func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error {
  895. tr := tar.NewReader(decompressedArchive)
  896. trBuf := pools.BufioReader32KPool.Get(nil)
  897. defer pools.BufioReader32KPool.Put(trBuf)
  898. var dirs []*tar.Header
  899. rootIDs := options.IDMap.RootPair()
  900. whiteoutConverter, err := getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS)
  901. if err != nil {
  902. return err
  903. }
  904. // Iterate through the files in the archive.
  905. loop:
  906. for {
  907. hdr, err := tr.Next()
  908. if err == io.EOF {
  909. // end of tar archive
  910. break
  911. }
  912. if err != nil {
  913. return err
  914. }
  915. // ignore XGlobalHeader early to avoid creating parent directories for them
  916. if hdr.Typeflag == tar.TypeXGlobalHeader {
  917. logrus.Debugf("PAX Global Extended Headers found for %s and ignored", hdr.Name)
  918. continue
  919. }
  920. // Normalize name, for safety and for a simple is-root check
  921. // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows:
  922. // This keeps "..\" as-is, but normalizes "\..\" to "\".
  923. hdr.Name = filepath.Clean(hdr.Name)
  924. for _, exclude := range options.ExcludePatterns {
  925. if strings.HasPrefix(hdr.Name, exclude) {
  926. continue loop
  927. }
  928. }
  929. // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in
  930. // the filepath format for the OS on which the daemon is running. Hence
  931. // the check for a slash-suffix MUST be done in an OS-agnostic way.
  932. if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) {
  933. // Not the root directory, ensure that the parent directory exists
  934. parent := filepath.Dir(hdr.Name)
  935. parentPath := filepath.Join(dest, parent)
  936. if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
  937. err = idtools.MkdirAllAndChownNew(parentPath, 0755, rootIDs)
  938. if err != nil {
  939. return err
  940. }
  941. }
  942. }
  943. // #nosec G305 -- The joined path is checked for path traversal.
  944. path := filepath.Join(dest, hdr.Name)
  945. rel, err := filepath.Rel(dest, path)
  946. if err != nil {
  947. return err
  948. }
  949. if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
  950. return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest))
  951. }
  952. // If path exits we almost always just want to remove and replace it
  953. // The only exception is when it is a directory *and* the file from
  954. // the layer is also a directory. Then we want to merge them (i.e.
  955. // just apply the metadata from the layer).
  956. if fi, err := os.Lstat(path); err == nil {
  957. if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir {
  958. // If NoOverwriteDirNonDir is true then we cannot replace
  959. // an existing directory with a non-directory from the archive.
  960. return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest)
  961. }
  962. if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir {
  963. // If NoOverwriteDirNonDir is true then we cannot replace
  964. // an existing non-directory with a directory from the archive.
  965. return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest)
  966. }
  967. if fi.IsDir() && hdr.Name == "." {
  968. continue
  969. }
  970. if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
  971. if err := os.RemoveAll(path); err != nil {
  972. return err
  973. }
  974. }
  975. }
  976. trBuf.Reset(tr)
  977. if err := remapIDs(options.IDMap, hdr); err != nil {
  978. return err
  979. }
  980. if whiteoutConverter != nil {
  981. writeFile, err := whiteoutConverter.ConvertRead(hdr, path)
  982. if err != nil {
  983. return err
  984. }
  985. if !writeFile {
  986. continue
  987. }
  988. }
  989. if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts, options.InUserNS); err != nil {
  990. return err
  991. }
  992. // Directory mtimes must be handled at the end to avoid further
  993. // file creation in them to modify the directory mtime
  994. if hdr.Typeflag == tar.TypeDir {
  995. dirs = append(dirs, hdr)
  996. }
  997. }
  998. for _, hdr := range dirs {
  999. // #nosec G305 -- The header was checked for path traversal before it was appended to the dirs slice.
  1000. path := filepath.Join(dest, hdr.Name)
  1001. if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil {
  1002. return err
  1003. }
  1004. }
  1005. return nil
  1006. }
  1007. // Untar reads a stream of bytes from `archive`, parses it as a tar archive,
  1008. // and unpacks it into the directory at `dest`.
  1009. // The archive may be compressed with one of the following algorithms:
  1010. // identity (uncompressed), gzip, bzip2, xz.
  1011. //
  1012. // FIXME: specify behavior when target path exists vs. doesn't exist.
  1013. func Untar(tarArchive io.Reader, dest string, options *TarOptions) error {
  1014. return untarHandler(tarArchive, dest, options, true)
  1015. }
  1016. // UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive,
  1017. // and unpacks it into the directory at `dest`.
  1018. // The archive must be an uncompressed stream.
  1019. func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error {
  1020. return untarHandler(tarArchive, dest, options, false)
  1021. }
  1022. // Handler for teasing out the automatic decompression
  1023. func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error {
  1024. if tarArchive == nil {
  1025. return fmt.Errorf("Empty archive")
  1026. }
  1027. dest = filepath.Clean(dest)
  1028. if options == nil {
  1029. options = &TarOptions{}
  1030. }
  1031. if options.ExcludePatterns == nil {
  1032. options.ExcludePatterns = []string{}
  1033. }
  1034. r := tarArchive
  1035. if decompress {
  1036. decompressedArchive, err := DecompressStream(tarArchive)
  1037. if err != nil {
  1038. return err
  1039. }
  1040. defer decompressedArchive.Close()
  1041. r = decompressedArchive
  1042. }
  1043. return Unpack(r, dest, options)
  1044. }
  1045. // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other.
  1046. // If either Tar or Untar fails, TarUntar aborts and returns the error.
  1047. func (archiver *Archiver) TarUntar(src, dst string) error {
  1048. archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed})
  1049. if err != nil {
  1050. return err
  1051. }
  1052. defer archive.Close()
  1053. options := &TarOptions{
  1054. IDMap: archiver.IDMapping,
  1055. }
  1056. return archiver.Untar(archive, dst, options)
  1057. }
  1058. // UntarPath untar a file from path to a destination, src is the source tar file path.
  1059. func (archiver *Archiver) UntarPath(src, dst string) error {
  1060. archive, err := os.Open(src)
  1061. if err != nil {
  1062. return err
  1063. }
  1064. defer archive.Close()
  1065. options := &TarOptions{
  1066. IDMap: archiver.IDMapping,
  1067. }
  1068. return archiver.Untar(archive, dst, options)
  1069. }
  1070. // CopyWithTar creates a tar archive of filesystem path `src`, and
  1071. // unpacks it at filesystem path `dst`.
  1072. // The archive is streamed directly with fixed buffering and no
  1073. // intermediary disk IO.
  1074. func (archiver *Archiver) CopyWithTar(src, dst string) error {
  1075. srcSt, err := os.Stat(src)
  1076. if err != nil {
  1077. return err
  1078. }
  1079. if !srcSt.IsDir() {
  1080. return archiver.CopyFileWithTar(src, dst)
  1081. }
  1082. // if this Archiver is set up with ID mapping we need to create
  1083. // the new destination directory with the remapped root UID/GID pair
  1084. // as owner
  1085. rootIDs := archiver.IDMapping.RootPair()
  1086. // Create dst, copy src's content into it
  1087. if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil {
  1088. return err
  1089. }
  1090. return archiver.TarUntar(src, dst)
  1091. }
  1092. // CopyFileWithTar emulates the behavior of the 'cp' command-line
  1093. // for a single file. It copies a regular file from path `src` to
  1094. // path `dst`, and preserves all its metadata.
  1095. func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) {
  1096. srcSt, err := os.Stat(src)
  1097. if err != nil {
  1098. return err
  1099. }
  1100. if srcSt.IsDir() {
  1101. return fmt.Errorf("Can't copy a directory")
  1102. }
  1103. // Clean up the trailing slash. This must be done in an operating
  1104. // system specific manner.
  1105. if dst[len(dst)-1] == os.PathSeparator {
  1106. dst = filepath.Join(dst, filepath.Base(src))
  1107. }
  1108. // Create the holding directory if necessary
  1109. if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil {
  1110. return err
  1111. }
  1112. r, w := io.Pipe()
  1113. errC := make(chan error, 1)
  1114. go func() {
  1115. defer close(errC)
  1116. errC <- func() error {
  1117. defer w.Close()
  1118. srcF, err := os.Open(src)
  1119. if err != nil {
  1120. return err
  1121. }
  1122. defer srcF.Close()
  1123. hdr, err := FileInfoHeaderNoLookups(srcSt, "")
  1124. if err != nil {
  1125. return err
  1126. }
  1127. hdr.Format = tar.FormatPAX
  1128. hdr.ModTime = hdr.ModTime.Truncate(time.Second)
  1129. hdr.AccessTime = time.Time{}
  1130. hdr.ChangeTime = time.Time{}
  1131. hdr.Name = filepath.Base(dst)
  1132. hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))
  1133. if err := remapIDs(archiver.IDMapping, hdr); err != nil {
  1134. return err
  1135. }
  1136. tw := tar.NewWriter(w)
  1137. defer tw.Close()
  1138. if err := tw.WriteHeader(hdr); err != nil {
  1139. return err
  1140. }
  1141. if _, err := io.Copy(tw, srcF); err != nil {
  1142. return err
  1143. }
  1144. return nil
  1145. }()
  1146. }()
  1147. defer func() {
  1148. if er := <-errC; err == nil && er != nil {
  1149. err = er
  1150. }
  1151. }()
  1152. err = archiver.Untar(r, filepath.Dir(dst), nil)
  1153. if err != nil {
  1154. r.CloseWithError(err)
  1155. }
  1156. return err
  1157. }
  1158. // IdentityMapping returns the IdentityMapping of the archiver.
  1159. func (archiver *Archiver) IdentityMapping() idtools.IdentityMapping {
  1160. return archiver.IDMapping
  1161. }
  1162. func remapIDs(idMapping idtools.IdentityMapping, hdr *tar.Header) error {
  1163. ids, err := idMapping.ToHost(idtools.Identity{UID: hdr.Uid, GID: hdr.Gid})
  1164. hdr.Uid, hdr.Gid = ids.UID, ids.GID
  1165. return err
  1166. }
  1167. // cmdStream executes a command, and returns its stdout as a stream.
  1168. // If the command fails to run or doesn't complete successfully, an error
  1169. // will be returned, including anything written on stderr.
  1170. func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) {
  1171. cmd.Stdin = input
  1172. pipeR, pipeW := io.Pipe()
  1173. cmd.Stdout = pipeW
  1174. var errBuf bytes.Buffer
  1175. cmd.Stderr = &errBuf
  1176. // Run the command and return the pipe
  1177. if err := cmd.Start(); err != nil {
  1178. return nil, err
  1179. }
  1180. // Ensure the command has exited before we clean anything up
  1181. done := make(chan struct{})
  1182. // Copy stdout to the returned pipe
  1183. go func() {
  1184. if err := cmd.Wait(); err != nil {
  1185. pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String()))
  1186. } else {
  1187. pipeW.Close()
  1188. }
  1189. close(done)
  1190. }()
  1191. return ioutils.NewReadCloserWrapper(pipeR, func() error {
  1192. // Close pipeR, and then wait for the command to complete before returning. We have to close pipeR first, as
  1193. // cmd.Wait waits for any non-file stdout/stderr/stdin to close.
  1194. err := pipeR.Close()
  1195. <-done
  1196. return err
  1197. }), nil
  1198. }
  1199. // NewTempArchive reads the content of src into a temporary file, and returns the contents
  1200. // of that file as an archive. The archive can only be read once - as soon as reading completes,
  1201. // the file will be deleted.
  1202. func NewTempArchive(src io.Reader, dir string) (*TempArchive, error) {
  1203. f, err := os.CreateTemp(dir, "")
  1204. if err != nil {
  1205. return nil, err
  1206. }
  1207. if _, err := io.Copy(f, src); err != nil {
  1208. return nil, err
  1209. }
  1210. if _, err := f.Seek(0, 0); err != nil {
  1211. return nil, err
  1212. }
  1213. st, err := f.Stat()
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. size := st.Size()
  1218. return &TempArchive{File: f, Size: size}, nil
  1219. }
  1220. // TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes,
  1221. // the file will be deleted.
  1222. type TempArchive struct {
  1223. *os.File
  1224. Size int64 // Pre-computed from Stat().Size() as a convenience
  1225. read int64
  1226. closed bool
  1227. }
  1228. // Close closes the underlying file if it's still open, or does a no-op
  1229. // to allow callers to try to close the TempArchive multiple times safely.
  1230. func (archive *TempArchive) Close() error {
  1231. if archive.closed {
  1232. return nil
  1233. }
  1234. archive.closed = true
  1235. return archive.File.Close()
  1236. }
  1237. func (archive *TempArchive) Read(data []byte) (int, error) {
  1238. n, err := archive.File.Read(data)
  1239. archive.read += int64(n)
  1240. if err != nil || archive.read == archive.Size {
  1241. archive.Close()
  1242. os.Remove(archive.File.Name())
  1243. }
  1244. return n, err
  1245. }