Skip to main content

hypermail/
txt2html.rs

1use crate::config::Config;
2use crate::message::BodyChain;
3use crate::quotes::{find_quote_class, is_sig_start, unquote};
4use crate::string_utils::conv_urls;
5
6/// Safe image MIME types for inline data-URI embedding.
7/// `image/svg+xml` is excluded — SVG can contain scripts.
8const SAFE_IMAGE_TYPES: &[&str] = &[
9    "image/gif",
10    "image/jpeg",
11    "image/jpg",
12    "image/png",
13    "image/webp",
14    "image/bmp",
15    "image/tiff",
16];
17
18/// Returns true if `s` is valid base64 alphabet only (A–Z, a–z, 0–9, +, /, =).
19/// Rejects quotes and other characters that could break out of HTML attributes.
20fn is_safe_base64(s: &str) -> bool {
21    !s.is_empty()
22        && s.bytes().all(|b| {
23            matches!(b,
24                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'/' | b'='
25            )
26        })
27}
28
29/// Build an inline image div if the line is a valid `[INLINE_IMAGE:…]` marker.
30fn try_inline_image_html(line: &str, pg_class: &str) -> Option<String> {
31    if !line.starts_with("[INLINE_IMAGE:") || !line.ends_with(']') {
32        return None;
33    }
34    let marker_content = line.strip_prefix("[INLINE_IMAGE:")?.strip_suffix(']')?;
35    let (mime_type, base64_data) = marker_content.split_once(':')?;
36    if !SAFE_IMAGE_TYPES.contains(&mime_type) || !is_safe_base64(base64_data) {
37        return None;
38    }
39    Some(format!(
40        "<div class=\"{}\"><img src=\"data:{};base64,{}\" alt=\"Embedded image\" style=\"max-width:100%;height:auto\"></div>\n",
41        pg_class, mime_type, base64_data
42    ))
43}
44
45fn txt2html_line(line: &str, config: &Config, in_sig: &mut bool) -> String {
46    let line = line.trim_end_matches('\n').trim_end_matches('\r');
47
48    if line.is_empty() {
49        // Emit a class-less marker that format_body() will collapse into a
50        // bare newline within the surrounding run, producing a real
51        // paragraph break inside one flowing pre-wrap block.
52        return String::from("<div class=\"hm-blank\"></div>\n");
53    }
54
55    if is_sig_start(line) {
56        *in_sig = true;
57        return String::from("<hr class=\"hm-sig\">\n");
58    }
59
60    // Determine CSS class: monospace for signatures, proportional for body/quotes
61    let pg_class = if *in_sig { "hm-sig-text" } else { "hm-pg" };
62
63    // Check for inline image marker: [INLINE_IMAGE:mime/type:base64data]
64    if let Some(html) = try_inline_image_html(line, pg_class) {
65        return html;
66    }
67
68    let is_quote = line.starts_with('>');
69    if is_quote {
70        let unquoted = unquote(line);
71        let quote_class = find_quote_class(line);
72        let with_links = if config.href_detection {
73            conv_urls(&unquoted)
74        } else {
75            escape_html(&unquoted)
76        };
77        format!("<div class=\"{}\">{}</div>\n", quote_class, with_links)
78    } else {
79        let with_links = if config.href_detection {
80            conv_urls(line)
81        } else {
82            escape_html(line)
83        };
84        format!("<div class=\"{}\">{}</div>\n", pg_class, with_links)
85    }
86}
87
88pub fn escape_html(s: &str) -> String {
89    let mut result = String::with_capacity(s.len());
90    for c in s.chars() {
91        match c {
92            '&' => result.push_str("&amp;"),
93            '<' => result.push_str("&lt;"),
94            '>' => result.push_str("&gt;"),
95            '"' => result.push_str("&quot;"),
96            '\'' => result.push_str("&#39;"),
97            '\t' => result.push_str("        "),
98            _ => result.push(c),
99        }
100    }
101    result
102}
103
104pub fn conv_showhtml(body: &mut BodyChain, config: &Config) {
105    let showhtml = config.showhtml;
106    let mut in_sig = false;
107
108    for b in &mut body.bodies {
109        if b.attached || b.header || b.converted {
110            continue;
111        }
112        b.converted = true;
113
114        // Detect signature start
115        let trimmed = b.line.trim_end_matches('\n').trim_end_matches('\r');
116        if is_sig_start(trimmed) {
117            in_sig = true;
118            b.line = String::from("<hr class=\"hm-sig\">\n");
119            continue;
120        }
121
122        let pg_class = if in_sig { "hm-sig-text" } else { "hm-pg" };
123
124        if b.html {
125            // Email HTML is untrusted even when it mimics our hm-* converter markup.
126            let escaped = escape_html(&b.line);
127            b.line = if escaped.is_empty() {
128                String::from("<div class=\"hm-blank\"></div>\n")
129            } else {
130                format!("<div class=\"{}\">{}</div>\n", pg_class, escaped)
131            };
132            continue;
133        }
134        // !b.html (plain text body)
135        // Wrap in <div> so format_body() does not double-escape (it trusts <div>/<hr> lines).
136        if showhtml == 0 {
137            let escaped = escape_html(&b.line);
138            b.line = if escaped.is_empty() {
139                String::from("<div class=\"hm-blank\"></div>\n")
140            } else {
141                format!("<div class=\"{}\">{}</div>\n", pg_class, escaped)
142            };
143            continue;
144        }
145        if showhtml == 1 {
146            // Check for inline image marker first (MIME type + base64 alphabet validated)
147            let line = b.line.trim_end_matches('\n').trim_end_matches('\r');
148            if let Some(html) = try_inline_image_html(line, pg_class) {
149                b.line = html;
150                continue;
151            }
152
153            // Normal text processing; linkify when href_detection is enabled (Hypermail default path)
154            let content = if config.href_detection {
155                conv_urls(&b.line)
156            } else {
157                escape_html(&b.line)
158            };
159            b.line = if content.is_empty() {
160                String::from("<div class=\"hm-blank\"></div>\n")
161            } else {
162                format!("<div class=\"{}\">{}</div>\n", pg_class, content)
163            };
164            continue;
165        }
166        b.line = txt2html_line(&b.line, config, &mut in_sig);
167    }
168}
169
170pub fn conv_body_line(line: &str, config: &Config) -> String {
171    if is_sig_start(line) {
172        return String::from("<hr class=\"hm-sig\">\n");
173    }
174
175    let is_quote = line.starts_with('>');
176    let with_links = if config.href_detection {
177        conv_urls(line)
178    } else {
179        escape_html(line)
180    };
181
182    if is_quote {
183        format!("<div class=\"{}\">{}</div>\n", find_quote_class_with_fallback(line), with_links)
184    } else {
185        format!("<div class=\"hm-pg\">{}</div>\n", with_links)
186    }
187}
188
189fn find_quote_class_with_fallback(line: &str) -> String {
190    let class = find_quote_class(line);
191    if class.is_empty() {
192        "hm-quote-1".to_string()
193    } else {
194        class
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use crate::config::Config;
202
203    fn make_config() -> Config {
204        Config::default()
205    }
206
207    #[test]
208    fn test_link_detection_escapes_once_and_stops_at_angle_brackets() {
209        let config = Config { href_detection: true, ..Default::default() };
210        for showhtml in [1, 2] {
211            let mut chain = make_body_chain("<https://example.com/?a=1&b=2> <script>bad</script>");
212            let config = Config { showhtml, ..config.clone() };
213            conv_showhtml(&mut chain, &config);
214            let output = &chain.bodies[0].line;
215            assert!(output.contains("href=\"https://example.com/?a=1&amp;b=2\""), "{output}");
216            assert!(output.contains("</a>&gt; &lt;script&gt;bad&lt;/script&gt;"), "{output}");
217            assert!(!output.contains("&amp;amp;"));
218        }
219        let output = conv_body_line("<https://example.com/?a=1&b=2>", &config);
220        assert!(output.contains("href=\"https://example.com/?a=1&amp;b=2\""), "{output}");
221    }
222
223    #[test]
224    fn test_escape_html() {
225        assert_eq!(escape_html("<test>"), "&lt;test&gt;");
226        assert_eq!(escape_html("a&b"), "a&amp;b");
227        assert_eq!(escape_html("hello"), "hello");
228    }
229
230    #[test]
231    fn test_txt2html_line_normal() {
232        let config = make_config();
233        let mut in_sig = false;
234        let result = txt2html_line("hello world", &config, &mut in_sig);
235        assert_eq!(result, "<div class=\"hm-pg\">hello world</div>\n");
236    }
237
238    #[test]
239    fn test_txt2html_line_quote() {
240        let config = make_config();
241        let mut in_sig = false;
242        let result = txt2html_line("> quoted text", &config, &mut in_sig);
243        assert!(result.contains("hm-quote-1"));
244        assert!(result.contains("quoted text"));
245    }
246
247    #[test]
248    fn test_txt2html_line_sig() {
249        let config = make_config();
250        let mut in_sig = false;
251        let result = txt2html_line("-- ", &config, &mut in_sig);
252        assert_eq!(result, "<hr class=\"hm-sig\">\n");
253        assert!(in_sig);
254    }
255
256    #[test]
257    fn test_txt2html_line_empty() {
258        let config = make_config();
259        let mut in_sig = false;
260        let result = txt2html_line("", &config, &mut in_sig);
261        assert_eq!(result, "<div class=\"hm-blank\"></div>\n");
262    }
263
264    #[test]
265    fn test_txt2html_line_urls() {
266        let config = make_config();
267        let mut in_sig = false;
268        let result = txt2html_line("Visit https://example.com", &config, &mut in_sig);
269        assert!(result.contains("<a href=\"https://example.com\""));
270        assert!(result.contains("rel=\"noopener noreferrer\""));
271    }
272
273    fn make_body_chain(text: &str) -> BodyChain {
274        let mut chain = BodyChain { bodies: Vec::new() };
275        chain.bodies.push(crate::message::Body {
276            line: text.to_string(),
277            html: false,
278            header: false,
279            parsed_header: false,
280            attached: false,
281            demimed: false,
282            converted: false,
283            msgnum: 1,
284        });
285        chain
286    }
287
288    #[test]
289    fn test_conv_showhtml_showhtml_0_escapes() {
290        let mut config = make_config();
291        config.showhtml = 0;
292        let mut chain = make_body_chain("<script>alert('xss')</script>");
293        conv_showhtml(&mut chain, &config);
294        // Wrapped in div so format_body does not double-escape
295        assert_eq!(
296            chain.bodies[0].line,
297            "<div class=\"hm-pg\">&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;</div>\n"
298        );
299    }
300
301    #[test]
302    fn test_conv_showhtml_showhtml_0_plain_text() {
303        let mut config = make_config();
304        config.showhtml = 0;
305        let mut chain = make_body_chain("Hello World");
306        conv_showhtml(&mut chain, &config);
307        assert_eq!(chain.bodies[0].line, "<div class=\"hm-pg\">Hello World</div>\n");
308    }
309
310    #[test]
311    fn test_inline_image_rejects_attribute_breakout() {
312        let config = make_config();
313        let mut in_sig = false;
314        let line = r#"[INLINE_IMAGE:image/png:x" onerror="alert(1)]"#;
315        let result = txt2html_line(line, &config, &mut in_sig);
316        // Must not emit an <img> data-URI; fall through to escaped text is OK.
317        assert!(!result.contains("<img"), "invalid marker must not become img tag: {}", result);
318        assert!(
319            !result.contains(r#"onerror=""#) && !result.contains("onerror='"),
320            "must not create an onerror attribute: {}",
321            result
322        );
323    }
324
325    #[test]
326    fn test_inline_image_rejects_empty_base64() {
327        let config = make_config();
328        let mut in_sig = false;
329        let line = "[INLINE_IMAGE:image/png:]";
330        let result = txt2html_line(line, &config, &mut in_sig);
331        assert!(!result.contains("<img"));
332    }
333
334    #[test]
335    fn test_conv_showhtml_showhtml_1_wraps_in_div() {
336        let mut config = make_config();
337        config.showhtml = 1;
338        let mut chain = make_body_chain("Hello World");
339        conv_showhtml(&mut chain, &config);
340        assert_eq!(chain.bodies[0].line, "<div class=\"hm-pg\">Hello World</div>\n");
341    }
342
343    #[test]
344    fn test_conv_showhtml_showhtml_1_escapes_xss() {
345        let mut config = make_config();
346        config.showhtml = 1;
347        let mut chain = make_body_chain("<script>bad</script>");
348        conv_showhtml(&mut chain, &config);
349        assert_eq!(
350            chain.bodies[0].line,
351            "<div class=\"hm-pg\">&lt;script&gt;bad&lt;/script&gt;</div>\n"
352        );
353    }
354
355    #[test]
356    fn test_conv_showhtml_showhtml_2_txt2html() {
357        let mut config = make_config();
358        config.showhtml = 2;
359        let mut chain = make_body_chain("> quote");
360        conv_showhtml(&mut chain, &config);
361        assert!(chain.bodies[0].line.contains("hm-quote"));
362    }
363
364    #[test]
365    fn test_conv_showhtml_attached_unchanged() {
366        let mut config = make_config();
367        config.showhtml = 0;
368        let mut chain = BodyChain { bodies: Vec::new() };
369        chain.bodies.push(crate::message::Body {
370            line: "<script>attack</script>".to_string(),
371            html: false,
372            header: false,
373            parsed_header: false,
374            attached: true,
375            demimed: false,
376            converted: false,
377            msgnum: 1,
378        });
379        conv_showhtml(&mut chain, &config);
380        // Attached bodies should not be processed
381        assert_eq!(chain.bodies[0].line, "<script>attack</script>");
382    }
383
384    #[test]
385    fn test_conv_showhtml_header_unchanged() {
386        let mut config = make_config();
387        config.showhtml = 0;
388        let mut chain = BodyChain { bodies: Vec::new() };
389        chain.bodies.push(crate::message::Body {
390            line: "<script>attack</script>".to_string(),
391            html: false,
392            header: true,
393            parsed_header: false,
394            attached: false,
395            demimed: false,
396            converted: false,
397            msgnum: 1,
398        });
399        conv_showhtml(&mut chain, &config);
400        assert_eq!(chain.bodies[0].line, "<script>attack</script>");
401    }
402
403    #[test]
404    fn test_txt2html_line_inline_image() {
405        let config = make_config();
406        let mut in_sig = false;
407        let line =
408            "[INLINE_IMAGE:image/gif:R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7]";
409        let result = txt2html_line(line, &config, &mut in_sig);
410
411        // Should convert to actual HTML img tag
412        assert!(
413            result.contains("<img src=\"data:image/gif;base64,"),
414            "Should convert marker to img tag"
415        );
416        assert!(
417            result.contains("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"),
418            "Should contain base64 data"
419        );
420        assert!(result.contains("alt=\"Embedded image\""), "Should have alt text");
421        assert!(!result.contains("[INLINE_IMAGE:"), "Should not contain marker text");
422    }
423
424    #[test]
425    fn test_txt2html_line_inline_image_jpeg() {
426        let config = make_config();
427        let mut in_sig = false;
428        let line = "[INLINE_IMAGE:image/jpeg:abcd1234]";
429        let result = txt2html_line(line, &config, &mut in_sig);
430
431        assert!(
432            result.contains("<img src=\"data:image/jpeg;base64,abcd1234\""),
433            "Should create data URI with correct MIME type"
434        );
435    }
436
437    #[test]
438    fn test_txt2html_sig_then_body_uses_sig_class() {
439        let config = make_config();
440        let mut in_sig = false;
441        let _ = txt2html_line("-- ", &config, &mut in_sig);
442        assert!(in_sig);
443        let result = txt2html_line("John Doe", &config, &mut in_sig);
444        assert_eq!(result, "<div class=\"hm-sig-text\">John Doe</div>\n");
445    }
446
447    #[test]
448    fn test_conv_body_line_plain() {
449        let config = make_config();
450        let result = conv_body_line("Hello world", &config);
451        assert_eq!(result, "<div class=\"hm-pg\">Hello world</div>\n");
452    }
453
454    #[test]
455    fn test_conv_body_line_quote() {
456        let config = make_config();
457        let result = conv_body_line("> quoted", &config);
458        assert!(result.contains("hm-quote-1"));
459        assert!(result.contains("quoted"));
460    }
461
462    #[test]
463    fn test_conv_body_line_sig() {
464        let config = make_config();
465        let result = conv_body_line("-- ", &config);
466        assert_eq!(result, "<hr class=\"hm-sig\">\n");
467    }
468
469    #[test]
470    fn test_conv_body_line_escapes_html() {
471        let config = make_config();
472        let result = conv_body_line("<b>bold</b>", &config);
473        assert!(result.contains("&lt;b&gt;"));
474        assert!(!result.contains("<b>"));
475    }
476
477    #[test]
478    fn test_escape_html_quote() {
479        assert_eq!(escape_html("it's"), "it&#39;s");
480    }
481
482    #[test]
483    fn test_escape_html_double_quote() {
484        assert_eq!(escape_html(r#"say "hi""#), "say &quot;hi&quot;");
485    }
486
487    #[test]
488    fn test_escape_html_tab_expanded() {
489        let result = escape_html("a\tb");
490        assert!(result.contains("        ")); // 8 spaces
491        assert!(!result.contains('\t'));
492    }
493
494    #[test]
495    fn test_inline_image_svg_blocked() {
496        let config = make_config();
497        let mut in_sig = false;
498        let line = "[INLINE_IMAGE:image/svg+xml:PHN2Zy8+]";
499        let result = txt2html_line(line, &config, &mut in_sig);
500        // SVG is not in the allowlist; should NOT produce an <img> tag
501        assert!(!result.contains("<img"), "SVG should be blocked from inline embedding");
502    }
503}