// 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. //! //! Zig's `std.time.epoch` only goes one way — it turns a second count into a //! date and has nothing coming back — and its second count is unsigned, so it //! cannot reach a `Last-Modified` before 1970. Both directions are here //! instead, as Howard Hinnant's `days_from_civil` and `civil_from_days`, //! which are exact over the whole proleptic Gregorian calendar and about //! fifteen lines each. //! //! The arithmetic is done in `i128` where a year at either end of `i64` //! seconds would otherwise overflow it. 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 day_names = [_][]const u8{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; const month_names = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; const long_day_names = [_][]const u8{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", }; /// A civil date and time, in UTC. pub const Civil = struct { year: i64, /// 1 to 12. month: u8, /// 1 to 31. day: u8, hour: u8, minute: u8, second: u8, /// 0 is Sunday. weekday: u8, }; /// Days since 1970-01-01 for a civil date, by Howard Hinnant's /// `days_from_civil`. Exact for every year the proleptic Gregorian calendar /// has. pub fn daysFromCivil(year: i64, month: u8, day: u8) i64 { const y: i128 = @as(i128, year) - @intFromBool(month <= 2); const era = @divFloor(y, 400); const yoe = y - era * 400; // [0, 399] const mp: i128 = (@as(i128, month) + if (month > 2) @as(i128, -3) else @as(i128, 9)); const doy = @divTrunc(153 * mp + 2, 5) + @as(i128, day) - 1; // [0, 365] const doe = yoe * 365 + @divTrunc(yoe, 4) - @divTrunc(yoe, 100) + doy; // [0, 146096] return @intCast(era * 146097 + doe - 719468); } /// The civil date for a day count since 1970-01-01, by Howard Hinnant's /// `civil_from_days`. pub fn civilFromDays(days: i64) struct { year: i64, month: u8, day: u8 } { const z: i128 = @as(i128, days) + 719468; const era = @divFloor(z, 146097); const doe = z - era * 146097; // [0, 146096] const yoe = @divTrunc(doe - @divTrunc(doe, 1460) + @divTrunc(doe, 36524) - @divTrunc(doe, 146096), 365); // [0, 399] const y = yoe + era * 400; const doy = doe - (365 * yoe + @divTrunc(yoe, 4) - @divTrunc(yoe, 100)); // [0, 365] const mp = @divTrunc(5 * doy + 2, 153); // [0, 11] const d = doy - @divTrunc(153 * mp + 2, 5) + 1; // [1, 31] const m = mp + (if (mp < 10) @as(i128, 3) else @as(i128, -9)); // [1, 12] return .{ .year = @intCast(y + @intFromBool(m <= 2)), .month = @intCast(m), .day = @intCast(d), }; } /// Takes a count of seconds since the Unix epoch apart into a civil date and /// time in UTC. pub fn civilFromEpoch(epoch_seconds: i64) Civil { // In `i128` because `seconds - days * 86400` overflows `i64` one day // below the bottom of it, where `@mod` does not save you either. const secs: i128 = epoch_seconds; const days: i64 = @intCast(@divFloor(secs, 86400)); const sod: u32 = @intCast(secs - @as(i128, days) * 86400); const civil = civilFromDays(days); return .{ .year = civil.year, .month = civil.month, .day = civil.day, .hour = @intCast(sod / 3600), .minute = @intCast(sod % 3600 / 60), .second = @intCast(sod % 60), // 1970-01-01 was a Thursday, and `@mod` gives a non-negative // remainder for a negative day count, which `%` would not. .weekday = @intCast(@mod(@as(i64, days) + 4, 7)), }; } /// Seconds since the Unix epoch for a civil date and time in UTC. pub fn epochFromCivil(year: i64, month: u8, day: u8, hour: u8, minute: u8, second: u8) i64 { const days: i128 = daysFromCivil(year, month, day); return @intCast(days * 86400 + @as(i128, hour) * 3600 + @as(i128, minute) * 60 + second); } /// 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. /// /// Composed by hand rather than through a `Writer`, because the result is /// exactly `imf_len` octets: a `Writer.fixed` over a buffer that size has no /// slack, and the number formatter asks for room to align in before it knows /// it will not need it. /// /// `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 c = civilFromEpoch(epoch_seconds); if (c.year < 0 or c.year > 9999) return error.OutOfRange; buf[0..3].* = day_names[c.weekday][0..3].*; buf[3] = ','; buf[4] = ' '; writeDigits(buf[5..7], c.day); buf[7] = ' '; buf[8..11].* = month_names[c.month - 1][0..3].*; buf[11] = ' '; writeDigits(buf[12..16], @intCast(c.year)); buf[16] = ' '; writeDigits(buf[17..19], c.hour); buf[19] = ':'; writeDigits(buf[20..22], c.minute); buf[22] = ':'; writeDigits(buf[23..25], c.second); buf[25..29].* = " GMT".*; return buf; } /// Writes `value` right-aligned and zero-padded into exactly `dst.len` /// digits, which is what every field of an IMF-fixdate is. fn writeDigits(dst: []u8, value: u16) void { var v = value; var i = dst.len; while (i > 0) { i -= 1; dst[i] = '0' + @as(u8, @intCast(v % 10)); v /= 10; } } /// 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 { var buf: [imf_len]u8 = undefined; if (formatImf(&buf, epoch_seconds)) |s| return w.writeAll(s) else |_| {} const c = civilFromEpoch(epoch_seconds); try w.print("{s}, {d:0>2} {s} {d} {d:0>2}:{d:0>2}:{d:0>2} GMT", .{ day_names[c.weekday], c.day, month_names[c.month - 1], c.year, c.hour, c.minute, c.second, }); } /// Reads any of the three formats RFC 9110 §5.6.7 requires a recipient to /// accept, returning seconds since the Unix epoch. /// /// 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 { return parseImf(s) orelse parseRfc850(s) orelse parseAsctime(s); } /// `Sun, 06 Nov 1994 08:49:37 GMT` fn parseImf(s: []const u8) ?i64 { if (s.len != imf_len) return null; if (indexOfName(&day_names, s[0..3]) == null) return null; if (!std.mem.eql(u8, s[3..5], ", ")) return null; const day = twoDigits(s[5..7]) orelse return null; if (s[7] != ' ') return null; const month = indexOfName(&month_names, s[8..11]) orelse return null; if (s[11] != ' ') return null; const year = fourDigits(s[12..16]) orelse return null; if (s[16] != ' ') return null; const time = parseTime(s[17..25]) orelse return null; if (!std.mem.eql(u8, s[25..], " GMT")) return null; return assemble(year, month + 1, day, time); } /// `Sunday, 06-Nov-94 08:49:37 GMT` fn parseRfc850(s: []const u8) ?i64 { const comma = std.mem.indexOfScalar(u8, s, ',') orelse return null; if (indexOfName(&long_day_names, s[0..comma]) == null) return null; const rest = s[comma + 1 ..]; if (rest.len != " 06-Nov-94 08:49:37 GMT".len) return null; if (rest[0] != ' ') return null; const day = twoDigits(rest[1..3]) orelse return null; if (rest[3] != '-') return null; const month = indexOfName(&month_names, rest[4..7]) orelse return null; if (rest[7] != '-') return null; const yy = twoDigits(rest[8..10]) orelse return null; if (rest[10] != ' ') return null; const time = parseTime(rest[11..19]) orelse return null; if (!std.mem.eql(u8, rest[19..], " GMT")) return null; // RFC 9110 §5.6.7: a two-digit year more than fifty years in the future // is the most recent year in the past with the same last two digits. // Anchoring on 1970 rather than on the current year keeps this a pure // function, at the cost of being wrong about dates after 2069 -- which // is a format nobody should still be sending by then. const year: i64 = if (yy >= 70) 1900 + @as(i64, yy) else 2000 + @as(i64, yy); return assemble(year, month + 1, day, time); } /// `Sun Nov 6 08:49:37 1994` fn parseAsctime(s: []const u8) ?i64 { if (s.len != "Sun Nov 6 08:49:37 1994".len) return null; if (indexOfName(&day_names, s[0..3]) == null) return null; if (s[3] != ' ') return null; const month = indexOfName(&month_names, s[4..7]) orelse return null; if (s[7] != ' ') return null; // The day is space-padded rather than zero-padded here, and only here. const day: u8 = if (s[8] == ' ') (std.fmt.charToDigit(s[9], 10) catch return null) else (twoDigits(s[8..10]) orelse return null); if (s[10] != ' ') return null; const time = parseTime(s[11..19]) orelse return null; if (s[19] != ' ') return null; const year = fourDigits(s[20..24]) orelse return null; return assemble(year, month + 1, day, time); } const Time = struct { hour: u8, minute: u8, second: u8 }; fn parseTime(s: []const u8) ?Time { std.debug.assert(s.len == 8); if (s[2] != ':' or s[5] != ':') return null; return .{ .hour = twoDigits(s[0..2]) orelse return null, .minute = twoDigits(s[3..5]) orelse return null, // A leap second arrives as :60 and has no epoch second of its own; // it is folded onto the one before it rather than rejected. .second = twoDigits(s[6..8]) orelse return null, }; } /// Ranges are checked here, after the digits have been read, and never by /// narrowing: `@intCast` of `99` into a `u5` day field is a panic rather than /// an error, so a parser that narrows first crashes on input it meant to /// reject. fn assemble(year: i64, month: u8, day: u8, time: Time) ?i64 { if (month < 1 or month > 12) return null; if (day < 1 or day > 31) return null; if (time.hour > 23 or time.minute > 59 or time.second > 60) return null; const second = @min(time.second, 59); return epochFromCivil(year, month, day, time.hour, time.minute, second); } fn indexOfName(names: []const []const u8, s: []const u8) ?u8 { for (names, 0..) |name, i| { if (std.mem.eql(u8, name, s)) return @intCast(i); } return null; } fn twoDigits(s: []const u8) ?u8 { std.debug.assert(s.len == 2); const hi = std.fmt.charToDigit(s[0], 10) catch return null; const lo = std.fmt.charToDigit(s[1], 10) catch return null; return hi * 10 + lo; } fn fourDigits(s: []const u8) ?i64 { std.debug.assert(s.len == 4); var n: i64 = 0; for (s) |c| n = n * 10 + (std.fmt.charToDigit(c, 10) catch return null); return n; } 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").?); } test "dates before the epoch" { var buf: [imf_len]u8 = undefined; // 1969-12-31 23:59:59, one second before the epoch. The day count is // negative here, which is the case `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 "round trip across a few thousand years" { // Every leap year rule gets exercised: the 4, the 100 and the 400. const days = [_]i64{ -719468, -25567, 0, 11017, 19723, 25202, 2932896 }; for (days) |d| { const c = civilFromDays(d); try std.testing.expectEqual(d, daysFromCivil(c.year, c.month, c.day)); } // 2000 was a leap year and 1900 was not. try std.testing.expectEqual(daysFromCivil(2000, 3, 1), daysFromCivil(2000, 2, 29) + 1); try std.testing.expectEqual(daysFromCivil(1900, 3, 1), daysFromCivil(1900, 2, 28) + 1); } 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)); } 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); // 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); }