-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrootfs.go
107 lines (90 loc) · 2.33 KB
/
rootfs.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
func pivot_root(newroot string) error {
// pivot_root(2) - putold must be under or underneath newroot.
putold := filepath.Join(newroot, "/.pivot_root")
// bind mounting the newroot to itself - this is a slight hack
// to work around the pivot_root requirement (the newroot must
// be a path to a mount point `pivot_root(2)`)
if err := unix.Mount(
newroot,
newroot,
"",
unix.MS_BIND|unix.MS_REC,
"",
); err != nil {
return err
}
// creating putold directory for the old rootdir to be pivoted to.
// This directory is created at `/.pivot_root` to satisfy the
// pivot_mount(2) rule that requires the putold directory to be
// underneath the newroot directory.
if err := os.MkdirAll(putold, 0700); err != nil {
return err
}
// calling pivot_root
if err := unix.PivotRoot(newroot, putold); err != nil {
return err
}
// changing the directory into the new root directory. This is done
// because pivot_root(2) only changes the root/current workig dirs of
// each process or thread in the same mountspace to new_root if they
// point to the old root dir. However, It doesn't change the caller's
// current working directory (unless it's in the old root dir), thus it
// should be followed with a chdir("/") call.
if err := os.Chdir("/"); err != nil {
return err
}
// unmounting putold, which now lives at /.pivot
putold = "/.pivot_root"
if err := unix.Unmount(putold, unix.MNT_DETACH); err != nil {
return err
}
// removing putold
if err := os.RemoveAll(putold); err != nil {
return err
}
return nil
}
// mountProc mounts the proc fs in the new root dir
func mountProc(newroot string) error {
source := "proc"
target := filepath.Join(newroot, "/proc")
fstype := "proc"
flags := 0
data := ""
os.MkdirAll(target, 0755)
if err := unix.Mount(
source,
target,
fstype,
uintptr(flags),
data,
); err != nil {
return err
}
return nil
}
// mountSys mounts the sysfs in the new root dir
func mountSys(newroot string) error {
source := ""
target := filepath.Join(newroot, "/sys")
fstype := "sysfs"
flags := unix.MS_NOSUID | unix.MS_NOEXEC | unix.MS_NODEV | unix.MS_RDONLY
data := ""
os.MkdirAll(target, 0755)
if err := unix.Mount(
source,
target,
fstype,
uintptr(flags),
data,
); err != nil {
return err
}
return nil
}