use std::fs::{File, Metadata};
use std::path::{Path, PathBuf};
use crate::error::StaticError;
pub(crate) struct ResolvedFile {
pub(crate) file: File,
pub(crate) metadata: Metadata,
pub(crate) path: PathBuf,
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
use std::os::fd::AsRawFd;
use std::os::unix::ffi::OsStrExt;
let mut buf = [0u8; libc::PATH_MAX as usize];
let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
if rc != 0 {
return Err(std::io::Error::last_os_error());
}
let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..len])))
}
#[cfg(target_os = "linux")]
fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
use std::os::fd::AsRawFd;
std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))
}
#[cfg_attr(
any(target_os = "macos", target_os = "ios", target_os = "linux"),
allow(dead_code)
)]
pub(crate) fn canonicalize_within_root(
root_canon: &Path,
joined: &Path,
) -> Result<PathBuf, StaticError> {
let canon = joined
.canonicalize()
.map_err(|_| StaticError::NotFound(joined.display().to_string()))?;
if canon.starts_with(root_canon) {
Ok(canon)
} else {
Err(StaticError::Traversal(joined.display().to_string()))
}
}
pub fn resolve_with_canonical_root(
root_canon: &Path,
request_path: &str,
) -> Result<PathBuf, StaticError> {
resolve_with_policy(root_canon, request_path, HiddenFiles::Deny)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HiddenFiles {
Deny,
Serve,
}
const WELL_KNOWN: &str = ".well-known";
fn has_hidden_segment(decoded: &str) -> bool {
decoded
.trim_start_matches('/')
.split('/')
.enumerate()
.any(|(index, segment)| {
let is_well_known_root = index == 0 && segment == WELL_KNOWN;
segment.starts_with('.') && segment != "." && !is_well_known_root
})
}
pub(crate) fn resolve_with_policy(
root_canon: &Path,
request_path: &str,
hidden: HiddenFiles,
) -> Result<PathBuf, StaticError> {
if request_path.contains('\0') {
return Err(StaticError::Traversal(request_path.to_string()));
}
let decoded = decode_request_path(request_path);
for segment in decoded.split('/') {
if segment == ".." {
return Err(StaticError::Traversal(request_path.to_string()));
}
}
if hidden == HiddenFiles::Deny && has_hidden_segment(&decoded) {
return Err(StaticError::NotFound(request_path.to_string()));
}
let stripped = decoded.trim_start_matches('/');
let joined = root_canon.join(stripped);
open_verified(root_canon, &joined, request_path).map(|resolved| resolved.path)
}
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
fn open_verified(
root_canon: &Path,
joined: &Path,
request_path: &str,
) -> Result<ResolvedFile, StaticError> {
let file = File::open(joined).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
let real = real_path_of(&file).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
if !real.starts_with(root_canon) {
return Err(StaticError::Traversal(request_path.to_string()));
}
let metadata = file
.metadata()
.map_err(|_| StaticError::NotFound(request_path.to_string()))?;
if metadata.is_dir() {
return open_verified(root_canon, &real.join("index.html"), request_path);
}
Ok(ResolvedFile {
file,
metadata,
path: real,
})
}
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
fn open_verified(
root_canon: &Path,
joined: &Path,
request_path: &str,
) -> Result<ResolvedFile, StaticError> {
let canon = canonicalize_within_root(root_canon, joined)?;
let target = if canon.is_dir() {
let index = canon.join("index.html");
canonicalize_within_root(root_canon, &index)?;
index
} else {
canon
};
let file = File::open(&target).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
let metadata = file
.metadata()
.map_err(|_| StaticError::NotFound(request_path.to_string()))?;
Ok(ResolvedFile {
file,
metadata,
path: target,
})
}
pub(crate) fn open_with_policy(
root_canon: &Path,
request_path: &str,
hidden: HiddenFiles,
) -> Result<ResolvedFile, StaticError> {
if request_path.contains('\0') {
return Err(StaticError::Traversal(request_path.to_string()));
}
let decoded = decode_request_path(request_path);
for segment in decoded.split('/') {
if segment == ".." {
return Err(StaticError::Traversal(request_path.to_string()));
}
}
if hidden == HiddenFiles::Deny && has_hidden_segment(&decoded) {
return Err(StaticError::NotFound(request_path.to_string()));
}
let stripped = decoded.trim_start_matches('/');
open_verified(root_canon, &root_canon.join(stripped), request_path)
}
pub(crate) fn decode_request_path(request_path: &str) -> String {
percent_encoding::percent_decode_str(request_path)
.decode_utf8()
.map(|s| s.to_string())
.unwrap_or_else(|_| request_path.to_string())
}
pub fn resolve(root: &Path, request_path: &str) -> Result<PathBuf, StaticError> {
let root_canon = root.canonicalize().map_err(StaticError::Io)?;
resolve_with_canonical_root(&root_canon, request_path)
}