Skip to main content

hypermail/
mime.rs

1use crate::error::Result;
2
3/// Parsed MIME Content-Type header with type, subtype, and parameters.
4#[derive(Debug, Clone)]
5pub struct ContentType {
6    pub type_: String,
7    pub subtype: String,
8    pub params: std::collections::HashMap<String, String>,
9}
10
11impl ContentType {
12    /// Parses a Content-Type header value into structured components.
13    pub fn parse(s: &str) -> Self {
14        let s = s.trim();
15        let mut params = std::collections::HashMap::new();
16
17        let (base, param_str) = if let Some(semi) = s.find(';') {
18            (s[..semi].trim(), Some(s[semi + 1..].trim()))
19        } else {
20            (s, None)
21        };
22
23        let (type_, subtype) = if let Some(slash) = base.find('/') {
24            (base[..slash].trim().to_lowercase(), base[slash + 1..].trim().to_lowercase())
25        } else {
26            (base.to_lowercase(), "".to_string())
27        };
28
29        if let Some(pstr) = param_str {
30            for part in pstr.split(';') {
31                let part = part.trim();
32                if let Some(eq) = part.find('=') {
33                    let key = part[..eq].trim().to_lowercase();
34                    let mut val = part[eq + 1..].trim().to_string();
35                    if val.len() >= 2
36                        && ((val.starts_with('"') && val.ends_with('"'))
37                            || (val.starts_with('\'') && val.ends_with('\'')))
38                    {
39                        val = val[1..val.len() - 1].to_string();
40                    }
41                    params.insert(key, val);
42                }
43            }
44        }
45
46        ContentType { type_, subtype, params }
47    }
48
49    pub fn is_text(&self) -> bool {
50        self.type_ == "text"
51    }
52
53    pub fn is_multipart(&self) -> bool {
54        self.type_ == "multipart"
55    }
56
57    pub fn boundary(&self) -> Option<&str> {
58        self.params.get("boundary").map(|s| s.as_str())
59    }
60
61    pub fn charset(&self) -> Option<&str> {
62        self.params.get("charset").map(|s| s.as_str())
63    }
64
65    pub fn name(&self) -> Option<&str> {
66        self.params.get("name").map(|s| s.as_str())
67    }
68
69    pub fn full_type(&self) -> String {
70        format!("{}/{}", self.type_, self.subtype)
71    }
72}
73
74/// Parsed MIME Content-Disposition header with disposition type and parameters.
75#[derive(Debug, Clone)]
76pub struct ContentDisposition {
77    pub disposition: String,
78    pub params: std::collections::HashMap<String, String>,
79}
80
81impl ContentDisposition {
82    /// Parses a Content-Disposition header value into structured components.
83    pub fn parse(s: &str) -> Self {
84        let s = s.trim();
85        let mut params = std::collections::HashMap::new();
86
87        let (disp, param_str) = if let Some(semi) = s.find(';') {
88            (s[..semi].trim().to_lowercase(), Some(s[semi + 1..].trim()))
89        } else {
90            (s.to_lowercase(), None)
91        };
92
93        if let Some(pstr) = param_str {
94            for part in pstr.split(';') {
95                let part = part.trim();
96                if let Some(eq) = part.find('=') {
97                    let key = part[..eq].trim().to_lowercase();
98                    let mut val = part[eq + 1..].trim().to_string();
99                    if val.len() >= 2
100                        && ((val.starts_with('"') && val.ends_with('"'))
101                            || (val.starts_with('\'') && val.ends_with('\'')))
102                    {
103                        val = val[1..val.len() - 1].to_string();
104                    }
105                    params.insert(key, val);
106                }
107            }
108        }
109
110        ContentDisposition { disposition: disp, params }
111    }
112
113    pub fn filename(&self) -> Option<&str> {
114        self.params.get("filename").map(|s| s.as_str())
115    }
116
117    pub fn is_attachment(&self) -> bool {
118        self.disposition == "attachment"
119    }
120}
121
122fn hex_val(b: u8) -> Option<u8> {
123    match b {
124        b'0'..=b'9' => Some(b - b'0'),
125        b'A'..=b'F' => Some(b - b'A' + 10),
126        b'a'..=b'f' => Some(b - b'a' + 10),
127        _ => None,
128    }
129}
130
131/// Decodes base64-encoded data, ignoring whitespace.
132pub fn decode_base64(data: &[u8]) -> Result<Vec<u8>> {
133    let text = std::str::from_utf8(data)
134        .map_err(|e| crate::error::HypermailError::Parse(format!("Invalid base64 text: {e}")))?;
135
136    let clean: String = text.chars().filter(|c| !c.is_whitespace()).collect();
137
138    use base64::Engine as _;
139    let engine = base64::engine::general_purpose::STANDARD;
140    engine
141        .decode(&clean)
142        .map_err(|e| crate::error::HypermailError::Parse(format!("Base64 decode error: {e}")))
143}
144
145/// Decodes quoted-printable encoded data, handling soft line breaks and `_` as space.
146pub fn decode_quoted_printable(data: &[u8]) -> Vec<u8> {
147    let mut result = Vec::with_capacity(data.len());
148    let mut i = 0;
149    while i < data.len() {
150        if data[i] == b'=' {
151            if i + 2 < data.len() && data[i + 1] == b'\r' && data[i + 2] == b'\n' {
152                // Soft line break: =\r\n
153                i += 3;
154                continue;
155            }
156            if i + 1 < data.len() && data[i + 1] == b'\n' {
157                // Soft line break: =\n (Unix-style, no \r)
158                i += 2;
159                continue;
160            }
161            if i + 2 < data.len() {
162                if let (Some(h), Some(l)) = (hex_val(data[i + 1]), hex_val(data[i + 2])) {
163                    result.push(h << 4 | l);
164                    i += 3;
165                    continue;
166                }
167            }
168        }
169        if data[i] == b'_' {
170            result.push(b' ');
171        } else if data[i] != b'\r' {
172            result.push(data[i]);
173        }
174        i += 1;
175    }
176    result
177}
178
179/// Decodes uuencoded data, returning `None` if no valid uuencode block is found.
180pub fn decode_uuencode(data: &[u8]) -> Option<Vec<u8>> {
181    let text = std::str::from_utf8(data).ok()?;
182    let mut result = Vec::new();
183    let mut in_encoded = false;
184
185    for line in text.lines() {
186        let line = line.trim_end();
187        if line.starts_with("begin ") {
188            in_encoded = true;
189            continue;
190        }
191        if line == "end" || line == "`" {
192            in_encoded = false;
193            continue;
194        }
195        if !in_encoded || line.is_empty() {
196            continue;
197        }
198
199        let bytes = line.as_bytes();
200        if bytes.is_empty() {
201            continue;
202        }
203
204        let count = (bytes[0] as usize - 32) & 0x3f;
205        if count == 0 {
206            continue;
207        }
208
209        let mut buf = [0u8; 3];
210        let mut j = 1;
211        let mut out = 0;
212
213        while j < bytes.len() && out < count {
214            let mut chars = [0u8; 4];
215            let mut n = 0;
216            while n < 4 && j < bytes.len() {
217                chars[n] = bytes[j].wrapping_sub(32) & 0x3f;
218                j += 1;
219                n += 1;
220            }
221
222            if n >= 2 {
223                buf[0] = (chars[0] << 2) | (chars[1] >> 4);
224            }
225            if n >= 3 {
226                buf[1] = (chars[1] << 4) | (chars[2] >> 2);
227            }
228            if n >= 4 {
229                buf[2] = (chars[2] << 6) | chars[3];
230            }
231
232            let to_push = n.saturating_sub(1);
233            result.extend_from_slice(&buf[..to_push]);
234            out += to_push;
235        }
236    }
237
238    if result.is_empty() {
239        None
240    } else {
241        Some(result)
242    }
243}
244
245/// Combined MIME content-type and transfer-encoding information for a message part.
246#[derive(Debug, Clone)]
247pub struct MimeInfo {
248    pub content_type: ContentType,
249    pub content_transfer_encoding: Option<String>,
250}
251
252/// Extracts MIME info (content-type and transfer-encoding) from parsed headers.
253pub fn parse_mime_info(headers: &[(String, String)]) -> Option<MimeInfo> {
254    let ct_str = headers
255        .iter()
256        .find(|(name, _)| name.eq_ignore_ascii_case("content-type"))
257        .map(|(_, val)| val.as_str())?;
258
259    let content_type = ContentType::parse(ct_str);
260    let cte = headers
261        .iter()
262        .find(|(name, _)| name.eq_ignore_ascii_case("content-transfer-encoding"))
263        .map(|(_, val)| val.trim().to_lowercase());
264
265    Some(MimeInfo { content_type, content_transfer_encoding: cte })
266}
267
268fn find_multipart_charset(body: &[u8], boundary: &str) -> Option<String> {
269    let boundary_tag = format!("--{}", boundary);
270    let boundary_bytes = boundary_tag.as_bytes();
271    let mut pos = 0;
272
273    while pos < body.len() {
274        // Find next boundary starting from pos
275        let start =
276            match body[pos..].windows(boundary_bytes.len()).position(|w| w == boundary_bytes) {
277                Some(offset) => pos + offset,
278                None => break, // No more boundaries found, exit loop
279            };
280
281        let after_boundary = &body[start + boundary_bytes.len()..];
282
283        // Verify boundary is followed by newline (not just part of content)
284        let after_eol = if after_boundary.starts_with(b"\r\n") {
285            &after_boundary[2..]
286        } else if after_boundary.starts_with(b"\n") {
287            &after_boundary[1..]
288        } else {
289            // Not a valid boundary, continue searching
290            pos = start + 1;
291            continue;
292        };
293
294        // Find end of headers (empty line)
295        let header_end = after_eol
296            .windows(2)
297            .position(|w| w == b"\n\n")
298            .or_else(|| after_eol.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 2));
299
300        if let Some(header_end) = header_end {
301            let part_headers = &after_eol[..header_end];
302            if let Ok(header_block) = std::str::from_utf8(part_headers) {
303                for line in header_block.lines() {
304                    let lower = line.to_ascii_lowercase();
305                    if lower.starts_with("content-type:") {
306                        if let Some(charset_start) = lower.find("charset=") {
307                            let after = &line[charset_start + 8..];
308                            let charset = after.trim().trim_matches('"').trim_matches('\'');
309                            let charset =
310                                charset.split([';', ' ', '\r', '\n']).next().unwrap_or(charset);
311                            if !charset.is_empty() {
312                                return Some(charset.to_string());
313                            }
314                        }
315                    }
316                }
317            }
318        }
319
320        // Move past this boundary to search for next part
321        pos = start + boundary_bytes.len();
322    }
323    None
324}
325
326/// Decodes a MIME message body using its content-type and transfer-encoding.
327///
328/// Handles charset conversion, multipart boundaries, and format=flowed unwrapping.
329pub fn decode_body(body: &[u8], mime_info: &MimeInfo) -> String {
330    let decoded_bytes = match mime_info.content_transfer_encoding.as_deref() {
331        Some("base64") => match decode_base64(body) {
332            Ok(bytes) => bytes,
333            Err(_) => body.to_vec(),
334        },
335        Some("quoted-printable") | Some("qp") => decode_quoted_printable(body),
336        // 7bit, 8bit, binary → use raw bytes
337        _ => body.to_vec(),
338    };
339
340    let charset: Option<String> =
341        mime_info.content_type.charset().map(|s| s.to_string()).or_else(|| {
342            if mime_info.content_type.is_multipart() {
343                if let Some(boundary) = mime_info.content_type.boundary() {
344                    find_multipart_charset(body, boundary)
345                } else {
346                    None
347                }
348            } else {
349                None
350            }
351        });
352
353    // Use smart charset detection that handles mislabeled charsets
354    if let Some(ref charset) = charset {
355        return crate::headers::decode_to_utf8(&decoded_bytes, charset);
356    }
357
358    // No charset specified: try UTF-8 first, then common fallbacks
359    if let Ok(s) = std::str::from_utf8(&decoded_bytes) {
360        return s.to_string();
361    }
362
363    // Try common Greek/European charsets as fallback
364    for label in &["windows-1253", "iso-8859-7", "iso-8859-1", "windows-1252"] {
365        if let Some(encoding) = encoding_rs::Encoding::for_label(label.as_bytes()) {
366            let (cow, _, _) = encoding.decode(&decoded_bytes);
367            if !cow.contains('\u{FFFD}') {
368                return cow.into_owned();
369            }
370        }
371    }
372
373    String::from_utf8_lossy(&decoded_bytes).to_string()
374}
375
376/// QUAL-4: Variant of `decode_body` that skips internal charset resolution,
377/// using the already-resolved `charset` string instead.
378fn decode_body_with_charset(body: &[u8], mime_info: &MimeInfo, charset: Option<&str>) -> String {
379    let decoded_bytes = match mime_info.content_transfer_encoding.as_deref() {
380        Some("base64") => match decode_base64(body) {
381            Ok(bytes) => bytes,
382            Err(_) => body.to_vec(),
383        },
384        Some("quoted-printable") | Some("qp") => decode_quoted_printable(body),
385        _ => body.to_vec(),
386    };
387
388    if let Some(cs) = charset {
389        return crate::headers::decode_to_utf8(&decoded_bytes, cs);
390    }
391
392    if let Ok(s) = std::str::from_utf8(&decoded_bytes) {
393        return s.to_string();
394    }
395
396    for label in &["windows-1253", "iso-8859-7", "iso-8859-1", "windows-1252"] {
397        if let Some(encoding) = encoding_rs::Encoding::for_label(label.as_bytes()) {
398            let (cow, _, _) = encoding.decode(&decoded_bytes);
399            if !cow.contains('\u{FFFD}') {
400                return cow.into_owned();
401            }
402        }
403    }
404
405    String::from_utf8_lossy(&decoded_bytes).to_string()
406}
407
408fn resolve_charset(body_raw: &[u8], mi: &MimeInfo) -> Option<String> {
409    mi.content_type.charset().map(|s| s.to_string()).or_else(|| {
410        if mi.content_type.is_multipart() {
411            if let Some(boundary) = mi.content_type.boundary() {
412                find_multipart_charset(body_raw, boundary)
413            } else {
414                None
415            }
416        } else {
417            None
418        }
419    })
420}
421
422/// Maximum nested multipart depth to prevent stack overflow from crafted messages.
423const MAX_MULTIPART_DEPTH: u32 = 16;
424
425/// Processes a MIME message body, returning decoded text and detected charset.
426///
427/// Handles multipart messages, inline images, attachments, and charset detection.
428///
429/// # Security
430///
431/// Only safe image MIME types are embedded inline; SVG is excluded due to script risks.
432/// Nested multiparts are limited to [`MAX_MULTIPART_DEPTH`] levels.
433pub fn process_mime_body(
434    headers: &[(String, String)],
435    body_raw: &[u8],
436) -> (String, Option<String>) {
437    process_mime_body_depth(headers, body_raw, 0)
438}
439
440fn process_mime_body_depth(
441    headers: &[(String, String)],
442    body_raw: &[u8],
443    depth: u32,
444) -> (String, Option<String>) {
445    let mi = parse_mime_info(headers);
446    if let Some(ref mi) = mi {
447        // Check if this is a multipart message
448        if mi.content_type.is_multipart() {
449            if depth >= MAX_MULTIPART_DEPTH {
450                log::warn!(
451                    "multipart nesting depth limit ({}) exceeded; treating as plain text",
452                    MAX_MULTIPART_DEPTH
453                );
454                return (String::from_utf8_lossy(body_raw).to_string(), None);
455            }
456            if let Some(boundary) = mi.content_type.boundary() {
457                return process_multipart_body(body_raw, boundary, mi, depth);
458            }
459        }
460
461        let charset = resolve_charset(body_raw, mi);
462        // QUAL-4: Use decode_body_with_charset to avoid resolving charset twice.
463        let mut decoded = decode_body_with_charset(body_raw, mi, charset.as_deref());
464        // RFC 3676: unwrap format=flowed text
465        if mi
466            .content_type
467            .params
468            .get("format")
469            .map(|v| v.eq_ignore_ascii_case("flowed"))
470            .unwrap_or(false)
471        {
472            decoded = unflow_text(&decoded);
473        }
474        (decoded, charset)
475    } else {
476        // No Content-Type header: try UTF-8 first, then fallback charsets
477        if let Ok(s) = std::str::from_utf8(body_raw) {
478            return (s.to_string(), None);
479        }
480        for label in &["windows-1253", "iso-8859-7", "iso-8859-1", "windows-1252"] {
481            if let Some(encoding) = encoding_rs::Encoding::for_label(label.as_bytes()) {
482                let (cow, _, _) = encoding.decode(body_raw);
483                if !cow.contains('\u{FFFD}') {
484                    return (cow.into_owned(), Some(label.to_string()));
485                }
486            }
487        }
488        (String::from_utf8_lossy(body_raw).to_string(), None)
489    }
490}
491
492fn process_multipart_body(
493    body: &[u8],
494    boundary: &str,
495    parent_mime: &MimeInfo,
496    depth: u32,
497) -> (String, Option<String>) {
498    let is_alternative = parent_mime.content_type.subtype == "alternative";
499    let boundary_tag = format!("--{}", boundary);
500    let boundary_bytes = boundary_tag.as_bytes();
501    let mut result = String::new();
502    let mut detected_charset = None;
503    let mut pos = 0;
504
505    // For multipart/alternative: collect all text parts, then pick the best one.
506    // Prefer text/plain over text/html to avoid rendering raw HTML.
507    let mut alt_plain: Option<(String, Option<String>)> = None;
508    let mut alt_html: Option<(String, Option<String>)> = None;
509
510    while pos < body.len() {
511        // Find next boundary
512        let start =
513            match body[pos..].windows(boundary_bytes.len()).position(|w| w == boundary_bytes) {
514                Some(offset) => pos + offset,
515                None => break,
516            };
517
518        // Check for end boundary
519        let after_boundary = &body[start + boundary_bytes.len()..];
520        if after_boundary.starts_with(b"--") {
521            // End boundary found
522            break;
523        }
524
525        // Skip to content after boundary line
526        let after_eol = if after_boundary.starts_with(b"\r\n") {
527            &after_boundary[2..]
528        } else if after_boundary.starts_with(b"\n") {
529            &after_boundary[1..]
530        } else {
531            pos = start + boundary_bytes.len();
532            continue;
533        };
534
535        // Find end of part headers
536        let header_end = after_eol
537            .windows(2)
538            .position(|w| w == b"\n\n")
539            .or_else(|| after_eol.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 2));
540
541        if let Some(header_end) = header_end {
542            let part_headers_bytes = &after_eol[..header_end];
543            let part_body_start = header_end + 2;
544
545            // Find next boundary to determine part body end
546            let part_body = if let Some(next_boundary_pos) = after_eol[part_body_start..]
547                .windows(boundary_bytes.len())
548                .position(|w| w == boundary_bytes)
549            {
550                &after_eol[part_body_start..part_body_start + next_boundary_pos]
551            } else {
552                &after_eol[part_body_start..]
553            };
554
555            // Parse part headers
556            if let Ok(headers_str) = std::str::from_utf8(part_headers_bytes) {
557                let mut part_headers = Vec::new();
558                for line in headers_str.lines() {
559                    if let Some((name, value)) = line.split_once(':') {
560                        part_headers.push((name.trim().to_lowercase(), value.trim().to_string()));
561                    }
562                }
563
564                // Check if this part is an attachment, inline content, or has Content-ID
565                let mut is_attachment = false;
566                let mut _has_content_id = false;
567                let mut content_type_main = String::new();
568                let mut encoding = String::new();
569
570                for (name, value) in &part_headers {
571                    if name == "content-disposition" {
572                        is_attachment = value.to_lowercase().starts_with("attachment");
573                    }
574                    if name == "content-id" {
575                        _has_content_id = true;
576                    }
577                    if name == "content-type" {
578                        if let Some(main_type) = value.split(';').next() {
579                            content_type_main = main_type.trim().to_lowercase();
580                        }
581                    }
582                    if name == "content-transfer-encoding" {
583                        encoding = value.trim().to_lowercase();
584                    }
585                }
586
587                // Allowlist of safe image MIME types for inline embedding.
588                // image/svg+xml is excluded — SVG can contain scripts.
589                const SAFE_IMAGE_TYPES: &[&str] = &[
590                    "image/gif",
591                    "image/jpeg",
592                    "image/jpg",
593                    "image/png",
594                    "image/webp",
595                    "image/bmp",
596                    "image/tiff",
597                ];
598
599                // Determine how to handle this part
600                if content_type_main.starts_with("image/")
601                    && SAFE_IMAGE_TYPES.contains(&content_type_main.as_str())
602                {
603                    // Always embed images inline for the HTML archive — viewers browse,
604                    // they don't download.  Content-Disposition: attachment is an email-client
605                    // hint that does not apply here.  Only fall back to a link if the raw
606                    // data is missing or decoding fails.
607                    let image_data = if encoding == "base64" {
608                        decode_base64(part_body.trim_ascii()).ok()
609                    } else if !part_body.is_empty() {
610                        Some(part_body.to_vec())
611                    } else {
612                        None
613                    };
614
615                    if let Some(data) = image_data {
616                        use base64::Engine as _;
617                        let engine = base64::engine::general_purpose::STANDARD;
618                        let base64_data = engine.encode(&data);
619                        if !result.is_empty() {
620                            result.push('\n');
621                        }
622                        result.push_str(&format!(
623                            "[INLINE_IMAGE:{}:{}]\n",
624                            content_type_main, base64_data
625                        ));
626                    } else if let Some(filename) = extract_filename(&part_headers) {
627                        // Decoding failed — fall back to a named attachment link
628                        if !result.is_empty() {
629                            result.push('\n');
630                        }
631                        result.push_str(&format!("[Attachment: {}]\n", filename));
632                    }
633                } else if content_type_main.starts_with("image/")
634                    || is_attachment
635                    || content_type_main.starts_with("application/")
636                {
637                    // Non-safe image or non-image attachment - just note it
638                    if let Some(filename) = extract_filename(&part_headers) {
639                        if !result.is_empty() {
640                            result.push('\n');
641                        }
642                        result.push_str(&format!("[Attachment: {}]\n", filename));
643                    }
644                } else if content_type_main.starts_with("text/")
645                    || content_type_main.starts_with("multipart/")
646                    || content_type_main.is_empty()
647                {
648                    // Process text / nested multipart content (depth-limited)
649                    let (decoded, charset) =
650                        process_mime_body_depth(&part_headers, part_body, depth + 1);
651                    if is_alternative {
652                        // LOG-2: For multipart/alternative, collect parts separately.
653                        if content_type_main == "text/plain" || content_type_main.is_empty() {
654                            if alt_plain.is_none() {
655                                alt_plain = Some((decoded, charset));
656                            }
657                        } else if content_type_main == "text/html" && alt_html.is_none() {
658                            alt_html = Some((decoded, charset));
659                        }
660                        // other text/* subtypes ignored for alternative
661                    } else {
662                        if detected_charset.is_none() && charset.is_some() {
663                            detected_charset = charset;
664                        }
665                        if !result.is_empty() && !decoded.is_empty() {
666                            result.push('\n');
667                        }
668                        result.push_str(&decoded);
669                    }
670                }
671            }
672        }
673
674        // Move to next part
675        pos = start + boundary_bytes.len();
676    }
677
678    // LOG-2: For multipart/alternative, select the single best part.
679    // Prefer text/plain; fall back to text/html if no plain part exists.
680    if is_alternative {
681        let chosen = alt_plain.or(alt_html);
682        if let Some((text, charset)) = chosen {
683            return (text, charset);
684        }
685        return (result, detected_charset);
686    }
687
688    (result, detected_charset)
689}
690
691fn extract_filename(headers: &[(String, String)]) -> Option<String> {
692    for (name, value) in headers {
693        if name == "content-disposition" || name == "content-type" {
694            // Try RFC 2231 continuation first (filename*0=, filename*1=, ...)
695            if let Some(f) = extract_rfc2231_filename(value) {
696                return Some(f);
697            }
698            // Try RFC 2231 charset encoding (filename*=charset'lang'value)
699            if let Some(f) = extract_rfc2231_encoded_filename(value) {
700                return Some(f);
701            }
702            // Fall back to simple filename= or name=
703            for param in value.split(';') {
704                let param = param.trim();
705                if let Some(filename_part) =
706                    param.strip_prefix("filename=").or_else(|| param.strip_prefix("name="))
707                {
708                    let filename = filename_part.trim().trim_matches('"').trim_matches('\'');
709                    if !filename.is_empty() {
710                        return Some(filename.to_string());
711                    }
712                }
713            }
714        }
715    }
716    None
717}
718
719fn extract_rfc2231_filename(value: &str) -> Option<String> {
720    // RFC 2231 allows arbitrarily many continuation segments (filename*0=, *1=, ...).
721    // A pathological message could supply many huge segments that concatenate into
722    // hundreds of MB of `String`. Cap the reassembled length to defend against
723    // memory exhaustion; legitimate filenames are well under this.
724    const MAX_FILENAME_LEN: usize = 8 * 1024;
725
726    let mut parts: Vec<(usize, String)> = Vec::new();
727    for param in value.split(';') {
728        let param = param.trim();
729        for prefix in &["filename*", "name*"] {
730            if let Some(rest) = param.strip_prefix(prefix) {
731                if let Some(eq_pos) = rest.find('=') {
732                    let num_part = &rest[..eq_pos];
733                    let val_part = &rest[eq_pos + 1..];
734                    let num_str = num_part.trim_end_matches('*');
735                    if let Ok(idx) = num_str.parse::<usize>() {
736                        let val = val_part.trim().trim_matches('"').trim_matches('\'');
737                        let decoded = if num_part.ends_with('*') {
738                            decode_rfc2231_value(val)
739                        } else {
740                            val.to_string()
741                        };
742                        parts.push((idx, decoded));
743                    }
744                }
745            }
746        }
747    }
748    if parts.is_empty() {
749        return None;
750    }
751    parts.sort_by_key(|(idx, _)| *idx);
752    let mut result = String::new();
753    for (_, v) in parts {
754        if result.len().saturating_add(v.len()) > MAX_FILENAME_LEN {
755            // Truncate rather than fail the whole parse — the partial filename
756            // is still safer than `None` triggering downstream defaults that
757            // might leak the original.
758            let remaining = MAX_FILENAME_LEN.saturating_sub(result.len());
759            if remaining > 0 {
760                let take = v
761                    .char_indices()
762                    .take_while(|(i, _)| *i <= remaining)
763                    .last()
764                    .map(|(i, c)| i + c.len_utf8())
765                    .unwrap_or(0);
766                result.push_str(&v[..take.min(v.len())]);
767            }
768            break;
769        }
770        result.push_str(&v);
771    }
772    if result.is_empty() {
773        None
774    } else {
775        Some(result)
776    }
777}
778
779fn extract_rfc2231_encoded_filename(value: &str) -> Option<String> {
780    for param in value.split(';') {
781        let param = param.trim();
782        for prefix in &["filename*=", "name*="] {
783            if let Some(rest) = param.strip_prefix(prefix) {
784                let val = rest.trim().trim_matches('"');
785                return Some(decode_rfc2231_value(val));
786            }
787        }
788    }
789    None
790}
791
792fn decode_rfc2231_value(value: &str) -> String {
793    let parts: Vec<&str> = value.splitn(3, '\'').collect();
794    if parts.len() == 3 {
795        let charset = parts[0];
796        let encoded = parts[2];
797        let decoded_bytes = percent_decode_bytes(encoded);
798        let encoding =
799            encoding_rs::Encoding::for_label(charset.as_bytes()).unwrap_or(encoding_rs::UTF_8);
800        let (result, _, _) = encoding.decode(&decoded_bytes);
801        result.into_owned()
802    } else {
803        let decoded_bytes = percent_decode_bytes(value);
804        String::from_utf8_lossy(&decoded_bytes).into_owned()
805    }
806}
807
808fn percent_decode_bytes(input: &str) -> Vec<u8> {
809    let mut result = Vec::with_capacity(input.len());
810    let bytes = input.as_bytes();
811    let mut i = 0;
812    while i < bytes.len() {
813        if bytes[i] == b'%' && i + 2 < bytes.len() {
814            if let Ok(byte) =
815                u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""), 16)
816            {
817                result.push(byte);
818                i += 3;
819                continue;
820            }
821        }
822        result.push(bytes[i]);
823        i += 1;
824    }
825    result
826}
827
828/// RFC 3676: Unwrap format=flowed text
829/// Lines ending with a space (SP) are joined with the following line.
830/// Lines beginning with "-- " are signature separators (never flowed).
831pub fn unflow_text(text: &str) -> String {
832    let mut result = String::with_capacity(text.len());
833
834    for line in text.lines() {
835        // Signature separator is never flowed
836        if line == "-- " {
837            result.push_str(line);
838            result.push('\n');
839            continue;
840        }
841
842        if line.ends_with(' ') {
843            result.push_str(line.trim_end_matches(' '));
844            result.push(' ');
845        } else {
846            result.push_str(line);
847            result.push('\n');
848        }
849    }
850    result
851}
852
853#[cfg(test)]
854mod tests {
855    use super::*;
856
857    #[test]
858    fn test_content_type_parse() {
859        let ct = ContentType::parse("text/plain; charset=utf-8");
860        assert_eq!(ct.type_, "text");
861        assert_eq!(ct.subtype, "plain");
862        assert_eq!(ct.charset(), Some("utf-8"));
863    }
864
865    #[test]
866    fn test_content_type_multipart() {
867        let ct = ContentType::parse("multipart/mixed; boundary=\"----=_Part_123\"");
868        assert!(ct.is_multipart());
869        assert_eq!(ct.boundary(), Some("----=_Part_123"));
870    }
871
872    #[test]
873    fn test_content_disposition() {
874        let cd = ContentDisposition::parse("attachment; filename=\"test.pdf\"");
875        assert!(cd.is_attachment());
876        assert_eq!(cd.filename(), Some("test.pdf"));
877    }
878
879    #[test]
880    fn test_param_single_quote_char_no_panic() {
881        assert_eq!(ContentType::parse("text/plain; charset=\"").charset(), Some("\""));
882        assert_eq!(ContentDisposition::parse("attachment; filename='").filename(), Some("'"));
883    }
884
885    #[test]
886    fn test_content_disposition_inline() {
887        let cd = ContentDisposition::parse("inline");
888        assert!(!cd.is_attachment());
889    }
890
891    #[test]
892    fn test_base64_decode() {
893        let data = b"SGVsbG8gV29ybGQ=";
894        let decoded = decode_base64(data).unwrap();
895        assert_eq!(decoded, b"Hello World");
896    }
897
898    #[test]
899    fn test_base64_decode_with_newlines() {
900        let data = b"SGVs\nbG8g\nV29y\nbGQ=";
901        let decoded = decode_base64(data).unwrap();
902        assert_eq!(decoded, b"Hello World");
903    }
904
905    #[test]
906    fn test_quoted_printable_decode() {
907        let data = b"=48=C3=A5kan";
908        let decoded = decode_quoted_printable(data);
909        assert_eq!(std::str::from_utf8(&decoded).unwrap(), "Håkan");
910    }
911
912    #[test]
913    fn test_quoted_printable_soft_break() {
914        let data = b"line=\r\ncontinued";
915        let decoded = decode_quoted_printable(data);
916        assert_eq!(std::str::from_utf8(&decoded).unwrap(), "linecontinued");
917    }
918
919    #[test]
920    fn test_quoted_printable_soft_break_unix_lf_only() {
921        // Unix-style soft break: =\n without \r (common in Unix-originated emails)
922        let data = b"line=\ncontinued";
923        let decoded = decode_quoted_printable(data);
924        assert_eq!(
925            std::str::from_utf8(&decoded).unwrap(),
926            "linecontinued",
927            "=\\n soft break (without \\r) should be handled"
928        );
929    }
930
931    #[test]
932    fn test_quoted_printable_soft_break_mixed() {
933        // Mix of Unix and DOS soft breaks
934        let data = b"part1=\npart2=\r\npart3";
935        let decoded = decode_quoted_printable(data);
936        assert_eq!(std::str::from_utf8(&decoded).unwrap(), "part1part2part3");
937    }
938
939    #[test]
940    fn test_uuencode_simple() {
941        let data = b"begin 644 test.txt\n+5B5C(&%L9&%C\n`\nend\n";
942        let decoded = decode_uuencode(data);
943        assert!(decoded.is_some());
944        assert!(!decoded.unwrap().is_empty());
945    }
946
947    #[test]
948    fn test_parse_mime_info() {
949        let headers = vec![
950            ("content-type".to_string(), "text/plain; charset=iso-8859-1".to_string()),
951            ("content-transfer-encoding".to_string(), "quoted-printable".to_string()),
952        ];
953        let mi = parse_mime_info(&headers).unwrap();
954        assert_eq!(mi.content_type.charset(), Some("iso-8859-1"));
955        assert_eq!(mi.content_transfer_encoding.as_deref(), Some("quoted-printable"));
956    }
957
958    #[test]
959    fn test_parse_mime_info_no_cte() {
960        let headers = vec![("content-type".to_string(), "text/plain; charset=utf-8".to_string())];
961        let mi = parse_mime_info(&headers).unwrap();
962        assert_eq!(mi.content_type.charset(), Some("utf-8"));
963        assert!(mi.content_transfer_encoding.is_none());
964    }
965
966    #[test]
967    fn test_parse_mime_info_no_ct() {
968        let headers: Vec<(String, String)> = vec![("from".to_string(), "a@b.com".to_string())];
969        assert!(parse_mime_info(&headers).is_none());
970    }
971
972    #[test]
973    fn test_decode_body_base64() {
974        let headers = vec![
975            ("content-type".to_string(), "text/plain; charset=utf-8".to_string()),
976            ("content-transfer-encoding".to_string(), "base64".to_string()),
977        ];
978        let mi = parse_mime_info(&headers).unwrap();
979        let body = b"SGVsbG8gV29ybGQ=";
980        let decoded = decode_body(body, &mi);
981        assert_eq!(decoded, "Hello World");
982    }
983
984    #[test]
985    fn test_decode_body_quoted_printable() {
986        let headers = vec![
987            ("content-type".to_string(), "text/plain; charset=utf-8".to_string()),
988            ("content-transfer-encoding".to_string(), "quoted-printable".to_string()),
989        ];
990        let mi = parse_mime_info(&headers).unwrap();
991        let body = b"Hello=20World=21";
992        let decoded = decode_body(body, &mi);
993        assert_eq!(decoded, "Hello World!");
994    }
995
996    #[test]
997    fn test_decode_body_7bit_passthrough() {
998        let headers = vec![("content-type".to_string(), "text/plain; charset=utf-8".to_string())];
999        let mi = parse_mime_info(&headers).unwrap();
1000        let body = b"Hello World";
1001        let decoded = decode_body(body, &mi);
1002        assert_eq!(decoded, "Hello World");
1003    }
1004
1005    #[test]
1006    fn test_decode_body_charset_iso8859_1() {
1007        let headers = vec![
1008            ("content-type".to_string(), "text/plain; charset=iso-8859-1".to_string()),
1009            ("content-transfer-encoding".to_string(), "quoted-printable".to_string()),
1010        ];
1011        let mi = parse_mime_info(&headers).unwrap();
1012        // "H=E5kan" with iso-8859-1: å = 0xE5 = 229
1013        let body = b"H=E5kan";
1014        let decoded = decode_body(body, &mi);
1015        assert_eq!(decoded, "Håkan");
1016    }
1017
1018    #[test]
1019    fn test_process_mime_body_no_mime() {
1020        let headers = vec![("from".to_string(), "a@b.com".to_string())];
1021        let (body, charset) = process_mime_body(&headers, b"Hello World");
1022        assert_eq!(body, "Hello World");
1023        assert!(charset.is_none());
1024    }
1025
1026    #[test]
1027    fn test_process_mime_body_with_charset() {
1028        let headers =
1029            vec![("content-type".to_string(), "text/plain; charset=iso-8859-1".to_string())];
1030        let (body, charset) = process_mime_body(&headers, b"Hello");
1031        assert_eq!(body, "Hello");
1032        assert_eq!(charset.as_deref(), Some("iso-8859-1"));
1033    }
1034
1035    #[test]
1036    fn test_decode_body_iso_8859_7_kalimera() {
1037        let headers =
1038            vec![("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string())];
1039        let mi = parse_mime_info(&headers).unwrap();
1040        // "Καλημερα" in ISO-8859-7: Κ=0xCA α=0xE1 λ=0xEB η=0xE7 μ=0xEC ε=0xE5 ρ=0xF1 α=0xE1
1041        let body = b"\xCA\xE1\xEB\xE7\xEC\xE5\xF1\xE1";
1042        let decoded = decode_body(body, &mi);
1043        assert_eq!(decoded, "Καλημερα");
1044    }
1045
1046    #[test]
1047    fn test_decode_body_windows_1253_kalimera() {
1048        let headers =
1049            vec![("content-type".to_string(), "text/plain; charset=windows-1253".to_string())];
1050        let mi = parse_mime_info(&headers).unwrap();
1051        // "Καλημερα" in Windows-1253 (same code points for unaccented Greek)
1052        let body = b"\xCA\xE1\xEB\xE7\xEC\xE5\xF1\xE1";
1053        let decoded = decode_body(body, &mi);
1054        assert_eq!(decoded, "Καλημερα");
1055    }
1056
1057    #[test]
1058    fn test_decode_body_iso_8859_7_tonos() {
1059        let headers =
1060            vec![("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string())];
1061        let mi = parse_mime_info(&headers).unwrap();
1062        // "άνθρωπος" in ISO-8859-7: ά=0xDC ν=0xED θ=0xE8 ρ=0xF1 ω=0xF9 π=0xF0 ο=0xEF ς=0xF2
1063        let body = b"\xDC\xED\xE8\xF1\xF9\xF0\xEF\xF2";
1064        let decoded = decode_body(body, &mi);
1065        assert_eq!(decoded, "άνθρωπος");
1066    }
1067
1068    #[test]
1069    fn test_decode_body_windows_1253_tonos() {
1070        let headers =
1071            vec![("content-type".to_string(), "text/plain; charset=windows-1253".to_string())];
1072        let mi = parse_mime_info(&headers).unwrap();
1073        // "άνθρωπος" in Windows-1253: ά=0xDC ν=0xED θ=0xE8 ρ=0xF1 ω=0xF9 π=0xF0 ο=0xEF ς=0xF2
1074        let body = b"\xDC\xED\xE8\xF1\xF9\xF0\xEF\xF2";
1075        let decoded = decode_body(body, &mi);
1076        assert_eq!(decoded, "άνθρωπος");
1077    }
1078
1079    #[test]
1080    fn test_decode_body_no_charset_iso_8859_7_fallback() {
1081        let headers = vec![("content-type".to_string(), "text/plain".to_string())];
1082        let mi = parse_mime_info(&headers).unwrap();
1083        // "Καλημερα" in ISO-8859-7
1084        let body = b"\xCA\xE1\xEB\xE7\xEC\xE5\xF1\xE1";
1085        let decoded = decode_body(body, &mi);
1086        assert_eq!(decoded, "Καλημερα");
1087    }
1088
1089    #[test]
1090    fn test_decode_body_iso_8859_7_quoted_printable() {
1091        let headers = vec![
1092            ("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string()),
1093            ("content-transfer-encoding".to_string(), "quoted-printable".to_string()),
1094        ];
1095        let mi = parse_mime_info(&headers).unwrap();
1096        // QP-encoded "Καλημερα": Κ=CA α=E1 λ=EB η=E7 μ=EC ε=E5 ρ=F1 α=E1
1097        let body = b"\xCA=E1=EB=E7=EC=E5=F1=E1";
1098        let decoded = decode_body(body, &mi);
1099        assert_eq!(decoded, "Καλημερα");
1100    }
1101
1102    #[test]
1103    fn test_decode_body_iso_8859_7_base64() {
1104        let headers = vec![
1105            ("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string()),
1106            ("content-transfer-encoding".to_string(), "base64".to_string()),
1107        ];
1108        let mi = parse_mime_info(&headers).unwrap();
1109        // Base64 of ISO-8859-7 "Καλημερα" (bytes: CAE1EBE7ECE5F1E1)
1110        let body = b"yuHr5+zl8eE=";
1111        let decoded = decode_body(body, &mi);
1112        assert_eq!(decoded, "Καλημερα");
1113    }
1114
1115    #[test]
1116    fn test_find_multipart_charset_second_part() {
1117        // Multipart where first part has no charset, second part does
1118        let boundary = "----=_NextPart_000_1234";
1119        let body = "------=_NextPart_000_1234\n\
1120             Content-Type: text/plain; format=flowed\n\
1121             \n\
1122             Some plain text\n\
1123             \n\
1124             ------=_NextPart_000_1234\n\
1125             Content-Type: text/html; charset=\"iso-8859-7\"\n\
1126             \n\
1127             <p>Some text</p>\n\
1128             \n\
1129             ------=_NextPart_000_1234--\n"
1130            .to_string();
1131        let result = find_multipart_charset(body.as_bytes(), boundary);
1132        assert_eq!(result.as_deref(), Some("iso-8859-7"));
1133    }
1134
1135    #[test]
1136    fn test_multipart_charset_preserves_unicode_header_offsets() {
1137        let body = "--boundary\nContent-Type: text/plain; nameİİİ=x; charset=utf-8\n\nbody\n--boundary--\n";
1138        assert_eq!(find_multipart_charset(body.as_bytes(), "boundary").as_deref(), Some("utf-8"));
1139    }
1140
1141    #[test]
1142    fn test_find_multipart_charset_all_parts_no_charset() {
1143        // Multipart where NO part has a charset
1144        let boundary = "----=_NextPart_000_5678";
1145        let body = "------=_NextPart_000_5678\n\
1146             Content-Type: text/plain; format=flowed\n\
1147             \n\
1148             First part\n\
1149             \n\
1150             ------=_NextPart_000_5678\n\
1151             Content-Type: text/plain\n\
1152             \n\
1153             Second part\n\
1154             \n\
1155             ------=_NextPart_000_5678--\n"
1156            .to_string();
1157        let result = find_multipart_charset(body.as_bytes(), boundary);
1158        assert!(result.is_none());
1159    }
1160
1161    #[test]
1162    fn test_process_mime_body_multipart_charset_in_second_part() {
1163        let headers = vec![(
1164            "content-type".to_string(),
1165            "multipart/mixed; boundary=\"----=_NextPart_000_9999\"".to_string(),
1166        )];
1167        let body = b"------=_NextPart_000_9999\n\
1168             Content-Type: text/plain; format=flowed\n\
1169             Content-Transfer-Encoding: 8bit\n\
1170             \n\
1171             Hello\n\
1172             \n\
1173             ------=_NextPart_000_9999\n\
1174             Content-Type: text/html; charset=\"iso-8859-7\"\n\
1175             Content-Transfer-Encoding: 8bit\n\
1176             \n\
1177             \xCB\xE1\xEC\xE7\xED\xE5\xF1\xE1\n\
1178             \n\
1179             ------=_NextPart_000_9999--\n";
1180        let charset = resolve_charset(body, &parse_mime_info(&headers).unwrap());
1181        assert_eq!(
1182            charset.as_deref(),
1183            Some("iso-8859-7"),
1184            "Should detect charset from second part when first part lacks it"
1185        );
1186    }
1187
1188    #[test]
1189    fn test_decode_body_greek_utf8() {
1190        let headers = vec![("content-type".to_string(), "text/plain; charset=utf-8".to_string())];
1191        let mi = parse_mime_info(&headers).unwrap();
1192        let body = "Καλημερα".as_bytes();
1193        let decoded = decode_body(body, &mi);
1194        assert_eq!(decoded, "Καλημερα");
1195    }
1196
1197    #[test]
1198    fn test_process_mime_body_no_ct_greek_fallback() {
1199        // No Content-Type header, but body has Greek ISO-8859-7 bytes
1200        let headers = vec![("from".to_string(), "a@b.com".to_string())];
1201        // "Γεια" in ISO-8859-7: Γ=0xC3 ε=0xE5 ι=0xE9 α=0xE1
1202        let body = b"\xC3\xE5\xE9\xE1";
1203        let (decoded, charset) = process_mime_body(&headers, body);
1204        assert!(!decoded.contains('\u{FFFD}'), "Should decode Greek without replacement chars");
1205        // Should have detected a charset from fallbacks
1206        assert!(charset.is_some(), "Should report a detected charset");
1207        assert_eq!(decoded, "Γεια");
1208    }
1209
1210    // Additional comprehensive Greek charset tests
1211
1212    #[test]
1213    fn test_decode_body_uppercase_tonos_iso_8859_7() {
1214        // Test uppercase Greek with tonos: "Άνθρωπος" (capital Ά)
1215        // ISO-8859-7: Ά=0xB6 ν=0xED θ=0xE8 ρ=0xF1 ω=0xF9 π=0xF0 ο=0xEF ς=0xF2
1216        let headers =
1217            vec![("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string())];
1218        let mi = parse_mime_info(&headers).unwrap();
1219        let body = b"\xB6\xED\xE8\xF1\xF9\xF0\xEF\xF2";
1220        let decoded = decode_body(body, &mi);
1221        assert_eq!(decoded, "Άνθρωπος");
1222    }
1223
1224    #[test]
1225    fn test_decode_body_uppercase_tonos_windows_1253() {
1226        // Test uppercase Greek with tonos: "Άνθρωπος" (capital Ά)
1227        // Windows-1253: Ά=0xA2 ν=0xED θ=0xE8 ρ=0xF1 ω=0xF9 π=0xF0 ο=0xEF ς=0xF2
1228        let headers =
1229            vec![("content-type".to_string(), "text/plain; charset=windows-1253".to_string())];
1230        let mi = parse_mime_info(&headers).unwrap();
1231        let body = b"\xA2\xED\xE8\xF1\xF9\xF0\xEF\xF2";
1232        let decoded = decode_body(body, &mi);
1233        assert_eq!(decoded, "Άνθρωπος");
1234    }
1235
1236    #[test]
1237    fn test_decode_body_real_world_greek_phrase() {
1238        // Real-world phrase: "Καλό απόγευμα" (Good afternoon)
1239        // ISO-8859-7: Κ=0xCA α=0xE1 λ=0xEB ό=0xFC <space> α=0xE1 π=0xF0 ό=0xFC γ=0xE3 ε=0xE5 υ=0xF5 μ=0xEC α=0xE1
1240        let headers =
1241            vec![("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string())];
1242        let mi = parse_mime_info(&headers).unwrap();
1243        let body = b"\xCA\xE1\xEB\xFC\x20\xE1\xF0\xFC\xE3\xE5\xF5\xEC\xE1";
1244        let decoded = decode_body(body, &mi);
1245        assert_eq!(decoded, "Καλό απόγευμα");
1246    }
1247
1248    #[test]
1249    fn test_decode_body_mixed_greek_latin() {
1250        // Mixed text: "Hello Κόσμε!" (Hello World! in mixed Greek/Latin)
1251        // UTF-8 encoding for the Greek part
1252        let headers = vec![("content-type".to_string(), "text/plain; charset=utf-8".to_string())];
1253        let mi = parse_mime_info(&headers).unwrap();
1254        let body = "Hello Κόσμε!".as_bytes();
1255        let decoded = decode_body(body, &mi);
1256        assert_eq!(decoded, "Hello Κόσμε!");
1257    }
1258
1259    #[test]
1260    fn test_decode_body_question_marks_greek() {
1261        // Greek semicolon (U+037E) looks like ";" and question mark is ";"
1262        // "Πώς είσαι;" (How are you?)
1263        // ISO-8859-7: Π=0xD0 ώ=0xFE ς=0xF2 <space> ε=0xE5 ί=0xDF σ=0xF3 α=0xE1 ι=0xE9 ;
1264        let headers =
1265            vec![("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string())];
1266        let mi = parse_mime_info(&headers).unwrap();
1267        let body = b"\xD0\xFE\xF2\x20\xE5\xDF\xF3\xE1\xE9;";
1268        let decoded = decode_body(body, &mi);
1269        assert_eq!(decoded, "Πώς είσαι;");
1270    }
1271
1272    #[test]
1273    fn test_find_multipart_charset_mixed_encodings() {
1274        // Multipart with first part in UTF-8 (no charset param), second in ISO-8859-7
1275        let boundary = "----=_Part_123";
1276        let body = "------=_Part_123\n\
1277             Content-Type: text/plain\n\
1278             \n\
1279             English text\n\
1280             \n\
1281             ------=_Part_123\n\
1282             Content-Type: text/html; charset=\"iso-8859-7\"\n\
1283             \n\
1284             <p>Greek text</p>\n\
1285             \n\
1286             ------=_Part_123--\n"
1287            .to_string();
1288        let result = find_multipart_charset(body.as_bytes(), boundary);
1289        assert_eq!(
1290            result.as_deref(),
1291            Some("iso-8859-7"),
1292            "Should find charset from second part even when first part has none"
1293        );
1294    }
1295
1296    #[test]
1297    fn test_process_mime_body_multipart_with_greek_html() {
1298        // Real-world scenario: multipart/alternative with Greek HTML
1299        let headers = vec![(
1300            "content-type".to_string(),
1301            "multipart/alternative; boundary=\"----=_NextPart_000_1111\"".to_string(),
1302        )];
1303        let body = b"------=_NextPart_000_1111\n\
1304             Content-Type: text/plain; charset=\"iso-8859-7\"\n\
1305             \n\
1306             \xCA\xE1\xEB\xE7\xEC\xE5\xF1\xE1\n\
1307             \n\
1308             ------=_NextPart_000_1111\n\
1309             Content-Type: text/html; charset=\"iso-8859-7\"\n\
1310             \n\
1311             <html><body>\xCA\xE1\xEB\xE7\xEC\xE5\xF1\xE1</body></html>\n\
1312             \n\
1313             ------=_NextPart_000_1111--\n";
1314        let (decoded, charset) = process_mime_body(&headers, body);
1315        assert_eq!(charset.as_deref(), Some("iso-8859-7"));
1316        // Should decode Greek correctly from first text/plain part
1317        assert!(decoded.contains("Καλημερα"), "Should contain decoded Greek text");
1318        assert!(!decoded.contains('\u{FFFD}'), "Should not have replacement characters");
1319    }
1320
1321    #[test]
1322    fn test_decode_body_all_greek_letters_iso_8859_7() {
1323        // Test basic Greek alphabet (lowercase): α β γ δ ε
1324        // ISO-8859-7: α=0xE1 β=0xE2 γ=0xE3 δ=0xE4 ε=0xE5
1325        let headers =
1326            vec![("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string())];
1327        let mi = parse_mime_info(&headers).unwrap();
1328        let body = b"\xE1\xE2\xE3\xE4\xE5";
1329        let decoded = decode_body(body, &mi);
1330        assert_eq!(decoded, "αβγδε");
1331    }
1332
1333    #[test]
1334    fn test_decode_body_all_greek_letters_windows_1253() {
1335        // Test basic Greek alphabet (uppercase): Α Β Γ Δ Ε
1336        // Windows-1253: Α=0xC1 Β=0xC2 Γ=0xC3 Δ=0xC4 Ε=0xC5
1337        let headers =
1338            vec![("content-type".to_string(), "text/plain; charset=windows-1253".to_string())];
1339        let mi = parse_mime_info(&headers).unwrap();
1340        let body = b"\xC1\xC2\xC3\xC4\xC5";
1341        let decoded = decode_body(body, &mi);
1342        assert_eq!(decoded, "ΑΒΓΔΕ");
1343    }
1344
1345    #[test]
1346    fn test_decode_body_diaeresis_greek() {
1347        // Test Greek with diaeresis: "ϊδιος" (same, with diaeresis on iota)
1348        // ISO-8859-7: ϊ=0xFA δ=0xE4 ι=0xE9 ο=0xEF ς=0xF2
1349        let headers =
1350            vec![("content-type".to_string(), "text/plain; charset=iso-8859-7".to_string())];
1351        let mi = parse_mime_info(&headers).unwrap();
1352        let body = b"\xFA\xE4\xE9\xEF\xF2";
1353        let decoded = decode_body(body, &mi);
1354        assert_eq!(decoded, "ϊδιος");
1355    }
1356
1357    #[test]
1358    fn test_multipart_inline_image() {
1359        // Test multipart message with inline image (Content-Disposition: inline)
1360        let headers = vec![(
1361            "content-type".to_string(),
1362            "multipart/mixed; boundary=\"----=_Part_123\"".to_string(),
1363        )];
1364
1365        // Create a small 1x1 red pixel GIF
1366        let gif_bytes = b"R0lGODlhAQABAIAAAP8AAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
1367
1368        let body = format!(
1369            "------=_Part_123\n\
1370             Content-Type: text/plain; charset=utf-8\n\
1371             \n\
1372             Hello world\n\
1373             \n\
1374             ------=_Part_123\n\
1375             Content-Type: image/gif; name=\"pixel.gif\"\n\
1376             Content-Disposition: inline; filename=\"pixel.gif\"\n\
1377             Content-Transfer-Encoding: base64\n\
1378             \n\
1379             {}\n\
1380             \n\
1381             ------=_Part_123--\n",
1382            std::str::from_utf8(gif_bytes).unwrap()
1383        );
1384
1385        let (decoded, _charset) = process_mime_body(&headers, body.as_bytes());
1386
1387        // Should contain the text part
1388        assert!(decoded.contains("Hello world"), "Should contain text content");
1389
1390        // Should contain inline image marker (not escaped HTML)
1391        assert!(
1392            decoded.contains("[INLINE_IMAGE:image/gif:"),
1393            "Should contain inline image marker"
1394        );
1395        assert!(
1396            decoded.contains("R0lGODlhAQABAIAAAP8AAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"),
1397            "Should contain base64 data in marker"
1398        );
1399
1400        // Should NOT show MIME boundaries
1401        assert!(!decoded.contains("------=_Part_123"), "Should not contain MIME boundaries");
1402    }
1403
1404    #[test]
1405    fn test_multipart_attachment_image() {
1406        // Images are always embedded inline in the HTML archive regardless of
1407        // Content-Disposition: attachment — browsers browse, they don't download.
1408        let headers = vec![(
1409            "content-type".to_string(),
1410            "multipart/mixed; boundary=\"----=_Part_456\"".to_string(),
1411        )];
1412
1413        let gif_bytes = b"R0lGODlhAQABAIAAAP8AAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
1414
1415        let body = format!(
1416            "------=_Part_456\n\
1417             Content-Type: text/plain; charset=utf-8\n\
1418             \n\
1419             See attached image\n\
1420             \n\
1421             ------=_Part_456\n\
1422             Content-Type: image/gif; name=\"chart.gif\"\n\
1423             Content-Disposition: attachment; filename=\"chart.gif\"\n\
1424             Content-Transfer-Encoding: base64\n\
1425             \n\
1426             {}\n\
1427             \n\
1428             ------=_Part_456--\n",
1429            std::str::from_utf8(gif_bytes).unwrap()
1430        );
1431
1432        let (decoded, _charset) = process_mime_body(&headers, body.as_bytes());
1433
1434        // Should contain the text part
1435        assert!(decoded.contains("See attached image"), "Should contain text content");
1436
1437        // Image must be embedded inline regardless of Content-Disposition: attachment
1438        assert!(
1439            decoded.contains("[INLINE_IMAGE:image/gif:"),
1440            "Should embed image inline even when Content-Disposition is attachment"
1441        );
1442        assert!(
1443            !decoded.contains("[Attachment: chart.gif]"),
1444            "Should NOT show attachment notation for images"
1445        );
1446    }
1447
1448    #[test]
1449    fn test_multipart_image_with_content_id() {
1450        // Test multipart message with image referenced by Content-ID (for HTML email)
1451        let headers = vec![(
1452            "content-type".to_string(),
1453            "multipart/related; boundary=\"----=_Part_789\"".to_string(),
1454        )];
1455
1456        let gif_bytes = b"R0lGODlhAQABAIAAAP8AAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
1457
1458        let body = format!(
1459            "------=_Part_789\n\
1460             Content-Type: text/html; charset=utf-8\n\
1461             \n\
1462             <html><body>Logo: <img src=\"cid:logo@example.com\"></body></html>\n\
1463             \n\
1464             ------=_Part_789\n\
1465             Content-Type: image/gif; name=\"logo.gif\"\n\
1466             Content-ID: <logo@example.com>\n\
1467             Content-Transfer-Encoding: base64\n\
1468             \n\
1469             {}\n\
1470             \n\
1471             ------=_Part_789--\n",
1472            std::str::from_utf8(gif_bytes).unwrap()
1473        );
1474
1475        let (decoded, _charset) = process_mime_body(&headers, body.as_bytes());
1476
1477        // Should contain HTML part
1478        assert!(decoded.contains("<html>"), "Should contain HTML content");
1479
1480        // Should contain inline image marker (since it has Content-ID)
1481        assert!(
1482            decoded.contains("[INLINE_IMAGE:image/gif:"),
1483            "Should contain inline image marker for Content-ID image"
1484        );
1485    }
1486
1487    #[test]
1488    fn test_multipart_pdf_attachment() {
1489        // Test multipart message with PDF attachment
1490        let headers = vec![(
1491            "content-type".to_string(),
1492            "multipart/mixed; boundary=\"----=_Part_PDF\"".to_string(),
1493        )];
1494
1495        let pdf_bytes = b"JVBERi0xLjQKJeLjz9M="; // Minimal PDF header in base64
1496
1497        let body = format!(
1498            "------=_Part_PDF\n\
1499             Content-Type: text/plain; charset=utf-8\n\
1500             \n\
1501             Please review the attached document.\n\
1502             \n\
1503             ------=_Part_PDF\n\
1504             Content-Type: application/pdf; name=\"report.pdf\"\n\
1505             Content-Disposition: attachment; filename=\"report.pdf\"\n\
1506             Content-Transfer-Encoding: base64\n\
1507             \n\
1508             {}\n\
1509             \n\
1510             ------=_Part_PDF--\n",
1511            std::str::from_utf8(pdf_bytes).unwrap()
1512        );
1513
1514        let (decoded, _charset) = process_mime_body(&headers, body.as_bytes());
1515
1516        // Should contain the text part
1517        assert!(decoded.contains("Please review"), "Should contain text content");
1518
1519        // Should show attachment notation for PDF
1520        assert!(
1521            decoded.contains("[Attachment: report.pdf]"),
1522            "Should show PDF attachment notation"
1523        );
1524
1525        // Should NOT show raw base64 PDF data
1526        assert!(!decoded.contains("JVBERi0xLjQKJeLjz9M="), "Should not contain raw PDF base64");
1527        assert!(!decoded.contains("application/pdf"), "Should not show content-type in output");
1528    }
1529
1530    #[test]
1531    fn test_multipart_mixed_inline_and_attachment() {
1532        // Both inline and attachment-disposition images are now always embedded inline.
1533        let headers = vec![(
1534            "content-type".to_string(),
1535            "multipart/mixed; boundary=\"----=_Part_MIX\"".to_string(),
1536        )];
1537
1538        let gif_bytes = b"R0lGODlhAQABAIAAAP8AAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
1539
1540        let body = format!(
1541            "------=_Part_MIX\n\
1542             Content-Type: text/plain; charset=utf-8\n\
1543             \n\
1544             Email body text\n\
1545             \n\
1546             ------=_Part_MIX\n\
1547             Content-Type: image/gif; name=\"inline.gif\"\n\
1548             Content-Disposition: inline; filename=\"inline.gif\"\n\
1549             Content-Transfer-Encoding: base64\n\
1550             \n\
1551             {}\n\
1552             \n\
1553             ------=_Part_MIX\n\
1554             Content-Type: image/jpeg; name=\"photo.jpg\"\n\
1555             Content-Disposition: attachment; filename=\"photo.jpg\"\n\
1556             Content-Transfer-Encoding: base64\n\
1557             \n\
1558             {}\n\
1559             \n\
1560             ------=_Part_MIX--\n",
1561            std::str::from_utf8(gif_bytes).unwrap(),
1562            std::str::from_utf8(gif_bytes).unwrap()
1563        );
1564
1565        let (decoded, _charset) = process_mime_body(&headers, body.as_bytes());
1566
1567        // Should contain text
1568        assert!(decoded.contains("Email body text"), "Should contain text content");
1569
1570        // Both images must be embedded inline — disposition is irrelevant for archives
1571        let inline_count = decoded.matches("[INLINE_IMAGE:").count();
1572        assert_eq!(inline_count, 2, "Both images (inline + attachment) should be embedded");
1573
1574        assert!(!decoded.contains("[Attachment: "), "No image should remain as attachment link");
1575    }
1576
1577    #[test]
1578    fn test_multipart_greek_text_with_inline_image() {
1579        // Real-world test: Greek text with inline image
1580        let headers = vec![(
1581            "content-type".to_string(),
1582            "multipart/mixed; boundary=\"----=_Part_GR\"".to_string(),
1583        )];
1584
1585        // "Γεια σου" in ISO-8859-7: Γ=0xC3 ε=0xE5 ι=0xE9 α=0xE1 space σ=0xF3 ο=0xEF υ=0xF5
1586        let greek_text = vec![0xC3u8, 0xE5, 0xE9, 0xE1, 0x20, 0xF3, 0xEF, 0xF5];
1587        let gif_bytes = b"R0lGODlhAQABAIAAAP8AAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
1588
1589        let mut body =
1590            b"------=_Part_GR\nContent-Type: text/plain; charset=iso-8859-7\n\n".to_vec();
1591        body.extend_from_slice(&greek_text);
1592        body.extend_from_slice(b"\n\n------=_Part_GR\n");
1593        body.extend_from_slice(b"Content-Type: image/gif; name=\"icon.gif\"\n");
1594        body.extend_from_slice(b"Content-Disposition: inline; filename=\"icon.gif\"\n");
1595        body.extend_from_slice(b"Content-Transfer-Encoding: base64\n\n");
1596        body.extend_from_slice(gif_bytes);
1597        body.extend_from_slice(b"\n\n------=_Part_GR--\n");
1598
1599        let (decoded, charset) = process_mime_body(&headers, &body);
1600
1601        // Should detect ISO-8859-7 charset
1602        assert_eq!(charset.as_deref(), Some("iso-8859-7"), "Should detect Greek charset");
1603
1604        // Should contain decoded Greek text
1605        assert!(decoded.contains("Γεια σου"), "Should contain decoded Greek text");
1606
1607        // Should contain inline image marker
1608        assert!(
1609            decoded.contains("[INLINE_IMAGE:image/gif:"),
1610            "Should contain inline image marker"
1611        );
1612
1613        // Should NOT have mojibake or replacement characters
1614        assert!(!decoded.contains('\u{FFFD}'), "Should not have replacement characters");
1615    }
1616
1617    #[test]
1618    fn test_decode_body_mislabeled_iso_8859_1_as_greek() {
1619        // Real-world case: Body labeled as iso-8859-1 but contains Greek (iso-8859-7)
1620        // Greek text: "Σωστά όλα αυτά" (Correct, all that)
1621        // In iso-8859-7: Σ=0xD3 ω=0xF9 σ=0xF3 τ=0xF4 ά=0xDC space=0x20 ό=0xFC λ=0xEB α=0xE1
1622        let headers =
1623            vec![("content-type".to_string(), "text/plain; charset=iso-8859-1".to_string())];
1624        let mi = parse_mime_info(&headers).unwrap();
1625        let body = b"\xD3\xF9\xF3\xF4\xDC\x20\xFC\xEB\xE1\x20\xE1\xF5\xF4\xDC";
1626
1627        let decoded = decode_body(body, &mi);
1628
1629        // Should auto-detect Greek despite iso-8859-1 label
1630        assert!(
1631            decoded.contains("Σωστά") || decoded.contains("ωστά"),
1632            "Should detect Greek in mislabeled iso-8859-1 body: got '{}'",
1633            decoded
1634        );
1635
1636        // Should NOT have mojibake
1637        assert!(!decoded.contains("ÓùóôÜ"), "Should not have mojibake: got '{}'", decoded);
1638    }
1639
1640    #[test]
1641    fn test_rfc2231_continuation_filename() {
1642        let headers = vec![(
1643            "content-disposition".to_string(),
1644            "attachment; filename*0=\"very_long_\"; filename*1=\"filename.pdf\"".to_string(),
1645        )];
1646        assert_eq!(extract_filename(&headers), Some("very_long_filename.pdf".to_string()));
1647    }
1648
1649    #[test]
1650    fn test_rfc2231_encoded_filename() {
1651        let headers = vec![(
1652            "content-disposition".to_string(),
1653            "attachment; filename*=utf-8''%C3%A9tude.pdf".to_string(),
1654        )];
1655        assert_eq!(extract_filename(&headers), Some("étude.pdf".to_string()));
1656    }
1657
1658    #[test]
1659    fn test_format_flowed_unwrap() {
1660        let input = "This is a long \nline that was wrapped.\n\nNew paragraph.\n";
1661        let expected = "This is a long line that was wrapped.\n\nNew paragraph.\n";
1662        assert_eq!(unflow_text(input), expected);
1663    }
1664
1665    #[test]
1666    fn test_format_flowed_signature_not_unwrapped() {
1667        let input = "Hello \nworld.\n-- \nSignature\n";
1668        let expected = "Hello world.\n-- \nSignature\n";
1669        assert_eq!(unflow_text(input), expected);
1670    }
1671
1672    #[test]
1673    fn test_decode_body_correct_iso_8859_1_latin_preserved() {
1674        // Verify that actual Latin-1 content is NOT incorrectly "fixed" to Greek
1675        // French: "Café résumé"
1676        let headers =
1677            vec![("content-type".to_string(), "text/plain; charset=iso-8859-1".to_string())];
1678        let mi = parse_mime_info(&headers).unwrap();
1679        let body = b"Caf\xE9 r\xE9sum\xE9";
1680
1681        let decoded = decode_body(body, &mi);
1682
1683        // Should preserve correct Latin-1
1684        assert_eq!(
1685            decoded, "Café résumé",
1686            "Should preserve correct Latin-1 text: got '{}'",
1687            decoded
1688        );
1689    }
1690
1691    #[test]
1692    fn test_content_type_is_text() {
1693        let ct = ContentType::parse("text/html; charset=utf-8");
1694        assert!(ct.is_text());
1695        assert!(!ct.is_multipart());
1696    }
1697
1698    #[test]
1699    fn test_content_type_full_type() {
1700        let ct = ContentType::parse("application/pdf");
1701        assert_eq!(ct.full_type(), "application/pdf");
1702    }
1703
1704    #[test]
1705    fn test_content_type_name_param() {
1706        let ct = ContentType::parse("image/jpeg; name=\"photo.jpg\"");
1707        assert_eq!(ct.name(), Some("photo.jpg"));
1708    }
1709
1710    #[test]
1711    fn test_content_type_no_subtype() {
1712        let ct = ContentType::parse("text");
1713        assert_eq!(ct.type_, "text");
1714        assert_eq!(ct.subtype, "");
1715    }
1716
1717    #[test]
1718    fn test_content_disposition_no_filename() {
1719        let cd = ContentDisposition::parse("inline");
1720        assert_eq!(cd.filename(), None);
1721        assert!(!cd.is_attachment());
1722    }
1723
1724    #[test]
1725    fn test_decode_quoted_printable_underscore_as_space() {
1726        let data = b"Hello_World";
1727        let decoded = decode_quoted_printable(data);
1728        assert_eq!(std::str::from_utf8(&decoded).unwrap(), "Hello World");
1729    }
1730
1731    #[test]
1732    fn test_decode_uuencode_no_begin() {
1733        let data = b"not a uuencoded block";
1734        let result = decode_uuencode(data);
1735        assert!(result.is_none());
1736    }
1737
1738    #[test]
1739    fn test_unflow_text_no_trailing_space() {
1740        let input = "Line one.\nLine two.\n";
1741        let result = unflow_text(input);
1742        assert_eq!(result, "Line one.\nLine two.\n");
1743    }
1744
1745    #[test]
1746    fn test_process_mime_body_format_flowed() {
1747        let headers = vec![(
1748            "content-type".to_string(),
1749            "text/plain; charset=utf-8; format=flowed".to_string(),
1750        )];
1751        let body = b"This is a long \nline that flows.\n";
1752        let (decoded, _) = process_mime_body(&headers, body);
1753        assert!(decoded.contains("This is a long line that flows."), "got: {}", decoded);
1754    }
1755}