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//!
6//! Special case: `/Volumes/linux/...` maps **directly** to host `/...` (skips
7//! the bottle symlink hop that would otherwise run on every open/stat).
8
9use std::ffi::CStr;
10use std::path::{Component, Path, PathBuf};
11
12use thiserror::Error;
13
14use crate::process;
15
16/// Path translation errors.
17#[derive(Debug, Error, Clone, PartialEq, Eq)]
18pub enum PathError {
19    /// Guest path was empty.
20    #[error("empty guest path")]
21    Empty,
22
23    /// Guest path contained `..` or other disallowed components.
24    #[error("guest path escapes bottle: {0}")]
25    Escape(String),
26
27    /// Path is not valid UTF-8 / OS string.
28    #[error("invalid path encoding")]
29    InvalidEncoding,
30
31    /// Host path did not fit in the provided buffer.
32    #[error("path too long for buffer")]
33    TooLong,
34}
35
36/// Configures the bottle root used by path-taking syscalls (`open`, `access`, …).
37///
38/// Pass `None` to clear (pass-through absolute guest paths to the host).
39pub fn set_bottle_root(root: Option<PathBuf>) {
40    process::set_bottle_root(root);
41}
42
43/// Returns a clone of the configured bottle root, if any.
44#[must_use]
45pub fn bottle_root() -> Option<PathBuf> {
46    process::bottle_root()
47}
48
49/// Guest host-bridge prefix (symlink target is `/`; we short-circuit in translate).
50const VOLUMES_LINUX: &str = "Volumes/linux";
51
52/// Translates a guest path string into a host path.
53///
54/// * `/Volumes/linux/...` → host `/...` (no bottle hop)
55/// * Absolute guest path + bottle → `{root}/{relative}`
56/// * Absolute guest path, no bottle → host absolute path as-is
57/// * Relative guest path + bottle → `{root}/{relative}`
58/// * Relative guest path, no bottle → host-relative path as-is
59pub fn translate_path(guest: &str) -> Result<PathBuf, PathError> {
60    process::with_bottle_root(|root| translate_path_with_root(root, guest))
61}
62
63/// Pure translation helper (testable without process globals).
64pub fn translate_path_with_root(root: Option<&Path>, guest: &str) -> Result<PathBuf, PathError> {
65    if guest.is_empty() {
66        return Err(PathError::Empty);
67    }
68
69    // Host bridge: `/Volumes/linux/foo` → `/foo` (skip bottle symlink walk).
70    if let Some(host) = try_volumes_linux(guest)? {
71        return Ok(host);
72    }
73
74    // Fast path: no `..` and no empty components → strip leading slashes / `.`
75    // without allocating intermediate PathBufs for each component.
76    if let Some(rel) = try_fast_relative(guest) {
77        return match root {
78            Some(r) => {
79                let mut out = PathBuf::with_capacity(
80                    r.as_os_str()
81                        .len()
82                        .saturating_add(rel.len())
83                        .saturating_add(1),
84                );
85                out.push(r);
86                if !rel.is_empty() {
87                    out.push(rel);
88                }
89                Ok(out)
90            }
91            None => Ok(PathBuf::from(guest)),
92        };
93    }
94
95    let guest_path = Path::new(guest);
96    let relative = strip_root_components(guest_path)?;
97
98    match root {
99        Some(r) => {
100            let mut out = r.to_path_buf();
101            out.push(relative);
102            Ok(out)
103        }
104        None => Ok(guest_path.to_path_buf()),
105    }
106}
107
108/// Writes a translated host path as a NUL-terminated C string into `out`.
109///
110/// Returns a [`CStr`] view into `out` on success. Prefer this on open/stat hot
111/// paths to avoid `PathBuf` + `CString` heap traffic.
112pub fn translate_path_cstr<'a>(
113    guest: &str,
114    out: &'a mut [u8],
115) -> Result<&'a CStr, PathError> {
116    process::with_bottle_root(|root| translate_path_cstr_with_root(root, guest, out))
117}
118
119/// Pure form of [`translate_path_cstr`].
120pub fn translate_path_cstr_with_root<'a>(
121    root: Option<&Path>,
122    guest: &str,
123    out: &'a mut [u8],
124) -> Result<&'a CStr, PathError> {
125    if guest.is_empty() {
126        return Err(PathError::Empty);
127    }
128    if out.len() < 2 {
129        return Err(PathError::TooLong);
130    }
131
132    if let Some(host) = try_volumes_linux(guest)? {
133        return write_path_cstr(&host, out);
134    }
135
136    if let Some(rel) = try_fast_relative(guest) {
137        return match root {
138            Some(r) => join_root_rel_cstr(r, rel, out),
139            None => write_bytes_cstr(guest.as_bytes(), out),
140        };
141    }
142
143    // Slow path: component walk, then write.
144    let host = translate_path_with_root(root, guest)?;
145    write_path_cstr(&host, out)
146}
147
148fn try_volumes_linux(guest: &str) -> Result<Option<PathBuf>, PathError> {
149    let rest = if guest == "/Volumes/linux" || guest == VOLUMES_LINUX {
150        ""
151    } else if let Some(r) = guest.strip_prefix("/Volumes/linux/") {
152        r
153    } else if let Some(r) = guest.strip_prefix("Volumes/linux/") {
154        r
155    } else {
156        return Ok(None);
157    };
158
159    // Reject `..` escapes under the bridge.
160    if let Some(rel) = try_fast_relative(rest) {
161        if rel.is_empty() {
162            return Ok(Some(PathBuf::from("/")));
163        }
164        let mut out = PathBuf::from("/");
165        out.push(rel);
166        return Ok(Some(out));
167    }
168    // May contain `..` or `//` — validate.
169    let relative = strip_root_components(Path::new(rest))?;
170    if relative.as_os_str().is_empty() {
171        return Ok(Some(PathBuf::from("/")));
172    }
173    let mut out = PathBuf::from("/");
174    out.push(relative);
175    Ok(Some(out))
176}
177
178fn join_root_rel_cstr<'a>(
179    root: &Path,
180    rel: &str,
181    out: &'a mut [u8],
182) -> Result<&'a CStr, PathError> {
183    let root_bytes = root.as_os_str().as_encoded_bytes();
184    let need = root_bytes
185        .len()
186        .saturating_add(if rel.is_empty() { 0 } else { rel.len().saturating_add(1) })
187        .saturating_add(1);
188    if need > out.len() {
189        return Err(PathError::TooLong);
190    }
191    let mut n = 0_usize;
192    if let Some(dst) = out.get_mut(..root_bytes.len()) {
193        dst.copy_from_slice(root_bytes);
194        n = root_bytes.len();
195    }
196    if !rel.is_empty() {
197        // Ensure a single `/` between root and rel when root has no trailing slash.
198        let need_sep = !root_bytes.ends_with(b"/");
199        if need_sep
200            && let Some(slot) = out.get_mut(n)
201        {
202            *slot = b'/';
203            n = n.saturating_add(1);
204        }
205        if let Some(dst) = out.get_mut(n..n.saturating_add(rel.len())) {
206            dst.copy_from_slice(rel.as_bytes());
207            n = n.saturating_add(rel.len());
208        }
209    }
210    if let Some(slot) = out.get_mut(n) {
211        *slot = 0;
212    } else {
213        return Err(PathError::TooLong);
214    }
215    let Some(with_nul) = out.get(..n.saturating_add(1)) else {
216        return Err(PathError::TooLong);
217    };
218    CStr::from_bytes_with_nul(with_nul).map_err(|_| PathError::InvalidEncoding)
219}
220
221fn write_path_cstr<'a>(path: &Path, out: &'a mut [u8]) -> Result<&'a CStr, PathError> {
222    write_bytes_cstr(path.as_os_str().as_encoded_bytes(), out)
223}
224
225fn write_bytes_cstr<'a>(bytes: &[u8], out: &'a mut [u8]) -> Result<&'a CStr, PathError> {
226    if bytes.contains(&0) {
227        return Err(PathError::InvalidEncoding);
228    }
229    let need = bytes.len().saturating_add(1);
230    if need > out.len() {
231        return Err(PathError::TooLong);
232    }
233    if let Some(dst) = out.get_mut(..bytes.len()) {
234        dst.copy_from_slice(bytes);
235    }
236    if let Some(slot) = out.get_mut(bytes.len()) {
237        *slot = 0;
238    }
239    let Some(with_nul) = out.get(..bytes.len().saturating_add(1)) else {
240        return Err(PathError::TooLong);
241    };
242    CStr::from_bytes_with_nul(with_nul).map_err(|_| PathError::InvalidEncoding)
243}
244
245/// Returns stripped relative guest path when it has no `..` (and no empty segs).
246///
247/// `None` means fall back to the full component walker.
248fn try_fast_relative(guest: &str) -> Option<&str> {
249    if guest.contains("..") {
250        // May be `foo..bar` (ok) or `../x` / `a/../b` — let the slow path decide.
251        if guest == ".."
252            || guest.starts_with("../")
253            || guest.ends_with("/..")
254            || guest.contains("/../")
255        {
256            return None;
257        }
258    }
259    let mut s = guest;
260    while let Some(rest) = s.strip_prefix('/') {
261        s = rest;
262    }
263    // Drop a single leading "./"
264    if let Some(rest) = s.strip_prefix("./") {
265        s = rest;
266    }
267    // Reject remaining "./" or empty segments that need normalization.
268    if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
269        return None;
270    }
271    Some(s)
272}
273
274/// Strips leading `/` (and Windows-style prefixes if any) and rejects `..`.
275fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
276    let mut out = PathBuf::new();
277    for comp in path.components() {
278        match comp {
279            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
280            Component::ParentDir => {
281                return Err(PathError::Escape(path.display().to_string()));
282            }
283            Component::Normal(s) => out.push(s),
284        }
285    }
286    Ok(out)
287}
288
289/// Stack buffer size for typical guest paths (avoids heap on open/stat).
290const PATH_STACK: usize = 512;
291
292/// Host path stack buffer for open/stat (bottle root + guest path).
293pub const HOST_PATH_STACK: usize = 1024;
294
295/// Reads a NUL-terminated C string from an identity-mapped guest pointer.
296///
297/// Used by `open` / `access` handlers. Caps length to avoid runaway scans.
298#[must_use]
299#[allow(unsafe_code)]
300pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
301    with_guest_path_bytes(ptr, max_len, |bytes| {
302        std::str::from_utf8(bytes).ok().map(str::to_owned)
303    })?
304}
305
306/// Calls `f` with the raw guest path bytes (no NUL) without forcing a `String`
307/// when the path fits on the stack.
308#[must_use]
309#[allow(unsafe_code)]
310pub fn with_guest_path_bytes<R>(
311    ptr: u64,
312    max_len: usize,
313    f: impl FnOnce(&[u8]) -> R,
314) -> Option<R> {
315    if ptr == 0 || max_len == 0 {
316        return None;
317    }
318    let base = usize::try_from(ptr).ok()?;
319    let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
320
321    let mut stack = [0_u8; PATH_STACK];
322    let stack_cap = PATH_STACK.min(max_len);
323    for i in 0..stack_cap {
324        // SAFETY: identity map — guest VA == host VA for mapped pages.
325        let byte = unsafe { *base_ptr.wrapping_add(i) };
326        if byte == 0 {
327            let slice = stack.get(..i)?;
328            return Some(f(slice));
329        }
330        if let Some(slot) = stack.get_mut(i) {
331            *slot = byte;
332        }
333    }
334    if stack_cap == max_len {
335        return None; // no NUL within cap
336    }
337
338    // Longer path: fall back to heap.
339    let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
340    if let Some(prefix) = stack.get(..stack_cap) {
341        buf.extend_from_slice(prefix);
342    }
343    for i in stack_cap..max_len {
344        let byte = unsafe { *base_ptr.wrapping_add(i) };
345        if byte == 0 {
346            return Some(f(&buf));
347        }
348        buf.push(byte);
349    }
350    None
351}
352
353#[cfg(test)]
354#[allow(clippy::expect_used)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn absolute_under_bottle() {
360        let root = Path::new("/opt/bottle");
361        let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
362            .expect("translate absolute");
363        assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
364    }
365
366    #[test]
367    fn relative_under_bottle() {
368        let root = Path::new("/opt/bottle");
369        let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
370        assert_eq!(host, PathBuf::from("/opt/bottle/tmp/x"));
371    }
372
373    #[test]
374    fn no_bottle_passthrough() {
375        let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
376        assert_eq!(host, PathBuf::from("/tmp/foo"));
377    }
378
379    #[test]
380    fn rejects_parent_dir() {
381        let root = Path::new("/opt/bottle");
382        let err =
383            translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
384        assert!(matches!(err, PathError::Escape(_)));
385    }
386
387    #[test]
388    fn empty_rejected() {
389        assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
390    }
391
392    #[test]
393    fn volumes_linux_short_circuits_to_host_root() {
394        let root = Path::new("/var/lib/my-renamed-bottle");
395        let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
396            .expect("translate volumes");
397        assert_eq!(host, PathBuf::from("/tmp/x"));
398    }
399
400    #[test]
401    fn volumes_linux_root_only() {
402        let host = translate_path_with_root(Some(Path::new("/b")), "/Volumes/linux")
403            .expect("volumes root");
404        assert_eq!(host, PathBuf::from("/"));
405    }
406
407    #[test]
408    fn volumes_linux_rejects_parent() {
409        let err = translate_path_with_root(Some(Path::new("/b")), "/Volumes/linux/../etc")
410            .expect_err("escape");
411        assert!(matches!(err, PathError::Escape(_)));
412    }
413
414    #[test]
415    fn fast_path_dots_in_name_ok() {
416        let root = Path::new("/b");
417        let host = translate_path_with_root(Some(root), "/foo..bar").expect("dots in name");
418        assert_eq!(host, PathBuf::from("/b/foo..bar"));
419    }
420
421    #[test]
422    fn cstr_join_matches_pathbuf() {
423        let root = Path::new("/opt/bottle");
424        let mut buf = [0_u8; 256];
425        let c = translate_path_cstr_with_root(Some(root), "/usr/lib/x", &mut buf).expect("cstr");
426        assert_eq!(c.to_bytes(), b"/opt/bottle/usr/lib/x");
427    }
428
429    #[test]
430    fn cstr_volumes_linux() {
431        let mut buf = [0_u8; 64];
432        let c = translate_path_cstr_with_root(Some(Path::new("/b")), "/Volumes/linux/tmp/a", &mut buf)
433            .expect("cstr");
434        assert_eq!(c.to_bytes(), b"/tmp/a");
435    }
436}