Skip to main content

mailparsing/
parsed_header.rs

1use crate::headermap::EncodeHeaderValue;
2use crate::rfc5322_parser::{qp_encode, Parser};
3use crate::{
4    AddressList, AuthenticationResults, MailParsingError, Mailbox, MailboxList, MessageID,
5    MimeParameters, Result, SharedString,
6};
7use bstr::BString;
8use chrono::FixedOffset;
9use kumo_chrono_helper::DateTime;
10
11/// The parsed, typed value of a header, as distinct from the raw wire form
12/// held by `Header`. A header's name determines the grammar its bytes are
13/// parsed with (see `ParsedHeader::structured`), so callers reach a value
14/// of the correct type without choosing a parser themselves.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum ParsedHeader {
17    MailboxList(MailboxList),
18    Mailbox(Mailbox),
19    AddressList(AddressList),
20    MessageId(MessageID),
21    MessageIdList(Vec<MessageID>),
22    MimeParameters(MimeParameters),
23    Date(DateTime<FixedOffset>),
24    AuthenticationResults(AuthenticationResults),
25    Unstructured(BString),
26}
27
28impl ParsedHeader {
29    /// Parse `value` as the header named by `name`, selecting the grammar
30    /// from the name. An unrecognized name is treated as unstructured.
31    pub fn structured(name: &[u8], value: &[u8]) -> Result<Self> {
32        Ok(match grammar_for_name(name) {
33            Grammar::MailboxList => Self::MailboxList(Parser::parse_mailbox_list_header(value)?),
34            Grammar::Mailbox => Self::Mailbox(Parser::parse_mailbox_header(value)?),
35            Grammar::AddressList => Self::AddressList(Parser::parse_address_list_header(value)?),
36            Grammar::MessageId => Self::MessageId(Parser::parse_msg_id_header(value)?),
37            Grammar::ContentId => Self::MessageId(Parser::parse_content_id_header(value)?),
38            Grammar::MessageIdList => Self::MessageIdList(Parser::parse_msg_id_header_list(value)?),
39            Grammar::ContentType => Self::MimeParameters(Parser::parse_content_type_header(value)?),
40            // No dedicated Content-Disposition grammar exists. This reuses the
41            // CTE parameter grammar, kept unchanged from the old rebuild()
42            // dispatch.
43            Grammar::ContentTransferEncoding | Grammar::ContentDisposition => {
44                Self::MimeParameters(Parser::parse_content_transfer_encoding_header(value)?)
45            }
46            Grammar::Date => {
47                let value = std::str::from_utf8(value).map_err(|_| MailParsingError::EightBit)?;
48                Self::Date(crate::parse_rfc2822_date(value).map_err(MailParsingError::ChronoError)?)
49            }
50            Grammar::AuthenticationResults => {
51                Self::AuthenticationResults(Parser::parse_authentication_results_header(value)?)
52            }
53            Grammar::Unstructured => Self::Unstructured(Parser::parse_unstructured_header(value)?),
54        })
55    }
56}
57
58impl EncodeHeaderValue for ParsedHeader {
59    fn encode_value(&self) -> SharedString<'static> {
60        match self {
61            Self::MailboxList(v) => v.encode_value(),
62            Self::Mailbox(v) => v.encode_value(),
63            Self::AddressList(v) => v.encode_value(),
64            Self::MessageId(v) => v.encode_value(),
65            Self::MessageIdList(v) => v.encode_value(),
66            Self::MimeParameters(v) => v.encode_value(),
67            Self::Date(v) => v.encode_value(),
68            Self::AuthenticationResults(v) => v.encode_value(),
69            Self::Unstructured(v) => encode_unstructured_value(v.as_slice()),
70        }
71    }
72}
73
74/// Encode a free-text header value: fold a plain-ASCII value at whitespace,
75/// or wrap a value with non-ASCII bytes in an RFC 2047 encoded-word.
76/// `Header::new_unstructured` and `ParsedHeader`'s unstructured arm share
77/// this so a value encodes the same either way.
78pub(crate) fn encode_unstructured_value(value: &[u8]) -> SharedString<'static> {
79    match std::str::from_utf8(value) {
80        Ok(value) if value.is_ascii() => kumo_wrap::wrap_bytes(value).into(),
81        Ok(value) => qp_encode(value.as_bytes()).into(),
82        Err(_) => kumo_wrap::wrap_bytes(value).into(),
83    }
84}
85
86/// The grammar a header's value is parsed with. Several names share a
87/// grammar, and several grammars yield the same `ParsedHeader` value type,
88/// so this stays private: callers key off the header name, never this tag.
89#[derive(Clone, Copy, PartialEq, Eq)]
90enum Grammar {
91    MailboxList,
92    Mailbox,
93    AddressList,
94    MessageId,
95    ContentId,
96    MessageIdList,
97    ContentType,
98    ContentTransferEncoding,
99    ContentDisposition,
100    Date,
101    AuthenticationResults,
102    Unstructured,
103}
104
105/// The header names with a defined grammar or canonical spelling. This is
106/// the single source of truth behind `grammar_for_name`,
107/// `canonical_header_name`, and `is_address_header_name`. The unstructured
108/// entries earn their place by fixing the canonical casing of headers whose
109/// value is otherwise free text.
110const KNOWN_HEADERS: &[(&str, Grammar)] = &[
111    ("From", Grammar::MailboxList),
112    ("Resent-From", Grammar::MailboxList),
113    ("Sender", Grammar::Mailbox),
114    ("Resent-Sender", Grammar::Mailbox),
115    ("Reply-To", Grammar::AddressList),
116    ("To", Grammar::AddressList),
117    ("Cc", Grammar::AddressList),
118    ("Bcc", Grammar::AddressList),
119    ("Resent-To", Grammar::AddressList),
120    ("Resent-Cc", Grammar::AddressList),
121    ("Resent-Bcc", Grammar::AddressList),
122    ("Date", Grammar::Date),
123    ("Message-ID", Grammar::MessageId),
124    ("Content-ID", Grammar::ContentId),
125    ("References", Grammar::MessageIdList),
126    ("Content-Type", Grammar::ContentType),
127    (
128        "Content-Transfer-Encoding",
129        Grammar::ContentTransferEncoding,
130    ),
131    ("Content-Disposition", Grammar::ContentDisposition),
132    ("Authentication-Results", Grammar::AuthenticationResults),
133    ("Subject", Grammar::Unstructured),
134    ("Comments", Grammar::Unstructured),
135    ("MIME-Version", Grammar::Unstructured),
136];
137
138fn grammar_for_name(name: &[u8]) -> Grammar {
139    KNOWN_HEADERS
140        .iter()
141        .find(|(known, _)| known.as_bytes().eq_ignore_ascii_case(name))
142        .map(|(_, grammar)| *grammar)
143        .unwrap_or(Grammar::Unstructured)
144}
145
146/// The canonical spelling of `name`, or None when it isn't a known header.
147pub fn canonical_header_name(name: &[u8]) -> Option<&'static str> {
148    KNOWN_HEADERS
149        .iter()
150        .find(|(known, _)| known.as_bytes().eq_ignore_ascii_case(name))
151        .map(|(known, _)| *known)
152}
153
154/// True when `name` names a header whose value is one or more addresses
155/// (a mailbox, mailbox list, or address list).
156pub fn is_address_header_name(name: &[u8]) -> bool {
157    matches!(
158        grammar_for_name(name),
159        Grammar::MailboxList | Grammar::Mailbox | Grammar::AddressList
160    )
161}
162
163#[cfg(test)]
164mod test {
165    use super::*;
166
167    #[test]
168    fn address_header_names() {
169        // Matched case-insensitively; From/To/Bcc are address headers,
170        // Subject/Date/unknown are not.
171        assert!(is_address_header_name(b"from"));
172        assert!(is_address_header_name(b"To"));
173        assert!(is_address_header_name(b"BCC"));
174        assert!(is_address_header_name(b"Sender"));
175        assert!(!is_address_header_name(b"Subject"));
176        assert!(!is_address_header_name(b"Date"));
177        assert!(!is_address_header_name(b"X-Custom"));
178    }
179
180    #[test]
181    fn canonical_names() {
182        k9::assert_equal!(canonical_header_name(b"message-id"), Some("Message-ID"));
183        k9::assert_equal!(canonical_header_name(b"REPLY-TO"), Some("Reply-To"));
184        k9::assert_equal!(canonical_header_name(b"X-Custom"), None);
185    }
186
187    #[test]
188    fn structured_dispatch() {
189        // The name selects the grammar: To parses as an address list, an
190        // unknown name is unstructured.
191        let to = ParsedHeader::structured(b"To", b"a@example.com, b@example.com").unwrap();
192        match to {
193            ParsedHeader::AddressList(list) => {
194                k9::assert_equal!(list.len(), 2);
195            }
196            other => panic!("expected AddressList, got {other:?}"),
197        }
198
199        let custom = ParsedHeader::structured(b"X-Custom", b"anything at all").unwrap();
200        assert!(matches!(custom, ParsedHeader::Unstructured(_)));
201    }
202}