// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The one timestamp format the protocol has, and the calendar arithmetic //! behind it. //! //! RFC 3659 §2.3 settled a question RFC 959 left open by giving `MDTM` and the //! `modify` fact a single format — `YYYYMMDDHHMMSS`, always UTC, never a zone //! offset — and it is the only unambiguous timestamp in FTP. The date in a //! `LIST` line is the other kind: local to the server, in a format meant for a //! person, and missing either the year or the time of day depending on how old //! the file is. `listing.zig` parses those as best it can; this file is what //! it and `MDTM` share. //! //! `std.time.epoch` decodes a timestamp but cannot encode one, and its //! `EpochSeconds` is unsigned, so a file dated before 1970 — which is every //! file on a machine whose clock has not been set — cannot be represented. The //! conversions here are Howard Hinnant's, which are exact in both directions //! over the whole proleptic Gregorian calendar. const std = @import("std"); const Io = std.Io; /// A civil date and time, in UTC. pub const DateTime = struct { /// Wide enough for every date a signed 64-bit second count can reach, /// which runs to about 292 billion years either side of 1970. Narrower /// would mean `fromUnixSeconds` had inputs it could only answer by /// crashing, and it is handed whatever a file system says a file's mtime /// is. year: i64, /// 1 to 12. month: u4, /// 1 to 31. day: u5, /// 0 to 23. hour: u5, /// 0 to 59. minute: u6, /// 0 to 60; 60 only ever arrives from a peer claiming a leap second. second: u6, /// Total: every `i64` names a date, including the two ends of the range. pub fn fromUnixSeconds(seconds: i64) DateTime { // Floored division, so that a time before the epoch lands on the day // before rather than the day after. `@mod` rather than subtracting // `days * seconds_per_day`, which overflows at the bottom of the // range -- the product is one day further from zero than `i64` goes. const days = @divFloor(seconds, seconds_per_day); const day_seconds: u32 = @intCast(@mod(seconds, seconds_per_day)); const civil = civilFromDays(days); return .{ .year = civil.year, .month = civil.month, .day = civil.day, .hour = @intCast(day_seconds / 3600), .minute = @intCast(day_seconds / 60 % 60), .second = @intCast(day_seconds % 60), }; } /// The inverse of `fromUnixSeconds`, saturating at the ends of `i64`. /// /// A `DateTime` can hold a year that no second count can express, since /// nothing stops one being written down; the arithmetic is done in `i128` /// so that building such a date is not a crash, and the answer is clamped /// rather than wrapped so that it is at least in the right direction. pub fn toUnixSeconds(dt: DateTime) i64 { const seconds = daysFromCivil(dt.year, dt.month, dt.day) * seconds_per_day + @as(i128, dt.hour) * 3600 + @as(i128, dt.minute) * 60 + dt.second; return @intCast(std.math.clamp( seconds, std.math.minInt(i64), std.math.maxInt(i64), )); } /// Whether the fields name a date that exists. A parser has to ask, /// because `20250230120000` is fourteen perfectly good digits. pub fn isValid(dt: DateTime) bool { return dt.month >= 1 and dt.month <= 12 and dt.day >= 1 and dt.day <= daysInMonth(dt.year, dt.month) and dt.hour <= 23 and dt.minute <= 59 and dt.second <= 60; } }; const seconds_per_day = 24 * 60 * 60; pub fn isLeapYear(year: i64) bool { return @mod(year, 4) == 0 and (@mod(year, 100) != 0 or @mod(year, 400) == 0); } pub fn daysInMonth(year: i64, month: u4) u5 { return switch (month) { 1, 3, 5, 7, 8, 10, 12 => 31, 4, 6, 9, 11 => 30, 2 => if (isLeapYear(year)) 29 else 28, else => 0, }; } const Civil = struct { year: i64, month: u4, day: u5 }; /// Days since 1970-01-01 for a proleptic Gregorian date. /// /// In `i128`, because the year is an `i64` and a year near the end of that /// range multiplied out by 146097 is not. fn daysFromCivil(year: i64, month: u4, day: u5) i128 { // The calendar is shifted so that a year begins in March, which puts the // leap day at the end of it and makes the month-length pattern a straight // line: that is what the `(153 * mp + 2) / 5` below is. const y: i128 = @as(i128, year) - @intFromBool(month <= 2); const era = @divFloor(y, 400); const yoe = y - era * 400; // 0 to 399 const mp: i128 = @as(i128, month) + (if (month > 2) @as(i128, -3) else 9); const doy = @divTrunc(153 * mp + 2, 5) + day - 1; // 0 to 365 const doe = yoe * 365 + @divTrunc(yoe, 4) - @divTrunc(yoe, 100) + doy; // 0 to 146096 return era * 146097 + doe - 719468; } fn civilFromDays(days: i128) Civil { const z = days + 719468; const era = @divFloor(z, 146097); const doe = z - era * 146097; // 0 to 146096 const yoe = @divTrunc(doe - @divTrunc(doe, 1460) + @divTrunc(doe, 36524) - @divTrunc(doe, 146096), 365); const y = yoe + era * 400; const doy = doe - (365 * yoe + @divTrunc(yoe, 4) - @divTrunc(yoe, 100)); const mp = @divTrunc(5 * doy + 2, 153); // 0 to 11, March being 0 const d = doy - @divTrunc(153 * mp + 2, 5) + 1; const m = mp + (if (mp < 10) @as(i64, 3) else -9); return .{ .year = @intCast(y + @intFromBool(m <= 2)), .month = @intCast(m), .day = @intCast(d), }; } /// Writes a timestamp as RFC 3659 §2.3 writes one: `YYYYMMDDHHMMSS`, in UTC. pub fn writeTimeval(w: *Io.Writer, seconds: i64) Io.Writer.Error!void { const dt: DateTime = .fromUnixSeconds(seconds); // The year is four digits by definition, so a date outside 0 to 9999 // cannot be written at all. Clamping is the least bad answer: refusing // would mean a single absurd mtime makes a directory unlistable. const year = std.math.clamp(dt.year, 0, 9999); try w.print("{d:0>4}{d:0>2}{d:0>2}{d:0>2}{d:0>2}{d:0>2}", .{ @as(u16, @intCast(year)), dt.month, dt.day, dt.hour, dt.minute, dt.second, }); } /// Formats a timestamp for `{f}` as RFC 3659 writes one. See `writeTimeval`. pub fn timeval(seconds: i64) Timeval { return .{ .seconds = seconds }; } pub const Timeval = struct { seconds: i64, pub fn format(t: Timeval, w: *Io.Writer) Io.Writer.Error!void { return writeTimeval(w, t.seconds); } }; pub const ParseError = error{ /// The text is not fourteen digits, or the digits name a date that does /// not exist. InvalidTimeval, }; /// Reads an RFC 3659 timestamp. /// /// A fractional part after a full stop is accepted and discarded: RFC 3659 /// §2.3 allows servers to send one, and no client has ever needed sub-second /// resolution from a file listing. pub fn parseTimeval(text: []const u8) ParseError!i64 { const digits = text[0 .. std.mem.findScalar(u8, text, '.') orelse text.len]; if (digits.len != 14) return error.InvalidTimeval; for (digits) |c| if (!std.ascii.isDigit(c)) return error.InvalidTimeval; const year = number(digits[0..4]); const month = number(digits[4..6]); const day = number(digits[6..8]); const hour = number(digits[8..10]); const minute = number(digits[10..12]); const second = number(digits[12..14]); // Ranges checked *before* narrowing. A `DateTime` holds its month in four // bits and its day in five, and two digits reach 99, so casting first // turns a timestamp of `20259999999999` into a panic rather than an // error — which a malformed `modify` fact in an `MLSD` reply would then // crash a client with. A fuzzer found that; `isValid` cannot help, // because the cast happens before it is called. if (month < 1 or month > 12) return error.InvalidTimeval; if (day < 1 or day > 31) return error.InvalidTimeval; if (hour > 23 or minute > 59 or second > 60) return error.InvalidTimeval; const dt: DateTime = .{ .year = @intCast(year), .month = @intCast(month), .day = @intCast(day), .hour = @intCast(hour), .minute = @intCast(minute), .second = @intCast(second), }; // Still asked, because 31 February passes every check above. if (!dt.isValid()) return error.InvalidTimeval; return dt.toUnixSeconds(); } /// Reads a run of digits that has already been checked to be digits. /// /// Returns a `u32`, which the four digits of a year cannot overflow, and /// leaves the narrowing to a caller that has checked the range first. fn number(digits: []const u8) u32 { var value: u32 = 0; for (digits) |c| value = value * 10 + (c - '0'); return value; } /// Converts one of the `Io.Timestamp` values a file system reports into the /// seconds this file deals in, rounding towards the past. pub fn secondsFromTimestamp(t: Io.Timestamp) i64 { return @intCast(@divFloor(t.nanoseconds, std.time.ns_per_s)); } /// The inverse of `secondsFromTimestamp`. pub fn timestampFromSeconds(seconds: i64) Io.Timestamp { return .{ .nanoseconds = @as(i96, seconds) * std.time.ns_per_s }; } // -- tests ---------------------------------------------------------------- const testing = std.testing; test "the epoch" { const dt: DateTime = .fromUnixSeconds(0); try testing.expectEqual(DateTime{ .year = 1970, .month = 1, .day = 1, .hour = 0, .minute = 0, .second = 0, }, dt); try testing.expectEqual(@as(i64, 0), dt.toUnixSeconds()); } test "known instants" { const cases = [_]struct { i64, DateTime }{ .{ 1234567890, .{ .year = 2009, .month = 2, .day = 13, .hour = 23, .minute = 31, .second = 30 } }, // A leap day, which is where a calendar that got the rule wrong shows // it. .{ 951782400, .{ .year = 2000, .month = 2, .day = 29, .hour = 0, .minute = 0, .second = 0 } }, .{ 1709164800, .{ .year = 2024, .month = 2, .day = 29, .hour = 0, .minute = 0, .second = 0 } }, // 1900 was not a leap year, which is the other half of the rule. .{ -2208988800, .{ .year = 1900, .month = 1, .day = 1, .hour = 0, .minute = 0, .second = 0 } }, // Before the epoch, where an unsigned implementation cannot go. .{ -1, .{ .year = 1969, .month = 12, .day = 31, .hour = 23, .minute = 59, .second = 59 } }, .{ 2147483647, .{ .year = 2038, .month = 1, .day = 19, .hour = 3, .minute = 14, .second = 7 } }, }; for (cases) |case| { const seconds, const expected = case; try testing.expectEqual(expected, DateTime.fromUnixSeconds(seconds)); try testing.expectEqual(seconds, expected.toUnixSeconds()); } } test "every day of four centuries round trips" { // The conversions are each other's inverse or they are worthless, and the // cheapest way to be sure of that across every leap rule is to walk the // whole cycle the Gregorian calendar repeats on. var day: i128 = daysFromCivil(1800, 1, 1); const end = daysFromCivil(2200, 1, 1); while (day < end) : (day += 1) { const civil = civilFromDays(day); try testing.expectEqual(day, daysFromCivil(civil.year, civil.month, civil.day)); } } test "MDTM timestamps" { var buffer: [32]u8 = undefined; try testing.expectEqualStrings( "20090213233130", try std.fmt.bufPrint(&buffer, "{f}", .{timeval(1234567890)}), ); try testing.expectEqual(@as(i64, 1234567890), try parseTimeval("20090213233130")); try testing.expectEqual(@as(i64, 1234567890), try parseTimeval("20090213233130.500")); } test "MDTM timestamps that are not" { try testing.expectError(error.InvalidTimeval, parseTimeval("")); try testing.expectError(error.InvalidTimeval, parseTimeval("2009021323313")); try testing.expectError(error.InvalidTimeval, parseTimeval("200902132331300")); try testing.expectError(error.InvalidTimeval, parseTimeval("2009021x233130")); // A month, a day and an hour that do not exist. try testing.expectError(error.InvalidTimeval, parseTimeval("20091313233130")); try testing.expectError(error.InvalidTimeval, parseTimeval("20090230233130")); try testing.expectError(error.InvalidTimeval, parseTimeval("20090213243130")); // 29 February in a year that had none. try testing.expectError(error.InvalidTimeval, parseTimeval("19000229000000")); } test "digits that cannot fit the field they are for" { // Every one of these overflows a `DateTime` field, and every one of them // used to be a panic rather than an error: the value was narrowed into // four or five bits before anything looked at it. A server sending a // `modify` fact like this would crash the client listing its directory. try testing.expectError(error.InvalidTimeval, parseTimeval("20259999999999")); try testing.expectError(error.InvalidTimeval, parseTimeval("20259901000000")); // month 99 try testing.expectError(error.InvalidTimeval, parseTimeval("20250199000000")); // day 99 try testing.expectError(error.InvalidTimeval, parseTimeval("20250101990000")); // hour 99 try testing.expectError(error.InvalidTimeval, parseTimeval("20250101009900")); // minute 99 try testing.expectError(error.InvalidTimeval, parseTimeval("20250101000099")); // second 99 // And the boundaries either side of what is allowed. try testing.expectError(error.InvalidTimeval, parseTimeval("20251301000000")); try testing.expectError(error.InvalidTimeval, parseTimeval("20250132000000")); try testing.expectError(error.InvalidTimeval, parseTimeval("20250101240000")); try testing.expectError(error.InvalidTimeval, parseTimeval("20250101006000")); // A leap second is allowed, because a peer may claim one. _ = try parseTimeval("20250101000060"); } test "29 February in a year that had one" { try testing.expectEqual(@as(i64, 951782400), try parseTimeval("20000229000000")); } test "Io.Timestamp conversion" { try testing.expectEqual(@as(i64, 5), secondsFromTimestamp(.{ .nanoseconds = 5_999_999_999 })); try testing.expectEqual(@as(i64, -1), secondsFromTimestamp(.{ .nanoseconds = -1 })); try testing.expectEqual(@as(i96, 5_000_000_000), timestampFromSeconds(5).nanoseconds); } test "every second is a date, including the ends of the range" { // `fromUnixSeconds` is handed whatever a file system says a file's mtime // is, so it has to answer rather than crash. Both of these used to: the // year did not fit an `i32`, and the seconds-into-the-day was worked out // with a multiplication that overflows one day past the bottom of `i64`. for ([_]i64{ std.math.minInt(i64), std.math.maxInt(i64), std.math.minInt(i64) + 1, std.math.maxInt(i64) - 1, -seconds_per_day, 1 << 62, -(1 << 62), }) |seconds| { const dt: DateTime = .fromUnixSeconds(seconds); // Whatever it says, the time of day is a real one. try testing.expect(dt.hour <= 23 and dt.minute <= 59 and dt.second <= 59); try testing.expect(dt.month >= 1 and dt.month <= 12); try testing.expect(dt.day >= 1 and dt.day <= 31); } } test "a date no second count can express saturates rather than wrapping" { const far: DateTime = .{ .year = std.math.maxInt(i64), .month = 1, .day = 1, .hour = 0, .minute = 0, .second = 0, }; try testing.expectEqual(std.math.maxInt(i64), far.toUnixSeconds()); var back = far; back.year = std.math.minInt(i64); try testing.expectEqual(std.math.minInt(i64), back.toUnixSeconds()); } test "writing a timestamp no calendar year can show" { // The format has four columns for a year, so anything outside them is // clamped rather than printed wrongly or refused. var buffer: [32]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeTimeval(&w, std.math.maxInt(i64)); try testing.expect(std.mem.startsWith(u8, w.buffered(), "9999")); var w2: Io.Writer = .fixed(&buffer); try writeTimeval(&w2, std.math.minInt(i64)); try testing.expect(std.mem.startsWith(u8, w2.buffered(), "0000")); }