use crate::error::{self, Error};
use crate::io::fs::{open_without_blocking, restore_blocking};
use crate::io::stream::{InputStream, RawInputStream};
use std::fs::{self, File};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub(super) struct PathBody {
pub(super) path: PathBuf,
pub(super) length: u64,
pub(super) offset: u64,
}
impl PathBody {
pub(super) fn check_file_type(&self) -> Result<(), Error> {
let path = &self.path;
let metadata =
fs::metadata(path).map_err(|e| error::io_at("reading metadata of", path, e))?;
if !metadata.is_file() {
return Err(not_regular_file(path));
}
Ok(())
}
pub(super) fn open(&self) -> Result<File, Error> {
let path = &self.path;
let file = open_without_blocking(path).map_err(|e| error::io_at("opening", path, e))?;
#[cfg(windows)]
if !crate::io::fs::is_disk_file(&file) {
return Err(not_regular_file(path));
}
let metadata = file
.metadata()
.map_err(|e| error::io_at("reading metadata of", path, e))?;
if !metadata.is_file() {
return Err(not_regular_file(path));
}
restore_blocking(&file).map_err(|e| error::io_at("opening", path, e))?;
Ok(file)
}
}
fn not_regular_file(path: &Path) -> Error {
error::invalid_input(format!("{} is not a regular file", path.display()))
}
#[derive(Debug, Default)]
pub struct PathBodyBuilder {
path: Option<PathBuf>,
length: Option<u64>,
offset: Option<u64>,
metadata: Option<fs::Metadata>,
}
impl PathBodyBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn path(mut self, path: impl AsRef<std::path::Path>) -> Self {
self.path = Some(path.as_ref().to_path_buf());
self
}
pub fn offset(mut self, offset: u64) -> Self {
self.offset = Some(offset);
self
}
pub fn length(mut self, length: u64) -> Self {
self.length = Some(length);
self
}
pub(crate) fn metadata(mut self, metadata: fs::Metadata) -> Self {
self.metadata = Some(metadata);
self
}
pub fn build(self) -> Result<InputStream, Error> {
let path = self
.path
.ok_or_else(|| error::invalid_input("a path is required to read a file"))?;
let offset = self.offset.unwrap_or_default();
let length = match self.length {
None => {
let metadata = match self.metadata {
Some(metadata) => metadata,
None => fs::metadata(&path)
.map_err(|e| error::io_at("reading metadata of", &path, e))?,
};
if !metadata.is_file() {
return Err(not_regular_file(&path));
}
let file_size = metadata.len();
if offset > file_size {
return Err(error::invalid_input(format!(
"offset {offset} is greater than the size of {} ({file_size} bytes)",
path.display()
)));
}
file_size - offset
}
Some(explicit) => explicit,
};
let body = PathBody {
path,
length,
offset,
};
let stream = InputStream {
inner: RawInputStream::Fs(body),
};
Ok(stream)
}
}
#[cfg(test)]
mod test {
use std::io::Write;
use tempfile::NamedTempFile;
use crate::error::ErrorKind;
use crate::io::{path_body::PathBodyBuilder, InputStream};
use super::PathBody;
fn path_body(stream: &InputStream) -> &PathBody {
match &stream.inner {
crate::io::stream::RawInputStream::Buf(_) => panic!("unexpected inner body"),
crate::io::stream::RawInputStream::Dyn(_) => panic!("unexpected inner body"),
crate::io::stream::RawInputStream::Fs(path_body) => path_body,
}
}
#[test]
fn test_from_path() {
let mut tmp = NamedTempFile::new().unwrap();
let content = "hello path body";
tmp.write_all(content.as_bytes()).unwrap();
let stream = PathBodyBuilder::new().path(tmp.path()).build().unwrap();
let body = path_body(&stream);
assert_eq!(0, body.offset);
assert_eq!(content.len() as u64, body.length);
}
#[test]
fn test_explicit_content_length() {
let tmp = NamedTempFile::new().unwrap();
let stream = PathBodyBuilder::new()
.path(tmp.path())
.length(64)
.build()
.unwrap();
let body = path_body(&stream);
assert_eq!(0, body.offset);
assert_eq!(64, body.length);
}
#[test]
fn test_length_with_offset() {
let mut tmp = NamedTempFile::new().unwrap();
let content = "hello path body";
tmp.write_all(content.as_bytes()).unwrap();
let offset = 5;
let stream = PathBodyBuilder::new()
.path(tmp.path())
.offset(offset)
.build()
.unwrap();
let body = path_body(&stream);
assert_eq!(offset, body.offset);
assert_eq!(content.len() as u64 - offset, body.length);
}
#[test]
fn test_explicit_content_length_and_offset() {
let tmp = NamedTempFile::new().unwrap();
let stream = PathBodyBuilder::new()
.path(tmp.path())
.length(64)
.offset(12)
.build()
.unwrap();
let body = path_body(&stream);
assert_eq!(12, body.offset);
assert_eq!(64, body.length);
}
#[cfg(unix)]
fn assert_build_rejects_non_regular_file(path: &std::path::Path) {
use aws_smithy_types::error::display::DisplayErrorContext;
let error = PathBodyBuilder::new().path(path).build().unwrap_err();
assert_eq!(error.kind(), &crate::error::ErrorKind::InputInvalid);
let message = DisplayErrorContext(&error).to_string();
assert!(
message.contains("is not a regular file"),
"{}: {message}",
path.display()
);
}
#[cfg_attr(miri, ignore)]
#[test]
#[cfg(unix)]
fn test_rejects_non_regular_files() {
let directory = tempfile::tempdir().unwrap();
for path in [std::path::Path::new("/dev/zero"), directory.path()] {
assert_build_rejects_non_regular_file(path);
}
}
#[cfg_attr(miri, ignore)]
#[test]
#[cfg(all(unix, not(target_os = "android")))]
fn test_rejects_fifo() {
let directory = tempfile::tempdir().unwrap();
let fifo = directory.path().join("fifo");
nix::unistd::mkfifo(&fifo, nix::sys::stat::Mode::S_IRWXU).unwrap();
assert_build_rejects_non_regular_file(&fifo);
}
#[cfg_attr(miri, ignore)]
#[test]
#[cfg(all(unix, not(target_os = "android")))]
fn test_open_rejects_a_device_or_fifo_without_waiting_for_a_writer() {
let directory = tempfile::tempdir().unwrap();
let fifo = directory.path().join("fifo");
nix::unistd::mkfifo(&fifo, nix::sys::stat::Mode::S_IRWXU).unwrap();
for path in [std::path::PathBuf::from("/dev/zero"), fifo] {
let body = PathBody {
path: path.clone(),
length: 16,
offset: 0,
};
let (opened, result) = std::sync::mpsc::channel();
std::thread::spawn(move || opened.send(body.open().map(drop)));
let error = result
.recv_timeout(std::time::Duration::from_secs(10))
.unwrap_or_else(|_| panic!("opening {} did not return", path.display()))
.unwrap_err();
assert_eq!(
error.kind(),
&crate::error::ErrorKind::InputInvalid,
"{}",
path.display()
);
}
}
#[test]
fn test_invalid_offset() {
let mut tmp = NamedTempFile::new().unwrap();
let content = "hello path body";
tmp.write_all(content.as_bytes()).unwrap();
let err = PathBodyBuilder::new()
.path(tmp.path())
.offset(content.len() as u64 + 1)
.build()
.unwrap_err();
assert_eq!(err.kind(), &ErrorKind::InputInvalid);
}
#[test]
fn test_offset_at_end_of_file_is_empty() {
let mut tmp = NamedTempFile::new().unwrap();
let content = "hello path body";
tmp.write_all(content.as_bytes()).unwrap();
let stream = PathBodyBuilder::new()
.path(tmp.path())
.offset(content.len() as u64)
.build()
.unwrap();
assert_eq!(0, path_body(&stream).length);
}
#[test]
fn test_missing_path_is_invalid_input() {
let err = PathBodyBuilder::new().build().unwrap_err();
assert_eq!(err.kind(), &ErrorKind::InputInvalid);
}
#[test]
fn test_missing_file_is_io_error() {
let dir = tempfile::tempdir().unwrap();
let err = PathBodyBuilder::new()
.path(dir.path().join("missing"))
.build()
.unwrap_err();
assert_eq!(err.kind(), &ErrorKind::IOError);
let source = std::error::Error::source(&err)
.and_then(|source| source.downcast_ref::<std::io::Error>())
.expect("the filesystem error is the source");
assert_eq!(source.kind(), std::io::ErrorKind::NotFound);
}
#[test]
fn test_supplied_metadata_skips_stat() {
let mut tmp = NamedTempFile::new().unwrap();
let content = "hello path body";
tmp.write_all(content.as_bytes()).unwrap();
let metadata = std::fs::metadata(tmp.path()).unwrap();
let dir = tempfile::tempdir().unwrap();
let stream = PathBodyBuilder::new()
.path(dir.path().join("missing"))
.metadata(metadata)
.build()
.unwrap();
let body = path_body(&stream);
assert_eq!(0, body.offset);
assert_eq!(content.len() as u64, body.length);
}
}