summaryrefslogtreecommitdiff
path: root/libpod/container_copy_linux.go
blob: 3b029f08f6504fd577c1f16907575a84b8f580e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package libpod

import (
	"fmt"
	"os"
	"runtime"

	"github.com/containers/podman/v4/libpod/define"
	"golang.org/x/sys/unix"
)

// joinMountAndExec executes the specified function `f` inside the container's
// mount and PID namespace.  That allows for having the exact view on the
// container's file system.
//
// Note, if the container is not running `f()` will be executed as is.
func (c *Container) joinMountAndExec(f func() error) error {
	if c.state.State != define.ContainerStateRunning {
		return f()
	}

	// Container's running, so we need to execute `f()` inside its mount NS.
	errChan := make(chan error)
	go func() {
		runtime.LockOSThread()

		// Join the mount and PID NS of the container.
		getFD := func(ns LinuxNS) (*os.File, error) {
			nsPath, err := c.namespacePath(ns)
			if err != nil {
				return nil, err
			}
			return os.Open(nsPath)
		}

		mountFD, err := getFD(MountNS)
		if err != nil {
			errChan <- err
			return
		}
		defer mountFD.Close()

		inHostPidNS, err := c.inHostPidNS()
		if err != nil {
			errChan <- fmt.Errorf("checking inHostPidNS: %w", err)
			return
		}
		var pidFD *os.File
		if !inHostPidNS {
			pidFD, err = getFD(PIDNS)
			if err != nil {
				errChan <- err
				return
			}
			defer pidFD.Close()
		}

		if err := unix.Unshare(unix.CLONE_NEWNS); err != nil {
			errChan <- err
			return
		}

		if pidFD != nil {
			if err := unix.Setns(int(pidFD.Fd()), unix.CLONE_NEWPID); err != nil {
				errChan <- err
				return
			}
		}
		if err := unix.Setns(int(mountFD.Fd()), unix.CLONE_NEWNS); err != nil {
			errChan <- err
			return
		}

		// Last but not least, execute the workload.
		errChan <- f()
	}()
	return <-errChan
}

func (c *Container) resolveCopyTarget(mountPoint string, containerPath string) (string, string, error) {
	// If the container is running, we will execute the copy
	// inside the container's mount namespace so we return a path
	// relative to the container's root.
	if c.state.State == define.ContainerStateRunning {
		return "/", c.pathAbs(containerPath), nil
	}
	return c.resolvePath(mountPoint, containerPath)
}