forked from apple/containerization
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunCommand.swift
More file actions
311 lines (263 loc) · 10.9 KB
/
RunCommand.swift
File metadata and controls
311 lines (263 loc) · 10.9 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//===----------------------------------------------------------------------===//
// Copyright © 2025 Apple Inc. and the Containerization project authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//
import ArgumentParser
import ContainerizationOCI
import Foundation
import LCShim
import Logging
import Musl
#if canImport(Musl)
import Musl
private let _ptsname = Musl.ptsname
#elseif canImport(Glibc)
import Glibc
private let _ptsname = Glibc.ptsname
#endif
struct RunCommand: ParsableCommand {
static let configuration = CommandConfiguration(
commandName: "run",
abstract: "Run a container"
)
@Option(name: .long, help: "path to an OCI bundle")
var bundlePath: String
mutating func run() throws {
LoggingSystem.bootstrap(App.standardError)
let log = Logger(label: "vmexec")
let bundle = try ContainerizationOCI.Bundle.load(path: URL(filePath: bundlePath))
let ociSpec = try bundle.loadConfig()
try execInNamespace(spec: ociSpec, log: log)
}
private func childRootSetup(rootfs: ContainerizationOCI.Root, mounts: [ContainerizationOCI.Mount], log: Logger) throws {
// setup rootfs
try prepareRoot(rootfs: rootfs.path)
try mountRootfs(rootfs: rootfs.path, mounts: mounts)
try setDevSymlinks(rootfs: rootfs.path)
try pivotRoot(rootfs: rootfs.path)
try reOpenDevNull()
}
private func execInNamespace(spec: ContainerizationOCI.Spec, log: Logger) throws {
guard let process = spec.process else {
fatalError("no process configuration found in runtime spec")
}
guard let root = spec.root else {
fatalError("no root found in runtime spec")
}
let syncfd = FileHandle(fileDescriptor: 3)
if fcntl(3, F_SETFD, FD_CLOEXEC) == -1 {
throw App.Errno(stage: "cloexec(syncfd)")
}
guard unshare(CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUTS) == 0 else {
throw App.Errno(stage: "unshare(pid|mnt|uts)")
}
let childPipe = Pipe()
try childPipe.setCloexec()
var hostFd: Int32 = -1
let processID = fork()
guard processID != -1 else {
try? childPipe.fileHandleForReading.close()
try? childPipe.fileHandleForWriting.close()
try? syncfd.close()
throw App.Errno(stage: "fork")
}
if processID == 0 { // child
try childPipe.fileHandleForReading.close()
try syncfd.close()
guard unshare(CLONE_NEWCGROUP) == 0 else {
throw App.Errno(stage: "unshare(cgroup)")
}
guard setsid() != -1 else {
throw App.Errno(stage: "setsid()")
}
try childRootSetup(rootfs: root, mounts: spec.mounts, log: log)
if process.terminal {
let containerMount = ContainerMount(rootfs: root.path, mounts: spec.mounts)
try containerMount.configureConsole()
var containerFd: Int32 = 0
var ws = winsize(ws_row: 40, ws_col: 120, ws_xpixel: 0, ws_ypixel: 0)
guard openpty(&hostFd, &containerFd, nil, nil, &ws) == 0 else {
throw App.Errno(stage: "openpty()")
}
guard dup3(containerFd, 0, 0) != -1 else {
throw App.Errno(stage: "dup3(slave->stdin)")
}
guard dup3(containerFd, 1, 0) != -1 else {
throw App.Errno(stage: "dup3(slave->stdout)")
}
guard dup3(containerFd, 2, 0) != -1 else {
throw App.Errno(stage: "dup3(slave->stderr)")
}
_ = close(containerFd)
guard ioctl(0, UInt(TIOCSCTTY), 0) != -1 else {
throw App.Errno(stage: "setctty()")
}
if let cPtr = _ptsname(hostFd) {
mountConsole(path: String(cString: cPtr))
}
}
if !spec.hostname.isEmpty {
let errCode = spec.hostname.withCString { ptr in
Musl.sethostname(ptr, spec.hostname.count)
}
guard errCode == 0 else {
throw App.Errno(stage: "sethostname()")
}
}
var fdCopy = hostFd
var fdData = Data(bytes: &fdCopy, count: MemoryLayout.size(ofValue: fdCopy))
try childPipe.fileHandleForWriting.write(contentsOf: fdData)
try childPipe.fileHandleForWriting.close()
var ackBuf: UInt8 = 0
_ = read(4, &ackBuf, 1)
close(4)
close(hostFd)
// Apply O_CLOEXEC to all file descriptors except stdio.
// This ensures that all unwanted fds we may have accidentally
// inherited are marked close-on-exec so they stay out of the
// container.
try App.applyCloseExecOnFDs()
try App.setRLimits(rlimits: process.rlimits)
// Change stdio to be owned by the requested user.
try App.fixStdioPerms(user: process.user)
// Set uid, gid, and supplementary groups.
try App.setPermissions(user: process.user)
try App.exec(process: process)
} else { // parent process
try childPipe.fileHandleForWriting.close()
// wait until the pipe is closed then carry on.
_ = try childPipe.fileHandleForReading.readToEnd()
try childPipe.fileHandleForReading.close()
// send our child's pid and the host fd to our parent before we exit.
var payload = [Int32(processID), hostFd]
let data = Data(bytes: &payload, count: MemoryLayout<Int32>.size * 2)
try syncfd.write(contentsOf: data)
try syncfd.close()
}
}
private func mountRootfs(rootfs: String, mounts: [ContainerizationOCI.Mount]) throws {
let containerMount = ContainerMount(rootfs: rootfs, mounts: mounts)
try containerMount.mountToRootfs()
}
private func prepareRoot(rootfs: String) throws {
guard mount("", "/", "", UInt(MS_SLAVE | MS_REC), nil) == 0 else {
throw App.Errno(stage: "mount(slave|rec)")
}
guard mount(rootfs, rootfs, "bind", UInt(MS_BIND | MS_REC), nil) == 0 else {
throw App.Errno(stage: "mount(bind|rec)")
}
}
private func setDevSymlinks(rootfs: String) throws {
let links: [(src: String, dst: String)] = [
("/proc/self/fd", "/dev/fd"),
("/proc/self/fd/0", "/dev/stdin"),
("/proc/self/fd/1", "/dev/stdout"),
("/proc/self/fd/2", "/dev/stderr"),
]
let rootfsURL = URL(fileURLWithPath: rootfs)
for (src, dst) in links {
let dest = rootfsURL.appendingPathComponent(dst)
guard symlink(src, dest.path) == 0 else {
if errno == EEXIST {
continue
}
throw App.Errno(stage: "symlink()")
}
}
}
private func reOpenDevNull() throws {
let file = open("/dev/null", O_RDWR)
guard file != -1 else {
throw App.Errno(stage: "open(/dev/null)")
}
defer { close(file) }
var devNullStat = stat()
try withUnsafeMutablePointer(to: &devNullStat) { pointer in
guard fstat(file, pointer) == 0 else {
throw App.Errno(stage: "fstat(/dev/null)")
}
}
for fd: Int32 in 0...2 {
var fdStat = stat()
try withUnsafeMutablePointer(to: &fdStat) { pointer in
guard fstat(fd, pointer) == 0 else {
throw App.Errno(stage: "fstat(fd)")
}
}
if fdStat.st_rdev == devNullStat.st_rdev {
guard dup3(file, fd, 0) != -1 else {
throw App.Errno(stage: "dup3(null)")
}
}
}
}
/// Pivots the rootfs of the calling process in the namespace to the provided
/// rootfs in the argument.
///
/// The pivot_root(".", ".") and unmount old root approach is exactly the same
/// as runc's pivot root implementation in:
/// https://github.com/opencontainers/runc/blob/main/libcontainer/rootfs_linux.go
private func pivotRoot(rootfs: String) throws {
let oldRoot = open("/", O_RDONLY | O_DIRECTORY)
if oldRoot <= 0 {
throw App.Errno(stage: "open(oldroot)")
}
defer { close(oldRoot) }
let newRoot = open(rootfs, O_RDONLY | O_DIRECTORY)
if newRoot <= 0 {
throw App.Errno(stage: "open(newroot)")
}
defer { close(newRoot) }
// change cwd to the new root
guard fchdir(newRoot) == 0 else {
throw App.Errno(stage: "fchdir(newroot)")
}
guard CZ_pivot_root(toCString("."), toCString(".")) == 0 else {
throw App.Errno(stage: "pivot_root()")
}
// change cwd to the old root
guard fchdir(oldRoot) == 0 else {
throw App.Errno(stage: "fchdir(oldroot)")
}
// mount old root rslave so that unmount doesn't propagate back to outside
// the namespace
guard mount("", ".", "", UInt(MS_SLAVE | MS_REC), nil) == 0 else {
throw App.Errno(stage: "mount(., slave|rec)")
}
// unmount old root
guard umount2(".", Int32(MNT_DETACH)) == 0 else {
throw App.Errno(stage: "umount(.)")
}
// switch cwd to the new root
guard chdir("/") == 0 else {
throw App.Errno(stage: "chdir(/)")
}
}
private func toCString(_ str: String) -> UnsafeMutablePointer<CChar>? {
let cString = str.utf8CString
let cStringCopy = UnsafeMutableBufferPointer<CChar>.allocate(capacity: cString.count)
_ = cStringCopy.initialize(from: cString)
return UnsafeMutablePointer(cStringCopy.baseAddress)
}
private func mountConsole(path: String) {
let console = "/dev/console"
if access(console, F_OK) != 0 {
let fd = open(console, O_RDWR | O_CREAT, mode_t(UInt16(0o600)))
if fd != -1 {
close(fd)
}
}
_ = mount(path, console, "", UInt(MS_BIND), nil)
}
}