krab-runtime 0.2.2

Container runtime abstraction and Docker backend for krabkube
Documentation
#[cfg(target_os = "linux")]
use std::ffi::CString;
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};

#[cfg(target_os = "linux")]
fn cstr(p: &Path) -> io::Result<CString> {
    CString::new(p.as_os_str().as_bytes()).map_err(|_| io::Error::other("path contains NUL"))
}

#[cfg(target_os = "linux")]
fn check(rc: libc::c_int) -> io::Result<()> {
    if rc == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

pub fn is_root() -> bool {
    unsafe { libc::geteuid() == 0 }
}

pub fn option_safe(p: &Path) -> bool {
    let b = p.as_os_str().as_bytes();
    p.is_absolute()
        && !b
            .iter()
            .any(|c| matches!(c, b',' | b':' | b'\\' | b'\n' | b'\t' | b' ' | 0))
}

pub fn overlay_options(lower: &[PathBuf], upper: &Path, work: &Path) -> io::Result<String> {
    if lower.is_empty() || lower.len() > 128 {
        return Err(io::Error::other("overlay: bad number of layers"));
    }
    for p in lower.iter().map(PathBuf::as_path).chain([upper, work]) {
        if !option_safe(p) {
            return Err(io::Error::other(format!(
                "overlay: unsafe path {}",
                p.display()
            )));
        }
    }
    let lowers: Vec<String> = lower
        .iter()
        .rev()
        .map(|p| p.display().to_string())
        .collect();
    let opts = format!(
        "lowerdir={},upperdir={},workdir={}",
        lowers.join(":"),
        upper.display(),
        work.display()
    );
    if opts.len() > 4000 {
        return Err(io::Error::other("overlay: options too long"));
    }
    Ok(opts)
}

#[cfg(target_os = "linux")]
pub fn mount_overlay(
    lower: &[PathBuf],
    upper: &Path,
    work: &Path,
    target: &Path,
) -> io::Result<()> {
    if !option_safe(target) {
        return Err(io::Error::other("overlay: unsafe target"));
    }
    let opts = CString::new(overlay_options(lower, upper, work)?).map_err(io::Error::other)?;
    let t = cstr(target)?;
    let fs = c"overlay";
    check(unsafe {
        libc::mount(
            fs.as_ptr(),
            t.as_ptr(),
            fs.as_ptr(),
            libc::MS_NODEV,
            opts.as_ptr().cast(),
        )
    })
}

#[cfg(target_os = "linux")]
pub fn umount(target: &Path) -> io::Result<()> {
    let t = cstr(target)?;
    match check(unsafe { libc::umount2(t.as_ptr(), libc::MNT_DETACH) }) {
        Err(e) if e.raw_os_error() == Some(libc::EINVAL) || e.kind() == io::ErrorKind::NotFound => {
            Ok(())
        }
        r => r,
    }
}

#[cfg(target_os = "linux")]
pub fn is_mounted(target: &Path) -> bool {
    let want = target.as_os_str().as_bytes();
    std::fs::read("/proc/self/mountinfo")
        .map(|m| {
            m.split(|b| *b == b'\n')
                .any(|l| l.split(|b| *b == b' ').nth(4) == Some(want))
        })
        .unwrap_or(false)
}

#[cfg(target_os = "linux")]
pub fn whiteout(path: &Path) -> io::Result<()> {
    let p = cstr(path)?;
    check(unsafe { libc::mknod(p.as_ptr(), libc::S_IFCHR, 0) })
}

#[cfg(target_os = "linux")]
pub fn opaque(dir: &Path) -> io::Result<()> {
    let p = cstr(dir)?;
    let name = c"trusted.overlay.opaque";
    check(unsafe { libc::setxattr(p.as_ptr(), name.as_ptr(), b"y".as_ptr().cast(), 1, 0) })
}

#[cfg(not(target_os = "linux"))]
fn linux_only() -> io::Error {
    io::Error::new(io::ErrorKind::Unsupported, "native runtime requires Linux")
}

#[cfg(not(target_os = "linux"))]
pub fn mount_overlay(lower: &[PathBuf], upper: &Path, work: &Path, _: &Path) -> io::Result<()> {
    overlay_options(lower, upper, work)?;
    Err(linux_only())
}

#[cfg(not(target_os = "linux"))]
pub fn umount(_: &Path) -> io::Result<()> {
    Ok(())
}

#[cfg(not(target_os = "linux"))]
pub fn is_mounted(_: &Path) -> bool {
    false
}

#[cfg(not(target_os = "linux"))]
pub fn whiteout(_: &Path) -> io::Result<()> {
    Err(linux_only())
}

#[cfg(not(target_os = "linux"))]
pub fn opaque(_: &Path) -> io::Result<()> {
    Err(linux_only())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn overlay_options_validate() {
        let l = vec![PathBuf::from("/r/layers/a"), PathBuf::from("/r/layers/b")];
        let o = overlay_options(&l, Path::new("/r/c/upper"), Path::new("/r/c/work")).unwrap();
        assert_eq!(
            o,
            "lowerdir=/r/layers/b:/r/layers/a,upperdir=/r/c/upper,workdir=/r/c/work"
        );
        let bad = vec![PathBuf::from("/r/la,yers")];
        assert!(overlay_options(&bad, Path::new("/u"), Path::new("/w")).is_err());
        let bad = vec![PathBuf::from("/r/a:b")];
        assert!(overlay_options(&bad, Path::new("/u"), Path::new("/w")).is_err());
        assert!(overlay_options(&l, Path::new("rel"), Path::new("/w")).is_err());
        assert!(overlay_options(&[], Path::new("/u"), Path::new("/w")).is_err());
    }
}