Skip to main content

mailparsing/
datetime.rs

1use chrono::{Datelike, FixedOffset, Offset, TimeZone, Timelike};
2use kumo_chrono_helper::DateTime;
3
4const SHORT_WEEKDAYS: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
5const SHORT_MONTHS: [&str; 12] = [
6    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
7];
8
9/// Format `date` as an RFC 2822 `date-time`.
10///
11/// A year with more than four digits keeps all of them, and a negative year is
12/// clamped to `0000`. This keeps a corrupt timestamp printable, where chrono's
13/// `DateTime::to_rfc2822` would panic instead.
14pub fn format_rfc2822_date<Tz: TimeZone>(date: DateTime<Tz>) -> String {
15    let zero = FixedOffset::east_opt(0).expect("zero is a valid offset");
16    let raw_offset = date.offset().fix();
17    // Near the minimum or maximum representable date, adding the offset can
18    // push the value out of range; when that happens, fall back to the UTC
19    // value instead of panicking.
20    #[allow(clippy::disallowed_methods)]
21    let (local, offset) = match date.naive_utc().checked_add_offset(raw_offset) {
22        Some(local) => (local, raw_offset),
23        // The fields printed below are the UTC value, and +0000 is the offset
24        // label that makes that true.
25        None => (date.naive_utc(), zero),
26    };
27
28    let weekday = SHORT_WEEKDAYS[local.weekday().num_days_from_sunday() as usize];
29    let month = SHORT_MONTHS[local.month0() as usize];
30    let year = local.year().max(0);
31    let day = local.day();
32    let hour = local.hour();
33    let minute = local.minute();
34    // A leap second is stored as second 59 with a nanosecond past one second.
35    // Adding it here renders the 60 that RFC 2822 expects.
36    let second = local.second() + local.nanosecond() / 1_000_000_000;
37
38    let offset_seconds = offset.local_minus_utc();
39    let (sign, offset_seconds) = if offset_seconds < 0 {
40        ('-', -offset_seconds)
41    } else {
42        ('+', offset_seconds)
43    };
44    let offset_hours = offset_seconds / 3600;
45    let offset_minutes = (offset_seconds % 3600) / 60;
46
47    format!(
48        "{weekday}, {day} {month} {year:04} \
49         {hour:02}:{minute:02}:{second:02} \
50         {sign}{offset_hours:02}{offset_minutes:02}"
51    )
52}
53
54/// Parse an RFC 2822 `date-time`, tolerating obsolete alphabetic time zones.
55///
56/// chrono's `parse_from_rfc2822` accepts the zone tokens named in RFC 5322
57/// section 4.3 (`UT`, `GMT`, the North American `EST`/`EDT`/... set) but
58/// rejects any other alphabetic zone. Real senders still emit some: Amazon SES
59/// writes its DSN dates with the token `UTC`, which chrono does not recognize.
60///
61/// When the strict parse fails we retry after replacing a trailing alphabetic
62/// zone token with a numeric offset. A token with one widely-agreed meaning
63/// (`UTC`, and the common regional abbreviations chrono lacks such as
64/// `CET`/`CEST`) resolves to its real offset. Anything chrono neither knows nor
65/// we can resolve unambiguously falls back to `-0000`, the RFC 5322 section 4.3
66/// unknown-offset marker: the same instant as UTC, which keeps the stated
67/// wall-clock date and time while recording that the true offset is unknown.
68/// The original error is preserved when the retry does not help. This keeps
69/// malformed input reporting the real problem rather than a zone complaint.
70// This function is the sanctioned caller of chrono's strict parser. The
71// disallowed_methods lint blocks calling it anywhere else.
72#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
73pub fn parse_rfc2822_date(
74    input: &str,
75) -> Result<DateTime<FixedOffset>, chrono::format::ParseError> {
76    chrono::DateTime::parse_from_rfc2822(input)
77        .or_else(|err| {
78            if let Some(rewritten) = rewrite_unknown_alphabetic_zone(input) {
79                if let Ok(date) = chrono::DateTime::parse_from_rfc2822(&rewritten) {
80                    return Ok(date);
81                }
82            }
83            Err(err)
84        })
85        .map(DateTime::from)
86}
87
88/// If `input` ends with an alphabetic zone token, return a copy with that token
89/// replaced by a numeric offset; otherwise return `None`.
90///
91/// CFWS (comments and folding whitespace) is stripped with the crate's parser
92/// first, so a trailing comment such as `(Coordinated)` does not hide the zone.
93/// A recognized abbreviation resolves to its offset; any other alphabetic token
94/// becomes the `-0000` unknown offset.
95fn rewrite_unknown_alphabetic_zone(input: &str) -> Option<String> {
96    let cleaned = crate::rfc5322_parser::strip_cfws(input)?;
97    // strip_cfws joins non-empty tokens with single spaces, so the token after
98    // the final space is never empty.
99    let (head, zone) = cleaned.rsplit_once(' ')?;
100    if !zone.bytes().all(|b| b.is_ascii_alphabetic()) {
101        return None;
102    }
103    let offset = named_zone_offset(zone).unwrap_or("-0000");
104    Some(format!("{head} {offset}"))
105}
106
107/// Return the numeric UTC offset, in RFC 2822 `+HHMM` form, for an alphabetic
108/// zone abbreviation, or `None` when it is unknown or ambiguous.
109///
110/// The mapping comes from the generated `zone_offsets` table.
111fn named_zone_offset(zone: &str) -> Option<&'static str> {
112    crate::zone_offsets::ZONE_OFFSETS
113        .get(zone.to_ascii_uppercase().as_str())
114        .copied()
115}
116
117#[cfg(test)]
118mod test {
119    use super::*;
120
121    #[test]
122    fn obsolete_utc_zone() {
123        let ses = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 UTC").unwrap();
124        let canonical = parse_rfc2822_date("Thu, 02 Jul 2026 18:55:38 +0000").unwrap();
125        k9::assert_equal!(ses, canonical);
126    }
127
128    #[test]
129    fn recognized_zones_keep_their_offset() {
130        // chrono already handles these; the fallback must not intercept them.
131        let eastern = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 EST").unwrap();
132        k9::assert_equal!(eastern.to_rfc3339(), "2026-07-02T18:55:38-05:00");
133
134        let numeric = parse_rfc2822_date("Tue, 1 Jul 2003 10:52:37 +0200").unwrap();
135        k9::assert_equal!(numeric.to_rfc3339(), "2003-07-01T10:52:37+02:00");
136    }
137
138    #[test]
139    fn regional_zone_resolves_to_its_offset() {
140        // Common abbreviations chrono rejects are resolved to their real offset.
141        let cest = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 CEST").unwrap();
142        k9::assert_equal!(cest.to_rfc3339(), "2026-07-02T18:55:38+02:00");
143
144        let jst = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 JST").unwrap();
145        k9::assert_equal!(jst.to_rfc3339(), "2026-07-02T18:55:38+09:00");
146    }
147
148    #[test]
149    fn ambiguous_zone_becomes_unknown_offset() {
150        // The tz database itself renders `IST` at three offsets (Ireland
151        // +0100, Israel +0200, India +0530), so it is ambiguous in the data
152        // and we cannot resolve it. Per RFC 5322 section 4.3 it keeps the
153        // stated wall-clock time at the -0000 unknown offset, which is the same
154        // instant as UTC.
155        let ist = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 IST").unwrap();
156        let utc = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 UTC").unwrap();
157        k9::assert_equal!(ist, utc);
158    }
159
160    #[test]
161    fn trailing_zone_comment_is_ignored() {
162        let with_comment = parse_rfc2822_date("Thu, 02 Jul 26 18:55:38 UTC (Coordinated)").unwrap();
163        let canonical = parse_rfc2822_date("Thu, 02 Jul 2026 18:55:38 +0000").unwrap();
164        k9::assert_equal!(with_comment, canonical);
165    }
166
167    #[test]
168    fn garbage_still_errors() {
169        parse_rfc2822_date("not a date").unwrap_err();
170    }
171
172    #[test]
173    fn format_representable_date() {
174        let date = parse_rfc2822_date("Tue, 1 Jul 2003 10:52:37 +0200").unwrap();
175        k9::assert_equal!(format_rfc2822_date(date), "Tue, 1 Jul 2003 10:52:37 +0200");
176    }
177
178    #[test]
179    fn format_matches_chrono_for_representable_dates() {
180        // Our hand-rolled formatter must agree with chrono byte-for-byte over
181        // the range chrono can render, across the day/year padding and offset
182        // boundaries. Outside that range chrono panics, which is the whole
183        // reason we format the field ourselves.
184        let utc = FixedOffset::east_opt(0).unwrap();
185        let east = FixedOffset::east_opt(2 * 3600).unwrap();
186        let west = FixedOffset::west_opt(5 * 3600).unwrap();
187        let samples = [
188            east.with_ymd_and_hms(2003, 7, 1, 10, 52, 37).unwrap(),
189            utc.with_ymd_and_hms(2026, 7, 2, 18, 55, 38).unwrap(),
190            west.with_ymd_and_hms(2026, 7, 2, 18, 55, 38).unwrap(),
191            utc.with_ymd_and_hms(9999, 12, 31, 23, 59, 59).unwrap(),
192            utc.with_ymd_and_hms(1, 1, 1, 0, 0, 0).unwrap(),
193        ];
194        for date in samples {
195            // The comparison against chrono's own output is the point of the test.
196            #[allow(clippy::disallowed_methods)]
197            let expected = date.to_rfc2822();
198            k9::assert_equal!(format_rfc2822_date(date.into()), expected);
199        }
200    }
201
202    #[test]
203    fn format_far_future_year_keeps_all_digits() {
204        // A year past 9999 has no four-digit RFC 2822 form. chrono panics on it;
205        // ours renders every digit rather than fail.
206        let far_future = chrono::Utc.with_ymd_and_hms(60123, 1, 1, 0, 0, 0).unwrap();
207        k9::assert_equal!(
208            format_rfc2822_date(far_future.into()),
209            "Fri, 1 Jan 60123 00:00:00 +0000"
210        );
211    }
212
213    #[test]
214    fn format_negative_year_clamps_to_zero() {
215        let ancient = chrono::Utc.with_ymd_and_hms(-44, 3, 15, 12, 0, 0).unwrap();
216        k9::assert_equal!(
217            format_rfc2822_date(ancient.into()),
218            "Thu, 15 Mar 0000 12:00:00 +0000"
219        );
220    }
221
222    #[test]
223    fn format_offset_overflow_falls_back_to_utc() {
224        // An instant at the top of NaiveDateTime's range cannot have a positive
225        // offset applied without overflowing. The result must stay internally
226        // consistent, keeping the same UTC wall clock and +0000 offset as the
227        // plain UTC value rather than pairing the UTC fields with the
228        // un-applied offset.
229        let max_utc = DateTime::<chrono::Utc>::MAX_UTC;
230        let shifted = max_utc.with_timezone(&FixedOffset::east_opt(5 * 3600).unwrap());
231        k9::assert_equal!(format_rfc2822_date(shifted), format_rfc2822_date(max_utc));
232    }
233}