#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod common;
#[cfg(any(target_os = "linux", target_os = "fullrust"))]
mod linux {
use super::common::emulated;
use oscall::process::linux::{self, IdMap, Namespaces};
use oscall::{ErrorKind, process};
const EPERM: i32 = 1;
const EACCES: i32 = 13;
const ENOSPC: i32 = 28;
const ENOSYS: i32 = 38;
fn status_field(name: &str, index: usize) -> String {
let status = std::fs::read_to_string("/proc/self/status").unwrap();
let line = status
.lines()
.find_map(|line| line.strip_prefix(name)?.strip_prefix(':'))
.unwrap();
line.split_whitespace().nth(index).unwrap().to_owned()
}
fn effective_ids() -> (u32, u32) {
(
status_field("Uid", 1).parse().unwrap(),
status_field("Gid", 1).parse().unwrap(),
)
}
fn host_name() -> String {
std::fs::read_to_string("/proc/sys/kernel/hostname")
.unwrap()
.trim()
.to_owned()
}
fn namespace(kind: &str) -> String {
let link = std::fs::read_link(format!("/proc/self/ns/{kind}")).unwrap();
link.to_string_lossy().into_owned()
}
fn refused(error: &oscall::Error) -> bool {
matches!(error.raw_os_error(), EPERM | EACCES | ENOSPC | ENOSYS)
}
macro_rules! skip {
($($arg:tt)*) => {
super::common::skip(&format!($($arg)*))
};
}
pub fn say(what: &str) {
match what {
"host" => println!("{}", host_name()),
"time" => println!("{}", namespace("time")),
"clock" => println!(
"{}",
oscall::time::Clock::Monotonic.now().unwrap().as_secs()
),
"pid" => println!("{}", process::id()),
_ => panic!("unknown helper mode {what}"),
}
}
pub fn main() {
if !emulated() {
assert_eq!(status_field("Threads", 0), "1");
}
let (uid, gid) = effective_ids();
let outside_host = host_name();
let outside_user = namespace("user");
let outside_uts = namespace("uts");
let nobody: u32 = std::fs::read_to_string("/proc/sys/kernel/overflowuid")
.unwrap()
.trim()
.parse()
.unwrap();
if let Err(error) = linux::unshare(Namespaces::USER) {
if error.kind() == ErrorKind::InvalidInput && emulated() {
skip!("the emulator is a process with several threads: {error}");
return;
}
assert!(refused(&error), "unshare: {error:?}");
skip!("no user namespace for this process: {error}");
return;
}
assert_ne!(namespace("user"), outside_user);
assert_eq!(effective_ids(), (nobody, nobody));
let me = process::id();
let map = |outside| {
[IdMap {
inside: 0,
outside,
count: 1,
}]
};
let error = linux::write_gid_map(me, &map(gid)).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
if let Err(error) = linux::allow_setgroups(me, false) {
assert!(refused(&error), "setgroups: {error:?}");
skip!(
"no use of capabilities in the user namespace ({})",
super::common::confinement()
);
return;
}
let error = linux::allow_setgroups(me, true).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
linux::write_gid_map(me, &map(gid)).unwrap();
linux::write_uid_map(me, &map(uid)).unwrap();
assert_eq!(effective_ids(), (0, 0));
let error = linux::write_uid_map(me, &map(uid)).unwrap_err();
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
if let Err(error) = linux::unshare(Namespaces::UTS | Namespaces::IPC | Namespaces::NETWORK)
{
assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
skip!(
"no use of capabilities in the user namespace ({})",
super::common::confinement()
);
return;
}
assert_ne!(namespace("uts"), outside_uts);
assert_eq!(host_name(), outside_host);
linux::set_host_name(b"oscall-single").unwrap();
assert_eq!(host_name(), "oscall-single");
linux::unshare(Namespaces::MOUNT | Namespaces::CGROUP).unwrap();
#[cfg(feature = "alloc")]
children();
println!("ok");
}
#[cfg(feature = "alloc")]
fn children() {
use oscall::process::{Command, Stdio};
use oscall::{AsHandle, io};
fn run(what: &str) -> oscall::Result<String> {
let exe = std::env::current_exe().unwrap();
let mut env: Vec<Vec<u8>> = std::env::vars_os()
.map(|(name, value)| {
[name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat()
})
.collect();
env.push(format!("OSCALL_TEST_HELPER={what}").into_bytes());
let (output, write) = io::pipe().unwrap();
let mut child = Command::new(exe.as_os_str().as_encoded_bytes())
.env(&env)
.stdin(Stdio::Null)
.stdout(Stdio::Handle(write.as_handle()))
.spawn()?;
drop(write);
let mut text = Vec::new();
let mut buf = [0u8; 256];
loop {
match io::read(&output, &mut buf).unwrap() {
0 => break,
n => text.extend_from_slice(&buf[..n]),
}
}
assert!(child.wait().unwrap().success());
Ok(String::from_utf8(text).unwrap().trim().to_owned())
}
assert_eq!(run("host").unwrap(), "oscall-single");
if std::path::Path::new("/proc/self/ns/time").exists() {
let before = namespace("time");
linux::unshare(Namespaces::TIME).unwrap();
assert_eq!(namespace("time"), before);
let number = |link: String| link.split_once(':').unwrap().1.to_owned();
assert_ne!(
number(namespace("time_for_children")),
number(before.clone())
);
let ahead = 3_000_000;
let offsets = linux::TimeOffsets {
monotonic: Some(linux::ClockOffset::new(ahead, 0)),
boot_time: Some(linux::ClockOffset::new(-1, 999_999_999)),
};
let clock = || oscall::time::Clock::Monotonic.now().unwrap().as_secs();
let started = clock();
linux::set_time_offsets(&offsets).unwrap();
let shown = std::fs::read_to_string("/proc/self/timens_offsets").unwrap();
let shown: Vec<Vec<&str>> = shown
.lines()
.map(|line| line.split_whitespace().collect())
.collect();
assert_eq!(
shown,
[
["monotonic", "3000000", "0"],
["boottime", "-1", "999999999"]
]
);
let child: u64 = run("clock").unwrap().parse().unwrap();
let ended = clock();
assert!(ended - started < 600, "the clock of this process moved");
assert!(
started + ahead as u64 <= child && child <= ended + ahead as u64,
"{child} is not {ahead} after {started}..{ended}"
);
assert_ne!(run("time").unwrap(), before);
let error = linux::set_time_offsets(&offsets).unwrap_err();
assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
} else {
super::common::no_time_namespaces();
}
let pid = process::id();
linux::unshare(Namespaces::PID).unwrap();
assert_eq!(process::id(), pid);
assert_eq!(run("pid").unwrap(), "1");
let error = run("pid").unwrap_err();
assert_eq!(error.kind(), ErrorKind::OutOfMemory, "{error:?}");
}
}
const NAME: &str = "single_thread";
#[cfg(not(any(target_os = "linux", target_os = "fullrust")))]
mod linux {
pub fn main() {}
pub fn say(_: &str) {}
}
fn main() {
if let Some(what) = std::env::var_os("OSCALL_TEST_HELPER") {
linux::say(&what.into_string().unwrap());
return;
}
let mut filters = std::env::args().skip(1).filter(|arg| !arg.starts_with('-'));
let selected = match filters.next() {
None => true,
Some(first) => NAME.contains(&first) || filters.any(|filter| NAME.contains(&filter)),
};
let list = std::env::args().any(|arg| arg == "--list");
if selected && !list {
linux::main();
}
}