Skip to main content

hypermail/
file_utils.rs

1use crate::config::Config;
2use crate::message::EmailInfo;
3use chrono::{Local, TimeZone, Utc};
4use std::fs;
5use std::path::{Path, PathBuf};
6
7/// Apply configured permissions to a path (Unix only).
8#[cfg(unix)]
9pub fn apply_permissions(path: &Path, mode: i32) {
10    use std::os::unix::fs::PermissionsExt;
11    let perms = std::fs::Permissions::from_mode(mode as u32);
12    if let Err(e) = std::fs::set_permissions(path, perms) {
13        log::debug!("Failed to set permissions on {:?}: {}", path, e);
14    }
15}
16
17/// Apply configured permissions to a path (no-op on non-Unix platforms).
18#[cfg(not(unix))]
19pub fn apply_permissions(_path: &Path, _mode: i32) {
20    // Permissions are Unix-only; no-op on other platforms
21}
22
23/// Generates a unique name for an email message.
24///
25/// Uses either sequential numbering (default) or content-based hashing
26/// when `config.nonsequential` is enabled.
27///
28/// # Arguments
29///
30/// * `email` - The email to generate a name for
31/// * `config` - Configuration determining naming scheme
32///
33/// # Returns
34///
35/// - Sequential: `"0001"`, `"0042"`, etc. (4 digits, zero-padded)
36/// - Hashed: `"a3f2c891be4f3210"` (16 hex digits from FNV32 hash)
37///
38/// # Security
39///
40/// The hashed mode uses FNV-1a to prevent predictable filenames, which
41/// could be used to guess Message-IDs. The hash includes both message ID
42/// and timestamp for uniqueness.
43pub fn message_name(email: &EmailInfo, config: &Config) -> String {
44    if config.nonsequential {
45        if let Some(ref msgid) = email.msgid {
46            let hash = fnv32(msgid.as_bytes(), email.from_date);
47            return format!("{:08x}{:08x}", hash, email.from_date as u32);
48        }
49    }
50    format!("{:04}", email.msgnum)
51}
52
53/// FNV-1a 32-bit hash function.
54///
55/// Computes a hash using the FNV-1a algorithm with an optional seed.
56/// This is used for generating content-based filenames that don't reveal
57/// the original Message-ID.
58///
59/// # Security Note
60///
61/// Uses `wrapping_mul` intentionally as required by the FNV algorithm.
62/// Integer overflow is part of the hash specification and produces
63/// correct hash distribution.
64///
65/// # Arguments
66///
67/// * `buf` - Input bytes to hash
68/// * `seed` - Optional seed value (typically timestamp)
69///
70/// # Returns
71///
72/// 32-bit hash value as u32
73fn fnv32(buf: &[u8], seed: i64) -> u32 {
74    const FNV1_32_INIT: u32 = 0x811c9dc5;
75    const FNV_32_PRIME: u32 = 0x01000193;
76    let mut hash = FNV1_32_INIT;
77    for &b in buf {
78        hash ^= b as u32;
79        hash = hash.wrapping_mul(FNV_32_PRIME);
80    }
81    if seed != 0 {
82        for b in seed.to_le_bytes() {
83            hash ^= b as u32;
84            hash = hash.wrapping_mul(FNV_32_PRIME);
85        }
86    }
87    hash
88}
89
90/// Returns the full filename for a message (name + HTML suffix).
91pub fn message_filename(email: &EmailInfo, config: &Config) -> String {
92    format!("{}.{}", message_name(email, config), config.htmlsuffix)
93}
94
95/// Returns the full filesystem path for a message's HTML file.
96pub fn message_path(email: &EmailInfo, config: &Config) -> PathBuf {
97    let dir = config.dir.as_deref().unwrap_or(".");
98    let sub = msg_subdir(email, config);
99    let base = match sub {
100        Some(ref s) => PathBuf::from(dir).join(&s.subdir),
101        None => PathBuf::from(dir),
102    };
103    base.join(message_filename(email, config))
104}
105
106/// Returns the relative URL string for a message, including subdirectory if applicable.
107///
108/// When `config.current_output_subdir` names the same folder the message belongs
109/// to, the page being rendered already lives inside that folder, so the subdir
110/// prefix is omitted (otherwise e.g. a page at `2025/index.html` would link to
111/// `2025/0001.html`, which the browser resolves to the non-existent
112/// `2025/2025/0001.html`).
113pub fn message_url_str(email: &EmailInfo, config: &Config) -> String {
114    let sub = msg_subdir(email, config);
115    let filename = message_filename(email, config);
116    match sub {
117        Some(ref s) => {
118            let subdir = s.subdir.trim_end_matches('/');
119            if subdir.is_empty() {
120                return filename;
121            }
122            if config.current_output_subdir.as_deref() == Some(subdir) {
123                return filename;
124            }
125            format!("{}/{}", subdir, filename)
126        },
127        None => filename,
128    }
129}
130
131/// Returns the path to the message index file.
132pub fn messageindex_name(config: &Config) -> PathBuf {
133    PathBuf::from(config.dir.as_deref().unwrap_or(".")).join("msgindex")
134}
135
136/// Expands date format placeholders (`%y`, `%m`, `%d`, etc.) in a path template.
137pub fn dirpath(frmptr: &str) -> String {
138    let now = chrono::Local::now();
139    let mut result = String::new();
140    let mut chars = frmptr.chars();
141    while let Some(c) = chars.next() {
142        if c == '%' {
143            match chars.next() {
144                Some('d') => result.push_str(&now.format("%d").to_string()),
145                Some('D') => result.push_str(&now.format("%a").to_string()),
146                Some('j') => result.push_str(&now.format("%j").to_string()),
147                Some('m') => result.push_str(&now.format("%m").to_string()),
148                Some('M') => result.push_str(&now.format("%b").to_string()),
149                Some('y') => result.push_str(&now.format("%Y").to_string()),
150                Some('%') => result.push('%'),
151                Some(c) => {
152                    result.push('%');
153                    result.push(c);
154                },
155                None => result.push('%'),
156            }
157        } else {
158            result.push(c);
159        }
160    }
161    result
162}
163
164/// Information about the subdirectory for a message when using folder-based layouts.
165pub struct EmailSubdirInfo {
166    pub subdir: String,
167    pub full_path: String,
168    pub rel_path_to_top: String,
169    pub description: Option<String>,
170}
171
172/// Determines the subdirectory for a message based on folder configuration.
173pub fn msg_subdir(email: &EmailInfo, config: &Config) -> Option<EmailSubdirInfo> {
174    if config.msgsperfolder > 0 {
175        let subdir_no = email.msgnum / config.msgsperfolder;
176        let sub = format!("{}/", subdir_no);
177        let base = config.dir.as_deref().unwrap_or(".");
178        let full = PathBuf::from(base).join(&sub).to_string_lossy().to_string();
179        let rel = "../".repeat(sub.matches('/').count());
180        return Some(EmailSubdirInfo {
181            subdir: sub,
182            full_path: full,
183            rel_path_to_top: rel,
184            description: None,
185        });
186    }
187    if let Some(ref fbd) = config.folder_by_date {
188        if email.date > 0 {
189            if chrono::format::StrftimeItems::new(fbd)
190                .any(|item| matches!(item, chrono::format::Item::Error))
191            {
192                log::warn!("invalid folder_by_date format '{}', using flat layout", fbd);
193                return None;
194            }
195            let ts = Utc.timestamp_opt(email.date, 0).single().unwrap_or_default();
196            let sub = if config.gmtime {
197                ts.format(fbd).to_string()
198            } else {
199                ts.with_timezone(&Local).format(fbd).to_string()
200            };
201            // Security: reject path traversal attempts via format string
202            if sub.contains("..") || is_rooted_path(&sub) {
203                log::warn!("folder_by_date produced suspicious path '{}', using flat layout", sub);
204                return None;
205            }
206            let sub = if !sub.ends_with('/') {
207                format!("{}/", sub)
208            } else {
209                sub
210            };
211            let base = config.dir.as_deref().unwrap_or(".");
212            let full = PathBuf::from(base).join(&sub).to_string_lossy().to_string();
213            let depth = sub.matches('/').count();
214            let rel = if depth == 0 {
215                "./".to_string()
216            } else {
217                let mut r = String::new();
218                for _ in 0..depth {
219                    r.push_str("../");
220                }
221                r
222            };
223            return Some(EmailSubdirInfo {
224                subdir: sub,
225                full_path: full,
226                rel_path_to_top: rel,
227                description: None,
228            });
229        }
230    }
231    None
232}
233
234/// Returns true if `s` looks like an absolute/rooted path on *any* platform.
235///
236/// `Path::is_absolute()` only recognizes Windows drive/UNC prefixes on Windows,
237/// so a Unix-style `/etc/passwd` config value is (wrongly) "relative" there and
238/// slips past a naive absolute-path guard. Config values are always written with
239/// forward slashes regardless of host OS, so reject leading `/` or `\` and
240/// Windows drive prefixes (`C:`) uniformly.
241fn is_rooted_path(s: &str) -> bool {
242    s.starts_with('/')
243        || s.starts_with('\\')
244        || s.get(1..2) == Some(":")
245        || std::path::Path::new(s).is_absolute()
246}
247
248/// Creates a symlink pointing to the latest folder (if configured).
249///
250/// Target is the subdirectory of the newest message by date (folder_by_date or
251/// msgsperfolder layout). Relative link target matches classic Hypermail.
252pub fn symlink_latest(store: &crate::structs::EmailStore, config: &Config) -> std::io::Result<()> {
253    if let Some(ref latest) = config.latest_folder {
254        // Security: reject path traversal / absolute paths in the (operator-configured)
255        // latest_folder value, same guard as folder_by_date above — a misconfigured or
256        // malicious config could otherwise place a symlink outside the archive dir.
257        if latest.contains("..") || is_rooted_path(latest) {
258            log::warn!(
259                "latest_folder '{}' looks unsafe (absolute or contains ..); skipping symlink",
260                latest
261            );
262            return Ok(());
263        }
264        let dir = config.dir.as_deref().unwrap_or(".");
265        let link_path = PathBuf::from(dir).join(latest);
266        let target = latest_folder_target(store, config);
267        let _ = fs::remove_file(&link_path);
268        // Also remove if it is a directory symlink/junction
269        let _ = fs::remove_dir(&link_path);
270        #[cfg(unix)]
271        std::os::unix::fs::symlink(&target, &link_path)?;
272        #[cfg(windows)]
273        std::os::windows::fs::symlink_dir(&target, &link_path)?;
274    }
275    Ok(())
276}
277
278/// Relative path of the folder containing the newest message, or `"."` if flat layout.
279fn latest_folder_target(store: &crate::structs::EmailStore, config: &Config) -> String {
280    let mut best: Option<(i64, String)> = None;
281    for email in &store.emails {
282        if let Some(sub) = msg_subdir(email, config) {
283            let subdir = sub.subdir.trim_end_matches('/').to_string();
284            if subdir.is_empty() {
285                continue;
286            }
287            match best {
288                Some((d, _)) if email.date < d => {},
289                _ => best = Some((email.date, subdir)),
290            }
291        }
292    }
293    best.map(|(_, s)| s).unwrap_or_else(|| ".".to_string())
294}
295
296/// Creates a directory and all parent directories if they don't exist.
297pub fn checkdir(path: &str) -> std::io::Result<()> {
298    let p = Path::new(path);
299    if !p.exists() {
300        fs::create_dir_all(p)?;
301    }
302    Ok(())
303}
304
305/// Returns true if the archive directory contains no non-hidden files.
306pub fn is_empty_archive(config: &Config) -> bool {
307    let dir = config.dir.as_deref().unwrap_or(".");
308    if let Ok(entries) = fs::read_dir(dir) {
309        for entry in entries.flatten() {
310            if let Some(name) = entry.file_name().to_str() {
311                if !name.starts_with('.') {
312                    return false;
313                }
314            }
315        }
316    }
317    true
318}
319
320/// Writes the message index file mapping message numbers to filenames.
321pub fn write_messageindex(
322    store: &crate::structs::EmailStore,
323    config: &Config,
324) -> std::io::Result<()> {
325    let path = messageindex_name(config);
326    let mut content = String::new();
327    content.push_str(&format!("{:04} {:04}\n", 0, store.max_msgnum.max(0)));
328    for email in &store.emails {
329        let name = message_name(email, config);
330        content.push_str(&format!("{:04} {}\n", email.msgnum, name));
331    }
332    fs::write(&path, &content)
333}
334
335/// Reads the message index file, returning a table of message number to filename mappings.
336pub fn read_messageindex(config: &Config) -> std::io::Result<Vec<Option<String>>> {
337    let path = messageindex_name(config);
338    let content = fs::read_to_string(&path)?;
339    let mut lines = content.lines();
340    let mut table: Vec<Option<String>> = Vec::new();
341    if let Some(first) = lines.next() {
342        let parts: Vec<&str> = first.split_whitespace().collect();
343        let max_num: i32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
344        // Reject negative or implausibly large values to prevent DoS via a corrupted
345        // messageindex file: `(max_num + 1) as usize` would otherwise overflow or
346        // attempt to allocate gigabytes of `Vec` slots.
347        const MAX_MESSAGES: i32 = 100_000_000;
348        if !(0..=MAX_MESSAGES).contains(&max_num) {
349            return Err(std::io::Error::new(
350                std::io::ErrorKind::InvalidData,
351                format!("invalid message count in messageindex header: {}", max_num),
352            ));
353        }
354        let size = (max_num as usize).saturating_add(1);
355        table.resize(size, None);
356        for line in lines {
357            let parts: Vec<&str> = line.split_whitespace().collect();
358            if parts.len() >= 2 {
359                if let Ok(num) = parts[0].parse::<i32>() {
360                    if (num as usize) < table.len() {
361                        table[num as usize] = Some(parts[1].to_string());
362                    }
363                }
364            }
365        }
366    }
367    Ok(table)
368}
369
370/// Loads email metadata from existing HTML archive files for incremental updates.
371pub fn load_old_headers_from_html(store: &mut crate::structs::EmailStore, config: &Config) -> i32 {
372    let dir = config.dir.as_deref().unwrap_or(".");
373    let suffix = &config.htmlsuffix;
374    let mut count = 0;
375
376    let mut files = Vec::new();
377    collect_html_files(Path::new(dir), suffix, &mut files);
378    // Also scan subdirectories if using folders
379    if config.msgsperfolder > 0 || config.folder_by_date.is_some() {
380        if let Ok(entries) = fs::read_dir(dir) {
381            for entry in entries.flatten() {
382                let path = entry.path();
383                if path.is_dir() {
384                    collect_html_files(&path, suffix, &mut files);
385                }
386            }
387        }
388    }
389
390    for path in files {
391        let msgnum = if config.nonsequential {
392            if let Ok(content) = fs::read_to_string(&path) {
393                extract_msgnum_from_html(&content, &config.fragment_prefix).unwrap_or(0)
394            } else {
395                0
396            }
397        } else {
398            path.file_stem()
399                .and_then(|s| s.to_str())
400                .and_then(|s| s.parse::<i32>().ok())
401                .unwrap_or(0)
402        };
403        if msgnum == 0 {
404            continue;
405        }
406        if let Ok(content) = fs::read_to_string(&path) {
407            if let Some(email) = parse_old_html_comments(&content, msgnum) {
408                let idx = store.add_email(email);
409                store.insert_into_date_list(idx);
410                store.insert_into_subject_list(idx);
411                store.insert_into_author_list(idx);
412                count += 1;
413            }
414        }
415    }
416    count
417}
418
419fn collect_html_files(dir: &Path, suffix: &str, files: &mut Vec<PathBuf>) {
420    if let Ok(entries) = fs::read_dir(dir) {
421        for entry in entries.flatten() {
422            let path = entry.path();
423            if path.is_file() {
424                if let Some(ext) = path.extension() {
425                    if ext.to_string_lossy() == suffix {
426                        files.push(path);
427                    }
428                }
429            }
430        }
431    }
432}
433
434fn extract_msgnum_from_html(html: &str, fragment_prefix: &str) -> Option<i32> {
435    // New format: <article id="PREFIXmsgnum">
436    let id_needle_str = format!("<article id=\"{}\"", fragment_prefix);
437    let id_needle = id_needle_str.trim_end_matches('"');
438    if let Some(start) = html.find(id_needle) {
439        let after_prefix = start + id_needle.len();
440        if let Some(end) = html[after_prefix..].find('"') {
441            let msgnum_str = &html[after_prefix..after_prefix + end];
442            if let Ok(n) = msgnum_str.parse::<i32>() {
443                return Some(n);
444            }
445        }
446    }
447    // Legacy format: <a name="PREFIXmsgnum"> (for backward compatibility with old archives)
448    let needle_str = format!("<a name=\"{}\"", fragment_prefix);
449    let needle = needle_str.trim_end_matches('"');
450    if let Some(start) = html.find(needle) {
451        let after_prefix = start + needle.len();
452        if let Some(end) = html[after_prefix..].find('"') {
453            let msgnum_str = &html[after_prefix..after_prefix + end];
454            return msgnum_str.parse::<i32>().ok();
455        }
456    }
457    None
458}
459
460fn parse_old_html_comments(html: &str, msgnum: i32) -> Option<EmailInfo> {
461    let mut name = None;
462    let mut email_addr = None;
463    let mut subject = None;
464    let mut msgid = None;
465    let mut inreplyto = None;
466    let mut date_str = None;
467    let mut from_date_str = None;
468    let mut charset = None;
469    let mut is_deleted = 0;
470    let mut found_body = false;
471
472    for line in html.lines() {
473        let line = line.trim();
474        if let Some(val) = extract_comment(line, "received") {
475            from_date_str = Some(val.to_string());
476        } else if let Some(val) = extract_comment(line, "sent") {
477            date_str = Some(val.to_string());
478        } else if let Some(val) = extract_comment(line, "name") {
479            name = Some(val.to_string());
480        } else if let Some(val) = extract_comment(line, "email") {
481            email_addr = Some(val.to_string());
482        } else if let Some(val) = extract_comment(line, "subject") {
483            subject = Some(val.to_string());
484        } else if let Some(val) = extract_comment(line, "id") {
485            msgid = Some(val.to_string());
486        } else if let Some(val) = extract_comment(line, "charset") {
487            charset = Some(val.to_string());
488        } else if let Some(val) = extract_comment(line, "inreplyto") {
489            inreplyto = Some(val.to_string());
490        } else if let Some(val) = extract_comment(line, "isdeleted") {
491            is_deleted = val.parse().unwrap_or(0);
492        } else if let Some(val) = extract_comment(line, "body") {
493            if val == "start" {
494                found_body = true;
495            }
496        }
497    }
498
499    if !found_body && msgid.is_none() {
500        return None;
501    }
502
503    // Restore timestamps for incremental updates / date-based folders
504    let date = date_str
505        .as_deref()
506        .and_then(parse_comment_timestamp)
507        .or_else(|| from_date_str.as_deref().and_then(parse_comment_timestamp))
508        .unwrap_or(0);
509    let from_date = from_date_str.as_deref().and_then(parse_comment_timestamp).unwrap_or(date);
510
511    Some(EmailInfo {
512        msgnum,
513        name,
514        email_addr,
515        from_date_str,
516        from_date,
517        date_str,
518        date,
519        datenum: date,
520        subject,
521        msgid,
522        inreplyto,
523        charset,
524        is_deleted,
525        ..Default::default()
526    })
527}
528
529/// Parse a timestamp from an HTML comment value (ISO or RFC 2822).
530fn parse_comment_timestamp(s: &str) -> Option<i64> {
531    crate::date::iso_to_secs(s)
532        .ok()
533        .or_else(|| crate::date::parse_rfc2822_date(s).ok())
534        .filter(|&t| t > 0)
535}
536
537fn extract_comment<'a>(line: &'a str, key: &str) -> Option<&'a str> {
538    let pattern = format!("<!-- {}=\"", key);
539    if let Some(start) = line.find(&pattern) {
540        let val_start = start + pattern.len();
541        if let Some(end) = line[val_start..].find('"') {
542            return Some(&line[val_start..val_start + end]);
543        }
544    }
545    None
546}
547
548/// Returns true if two Message-IDs match (trimmed comparison).
549pub fn matches_existing(msgid: &str, existing_msgid: &str) -> bool {
550    msgid.trim() == existing_msgid.trim()
551}
552
553/// Returns the path to the lock file for this archive.
554pub fn lock_file_name(config: &Config) -> PathBuf {
555    PathBuf::from(config.dir.as_deref().unwrap_or(".")).join(".hm_lock")
556}
557
558/// Acquires an exclusive non-blocking lock on the archive directory.
559#[allow(unsafe_code)]
560pub fn try_lock(config: &Config) -> std::io::Result<fs::File> {
561    let path = lock_file_name(config);
562    let file = fs::OpenOptions::new().write(true).create(true).truncate(true).open(&path)?;
563
564    #[cfg(unix)]
565    {
566        use std::os::unix::io::AsRawFd;
567
568        let fd = file.as_raw_fd();
569
570        // SAFETY: This is a safe FFI call to the POSIX flock() system call.
571        // - `fd` is a valid file descriptor obtained via AsRawFd()
572        // - flock() is a standard POSIX function that cannot cause UB with valid fd
573        // - LOCK_EX | LOCK_NB requests exclusive non-blocking lock (safe flags)
574        // - Return value is checked for errors
575        // - The file is owned by this function and fd remains valid
576        let ret = unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) };
577        if ret != 0 {
578            return Err(std::io::Error::last_os_error());
579        }
580    }
581
582    // Write PID on all platforms (best-effort advisory on non-Unix)
583    use std::io::Write;
584    let _ = write!(&file, "{}", std::process::id());
585
586    Ok(file)
587}
588
589#[cfg(test)]
590mod tests {
591    use super::*;
592    use crate::config::Config;
593    use crate::message::EmailInfo;
594
595    fn make_email(msgnum: i32, msgid: &str) -> EmailInfo {
596        EmailInfo { msgnum, msgid: Some(msgid.to_string()), date: 1000000, ..Default::default() }
597    }
598
599    #[test]
600    fn test_message_name_sequential() {
601        let config = Config::default();
602        let email = make_email(42, "<a@b>");
603        assert_eq!(message_name(&email, &config), "0042");
604    }
605
606    #[test]
607    fn test_message_name_nonsequential() {
608        let mut config = Config::default();
609        config.nonsequential = true;
610        let email = make_email(42, "<hello@world.com>");
611        let name = message_name(&email, &config);
612        assert_eq!(name.len(), 16);
613        assert!(name.chars().all(|c| c.is_ascii_hexdigit()));
614    }
615
616    #[test]
617    fn test_message_filename() {
618        let config = Config::default();
619        let email = make_email(7, "<a@b>");
620        assert_eq!(message_filename(&email, &config), "0007.html");
621    }
622
623    #[test]
624    fn test_fnv32_consistency() {
625        let h1 = fnv32(b"test", 0);
626        let h2 = fnv32(b"test", 0);
627        assert_eq!(h1, h2);
628    }
629
630    #[test]
631    fn test_fnv32_different() {
632        let h1 = fnv32(b"abc", 0);
633        let h2 = fnv32(b"xyz", 0);
634        assert_ne!(h1, h2);
635    }
636
637    #[test]
638    fn test_extract_comment() {
639        let line = "<!-- name=\"Alice\" -->";
640        assert_eq!(extract_comment(line, "name"), Some("Alice"));
641        assert_eq!(extract_comment(line, "subject"), None);
642    }
643
644    #[test]
645    fn test_matches_existing() {
646        assert!(matches_existing("<a@b>", "<a@b>"));
647        assert!(!matches_existing("<a@b>", "<c@d>"));
648    }
649
650    #[test]
651    fn test_dirpath() {
652        let result = dirpath("/archives/%y/%m");
653        assert!(result.starts_with("/archives/20"));
654    }
655
656    #[test]
657    fn test_message_url_str_sequential() {
658        let config = Config::default();
659        let email = make_email(42, "<a@b>");
660        assert_eq!(message_url_str(&email, &config), "0042.html");
661    }
662
663    #[test]
664    fn test_message_url_str_nonsequential() {
665        let mut config = Config::default();
666        config.nonsequential = true;
667        let email = make_email(42, "<hello@world.com>");
668        let url = message_url_str(&email, &config);
669        assert_eq!(url.len(), 21); // 16 hex + ".html"
670        assert!(url.ends_with(".html"));
671    }
672
673    #[test]
674    fn test_message_url_str_with_subdir() {
675        let mut config = Config::default();
676        config.msgsperfolder = 100;
677        let email = make_email(142, "<a@b>");
678        let url = message_url_str(&email, &config);
679        assert_eq!(url, "1/0142.html");
680    }
681
682    /// Regression test: when rendering a page that already lives inside the
683    /// message's folder (e.g. `2025/index.html`), message_url_str() must return
684    /// just the filename, not `folder/filename` (which would 404 as
685    /// `folder/folder/filename` once resolved relative to the page).
686    #[test]
687    fn test_message_url_str_omits_subdir_when_rendering_within_it() {
688        let mut config = Config::default();
689        config.msgsperfolder = 100;
690        config.current_output_subdir = Some("1".to_string());
691        let email = make_email(142, "<a@b>");
692        let url = message_url_str(&email, &config);
693        assert_eq!(url, "0142.html");
694    }
695
696    /// A different folder's output context must NOT suppress the prefix.
697    #[test]
698    fn test_message_url_str_keeps_subdir_for_other_folder_context() {
699        let mut config = Config::default();
700        config.msgsperfolder = 100;
701        config.current_output_subdir = Some("0".to_string());
702        let email = make_email(142, "<a@b>");
703        let url = message_url_str(&email, &config);
704        assert_eq!(url, "1/0142.html");
705    }
706
707    #[test]
708    fn test_extract_msgnum_from_html_basic() {
709        let html = r#"<html><body><article id="msg42"></article></body></html>"#;
710        let msgnum = extract_msgnum_from_html(html, "msg");
711        assert_eq!(msgnum, Some(42));
712    }
713
714    #[test]
715    fn test_extract_msgnum_from_html_no_match() {
716        let html = r#"<html><body>no anchor here</body></html>"#;
717        let msgnum = extract_msgnum_from_html(html, "msg");
718        assert_eq!(msgnum, None);
719    }
720
721    #[test]
722    fn test_extract_msgnum_from_html_invalid_prefix() {
723        let html = r#"<html><body><article id="HM_42"></article></body></html>"#;
724        let msgnum = extract_msgnum_from_html(html, "XYZ");
725        assert_eq!(msgnum, None);
726    }
727
728    #[test]
729    fn test_extract_msgnum_from_html_large_msgnum() {
730        let html = r#"<html><body><article id="msg9999999"></article></body></html>"#;
731        let msgnum = extract_msgnum_from_html(html, "msg");
732        assert_eq!(msgnum, Some(9999999));
733    }
734
735    #[test]
736    fn test_extract_msgnum_from_html_legacy_a_name() {
737        // Backward compatibility: old archives use <a name="msg42">
738        let html = r#"<html><body><a name="msg42"></a></body></html>"#;
739        let msgnum = extract_msgnum_from_html(html, "msg");
740        assert_eq!(msgnum, Some(42));
741    }
742
743    #[test]
744    fn test_checkdir_creates_directory() {
745        let tmp = tempfile::tempdir().unwrap();
746        let new_dir = tmp.path().join("new_subdir").to_string_lossy().to_string();
747        assert!(!std::path::Path::new(&new_dir).exists());
748        checkdir(&new_dir).unwrap();
749        assert!(std::path::Path::new(&new_dir).exists());
750    }
751
752    #[test]
753    fn test_checkdir_existing_dir_is_ok() {
754        let tmp = tempfile::tempdir().unwrap();
755        let result = checkdir(tmp.path().to_str().unwrap());
756        assert!(result.is_ok());
757    }
758
759    #[test]
760    fn test_is_empty_archive_empty_dir() {
761        let tmp = tempfile::tempdir().unwrap();
762        let mut config = Config::default();
763        config.dir = Some(tmp.path().to_str().unwrap().to_string());
764        assert!(is_empty_archive(&config));
765    }
766
767    #[test]
768    fn test_is_empty_archive_with_file() {
769        let tmp = tempfile::tempdir().unwrap();
770        std::fs::write(tmp.path().join("index.html"), "content").unwrap();
771        let mut config = Config::default();
772        config.dir = Some(tmp.path().to_str().unwrap().to_string());
773        assert!(!is_empty_archive(&config));
774    }
775
776    #[test]
777    fn test_is_empty_archive_hidden_file_ignored() {
778        let tmp = tempfile::tempdir().unwrap();
779        std::fs::write(tmp.path().join(".hidden"), "content").unwrap();
780        let mut config = Config::default();
781        config.dir = Some(tmp.path().to_str().unwrap().to_string());
782        assert!(is_empty_archive(&config));
783    }
784
785    #[test]
786    fn test_write_and_read_messageindex_roundtrip() {
787        let tmp = tempfile::tempdir().unwrap();
788        let mut config = Config::default();
789        config.dir = Some(tmp.path().to_str().unwrap().to_string());
790
791        let mut store = crate::structs::EmailStore::new();
792        store.add_email(make_email(0, "<a@b>"));
793        store.add_email(make_email(1, "<b@b>"));
794        store.add_email(make_email(2, "<c@b>"));
795
796        write_messageindex(&store, &config).unwrap();
797        let table = read_messageindex(&config).unwrap();
798
799        assert_eq!(table[0].as_deref(), Some("0000"));
800        assert_eq!(table[1].as_deref(), Some("0001"));
801        assert_eq!(table[2].as_deref(), Some("0002"));
802    }
803
804    #[test]
805    fn test_msg_subdir_msgsperfolder() {
806        let mut config = Config::default();
807        config.dir = Some("/tmp".to_string());
808        config.msgsperfolder = 100;
809
810        let email = make_email(250, "<a@b>");
811        let sub = msg_subdir(&email, &config);
812        assert!(sub.is_some());
813        let info = sub.unwrap();
814        assert_eq!(info.subdir, "2/");
815    }
816
817    #[test]
818    fn test_msg_subdir_first_folder_links_up() {
819        let mut config = Config::default();
820        config.msgsperfolder = 100;
821        let info = msg_subdir(&make_email(5, "<a@b>"), &config).unwrap();
822        assert_eq!(info.subdir, "0/");
823        assert_eq!(info.rel_path_to_top, "../");
824    }
825
826    #[test]
827    fn test_msg_subdir_none_by_default() {
828        let config = Config::default();
829        let email = make_email(42, "<a@b>");
830        assert!(msg_subdir(&email, &config).is_none());
831    }
832
833    #[test]
834    fn test_msg_subdir_invalid_date_format_uses_flat_layout() {
835        let config = Config { folder_by_date: Some("%Q".to_string()), ..Default::default() };
836        let mut email = make_email(1, "<a@b>");
837        email.date = 1615809600;
838        assert!(msg_subdir(&email, &config).is_none());
839    }
840
841    #[test]
842    fn test_message_path_sequential() {
843        let mut config = Config::default();
844        config.dir = Some("/tmp".to_string());
845        let email = make_email(7, "<a@b>");
846        let path = message_path(&email, &config);
847        assert!(path.to_string_lossy().ends_with("0007.html"));
848    }
849
850    #[test]
851    fn test_latest_folder_target_msgsperfolder() {
852        let mut config = Config::default();
853        config.dir = Some("/tmp".to_string());
854        config.msgsperfolder = 100;
855        let mut store = crate::structs::EmailStore::new();
856        let mut e1 = make_email(50, "<a@b>");
857        e1.date = 1000;
858        let mut e2 = make_email(250, "<c@d>");
859        e2.date = 2000;
860        store.add_email(e1);
861        store.add_email(e2);
862        let target = latest_folder_target(&store, &config);
863        assert_eq!(target, "2"); // msgnum 250 / 100
864    }
865
866    #[test]
867    fn test_latest_folder_target_flat() {
868        let config = Config::default();
869        let mut store = crate::structs::EmailStore::new();
870        store.add_email(make_email(1, "<a@b>"));
871        assert_eq!(latest_folder_target(&store, &config), ".");
872    }
873
874    #[test]
875    fn test_symlink_latest_rejects_path_traversal() {
876        let tmpdir = std::env::temp_dir().join(format!("hm_test_symlink_{}", std::process::id()));
877        let _ = fs::create_dir_all(&tmpdir);
878        let mut config = Config::default();
879        config.dir = Some(tmpdir.to_string_lossy().to_string());
880        config.latest_folder = Some("../../evil".to_string());
881        let store = crate::structs::EmailStore::new();
882        // Must not error (guard returns Ok early) and must not create anything outside tmpdir.
883        assert!(symlink_latest(&store, &config).is_ok());
884        let escaped = tmpdir.parent().unwrap().parent().unwrap().join("evil");
885        assert!(!escaped.exists());
886        let _ = fs::remove_dir_all(&tmpdir);
887    }
888
889    #[test]
890    fn test_symlink_latest_rejects_absolute_path() {
891        let tmpdir =
892            std::env::temp_dir().join(format!("hm_test_symlink_abs_{}", std::process::id()));
893        let _ = fs::create_dir_all(&tmpdir);
894        let mut config = Config::default();
895        config.dir = Some(tmpdir.to_string_lossy().to_string());
896        config.latest_folder = Some("/tmp/hm_evil_absolute_link".to_string());
897        let store = crate::structs::EmailStore::new();
898        assert!(symlink_latest(&store, &config).is_ok());
899        assert!(!PathBuf::from("/tmp/hm_evil_absolute_link").exists());
900        let _ = fs::remove_dir_all(&tmpdir);
901    }
902
903    #[test]
904    fn test_parse_comment_timestamp_rfc2822() {
905        let t = parse_comment_timestamp("Mon, 15 Mar 2021 12:00:00 +0000");
906        assert!(t.is_some());
907        assert!(t.unwrap() > 0);
908    }
909}