use crate::error::KitError;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use troupekit_trace::{trace, Trace};
const MAX_LAW_FILE_BYTES: u64 = 1024 * 1024;
const MAX_INLINE_LAW_BYTES: usize = 64 * 1024;
const MAX_LAWS: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Laws {
paths: Vec<PathBuf>,
inline: Vec<String>,
auto: bool,
}
impl Laws {
pub fn paths(&self) -> &[PathBuf] {
&self.paths
}
pub fn inline(&self) -> &[String] {
&self.inline
}
pub fn auto(&self) -> bool {
self.auto
}
pub(crate) fn check(
owner: &str,
paths: &[PathBuf],
inline: &[String],
auto: bool,
) -> Result<Laws, KitError> {
let fail = |m: String| KitError::config(owner, m);
let total = paths.len() + inline.len();
if total > MAX_LAWS {
return Err(fail(format!("takes at most {MAX_LAWS} laws, got {total}")));
}
let mut resolved = Vec::with_capacity(paths.len());
for path in paths {
resolved.push(
read_checked(path, "bend", MAX_LAW_FILE_BYTES)
.map(|(absolute, _)| absolute)
.map_err(|m| fail(format!("law file `{}` {m}", path.display())))?,
);
}
for (i, law) in inline.iter().enumerate() {
let n = i + 1;
if law.trim().is_empty() {
return Err(fail(format!("inline law {n} is blank")));
}
if law.len() > MAX_INLINE_LAW_BYTES {
return Err(fail(format!("inline law {n} is over 64 KiB")));
}
if law.contains('\0') {
return Err(fail(format!("inline law {n} contains a NUL byte")));
}
}
assert_eq!(resolved.len(), paths.len());
for path in &resolved {
let shown = path.display().to_string();
trace!(
Trace::Laws,
"law.load",
owner = owner,
source = "file",
path = shown,
auto = auto,
);
}
for law in inline {
trace!(
Trace::Laws,
"law.load",
owner = owner,
source = "inline",
bytes = law.len(),
auto = auto,
);
}
Ok(Laws {
paths: resolved,
inline: inline.to_vec(),
auto,
})
}
}
impl Default for Laws {
fn default() -> Self {
Laws {
paths: Vec::new(),
inline: Vec::new(),
auto: true,
}
}
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly"
))]
const O_NONBLOCK: i32 = 0x0004;
#[cfg(all(
any(target_os = "linux", target_os = "android"),
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "arm",
target_arch = "aarch64",
target_arch = "riscv64",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "s390x",
target_arch = "loongarch64"
)
))]
const O_NONBLOCK: i32 = 0o4000;
#[cfg(all(
unix,
not(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly"
)),
not(all(
any(target_os = "linux", target_os = "android"),
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "arm",
target_arch = "aarch64",
target_arch = "riscv64",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "s390x",
target_arch = "loongarch64"
)
))
))]
const O_NONBLOCK: i32 = 0;
fn open_nonblocking(path: &Path) -> std::io::Result<std::fs::File> {
let mut options = std::fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::custom_flags(&mut options, O_NONBLOCK);
options.open(path)
}
pub(crate) fn read_checked(
path: &Path,
extension: &str,
max_bytes: u64,
) -> Result<(PathBuf, String), String> {
assert!(max_bytes > 0 && max_bytes.is_multiple_of(1024 * 1024));
let too_big = || format!("is over {} MiB", max_bytes / (1024 * 1024));
if path.as_os_str().is_empty() {
return Err("is empty".into());
}
if path.components().any(|c| c == Component::ParentDir) {
return Err("must not contain `..`".into());
}
if path.extension().is_none_or(|e| e != extension) {
return Err(format!("must be a .{extension} file"));
}
let absolute = std::path::absolute(path).map_err(|e| format!("cannot be resolved: {e}"))?;
assert!(absolute.is_absolute(), "std::path::absolute returns an absolute path");
let file = match open_nonblocking(&absolute) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err("does not exist".into()),
Err(e) => return Err(format!("cannot be read: {e}")),
};
let meta = file.metadata().map_err(|e| format!("cannot be read: {e}"))?;
if !meta.is_file() {
return Err("is not a regular file".into());
}
if meta.len() > max_bytes {
return Err(too_big());
}
let bytes = read_bounded(file, max_bytes).map_err(|e| e.unwrap_or_else(too_big))?;
let text = String::from_utf8(bytes).map_err(|_| "is not valid UTF-8".to_string())?;
Ok((absolute, text))
}
fn read_bounded(file: impl Read, max_bytes: u64) -> Result<Vec<u8>, Option<String>> {
let mut bytes = Vec::new();
file.take(max_bytes + 1)
.read_to_end(&mut bytes)
.map_err(|e| Some(format!("cannot be read: {e}")))?;
if bytes.len() as u64 > max_bytes {
return Err(None);
}
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read_stops_one_byte_past_the_cap() {
assert_eq!(read_bounded(std::io::repeat(b'a'), MAX_LAW_FILE_BYTES).unwrap_err(), None);
let exact = vec![b'a'; MAX_LAW_FILE_BYTES as usize];
assert_eq!(read_bounded(exact.as_slice(), MAX_LAW_FILE_BYTES).unwrap().len(), exact.len());
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly",
all(
any(target_os = "linux", target_os = "android"),
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "arm",
target_arch = "aarch64",
target_arch = "riscv64",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "s390x",
target_arch = "loongarch64"
)
)
))]
#[test]
fn a_named_pipe_law_file_is_refused_without_blocking() {
let dir = tempfile::tempdir().unwrap();
let fifo = dir.path().join("rules.bend");
let made = std::process::Command::new("mkfifo").arg(&fifo).status().unwrap();
assert!(made.success());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || tx.send(read_checked(&fifo, "bend", MAX_LAW_FILE_BYTES).map(|(p, _)| p)).unwrap());
let result = rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("read_checked blocked on a named pipe");
assert_eq!(result, Err("is not a regular file".to_string()));
}
#[cfg(windows)]
#[test]
fn drive_relative_path_resolves_to_an_absolute_one() {
let dir = tempfile::tempdir().unwrap();
std::env::set_current_dir(dir.path()).unwrap();
std::fs::write(dir.path().join("rules.bend"), "law").unwrap();
let drive = dir.path().components().next().unwrap().as_os_str().to_owned();
let mut relative = std::ffi::OsString::from(drive);
relative.push("rules.bend");
let (resolved, _) = read_checked(&PathBuf::from(relative), "bend", MAX_LAW_FILE_BYTES).unwrap();
assert!(resolved.is_absolute(), "{}", resolved.display());
assert!(resolved.ends_with("rules.bend"), "{}", resolved.display());
}
}