Something went wrong. Try again.
Reading, writing and creating MIME and RFC 5322 email messages in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! `Date: Tue, 01 Jul 2003 10:52:37 +0200` — RFC 5322 §3.3.//!//! The calendar is not this library's business. Dates, times, offsets and the//! arithmetic between them come from [zig-datetime][], whose `rfc822` module//! already speaks the syntax that a mail header uses; what is here is the//! layer between that and a header field, which is two things the general//! parser cannot be expected to do://!//! * **Comments.** A header value may carry `(...)` anywhere whitespace is//! allowed, and `Date: Tue, 1 Jul 2003 10:52:37 +0200 (CEST)` is how a//! great deal of mail names its zone twice. They are removed here, where//! the rest of this library already knows what a comment is.//! * **Damaged dates.** A `Date:` is written by the sender, and a sender's//! clock and calendar do not always agree with each other. RFC 5322 says a//! day-of-week that contradicts the date is an error, and so does//! zig-datetime; a mail reader that refused to file a message over it would//! be refusing to file a great deal of real mail. `parse` retries without//! the day name, and retries again with a `-0000` for a message that gave//! no zone at all.//!//! The one thing the syntax carries that a `DateTime` cannot is the//! difference between `+0000` and `-0000`. RFC 5322 §3.3 gives the negative//! zero a meaning of its own — the time is UTC, and the sender is declining//! to say what their local time was, which is what an anonymising remailer//! writes — and as an offset both are zero. `Parsed.zone_unknown` carries it,//! and `write` puts it back.//!//! [zig-datetime]: https://git.jcollie.dev/jeff/zig-datetime
const std = @import("std");const Io = std.Io;const testing = std.testing;
const datetime = @import("datetime");
const lexer = @import("lexer.zig");
/// The format string that spells an RFC 5322 date, in the sequences/// `datetime.DateTime.format` reads.pub const format_string = "ddd, DD MMM YYYY HH:mm:ss ZZ";
/// The longest a cleaned-up date is allowed to be before parsing. A date is/// about thirty characters; anything much longer than this is not one, and a/// fixed buffer is what keeps this whole module free of allocation.const max_length = 128;
pub const ParseError = error{ /// Not a date: a missing or impossible field, or nothing recognisable at /// all. InvalidDate,};
pub const Parsed = struct { time: datetime.DateTime, /// Whether the zone was written `-0000`, or was missing altogether. See /// the module comment. zone_unknown: bool,};
/// Reads the value of a `Date:` header.pub fn parse(value: []const u8) ParseError!Parsed { var buffer: [max_length]u8 = undefined; const cleaned = clean(value, &buffer);
// Strictly first, so that a date which is entirely well formed is checked // against its own day-of-week the way RFC 5322 asks. if (datetime.rfc822.parse(cleaned)) |result| { return .{ .time = result.value, .zone_unknown = hasNegativeZeroZone(result.str) }; } else |_| {}
// Then without the day name, which is the field a wrong clock gets wrong // and the only one that is pure redundancy: the weekday comes back // computed from the date either way. const without_day = dropDayName(cleaned); if (datetime.rfc822.parse(without_day)) |result| { return .{ .time = result.value, .zone_unknown = hasNegativeZeroZone(result.str) }; } else |_| {}
// Then with a zone supplied, for the sender that gave none. RFC 5322 // requires one; `-0000` is the right thing to assume, because it says // exactly what is true — the offset is unknown. var with_zone: [max_length + 6]u8 = undefined; if (without_day.len + 6 <= with_zone.len) { @memcpy(with_zone[0..without_day.len], without_day); @memcpy(with_zone[without_day.len..][0..6], " -0000"); if (datetime.rfc822.parse(with_zone[0 .. without_day.len + 6])) |result| { return .{ .time = result.value, .zone_unknown = true }; } else |_| {} }
return error.InvalidDate;}
/// Copies `value` with its comments removed and every run of whitespace/// reduced to one space, which is the form the general parser expects and/// which a folded header value is not.fn clean(value: []const u8, buffer: *[max_length]u8) []u8 { var scanner: lexer.Scanner = .init(value); var out: usize = 0; while (out < buffer.len) { scanner.skipCfws(); if (scanner.atEnd()) break; if (out != 0) { buffer[out] = ' '; out += 1; if (out == buffer.len) break; } const start = scanner.index; while (!scanner.atEnd()) { const c = scanner.source[scanner.index]; if (lexer.isWsp(c) or c == '(' or c == '\r' or c == '\n') break; scanner.index += 1; } const token = scanner.source[start..scanner.index]; const room = @min(token.len, buffer.len - out); @memcpy(buffer[out..][0..room], token[0..room]); out += room; } return buffer[0..out];}
/// Removes a leading `Tue,` or `Tue`, if that is what is there. A day name/// never begins with a digit, so this cannot eat the day of the month.fn dropDayName(value: []const u8) []const u8 { if (value.len == 0 or std.ascii.isDigit(value[0])) return value; const space = std.mem.findScalar(u8, value, ' ') orelse return value; return std.mem.trimStart(u8, value[space + 1 ..], " ");}
/// Whether the zone at the end of what was consumed was written `-0000`.fn hasNegativeZeroZone(consumed: []const u8) bool { return std.mem.endsWith(u8, consumed, "-0000");}
/// Writes a date the way RFC 5322 §3.3 says to, with the day of the week and/// the seconds included: both are optional in the grammar and both are/// expected by readers.pub fn write(w: *Io.Writer, time: datetime.DateTime) Io.Writer.Error!void { time.format(format_string, w) catch |err| switch (err) { error.WriteFailed => return error.WriteFailed, else => unreachable, // The format string is a constant and it is valid. };}
/// Writes a date whose zone is unknown — `-0000` rather than `+0000`. See the/// module comment on why the difference is worth keeping.pub fn writeUnknownZone(w: *Io.Writer, time: datetime.DateTime) Io.Writer.Error!void { var buffer: [max_length]u8 = undefined; var fixed: Io.Writer = .fixed(&buffer); write(&fixed, time) catch unreachable; // A formatted date fits. const text = fixed.buffered(); if (std.mem.endsWith(u8, text, "+0000")) { try w.writeAll(text[0 .. text.len - 5]); try w.writeAll("-0000"); return; } try w.writeAll(text);}
/// Wraps a date so that it can be written with `{f}`.pub fn fmt(time: datetime.DateTime) Formatter { return .{ .time = time };}
pub const Formatter = struct { time: datetime.DateTime,
pub fn format(self: Formatter, w: *Io.Writer) Io.Writer.Error!void { return write(w, self.time); }};
test "the ordinary case" { const parsed = try parse("Tue, 01 Jul 2003 10:52:37 +0200"); try testing.expectEqual(2003, parsed.time.year); try testing.expectEqual(datetime.Month.Jul, parsed.time.month); try testing.expectEqual(1, parsed.time.day); try testing.expectEqual(10, parsed.time.hour); try testing.expectEqual(52, parsed.time.minute); try testing.expectEqual(37, parsed.time.second); try testing.expectEqual(2 * 60 * 60, parsed.time.offset); try testing.expect(!parsed.zone_unknown); // The example from RFC 5322 §A.1.1, and the instant it names. try testing.expectEqual(1057049557, @divTrunc(parsed.time.toInstant().timestamp, std.time.ns_per_s));}
test "a folded value with comments in it" { const parsed = try parse("Tue, 1 Jul 2003\r\n 10:52:37 +0200 (CEST)"); try testing.expectEqual(1, parsed.time.day); try testing.expectEqual(2 * 60 * 60, parsed.time.offset);}
test "negative zero is not zero" { const utc = try parse("Tue, 01 Jul 2003 10:52:37 +0000"); try testing.expect(!utc.zone_unknown); const anonymous = try parse("Tue, 01 Jul 2003 10:52:37 -0000"); try testing.expect(anonymous.zone_unknown); try testing.expectEqual(utc.time.toInstant().timestamp, anonymous.time.toInstant().timestamp);}
test "a day of the week that is wrong is ignored" { // 1 July 2003 was a Tuesday whatever the header says. const parsed = try parse("Sun, 01 Jul 2003 10:52:37 +0200"); try testing.expectEqual(datetime.DayOfWeek.Tue, parsed.time.weekday); try testing.expectEqual(1, parsed.time.day);}
test "a missing zone becomes an unknown one" { const parsed = try parse("1 Jul 2003 10:52:37"); try testing.expectEqual(0, parsed.time.offset); try testing.expect(parsed.zone_unknown);}
test "the obsolete forms" { const old = try parse("Mon, 3 Jan 94 12:00:00 EST"); try testing.expectEqual(1994, old.time.year); try testing.expectEqual(-5 * 60 * 60, old.time.offset);
const recent = try parse("3 Jan 03 12:00:00 GMT"); try testing.expectEqual(2003, recent.time.year);}
test "dates that are not dates" { for ([_][]const u8{ "", "Tue, 01 Jul 2003", "31 Feb 2003 00:00:00 +0000", "1 Xxx 2003 00:00:00 +0000", "99 Jan 9999 99:99:99 +0000", "0 Jan 2003 00:00:00 +0000", "(only a comment)", }) |value| { try testing.expectError(error.InvalidDate, parse(value)); }}
test "writing and reading back" { for ([_][]const u8{ "Tue, 01 Jul 2003 10:52:37 +0200", "Thu, 01 Jan 1970 00:00:00 +0000", "Sat, 29 Feb 2020 23:59:59 -0530", }) |source| { const parsed = try parse(source); var buffer: [128]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try write(&w, parsed.time); try testing.expectEqualStrings(source, w.buffered()); }}
test writeUnknownZone { const parsed = try parse("Tue, 01 Jul 2003 10:52:37 -0000"); var buffer: [128]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeUnknownZone(&w, parsed.time); try testing.expectEqualStrings("Tue, 01 Jul 2003 10:52:37 -0000", w.buffered());}
test "a value longer than the buffer does not overflow it" { var long: [1024]u8 = @splat('x'); try testing.expectError(error.InvalidDate, parse(&long));
var padded: [512]u8 = undefined; const prefix = "Tue, 01 Jul 2003 10:52:37 +0200 ("; @memcpy(padded[0..prefix.len], prefix); @memset(padded[prefix.len..], 'c'); // An unterminated comment swallows the rest, which is what it should do. const parsed = try parse(&padded); try testing.expectEqual(2003, parsed.time.year);}