oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `oscall::process::linux` in a process that has a single thread, which
//! `unshare` wants for a user namespace: this test has no harness
//! (`harness = false` in `Cargo.toml`), since the harness runs every test
//! on a thread of its own. `main` is the test; it changes the namespaces of
//! the process for good, and is alone in it.
//!
//! As in `process_linux.rs`, what the environment refuses is said and
//! skipped.

#[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;

    /// A field of `/proc/self/status`.
    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()
    }

    /// Whether the environment is what refused.
    fn refused(error: &oscall::Error) -> bool {
        matches!(error.raw_os_error(), EPERM | EACCES | ENOSPC | ENOSYS)
    }

    /// Says what the environment kept the test from doing, which is a
    /// failure in a run that exists to cover it: see `common::skip`.
    macro_rules! skip {
        ($($arg:tt)*) => {
            super::common::skip(&format!($($arg)*))
        };
    }

    /// The child half of the test: says what the process is, when the
    /// test runs this program again to ask (`OSCALL_TEST_HELPER`).
    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() {
        // Under qemu-user the process the kernel sees is the emulator,
        // which has threads of its own.
        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();

        // A user namespace for the process, and with it the right to the
        // others.
        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);
        // Nobody, until the maps say who.
        assert_eq!(effective_ids(), (nobody, nobody));

        // The maps of the process's own namespace, by the process itself:
        // one identifier each, its own, and no `setgroups`.
        let me = process::id();
        let map = |outside| {
            [IdMap {
                inside: 0,
                outside,
                count: 1,
            }]
        };
        // The group map is refused while `setgroups` is allowed: to root
        // as well, who left its capabilities outside with the namespace.
        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:?}");
            // Ubuntu's AppArmor restriction: the namespace is there, and
            // its creator has no use of its capabilities.
            skip!(
                "no use of capabilities in the user namespace ({})",
                super::common::confinement()
            );
            return;
        }
        // Denied for good.
        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));
        // Written once.
        let error = linux::write_uid_map(me, &map(uid)).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");

        // Root of the namespace: the others can be had.
        if let Err(error) = linux::unshare(Namespaces::UTS | Namespaces::IPC | Namespaces::NETWORK)
        {
            // As above, found out later.
            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");
    }

    /// The two kinds that are for the processes created afterwards.
    #[cfg(feature = "alloc")]
    fn children() {
        use oscall::process::{Command, Stdio};
        use oscall::{AsHandle, io};

        /// What this program writes when it is run again to say `what`:
        /// see `say`.
        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())
        }

        // The children see the host name of the namespace.
        assert_eq!(run("host").unwrap(), "oscall-single");

        // A time namespace: the caller stays, its children are in the new
        // one.
        if std::path::Path::new("/proc/self/ns/time").exists() {
            let before = namespace("time");
            linux::unshare(Namespaces::TIME).unwrap();
            assert_eq!(namespace("time"), before);
            // "time:[...]" against "time_for_children:[...]".
            let number = |link: String| link.split_once(':').unwrap().1.to_owned();
            assert_ne!(
                number(namespace("time_for_children")),
                number(before.clone())
            );
            // The clocks of the namespace, while nothing is in it: those
            // of the children, not of this process.
            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();
            // What the kernel shows of it.
            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);
            // The namespace has had a process: its clocks are set.
            let error = linux::set_time_offsets(&offsets).unwrap_err();
            assert_eq!(error.raw_os_error(), EACCES, "{error:?}");
        } else {
            super::common::no_time_namespaces();
        }

        // A process namespace: the caller keeps its identifier, the next
        // child is process 1, and the only one there will be.
        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:?}");
    }
}

/// The one test of this file, by the name a filter would select it with.
const NAME: &str = "single_thread";

/// Nothing to test on the other systems.
#[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;
    }
    // What `cargo test` passes on: options, which are ignored, and the
    // names of the tests to run, if not all.
    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();
    }
}