use std::ffi::CStr;
use std::path::{Component, Path, PathBuf};
use thiserror::Error;
use crate::process;
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum PathError {
#[error("empty guest path")]
Empty,
#[error("guest path escapes bottle: {0}")]
Escape(String),
#[error("invalid path encoding")]
InvalidEncoding,
#[error("path too long for buffer")]
TooLong,
}
pub fn set_bottle_root(root: Option<PathBuf>) {
process::set_bottle_root(root);
}
#[must_use]
pub fn bottle_root() -> Option<PathBuf> {
process::bottle_root()
}
const VOLUMES_LINUX: &str = "Volumes/linux";
pub fn translate_path(guest: &str) -> Result<PathBuf, PathError> {
process::with_bottle_root(|root| translate_path_with_root(root, guest))
}
pub fn translate_path_with_root(root: Option<&Path>, guest: &str) -> Result<PathBuf, PathError> {
if guest.is_empty() {
return Err(PathError::Empty);
}
if let Some(host) = try_volumes_linux(guest)? {
return Ok(host);
}
if let Some(rel) = try_fast_relative(guest) {
return match root {
Some(r) => {
let mut out = PathBuf::with_capacity(
r.as_os_str()
.len()
.saturating_add(rel.len())
.saturating_add(1),
);
out.push(r);
if !rel.is_empty() {
out.push(rel);
}
Ok(out)
}
None => Ok(PathBuf::from(guest)),
};
}
let guest_path = Path::new(guest);
let relative = strip_root_components(guest_path)?;
match root {
Some(r) => {
let mut out = r.to_path_buf();
out.push(relative);
Ok(out)
}
None => Ok(guest_path.to_path_buf()),
}
}
pub fn translate_path_cstr<'a>(
guest: &str,
out: &'a mut [u8],
) -> Result<&'a CStr, PathError> {
process::with_bottle_root(|root| translate_path_cstr_with_root(root, guest, out))
}
pub fn translate_path_cstr_with_root<'a>(
root: Option<&Path>,
guest: &str,
out: &'a mut [u8],
) -> Result<&'a CStr, PathError> {
if guest.is_empty() {
return Err(PathError::Empty);
}
if out.len() < 2 {
return Err(PathError::TooLong);
}
if let Some(host) = try_volumes_linux(guest)? {
return write_path_cstr(&host, out);
}
if let Some(rel) = try_fast_relative(guest) {
return match root {
Some(r) => join_root_rel_cstr(r, rel, out),
None => write_bytes_cstr(guest.as_bytes(), out),
};
}
let host = translate_path_with_root(root, guest)?;
write_path_cstr(&host, out)
}
fn try_volumes_linux(guest: &str) -> Result<Option<PathBuf>, PathError> {
let rest = if guest == "/Volumes/linux" || guest == VOLUMES_LINUX {
""
} else if let Some(r) = guest.strip_prefix("/Volumes/linux/") {
r
} else if let Some(r) = guest.strip_prefix("Volumes/linux/") {
r
} else {
return Ok(None);
};
if let Some(rel) = try_fast_relative(rest) {
if rel.is_empty() {
return Ok(Some(PathBuf::from("/")));
}
let mut out = PathBuf::from("/");
out.push(rel);
return Ok(Some(out));
}
let relative = strip_root_components(Path::new(rest))?;
if relative.as_os_str().is_empty() {
return Ok(Some(PathBuf::from("/")));
}
let mut out = PathBuf::from("/");
out.push(relative);
Ok(Some(out))
}
fn join_root_rel_cstr<'a>(
root: &Path,
rel: &str,
out: &'a mut [u8],
) -> Result<&'a CStr, PathError> {
let root_bytes = root.as_os_str().as_encoded_bytes();
let need = root_bytes
.len()
.saturating_add(if rel.is_empty() { 0 } else { rel.len().saturating_add(1) })
.saturating_add(1);
if need > out.len() {
return Err(PathError::TooLong);
}
let mut n = 0_usize;
if let Some(dst) = out.get_mut(..root_bytes.len()) {
dst.copy_from_slice(root_bytes);
n = root_bytes.len();
}
if !rel.is_empty() {
let need_sep = !root_bytes.ends_with(b"/");
if need_sep
&& let Some(slot) = out.get_mut(n)
{
*slot = b'/';
n = n.saturating_add(1);
}
if let Some(dst) = out.get_mut(n..n.saturating_add(rel.len())) {
dst.copy_from_slice(rel.as_bytes());
n = n.saturating_add(rel.len());
}
}
if let Some(slot) = out.get_mut(n) {
*slot = 0;
} else {
return Err(PathError::TooLong);
}
let Some(with_nul) = out.get(..n.saturating_add(1)) else {
return Err(PathError::TooLong);
};
CStr::from_bytes_with_nul(with_nul).map_err(|_| PathError::InvalidEncoding)
}
fn write_path_cstr<'a>(path: &Path, out: &'a mut [u8]) -> Result<&'a CStr, PathError> {
write_bytes_cstr(path.as_os_str().as_encoded_bytes(), out)
}
fn write_bytes_cstr<'a>(bytes: &[u8], out: &'a mut [u8]) -> Result<&'a CStr, PathError> {
if bytes.contains(&0) {
return Err(PathError::InvalidEncoding);
}
let need = bytes.len().saturating_add(1);
if need > out.len() {
return Err(PathError::TooLong);
}
if let Some(dst) = out.get_mut(..bytes.len()) {
dst.copy_from_slice(bytes);
}
if let Some(slot) = out.get_mut(bytes.len()) {
*slot = 0;
}
let Some(with_nul) = out.get(..bytes.len().saturating_add(1)) else {
return Err(PathError::TooLong);
};
CStr::from_bytes_with_nul(with_nul).map_err(|_| PathError::InvalidEncoding)
}
fn try_fast_relative(guest: &str) -> Option<&str> {
if guest.contains("..") {
if guest == ".."
|| guest.starts_with("../")
|| guest.ends_with("/..")
|| guest.contains("/../")
{
return None;
}
}
let mut s = guest;
while let Some(rest) = s.strip_prefix('/') {
s = rest;
}
if let Some(rest) = s.strip_prefix("./") {
s = rest;
}
if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
return None;
}
Some(s)
}
fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
Component::ParentDir => {
return Err(PathError::Escape(path.display().to_string()));
}
Component::Normal(s) => out.push(s),
}
}
Ok(out)
}
const PATH_STACK: usize = 512;
pub const HOST_PATH_STACK: usize = 1024;
#[must_use]
#[allow(unsafe_code)]
pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
with_guest_path_bytes(ptr, max_len, |bytes| {
std::str::from_utf8(bytes).ok().map(str::to_owned)
})?
}
#[must_use]
#[allow(unsafe_code)]
pub fn with_guest_path_bytes<R>(
ptr: u64,
max_len: usize,
f: impl FnOnce(&[u8]) -> R,
) -> Option<R> {
if ptr == 0 || max_len == 0 {
return None;
}
let base = usize::try_from(ptr).ok()?;
let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
let mut stack = [0_u8; PATH_STACK];
let stack_cap = PATH_STACK.min(max_len);
for i in 0..stack_cap {
let byte = unsafe { *base_ptr.wrapping_add(i) };
if byte == 0 {
let slice = stack.get(..i)?;
return Some(f(slice));
}
if let Some(slot) = stack.get_mut(i) {
*slot = byte;
}
}
if stack_cap == max_len {
return None; }
let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
if let Some(prefix) = stack.get(..stack_cap) {
buf.extend_from_slice(prefix);
}
for i in stack_cap..max_len {
let byte = unsafe { *base_ptr.wrapping_add(i) };
if byte == 0 {
return Some(f(&buf));
}
buf.push(byte);
}
None
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn absolute_under_bottle() {
let root = Path::new("/opt/bottle");
let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
.expect("translate absolute");
assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
}
#[test]
fn relative_under_bottle() {
let root = Path::new("/opt/bottle");
let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
assert_eq!(host, PathBuf::from("/opt/bottle/tmp/x"));
}
#[test]
fn no_bottle_passthrough() {
let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
assert_eq!(host, PathBuf::from("/tmp/foo"));
}
#[test]
fn rejects_parent_dir() {
let root = Path::new("/opt/bottle");
let err =
translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
assert!(matches!(err, PathError::Escape(_)));
}
#[test]
fn empty_rejected() {
assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
}
#[test]
fn volumes_linux_short_circuits_to_host_root() {
let root = Path::new("/var/lib/my-renamed-bottle");
let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
.expect("translate volumes");
assert_eq!(host, PathBuf::from("/tmp/x"));
}
#[test]
fn volumes_linux_root_only() {
let host = translate_path_with_root(Some(Path::new("/b")), "/Volumes/linux")
.expect("volumes root");
assert_eq!(host, PathBuf::from("/"));
}
#[test]
fn volumes_linux_rejects_parent() {
let err = translate_path_with_root(Some(Path::new("/b")), "/Volumes/linux/../etc")
.expect_err("escape");
assert!(matches!(err, PathError::Escape(_)));
}
#[test]
fn fast_path_dots_in_name_ok() {
let root = Path::new("/b");
let host = translate_path_with_root(Some(root), "/foo..bar").expect("dots in name");
assert_eq!(host, PathBuf::from("/b/foo..bar"));
}
#[test]
fn cstr_join_matches_pathbuf() {
let root = Path::new("/opt/bottle");
let mut buf = [0_u8; 256];
let c = translate_path_cstr_with_root(Some(root), "/usr/lib/x", &mut buf).expect("cstr");
assert_eq!(c.to_bytes(), b"/opt/bottle/usr/lib/x");
}
#[test]
fn cstr_volumes_linux() {
let mut buf = [0_u8; 64];
let c = translate_path_cstr_with_root(Some(Path::new("/b")), "/Volumes/linux/tmp/a", &mut buf)
.expect("cstr");
assert_eq!(c.to_bytes(), b"/tmp/a");
}
}