use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use crate::go_err::go_errno_text;
use crate::go_fmt::go_quote;
use crate::go_path::{
go_filepath_is_local, go_filepath_rel, go_path_clean, go_path_dir, go_path_join,
};
pub const ERR_NOT_VALID_RELATIVE_PATH: &str =
"path is not a relative path inside the base directory";
pub const ERR_SYMLINK_IN_RELATIVE_PATH: &str =
"path leads outside the base directory through a link";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SafeSubpathErrorKind {
NotValidRelativePath,
SymlinkInRelativePath,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SafeSubpathError {
kind: SafeSubpathErrorKind,
message: String,
}
impl SafeSubpathError {
fn not_valid(detail: &str) -> Self {
Self {
kind: SafeSubpathErrorKind::NotValidRelativePath,
message: format!("{ERR_NOT_VALID_RELATIVE_PATH}: {detail}"),
}
}
fn symlink(detail: &str) -> Self {
Self {
kind: SafeSubpathErrorKind::SymlinkInRelativePath,
message: format!("{ERR_SYMLINK_IN_RELATIVE_PATH}: {detail}"),
}
}
fn other(message: String) -> Self {
Self {
kind: SafeSubpathErrorKind::Other,
message,
}
}
pub fn kind(&self) -> SafeSubpathErrorKind {
self.kind
}
pub fn is_not_valid_relative_path(&self) -> bool {
self.kind == SafeSubpathErrorKind::NotValidRelativePath
}
pub fn is_symlink_in_relative_path(&self) -> bool {
self.kind == SafeSubpathErrorKind::SymlinkInRelativePath
}
}
impl fmt::Display for SafeSubpathError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for SafeSubpathError {}
pub fn safe_subpath(base: &Path, rel: &str) -> Result<(PathBuf, String), SafeSubpathError> {
let base = base.to_string_lossy();
if !base.starts_with('/') {
return Err(SafeSubpathError::other(
"base path is not absolute".to_owned(),
));
}
let abs_base = go_path_clean(&base);
if rel.is_empty() {
return Err(SafeSubpathError::not_valid("rel path is empty"));
}
if rel.contains('\0') {
return Err(SafeSubpathError::not_valid("rel path contains null byte"));
}
if !go_filepath_is_local(rel) {
return Err(SafeSubpathError::not_valid("rel path is not local"));
}
let res = go_path_join(&[abs_base.as_str(), rel]);
let r = go_filepath_rel(&abs_base, &res).map_err(|e| {
SafeSubpathError::not_valid(&format!("failed to compute relative path: {e}"))
})?;
if r == "." {
return Err(SafeSubpathError::not_valid("rel is effectively empty"));
}
if !go_filepath_is_local(&r) {
return Err(SafeSubpathError::not_valid("not a subpath"));
}
let real = resolve_inside(&abs_base, &res)?;
Ok((PathBuf::from(real), r))
}
fn resolve_inside(base: &str, target: &str) -> Result<String, SafeSubpathError> {
let real_base = follow_links(base)
.map_err(|e| SafeSubpathError::other(format!("cannot resolve links in base: {e}")))?;
let real_target = follow_links(target)
.map_err(|e| SafeSubpathError::other(format!("cannot resolve links: {e}")))?;
match go_filepath_rel(&real_base, &real_target) {
Ok(rel) if rel == "." || go_filepath_is_local(&rel) => Ok(real_target),
_ => Err(SafeSubpathError::symlink(&format!(
"it resolves to {}",
go_quote(&real_target)
))),
}
}
const MAX_LINK_FOLLOWS: usize = 255;
fn follow_links(p: &str) -> Result<String, String> {
let mut cur = "/".to_owned();
let mut rest: Vec<String> = p.trim_matches('/').split('/').map(str::to_owned).collect();
let mut follows = 0usize;
let mut i = 0usize;
while i < rest.len() {
let c = rest[i].clone();
match c.as_str() {
"" | "." => {
i += 1;
continue;
}
".." => {
cur = go_path_dir(&cur);
i += 1;
continue;
}
_ => {}
}
let next = go_path_join(&[cur.as_str(), c.as_str()]);
let meta = match std::fs::symlink_metadata(&next) {
Ok(meta) => meta,
Err(e)
if matches!(
e.kind(),
io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
) =>
{
cur = next;
i += 1;
continue;
}
Err(e) => return Err(format!("lstat {next}: {}", go_errno_text(&e))),
};
if !is_link_like(&meta.file_type()) {
cur = next;
i += 1;
continue;
}
let dest = match std::fs::read_link(&next) {
Ok(dest) => dest.to_string_lossy().into_owned(),
Err(_) => {
cur = next;
i += 1;
continue;
}
};
follows += 1;
if follows > MAX_LINK_FOLLOWS {
return Err(format!("too many links in {}", go_quote(p)));
}
if dest.starts_with('/') {
cur = "/".to_owned();
}
let mut spliced: Vec<String> = dest
.trim_matches('/')
.split('/')
.map(str::to_owned)
.collect();
spliced.extend(rest.drain(i + 1..));
rest = spliced;
i = 0;
}
Ok(go_path_clean(&cur))
}
pub fn is_link_like(file_type: &std::fs::FileType) -> bool {
file_type.is_symlink()
}