Skip to main content

kh_runtime/bottle/
path.rs

1//! Bottle root path translation (macOS-like FS tree under a host directory).
2//!
3//! Guest absolute paths such as `/usr/lib/libSystem.B.dylib` resolve to
4//! `{root}/usr/lib/libSystem.B.dylib`. Path escape via `..` is rejected.
5
6use std::path::{Component, Path, PathBuf};
7
8use thiserror::Error;
9
10use crate::process;
11
12/// Path translation errors.
13#[derive(Debug, Error, Clone, PartialEq, Eq)]
14pub enum PathError {
15    /// Guest path was empty.
16    #[error("empty guest path")]
17    Empty,
18
19    /// Guest path contained `..` or other disallowed components.
20    #[error("guest path escapes bottle: {0}")]
21    Escape(String),
22
23    /// Path is not valid UTF-8 / OS string.
24    #[error("invalid path encoding")]
25    InvalidEncoding,
26}
27
28/// Configures the bottle root used by path-taking syscalls (`open`, `access`, …).
29///
30/// Pass `None` to clear (pass-through absolute guest paths to the host).
31pub fn set_bottle_root(root: Option<PathBuf>) {
32    process::set_bottle_root(root);
33}
34
35/// Returns a clone of the configured bottle root, if any.
36#[must_use]
37pub fn bottle_root() -> Option<PathBuf> {
38    process::bottle_root()
39}
40
41/// Translates a guest path string into a host path.
42///
43/// * Absolute guest path + bottle → `{root}/{stripped absolute}`
44/// * Absolute guest path, no bottle → host absolute path as-is
45/// * Relative guest path → **host CWD-relative** (Darwin open semantics); bottle
46///   is not applied. Still rejects `..` escape components.
47pub fn translate_path(guest: &str) -> Result<PathBuf, PathError> {
48    // Avoid cloning the bottle root PathBuf on every open/stat.
49    process::with_bottle_root(|root| translate_path_with_root(root, guest))
50}
51
52/// Pure translation helper (testable without process globals).
53pub fn translate_path_with_root(root: Option<&Path>, guest: &str) -> Result<PathBuf, PathError> {
54    if guest.is_empty() {
55        return Err(PathError::Empty);
56    }
57
58    // Relative paths follow host CWD (fixtures / argv paths), not the bottle tree.
59    if !guest.starts_with('/') {
60        // Reject `..` while keeping the original relative string for open(2).
61        strip_root_components(Path::new(guest))?;
62        return Ok(PathBuf::from(guest));
63    }
64
65    // Fast path: no `..` and no empty components → strip leading slashes / `.`
66    // without allocating intermediate PathBufs for each component.
67    if let Some(rel) = try_fast_relative(guest) {
68        return match root {
69            Some(r) => {
70                let mut out = PathBuf::with_capacity(
71                    r.as_os_str()
72                        .len()
73                        .saturating_add(rel.len())
74                        .saturating_add(1),
75                );
76                out.push(r);
77                if !rel.is_empty() {
78                    out.push(rel);
79                }
80                Ok(out)
81            }
82            None => Ok(PathBuf::from(guest)),
83        };
84    }
85
86    let guest_path = Path::new(guest);
87    let relative = strip_root_components(guest_path)?;
88
89    match root {
90        Some(r) => {
91            let mut out = r.to_path_buf();
92            out.push(relative);
93            Ok(out)
94        }
95        None => Ok(guest_path.to_path_buf()),
96    }
97}
98
99/// Bottle-relative openat target for an absolute guest path (B1).
100///
101/// When `Some((dirfd, rel))`, callers should `openat`/`fstatat` with `rel`
102/// (`"."` when the guest path is `/`) instead of allocating `{root}/{rel}`.
103#[must_use]
104pub fn bottle_openat_rel(guest: &str) -> Option<(std::os::fd::RawFd, &str)> {
105    if !guest.starts_with('/') {
106        return None;
107    }
108    let dirfd = process::bottle_dirfd()?;
109    let rel = try_fast_relative(guest)?;
110    Some((dirfd, if rel.is_empty() { "." } else { rel }))
111}
112
113/// Returns stripped relative guest path when it has no `..` (and no empty segs).
114///
115/// `None` means fall back to the full component walker.
116fn try_fast_relative(guest: &str) -> Option<&str> {
117    if guest.contains("..") {
118        // May be `foo..bar` (ok) or `../x` / `a/../b` — let the slow path decide.
119        if guest == ".."
120            || guest.starts_with("../")
121            || guest.ends_with("/..")
122            || guest.contains("/../")
123        {
124            return None;
125        }
126    }
127    let mut s = guest;
128    while let Some(rest) = s.strip_prefix('/') {
129        s = rest;
130    }
131    // Drop a single leading "./"
132    if let Some(rest) = s.strip_prefix("./") {
133        s = rest;
134    }
135    // Reject remaining "./" or empty segments that need normalization.
136    if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
137        return None;
138    }
139    Some(s)
140}
141
142/// Strips leading `/` (and Windows-style prefixes if any) and rejects `..`.
143fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
144    let mut out = PathBuf::new();
145    for comp in path.components() {
146        match comp {
147            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
148            Component::ParentDir => {
149                return Err(PathError::Escape(path.display().to_string()));
150            }
151            Component::Normal(s) => out.push(s),
152        }
153    }
154    Ok(out)
155}
156
157/// Stack buffer size for typical guest paths (avoids heap on open/stat).
158const PATH_STACK: usize = 512;
159
160/// Reads a NUL-terminated C string from an identity-mapped guest pointer.
161///
162/// Used by `open` / `access` handlers. Caps length to avoid runaway scans.
163#[must_use]
164#[allow(unsafe_code)]
165pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
166    if ptr == 0 || max_len == 0 {
167        return None;
168    }
169    let base = usize::try_from(ptr).ok()?;
170    let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
171
172    let mut stack = [0_u8; PATH_STACK];
173    let stack_cap = PATH_STACK.min(max_len);
174    for i in 0..stack_cap {
175        // SAFETY: identity map — guest VA == host VA for mapped pages.
176        let byte = unsafe { *base_ptr.wrapping_add(i) };
177        if byte == 0 {
178            return stack
179                .get(..i)
180                .and_then(|s| std::str::from_utf8(s).ok())
181                .map(str::to_owned);
182        }
183        if let Some(slot) = stack.get_mut(i) {
184            *slot = byte;
185        }
186    }
187    if stack_cap == max_len {
188        return None; // no NUL within cap
189    }
190
191    // Longer path: fall back to heap.
192    let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
193    if let Some(prefix) = stack.get(..stack_cap) {
194        buf.extend_from_slice(prefix);
195    }
196    for i in stack_cap..max_len {
197        let byte = unsafe { *base_ptr.wrapping_add(i) };
198        if byte == 0 {
199            return String::from_utf8(buf).ok();
200        }
201        buf.push(byte);
202    }
203    None
204}
205
206#[cfg(test)]
207#[allow(clippy::expect_used)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn absolute_under_bottle() {
213        let root = Path::new("/opt/bottle");
214        let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
215            .expect("translate absolute");
216        assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
217    }
218
219    #[test]
220    fn relative_stays_host_cwd_even_with_bottle() {
221        let root = Path::new("/opt/bottle");
222        let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
223        assert_eq!(host, PathBuf::from("tmp/x"));
224    }
225
226    #[test]
227    fn relative_rejects_dotdot() {
228        let root = Path::new("/opt/bottle");
229        let err = translate_path_with_root(Some(root), "../etc/passwd").expect_err("..");
230        assert!(matches!(err, PathError::Escape(_)));
231    }
232
233    #[test]
234    fn no_bottle_passthrough() {
235        let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
236        assert_eq!(host, PathBuf::from("/tmp/foo"));
237    }
238
239    #[test]
240    fn rejects_parent_dir() {
241        let root = Path::new("/opt/bottle");
242        let err =
243            translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
244        assert!(matches!(err, PathError::Escape(_)));
245    }
246
247    #[test]
248    fn empty_rejected() {
249        assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
250    }
251
252    #[test]
253    fn volumes_linux_under_bottle() {
254        let root = Path::new("/var/lib/my-renamed-bottle");
255        let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
256            .expect("translate volumes");
257        assert_eq!(
258            host,
259            PathBuf::from("/var/lib/my-renamed-bottle/Volumes/linux/tmp/x")
260        );
261    }
262
263    #[test]
264    fn fast_path_dots_in_name_ok() {
265        let root = Path::new("/b");
266        let host = translate_path_with_root(Some(root), "/foo..bar").expect("dots in name");
267        assert_eq!(host, PathBuf::from("/b/foo..bar"));
268    }
269
270    #[test]
271    fn bottle_openat_rel_uses_dirfd_when_configured() {
272        let tmp = std::env::temp_dir().join(format!(
273            "kh-b1-openat-{}",
274            std::process::id()
275        ));
276        drop(std::fs::remove_dir_all(&tmp));
277        std::fs::create_dir_all(tmp.join("usr/lib")).expect("mkdir");
278        set_bottle_root(Some(tmp.clone()));
279        let (fd, rel) = bottle_openat_rel("/usr/lib/libSystem.B.dylib").expect("openat parts");
280        assert!(fd >= 0);
281        assert_eq!(rel, "usr/lib/libSystem.B.dylib");
282        assert!(bottle_openat_rel("relative").is_none());
283        set_bottle_root(None);
284        assert!(bottle_openat_rel("/usr/lib/x").is_none());
285        drop(std::fs::remove_dir_all(&tmp));
286    }
287}