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
use std::env;
use std::ffi::c_int;
use std::fs::{self, File};
use std::io;
use std::os::fd::AsRawFd as _;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use super::{RawCommand, Result};
use libseccomp::{ScmpAction, ScmpFilterContext, ScmpSyscall};
use nix::libc::{self, rusage, wait4, WEXITSTATUS, WSTOPPED, WTERMSIG};
use nix::sys::resource::{setrlimit, Resource};
use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
use nix::unistd::{alarm, dup2, execvp, fork, ForkResult};

extern "C" fn signal_handler(_: nix::libc::c_int) {}

#[derive(Debug, Clone)]
pub struct RlimitConfig {
    pub resource: Resource,
    pub soft_limit: u64,
    pub hard_limit: u64,
}

fn apply_rlimit_configs(configs: &[RlimitConfig]) -> Result<()> {
    for config in configs {
        setrlimit(config.resource, config.soft_limit, config.hard_limit)?;
    }

    Ok(())
}

#[derive(Debug)]
#[allow(unused)]
pub struct RawRunResultInfo {
    pub exit_status: c_int,
    pub exit_signal: c_int,
    pub exit_code: c_int,
    pub real_time_cost: Duration,
    pub resource_usage: Rusage,
}

#[derive(Debug)]
#[allow(unused)]
pub struct Rusage {
    pub user_time: Duration,
    pub system_time: Duration,
    pub max_rss: i64,
    pub page_faults: i64,
    pub involuntary_context_switches: i64,
    pub voluntary_context_switches: i64,
}

impl From<rusage> for Rusage {
    fn from(rusage: rusage) -> Self {
        Self {
            user_time: Duration::new(
                rusage.ru_utime.tv_sec as u64,
                rusage.ru_utime.tv_usec as u32 * 1000,
            ),
            system_time: Duration::new(
                rusage.ru_stime.tv_sec as u64,
                rusage.ru_stime.tv_usec as u32 * 1000,
            ),
            max_rss: rusage.ru_maxrss,
            page_faults: rusage.ru_majflt,
            involuntary_context_switches: rusage.ru_nivcsw,
            voluntary_context_switches: rusage.ru_nvcsw,
        }
    }
}

fn get_default_rusage() -> rusage {
    rusage {
        ru_utime: libc::timeval {
            tv_sec: 0,
            tv_usec: 0,
        },
        ru_stime: libc::timeval {
            tv_sec: 0,
            tv_usec: 0,
        },
        ru_maxrss: 0,
        ru_ixrss: 0,
        ru_idrss: 0,
        ru_isrss: 0,
        ru_minflt: 0,
        ru_majflt: 0,
        ru_nswap: 0,
        ru_inblock: 0,
        ru_oublock: 0,
        ru_msgsnd: 0,
        ru_msgrcv: 0,
        ru_nsignals: 0,
        ru_nvcsw: 0,
        ru_nivcsw: 0,
    }
}

pub struct Sandbox {
    scmp_filter: ScmpFilterContext,
    rlimit_configs: &'static [RlimitConfig],
    /// time out in second
    time_out: u32,
    project_path: PathBuf,
    command: RawCommand,
    input_redirect: File,
    output_redirect: File,
    error_redirect: File,
    child_pid: i32,
    begin_time: Instant,
}

impl Sandbox {
    pub fn new(
        scmp_black_list: &'static [&'static str],
        rlimit_configs: &'static [RlimitConfig],
        time_out: u32,
        project_path: PathBuf,
        command: RawCommand,
        input_path: &Path,
        output_path: &Path,
        error_path: &Path,
    ) -> Result<Self> {
        let mut scmp_filter = ScmpFilterContext::new_filter(ScmpAction::Allow)?;
        for s in scmp_black_list {
            let syscall = ScmpSyscall::from_name(s)?;
            scmp_filter.add_rule_exact(ScmpAction::KillProcess, syscall)?;
        }
        let input_redirect = fs::OpenOptions::new().read(true).open(input_path)?;
        let output_redirect = fs::OpenOptions::new().write(true).open(output_path)?;
        let error_redirect = fs::OpenOptions::new().write(true).open(error_path)?;

        let child_pid = -1;
        let begin_time = Instant::now();

        Ok(Self {
            scmp_filter,
            rlimit_configs,
            time_out,
            project_path,
            command,
            input_redirect,
            output_redirect,
            error_redirect,
            child_pid,
            begin_time,
        })
    }

    /// Currently close all `stderr` and close `stdin`/`stdout` if redirect is not set
    fn load_io(&self) -> Result<()> {
        let stdin_raw_fd = io::stdin().as_raw_fd();
        dup2(self.input_redirect.as_raw_fd(), stdin_raw_fd)?;

        let stdout_raw_fd = io::stdout().as_raw_fd();
        dup2(self.output_redirect.as_raw_fd(), stdout_raw_fd)?;

        let stderr_raw_fd = io::stderr().as_raw_fd();
        dup2(self.error_redirect.as_raw_fd(), stderr_raw_fd)?;

        Ok(())
    }

    pub fn wait(&self) -> Result<RawRunResultInfo> {
        let mut status: c_int = 0;
        let mut usage: rusage = get_default_rusage();
        unsafe {
            wait4(self.child_pid, &mut status, WSTOPPED, &mut usage);
        }

        Ok(RawRunResultInfo {
            exit_status: status,
            exit_signal: WTERMSIG(status),
            exit_code: WEXITSTATUS(status),
            real_time_cost: self.begin_time.elapsed(),
            resource_usage: Rusage::from(usage),
        })
    }

    /// WARNING:   
    /// Unsafe to use `println!()` (or `unwrap()`) in child process.
    /// See more in `fork()` document.
    pub fn spawn(&mut self) -> Result<i32> {
        let now = Instant::now();
        unsafe {
            sigaction(
                Signal::SIGALRM,
                &SigAction::new(
                    SigHandler::Handler(signal_handler),
                    SaFlags::empty(),
                    SigSet::empty(),
                ),
            )
            .unwrap();
        }
        match unsafe { fork() } {
            Ok(ForkResult::Parent { child, .. }) => {
                self.child_pid = child.as_raw();
                self.begin_time = now;
                Ok(child.as_raw())
            }
            // child process should not return to do things outside `spawn()`
            Ok(ForkResult::Child) => {
                if env::set_current_dir(&self.project_path).is_err() {
                    eprintln!("Failed to load change to project directory");
                    unsafe { libc::_exit(100) };
                }

                if self.load_io().is_err() {
                    eprintln!("Failed to load I/O");
                    unsafe { libc::_exit(1) };
                }
                if apply_rlimit_configs(&self.rlimit_configs).is_err() {
                    eprintln!("Failed to load rlimit configs");
                    unsafe { libc::_exit(1) };
                }
                if self.scmp_filter.load().is_err() {
                    eprintln!("Failed to load seccomp filter");
                    unsafe { libc::_exit(1) };
                }

                alarm::set(self.time_out);

                let RawCommand { binary, args } = self.command;

                if let Err(error) = execvp(binary, args) {
                    eprintln!("{}", error);
                }
                unsafe { libc::_exit(0) };
            }
            Err(e) => Err(e.into()),
        }
    }
}