add PathBuf resolved validation

This commit is contained in:
yggverse 2025-08-03 14:10:06 +03:00
parent 66c9e35481
commit 422ee62c3d

View file

@ -3,7 +3,7 @@ use std::{fs, path::PathBuf};
/// Temporary file storage for `librqbit` preload data /// Temporary file storage for `librqbit` preload data
pub struct Preload { pub struct Preload {
directory: PathBuf, root: PathBuf,
pub max_filecount: Option<usize>, pub max_filecount: Option<usize>,
pub max_filesize: Option<u64>, pub max_filesize: Option<u64>,
} }
@ -20,21 +20,17 @@ impl Preload {
Ok(Self { Ok(Self {
max_filecount, max_filecount,
max_filesize, max_filesize,
directory, root: directory.canonicalize()?,
}) })
} }
pub fn clear_output_folder(&self, info_hash: &str) -> Result<()> { pub fn clear_output_folder(&self, info_hash: &str) -> Result<()> {
let mut p = PathBuf::from(&self.directory); Ok(fs::remove_dir_all(&self.path(&PathBuf::from(info_hash))?)?)
p.push(info_hash);
fs::remove_dir_all(&p)?;
Ok(())
} }
/// * create new directory if not exists /// * create new directory if not exists
pub fn output_folder(&self, info_hash: &str) -> Result<PathBuf> { pub fn output_folder(&self, info_hash: &str) -> Result<PathBuf> {
let mut p = PathBuf::from(&self.directory); let p = self.path(&PathBuf::from(info_hash))?;
p.push(info_hash);
if !p.exists() { if !p.exists() {
fs::create_dir(&p)? fs::create_dir(&p)?
} }
@ -42,14 +38,22 @@ impl Preload {
} }
pub fn root(&self) -> PathBuf { pub fn root(&self) -> PathBuf {
self.directory.clone() self.root.clone()
} }
pub fn bytes(&self, path: &PathBuf) -> Result<Vec<u8>> { pub fn bytes(&self, relative: &PathBuf) -> Result<Vec<u8>> {
Ok(std::fs::read({ Ok(std::fs::read(self.path(relative)?)?)
let mut p = PathBuf::from(&self.directory); }
p.push(path);
p fn path(&self, relative: &PathBuf) -> Result<PathBuf> {
})?) let mut p = PathBuf::from(&self.root);
p.push(relative);
if p.canonicalize()?.starts_with(&self.root) {
bail!(
"Unexpected absolute path resolved for `{}`!",
p.to_string_lossy()
)
}
Ok(p)
} }
} }