oscall 0.0.2

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)
    }

    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() {
                println!("skipped: the emulator is a process with several threads: {error}");
                return;
            }
            assert!(refused(&error), "unshare: {error:?}");
            println!("skipped: 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.
            println!(
                "skipped: 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:?}");
            println!(
                "skipped: 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 a shell command writes.
        fn run(script: &str) -> oscall::Result<String> {
            let (output, write) = io::pipe().unwrap();
            let mut child = Command::new("/bin/sh")
                .args(&["-c", script])
                .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("cat /proc/sys/kernel/hostname").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())
            );
            assert_ne!(run("readlink /proc/self/ns/time").unwrap(), before);
        } else {
            println!("skipped: the kernel has 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("echo $$").unwrap(), "1");
        let error = run("echo $$").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() {}
}

fn main() {
    // 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();
    }
}