kh_runtime/bottle/
path.rs1use std::path::{Component, Path, PathBuf};
7
8use thiserror::Error;
9
10use crate::process;
11
12#[derive(Debug, Error, Clone, PartialEq, Eq)]
14pub enum PathError {
15 #[error("empty guest path")]
17 Empty,
18
19 #[error("guest path escapes bottle: {0}")]
21 Escape(String),
22
23 #[error("invalid path encoding")]
25 InvalidEncoding,
26}
27
28pub fn set_bottle_root(root: Option<PathBuf>) {
32 process::set_bottle_root(root);
33}
34
35#[must_use]
37pub fn bottle_root() -> Option<PathBuf> {
38 process::bottle_root()
39}
40
41pub fn translate_path(guest: &str) -> Result<PathBuf, PathError> {
48 process::with_bottle_root(|root| translate_path_with_root(root, guest))
50}
51
52pub 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 if !guest.starts_with('/') {
60 strip_root_components(Path::new(guest))?;
62 return Ok(PathBuf::from(guest));
63 }
64
65 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#[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
113fn try_fast_relative(guest: &str) -> Option<&str> {
117 if guest.contains("..") {
118 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 if let Some(rest) = s.strip_prefix("./") {
133 s = rest;
134 }
135 if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
137 return None;
138 }
139 Some(s)
140}
141
142fn 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
157const PATH_STACK: usize = 512;
159
160#[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 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; }
190
191 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}