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 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
87fn try_fast_relative(guest: &str) -> Option<&str> {
91 if guest.contains("..") {
92 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 if let Some(rest) = s.strip_prefix("./") {
107 s = rest;
108 }
109 if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
111 return None;
112 }
113 Some(s)
114}
115
116fn 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
131const PATH_STACK: usize = 512;
133
134#[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 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; }
161
162 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}