use std::fs::File as StdFile;
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
use tokio::fs::File as TokioFile;
use crate::error::{Error, Result};
use crate::security::paths::{ensure_path_within_root, join_under_root, sanitize_torrent_relative_path};
pub fn ensure_dir_under_root(root: &Path, relative: &Path) -> Result<PathBuf> {
let relative = if relative.as_os_str().is_empty() {
PathBuf::new()
} else {
sanitize_torrent_relative_path(relative)?
};
let target = if relative.as_os_str().is_empty() {
root.to_path_buf()
} else {
join_under_root(root, &relative)?
};
ensure_path_within_root(root, &target)?;
#[cfg(unix)]
{
ensure_dir_openat(root, &relative)?;
Ok(target)
}
#[cfg(not(unix))]
{
let mut cursor = root.to_path_buf();
for component in relative.components() {
let Component::Normal(part) = component else {
return Err(Error::Store(format!(
"invalid directory component under {}",
root.display()
)));
};
cursor.push(part);
match std::fs::symlink_metadata(&cursor) {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(Error::Store(format!(
"refusing symlink directory: {}",
cursor.display()
)));
}
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(Error::Store(format!(
"path exists and is not a directory: {}",
cursor.display()
)));
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
std::fs::create_dir(&cursor).map_err(|e| {
Error::Store(format!("create_dir {}: {e}", cursor.display()))
})?;
let meta = std::fs::symlink_metadata(&cursor)?;
if meta.file_type().is_symlink() || !meta.is_dir() {
return Err(Error::Store(format!(
"directory create raced to non-dir: {}",
cursor.display()
)));
}
}
Err(err) => return Err(Error::Io(err)),
}
}
Ok(target)
}
}
pub fn open_content_rw(root: &Path, relative: &Path) -> Result<StdFile> {
open_under_root(root, relative, true, false)
}
pub fn create_content_with_len(root: &Path, relative: &Path, length: u64) -> Result<()> {
let file = open_under_root(root, relative, true, true)?;
file.set_len(length)?;
Ok(())
}
pub fn open_content_read(root: &Path, relative: &Path) -> Result<StdFile> {
open_under_root(root, relative, false, false)
}
pub fn read_bytes_under_root(root: &Path, relative: &Path) -> Result<Vec<u8>> {
let mut file = open_content_read(root, relative)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
Ok(buf)
}
pub fn read_bytes_under_root_capped(root: &Path, relative: &Path, max: usize) -> Result<Vec<u8>> {
let mut file = open_content_read(root, relative)?;
let meta = file.metadata()?;
let len = usize::try_from(meta.len()).unwrap_or(usize::MAX);
if len > max {
return Err(Error::Store(format!(
"file exceeds size limit ({max} bytes)"
)));
}
let mut buf = Vec::with_capacity(len);
file.read_to_end(&mut buf)?;
if buf.len() > max {
return Err(Error::Store(format!(
"file exceeds size limit ({max} bytes)"
)));
}
Ok(buf)
}
pub fn write_bytes_under_root(root: &Path, relative: &Path, data: &[u8]) -> Result<()> {
let mut file = open_under_root(root, relative, true, true)?;
file.set_len(0)?;
file.write_all(data)?;
file.sync_all()?;
Ok(())
}
pub fn open_nofollow_read(path: &Path) -> Result<StdFile> {
#[cfg(unix)]
{
use std::fs::OpenOptions;
use std::os::unix::fs::OpenOptionsExt;
let file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(path)
.map_err(|err| {
if err.raw_os_error() == Some(libc::ELOOP) {
Error::Store(format!("refusing symlink path: {}", path.display()))
} else {
Error::Io(err)
}
})?;
assert_safe_regular_file(&file, path.as_os_str())?;
Ok(file)
}
#[cfg(not(unix))]
{
open_path_nofollow(path, false, false)
}
}
pub async fn open_content_rw_async(root: &Path, relative: &Path) -> Result<TokioFile> {
let root = root.to_path_buf();
let relative = relative.to_path_buf();
let std_file = tokio::task::spawn_blocking(move || open_content_rw(&root, &relative))
.await
.map_err(|err| Error::Store(format!("open_content_rw join: {err}")))??;
Ok(TokioFile::from_std(std_file))
}
pub async fn open_content_read_async(root: &Path, relative: &Path) -> Result<TokioFile> {
let root = root.to_path_buf();
let relative = relative.to_path_buf();
let std_file = tokio::task::spawn_blocking(move || open_content_read(&root, &relative))
.await
.map_err(|err| Error::Store(format!("open_content_read join: {err}")))??;
Ok(TokioFile::from_std(std_file))
}
pub async fn create_content_with_len_async(
root: &Path,
relative: &Path,
length: u64,
) -> Result<()> {
let root = root.to_path_buf();
let relative = relative.to_path_buf();
tokio::task::spawn_blocking(move || create_content_with_len(&root, &relative, length))
.await
.map_err(|err| Error::Store(format!("create_content join: {err}")))?
}
pub async fn read_bytes_under_root_async(root: &Path, relative: &Path) -> Result<Vec<u8>> {
let root = root.to_path_buf();
let relative = relative.to_path_buf();
tokio::task::spawn_blocking(move || read_bytes_under_root(&root, &relative))
.await
.map_err(|err| Error::Store(format!("read_bytes join: {err}")))?
}
pub async fn write_bytes_under_root_async(
root: &Path,
relative: &Path,
data: Vec<u8>,
) -> Result<()> {
let root = root.to_path_buf();
let relative = relative.to_path_buf();
tokio::task::spawn_blocking(move || write_bytes_under_root(&root, &relative, &data))
.await
.map_err(|err| Error::Store(format!("write_bytes join: {err}")))?
}
fn open_under_root(root: &Path, relative: &Path, write: bool, create: bool) -> Result<StdFile> {
let relative = sanitize_torrent_relative_path(relative)?;
let _ = join_under_root(root, &relative)?;
if let Some(parent) = Path::new(&relative).parent() {
if !parent.as_os_str().is_empty() {
ensure_dir_under_root(root, parent)?;
}
}
#[cfg(unix)]
{
open_under_root_openat(root, &relative, write, create)
}
#[cfg(not(unix))]
{
let path = join_under_root(root, &relative)?;
open_path_nofollow(&path, write, create)
}
}
#[cfg(unix)]
fn ensure_dir_openat(root: &Path, relative: &Path) -> Result<()> {
use std::ffi::CString;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
let root_fd = open_dir_fd(root)?;
let mut current = root_fd;
for component in relative.components() {
let Component::Normal(part) = component else {
return Err(Error::Store("invalid directory component".into()));
};
let c_name = CString::new(part.as_bytes()).map_err(|_| {
Error::Store("directory component contains NUL".into())
})?;
let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
let fd = unsafe { libc::openat(current.as_raw_fd(), c_name.as_ptr(), flags) };
if fd >= 0 {
current = unsafe { OwnedFd::from_raw_fd(fd) };
continue;
}
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ENOENT) {
let mk = unsafe {
libc::mkdirat(current.as_raw_fd(), c_name.as_ptr(), 0o700)
};
if mk != 0 {
let mk_err = std::io::Error::last_os_error();
if mk_err.raw_os_error() != Some(libc::EEXIST) {
return Err(Error::Io(mk_err));
}
}
let fd = unsafe { libc::openat(current.as_raw_fd(), c_name.as_ptr(), flags) };
if fd < 0 {
return Err(map_open_err(std::io::Error::last_os_error(), part));
}
current = unsafe { OwnedFd::from_raw_fd(fd) };
} else {
return Err(map_open_err(err, part));
}
}
Ok(())
}
#[cfg(unix)]
fn open_under_root_openat(
root: &Path,
relative: &Path,
write: bool,
create: bool,
) -> Result<StdFile> {
use std::ffi::CString;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
let components: Vec<_> = relative.components().collect();
let Some((file_comp, dirs)) = components.split_last() else {
return Err(Error::Store("empty relative path".into()));
};
let Component::Normal(file_name) = file_comp else {
return Err(Error::Store("invalid file component".into()));
};
let root_fd = open_dir_fd(root)?;
let mut dir_fd = root_fd;
for component in dirs {
let Component::Normal(part) = component else {
return Err(Error::Store("invalid directory component".into()));
};
let c_name = CString::new(part.as_bytes()).map_err(|_| {
Error::Store("directory component contains NUL".into())
})?;
let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
let fd = unsafe { libc::openat(dir_fd.as_raw_fd(), c_name.as_ptr(), flags) };
if fd < 0 {
return Err(map_open_err(std::io::Error::last_os_error(), part));
}
dir_fd = unsafe { OwnedFd::from_raw_fd(fd) };
}
let c_file = CString::new(file_name.as_bytes()).map_err(|_| {
Error::Store("file name contains NUL".into())
})?;
let mut flags = libc::O_CLOEXEC | libc::O_NOFOLLOW;
if write {
flags |= libc::O_RDWR;
} else {
flags |= libc::O_RDONLY;
}
if create {
flags |= libc::O_CREAT;
}
let fd = unsafe {
libc::openat(dir_fd.as_raw_fd(), c_file.as_ptr(), flags, 0o600)
};
if fd < 0 {
return Err(map_open_err(std::io::Error::last_os_error(), file_name));
}
let file = unsafe { StdFile::from_raw_fd(fd) };
assert_safe_regular_file(&file, file_name)?;
Ok(file)
}
#[cfg(unix)]
fn open_dir_fd(path: &Path) -> Result<std::os::fd::OwnedFd> {
use std::ffi::CString;
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
let c_path = CString::new(path.as_os_str().as_bytes()).map_err(|_| {
Error::Store(format!("path contains NUL: {}", path.display()))
})?;
let flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW;
let fd = unsafe { libc::open(c_path.as_ptr(), flags) };
if fd < 0 {
let err = std::io::Error::last_os_error();
if err.raw_os_error() == Some(libc::ELOOP) {
return Err(Error::Store(format!(
"refusing symlink root: {}",
path.display()
)));
}
return Err(Error::Io(err));
}
Ok(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) })
}
#[cfg(unix)]
fn assert_safe_regular_file(file: &StdFile, name: &std::ffi::OsStr) -> Result<()> {
let meta = file.metadata()?;
assert_safe_regular_metadata(&meta, &name.to_string_lossy())
}
fn assert_safe_regular_metadata(meta: &std::fs::Metadata, label: &str) -> Result<()> {
if !meta.is_file() {
return Err(Error::Store(format!("refusing non-regular file: {label}")));
}
let nlink = file_link_count(meta)?;
if nlink != 1 {
return Err(Error::Store(format!(
"refusing file with nlink={nlink} (hardlink/reflink): {label}"
)));
}
Ok(())
}
#[cfg(unix)]
fn file_link_count(meta: &std::fs::Metadata) -> Result<u64> {
use std::os::unix::fs::MetadataExt;
Ok(meta.nlink())
}
#[cfg(windows)]
fn file_link_count(meta: &std::fs::Metadata) -> Result<u64> {
use std::os::windows::fs::MetadataExt;
Ok(u64::from(meta.number_of_links()))
}
#[cfg(all(not(unix), not(windows)))]
fn file_link_count(_meta: &std::fs::Metadata) -> Result<u64> {
Err(Error::Store(
"hardlink policy requires Unix or Windows (cannot verify nlink)".into(),
))
}
#[cfg(unix)]
fn map_open_err(err: std::io::Error, name: &std::ffi::OsStr) -> Error {
if err.raw_os_error() == Some(libc::ELOOP) {
Error::Store(format!(
"refusing symlink path component: {}",
name.to_string_lossy()
))
} else {
Error::Io(err)
}
}
#[cfg(not(unix))]
fn open_path_nofollow(path: &Path, write: bool, create: bool) -> Result<StdFile> {
use std::fs::OpenOptions;
match std::fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(Error::Store(format!(
"refusing symlink content path: {}",
path.display()
)));
}
Ok(meta) if !meta.is_file() => {
return Err(Error::Store(format!(
"refusing non-regular file: {}",
path.display()
)));
}
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound && create => {}
Err(err) => return Err(Error::Io(err)),
}
let mut opts = OpenOptions::new();
opts.read(true);
if write {
opts.write(true);
}
if create {
opts.create(true);
}
let file = opts.open(path)?;
let meta = file.metadata().map_err(Error::from)?;
if meta.file_type().is_symlink() {
return Err(Error::Store(format!(
"refusing symlink content path: {}",
path.display()
)));
}
assert_safe_regular_metadata(&meta, &path.display().to_string())?;
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
#[test]
fn rejects_symlink_file_on_unix() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
let target = root.join("outside.bin");
std::fs::write(&target, b"secret").expect("write");
let link = root.join("evil.bin");
#[cfg(unix)]
{
std::os::unix::fs::symlink(&target, &link).expect("symlink");
let err = open_content_rw(root, Path::new("evil.bin"));
assert!(err.is_err(), "symlink open must fail");
}
#[cfg(not(unix))]
{
let _ = (target, link);
}
}
#[test]
fn rejects_hardlink_on_unix() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
#[cfg(unix)]
{
let outside = dir.path().join("outside-secret");
std::fs::write(&outside, b"secret").expect("write");
let link = root.join("linked.bin");
std::fs::hard_link(&outside, &link).expect("hardlink");
let err = open_content_read(root, Path::new("linked.bin"));
assert!(err.is_err(), "hardlink open must fail");
}
#[cfg(not(unix))]
{
let _ = root;
}
}
#[test]
fn rejects_hardlink_on_windows() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
#[cfg(windows)]
{
let outside = dir.path().join("outside-secret");
std::fs::write(&outside, b"secret").expect("write");
let link = root.join("linked.bin");
std::fs::hard_link(&outside, &link).expect("hardlink");
let err = open_content_read(root, Path::new("linked.bin"));
assert!(
err.is_err(),
"Windows hardlink open must fail (nlink check)"
);
}
#[cfg(not(windows))]
{
let _ = root;
}
}
#[test]
fn creates_and_reads_real_file() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
create_content_with_len(root, Path::new("a/b.bin"), 8).expect("create");
{
let mut f = open_content_rw(root, Path::new("a/b.bin")).expect("rw");
f.write_all(b"abcdefgh").expect("write");
}
let mut buf = Vec::new();
open_content_read(root, Path::new("a/b.bin"))
.expect("read")
.read_to_end(&mut buf)
.expect("read_to_end");
assert_eq!(buf, b"abcdefgh");
}
#[test]
fn write_bytes_roundtrip() {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
write_bytes_under_root(root, Path::new(".torrentdht/x.bin"), b"sidecar").expect("write");
let got = read_bytes_under_root(root, Path::new(".torrentdht/x.bin")).expect("read");
assert_eq!(got, b"sidecar");
}
}