forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 1
/
switch_root_linux.go
233 lines (204 loc) · 6.77 KB
/
switch_root_linux.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright 2012-2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux
package mount
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
// getDev returns the device (as returned by the FSTAT syscall) for the given file descriptor.
func getDev(fd int) (dev uint64, err error) {
var stat unix.Stat_t
if err := unix.Fstat(fd, &stat); err != nil {
return 0, err
}
return stat.Dev, nil
}
// RecursiveDelete deletes a directory identified by `fd` and everything in it.
//
// This function allows deleting directories no longer referenceable by
// any file name. This function does not descend into mounts.
func RecursiveDelete(fd int) error {
parentDev, err := getDev(fd)
if err != nil {
return err
}
// The file descriptor is already open, but allocating a os.File
// here makes reading the files in the dir so much nicer.
dir := os.NewFile(uintptr(fd), "__ignored__")
defer dir.Close()
names, err := dir.Readdirnames(-1)
if err != nil {
return err
}
for _, name := range names {
// Loop here, but handle loop in separate function to make defer work as expected.
if err := recusiveDeleteInner(fd, parentDev, name); err != nil {
return err
}
}
return nil
}
// recusiveDeleteInner is called from recursiveDelete and either deletes
// or recurses into the given file or directory
//
// There should be no need to call this function directly.
func recusiveDeleteInner(parentFd int, parentDev uint64, childName string) error {
// O_DIRECTORY and O_NOFOLLOW make this open fail for all files and all symlinks (even when pointing to a dir).
// We need to filter out symlinks because getDev later follows them.
childFd, err := unix.Openat(parentFd, childName, unix.O_DIRECTORY|unix.O_NOFOLLOW, unix.O_RDWR)
if err != nil {
// childName points to either a file or a symlink, delete in any case.
if err := unix.Unlinkat(parentFd, childName, 0); err != nil {
return err
}
} else {
// Open succeeded, which means childName points to a real directory.
defer unix.Close(childFd)
// Don't descent into other file systems.
if childFdDev, err := getDev(childFd); err != nil {
return err
} else if childFdDev != parentDev {
// This means continue in recursiveDelete.
return nil
}
if err := RecursiveDelete(childFd); err != nil {
return err
}
// Back from recursion, the directory is now empty, delete.
if err := unix.Unlinkat(parentFd, childName, unix.AT_REMOVEDIR); err != nil {
return err
}
}
return nil
}
// execCommand execs into the given command.
//
// In order to preserve whatever PID this program is running with,
// the implementation does an actual EXEC syscall without forking.
func execCommand(path string) error {
return unix.Exec(path, []string{path}, []string{})
}
// DirIsEmpty returns true if the directory with the given path is empty.
func DirIsEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
if _, err := f.Readdirnames(1); err == io.EOF {
return true, nil
}
return false, err
}
// MoveMount moves a mount from oldPath to newPath.
//
// This function is just a wrapper around the MOUNT syscall with the
// MOVE flag supplied.
func MoveMount(oldPath string, newPath string) error {
return unix.Mount(oldPath, newPath, "", unix.MS_MOVE, "")
}
// AddSpecialMounts moves the 'special' mounts to the given target path
//
// 'special' in this context refers to the following non-blockdevice backed
// mounts that are almost always used: /dev, /proc, /sys, and /run.
// This function will create the target directories, if necessary.
// If the target directories already exist, they must be empty.
// This function skips missing mounts.
func AddSpecialMounts(newRoot string) error {
var mounts = []string{"/dev", "/proc", "/sys", "/run"}
for _, mount := range mounts {
path := filepath.Join(newRoot, mount)
// Skip all mounting if the directory does not exist.
if _, err := os.Stat(mount); os.IsNotExist(err) {
log.Printf("switch_root: Skipping %q as the dir does not exist", mount)
continue
} else if err != nil {
return err
}
// Also skip if not currently a mount point
if same, err := SameFilesystem("/", mount); err != nil {
return err
} else if same {
log.Printf("switch_root: Skipping %q as it is not a mount", mount)
continue
}
// Make sure the target dir exists.
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
if err := MoveMount(mount, path); err != nil {
return err
}
}
return nil
}
// SameFilesystem returns true if both paths reside in the same filesystem.
// This is achieved by comparing Stat_t.Dev, which contains the fs device's
// major/minor numbers.
func SameFilesystem(path1, path2 string) (bool, error) {
var stat1, stat2 unix.Stat_t
if err := unix.Stat(path1, &stat1); err != nil {
return false, err
}
if err := unix.Stat(path2, &stat2); err != nil {
return false, err
}
return stat1.Dev == stat2.Dev, nil
}
// SwitchRoot moves special mounts (dev, proc, sys, run) to the new directory,
// then does a chroot, moves the root mount to the new directory and finally
// DELETES EVERYTHING in the old root and execs the given init.
func SwitchRoot(newRoot string, init string) error {
err := NewRoot(newRoot)
if err != nil {
return err
}
return ExecInit(init)
}
// NewRoot is the "first half" of SwitchRoot - that is, it creates special mounts
// in newRoot, chroot's there, and RECURSIVELY DELETES everything in the old root.
func NewRoot(newRoot string) error {
log.Printf("switch_root: moving mounts")
if err := AddSpecialMounts(newRoot); err != nil {
return fmt.Errorf("switch_root: moving mounts failed %v", err)
}
log.Printf("switch_root: Changing directory")
if err := unix.Chdir(newRoot); err != nil {
return fmt.Errorf("switch_root: failed change directory to new_root %v", err)
}
// Open "/" now, we need the file descriptor later.
oldRoot, err := os.Open("/")
if err != nil {
return err
}
defer oldRoot.Close()
log.Printf("switch_root: Moving /")
if err := MoveMount(newRoot, "/"); err != nil {
return err
}
log.Printf("switch_root: Changing root!")
if err := unix.Chroot("."); err != nil {
return fmt.Errorf("switch_root: fatal chroot error %v", err)
}
log.Printf("switch_root: Deleting old /")
if err := RecursiveDelete(int(oldRoot.Fd())); err != nil {
return err
}
return nil
}
// Function ExecInit is generally only useful as part of SwitchRoot or similar.
// It exec's the given binary in place of the current binary, necessary so that
// the new binary can be pid 1.
func ExecInit(init string) error {
log.Printf("switch_root: executing init")
if err := execCommand(init); err != nil {
return fmt.Errorf("switch_root: exec failed %v", err)
}
return nil
}