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
99fn try_fast_relative(guest: &str) -> Option<&str> {
103 if guest.contains("..") {
104 if guest == ".."
106 || guest.starts_with("../")
107 || guest.ends_with("/..")
108 || guest.contains("/../")
109 {
110 return None;
111 }
112 }
113 let mut s = guest;
114 while let Some(rest) = s.strip_prefix('/') {
115 s = rest;
116 }
117 if let Some(rest) = s.strip_prefix("./") {
119 s = rest;
120 }
121 if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
123 return None;
124 }
125 Some(s)
126}
127
128fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
130 let mut out = PathBuf::new();
131 for comp in path.components() {
132 match comp {
133 Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
134 Component::ParentDir => {
135 return Err(PathError::Escape(path.display().to_string()));
136 }
137 Component::Normal(s) => out.push(s),
138 }
139 }
140 Ok(out)
141}
142
143const PATH_STACK: usize = 512;
145
146#[must_use]
150#[allow(unsafe_code)]
151pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
152 if ptr == 0 || max_len == 0 {
153 return None;
154 }
155 let base = usize::try_from(ptr).ok()?;
156 let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
157
158 let mut stack = [0_u8; PATH_STACK];
159 let stack_cap = PATH_STACK.min(max_len);
160 for i in 0..stack_cap {
161 let byte = unsafe { *base_ptr.wrapping_add(i) };
163 if byte == 0 {
164 return stack.get(..i).and_then(|s| std::str::from_utf8(s).ok()).map(str::to_owned);
165 }
166 if let Some(slot) = stack.get_mut(i) {
167 *slot = byte;
168 }
169 }
170 if stack_cap == max_len {
171 return None; }
173
174 let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
176 if let Some(prefix) = stack.get(..stack_cap) {
177 buf.extend_from_slice(prefix);
178 }
179 for i in stack_cap..max_len {
180 let byte = unsafe { *base_ptr.wrapping_add(i) };
181 if byte == 0 {
182 return String::from_utf8(buf).ok();
183 }
184 buf.push(byte);
185 }
186 None
187}
188
189#[cfg(test)]
190#[allow(clippy::expect_used)]
191mod tests {
192 use super::*;
193
194 #[test]
195 fn absolute_under_bottle() {
196 let root = Path::new("/opt/bottle");
197 let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
198 .expect("translate absolute");
199 assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
200 }
201
202 #[test]
203 fn relative_stays_host_cwd_even_with_bottle() {
204 let root = Path::new("/opt/bottle");
205 let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
206 assert_eq!(host, PathBuf::from("tmp/x"));
207 }
208
209 #[test]
210 fn relative_rejects_dotdot() {
211 let root = Path::new("/opt/bottle");
212 let err = translate_path_with_root(Some(root), "../etc/passwd").expect_err("..");
213 assert!(matches!(err, PathError::Escape(_)));
214 }
215
216 #[test]
217 fn no_bottle_passthrough() {
218 let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
219 assert_eq!(host, PathBuf::from("/tmp/foo"));
220 }
221
222 #[test]
223 fn rejects_parent_dir() {
224 let root = Path::new("/opt/bottle");
225 let err =
226 translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
227 assert!(matches!(err, PathError::Escape(_)));
228 }
229
230 #[test]
231 fn empty_rejected() {
232 assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
233 }
234
235 #[test]
236 fn volumes_linux_under_bottle() {
237 let root = Path::new("/var/lib/my-renamed-bottle");
238 let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
239 .expect("translate volumes");
240 assert_eq!(
241 host,
242 PathBuf::from("/var/lib/my-renamed-bottle/Volumes/linux/tmp/x")
243 );
244 }
245
246 #[test]
247 fn fast_path_dots_in_name_ok() {
248 let root = Path::new("/b");
249 let host = translate_path_with_root(Some(root), "/foo..bar")
250 .expect("dots in name");
251 assert_eq!(host, PathBuf::from("/b/foo..bar"));
252 }
253}