1use std::collections::hash_map::DefaultHasher;
6use std::fs;
7use std::hash::{Hash, Hasher};
8use std::io;
9use std::path::{Path, PathBuf};
10
11#[cfg(unix)]
12use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
13
14const UNSAFE_TEMP_OUTPUT_STEM_CHARS: &[char] = &[
15 '&', '^', '%', '(', ')', '!', '"', '\'', '<', '>', '|', ';', '`', '$', '\\', '/', ':',
16];
17
18pub fn temp_output_for(input: &Path) -> io::Result<PathBuf> {
22 let canonical = fs::canonicalize(input).unwrap_or_else(|_| input.to_path_buf());
23 let mut hasher = DefaultHasher::new();
24 canonical.hash(&mut hasher);
25 let hash = hasher.finish();
26
27 let stem = input
28 .file_stem()
29 .and_then(|s| s.to_str())
30 .unwrap_or("document");
31 let stem = sanitize_temp_output_stem(stem);
32
33 let root = private_temp_root();
34 ensure_private_dir(&root)?;
35
36 let source_dir = root.join(format!("{:016x}", hash));
37 ensure_private_dir(&source_dir)?;
38
39 Ok(source_dir.join(format!("{stem}.html")))
40}
41
42fn sanitize_temp_output_stem(stem: &str) -> String {
43 let mut sanitized = String::with_capacity(stem.len());
44
45 for ch in stem.chars() {
46 if ch.is_control() || UNSAFE_TEMP_OUTPUT_STEM_CHARS.contains(&ch) {
47 sanitized.push('_');
48 } else {
49 sanitized.push(ch);
50 }
51 }
52
53 if sanitized.chars().any(|ch| ch != '_') {
54 sanitized
55 } else {
56 "document".to_string()
57 }
58}
59
60pub(crate) fn private_temp_root() -> PathBuf {
61 let mut p = std::env::temp_dir();
62 #[cfg(unix)]
63 p.push(format!("mdo-{}", unsafe { libc::geteuid() }));
64 #[cfg(not(unix))]
65 p.push("mdo");
66 p
67}
68
69#[cfg(unix)]
70pub(crate) fn ensure_private_dir(path: &Path) -> io::Result<()> {
71 match fs::symlink_metadata(path) {
72 Ok(metadata) => {
73 let file_type = metadata.file_type();
74 if file_type.is_symlink() || !file_type.is_dir() {
75 return Err(io::Error::new(
76 io::ErrorKind::AlreadyExists,
77 format!("{path:?} exists but is not a directory"),
78 ));
79 }
80
81 let uid = unsafe { libc::geteuid() };
82 if metadata.uid() != uid {
83 return Err(io::Error::new(
84 io::ErrorKind::PermissionDenied,
85 format!("{path:?} is not owned by the current user"),
86 ));
87 }
88
89 let mode = metadata.permissions().mode();
90 if mode & 0o077 != 0 {
91 fs::set_permissions(path, fs::Permissions::from_mode(mode & !0o077))?;
92 }
93 }
94 Err(e) if e.kind() == io::ErrorKind::NotFound => {
95 let mut builder = fs::DirBuilder::new();
96 builder.mode(0o700);
97 if let Err(create_error) = builder.create(path) {
98 if create_error.kind() == io::ErrorKind::AlreadyExists {
99 return ensure_private_dir(path);
100 }
101
102 return Err(create_error);
103 }
104 }
105 Err(e) => return Err(e),
106 }
107
108 Ok(())
109}
110
111#[cfg(not(unix))]
112pub(crate) fn ensure_private_dir(path: &Path) -> io::Result<()> {
113 fs::create_dir_all(path)
114}
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use std::sync::atomic::{AtomicU64, Ordering};
119 use std::time::{SystemTime, UNIX_EPOCH};
120
121 static NEXT_TEMP_FIXTURE_ID: AtomicU64 = AtomicU64::new(0);
122
123 #[test]
124 fn temp_output_stem_replaces_shell_metacharacters() {
125 let input = unique_temp_input("a&calc&.md");
126 let output = temp_output_for(&input).expect("temp path should be built");
127 let file_name = output
128 .file_name()
129 .and_then(|s| s.to_str())
130 .expect("temp path should end with unicode filename");
131
132 assert_eq!(file_name, "a_calc_.html");
133 assert!(!file_name.contains('&'));
134
135 cleanup_temp_fixture(&input, &output);
136 }
137
138 #[test]
139 fn temp_output_stem_keeps_readable_normal_names() {
140 let input = unique_temp_input("résumé-draft_2026.md");
141 let output = temp_output_for(&input).expect("temp path should be built");
142 let file_name = output
143 .file_name()
144 .and_then(|s| s.to_str())
145 .expect("temp path should end with unicode filename");
146
147 assert_eq!(file_name, "résumé-draft_2026.html");
148
149 cleanup_temp_fixture(&input, &output);
150 }
151
152 fn unique_temp_input(file_name: &str) -> PathBuf {
153 let nonce = SystemTime::now()
154 .duration_since(UNIX_EPOCH)
155 .expect("system time should be after epoch")
156 .as_nanos();
157 let counter = NEXT_TEMP_FIXTURE_ID.fetch_add(1, Ordering::Relaxed);
158 let dir = std::env::temp_dir().join(format!(
159 "mdo-unit-test-{}-{nonce}-{counter}",
160 std::process::id()
161 ));
162 fs::create_dir_all(&dir).expect("test temp dir should be created");
163 let input = dir.join(file_name);
164 fs::write(&input, "# Test\n").expect("test input should be written");
165 input
166 }
167
168 fn cleanup_temp_fixture(input: &Path, output: &Path) {
169 if let Some(parent) = output.parent() {
170 let _ = fs::remove_dir_all(parent);
171 }
172 if let Some(parent) = input.parent() {
173 let _ = fs::remove_dir_all(parent);
174 }
175 }
176}