use crate::error::{Error, Result};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
pub const DEFAULT_MAX_FILE_SIZE: u64 = 16 * 1024 * 1024;
pub const DEFAULT_MAX_EXPANDED_SIZE: u64 = 64 * 1024 * 1024;
pub const DEFAULT_MAX_EXPANSIONS: usize = 10_000;
pub const DEFAULT_MAX_EXPANSION_DEPTH: usize = 32;
pub const DEFAULT_MAX_INCLUDES: usize = 64;
#[cfg(feature = "noml")]
pub(crate) const MAX_INCLUDE_DEPTH: usize = 10;
#[derive(Debug, Clone)]
pub struct LoadOptions {
pub(crate) strict: bool,
pub(crate) include_dirs: Vec<PathBuf>,
pub(crate) includes_anywhere: bool,
pub(crate) max_file_size: u64,
pub(crate) max_includes: usize,
pub(crate) max_expanded_size: u64,
pub(crate) max_expansions: usize,
pub(crate) max_expansion_depth: usize,
}
impl Default for LoadOptions {
fn default() -> Self {
Self {
strict: false,
include_dirs: Vec::new(),
includes_anywhere: false,
max_file_size: DEFAULT_MAX_FILE_SIZE,
max_includes: DEFAULT_MAX_INCLUDES,
max_expanded_size: DEFAULT_MAX_EXPANDED_SIZE,
max_expansions: DEFAULT_MAX_EXPANSIONS,
max_expansion_depth: DEFAULT_MAX_EXPANSION_DEPTH,
}
}
}
impl LoadOptions {
pub fn new() -> Self {
Self::default()
}
pub fn strict_defaults() -> Self {
Self::default().strict(true)
}
pub fn strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
pub fn is_strict(&self) -> bool {
self.strict
}
pub fn allow_include_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.include_dirs.push(dir.into());
self
}
pub fn allow_includes_anywhere(mut self) -> Self {
self.includes_anywhere = true;
self
}
pub fn max_file_size(mut self, bytes: u64) -> Self {
self.max_file_size = bytes;
self
}
pub fn max_includes(mut self, count: usize) -> Self {
self.max_includes = count;
self
}
pub fn max_expanded_size(mut self, bytes: u64) -> Self {
self.max_expanded_size = bytes;
self
}
pub fn max_expansions(mut self, count: usize) -> Self {
self.max_expansions = count;
self
}
pub fn max_expansion_depth(mut self, depth: usize) -> Self {
self.max_expansion_depth = depth;
self
}
}
fn refuse(path: &Path, kind: io::ErrorKind, why: &str) -> Error {
Error::io(
path.display().to_string(),
io::Error::new(kind, why.to_string()),
)
}
pub(crate) fn read_file(path: &Path, max: u64) -> Result<String> {
let io_err = |e| Error::io(path.display().to_string(), e);
let meta = std::fs::metadata(path).map_err(io_err)?;
check_meta(path, &meta, max)?;
let file = std::fs::File::open(path).map_err(io_err)?;
let meta = file.metadata().map_err(io_err)?;
check_meta(path, &meta, max)?;
let mut bytes = Vec::with_capacity(usize::try_from(meta.len().min(max)).unwrap_or(0));
file.take(max.saturating_add(1))
.read_to_end(&mut bytes)
.map_err(io_err)?;
finish(path, bytes, max)
}
#[cfg(feature = "async")]
pub(crate) async fn read_file_async(path: &Path, max: u64) -> Result<String> {
use tokio::io::AsyncReadExt;
let io_err = |e| Error::io(path.display().to_string(), e);
let meta = tokio::fs::metadata(path).await.map_err(io_err)?;
check_meta(path, &meta, max)?;
let file = tokio::fs::File::open(path).await.map_err(io_err)?;
let meta = file.metadata().await.map_err(io_err)?;
check_meta(path, &meta, max)?;
let mut bytes = Vec::with_capacity(usize::try_from(meta.len().min(max)).unwrap_or(0));
file.take(max.saturating_add(1))
.read_to_end(&mut bytes)
.await
.map_err(io_err)?;
finish(path, bytes, max)
}
fn check_meta(path: &Path, meta: &std::fs::Metadata, max: u64) -> Result<()> {
if !meta.is_file() {
return Err(refuse(
path,
io::ErrorKind::InvalidInput,
"not a regular file",
));
}
if meta.len() > max {
return Err(refuse(
path,
io::ErrorKind::InvalidData,
"file is larger than the size limit",
));
}
Ok(())
}
fn finish(path: &Path, bytes: Vec<u8>, max: u64) -> Result<String> {
if bytes.len() as u64 > max {
return Err(refuse(
path,
io::ErrorKind::InvalidData,
"file is larger than the size limit",
));
}
String::from_utf8(bytes)
.map_err(|_| refuse(path, io::ErrorKind::InvalidData, "file is not valid UTF-8"))
}
#[cfg(feature = "noml")]
#[derive(Debug, Clone)]
pub(crate) struct IncludePolicy {
pub(crate) base_dir: PathBuf,
roots: Vec<PathBuf>,
anywhere: bool,
pub(crate) max_file_size: u64,
pub(crate) max_includes: usize,
}
#[cfg(feature = "noml")]
impl IncludePolicy {
pub(crate) fn new(file: Option<&Path>, options: &LoadOptions) -> Self {
let base_dir = match file.and_then(Path::parent) {
Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
_ => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
};
let mut roots = Vec::with_capacity(options.include_dirs.len() + 1);
roots.extend(std::fs::canonicalize(&base_dir).ok());
roots.extend(
options
.include_dirs
.iter()
.filter_map(|dir| std::fs::canonicalize(dir).ok()),
);
Self {
base_dir,
roots,
anywhere: options.includes_anywhere,
max_file_size: options.max_file_size,
max_includes: options.max_includes,
}
}
pub(crate) fn read(
&self,
from_dir: &Path,
include: &str,
) -> std::result::Result<(PathBuf, String), &'static str> {
if include.starts_with("http://") || include.starts_with("https://") {
return Err("remote includes are not supported");
}
let joined = from_dir.join(include);
let canonical =
std::fs::canonicalize(&joined).map_err(|_| "the included file does not exist")?;
if !self.anywhere && !self.roots.iter().any(|root| canonical.starts_with(root)) {
return Err("the included file is outside the allowed directories");
}
let text = read_file(&canonical, self.max_file_size).map_err(|e| match e {
Error::Io { source, .. } if source.kind() == io::ErrorKind::InvalidInput => {
"the included path is not a regular file"
}
Error::Io { source, .. } if source.kind() == io::ErrorKind::InvalidData => {
"the included file is too large or not UTF-8"
}
_ => "the included file could not be read",
})?;
Ok((canonical, text))
}
}