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}/{relative}`
44/// * Absolute guest path, no bottle → host absolute path as-is
45/// * Relative guest path + bottle → `{root}/{relative}`
46/// * Relative guest path, no bottle → host-relative path as-is
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    // Fast path: no `..` and no empty components → strip leading slashes / `.`
59    // without allocating intermediate PathBufs for each component.
60    if let Some(rel) = try_fast_relative(guest) {
61        return match root {
62            Some(r) => {
63                let mut out = PathBuf::with_capacity(r.as_os_str().len().saturating_add(rel.len()).saturating_add(1));
64                out.push(r);
65                if !rel.is_empty() {
66                    out.push(rel);
67                }
68                Ok(out)
69            }
70            None => Ok(PathBuf::from(guest)),
71        };
72    }
73
74    let guest_path = Path::new(guest);
75    let relative = strip_root_components(guest_path)?;
76
77    match root {
78        Some(r) => {
79            let mut out = r.to_path_buf();
80            out.push(relative);
81            Ok(out)
82        }
83        None => Ok(guest_path.to_path_buf()),
84    }
85}
86
87/// Returns stripped relative guest path when it has no `..` (and no empty segs).
88///
89/// `None` means fall back to the full component walker.
90fn try_fast_relative(guest: &str) -> Option<&str> {
91    if guest.contains("..") {
92        // May be `foo..bar` (ok) or `../x` / `a/../b` — let the slow path decide.
93        if guest == ".."
94            || guest.starts_with("../")
95            || guest.ends_with("/..")
96            || guest.contains("/../")
97        {
98            return None;
99        }
100    }
101    let mut s = guest;
102    while let Some(rest) = s.strip_prefix('/') {
103        s = rest;
104    }
105    // Drop a single leading "./"
106    if let Some(rest) = s.strip_prefix("./") {
107        s = rest;
108    }
109    // Reject remaining "./" or empty segments that need normalization.
110    if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
111        return None;
112    }
113    Some(s)
114}
115
116/// Strips leading `/` (and Windows-style prefixes if any) and rejects `..`.
117fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
118    let mut out = PathBuf::new();
119    for comp in path.components() {
120        match comp {
121            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
122            Component::ParentDir => {
123                return Err(PathError::Escape(path.display().to_string()));
124            }
125            Component::Normal(s) => out.push(s),
126        }
127    }
128    Ok(out)
129}
130
131/// Stack buffer size for typical guest paths (avoids heap on open/stat).
132const PATH_STACK: usize = 512;
133
134/// Reads a NUL-terminated C string from an identity-mapped guest pointer.
135///
136/// Used by `open` / `access` handlers. Caps length to avoid runaway scans.
137#[must_use]
138#[allow(unsafe_code)]
139pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
140    if ptr == 0 || max_len == 0 {
141        return None;
142    }
143    let base = usize::try_from(ptr).ok()?;
144    let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
145
146    let mut stack = [0_u8; PATH_STACK];
147    let stack_cap = PATH_STACK.min(max_len);
148    for i in 0..stack_cap {
149        // SAFETY: identity map — guest VA == host VA for mapped pages.
150        let byte = unsafe { *base_ptr.wrapping_add(i) };
151        if byte == 0 {
152            return stack.get(..i).and_then(|s| std::str::from_utf8(s).ok()).map(str::to_owned);
153        }
154        if let Some(slot) = stack.get_mut(i) {
155            *slot = byte;
156        }
157    }
158    if stack_cap == max_len {
159        return None; // no NUL within cap
160    }
161
162    // Longer path: fall back to heap.
163    let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
164    if let Some(prefix) = stack.get(..stack_cap) {
165        buf.extend_from_slice(prefix);
166    }
167    for i in stack_cap..max_len {
168        let byte = unsafe { *base_ptr.wrapping_add(i) };
169        if byte == 0 {
170            return String::from_utf8(buf).ok();
171        }
172        buf.push(byte);
173    }
174    None
175}
176
177#[cfg(test)]
178#[allow(clippy::expect_used)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn absolute_under_bottle() {
184        let root = Path::new("/opt/bottle");
185        let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
186            .expect("translate absolute");
187        assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
188    }
189
190    #[test]
191    fn relative_under_bottle() {
192        let root = Path::new("/opt/bottle");
193        let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
194        assert_eq!(host, PathBuf::from("/opt/bottle/tmp/x"));
195    }
196
197    #[test]
198    fn no_bottle_passthrough() {
199        let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
200        assert_eq!(host, PathBuf::from("/tmp/foo"));
201    }
202
203    #[test]
204    fn rejects_parent_dir() {
205        let root = Path::new("/opt/bottle");
206        let err =
207            translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
208        assert!(matches!(err, PathError::Escape(_)));
209    }
210
211    #[test]
212    fn empty_rejected() {
213        assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
214    }
215
216    #[test]
217    fn volumes_linux_under_bottle() {
218        let root = Path::new("/var/lib/my-renamed-bottle");
219        let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
220            .expect("translate volumes");
221        assert_eq!(
222            host,
223            PathBuf::from("/var/lib/my-renamed-bottle/Volumes/linux/tmp/x")
224        );
225    }
226
227    #[test]
228    fn fast_path_dots_in_name_ok() {
229        let root = Path::new("/b");
230        let host = translate_path_with_root(Some(root), "/foo..bar")
231            .expect("dots in name");
232        assert_eq!(host, PathBuf::from("/b/foo..bar"));
233    }
234}