@@ -25,6 +25,7 @@ import (
2525 "os"
2626 "os/exec"
2727 "path/filepath"
28+ "slices"
2829 "strconv"
2930 "strings"
3031
@@ -60,6 +61,134 @@ var (
6061 ErrCannotCopyDirToFile = errors .New ("cannot copy a directory to a file" ) // cp SOMEDIR foo:/etc/issue
6162)
6263
64+ const (
65+ // procSelfFd is where a process finds its own file descriptors by number.
66+ procSelfFd = "/proc/self/fd/"
67+ // pinnedDirArg is how the tar process refers to the directory handed to it as the first entry of ExtraFiles,
68+ // which becomes its fd 3.
69+ pinnedDirArg = procSelfFd + "3"
70+ )
71+
72+ // openHostMount opens the container mount whose host path is mountRoot as an os.Root, and returns the path of
73+ // relativePath inside it. A mount of a single file is opened on its parent directory.
74+ func openHostMount (mountRoot , relativePath string ) (* os.Root , string , error ) {
75+ st , err := os .Stat (mountRoot )
76+ if err != nil {
77+ return nil , "" , err
78+ }
79+ if ! st .IsDir () {
80+ relativePath = filepath .Join (filepath .Base (mountRoot ), relativePath )
81+ mountRoot = filepath .Dir (mountRoot )
82+ }
83+ root , err := os .OpenRoot (mountRoot )
84+ if err != nil {
85+ return nil , "" , err
86+ }
87+ return root , relativePath , nil
88+ }
89+
90+ // openMountRoot opens the container mount that holds dest as an os.Root, and returns the path of dest inside it.
91+ // A mount of a single file is opened on its parent directory on the host.
92+ //
93+ // liveRoot is the root of the running container (/proc/<pid>/root), or "" when the container is not running.
94+ // The host path of a mount can be reachable from the container through another mount, so that a process in the
95+ // container can rename it and put a symlink in its place. In a running container, a directory mount is therefore
96+ // opened the way the container sees it, through liveRoot, and for a file mount the host file is checked to still
97+ // be the file mounted in the container.
98+ func openMountRoot (dest * pathSpecifier , liveRoot string ) (* os.Root , string , error ) {
99+ if ! filepath .IsAbs (dest .mountRoot ) {
100+ return nil , "" , fmt .Errorf ("cannot copy into mount with non-path source %q" , dest .mountRoot )
101+ }
102+ rel := dest .relativePath
103+ if rel == "" {
104+ rel = "."
105+ }
106+ if liveRoot == "" {
107+ return openHostMount (dest .mountRoot , rel )
108+ }
109+
110+ container , err := os .OpenRoot (liveRoot )
111+ if err != nil {
112+ return nil , "" , err
113+ }
114+ mountPath , err := filepath .Rel ("/" , dest .mountPath )
115+ if err != nil {
116+ container .Close ()
117+ return nil , "" , err
118+ }
119+ if mountPath == "." {
120+ return container , rel , nil
121+ }
122+ defer container .Close ()
123+
124+ mounted , err := container .Stat (mountPath )
125+ if err != nil {
126+ return nil , "" , err
127+ }
128+ if mounted .IsDir () {
129+ root , err := container .OpenRoot (mountPath )
130+ if err != nil {
131+ return nil , "" , err
132+ }
133+ return root , rel , nil
134+ }
135+
136+ root , rel , err := openHostMount (dest .mountRoot , rel )
137+ if err != nil {
138+ return nil , "" , err
139+ }
140+ source , err := root .Lstat (filepath .Base (dest .mountRoot ))
141+ if err != nil || ! os .SameFile (source , mounted ) {
142+ root .Close ()
143+ return nil , "" , errors .Join (fmt .Errorf ("source of mount %q is not the file mounted in the container" , dest .mountPath ), err )
144+ }
145+ return root , rel , nil
146+ }
147+
148+ // openExtractDir prepares a copy into the container: it creates the destination when it does not exist, and returns
149+ // a handle on the directory tar extracts into, which is the destination itself if intoDest, and its parent otherwise.
150+ // A process in the container can replace any component of the destination with a symlink after it has been
151+ // resolved, and absolute symlinks under /proc/<pid>/root are followed against the host root. Both operations go
152+ // through an os.Root on the container mount so that they stay inside it, and tar gets the handle rather than a path.
153+ // liveRoot is as for openMountRoot.
154+ func openExtractDir (dest * pathSpecifier , intoDest bool , liveRoot string ) (* os.File , error ) {
155+ root , rel , err := openMountRoot (dest , liveRoot )
156+ if err != nil {
157+ return nil , errors .Join (ErrFilesystem , err )
158+ }
159+ defer root .Close ()
160+
161+ // XXX FIXME: this seems wrong. What about ownership? We could be doing that inside a container
162+ if ! dest .exists {
163+ if err = root .Mkdir (rel , 0o755 ); err != nil {
164+ return nil , errors .Join (ErrFilesystem , err )
165+ }
166+ }
167+
168+ if ! intoDest {
169+ rel = filepath .Dir (rel )
170+ }
171+ dir , err := root .OpenFile (rel , unix .O_PATH | unix .O_DIRECTORY , 0 )
172+ if err != nil {
173+ return nil , errors .Join (ErrFilesystem , err )
174+ }
175+ return dir , nil
176+ }
177+
178+ // tarExtractCmd returns the command running tarX, a tar -x command line to which it appends -C and -f, so that tar
179+ // extracts the archive read from stdin into dir. If pinned (the handle from openExtractDir) is not nil, tar receives
180+ // it as its fd 3 and extracts there instead of resolving dir again.
181+ func tarExtractCmd (ctx context.Context , tarX []string , dir string , pinned * os.File ) * exec.Cmd {
182+ var extraFiles []* os.File
183+ if pinned != nil {
184+ dir = pinnedDirArg
185+ extraFiles = []* os.File {pinned }
186+ }
187+ cmd := exec .CommandContext (ctx , tarX [0 ], append (slices .Clone (tarX [1 :]), "-C" , dir , "-f" , "-" )... )
188+ cmd .ExtraFiles = extraFiles
189+ return cmd
190+ }
191+
63192// getRoot will tentatively return the root of the container on the host (/proc/pid/root), along with the pid,
64193// (eg: doable when the container is running)
65194func getRoot (ctx context.Context , container containerd.Container ) (string , int , error ) {
@@ -213,8 +342,21 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
213342 return ErrDestinationDirMustExist
214343 }
215344
216- // XXX FIXME: this seems wrong. What about ownership? We could be doing that inside a container
217- if ! destinationSpec .exists {
345+ // tar extracts into the destination itself, or into its parent when copying a file to a new name
346+ intoDest := sourceSpec .isADir || destinationSpec .endsWithSeparator || (destinationSpec .exists && destinationSpec .isADir )
347+
348+ var tarXDirFile * os.File
349+ if ! options .Container2Host {
350+ liveRoot := ""
351+ if pid != 0 {
352+ liveRoot = root
353+ }
354+ tarXDirFile , err = openExtractDir (destinationSpec , intoDest , liveRoot )
355+ if err != nil {
356+ return err
357+ }
358+ defer tarXDirFile .Close ()
359+ } else if ! destinationSpec .exists {
218360 if err = os .Mkdir (destinationSpec .resolvedPath , 0o755 ); err != nil {
219361 return errors .Join (ErrFilesystem , err )
220362 }
@@ -272,7 +414,7 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
272414 }
273415
274416 tarXDir := destinationSpec .resolvedPath
275- if ! sourceSpec . isADir && ! destinationSpec . endsWithSeparator && ! ( destinationSpec . exists && destinationSpec . isADir ) {
417+ if ! intoDest {
276418 tarXDir = filepath .Dir (destinationSpec .resolvedPath )
277419 }
278420 var tarX []string
@@ -283,11 +425,15 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
283425 if options .Container2Host && isGNUTar {
284426 tarX = append (tarX , "--no-same-owner" )
285427 }
286- tarX = append (tarX , "-C" , tarXDir , "-f" , "-" )
287428
288429 // tar opens the -C directory by itself and fails with an unhelpful error when the directory
289430 // is not accessible, so detect this beforehand.
290- if accessErr := unix .Access (tarXDir , unix .X_OK ); errors .Is (accessErr , unix .EACCES ) {
431+ accessPath := tarXDir
432+ if tarXDirFile != nil {
433+ // this process has the handle under another number than tar
434+ accessPath = procSelfFd + strconv .Itoa (int (tarXDirFile .Fd ()))
435+ }
436+ if accessErr := unix .Access (accessPath , unix .X_OK ); errors .Is (accessErr , unix .EACCES ) {
291437 return ErrTargetIsReadOnly
292438 }
293439 }
@@ -308,7 +454,12 @@ func CopyFiles(ctx context.Context, client *containerd.Client, container contain
308454 tarCCmd .Stdin = nil
309455 tarCCmd .Stderr = os .Stderr
310456
311- tarXCmd := exec .CommandContext (ctx , tarX [0 ], tarX [1 :]... )
457+ var tarXCmd * exec.Cmd
458+ if destinationSpec .toStdout {
459+ tarXCmd = exec .CommandContext (ctx , tarX [0 ], tarX [1 :]... )
460+ } else {
461+ tarXCmd = tarExtractCmd (ctx , tarX , tarXDir , tarXDirFile )
462+ }
312463 if sourceSpec .fromStdin {
313464 // Reading from tar should pipe stdin into dst
314465 tarXCmd .Stdin = bufio .NewReader (os .Stdin )
0 commit comments