summaryrefslogtreecommitdiffstats
path: root/src/runner/container/mod.rs
blob: dbfa92929f6bf1e3bb0bcd6b8a4548b029e4302f (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
mod init;
mod run;
mod spec;
mod tar;

use std::process;

use ipc_channel::ipc;
use nix::{
	sched::CloneFlags,
	sys::{signal, stat},
	unistd,
};
use serde::{Deserialize, Serialize};

use crate::{
	runner, unshare,
	util::{clone, error::*, ipc::CheckDisconnect},
};

#[derive(Debug, Deserialize, Serialize)]
struct Request(runner::Task, ipc::IpcSender<Result<runner::TaskOutput>>);

fn runner(idmap_finished: ipc::IpcReceiver<()>, channel: ipc::IpcReceiver<Request>) -> ! {
	idmap_finished
		.recv()
		.check_disconnect()
		.expect("IPC recv() error")
		.expect("Unexpected IPC message");

	unistd::setgroups(&[]).expect("setgroups()");

	stat::umask(stat::Mode::from_bits_truncate(0o022));

	init::init_runner().unwrap();

	unsafe { signal::signal(signal::Signal::SIGCHLD, signal::SigHandler::SigIgn) }.unwrap();

	while let Ok(request) = channel.recv() {
		match unsafe { unistd::fork() }.expect("fork()") {
			unistd::ForkResult::Parent { .. } => {}
			unistd::ForkResult::Child => {
				unsafe { signal::signal(signal::Signal::SIGCHLD, signal::SigHandler::SigDfl) }
					.unwrap();

				let Request(task, reply_sender) = request;
				let result = run::handle_task(task);
				reply_sender.send(result).expect("IPC send() failed");
				process::exit(0);
			}
		}
	}

	process::exit(0);
}

pub struct ContainerRunner {
	channel: ipc::IpcSender<Request>,
}

impl ContainerRunner {
	/// Creates a new container runner
	///
	/// Unsafe: Do not call in multithreaded processes
	pub unsafe fn new() -> Result<Self> {
		init::preinit_runner()?;

		let (tx, rx) = ipc::channel().expect("IPC channel creation failed");
		let (idmap_finished_tx, idmap_finished_rx) =
			ipc::channel().expect("IPC channel creation failed");

		let pid = match clone::clone(CloneFlags::CLONE_NEWUSER | CloneFlags::CLONE_NEWNS)
			.expect("clone()")
		{
			unistd::ForkResult::Parent { child } => {
				drop(rx);
				drop(idmap_finished_rx);
				child
			}
			unistd::ForkResult::Child => {
				drop(tx);
				drop(idmap_finished_tx);
				runner(idmap_finished_rx, rx);
				/* Not reached */
			}
		};

		unshare::idmap(pid)?;

		drop(idmap_finished_tx);

		Ok(ContainerRunner { channel: tx })
	}
}

impl super::Runner for ContainerRunner {
	fn run(&self, task: &runner::Task) -> Result<runner::TaskOutput> {
		let (reply_tx, reply_rx) = ipc::channel().expect("IPC channel creation failed");

		self.channel
			.send(Request(task.clone(), reply_tx))
			.expect("ContainerRunner task submission failed");

		reply_rx.recv().expect("IPC recv() error")
	}
}