krab_runtime/native/
sys.rs1#[cfg(target_os = "linux")]
2use std::ffi::CString;
3use std::io;
4use std::os::unix::ffi::OsStrExt;
5use std::path::{Path, PathBuf};
6
7#[cfg(target_os = "linux")]
8fn cstr(p: &Path) -> io::Result<CString> {
9 CString::new(p.as_os_str().as_bytes()).map_err(|_| io::Error::other("path contains NUL"))
10}
11
12#[cfg(target_os = "linux")]
13fn check(rc: libc::c_int) -> io::Result<()> {
14 if rc == 0 {
15 Ok(())
16 } else {
17 Err(io::Error::last_os_error())
18 }
19}
20
21pub fn is_root() -> bool {
22 unsafe { libc::geteuid() == 0 }
23}
24
25pub fn option_safe(p: &Path) -> bool {
26 let b = p.as_os_str().as_bytes();
27 p.is_absolute()
28 && !b
29 .iter()
30 .any(|c| matches!(c, b',' | b':' | b'\\' | b'\n' | b'\t' | b' ' | 0))
31}
32
33pub fn overlay_options(lower: &[PathBuf], upper: &Path, work: &Path) -> io::Result<String> {
34 if lower.is_empty() || lower.len() > 128 {
35 return Err(io::Error::other("overlay: bad number of layers"));
36 }
37 for p in lower.iter().map(PathBuf::as_path).chain([upper, work]) {
38 if !option_safe(p) {
39 return Err(io::Error::other(format!(
40 "overlay: unsafe path {}",
41 p.display()
42 )));
43 }
44 }
45 let lowers: Vec<String> = lower
46 .iter()
47 .rev()
48 .map(|p| p.display().to_string())
49 .collect();
50 let opts = format!(
51 "lowerdir={},upperdir={},workdir={}",
52 lowers.join(":"),
53 upper.display(),
54 work.display()
55 );
56 if opts.len() > 4000 {
57 return Err(io::Error::other("overlay: options too long"));
58 }
59 Ok(opts)
60}
61
62#[cfg(target_os = "linux")]
63pub fn mount_overlay(
64 lower: &[PathBuf],
65 upper: &Path,
66 work: &Path,
67 target: &Path,
68) -> io::Result<()> {
69 if !option_safe(target) {
70 return Err(io::Error::other("overlay: unsafe target"));
71 }
72 let opts = CString::new(overlay_options(lower, upper, work)?).map_err(io::Error::other)?;
73 let t = cstr(target)?;
74 let fs = c"overlay";
75 check(unsafe {
76 libc::mount(
77 fs.as_ptr(),
78 t.as_ptr(),
79 fs.as_ptr(),
80 libc::MS_NODEV,
81 opts.as_ptr().cast(),
82 )
83 })
84}
85
86#[cfg(target_os = "linux")]
87pub fn umount(target: &Path) -> io::Result<()> {
88 let t = cstr(target)?;
89 match check(unsafe { libc::umount2(t.as_ptr(), libc::MNT_DETACH) }) {
90 Err(e) if e.raw_os_error() == Some(libc::EINVAL) || e.kind() == io::ErrorKind::NotFound => {
91 Ok(())
92 }
93 r => r,
94 }
95}
96
97#[cfg(target_os = "linux")]
98pub fn is_mounted(target: &Path) -> bool {
99 let want = target.as_os_str().as_bytes();
100 std::fs::read("/proc/self/mountinfo")
101 .map(|m| {
102 m.split(|b| *b == b'\n')
103 .any(|l| l.split(|b| *b == b' ').nth(4) == Some(want))
104 })
105 .unwrap_or(false)
106}
107
108#[cfg(target_os = "linux")]
109pub fn whiteout(path: &Path) -> io::Result<()> {
110 let p = cstr(path)?;
111 check(unsafe { libc::mknod(p.as_ptr(), libc::S_IFCHR, 0) })
112}
113
114#[cfg(target_os = "linux")]
115pub fn opaque(dir: &Path) -> io::Result<()> {
116 let p = cstr(dir)?;
117 let name = c"trusted.overlay.opaque";
118 check(unsafe { libc::setxattr(p.as_ptr(), name.as_ptr(), b"y".as_ptr().cast(), 1, 0) })
119}
120
121#[cfg(not(target_os = "linux"))]
122fn linux_only() -> io::Error {
123 io::Error::new(io::ErrorKind::Unsupported, "native runtime requires Linux")
124}
125
126#[cfg(not(target_os = "linux"))]
127pub fn mount_overlay(lower: &[PathBuf], upper: &Path, work: &Path, _: &Path) -> io::Result<()> {
128 overlay_options(lower, upper, work)?;
129 Err(linux_only())
130}
131
132#[cfg(not(target_os = "linux"))]
133pub fn umount(_: &Path) -> io::Result<()> {
134 Ok(())
135}
136
137#[cfg(not(target_os = "linux"))]
138pub fn is_mounted(_: &Path) -> bool {
139 false
140}
141
142#[cfg(not(target_os = "linux"))]
143pub fn whiteout(_: &Path) -> io::Result<()> {
144 Err(linux_only())
145}
146
147#[cfg(not(target_os = "linux"))]
148pub fn opaque(_: &Path) -> io::Result<()> {
149 Err(linux_only())
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 #[test]
157 fn overlay_options_validate() {
158 let l = vec![PathBuf::from("/r/layers/a"), PathBuf::from("/r/layers/b")];
159 let o = overlay_options(&l, Path::new("/r/c/upper"), Path::new("/r/c/work")).unwrap();
160 assert_eq!(
161 o,
162 "lowerdir=/r/layers/b:/r/layers/a,upperdir=/r/c/upper,workdir=/r/c/work"
163 );
164 let bad = vec![PathBuf::from("/r/la,yers")];
165 assert!(overlay_options(&bad, Path::new("/u"), Path::new("/w")).is_err());
166 let bad = vec![PathBuf::from("/r/a:b")];
167 assert!(overlay_options(&bad, Path::new("/u"), Path::new("/w")).is_err());
168 assert!(overlay_options(&l, Path::new("rel"), Path::new("/w")).is_err());
169 assert!(overlay_options(&[], Path::new("/u"), Path::new("/w")).is_err());
170 }
171}