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    // Host bridge prefixes: do **not** walk through bottle symlinks. Apple git
66    // realpath's `/Volumes/linux/tmp/…` via `readlink` → `/tmp/…`; that must still
67    // hit the host FS, not bottle `private/tmp`.
68    if let Some(host) = host_bridge_guest_to_host(guest)? {
69        return Ok(host);
70    }
71
72    // Fast path: no `..` and no empty components → strip leading slashes / `.`
73    // without allocating intermediate PathBufs for each component.
74    if let Some(rel) = try_fast_relative(guest) {
75        return match root {
76            Some(r) => {
77                let mut out = PathBuf::with_capacity(
78                    r.as_os_str()
79                        .len()
80                        .saturating_add(rel.len())
81                        .saturating_add(1),
82                );
83                out.push(r);
84                if !rel.is_empty() {
85                    out.push(rel);
86                }
87                Ok(out)
88            }
89            None => Ok(PathBuf::from(guest)),
90        };
91    }
92
93    let guest_path = Path::new(guest);
94    let relative = strip_root_components(guest_path)?;
95
96    match root {
97        Some(r) => {
98            let mut out = r.to_path_buf();
99            out.push(relative);
100            Ok(out)
101        }
102        None => Ok(guest_path.to_path_buf()),
103    }
104}
105
106/// Map guest bridge paths to host absolute paths (no bottle join).
107///
108/// | Guest | Host |
109/// | --- | --- |
110/// | `/Volumes/linux` + rest | `/` + rest |
111/// | `/tmp` + rest | `/tmp` + rest |
112/// | `/private/tmp` + rest | `/tmp` + rest (Darwin layout) |
113fn host_bridge_guest_to_host(guest: &str) -> Result<Option<PathBuf>, PathError> {
114    const VOL: &str = "/Volumes/linux";
115    if guest == VOL || guest.starts_with("/Volumes/linux/") {
116        let rest = guest.strip_prefix(VOL).unwrap_or("");
117        // Reject `..` in the host-relative rest.
118        let host = if rest.is_empty() {
119            PathBuf::from("/")
120        } else {
121            strip_root_components(Path::new(rest))?;
122            PathBuf::from(rest)
123        };
124        return Ok(Some(host));
125    }
126    if guest == "/private/tmp" || guest.starts_with("/private/tmp/") {
127        let rest = guest.strip_prefix("/private/tmp").unwrap_or("");
128        let host = if rest.is_empty() {
129            PathBuf::from("/tmp")
130        } else {
131            strip_root_components(Path::new(rest))?;
132            PathBuf::from(format!("/tmp{rest}"))
133        };
134        return Ok(Some(host));
135    }
136    if guest == "/tmp" || guest.starts_with("/tmp/") {
137        strip_root_components(Path::new(guest))?;
138        return Ok(Some(PathBuf::from(guest)));
139    }
140    Ok(None)
141}
142
143/// Bottle-relative openat target for an absolute guest path (B1).
144///
145/// When `Some((dirfd, rel))`, callers should `openat`/`fstatat` with `rel`
146/// (`"."` when the guest path is `/`) instead of allocating `{root}/{rel}`.
147/// Host-bridge paths (`/Volumes/linux`, `/tmp`, `/private/tmp`) return `None`
148/// so callers use [`translate_path`] instead.
149#[must_use]
150pub fn bottle_openat_rel(guest: &str) -> Option<(std::os::fd::RawFd, &str)> {
151    if !guest.starts_with('/') {
152        return None;
153    }
154    if host_bridge_guest_to_host(guest).ok().flatten().is_some() {
155        return None;
156    }
157    let dirfd = process::bottle_dirfd()?;
158    let rel = try_fast_relative(guest)?;
159    Some((dirfd, if rel.is_empty() { "." } else { rel }))
160}
161
162/// Returns stripped relative guest path when it has no `..` (and no empty segs).
163///
164/// `None` means fall back to the full component walker.
165fn try_fast_relative(guest: &str) -> Option<&str> {
166    if guest.contains("..") {
167        // May be `foo..bar` (ok) or `../x` / `a/../b` — let the slow path decide.
168        if guest == ".."
169            || guest.starts_with("../")
170            || guest.ends_with("/..")
171            || guest.contains("/../")
172        {
173            return None;
174        }
175    }
176    let mut s = guest;
177    while let Some(rest) = s.strip_prefix('/') {
178        s = rest;
179    }
180    // Drop a single leading "./"
181    if let Some(rest) = s.strip_prefix("./") {
182        s = rest;
183    }
184    // Reject remaining "./" or empty segments that need normalization.
185    if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
186        return None;
187    }
188    Some(s)
189}
190
191/// Strips leading `/` (and Windows-style prefixes if any) and rejects `..`.
192fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
193    let mut out = PathBuf::new();
194    for comp in path.components() {
195        match comp {
196            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
197            Component::ParentDir => {
198                return Err(PathError::Escape(path.display().to_string()));
199            }
200            Component::Normal(s) => out.push(s),
201        }
202    }
203    Ok(out)
204}
205
206/// Guest absolute path for the host process CWD.
207///
208/// * Host under bottle → bottle-relative absolute (`/usr/…`).
209/// * Host under `/tmp` → Darwin-style `/private/tmp/…` (bridged to host `/tmp`).
210/// * Else → `/Volumes/linux` + host absolute (bridged to host).
211#[must_use]
212pub fn guest_cwd_string() -> Option<String> {
213    let host = std::env::current_dir().ok()?;
214    host_path_to_guest(&host)
215}
216
217/// Maps an absolute host path to a guest absolute path (bottle or host bridge).
218#[must_use]
219pub fn host_path_to_guest(host: &Path) -> Option<String> {
220    let host_abs = if host.is_absolute() {
221        host.to_path_buf()
222    } else {
223        std::env::current_dir().ok()?.join(host)
224    };
225    // Prefer real paths so strip_prefix works across symlinks.
226    let host_real = host_abs.canonicalize().unwrap_or(host_abs);
227
228    if let Some(root) = bottle_root() {
229        let root_real = root.canonicalize().unwrap_or(root);
230        if let Ok(rel) = host_real.strip_prefix(&root_real) {
231            if rel.as_os_str().is_empty() {
232                return Some("/".to_owned());
233            }
234            let mut s = String::from("/");
235            s.push_str(&rel.to_string_lossy());
236            return Some(s.replace('\\', "/"));
237        }
238    }
239
240    let lossy = host_real.to_string_lossy();
241    // Prefer Darwin `/private/tmp` for host `/tmp` so realpath/readlink walks
242    // stay on the host bridge (see [`host_bridge_guest_to_host`]).
243    if lossy == "/tmp" {
244        return Some("/private/tmp".to_owned());
245    }
246    if let Some(rest) = lossy.strip_prefix("/tmp/") {
247        return Some(format!("/private/tmp/{rest}"));
248    }
249    if lossy == "/" {
250        return Some(format!("/{}", super::layout::VOLUMES_LINUX));
251    }
252    Some(format!("/{}{lossy}", super::layout::VOLUMES_LINUX).replace('\\', "/"))
253}
254
255/// Stack buffer size for typical guest paths (avoids heap on open/stat).
256const PATH_STACK: usize = 512;
257
258/// Reads a NUL-terminated C string from an identity-mapped guest pointer.
259///
260/// Used by `open` / `access` handlers. Caps length to avoid runaway scans.
261#[must_use]
262#[allow(unsafe_code)]
263pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
264    if ptr == 0 || max_len == 0 {
265        return None;
266    }
267    let base = usize::try_from(ptr).ok()?;
268    let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
269
270    let mut stack = [0_u8; PATH_STACK];
271    let stack_cap = PATH_STACK.min(max_len);
272    for i in 0..stack_cap {
273        // SAFETY: identity map — guest VA == host VA for mapped pages.
274        let byte = unsafe { *base_ptr.wrapping_add(i) };
275        if byte == 0 {
276            return stack
277                .get(..i)
278                .and_then(|s| std::str::from_utf8(s).ok())
279                .map(str::to_owned);
280        }
281        if let Some(slot) = stack.get_mut(i) {
282            *slot = byte;
283        }
284    }
285    if stack_cap == max_len {
286        return None; // no NUL within cap
287    }
288
289    // Longer path: fall back to heap.
290    let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
291    if let Some(prefix) = stack.get(..stack_cap) {
292        buf.extend_from_slice(prefix);
293    }
294    for i in stack_cap..max_len {
295        let byte = unsafe { *base_ptr.wrapping_add(i) };
296        if byte == 0 {
297            return String::from_utf8(buf).ok();
298        }
299        buf.push(byte);
300    }
301    None
302}
303
304#[cfg(test)]
305#[allow(clippy::expect_used)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn absolute_under_bottle() {
311        let root = Path::new("/opt/bottle");
312        let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
313            .expect("translate absolute");
314        assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
315    }
316
317    #[test]
318    fn relative_stays_host_cwd_even_with_bottle() {
319        let root = Path::new("/opt/bottle");
320        let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
321        assert_eq!(host, PathBuf::from("tmp/x"));
322    }
323
324    #[test]
325    fn relative_rejects_dotdot() {
326        let root = Path::new("/opt/bottle");
327        let err = translate_path_with_root(Some(root), "../etc/passwd").expect_err("..");
328        assert!(matches!(err, PathError::Escape(_)));
329    }
330
331    #[test]
332    fn no_bottle_passthrough() {
333        let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
334        assert_eq!(host, PathBuf::from("/tmp/foo"));
335    }
336
337    #[test]
338    fn rejects_parent_dir() {
339        let root = Path::new("/opt/bottle");
340        let err =
341            translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
342        assert!(matches!(err, PathError::Escape(_)));
343    }
344
345    #[test]
346    fn empty_rejected() {
347        assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
348    }
349
350    #[test]
351    fn volumes_linux_is_host_bridge_not_bottle_join() {
352        let root = Path::new("/var/lib/my-renamed-bottle");
353        let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
354            .expect("translate volumes");
355        assert_eq!(host, PathBuf::from("/tmp/x"));
356    }
357
358    #[test]
359    fn fast_path_dots_in_name_ok() {
360        let root = Path::new("/b");
361        let host = translate_path_with_root(Some(root), "/foo..bar").expect("dots in name");
362        assert_eq!(host, PathBuf::from("/b/foo..bar"));
363    }
364
365    #[test]
366    fn host_tmp_maps_to_private_tmp_guest() {
367        set_bottle_root(None);
368        let guest = host_path_to_guest(Path::new("/tmp/kh-guest-cwd-test")).expect("map");
369        assert_eq!(guest, "/private/tmp/kh-guest-cwd-test");
370    }
371
372    #[test]
373    fn bridge_private_tmp_to_host() {
374        let host = translate_path_with_root(Some(Path::new("/opt/bottle")), "/private/tmp/x")
375            .expect("bridge");
376        assert_eq!(host, PathBuf::from("/tmp/x"));
377    }
378
379    #[test]
380    fn bridge_volumes_linux_to_host() {
381        let host = translate_path_with_root(Some(Path::new("/opt/bottle")), "/Volumes/linux/home/a")
382            .expect("bridge");
383        assert_eq!(host, PathBuf::from("/home/a"));
384    }
385
386    #[test]
387    fn bottle_openat_rel_uses_dirfd_when_configured() {
388        let tmp = std::env::temp_dir().join(format!(
389            "kh-b1-openat-{}",
390            std::process::id()
391        ));
392        drop(std::fs::remove_dir_all(&tmp));
393        std::fs::create_dir_all(tmp.join("usr/lib")).expect("mkdir");
394        set_bottle_root(Some(tmp.clone()));
395        let (fd, rel) = bottle_openat_rel("/usr/lib/libSystem.B.dylib").expect("openat parts");
396        assert!(fd >= 0);
397        assert_eq!(rel, "usr/lib/libSystem.B.dylib");
398        assert!(bottle_openat_rel("relative").is_none());
399        set_bottle_root(None);
400        assert!(bottle_openat_rel("/usr/lib/x").is_none());
401        drop(std::fs::remove_dir_all(&tmp));
402    }
403}