Skip to main content

mailparsing/
header.rs

1use crate::headermap::{EncodeHeaderValue, HeaderMap};
2use crate::rfc5322_parser::Parser;
3use crate::strings::IntoSharedString;
4use crate::{
5    canonical_header_name, ARCAuthenticationResults, AddressList, AuthenticationResults,
6    MailParsingError, Mailbox, MailboxList, MessageID, MimeParameters, ParsedHeader, Result,
7    SharedString,
8};
9use bstr::{BStr, BString};
10use chrono::FixedOffset;
11use kumo_chrono_helper::DateTime;
12use std::borrow::Cow;
13use std::str::FromStr;
14
15/// Upper bound on the number of headers accepted from a header block. A parsed
16/// header borrows its name and value from the input rather than copying them,
17/// but each still occupies a fixed-size `Header` struct (~100 bytes) in the
18/// returned list. A block of many minimal lines (`A:\n` is three bytes) expands
19/// to far more resident memory than its size on the wire. The cap bounds that
20/// expansion per block. Real mail stays far below it. A block that exceeds it
21/// is rejected as malformed.
22const MAX_HEADER_COUNT: usize = 1000;
23
24bitflags::bitflags! {
25    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
26    pub struct MessageConformance: u16 {
27        const MISSING_COLON_VALUE = 0b0000_0001;
28        const NON_CANONICAL_LINE_ENDINGS = 0b0000_0010;
29        const NAME_ENDS_WITH_SPACE = 0b0000_0100;
30        const LINE_TOO_LONG = 0b0000_1000;
31        const NEEDS_TRANSFER_ENCODING = 0b0001_0000;
32        const MISSING_DATE_HEADER = 0b0010_0000;
33        const MISSING_MESSAGE_ID_HEADER = 0b0100_0000;
34        const MISSING_MIME_VERSION = 0b1000_0000;
35        const INVALID_MIME_HEADERS = 0b0001_0000_0000;
36        const MIME_NESTING_LIMIT_EXCEEDED = 0b0010_0000_0000;
37        const MIME_INVALID_BOUNDARY = 0b0100_0000_0000;
38    }
39}
40
41impl FromStr for MessageConformance {
42    type Err = String;
43
44    fn from_str(s: &str) -> std::result::Result<Self, String> {
45        let mut result = Self::default();
46        for ele in s.split('|') {
47            if ele.is_empty() {
48                continue;
49            }
50            match Self::from_name(ele) {
51                Some(v) => {
52                    result = result.union(v);
53                }
54                None => {
55                    let mut possible: Vec<String> = Self::all()
56                        .iter_names()
57                        .map(|(name, _)| format!("'{name}'"))
58                        .collect();
59                    possible.sort();
60                    let possible = possible.join(", ");
61                    return Err(format!(
62                        "invalid MessageConformance flag '{ele}', possible values are {possible}"
63                    ));
64                }
65            }
66        }
67        Ok(result)
68    }
69}
70
71impl ToString for MessageConformance {
72    fn to_string(&self) -> String {
73        let mut names: Vec<&str> = self.iter_names().map(|(name, _)| name).collect();
74        names.sort();
75        names.join("|")
76    }
77}
78
79#[derive(Clone, Debug, PartialEq)]
80pub struct Header<'a> {
81    /// The name portion of the header
82    name: SharedString<'a>,
83    /// The value portion of the header
84    value: SharedString<'a>,
85    /// The separator between the name and the value
86    separator: SharedString<'a>,
87    conformance: MessageConformance,
88}
89
90/// Holds the result of parsing a block of headers
91#[derive(Debug)]
92pub struct HeaderParseResult<'a> {
93    pub headers: HeaderMap<'a>,
94    pub body_offset: usize,
95    pub overall_conformance: MessageConformance,
96}
97
98impl<'a> Header<'a> {
99    pub fn with_name_value<N: Into<SharedString<'a>>, V: Into<SharedString<'a>>>(
100        name: N,
101        value: V,
102    ) -> Self {
103        let name = name.into();
104        let value = value.into();
105        Self {
106            name,
107            value,
108            separator: ": ".into(),
109            conformance: MessageConformance::default(),
110        }
111    }
112
113    pub fn to_owned(&'a self) -> Header<'static> {
114        Header {
115            name: self.name.to_owned(),
116            value: self.value.to_owned(),
117            separator: self.separator.to_owned(),
118            conformance: self.conformance,
119        }
120    }
121
122    pub fn new<N: Into<SharedString<'a>>>(name: N, value: impl EncodeHeaderValue) -> Self {
123        let name = name.into();
124        let value = value.encode_value();
125        Self {
126            name,
127            value,
128            separator: ": ".into(),
129            conformance: MessageConformance::default(),
130        }
131    }
132
133    pub fn new_unstructured<N: Into<SharedString<'a>>, V: Into<SharedString<'a>>>(
134        name: N,
135        value: V,
136    ) -> Self {
137        let name = name.into();
138        let value = value.into();
139        let value = crate::parsed_header::encode_unstructured_value(value.as_bytes());
140
141        Self {
142            name,
143            value,
144            separator: ": ".into(),
145            conformance: MessageConformance::default(),
146        }
147    }
148
149    pub fn assign(&mut self, v: impl EncodeHeaderValue) {
150        self.value = v.encode_value();
151    }
152
153    /// Format the header into the provided output stream,
154    /// as though writing it out as part of a mime part
155    pub fn write_header<W: std::io::Write>(&self, out: &mut W) -> std::io::Result<()> {
156        let line_ending = if self
157            .conformance
158            .contains(MessageConformance::NON_CANONICAL_LINE_ENDINGS)
159        {
160            "\n"
161        } else {
162            "\r\n"
163        };
164        out.write_all(self.name.as_bytes())?;
165        out.write_all(self.separator.as_bytes())?;
166        out.write_all(self.value.as_bytes())?;
167        out.write_all(line_ending.as_bytes())
168    }
169
170    /// Convenience method wrapping write_header that returns
171    /// the formatted header as a standalone string
172    pub fn to_header_string(&self) -> String {
173        let mut out = vec![];
174        self.write_header(&mut out).unwrap();
175        String::from_utf8_lossy(&out).to_string()
176    }
177
178    pub fn get_name(&self) -> &BStr {
179        BStr::new(self.name.as_bytes())
180    }
181
182    pub fn get_name_lossy(&self) -> Cow<'_, str> {
183        String::from_utf8_lossy(self.name.as_bytes())
184    }
185
186    pub fn get_raw_value(&self) -> &BStr {
187        BStr::new(self.value.as_bytes())
188    }
189
190    pub fn get_raw_value_string(&self) -> Result<&str> {
191        self.value.to_str().map_err(|_| MailParsingError::EightBit)
192    }
193
194    pub fn as_content_transfer_encoding(&self) -> Result<MimeParameters> {
195        Parser::parse_content_transfer_encoding_header(self.get_raw_value())
196    }
197
198    pub fn as_content_disposition(&self) -> Result<MimeParameters> {
199        Parser::parse_content_transfer_encoding_header(self.get_raw_value())
200    }
201
202    pub fn as_content_type(&self) -> Result<MimeParameters> {
203        Parser::parse_content_type_header(self.get_raw_value())
204    }
205
206    /// Parse the header into a mailbox-list (as defined in
207    /// RFC 5322), which is how the `From` and `Resent-From`,
208    /// headers are defined.
209    pub fn as_mailbox_list(&self) -> Result<MailboxList> {
210        Parser::parse_mailbox_list_header(self.get_raw_value())
211    }
212
213    /// Parse the header into a mailbox (as defined in
214    /// RFC 5322), which is how the `Sender` and `Resent-Sender`
215    /// headers are defined.
216    pub fn as_mailbox(&self) -> Result<Mailbox> {
217        Parser::parse_mailbox_header(self.get_raw_value())
218    }
219
220    pub fn as_address_list(&self) -> Result<AddressList> {
221        Parser::parse_address_list_header(self.get_raw_value())
222    }
223
224    pub fn as_message_id(&self) -> Result<MessageID> {
225        Parser::parse_msg_id_header(self.get_raw_value())
226    }
227
228    pub fn as_content_id(&self) -> Result<MessageID> {
229        Parser::parse_content_id_header(self.get_raw_value())
230    }
231
232    pub fn as_message_id_list(&self) -> Result<Vec<MessageID>> {
233        Parser::parse_msg_id_header_list(self.get_raw_value())
234    }
235
236    pub fn as_unstructured(&self) -> Result<BString> {
237        Parser::parse_unstructured_header(self.get_raw_value())
238    }
239
240    pub fn as_authentication_results(&self) -> Result<AuthenticationResults> {
241        Parser::parse_authentication_results_header(self.get_raw_value())
242    }
243
244    pub fn as_arc_authentication_results(&self) -> Result<ARCAuthenticationResults> {
245        Parser::parse_arc_authentication_results_header(self.get_raw_value())
246    }
247
248    pub fn as_date(&self) -> Result<DateTime<FixedOffset>> {
249        crate::parse_rfc2822_date(self.get_raw_value_string()?)
250            .map_err(MailParsingError::ChronoError)
251    }
252
253    /// Parse this header's value using the grammar implied by its name.
254    pub fn structured(&self) -> Result<ParsedHeader> {
255        ParsedHeader::structured(self.name.as_bytes(), self.value.as_bytes())
256    }
257
258    pub fn parse_headers<S>(header_block: S) -> Result<HeaderParseResult<'a>>
259    where
260        S: IntoSharedString<'a>,
261    {
262        let (header_block, mut overall_conformance) = header_block.into_shared_string();
263        let mut headers = vec![];
264        let mut idx = 0;
265
266        while idx < header_block.len() {
267            let b = header_block[idx];
268            if b == b'\n' {
269                // LF: End of header block
270                idx += 1;
271                overall_conformance.set(MessageConformance::NON_CANONICAL_LINE_ENDINGS, true);
272                break;
273            }
274            if b == b'\r' {
275                if idx + 1 < header_block.len() && header_block[idx + 1] == b'\n' {
276                    // CRLF: End of header block
277                    idx += 2;
278                    break;
279                }
280                return Err(MailParsingError::HeaderParse(
281                    "lone CR in header".to_string(),
282                ));
283            }
284            if headers.is_empty() && b.is_ascii_whitespace() {
285                return Err(MailParsingError::HeaderParse(
286                    "header block must not start with spaces".to_string(),
287                ));
288            }
289            if headers.len() >= MAX_HEADER_COUNT {
290                return Err(MailParsingError::HeaderParse(format!(
291                    "header block has more than {MAX_HEADER_COUNT} headers"
292                )));
293            }
294            let (header, next) = Self::parse(header_block.slice(idx..header_block.len()))?;
295            overall_conformance |= header.conformance;
296            headers.push(header);
297            debug_assert!(
298                idx != next + idx,
299                "idx={idx}, next={next}, headers: {headers:#?}"
300            );
301            idx += next;
302        }
303        Ok(HeaderParseResult {
304            headers: HeaderMap::new(headers),
305            body_offset: idx,
306            overall_conformance,
307        })
308    }
309
310    pub fn parse<S: Into<SharedString<'a>>>(header_block: S) -> Result<(Self, usize)> {
311        let header_block = header_block.into();
312
313        enum State {
314            Initial,
315            Name,
316            Separator,
317            Value,
318            NewLine,
319        }
320
321        let mut state = State::Initial;
322
323        let mut iter = header_block.as_bytes().iter();
324        let mut c = *iter
325            .next()
326            .ok_or_else(|| MailParsingError::HeaderParse("empty header string".to_string()))?;
327
328        let mut name_end = None;
329        let mut value_start = 0;
330        let mut value_end = 0;
331
332        let mut idx = 0usize;
333        let mut conformance = MessageConformance::default();
334        let mut saw_cr = false;
335        let mut line_start = 0;
336        let mut max_line_len = 0;
337
338        loop {
339            match state {
340                State::Initial => {
341                    if c.is_ascii_whitespace() {
342                        return Err(MailParsingError::HeaderParse(
343                            "header cannot start with space".to_string(),
344                        ));
345                    }
346                    state = State::Name;
347                    continue;
348                }
349                State::Name => {
350                    if c == b':' {
351                        if name_end.is_none() {
352                            name_end.replace(idx);
353                        }
354                        state = State::Separator;
355                    } else if c == b' ' || c == b'\t' {
356                        if name_end.is_none() {
357                            name_end.replace(idx);
358                        }
359                        conformance.set(MessageConformance::NAME_ENDS_WITH_SPACE, true);
360                    } else if c == b'\n' {
361                        // Got a newline before we finished parsing the name
362                        conformance.set(MessageConformance::MISSING_COLON_VALUE, true);
363                        name_end.replace(idx);
364                        max_line_len = max_line_len.max(idx.saturating_sub(line_start));
365                        value_start = idx;
366                        value_end = idx;
367                        idx += 1;
368                        break;
369                    } else if c != b'\r' && !(33..=126).contains(&c) {
370                        return Err(MailParsingError::HeaderParse(format!(
371                            "header name must be comprised of printable US-ASCII characters. Found {c:?}"
372                        )));
373                    }
374                }
375                State::Separator => {
376                    if c != b' ' {
377                        value_start = idx;
378                        value_end = idx;
379                        state = State::Value;
380                        continue;
381                    }
382                }
383                State::Value => {
384                    if c == b'\n' {
385                        if !saw_cr {
386                            conformance.set(MessageConformance::NON_CANONICAL_LINE_ENDINGS, true);
387                        }
388                        state = State::NewLine;
389                        saw_cr = false;
390                        max_line_len = max_line_len.max(idx.saturating_sub(line_start));
391                        line_start = idx + 1;
392                    } else if c != b'\r' {
393                        value_end = idx + 1;
394                        saw_cr = false;
395                    } else {
396                        saw_cr = true;
397                    }
398                }
399                State::NewLine => {
400                    if c == b' ' || c == b'\t' {
401                        state = State::Value;
402                        continue;
403                    }
404                    break;
405                }
406            }
407            idx += 1;
408            c = match iter.next() {
409                None => break,
410                Some(v) => *v,
411            };
412        }
413
414        max_line_len = max_line_len.max(idx.saturating_sub(line_start));
415        if max_line_len > 78 {
416            conformance.set(MessageConformance::LINE_TOO_LONG, true);
417        }
418
419        let name_end = name_end.unwrap_or_else(|| {
420            conformance.set(MessageConformance::MISSING_COLON_VALUE, true);
421            idx
422        });
423
424        let name = header_block.slice(0..name_end);
425        let value = header_block.slice(value_start..value_end.max(value_start));
426        let separator = header_block.slice(name_end..value_start.max(name_end));
427
428        let header = Self {
429            name,
430            value,
431            separator,
432            conformance,
433        };
434
435        Ok((header, idx))
436    }
437
438    /// Re-constitute the header.
439    /// The header value will be parsed out according to the known schema
440    /// of the associated header name, and the parsed form used
441    /// to build a new version of the header.
442    /// This has the side effect of "fixing" non-conforming elements,
443    /// but may come at the cost of "losing" the non-sensical or otherwise
444    /// out of spec elements in the rebuilt header
445    pub fn rebuild(&self) -> Result<Self> {
446        let name = self.get_name();
447        let value = self.structured().map_err(|err| {
448            MailParsingError::HeaderParse(format!("rebuilding '{name}' header: {err:#}"))
449        })?;
450        match canonical_header_name(name) {
451            Some(canonical) => Ok(Self::with_name_value(canonical, value.encode_value())),
452            None => Ok(Self::with_name_value(
453                name.to_string(),
454                value.encode_value(),
455            )),
456        }
457    }
458}
459
460#[cfg(test)]
461mod test {
462    use super::*;
463    use crate::AddrSpec;
464
465    fn assert_static_lifetime(_header: Header<'static>) {
466        assert!(true, "I wouldn't compile if this wasn't true");
467    }
468
469    #[test]
470    fn header_count_cap() {
471        // A block at the cap parses. One header beyond it is rejected.
472        let at_cap = "X: y\r\n".repeat(MAX_HEADER_COUNT) + "\r\n";
473        let parsed = Header::parse_headers(at_cap.as_str()).unwrap();
474        k9::assert_equal!(parsed.headers.iter().count(), MAX_HEADER_COUNT);
475
476        let over_cap = "X: y\r\n".repeat(MAX_HEADER_COUNT + 1) + "\r\n";
477        let err = Header::parse_headers(over_cap.as_str()).unwrap_err();
478        k9::assert_equal!(
479            err.to_string(),
480            "invalid header: header block has more than 1000 headers"
481        );
482    }
483
484    #[test]
485    fn header_construction() {
486        let header = Header::with_name_value("To", "someone@example.com");
487        assert_eq!(header.get_name(), "To");
488        assert_eq!(header.get_raw_value(), "someone@example.com");
489        assert_eq!(header.to_header_string(), "To: someone@example.com\r\n");
490        assert_static_lifetime(header);
491    }
492
493    #[test]
494    fn header_parsing() {
495        let message = concat!(
496            "Subject: hello there\n",
497            "From:  Someone <someone@example.com>\n",
498            "\n",
499            "I am the body"
500        );
501
502        let HeaderParseResult {
503            headers,
504            body_offset,
505            overall_conformance,
506        } = Header::parse_headers(message).unwrap();
507        assert_eq!(&message[body_offset..], "I am the body");
508        k9::snapshot!(
509            overall_conformance,
510            "
511MessageConformance(
512    NON_CANONICAL_LINE_ENDINGS,
513)
514"
515        );
516        k9::snapshot!(
517            headers,
518            r#"
519HeaderMap {
520    headers: [
521        Header {
522            name: "Subject",
523            value: "hello there",
524            separator: ": ",
525            conformance: MessageConformance(
526                NON_CANONICAL_LINE_ENDINGS,
527            ),
528        },
529        Header {
530            name: "From",
531            value: "Someone <someone@example.com>",
532            separator: ":  ",
533            conformance: MessageConformance(
534                NON_CANONICAL_LINE_ENDINGS,
535            ),
536        },
537    ],
538}
539"#
540        );
541    }
542
543    #[test]
544    fn as_mailbox() {
545        let sender = Header::with_name_value("Sender", "John Smith <jsmith@example.com>");
546        k9::snapshot!(
547            sender.as_mailbox(),
548            r#"
549Ok(
550    Mailbox {
551        name: Some(
552            "John Smith",
553        ),
554        address: AddrSpec {
555            local_part: "jsmith",
556            domain: "example.com",
557        },
558    },
559)
560"#
561        );
562    }
563
564    #[test]
565    fn assign_mailbox() {
566        let mut sender = Header::with_name_value("Sender", "");
567        sender.assign(Mailbox {
568            name: Some("John Smith".into()),
569            address: AddrSpec::new("john.smith", "example.com"),
570        });
571        assert_eq!(
572            sender.to_header_string(),
573            "Sender: \"John Smith\" <john.smith@example.com>\r\n"
574        );
575
576        sender.assign(Mailbox {
577            name: Some("John \"the smith\" Smith".into()),
578            address: AddrSpec::new("john.smith", "example.com"),
579        });
580        assert_eq!(
581            sender.to_header_string(),
582            "Sender: \"John \\\"the smith\\\" Smith\" <john.smith@example.com>\r\n"
583        );
584    }
585
586    #[test]
587    fn new_mailbox() {
588        let sender = Header::new(
589            "Sender",
590            Mailbox {
591                name: Some("John".into()),
592                address: AddrSpec::new("john.smith", "example.com"),
593            },
594        );
595        assert_eq!(
596            sender.to_header_string(),
597            "Sender: John <john.smith@example.com>\r\n"
598        );
599
600        let sender = Header::new(
601            "Sender",
602            Mailbox {
603                name: Some("John".into()),
604                address: AddrSpec::new("john smith", "example.com"),
605            },
606        );
607        assert_eq!(
608            sender.to_header_string(),
609            "Sender: John <\"john smith\"@example.com>\r\n"
610        );
611    }
612
613    #[test]
614    fn new_mailbox_2047() {
615        let sender = Header::new(
616            "Sender",
617            Mailbox {
618                name: Some("André Pirard".into()),
619                address: AddrSpec::new("andre", "example.com"),
620            },
621        );
622        assert_eq!(
623            sender.to_header_string(),
624            "Sender: =?UTF-8?q?Andr=C3=A9_Pirard?= <andre@example.com>\r\n"
625        );
626    }
627
628    #[test]
629    fn test_spacing_roundtrip() {
630        let (header, _size) = Header::parse(
631            "Subject: =?UTF-8?q?=D8=AA=D8=B3=D8=AA_=DB=8C=DA=A9_=D8=AF=D9=88_=D8=B3=D9=87?=",
632        )
633        .unwrap();
634        k9::snapshot!(
635            header.as_unstructured(),
636            r#"
637Ok(
638    "تست یک دو سه",
639)
640"#
641        );
642
643        let rebuilt = header.rebuild().unwrap();
644        k9::snapshot!(
645            rebuilt.as_unstructured(),
646            r#"
647Ok(
648    "تست یک دو سه",
649)
650"#
651        );
652    }
653
654    #[test]
655    fn test_rebuild_authentication_results() {
656        // Authentication-Results is parsed and re-encoded like other
657        // structured headers, which canonicalizes the name and drops the
658        // CFWS comment.
659        let header = Header::with_name_value(
660            "authentication-results",
661            "example.com;\n\tdkim=pass (good signature) header.d=example.com",
662        );
663        let rebuilt = header.rebuild().unwrap();
664        k9::assert_equal!(rebuilt.get_name(), "Authentication-Results");
665        rebuilt.as_authentication_results().unwrap();
666        assert!(
667            !rebuilt.get_raw_value().contains(&b'('),
668            "comment should be dropped by structured re-encode: {:?}",
669            rebuilt.get_raw_value()
670        );
671    }
672
673    #[test]
674    fn test_unstructured_encode() {
675        let header = Header::new_unstructured("Subject", "hello there");
676        k9::snapshot!(header.value, "hello there");
677
678        let header = Header::new_unstructured("Subject", "hello \"there\"");
679        k9::snapshot!(header.value, "hello \"there\"");
680
681        let header = Header::new_unstructured("Subject", "hello André Pirard");
682        k9::snapshot!(header.value, "=?UTF-8?q?hello_Andr=C3=A9_Pirard?=");
683
684        let header = Header::new_unstructured(
685            "Subject",
686            "hello there, this is a \
687            longer header than the standard width and so it should \
688            get wrapped in the produced value",
689        );
690        k9::snapshot!(
691            header.to_header_string(),
692            r#"
693Subject: hello there, this is a longer header than the standard width and so it\r
694\tshould get wrapped in the produced value\r
695
696"#
697        );
698
699        let input_text = "hello there André, this is a longer header \
700                          than the standard width and so it should get \
701                          wrapped in the produced value. Do you hear me \
702                          André? this should get really long!";
703        let header = Header::new_unstructured("Subject", input_text);
704        k9::snapshot!(
705            header.to_header_string(),
706            r#"
707Subject: =?UTF-8?q?hello_there_Andr=C3=A9=2C_this_is_a_longer_header_than_the_s?=\r
708\t=?UTF-8?q?tandard_width_and_so_it_should_get_wrapped_in_the_produced_v?=\r
709\t=?UTF-8?q?alue=2E_Do_you_hear_me_Andr=C3=A9=3F_this_should_get_really_?=\r
710\t=?UTF-8?q?long!?=\r
711
712"#
713        );
714
715        k9::assert_equal!(header.as_unstructured().unwrap(), input_text);
716    }
717
718    #[test]
719    fn test_unstructured_encode_farsi() {
720        let farsi_input = "بوت‌كمپ قدرت نوشتن رهنماکالج";
721        let header = Header::new_unstructured("Subject", farsi_input);
722        eprintln!("{}", header.value);
723        k9::assert_equal!(header.as_unstructured().unwrap(), farsi_input);
724    }
725
726    #[test]
727    fn test_wrapping_in_from_header() {
728        let header = Header::new_unstructured(
729            "From",
730            "=?UTF-8?q?=D8=B1=D9=87=D9=86=D9=85=D8=A7_=DA=A9=D8=A7=D9=84=D8=AC?= \
731            <from-dash-wrap-me@example.com>",
732        );
733
734        eprintln!("made: {}", header.to_header_string());
735
736        // In the original problem report, the header got wrapped onto a second
737        // line at `from-` which broke parsing the header as a mailbox.
738        // This line asserts that it does parse.
739        let _ = header.as_mailbox_list().unwrap();
740    }
741
742    #[test]
743    fn test_multi_line_filename() {
744        let header = Header::with_name_value(
745            "Content-Disposition",
746            "attachment;\r\n\
747            \tfilename*0*=UTF-8''%D0%A7%D0%B0%D1%81%D1%82%D0%B8%D0%BD%D0%B0%20%D0%B2;\r\n\
748            \tfilename*1*=%D0%BA%D0%BB%D0%B0%D0%B4%D0%B5%D0%BD%D0%BE%D0%B3%D0%BE%20;\r\n\
749            \tfilename*2*=%D0%BF%D0%BE%D0%B2%D1%96%D0%B4%D0%BE%D0%BC%D0%BB%D0%B5%D0%BD;\r\n\
750            \tfilename*3*=%D0%BD%D1%8F",
751        );
752
753        match header.as_content_disposition() {
754            Ok(cd) => {
755                k9::snapshot!(
756                    cd.get("filename"),
757                    r#"
758Some(
759    "Частина вкладеного повідомлення",
760)
761"#
762                );
763            }
764            Err(err) => {
765                eprintln!("{err:#}");
766                panic!("expected to parse");
767            }
768        }
769    }
770
771    #[test]
772    fn test_date() {
773        let header = Header::with_name_value("Date", "Tue, 1 Jul 2003 10:52:37 +0200");
774        let date = header.as_date().unwrap();
775        k9::snapshot!(date, "2003-07-01T10:52:37+02:00");
776    }
777
778    #[test]
779    fn conformance_string() {
780        k9::assert_equal!(
781            MessageConformance::LINE_TOO_LONG.to_string(),
782            "LINE_TOO_LONG"
783        );
784        k9::assert_equal!(
785            (MessageConformance::LINE_TOO_LONG | MessageConformance::NEEDS_TRANSFER_ENCODING)
786                .to_string(),
787            "LINE_TOO_LONG|NEEDS_TRANSFER_ENCODING"
788        );
789        k9::assert_equal!(
790            MessageConformance::from_str("").unwrap(),
791            MessageConformance::default()
792        );
793
794        k9::assert_equal!(
795            MessageConformance::from_str("LINE_TOO_LONG").unwrap(),
796            MessageConformance::LINE_TOO_LONG
797        );
798        k9::assert_equal!(
799            MessageConformance::from_str("LINE_TOO_LONG|MISSING_COLON_VALUE").unwrap(),
800            MessageConformance::LINE_TOO_LONG | MessageConformance::MISSING_COLON_VALUE
801        );
802        k9::assert_equal!(
803            MessageConformance::from_str("LINE_TOO_LONG|spoon").unwrap_err(),
804            "invalid MessageConformance flag 'spoon', possible values are \
805            'INVALID_MIME_HEADERS', 'LINE_TOO_LONG', 'MIME_INVALID_BOUNDARY', \
806            'MIME_NESTING_LIMIT_EXCEEDED', 'MISSING_COLON_VALUE', 'MISSING_DATE_HEADER', \
807            'MISSING_MESSAGE_ID_HEADER', \
808            'MISSING_MIME_VERSION', 'NAME_ENDS_WITH_SPACE', 'NEEDS_TRANSFER_ENCODING', \
809            'NON_CANONICAL_LINE_ENDINGS'"
810        );
811    }
812
813    #[test]
814    fn split_qp_display_name() {
815        let header = Header::with_name_value("From", "=?UTF-8?q?=D8=A7=D9=86=D8=AA=D8=B4=D8=A7=D8=B1=D8=A7=D8=AA_=D8=AC=D9=85?=\r\n\t=?UTF-8?q?=D8=A7=D9=84?= <noreply@email.ahasend.com>");
816
817        let mbox = header.as_mailbox_list().unwrap();
818
819        k9::snapshot!(
820            mbox,
821            r#"
822MailboxList(
823    [
824        Mailbox {
825            name: Some(
826                "انتشارات جم ال",
827            ),
828            address: AddrSpec {
829                local_part: "noreply",
830                domain: "email.ahasend.com",
831            },
832        },
833    ],
834)
835"#
836        );
837    }
838}