1use crate::error::{Error, Result};
20use std::io::{self, Read};
21use std::path::{Path, PathBuf};
22
23pub const DEFAULT_MAX_FILE_SIZE: u64 = 16 * 1024 * 1024;
25
26pub const DEFAULT_MAX_EXPANDED_SIZE: u64 = 64 * 1024 * 1024;
29
30pub const DEFAULT_MAX_EXPANSIONS: usize = 10_000;
32
33pub const DEFAULT_MAX_EXPANSION_DEPTH: usize = 32;
36
37pub const DEFAULT_MAX_INCLUDES: usize = 64;
40
41#[cfg(feature = "noml")]
44pub(crate) const MAX_INCLUDE_DEPTH: usize = 10;
45
46#[derive(Debug, Clone)]
66pub struct LoadOptions {
67 pub(crate) strict: bool,
68 pub(crate) include_dirs: Vec<PathBuf>,
69 pub(crate) includes_anywhere: bool,
70 pub(crate) max_file_size: u64,
71 pub(crate) max_includes: usize,
72 pub(crate) max_expanded_size: u64,
73 pub(crate) max_expansions: usize,
74 pub(crate) max_expansion_depth: usize,
75}
76
77impl Default for LoadOptions {
78 fn default() -> Self {
79 Self {
80 strict: false,
81 include_dirs: Vec::new(),
82 includes_anywhere: false,
83 max_file_size: DEFAULT_MAX_FILE_SIZE,
84 max_includes: DEFAULT_MAX_INCLUDES,
85 max_expanded_size: DEFAULT_MAX_EXPANDED_SIZE,
86 max_expansions: DEFAULT_MAX_EXPANSIONS,
87 max_expansion_depth: DEFAULT_MAX_EXPANSION_DEPTH,
88 }
89 }
90}
91
92impl LoadOptions {
93 pub fn new() -> Self {
95 Self::default()
96 }
97
98 pub fn strict_defaults() -> Self {
100 Self::default().strict(true)
101 }
102
103 pub fn strict(mut self, strict: bool) -> Self {
107 self.strict = strict;
108 self
109 }
110
111 pub fn is_strict(&self) -> bool {
113 self.strict
114 }
115
116 pub fn allow_include_dir(mut self, dir: impl Into<PathBuf>) -> Self {
121 self.include_dirs.push(dir.into());
122 self
123 }
124
125 pub fn allow_includes_anywhere(mut self) -> Self {
128 self.includes_anywhere = true;
129 self
130 }
131
132 pub fn max_file_size(mut self, bytes: u64) -> Self {
135 self.max_file_size = bytes;
136 self
137 }
138
139 pub fn max_includes(mut self, count: usize) -> Self {
142 self.max_includes = count;
143 self
144 }
145
146 pub fn max_expanded_size(mut self, bytes: u64) -> Self {
151 self.max_expanded_size = bytes;
152 self
153 }
154
155 pub fn max_expansions(mut self, count: usize) -> Self {
158 self.max_expansions = count;
159 self
160 }
161
162 pub fn max_expansion_depth(mut self, depth: usize) -> Self {
165 self.max_expansion_depth = depth;
166 self
167 }
168}
169
170fn refuse(path: &Path, kind: io::ErrorKind, why: &str) -> Error {
171 Error::io(
172 path.display().to_string(),
173 io::Error::new(kind, why.to_string()),
174 )
175}
176
177pub(crate) fn read_file(path: &Path, max: u64) -> Result<String> {
183 let io_err = |e| Error::io(path.display().to_string(), e);
184 let meta = std::fs::metadata(path).map_err(io_err)?;
185 check_meta(path, &meta, max)?;
186 let file = std::fs::File::open(path).map_err(io_err)?;
187 let meta = file.metadata().map_err(io_err)?;
188 check_meta(path, &meta, max)?;
189 let mut bytes = Vec::with_capacity(usize::try_from(meta.len().min(max)).unwrap_or(0));
190 file.take(max.saturating_add(1))
191 .read_to_end(&mut bytes)
192 .map_err(io_err)?;
193 finish(path, bytes, max)
194}
195
196#[cfg(feature = "async")]
198pub(crate) async fn read_file_async(path: &Path, max: u64) -> Result<String> {
199 use tokio::io::AsyncReadExt;
200 let io_err = |e| Error::io(path.display().to_string(), e);
201 let meta = tokio::fs::metadata(path).await.map_err(io_err)?;
202 check_meta(path, &meta, max)?;
203 let file = tokio::fs::File::open(path).await.map_err(io_err)?;
204 let meta = file.metadata().await.map_err(io_err)?;
205 check_meta(path, &meta, max)?;
206 let mut bytes = Vec::with_capacity(usize::try_from(meta.len().min(max)).unwrap_or(0));
207 file.take(max.saturating_add(1))
208 .read_to_end(&mut bytes)
209 .await
210 .map_err(io_err)?;
211 finish(path, bytes, max)
212}
213
214fn check_meta(path: &Path, meta: &std::fs::Metadata, max: u64) -> Result<()> {
215 if !meta.is_file() {
216 return Err(refuse(
217 path,
218 io::ErrorKind::InvalidInput,
219 "not a regular file",
220 ));
221 }
222 if meta.len() > max {
223 return Err(refuse(
224 path,
225 io::ErrorKind::InvalidData,
226 "file is larger than the size limit",
227 ));
228 }
229 Ok(())
230}
231
232fn finish(path: &Path, bytes: Vec<u8>, max: u64) -> Result<String> {
233 if bytes.len() as u64 > max {
234 return Err(refuse(
235 path,
236 io::ErrorKind::InvalidData,
237 "file is larger than the size limit",
238 ));
239 }
240 String::from_utf8(bytes)
241 .map_err(|_| refuse(path, io::ErrorKind::InvalidData, "file is not valid UTF-8"))
242}
243
244#[cfg(feature = "noml")]
246#[derive(Debug, Clone)]
247pub(crate) struct IncludePolicy {
248 pub(crate) base_dir: PathBuf,
251 roots: Vec<PathBuf>,
253 anywhere: bool,
254 pub(crate) max_file_size: u64,
255 pub(crate) max_includes: usize,
256}
257
258#[cfg(feature = "noml")]
259impl IncludePolicy {
260 pub(crate) fn new(file: Option<&Path>, options: &LoadOptions) -> Self {
264 let base_dir = match file.and_then(Path::parent) {
265 Some(dir) if !dir.as_os_str().is_empty() => dir.to_path_buf(),
266 _ => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
267 };
268 let mut roots = Vec::with_capacity(options.include_dirs.len() + 1);
269 roots.extend(std::fs::canonicalize(&base_dir).ok());
270 roots.extend(
271 options
272 .include_dirs
273 .iter()
274 .filter_map(|dir| std::fs::canonicalize(dir).ok()),
275 );
276 Self {
277 base_dir,
278 roots,
279 anywhere: options.includes_anywhere,
280 max_file_size: options.max_file_size,
281 max_includes: options.max_includes,
282 }
283 }
284
285 pub(crate) fn read(
291 &self,
292 from_dir: &Path,
293 include: &str,
294 ) -> std::result::Result<(PathBuf, String), &'static str> {
295 if include.starts_with("http://") || include.starts_with("https://") {
296 return Err("remote includes are not supported");
297 }
298 let joined = from_dir.join(include);
299 let canonical =
300 std::fs::canonicalize(&joined).map_err(|_| "the included file does not exist")?;
301 if !self.anywhere && !self.roots.iter().any(|root| canonical.starts_with(root)) {
302 return Err("the included file is outside the allowed directories");
303 }
304 let text = read_file(&canonical, self.max_file_size).map_err(|e| match e {
305 Error::Io { source, .. } if source.kind() == io::ErrorKind::InvalidInput => {
306 "the included path is not a regular file"
307 }
308 Error::Io { source, .. } if source.kind() == io::ErrorKind::InvalidData => {
309 "the included file is too large or not UTF-8"
310 }
311 _ => "the included file could not be read",
312 })?;
313 Ok((canonical, text))
314 }
315}