// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! HTTP dates: the `Date`, `Last-Modified`, `Expires`, `If-Modified-Since` //! and `If-Unmodified-Since` fields. //! //! RFC 9110 §5.6.7 says a sender must use one format and a recipient must //! accept three. The one to send is IMF-fixdate: //! //! Sun, 06 Nov 1994 08:49:37 GMT //! //! fixed width, always GMT, always the English day and month abbreviations //! whatever the machine's locale thinks. The two to accept and never send are //! the obsolete RFC 850 form, whose two-digit year is why it is obsolete, and //! the `asctime` form, which is what a 1970s C program printed and which //! carries no timezone at all. //! //! The calendar is zig-datetime's. All three formats are Go's time layouts //! -- the same three Go's `net/http` reads, spelled the way `golayout` spells //! them -- so what is left here is choosing among them and converting to and //! from a count of seconds, which is what every caller in this library holds. //! //! Every function here is total over `i64` seconds. A `Last-Modified` comes //! from a file's mtime, an mtime is whatever is in the inode, and a panic in a //! date formatter is a crash in whatever was serving the directory. const std = @import("std"); const Writer = std.Io.Writer; const datetime = @import("datetime"); const DateTime = datetime.DateTime; const golayout = datetime.golayout; /// IMF-fixdate as a Go layout. `GMT` is a literal here and not a zone: the /// format admits no other. const imf_layout = "Mon, 02 Jan 2006 15:04:05 GMT"; /// The obsolete RFC 850 form, likewise always `GMT`. const rfc850_layout = "Monday, 02-Jan-06 15:04:05 GMT"; /// `asctime`, with its space-padded day. const asctime_layout = golayout.layout.ansic; /// The number of octets an IMF-fixdate with a four-digit year occupies. pub const imf_len = "Sun, 06 Nov 1994 08:49:37 GMT".len; /// Writes an IMF-fixdate into a buffer of exactly the length one occupies, /// which is where a caller holding a timestamp and wanting a field value /// starts. /// /// `error.OutOfRange` is a year that will not fit in four digits, which is /// not a date HTTP can express. It is reachable: a `Last-Modified` comes from /// an mtime, and an mtime is whatever is in the inode. pub fn formatImf(buf: *[imf_len]u8, epoch_seconds: i64) error{OutOfRange}![]const u8 { const value = fromSeconds(epoch_seconds); if (value.year < 0 or value.year > 9999) return error.OutOfRange; // A writer over exactly `imf_len` octets has no slack, and the number // formatter asks for room to align in before it knows it will not need // it, so the date is written somewhere roomier and copied. var scratch: [2 * imf_len]u8 = undefined; var w: Writer = .fixed(&scratch); golayout.format(value, imf_layout, &w) catch unreachable; std.debug.assert(w.end == imf_len); buf.* = scratch[0..imf_len].*; return buf; } test formatImf { var buf: [imf_len]u8 = undefined; try std.testing.expectEqualStrings("Sun, 06 Nov 1994 08:49:37 GMT", try formatImf(&buf, 784111777)); // 10000-01-01 has a five-digit year, which an IMF-fixdate cannot hold. try std.testing.expectError(error.OutOfRange, formatImf(&buf, 253402300800)); } /// Writes an IMF-fixdate, which is the only format a sender may use. /// /// A year that will not fit in four digits is written with as many digits as /// it needs, which no recipient will parse — but a `Last-Modified` from a /// corrupt inode is better written oddly than not written at all, and /// `formatImf` is there for a caller that would rather leave the field out. pub fn writeImf(w: *Writer, epoch_seconds: i64) Writer.Error!void { golayout.format(fromSeconds(epoch_seconds), imf_layout, w) catch return error.WriteFailed; } test writeImf { var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try writeImf(&w, 784111777); try std.testing.expectEqualStrings("Sun, 06 Nov 1994 08:49:37 GMT", w.buffered()); // Out of a four-digit year's range, written anyway rather than dropped. w = .fixed(&buf); try writeImf(&w, 253402300800); try std.testing.expectEqualStrings("Sat, 01 Jan 10000 00:00:00 GMT", w.buffered()); } /// Reads any of the three formats RFC 9110 §5.6.7 requires a recipient to /// accept, returning seconds since the Unix epoch. /// /// The date has to be one the calendar has: a day past the end of its month /// -- `31 Feb` -- or a leap second (`:60`) is not one. The day of the week is /// required and not checked against the date, and month and day names are /// matched without regard to case, as Go's `net/http` matches them. /// /// The RFC 850 form's two-digit year is 1969 to 2068, the window Go uses. /// §5.6.7 asks for a window that slides with the clock instead -- a year more /// than fifty years ahead is the one a century earlier -- and the fixed one /// keeps this a pure function, at the cost of reading `69` a century early /// until 2019 and a century late from 2069. A format obsolete since 1996 will /// not be around to notice. /// /// Null for anything else. A malformed date is not an error worth a status /// code: RFC 9110 §13.1.3 has a recipient ignore an `If-Modified-Since` it /// cannot read rather than reject the request, because the alternative is /// failing a conditional request that would have succeeded unconditionally. pub fn parse(s: []const u8) ?i64 { const value = golayout.parse(imf_layout, s) catch golayout.parse(rfc850_layout, s) catch golayout.parse(asctime_layout, s) catch return null; return toSeconds(value); } test parse { // The three formats a recipient must accept, all naming the same instant. try std.testing.expectEqual(@as(i64, 784111777), parse("Sun, 06 Nov 1994 08:49:37 GMT").?); try std.testing.expectEqual(@as(i64, 784111777), parse("Sunday, 06-Nov-94 08:49:37 GMT").?); try std.testing.expectEqual(@as(i64, 784111777), parse("Sun Nov 6 08:49:37 1994").?); // Not an error, just not a date: the field is ignored. try std.testing.expect(parse("yesterday") == null); } /// The civil date and time in UTC of a count of seconds since the epoch. /// Total: an instant beyond the calendar's years gives the first or last date /// there is rather than a panic. fn fromSeconds(epoch_seconds: i64) DateTime { return datetime.Instant.fromNanoTimeStamp(@as(i128, epoch_seconds) * std.time.ns_per_s).asDateTime(); } /// The other way. Every date the parser can produce has a four-digit year at /// most, so the count always fits. fn toSeconds(value: DateTime) i64 { return @intCast(@divFloor(value.toInstant().timestamp, std.time.ns_per_s)); } test "the epoch itself" { var buf: [imf_len]u8 = undefined; try std.testing.expectEqualStrings("Thu, 01 Jan 1970 00:00:00 GMT", try formatImf(&buf, 0)); try std.testing.expectEqual(@as(i64, 0), parse("Thu, 01 Jan 1970 00:00:00 GMT").?); } test "the example from the RFC" { var buf: [imf_len]u8 = undefined; const expected = "Sun, 06 Nov 1994 08:49:37 GMT"; const secs = parse(expected).?; try std.testing.expectEqualStrings(expected, try formatImf(&buf, secs)); // All three formats name the same instant. try std.testing.expectEqual(secs, parse("Sunday, 06-Nov-94 08:49:37 GMT").?); try std.testing.expectEqual(secs, parse("Sun Nov 6 08:49:37 1994").?); // And `asctime` with a two-digit day, where the padding space is not. try std.testing.expectEqual(secs + 10 * 86400, parse("Wed Nov 16 08:49:37 1994").?); } test "dates before the epoch" { var buf: [imf_len]u8 = undefined; // 1969-12-31 23:59:59, one second before the epoch: a negative count, // which `std.time.epoch` cannot represent. try std.testing.expectEqualStrings("Wed, 31 Dec 1969 23:59:59 GMT", try formatImf(&buf, -1)); try std.testing.expectEqual(@as(i64, -1), parse("Wed, 31 Dec 1969 23:59:59 GMT").?); try std.testing.expectEqualStrings("Fri, 13 Dec 1901 20:45:52 GMT", try formatImf(&buf, -2147483648)); } test "the leap year rules" { // 2000 was a leap year and 1900 was not. try std.testing.expectEqual(@as(i64, 951782400), parse("Tue, 29 Feb 2000 00:00:00 GMT").?); try std.testing.expect(parse("Thu, 29 Feb 1900 00:00:00 GMT") == null); } test "the extremes do not panic" { var buf: [imf_len]u8 = undefined; // Well outside a four-digit year, which is what a corrupt mtime looks // like. It must be refused rather than crash. try std.testing.expectError(error.OutOfRange, formatImf(&buf, std.math.maxInt(i64))); try std.testing.expectError(error.OutOfRange, formatImf(&buf, std.math.minInt(i64))); // And the raw formatter must survive them too. var discard_buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&discard_buf); try writeImf(&w, std.math.minInt(i64)); w = .fixed(&discard_buf); try writeImf(&w, std.math.maxInt(i64)); } test "dates that are not dates" { try std.testing.expect(parse("") == null); try std.testing.expect(parse("not a date at all, really") == null); try std.testing.expect(parse("Xxx, 06 Nov 1994 08:49:37 GMT") == null); try std.testing.expect(parse("Sun, 06 Xxx 1994 08:49:37 GMT") == null); // Neither a local time nor another zone is an HTTP date. try std.testing.expect(parse("Sun, 06 Nov 1994 08:49:37 EST") == null); try std.testing.expect(parse("Sun, 06 Nov 1994 08:49:37") == null); // Ranges are checked rather than narrowed into. try std.testing.expect(parse("Sun, 99 Nov 1994 08:49:37 GMT") == null); try std.testing.expect(parse("Sun, 06 Nov 1994 99:49:37 GMT") == null); try std.testing.expect(parse("Sun, 31 Feb 1994 08:49:37 GMT") == null); }