use std::io::{self, Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::sync::Arc;
use crate::storage::response::{Reason, ResourceError, Response};
#[cfg_attr(unix, expect(clippy::unnecessary_wraps, reason = "only a non-Unix path can fail to convert"))]
pub(crate) fn path_from_utf8(path: &[u8]) -> Result<PathBuf, String> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
Ok(PathBuf::from(std::ffi::OsStr::from_bytes(path)))
}
#[cfg(not(unix))]
{
String::from_utf8(path.to_vec()).map(PathBuf::from).map_err(|_| "Invalid UTF-8 in path".to_owned())
}
}
pub(crate) fn read_file(path: &std::path::Path, data_range: Option<(u64, u64)>) -> io::Result<Vec<u8>> {
read_range(std::fs::File::open(path)?, data_range)
}
pub(crate) fn read_range(mut file: impl Read + Seek, data_range: Option<(u64, u64)>) -> io::Result<Vec<u8>> {
let mut data = Vec::new();
let Some((first, last)) = data_range else {
file.read_to_end(&mut data)?;
return Ok(data);
};
if last < first {
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("the range {first}-{last} is inverted")));
}
let len = file.seek(SeekFrom::End(0))?;
if first >= len {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("the range {first}-{last} starts past the end, {len} bytes"),
));
}
file.seek(SeekFrom::Start(first))?;
file.take((last - first).saturating_add(1)).read_to_end(&mut data)?;
Ok(data)
}
pub(crate) fn local_file_response(path: &[u8], data_range: Option<(u64, u64)>) -> Response {
let mut response = Response::new();
let path_display = String::from_utf8_lossy(path).into_owned();
let path = match path_from_utf8(path) {
Ok(path) => path,
Err(message) => {
response.error = Some(Box::new(ResourceError::new(Reason::Other, message)));
return response;
}
};
let status = std::fs::metadata(&path);
let not_found = matches!(&status, Err(e) if e.kind() == io::ErrorKind::NotFound);
let is_directory = matches!(&status, Ok(metadata) if metadata.is_dir());
if not_found {
response.error =
Some(Box::new(ResourceError::new(Reason::NotFound, format!("Cannot find file {path_display}"))));
} else if is_directory {
response.error =
Some(Box::new(ResourceError::new(Reason::NotFound, format!("Cannot read directory {path_display}"))));
} else {
match read_file(&path, data_range) {
Ok(data) => response.data = Some(Arc::new(data)),
Err(e) => {
response.error =
Some(Box::new(ResourceError::new(Reason::Other, format!("Cannot read file {path_display}: {e}"))));
}
}
}
response
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
struct Failing {
cursor: Cursor<Vec<u8>>,
good: u64,
}
impl Read for Failing {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let left = self.good.saturating_sub(self.cursor.position());
if left == 0 {
return Err(io::Error::other("unreadable"));
}
let len = buffer.len().min(usize::try_from(left).unwrap_or(usize::MAX));
self.cursor.read(&mut buffer[..len])
}
}
impl Seek for Failing {
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
self.cursor.seek(position)
}
}
#[test]
fn a_read_error_fails_the_read() {
let failing = || Failing { cursor: Cursor::new(b"0123456789".to_vec()), good: 4 };
assert_eq!("unreadable", read_range(failing(), None).unwrap_err().to_string());
assert_eq!("unreadable", read_range(failing(), Some((2, 8))).unwrap_err().to_string());
assert_eq!(b"123", &read_range(failing(), Some((1, 3))).unwrap()[..]);
}
#[test]
fn a_range_reads_its_bytes_up_to_the_end() {
let file = || Cursor::new(b"0123456789".to_vec());
assert_eq!(b"0123456789", &read_range(file(), None).unwrap()[..]);
assert_eq!(b"234", &read_range(file(), Some((2, 4))).unwrap()[..]);
assert_eq!(b"9", &read_range(file(), Some((9, 9))).unwrap()[..]);
assert_eq!(b"89", &read_range(file(), Some((8, 20))).unwrap()[..]);
assert_eq!(b"0123456789", &read_range(file(), Some((0, u64::MAX))).unwrap()[..]);
for range in [(10, 10), (11, 20), (5, 4)] {
assert_eq!(io::ErrorKind::InvalidInput, read_range(file(), Some(range)).unwrap_err().kind(), "{range:?}");
}
assert_eq!(io::ErrorKind::InvalidInput, read_range(Cursor::new(Vec::new()), Some((0, 0))).unwrap_err().kind());
}
}