Skip to main content

hypermail/
config.rs

1use crate::error::{HypermailError, Result};
2use std::path::{Path, PathBuf};
3
4pub const ANTISPAM_AT: &str = "@";
5pub const LANGUAGE: &str = "en";
6pub const HTMLSUFFIX: &str = "html";
7pub const DEFAULTINDEX: &str = "date";
8pub const INLINE_TYPES: &str = "image/gif image/jpeg image/png";
9pub const PROGRESS: i32 = 0;
10pub const MAILCOMMAND: &str = "mailto:$TO?subject=$SUBJECT&in-reply-to=$ID";
11pub const DOMAINADDR: &str = "";
12
13pub const DELETE_REMOVES_FILES: i32 = 0;
14pub const DELETE_LEAVES_STUBS: i32 = 1;
15pub const DELETE_LEAVES_EXPIRED_TEXT: i32 = 2;
16pub const DELETE_LEAVES_TEXT: i32 = 3;
17
18/// Supported configuration value types for the hypermail config parser.
19#[derive(Debug, Clone)]
20pub enum ConfigType {
21    String,
22    Switch,
23    Integer,
24    List,
25    StringList,
26    Octal,
27}
28
29/// A single configuration entry definition with metadata for parsing.
30#[derive(Debug, Clone)]
31pub struct ConfigEntry {
32    pub label: &'static str,
33    pub flags: ConfigType,
34    pub default_str: Option<&'static str>,
35    pub default_int: i64,
36    pub verbose: &'static str,
37}
38
39/// A whitespace-separated list of values used for multi-value config options.
40#[derive(Debug, Clone)]
41pub struct HmList {
42    pub values: Vec<String>,
43}
44
45impl Default for HmList {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl HmList {
52    /// Creates an empty list.
53    pub fn new() -> Self {
54        HmList { values: Vec::new() }
55    }
56
57    /// Creates a list by splitting a whitespace-delimited string.
58    pub fn from_whitespace_str(s: &str) -> Self {
59        let values: Vec<String> = s.split_whitespace().map(|s| s.to_string()).collect();
60        HmList { values }
61    }
62
63    /// Returns true if the list contains the given value.
64    pub fn contains(&self, val: &str) -> bool {
65        self.values.iter().any(|v| v == val)
66    }
67
68    /// Adds a value to the list if not already present.
69    pub fn add(&mut self, val: &str) {
70        if !self.contains(val) {
71            self.values.push(val.to_string());
72        }
73    }
74
75    /// Splits a whitespace-delimited string and adds each token to the list.
76    pub fn add_list(&mut self, val: &str) {
77        for v in val.split_whitespace() {
78            self.add(v);
79        }
80    }
81}
82
83/// Complete runtime configuration for a hypermail archive run.
84///
85/// Controls input/output paths, HTML generation options, index types,
86/// spam protection, i18n, MIME handling, and template customization.
87#[derive(Debug, Clone)]
88pub struct Config {
89    // --- String configs ---
90    pub fragment_prefix: String,
91    pub htmlmessage_deleted: Option<String>,
92    pub antispam_at: String,
93    pub antispamdomain: Option<String>,
94    pub language: String,
95    pub htmlsuffix: String,
96    pub mbox: Option<String>,
97    pub archives: Option<String>,
98    pub custom_archives: Option<String>,
99    pub about: Option<String>,
100    pub label: Option<String>,
101    pub dir: Option<String>,
102    pub defaultindex: String,
103    pub default_top_index: String,
104    pub mailcommand: String,
105    pub newmsg_command: String,
106    pub replymsg_command: String,
107    pub inreplyto_command: Option<String>,
108    pub mailto: Option<String>,
109    pub hmail: Option<String>,
110    pub domainaddr: Option<String>,
111    pub css: Option<String>,
112    pub icss_url: Option<String>,
113    pub mcss_url: Option<String>,
114    pub dateformat: Option<String>,
115    pub indexdateformat: Option<String>,
116    pub stripsubject: Option<String>,
117    pub link_to_replies: Option<String>,
118    pub quote_link_string: Option<String>,
119    pub ihtmlheader: Option<String>,
120    pub ihtmlfooter: Option<String>,
121    pub ihtmlhead: Option<String>,
122    pub ihtmlhelpup: Option<String>,
123    pub ihtmlhelplow: Option<String>,
124    pub ihtmlnavbar2up: Option<String>,
125    pub mhtmlheader: Option<String>,
126    pub mhtmlfooter: Option<String>,
127    pub attachmentlink: Option<String>,
128    pub bodyheader: Option<String>,
129    pub bodyheaderend: Option<String>,
130    pub bodyfooter: Option<String>,
131    pub unsafe_chars: Option<String>,
132    pub filename_base: Option<String>,
133    pub folder_by_date: Option<String>,
134    pub latest_folder: Option<String>,
135    pub base_url: Option<String>,
136    pub describe_folder: Option<String>,
137    pub delete_older: Option<String>,
138    pub delete_newer: Option<String>,
139    pub alts_text: Option<String>,
140    pub description: Option<String>,
141    pub theme: Option<String>,
142    pub append_filename: Option<String>,
143    pub txtsuffix: Option<String>,
144    /// Internal (not user-configurable): set while rendering per-folder index
145    /// pages so `message_url_str()` knows the generated page already lives
146    /// inside this subdirectory, and can emit a filename-only link instead of
147    /// repeating the folder in the path (which would 404: `2025/2025/0001.html`).
148    pub current_output_subdir: Option<String>,
149
150    // --- Switch (bool) configs ---
151    pub email_address_obfuscation: bool,
152    pub i18n: bool,
153    pub i18n_body: bool,
154    pub overwrite: bool,
155    pub inlinehtml: bool,
156    pub readone: bool,
157    pub reverse: bool,
158    pub reverse_folders: bool,
159    pub showheaders: bool,
160    pub showbr: bool,
161    pub showreplies: bool,
162    pub indextable: bool,
163    pub iquotes: bool,
164    pub eurodate: bool,
165    pub gmtime: bool,
166    pub isodate: bool,
167    pub require_msgids: bool,
168    pub discard_dup_msgids: bool,
169    pub usemeta: bool,
170    pub uselock: bool,
171    pub ietf_mbox: bool,
172    pub linkquotes: bool,
173    pub monthly_index: bool,
174    pub yearly_index: bool,
175    pub spamprotect: bool,
176    pub spamprotect_id: bool,
177    pub attachmentsindex: bool,
178    pub usegdbm: bool,
179    pub writehaof: bool,
180    pub append: bool,
181    pub nonsequential: bool,
182    pub warn_surpressions: bool,
183    pub files_by_thread: bool,
184    pub href_detection: bool,
185    pub mbox_shortened: bool,
186    pub report_new_file: bool,
187    pub report_new_folder: bool,
188    pub use_sender_date: bool,
189    pub inline_addlink: bool,
190    pub iso2022jp: bool,
191    pub delete_incremental: bool,
192    pub showgenerator: bool,
193    pub show_warnings: bool,
194    /// When true (default), link Google Fonts CDN. Set false for offline/privacy.
195    pub external_fonts: bool,
196
197    // --- Integer configs ---
198    pub increment: i32,
199    pub showhtml: i32,
200    pub show_msg_links: i32,
201    pub show_index_links: i32,
202    pub thrdlevels: i32,
203    pub dirmode: i32,
204    pub filemode: i32,
205    pub locktime: i32,
206    pub searchbackmsgnum: i32,
207    pub quote_hide_threshold: i32,
208    pub thread_file_depth: i32,
209    pub startmsgnum: i32,
210    pub msgsperfolder: i32,
211    pub save_alts: i32,
212    pub delete_level: i32,
213    pub progress: i32,
214    pub max_message_size: usize,
215    /// Hard cap on messages kept in one run (DoS guard). 0 = unlimited.
216    pub max_messages: usize,
217
218    // --- List configs ---
219    pub show_headers: HmList,
220    pub avoid_indices: HmList,
221    pub avoid_top_indices: HmList,
222    pub skip_headers: HmList,
223    pub text_types: HmList,
224    pub inline_types: HmList,
225    pub prefered_types: HmList,
226    pub ignore_types: HmList,
227    pub filter_out: HmList,
228    pub filter_require: HmList,
229    pub filter_out_full_body: HmList,
230    pub filter_require_full_body: HmList,
231    pub deleted: HmList,
232    pub expires: HmList,
233    pub delete_msgnum: HmList,
234}
235
236impl Default for Config {
237    fn default() -> Self {
238        Config {
239            fragment_prefix: "msg".to_string(),
240            htmlmessage_deleted: None,
241            antispam_at: ANTISPAM_AT.to_string(),
242            antispamdomain: None,
243            language: LANGUAGE.to_string(),
244            htmlsuffix: HTMLSUFFIX.to_string(),
245            mbox: None,
246            archives: None,
247            custom_archives: None,
248            about: None,
249            label: None,
250            dir: None,
251            defaultindex: DEFAULTINDEX.to_string(),
252            default_top_index: "folders".to_string(),
253            mailcommand: MAILCOMMAND.to_string(),
254            newmsg_command: "mailto:$TO".to_string(),
255            replymsg_command: MAILCOMMAND.to_string(),
256            inreplyto_command: None,
257            mailto: None,
258            hmail: None,
259            domainaddr: None,
260            css: None,
261            icss_url: None,
262            mcss_url: None,
263            dateformat: None,
264            indexdateformat: None,
265            stripsubject: None,
266            link_to_replies: None,
267            quote_link_string: None,
268            ihtmlheader: None,
269            ihtmlfooter: None,
270            ihtmlhead: None,
271            ihtmlhelpup: None,
272            ihtmlhelplow: None,
273            ihtmlnavbar2up: None,
274            mhtmlheader: None,
275            mhtmlfooter: None,
276            attachmentlink: None,
277            unsafe_chars: None,
278            filename_base: None,
279            folder_by_date: None,
280            latest_folder: None,
281            base_url: None,
282            describe_folder: None,
283            delete_older: None,
284            delete_newer: None,
285            alts_text: None,
286            append_filename: None,
287            txtsuffix: None,
288            current_output_subdir: None,
289            description: None,
290            theme: None,
291            bodyheader: None,
292            bodyheaderend: None,
293            bodyfooter: None,
294            email_address_obfuscation: false,
295            i18n: false,
296            i18n_body: false,
297            overwrite: false,
298            inlinehtml: true,
299            readone: false,
300            reverse: false,
301            reverse_folders: false,
302            showheaders: true,
303            showbr: true,
304            showreplies: true,
305            indextable: false,
306            iquotes: true,
307            eurodate: true,
308            gmtime: false,
309            isodate: false,
310            require_msgids: true,
311            discard_dup_msgids: true,
312            usemeta: false,
313            uselock: true,
314            ietf_mbox: false,
315            linkquotes: false,
316            monthly_index: false,
317            yearly_index: false,
318            spamprotect: true,
319            spamprotect_id: true,
320            attachmentsindex: true,
321            usegdbm: false,
322            writehaof: false,
323            append: false,
324            nonsequential: false,
325            warn_surpressions: true,
326            files_by_thread: false,
327            href_detection: true,
328            mbox_shortened: false,
329            report_new_file: false,
330            report_new_folder: false,
331            use_sender_date: false,
332            inline_addlink: true,
333            iso2022jp: false,
334            delete_incremental: true,
335            showgenerator: true,
336            show_warnings: false,
337            external_fonts: true,
338            increment: 0,
339            showhtml: 1,
340            show_msg_links: 1,
341            show_index_links: 1,
342            thrdlevels: 50, // High default to show full tree structure
343            dirmode: 0o755,
344            filemode: 0o644,
345            locktime: 3600,
346            searchbackmsgnum: 500,
347            quote_hide_threshold: 100,
348            thread_file_depth: 0,
349            startmsgnum: 0,
350            msgsperfolder: 0,
351            save_alts: 0,
352            delete_level: DELETE_LEAVES_TEXT,
353            progress: PROGRESS,
354            max_message_size: 100 * 1024 * 1024,
355            max_messages: 1_000_000,
356            show_headers: HmList::new(),
357            avoid_indices: HmList::new(),
358            avoid_top_indices: HmList::new(),
359            skip_headers: HmList::new(),
360            text_types: HmList::new(),
361            inline_types: HmList::from_whitespace_str(INLINE_TYPES),
362            deleted: HmList::from_whitespace_str("X-Hypermail-Deleted X-No-Archive"),
363            expires: HmList::from_whitespace_str("Expires"),
364            delete_msgnum: HmList::new(),
365            filter_out: HmList::new(),
366            filter_require: HmList::new(),
367            filter_out_full_body: HmList::new(),
368            filter_require_full_body: HmList::new(),
369            prefered_types: HmList::new(),
370            ignore_types: HmList::new(),
371        }
372    }
373}
374
375impl Config {
376    /// Sets a string configuration value by key name.
377    pub fn set_string(&mut self, key: &str, val: &str) -> Result<()> {
378        match key {
379            "fragment_prefix" => self.fragment_prefix = val.to_string(),
380            "htmlmessage_deleted" => self.htmlmessage_deleted = Some(val.to_string()),
381            "antispam_at" => self.antispam_at = val.to_string(),
382            "antispamdomain" => {
383                if val == "NONE" || val.is_empty() {
384                    self.antispamdomain = None;
385                } else {
386                    self.antispamdomain = Some(val.to_string());
387                }
388            },
389            "language" => self.language = val.to_string(),
390            "htmlsuffix" => self.htmlsuffix = val.to_string(),
391            "mbox" => {
392                if val == "NONE" {
393                    self.mbox = None;
394                } else {
395                    self.mbox = Some(val.to_string());
396                }
397            },
398            "archives" => {
399                if val == "NONE" {
400                    self.archives = None;
401                } else {
402                    self.archives = Some(val.to_string());
403                }
404            },
405            "custom_archives" => {
406                if val == "NONE" {
407                    self.custom_archives = None;
408                } else {
409                    self.custom_archives = Some(val.to_string());
410                }
411            },
412            "about" => {
413                if val == "NONE" {
414                    self.about = None;
415                } else {
416                    self.about = Some(val.to_string());
417                }
418            },
419            "label" => {
420                if val == "NONE" {
421                    self.label = None;
422                } else {
423                    self.label = Some(val.to_string());
424                }
425            },
426            "dir" => {
427                if val == "NONE" {
428                    self.dir = None;
429                } else {
430                    self.dir = Some(val.to_string());
431                }
432            },
433            "defaultindex" => self.defaultindex = val.to_string(),
434            "default_top_index" => self.default_top_index = val.to_string(),
435            "mailcommand" => self.mailcommand = val.to_string(),
436            "newmsg_command" => self.newmsg_command = val.to_string(),
437            "replymsg_command" => self.replymsg_command = val.to_string(),
438            "inreplyto_command" => self.inreplyto_command = Some(val.to_string()),
439            "mailto" => {
440                if val == "NONE" {
441                    self.mailto = None;
442                } else {
443                    self.mailto = Some(val.to_string());
444                }
445            },
446            "hmail" => {
447                if val == "NONE" {
448                    self.hmail = None;
449                } else {
450                    self.hmail = Some(val.to_string());
451                }
452            },
453            "domainaddr" => {
454                if val == "NONE" {
455                    self.domainaddr = None;
456                } else {
457                    self.domainaddr = Some(val.to_string());
458                }
459            },
460            "css" => self.css = Some(val.to_string()),
461            "icss_url" => self.icss_url = Some(val.to_string()),
462            "mcss_url" => self.mcss_url = Some(val.to_string()),
463            "dateformat" => self.dateformat = Some(val.to_string()),
464            "indexdateformat" => self.indexdateformat = Some(val.to_string()),
465            "stripsubject" => self.stripsubject = Some(val.to_string()),
466            "link_to_replies" => self.link_to_replies = Some(val.to_string()),
467            "quote_link_string" => self.quote_link_string = Some(val.to_string()),
468            "ihtmlheaderfile" => self.ihtmlheader = Some(val.to_string()),
469            "ihtmlfooterfile" => self.ihtmlfooter = Some(val.to_string()),
470            "ihtmlheadfile" => self.ihtmlhead = Some(val.to_string()),
471            "ihtmlhelpupfile" => self.ihtmlhelpup = Some(val.to_string()),
472            "ihtmlhelplowfile" => self.ihtmlhelplow = Some(val.to_string()),
473            "ihtmlnavbar2upfile" => self.ihtmlnavbar2up = Some(val.to_string()),
474            "mhtmlheaderfile" => self.mhtmlheader = Some(val.to_string()),
475            "mhtmlfooterfile" => self.mhtmlfooter = Some(val.to_string()),
476            // Aliases that apply to both index and message pages simultaneously.
477            "htmlheaderfile" => {
478                self.ihtmlheader = Some(val.to_string());
479                self.mhtmlheader = Some(val.to_string());
480            },
481            "htmlfooterfile" => {
482                self.ihtmlfooter = Some(val.to_string());
483                self.mhtmlfooter = Some(val.to_string());
484            },
485            "attachmentlink" => self.attachmentlink = Some(val.to_string()),
486            "unsafe_chars" => self.unsafe_chars = Some(val.to_string()),
487            "description" => self.description = Some(val.to_string()),
488            "theme" => self.theme = Some(val.to_string()),
489            "bodyheader" => self.bodyheader = Some(val.to_string()),
490            "bodyheaderend" => self.bodyheaderend = Some(val.to_string()),
491            "bodyfooter" => self.bodyfooter = Some(val.to_string()),
492            "filename_base" => self.filename_base = Some(val.to_string()),
493            "folder_by_date" => {
494                if val.is_empty() || val == "NONE" {
495                    self.folder_by_date = None;
496                } else {
497                    self.folder_by_date = Some(val.to_string());
498                }
499            },
500            "latest_folder" => self.latest_folder = Some(val.to_string()),
501            "base_url" => self.base_url = Some(val.to_string()),
502            "describe_folder" => self.describe_folder = Some(val.to_string()),
503            "delete_older" => {
504                self.delete_older = if val.is_empty() {
505                    None
506                } else {
507                    Some(val.to_string())
508                }
509            },
510            "delete_newer" => {
511                self.delete_newer = if val.is_empty() {
512                    None
513                } else {
514                    Some(val.to_string())
515                }
516            },
517            "alts_text" => self.alts_text = Some(val.to_string()),
518            "append_filename" => self.append_filename = Some(val.to_string()),
519            "txtsuffix" => self.txtsuffix = Some(val.to_string()),
520            _ => {
521                return Err(HypermailError::InvalidConfigValue {
522                    key: key.to_string(),
523                    message: format!("unknown string config key: {}", key),
524                })
525            },
526        }
527        Ok(())
528    }
529
530    /// Sets a boolean switch configuration value by key name.
531    pub fn set_switch(&mut self, key: &str, val: bool) -> Result<()> {
532        match key {
533            "email_address_obfuscation" => self.email_address_obfuscation = val,
534            "i18n" => self.i18n = val,
535            "i18n_body" => self.i18n_body = val,
536            "overwrite" => self.overwrite = val,
537            "inlinehtml" => self.inlinehtml = val,
538            "readone" => self.readone = val,
539            "reverse" => self.reverse = val,
540            "reverse_folders" => self.reverse_folders = val,
541            "showheaders" => self.showheaders = val,
542            "showbr" => self.showbr = val,
543            "showreplies" => self.showreplies = val,
544            "indextable" => self.indextable = val,
545            "iquotes" => self.iquotes = val,
546            "eurodate" => self.eurodate = val,
547            "gmtime" => self.gmtime = val,
548            "isodate" => self.isodate = val,
549            "require_msgids" => self.require_msgids = val,
550            "discard_dup_msgids" => self.discard_dup_msgids = val,
551            "usemeta" => self.usemeta = val,
552            "uselock" => self.uselock = val,
553            "ietf_mbox" => self.ietf_mbox = val,
554            "linkquotes" => self.linkquotes = val,
555            "monthly_index" => self.monthly_index = val,
556            "yearly_index" => self.yearly_index = val,
557            "spamprotect" => self.spamprotect = val,
558            "spamprotect_id" => self.spamprotect_id = val,
559            "attachmentsindex" => self.attachmentsindex = val,
560            "usegdbm" => self.usegdbm = val,
561            "writehaof" => self.writehaof = val,
562            "append" => self.append = val,
563            "nonsequential" => self.nonsequential = val,
564            "warn_surpressions" => self.warn_surpressions = val,
565            "files_by_thread" => self.files_by_thread = val,
566            "href_detection" => self.href_detection = val,
567            "mbox_shortened" => self.mbox_shortened = val,
568            "report_new_file" => self.report_new_file = val,
569            "report_new_folder" => self.report_new_folder = val,
570            "use_sender_date" => self.use_sender_date = val,
571            "inline_addlink" => self.inline_addlink = val,
572            "iso2022jp" => self.iso2022jp = val,
573            "delete_incremental" => self.delete_incremental = val,
574            "showgenerator" => self.showgenerator = val,
575            "show_warnings" => self.show_warnings = val,
576            "external_fonts" => self.external_fonts = val,
577            _ => {
578                return Err(HypermailError::InvalidConfigValue {
579                    key: key.to_string(),
580                    message: format!("unknown switch config key: {}", key),
581                })
582            },
583        }
584        Ok(())
585    }
586
587    /// Sets an integer configuration value by key name.
588    pub fn set_integer(&mut self, key: &str, val: i64) -> Result<()> {
589        // `as` casts below would silently wrap (e.g. -1 -> usize::MAX disables size limits)
590        let unsigned = matches!(key, "max_message_size" | "max_messages");
591        if (!unsigned && i32::try_from(val).is_err())
592            || (unsigned && usize::try_from(val).is_err())
593            || (matches!(key, "filemode" | "dirmode") && !(0..=0o7777).contains(&val))
594        {
595            return Err(HypermailError::InvalidConfigValue {
596                key: key.to_string(),
597                message: format!("value out of range: {}", val),
598            });
599        }
600        match key {
601            "increment" => self.increment = val as i32,
602            "showhtml" => self.showhtml = val as i32,
603            "show_msg_links" => self.show_msg_links = val as i32,
604            "show_index_links" => self.show_index_links = val as i32,
605            "thrdlevels" => self.thrdlevels = val as i32,
606            "dirmode" => self.dirmode = val as i32,
607            "filemode" => self.filemode = val as i32,
608            "locktime" => self.locktime = val as i32,
609            "searchbackmsgnum" => self.searchbackmsgnum = val as i32,
610            "quote_hide_threshold" => self.quote_hide_threshold = val as i32,
611            "thread_file_depth" => self.thread_file_depth = val as i32,
612            "startmsgnum" => self.startmsgnum = val as i32,
613            "msgsperfolder" => self.msgsperfolder = val as i32,
614            "save_alts" => self.save_alts = val as i32,
615            "delete_level" => self.delete_level = val as i32,
616            "progress" => self.progress = val as i32,
617            "max_message_size" => self.max_message_size = val as usize,
618            "max_messages" => self.max_messages = val as usize,
619            _ => {
620                return Err(HypermailError::InvalidConfigValue {
621                    key: key.to_string(),
622                    message: format!("unknown integer config key: {}", key),
623                })
624            },
625        }
626        Ok(())
627    }
628
629    /// Appends whitespace-separated values to a list configuration by key name.
630    pub fn set_list(&mut self, key: &str, val: &str) -> Result<()> {
631        let list = match key {
632            "show_headers" => &mut self.show_headers,
633            "avoid_indices" => &mut self.avoid_indices,
634            "avoid_top_indices" => &mut self.avoid_top_indices,
635            "text_types" => &mut self.text_types,
636            "inline_types" => &mut self.inline_types,
637            "prefered_types" => &mut self.prefered_types,
638            "ignore_types" => &mut self.ignore_types,
639            "filter_out" => &mut self.filter_out,
640            "filter_require" => &mut self.filter_require,
641            "filter_out_full_body" => &mut self.filter_out_full_body,
642            "filter_require_full_body" => &mut self.filter_require_full_body,
643            "deleted" => &mut self.deleted,
644            "expires" => &mut self.expires,
645            "delete_msgnum" => &mut self.delete_msgnum,
646            _ => {
647                return Err(HypermailError::InvalidConfigValue {
648                    key: key.to_string(),
649                    message: format!("unknown list config key: {}", key),
650                })
651            },
652        };
653        list.add_list(val);
654        Ok(())
655    }
656
657    /// Applies a CLI argument, auto-detecting the value type (bool/int/string/list).
658    ///
659    /// Supports `key=value` syntax, `hm_` and `set_` prefixes, and ON/OFF/YES/NO values.
660    pub fn apply_cli_arg(&mut self, key: &str, val: &str) -> Result<()> {
661        let (actual_key, actual_val) = if let Some(eq_pos) = key.find('=') {
662            let k = &key[..eq_pos];
663            let v = &key[eq_pos + 1..];
664            (k, v)
665        } else {
666            (key, val)
667        };
668
669        let actual_key = actual_key.strip_prefix("hm_").unwrap_or(actual_key);
670        let actual_key = actual_key.strip_prefix("set_").unwrap_or(actual_key);
671
672        // Deprecated keys from C hypermail that are no longer functional.
673        // Return a recognizable error so callers can emit a deprecation warning.
674        if matches!(actual_key, "showhr" | "usetable" | "body") {
675            return Err(HypermailError::InvalidConfigValue {
676                key: actual_key.to_string(),
677                message: "deprecated config key — has no effect; remove from your config file"
678                    .to_string(),
679            });
680        }
681        let actual_val = actual_val.trim();
682
683        if actual_val == "ON"
684            || actual_val == "YES"
685            || actual_val == "On"
686            || actual_val == "Yes"
687            || actual_val == "on"
688            || actual_val == "yes"
689        {
690            if let Ok(()) = self.set_switch(actual_key, true) {
691                return Ok(());
692            }
693            return self
694                .set_integer(actual_key, 1)
695                .or_else(|_| self.set_string(actual_key, actual_val));
696        }
697        if (actual_val == "OFF"
698            || actual_val == "NO"
699            || actual_val == "Off"
700            || actual_val == "No"
701            || actual_val == "off"
702            || actual_val == "no")
703            && self.set_switch(actual_key, false).is_ok()
704        {
705            return Ok(());
706        }
707
708        // Octal parsing for permission modes (dirmode, filemode)
709        // Always parse as octal — "755" means 0o755, with or without leading zero
710        if actual_key == "dirmode" || actual_key == "filemode" {
711            let octal_str = actual_val.strip_prefix('0').unwrap_or(actual_val);
712            if let Ok(i) = i64::from_str_radix(octal_str, 8) {
713                if self.set_integer(actual_key, i).is_ok() {
714                    return Ok(());
715                }
716            }
717        }
718
719        let int_val = actual_val.parse::<i64>();
720        if let Ok(i) = int_val {
721            if self.set_integer(actual_key, i).is_ok() {
722                return Ok(());
723            }
724        }
725        if self.set_string(actual_key, actual_val).is_ok() {
726            return Ok(());
727        }
728        if self.set_list(actual_key, actual_val).is_ok() {
729            return Ok(());
730        }
731
732        Err(HypermailError::InvalidConfigValue {
733            key: actual_key.to_string(),
734            message: format!("unrecognized config key or invalid value: {}", actual_val),
735        })
736    }
737
738    /// Loads configuration from environment variables prefixed with `HM_`.
739    pub fn load_env(&mut self) {
740        self.load_env_from(std::env::vars());
741    }
742
743    /// Loads configuration from an iterator of `(key, value)` pairs prefixed with `HM_`.
744    /// Used directly in tests to avoid `set_var`/`remove_var` races.
745    fn load_env_from(&mut self, vars: impl Iterator<Item = (String, String)>) {
746        for (key, val) in vars {
747            if let Some(stripped) = key.strip_prefix("HM_") {
748                let config_key = stripped.to_lowercase();
749                let _ = self.apply_cli_arg(&config_key, &val);
750            }
751        }
752    }
753
754    /// Applies post-processing defaults (e.g., always-skipped headers).
755    pub fn post_process(&mut self) {
756        self.skip_headers.add("from");
757        self.skip_headers.add("date");
758        self.skip_headers.add("subject");
759    }
760
761    /// Returns the resolved CSS path, joining with `dir` if relative.
762    pub fn css_path(&self) -> String {
763        if let Some(ref css) = self.css {
764            if css.starts_with("http") || Path::new(css).is_absolute() {
765                css.clone()
766            } else if let Some(ref dir) = self.dir {
767                PathBuf::from(dir).join(css).to_string_lossy().into_owned()
768            } else {
769                css.clone()
770            }
771        } else {
772            String::new()
773        }
774    }
775}
776
777#[cfg(test)]
778mod tests {
779    use super::*;
780
781    #[test]
782    fn test_set_integer_rejects_out_of_range() {
783        let mut cfg = Config::default();
784        assert!(cfg.set_integer("max_message_size", -1).is_err());
785        assert!(cfg.set_integer("filemode", 4_294_967_295).is_err());
786        assert!(cfg.set_integer("max_message_size", 1000).is_ok());
787        assert_eq!(cfg.max_message_size, 1000);
788    }
789
790    #[test]
791    fn test_permission_modes_reject_negative_or_non_permission_bits() {
792        let mut config = Config::default();
793        for key in ["filemode", "dirmode"] {
794            assert!(config.set_integer(key, -1).is_err());
795            assert!(config.set_integer(key, 0o10000).is_err());
796            assert!(config.set_integer(key, 0o600).is_ok());
797        }
798    }
799
800    #[test]
801    fn test_default_config() {
802        let cfg = Config::default();
803        assert_eq!(cfg.language, "en");
804        assert_eq!(cfg.htmlsuffix, "html");
805        assert_eq!(cfg.defaultindex, "date");
806        assert!(cfg.inlinehtml);
807        assert!(!cfg.overwrite);
808        assert_eq!(cfg.showhtml, 1);
809        assert_eq!(cfg.thrdlevels, 50); // Changed from 4 to 50 for deeper thread display
810        assert_eq!(cfg.dirmode, 0o755);
811        assert_eq!(cfg.filemode, 0o644);
812        assert_eq!(cfg.locktime, 3600);
813        assert_eq!(cfg.searchbackmsgnum, 500);
814        assert_eq!(cfg.quote_hide_threshold, 100);
815        assert_eq!(cfg.delete_level, DELETE_LEAVES_TEXT);
816        assert!(cfg.discard_dup_msgids);
817        assert!(cfg.require_msgids);
818        assert!(cfg.uselock);
819        assert!(cfg.href_detection);
820        assert!(cfg.warn_surpressions);
821        assert!(cfg.attachmentsindex);
822        assert!(cfg.spamprotect);
823        assert!(cfg.spamprotect_id);
824        assert!(cfg.showbr);
825        assert!(cfg.showreplies);
826        assert!(cfg.inline_addlink);
827        assert!(cfg.delete_incremental);
828        assert_eq!(cfg.fragment_prefix, "msg");
829        assert_eq!(cfg.antispam_at, "@");
830        assert_eq!(cfg.progress, 0);
831        assert!(cfg.inline_types.contains("image/gif"));
832        assert!(cfg.deleted.contains("X-Hypermail-Deleted"));
833        assert!(cfg.expires.contains("Expires"));
834    }
835
836    #[test]
837    fn test_set_string() {
838        let mut cfg = Config::default();
839        cfg.set_string("language", "de").unwrap();
840        assert_eq!(cfg.language, "de");
841        cfg.set_string("mbox", "NONE").unwrap();
842        assert!(cfg.mbox.is_none());
843        cfg.set_string("label", "test list").unwrap();
844        assert_eq!(cfg.label.as_deref(), Some("test list"));
845    }
846
847    #[test]
848    fn test_set_switch() {
849        let mut cfg = Config::default();
850        assert!(!cfg.overwrite);
851        cfg.set_switch("overwrite", true).unwrap();
852        assert!(cfg.overwrite);
853    }
854
855    #[test]
856    fn test_set_integer() {
857        let mut cfg = Config::default();
858        cfg.set_integer("showhtml", 2).unwrap();
859        assert_eq!(cfg.showhtml, 2);
860        cfg.set_integer("thrdlevels", 8).unwrap();
861        assert_eq!(cfg.thrdlevels, 8);
862    }
863
864    #[test]
865    fn test_set_list() {
866        let mut cfg = Config::default();
867        cfg.set_list("text_types", "text/html text/plain").unwrap();
868        assert!(cfg.text_types.contains("text/html"));
869        assert!(cfg.text_types.contains("text/plain"));
870    }
871
872    #[test]
873    fn test_apply_cli_arg() {
874        let mut cfg = Config::default();
875        cfg.apply_cli_arg("overwrite", "On").unwrap();
876        assert!(cfg.overwrite);
877        cfg.apply_cli_arg("showhtml", "2").unwrap();
878        assert_eq!(cfg.showhtml, 2);
879        cfg.apply_cli_arg("language=de", "").unwrap();
880        assert_eq!(cfg.language, "de");
881    }
882
883    #[test]
884    fn test_post_process() {
885        let mut cfg = Config::default();
886        cfg.post_process();
887        assert!(cfg.skip_headers.contains("from"));
888        assert!(cfg.skip_headers.contains("date"));
889        assert!(cfg.skip_headers.contains("subject"));
890    }
891
892    #[test]
893    fn test_unknown_key() {
894        let mut cfg = Config::default();
895        assert!(cfg.set_string("nonexistent", "value").is_err());
896        assert!(cfg.set_switch("nonexistent", true).is_err());
897        assert!(cfg.set_integer("nonexistent", 42).is_err());
898    }
899
900    #[test]
901    fn test_none_strings() {
902        let mut cfg = Config::default();
903        cfg.set_string("archives", "NONE").unwrap();
904        assert!(cfg.archives.is_none());
905        cfg.set_string("about", "NONE").unwrap();
906        assert!(cfg.about.is_none());
907        cfg.set_string("custom_archives", "NONE").unwrap();
908        assert!(cfg.custom_archives.is_none());
909    }
910
911    #[test]
912    fn test_apply_cli_hm_prefix() {
913        let mut cfg = Config::default();
914        cfg.apply_cli_arg("hm_overwrite", "On").unwrap();
915        assert!(cfg.overwrite);
916    }
917
918    #[test]
919    fn test_apply_cli_set_prefix() {
920        let mut cfg = Config::default();
921        cfg.apply_cli_arg("set_overwrite", "On").unwrap();
922        assert!(cfg.overwrite);
923    }
924
925    #[test]
926    fn test_apply_cli_bool_yes() {
927        let mut cfg = Config::default();
928        cfg.apply_cli_arg("overwrite", "YES").unwrap();
929        assert!(cfg.overwrite);
930    }
931
932    #[test]
933    fn test_apply_cli_bool_no() {
934        let mut cfg = Config::default();
935        assert!(cfg.inlinehtml);
936        cfg.apply_cli_arg("inlinehtml", "OFF").unwrap();
937        assert!(!cfg.inlinehtml);
938    }
939
940    #[test]
941    fn test_apply_cli_octal_dirmode() {
942        let mut cfg = Config::default();
943        cfg.apply_cli_arg("dirmode", "0755").unwrap();
944        assert_eq!(cfg.dirmode, 0o755);
945    }
946
947    #[test]
948    fn test_apply_cli_octal_filemode() {
949        let mut cfg = Config::default();
950        cfg.apply_cli_arg("filemode", "0644").unwrap();
951        assert_eq!(cfg.filemode, 0o644);
952    }
953
954    #[test]
955    fn test_apply_cli_decimal_dirmode() {
956        let mut cfg = Config::default();
957        // "755" without leading zero is still parsed as octal for dirmode/filemode
958        cfg.apply_cli_arg("dirmode", "755").unwrap();
959        assert_eq!(cfg.dirmode, 0o755);
960    }
961
962    #[test]
963    fn test_apply_cli_inline_eq() {
964        let mut cfg = Config::default();
965        cfg.apply_cli_arg("language=fr", "").unwrap();
966        assert_eq!(cfg.language, "fr");
967    }
968
969    #[test]
970    fn test_apply_cli_list() {
971        let mut cfg = Config::default();
972        cfg.apply_cli_arg("filter_out", "spam").unwrap();
973        assert!(cfg.filter_out.contains("spam"));
974    }
975
976    #[test]
977    fn test_apply_cli_with_quoted_value() {
978        let mut cfg = Config::default();
979        cfg.apply_cli_arg("label", "\"My Archive\"").unwrap();
980        assert_eq!(cfg.label.as_deref(), Some("\"My Archive\""));
981    }
982
983    #[test]
984    fn test_apply_cli_unknown_key() {
985        let mut cfg = Config::default();
986        assert!(cfg.apply_cli_arg("nonexistent", "value").is_err());
987    }
988
989    #[test]
990    fn test_htmlheaderfile_sets_both_i_and_m() {
991        let mut cfg = Config::default();
992        cfg.apply_cli_arg("htmlheaderfile", "/path/to/header.html").unwrap();
993        assert_eq!(cfg.ihtmlheader.as_deref(), Some("/path/to/header.html"));
994        assert_eq!(cfg.mhtmlheader.as_deref(), Some("/path/to/header.html"));
995    }
996
997    #[test]
998    fn test_htmlfooterfile_sets_both_i_and_m() {
999        let mut cfg = Config::default();
1000        cfg.apply_cli_arg("htmlfooterfile", "/path/to/footer.html").unwrap();
1001        assert_eq!(cfg.ihtmlfooter.as_deref(), Some("/path/to/footer.html"));
1002        assert_eq!(cfg.mhtmlfooter.as_deref(), Some("/path/to/footer.html"));
1003    }
1004
1005    #[test]
1006    fn test_htmlheaderfile_does_not_override_specific_variants() {
1007        let mut cfg = Config::default();
1008        cfg.apply_cli_arg("ihtmlheaderfile", "/index/header.html").unwrap();
1009        cfg.apply_cli_arg("htmlheaderfile", "/shared/header.html").unwrap();
1010        // htmlheaderfile overwrites both — if you want per-page control, use the specific keys
1011        assert_eq!(cfg.ihtmlheader.as_deref(), Some("/shared/header.html"));
1012        assert_eq!(cfg.mhtmlheader.as_deref(), Some("/shared/header.html"));
1013    }
1014
1015    #[test]
1016    fn test_deprecated_showhr_returns_deprecation_error() {
1017        let mut cfg = Config::default();
1018        let err = cfg.apply_cli_arg("showhr", "1").unwrap_err();
1019        assert!(
1020            err.to_string().contains("deprecated config key"),
1021            "expected deprecation message, got: {err}"
1022        );
1023    }
1024
1025    #[test]
1026    fn test_deprecated_usetable_returns_deprecation_error() {
1027        let mut cfg = Config::default();
1028        let err = cfg.apply_cli_arg("usetable", "1").unwrap_err();
1029        assert!(
1030            err.to_string().contains("deprecated config key"),
1031            "expected deprecation message, got: {err}"
1032        );
1033    }
1034
1035    #[test]
1036    fn test_deprecated_body_returns_deprecation_error() {
1037        let mut cfg = Config::default();
1038        let err = cfg.apply_cli_arg("body", "1").unwrap_err();
1039        assert!(
1040            err.to_string().contains("deprecated config key"),
1041            "expected deprecation message, got: {err}"
1042        );
1043    }
1044
1045    #[test]
1046    fn test_env_loading() {
1047        let mut cfg = Config::default();
1048        let vars = vec![("HM_LANGUAGE".to_string(), "de".to_string())];
1049        cfg.load_env_from(vars.into_iter());
1050        assert_eq!(cfg.language, "de");
1051    }
1052
1053    #[test]
1054    fn test_set_all_switches() {
1055        let mut cfg = Config::default();
1056        for (key, initial) in &[
1057            ("email_address_obfuscation", false),
1058            ("i18n", true),
1059            ("i18n_body", false),
1060            ("overwrite", false),
1061            ("inlinehtml", true),
1062            ("readone", false),
1063            ("reverse", false),
1064            ("reverse_folders", false),
1065            ("showheaders", true),
1066            ("showbr", true),
1067            ("showreplies", true),
1068            ("indextable", false),
1069            ("iquotes", true),
1070            ("eurodate", true),
1071            ("gmtime", false),
1072            ("isodate", false),
1073            ("require_msgids", true),
1074            ("discard_dup_msgids", true),
1075            ("usemeta", false),
1076            ("uselock", true),
1077            ("ietf_mbox", false),
1078            ("linkquotes", false),
1079            ("monthly_index", false),
1080            ("yearly_index", false),
1081            ("spamprotect", true),
1082            ("spamprotect_id", true),
1083            ("attachmentsindex", true),
1084            ("usegdbm", false),
1085            ("writehaof", false),
1086            ("append", false),
1087            ("nonsequential", false),
1088            ("warn_surpressions", true),
1089            ("files_by_thread", false),
1090            ("href_detection", true),
1091            ("mbox_shortened", false),
1092            ("report_new_file", false),
1093            ("report_new_folder", false),
1094            ("use_sender_date", false),
1095            ("inline_addlink", true),
1096            ("iso2022jp", false),
1097            ("delete_incremental", true),
1098            ("showgenerator", true),
1099            ("show_warnings", false),
1100            ("external_fonts", true),
1101        ] {
1102            assert!(cfg.set_switch(key, *initial).is_ok(), "switch {} should exist", key);
1103        }
1104    }
1105
1106    #[test]
1107    fn test_set_all_integers() {
1108        let mut cfg = Config::default();
1109        for key in &[
1110            "increment",
1111            "showhtml",
1112            "show_msg_links",
1113            "show_index_links",
1114            "thrdlevels",
1115            "dirmode",
1116            "filemode",
1117            "locktime",
1118            "searchbackmsgnum",
1119            "quote_hide_threshold",
1120            "thread_file_depth",
1121            "startmsgnum",
1122            "msgsperfolder",
1123            "save_alts",
1124            "delete_level",
1125            "progress",
1126            "max_message_size",
1127            "max_messages",
1128        ] {
1129            assert!(cfg.set_integer(key, 1).is_ok(), "integer {} should exist", key);
1130        }
1131    }
1132
1133    #[test]
1134    fn test_set_all_strings() {
1135        let mut cfg = Config::default();
1136        for key in &[
1137            "fragment_prefix",
1138            "htmlmessage_deleted",
1139            "antispam_at",
1140            "antispamdomain",
1141            "language",
1142            "htmlsuffix",
1143            "mbox",
1144            "archives",
1145            "custom_archives",
1146            "about",
1147            "label",
1148            "dir",
1149            "defaultindex",
1150            "default_top_index",
1151            "mailcommand",
1152            "newmsg_command",
1153            "replymsg_command",
1154            "inreplyto_command",
1155            "mailto",
1156            "hmail",
1157            "domainaddr",
1158            "css",
1159            "icss_url",
1160            "mcss_url",
1161            "dateformat",
1162            "indexdateformat",
1163            "stripsubject",
1164            "link_to_replies",
1165            "quote_link_string",
1166            "ihtmlheaderfile",
1167            "ihtmlfooterfile",
1168            "ihtmlheadfile",
1169            "ihtmlhelpupfile",
1170            "ihtmlhelplowfile",
1171            "ihtmlnavbar2upfile",
1172            "mhtmlheaderfile",
1173            "mhtmlfooterfile",
1174            "htmlheaderfile",
1175            "htmlfooterfile",
1176            "attachmentlink",
1177            "bodyheader",
1178            "bodyheaderend",
1179            "bodyfooter",
1180            "unsafe_chars",
1181            "filename_base",
1182            "folder_by_date",
1183            "latest_folder",
1184            "base_url",
1185            "describe_folder",
1186            "delete_older",
1187            "delete_newer",
1188            "alts_text",
1189            "description",
1190            "theme",
1191            "append_filename",
1192            "txtsuffix",
1193        ] {
1194            assert!(cfg.set_string(key, "test").is_ok(), "string {} should exist", key);
1195        }
1196    }
1197
1198    #[test]
1199    fn test_set_all_lists() {
1200        let mut cfg = Config::default();
1201        for key in &[
1202            "show_headers",
1203            "avoid_indices",
1204            "avoid_top_indices",
1205            "text_types",
1206            "inline_types",
1207            "prefered_types",
1208            "ignore_types",
1209            "filter_out",
1210            "filter_require",
1211            "filter_out_full_body",
1212            "filter_require_full_body",
1213            "deleted",
1214            "expires",
1215            "delete_msgnum",
1216        ] {
1217            assert!(cfg.set_list(key, "test").is_ok(), "list {} should exist", key);
1218        }
1219    }
1220
1221    #[test]
1222    fn test_config_file_content_can_parse() {
1223        let config_content = "\
1224# comment
1225set language=de
1226hm_overwrite=On
1227nonsequential On
1228dirmode 0755
1229mbox mailbox/test
1230label \"My Archive\"
1231";
1232        // Verify each line can be parsed via apply_cli_arg
1233        let mut cfg = Config::default();
1234        for line in config_content.lines() {
1235            let line = line.trim();
1236            if line.is_empty() || line.starts_with('#') {
1237                continue;
1238            }
1239            let line = line.strip_prefix("set ").unwrap_or(line);
1240            let eq_pos = line.find('=').or_else(|| line.find(':'));
1241            if let Some(eq_pos) = eq_pos {
1242                let key = line[..eq_pos].trim();
1243                let val = line[eq_pos + 1..].trim();
1244                let val = val.trim_matches('"');
1245                cfg.apply_cli_arg(key, val).unwrap_or_else(|e| {
1246                    panic!("Failed to parse line '{}': {e}", line);
1247                });
1248            }
1249        }
1250        assert_eq!(cfg.language, "de");
1251        assert!(cfg.overwrite);
1252    }
1253
1254    #[test]
1255    fn test_antispamdomain_roundtrip() {
1256        let mut cfg = Config::default();
1257        cfg.set_string("antispamdomain", "nospam.invalid").unwrap();
1258        assert_eq!(cfg.antispamdomain.as_deref(), Some("nospam.invalid"));
1259    }
1260
1261    #[test]
1262    fn test_antispamdomain_none_on_empty() {
1263        let mut cfg = Config::default();
1264        cfg.set_string("antispamdomain", "").unwrap();
1265        assert!(cfg.antispamdomain.is_none());
1266    }
1267
1268    #[test]
1269    fn test_antispamdomain_none_on_keyword() {
1270        let mut cfg = Config::default();
1271        cfg.set_string("antispamdomain", "NONE").unwrap();
1272        assert!(cfg.antispamdomain.is_none());
1273    }
1274}