Files
texrra-engine/examples/native_editor/bibliography/cache.rs
T

221 lines
7.4 KiB
Rust

use super::{MAX_BBL_BYTES, read_limited};
use sha2::{Digest, Sha256};
use std::{
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
sync::atomic::{AtomicU64, Ordering},
};
const MAGIC: &[u8; 8] = b"TEXBBL01";
const HEADER: usize = MAGIC.len() + 2 * 32;
static NEXT: AtomicU64 = AtomicU64::new(0);
pub(super) fn field(hash: &mut Sha256, bytes: &[u8]) {
hash.update((bytes.len() as u64).to_le_bytes());
hash.update(bytes);
}
pub(super) fn read(path: &Path, key: &[u8; 32]) -> Option<Vec<u8>> {
if !fs::symlink_metadata(path).ok()?.is_file() {
return None;
}
let bytes = read_limited(path, MAX_BBL_BYTES + HEADER as u64).ok()?;
let rest = bytes.strip_prefix(MAGIC)?;
let rest = rest.strip_prefix(key.as_slice())?;
let (digest, output) = rest.split_at_checked(32)?;
(Sha256::digest(output).as_slice() == digest).then(|| output.to_vec())
}
pub(super) fn write(path: &Path, key: &[u8; 32], output: &[u8]) -> io::Result<()> {
if output.len() as u64 > MAX_BBL_BYTES {
return Err(io::Error::other("BibTeX cache output exceeds size limit"));
}
let parent = path.parent().expect("cache entry has a parent");
fs::create_dir_all(parent)?;
if !fs::symlink_metadata(parent)?.is_dir() {
return Err(io::Error::other("BibTeX cache needs a private directory"));
}
let temporary = path.with_extension(format!(
"{}.{}.pending",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
let result = (|| {
file.write_all(MAGIC)?;
file.write_all(key)?;
file.write_all(&Sha256::digest(output))?;
file.write_all(output)?;
file.sync_all()?;
fs::rename(&temporary, path)
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
}
#[cfg(not(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu")))]
pub(super) fn tool_identity(_scratch: &Path) -> Option<[u8; 32]> {
None
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu"))]
pub(super) fn tool_identity(scratch: &Path) -> Option<[u8; 32]> {
use std::{env, path::PathBuf, process::Command};
const LOADER: &str = "/lib64/ld-linux-x86-64.so.2";
// A preloaded library can execute initialization outside the ordinary
// dependency list. Let the regular invocation handle such hosts.
if fs::symlink_metadata("/etc/ld.so.preload").err()?.kind() != io::ErrorKind::NotFound {
return None;
}
let search = env::var_os("PATH")?;
let bibtex = executable(&search, "bibtex")?;
let prlimit = executable(&search, "prlimit")?;
let kpsewhich = executable(&search, "kpsewhich")?;
if bibtex.parent() != kpsewhich.parent() {
return None;
}
let mut digest = Sha256::new();
field(&mut digest, search.as_encoded_bytes());
hash_file(&mut digest, Path::new(LOADER))?;
for command in [&bibtex, &prlimit] {
hash_file(&mut digest, command)?;
let listing = super::private_environment(&mut Command::new(LOADER), scratch)
.arg("--list")
.arg(command)
.output()
.ok()?;
if !listing.status.success() {
return None;
}
let mut listed_any = false;
for line in std::str::from_utf8(&listing.stdout).ok()?.lines() {
let (name, _) = line.trim().rsplit_once(" (")?;
if name.starts_with("linux-vdso.so.") {
continue;
}
let path = name.split_once(" => ").map_or(name, |(_, path)| path);
if !Path::new(path).is_absolute() {
return None;
}
hash_file(&mut digest, Path::new(path))?;
listed_any = true;
}
if !listed_any {
return None;
}
}
// Re-resolve configuration files. A new higher-priority texmf.cnf can
// alter BibTeX's search or capacity even when the binaries are unchanged.
let configs = super::private_environment(&mut Command::new(&kpsewhich), scratch)
.env("BIBINPUTS", ".")
.env("BSTINPUTS", ".")
.args(["--progname=bibtex", "--all", "texmf.cnf"])
.output()
.ok()?;
if !configs.status.success() || configs.stdout.len() > 64 * 1024 {
return None;
}
hash_file(&mut digest, &kpsewhich)?;
for line in std::str::from_utf8(&configs.stdout).ok()?.lines() {
let path = PathBuf::from(line);
if !path.is_absolute() {
return None;
}
hash_file(&mut digest, &path)?;
}
Some(digest.finalize().into())
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu"))]
fn executable(search: &std::ffi::OsStr, name: &str) -> Option<std::path::PathBuf> {
use std::os::unix::fs::PermissionsExt;
for directory in std::env::split_paths(search) {
if !directory.is_absolute() {
return None;
}
let path = directory.join(name);
match fs::metadata(&path) {
Ok(metadata) if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 => {
return Some(path);
}
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(_) => return None,
}
}
None
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu"))]
fn hash_file(hash: &mut Sha256, path: &Path) -> Option<()> {
use std::{
collections::BTreeMap,
fs::Metadata,
io::Read,
os::unix::fs::MetadataExt,
path::PathBuf,
sync::{Mutex, OnceLock},
};
#[derive(Clone, Copy, PartialEq, Eq)]
struct Stamp {
inode: (u64, u64),
bytes: u64,
modified: (i64, i64),
changed: (i64, i64),
}
impl From<&Metadata> for Stamp {
fn from(m: &Metadata) -> Self {
Self {
inode: (m.dev(), m.ino()),
bytes: m.len(),
modified: (m.mtime(), m.mtime_nsec()),
changed: (m.ctime(), m.ctime_nsec()),
}
}
}
type FileHashes = BTreeMap<PathBuf, (Stamp, [u8; 32])>;
static HASHES: OnceLock<Mutex<FileHashes>> = OnceLock::new();
let real = path.canonicalize().ok()?;
let file = fs::File::open(&real).ok()?;
let metadata = file.metadata().ok()?;
let stamp = Stamp::from(&metadata);
const MAX_TOOL_BYTES: u64 = 32 * 1024 * 1024;
if !metadata.is_file() || stamp.bytes > MAX_TOOL_BYTES {
return None;
}
let mut hashes = HASHES
.get_or_init(|| Mutex::new(BTreeMap::new()))
.lock()
.ok()?;
let sum = match hashes.get(&real) {
Some((previous, sum)) if *previous == stamp => *sum,
_ => {
let mut contents = Sha256::new();
let length = io::copy(&mut (&file).take(MAX_TOOL_BYTES + 1), &mut contents).ok()?;
if length != stamp.bytes || Stamp::from(&file.metadata().ok()?) != stamp {
return None;
}
let sum: [u8; 32] = contents.finalize().into();
if hashes.len() >= 64 {
hashes.clear();
}
hashes.insert(real.clone(), (stamp, sum));
sum
}
};
field(hash, path.as_os_str().as_encoded_bytes());
field(hash, real.as_os_str().as_encoded_bytes());
hash.update(sum);
Some(())
}