// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Directory listings, in the two formats FTP has and the one it should have //! had. //! //! `NLST` sends bare names, which is unambiguous and says nothing else. //! `LIST` sends whatever the server thinks a person would like to read, which //! in practice means the output of `ls -l` — RFC 959 §4.1.3 does not specify //! it at all, and a client that wants a file's size out of a `LIST` line is //! reverse-engineering another program's display format. `MLSD` and `MLST` //! (RFC 3659 §7) are the fix: the same information as `name=value;` pairs, in //! a fixed encoding, with a defined character set and an unambiguous UTC //! timestamp. //! //! Prefer `MLSD` wherever the server has it — `Client.list` does — and keep //! the `LIST` parsers for the servers that do not. They are heuristics and //! they are honest about it: every field is optional, and a line that cannot //! be read yields the name and nothing else rather than a wrong size. const std = @import("std"); const Io = std.Io; const ascii = std.ascii; const time = @import("time.zig"); /// What an entry is. The middle two exist only in `MLSD` output, where RFC /// 3659 §7.5.1 has a directory describe itself and its parent so that a client /// learns what it may do with them. pub const Kind = enum { file, dir, /// `.`, the directory being listed. current_dir, /// `..`, its parent. parent_dir, symlink, /// A device, socket, pipe or anything else that is not worth naming. other, /// Whether a client may `CWD` into this, ignoring permissions. pub fn isDirectory(k: Kind) bool { return switch (k) { .dir, .current_dir, .parent_dir => true, .file, .symlink, .other => false, }; } }; /// What the client may do with an entry: the `perm` fact of RFC 3659 §7.5.5, /// which is a set of letters and not a Unix mode. The distinction matters — /// these say what *this* client may do after the server has considered its /// identity, the file's owner and everything else, which is what a client /// actually wants to know and what a mode cannot tell it. pub const Permissions = packed struct { /// `a`: `APPE` may add to this file. append: bool = false, /// `c`: files may be created in this directory. create: bool = false, /// `d`: this may be deleted, with `DELE` or `RMD`. delete: bool = false, /// `e`: `CWD` may enter this directory. enter: bool = false, /// `f`: this may be renamed, with `RNFR`. rename: bool = false, /// `l`: this directory's contents may be listed. list: bool = false, /// `m`: `MKD` may create a directory inside this one. make_dir: bool = false, /// `p`: entries may be deleted from this directory. purge: bool = false, /// `r`: `RETR` may read this file. retrieve: bool = false, /// `w`: `STOR` may overwrite this file. store: bool = false, const letters = "acdeflmprw"; pub fn format(p: Permissions, w: *Io.Writer) Io.Writer.Error!void { // RFC 3659 §7.5.5 asks for the letters in this order, which is // alphabetical, and for a client to accept them in any. inline for (@typeInfo(Permissions).@"struct".field_names, letters) |name, letter| { if (@field(p, name)) try w.writeByte(letter); } } /// Reads a `perm` fact. Letters this library does not know are ignored /// rather than refused: the fact is a set, and a server that has invented /// a letter has not invalidated the ones it shares with everybody. pub fn parse(text: []const u8) Permissions { var p: Permissions = .{}; for (text) |c| { inline for (@typeInfo(Permissions).@"struct".field_names, letters) |name, letter| { if (ascii.toLower(c) == letter) @field(p, name) = true; } } return p; } }; /// The Unix facts a server may report alongside the portable ones. They are /// what a `LIST` line carries and what `MLSD` sends as `UNIX.mode` and /// friends, and they are advisory: `Permissions` is what says whether a /// command will work. pub const Unix = struct { /// The permission bits, without the file type: 0o644 and not 0o100644. mode: ?u16 = null, owner: ?[]const u8 = null, group: ?[]const u8 = null, link_count: ?u64 = null, }; /// One line of a directory listing, in whichever format it arrived. /// /// Every field but the name is optional, because every field but the name is /// missing from some real server's output. A client that needs a size should /// ask for it with `SIZE` when the listing did not supply one. /// /// The slices borrow from the line the entry was parsed out of. pub const Entry = struct { /// The name as the server wrote it. For `MLSD` this may be a path rather /// than a bare name; RFC 3659 §7.2 allows either. name: []const u8, kind: Kind = .file, size: ?u64 = null, /// Last modification, in seconds since 1970-01-01 UTC. modified: ?i64 = null, /// Creation, in seconds since 1970-01-01 UTC. Rare. created: ?i64 = null, permissions: ?Permissions = null, /// The `unique` fact: an identifier that is the same for two names if and /// only if they are the same file. What a recursive client uses to notice /// that a directory tree has a cycle in it. unique: ?[]const u8 = null, /// Where a symbolic link points, when the server said. link_target: ?[]const u8 = null, unix: Unix = .{}, /// Whether this is `.` or `..` under any of the spellings the formats use. /// A client walking a tree has to skip these or walk forever. pub fn isSelfOrParent(e: Entry) bool { return switch (e.kind) { .current_dir, .parent_dir => true, else => std.mem.eql(u8, e.name, ".") or std.mem.eql(u8, e.name, ".."), }; } }; // -- MLSD and MLST: the machine-readable format --------------------------- /// Writes one `MLSD` line: the facts, a space, the name. /// /// Only the facts that are set are written. RFC 3659 §7.8 has the client ask /// for the ones it wants with `OPTS MLST`, and a server that sends fewer than /// were asked for is within its rights; a server that sends more is too. pub fn writeMachineEntry(w: *Io.Writer, entry: Entry) Io.Writer.Error!void { switch (entry.kind) { .file => try w.writeAll("type=file;"), .dir => try w.writeAll("type=dir;"), .current_dir => try w.writeAll("type=cdir;"), .parent_dir => try w.writeAll("type=pdir;"), // RFC 3659 has no portable spelling for a symbolic link, so this is // the `OS.` form that RFC 3659 §7.5.1 provides for exactly this case // and that servers have settled on. .symlink => if (entry.link_target) |target| try w.print("type=OS.unix=slink:{s};", .{target}) else try w.writeAll("type=OS.unix=slink;"), // RFC 3659 §7.5.1 names four types and leaves anything else to an // `OS.` fact. A fact is written even so, because a line with none at // all is a line that begins with a space, and a reader cannot tell // that from the space an `MLST` reply's own framing adds. .other => try w.writeAll("type=OS.unknown;"), } if (entry.size) |size| try w.print("size={d};", .{size}); if (entry.modified) |m| try w.print("modify={f};", .{time.timeval(m)}); if (entry.created) |c| try w.print("create={f};", .{time.timeval(c)}); if (entry.permissions) |p| try w.print("perm={f};", .{p}); if (entry.unique) |u| try w.print("unique={s};", .{u}); if (entry.unix.mode) |mode| try w.print("UNIX.mode={o:0>4};", .{mode}); if (entry.unix.owner) |owner| try w.print("UNIX.owner={s};", .{owner}); if (entry.unix.group) |group| try w.print("UNIX.group={s};", .{group}); try w.print(" {s}", .{entry.name}); } pub const ParseError = error{ /// The line is not in the format asked for. InvalidEntry, }; /// Reads one `MLSD` or `MLST` line. /// /// A leading space is skipped, because an `MLST` reply is a multi-line reply /// whose single entry is one of the middle lines and is indented by one. pub fn parseMachineEntry(line: []const u8) ParseError!Entry { // Exactly one leading space is removed, and only one: it is the indent an // `MLST` reply's middle line carries, and taking more would swallow the // empty facts section of an entry that has none. const without_indent = if (std.mem.startsWith(u8, line, " ")) line[1..] else line; const text = std.mem.trimEnd(u8, without_indent, "\r"); // A fact value may not contain a space (RFC 3659 §7.1), so the first one // ends the facts -- and the name, which may contain spaces, is everything // after it. const separator = std.mem.findScalar(u8, text, ' ') orelse return error.InvalidEntry; var entry: Entry = .{ .name = text[separator + 1 ..], .kind = .other }; if (entry.name.len == 0) return error.InvalidEntry; var facts = std.mem.splitScalar(u8, text[0..separator], ';'); while (facts.next()) |fact| { if (fact.len == 0) continue; const equals = std.mem.findScalar(u8, fact, '=') orelse continue; const name = fact[0..equals]; const value = fact[equals + 1 ..]; if (ascii.eqlIgnoreCase(name, "type")) { entry.kind = parseKind(value); if (entry.kind == .symlink) { // `OS.unix=slink:/some/target`, whose target is after the // first colon and may itself contain colons. if (std.mem.findScalar(u8, value, ':')) |colon| { entry.link_target = value[colon + 1 ..]; } } } else if (ascii.eqlIgnoreCase(name, "size")) { entry.size = std.fmt.parseInt(u64, value, 10) catch null; } else if (ascii.eqlIgnoreCase(name, "modify")) { entry.modified = time.parseTimeval(value) catch null; } else if (ascii.eqlIgnoreCase(name, "create")) { entry.created = time.parseTimeval(value) catch null; } else if (ascii.eqlIgnoreCase(name, "perm")) { entry.permissions = .parse(value); } else if (ascii.eqlIgnoreCase(name, "unique")) { entry.unique = value; } else if (ascii.eqlIgnoreCase(name, "UNIX.mode")) { entry.unix.mode = std.fmt.parseInt(u16, value, 8) catch null; } else if (ascii.eqlIgnoreCase(name, "UNIX.owner") or ascii.eqlIgnoreCase(name, "UNIX.uid")) { entry.unix.owner = value; } else if (ascii.eqlIgnoreCase(name, "UNIX.group") or ascii.eqlIgnoreCase(name, "UNIX.gid")) { entry.unix.group = value; } // Anything else -- lang, media-type, charset, and whatever a // particular server has added -- is skipped rather than refused. } return entry; } fn parseKind(value: []const u8) Kind { if (ascii.eqlIgnoreCase(value, "file")) return .file; if (ascii.eqlIgnoreCase(value, "dir")) return .dir; if (ascii.eqlIgnoreCase(value, "cdir")) return .current_dir; if (ascii.eqlIgnoreCase(value, "pdir")) return .parent_dir; // `OS.unix=slink`, `OS.unix=slink:target`, and the `OS.unix=symlink` a few // servers write instead. const os_prefix = "OS.unix="; if (value.len > os_prefix.len and ascii.eqlIgnoreCase(value[0..os_prefix.len], os_prefix)) { const rest = value[os_prefix.len..]; const kind = rest[0 .. std.mem.findScalar(u8, rest, ':') orelse rest.len]; if (ascii.eqlIgnoreCase(kind, "slink") or ascii.eqlIgnoreCase(kind, "symlink")) return .symlink; } return .other; } // -- LIST: the format that was never a format ----------------------------- /// How long ago a file has to have been modified before `ls` stops printing /// the time of day and prints the year instead. Six months, as `ls` has used /// since the 1970s, and the reason a `LIST` line's year has to be guessed. pub const recent_seconds = 180 * 24 * 60 * 60; const month_names = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; /// Writes one `LIST` line in the `ls -l` layout every client knows how to /// read. /// /// `now` is used only to decide whether the date column shows the time of day /// or the year, which is the rule `ls` follows and which clients' parsers /// expect. The timestamp itself is written in UTC — `ls` would use the /// server's local zone, but the format carries no zone at all, so a client can /// only guess, and UTC is the guess that agrees with `MDTM`. pub fn writeUnixEntry(w: *Io.Writer, entry: Entry, now: i64) Io.Writer.Error!void { try writeModeString(w, entry); try w.print(" {d:>3}", .{entry.unix.link_count orelse 1}); try w.print(" {s:<8}", .{entry.unix.owner orelse "ftp"}); try w.print(" {s:<8}", .{entry.unix.group orelse "ftp"}); try w.print(" {d:>12}", .{entry.size orelse 0}); try w.writeByte(' '); try writeListDate(w, entry.modified orelse now, now); try w.print(" {s}", .{entry.name}); // The arrow is what tells a client the name ends earlier than the line // does, and it is only meaningful when the mode string began with `l`. if (entry.kind == .symlink) { if (entry.link_target) |target| try w.print(" -> {s}", .{target}); } } fn writeModeString(w: *Io.Writer, entry: Entry) Io.Writer.Error!void { try w.writeByte(switch (entry.kind) { .dir, .current_dir, .parent_dir => 'd', .symlink => 'l', .file => '-', .other => '-', }); // A server that has real Unix permissions reports them; one that does not // synthesises a plausible set from what the client may actually do, since // a client reading this column is trying to answer that question anyway. const mode: u16 = entry.unix.mode orelse blk: { const p = entry.permissions orelse break :blk if (entry.kind.isDirectory()) @as(u16, 0o755) else @as(u16, 0o644); var m: u16 = 0; if (p.retrieve or p.list) m |= 0o444; if (p.store or p.append or p.create or p.make_dir) m |= 0o200; if (entry.kind.isDirectory() and p.enter) m |= 0o111; break :blk m; }; inline for (.{ 6, 3, 0 }) |shift| { const bits: u3 = @truncate(mode >> shift); try w.writeByte(if (bits & 0o4 != 0) 'r' else '-'); try w.writeByte(if (bits & 0o2 != 0) 'w' else '-'); try w.writeByte(if (bits & 0o1 != 0) 'x' else '-'); } } fn writeListDate(w: *Io.Writer, seconds: i64, now: i64) Io.Writer.Error!void { const dt: time.DateTime = .fromUnixSeconds(seconds); const month = month_names[@min(dt.month, 12) - 1]; // `ls` shows the time of day for something in the last six months and the // year for anything older -- including anything in the future, which is // what the second half of this comparison catches. if (seconds <= now and now - seconds < recent_seconds) { try w.print("{s} {d:>2} {d:0>2}:{d:0>2}", .{ month, dt.day, dt.hour, dt.minute }); } else { try w.print("{s} {d:>2} {d:>4}", .{ month, dt.day, @as(u16, @intCast(std.math.clamp(dt.year, 0, 9999))) }); } } pub const ParseOptions = struct { /// The current time, used to resolve the year of a date that gave only /// the time of day. Without it such an entry parses with no `modified` at /// all, which is better than a date in 1970. now: ?i64 = null, }; /// Reads one line of a `LIST` listing, in whichever of the two layouts it is. /// /// Returns `error.InvalidEntry` for a line that is neither — including the /// `total 42` header that `ls -l` prints, which is not an entry and which a /// caller should skip rather than treat as a failure. pub fn parseEntry(line: []const u8, options: ParseOptions) ParseError!Entry { return parseUnixEntry(line, options) catch parseDosEntry(line, options); } /// Reads one line in the `ls -l` layout: /// `-rw-r--r-- 1 owner group 1234 Jan 2 03:04 name`. pub fn parseUnixEntry(line: []const u8, options: ParseOptions) ParseError!Entry { const text = std.mem.trimEnd(u8, line, "\r\n"); if (text.len < 11) return error.InvalidEntry; const kind: Kind = switch (text[0]) { 'd' => .dir, 'l' => .symlink, '-' => .file, 'b', 'c', 'p', 's', 'D' => .other, else => return error.InvalidEntry, }; for (text[1..10]) |c| switch (c) { 'r', 'w', 'x', 's', 'S', 't', 'T', 'l', '-' => {}, else => return error.InvalidEntry, }; // The name may hold spaces, so the fields cannot simply be split: the // date is found first, and everything after it is the name. The date is // three fields -- month, day, time-or-year -- and the size is the field // before them. var fields: [8]Field = undefined; const found = tokenize(text, &fields); var date_at: usize = 0; while (date_at + 2 < found) : (date_at += 1) { if (date_at < 3) continue; if (monthNumber(fields[date_at].text) == null) continue; if (!isAllDigits(fields[date_at + 1].text)) continue; if (parseTimeOrYear(fields[date_at + 2].text) == null) continue; break; } else return error.InvalidEntry; var entry: Entry = .{ .name = std.mem.trimStart(u8, text[fields[date_at + 2].end..], " "), .kind = kind, .size = std.fmt.parseInt(u64, fields[date_at - 1].text, 10) catch null, .modified = resolveListDate( monthNumber(fields[date_at].text).?, std.fmt.parseInt(u5, fields[date_at + 1].text, 10) catch return error.InvalidEntry, parseTimeOrYear(fields[date_at + 2].text).?, options.now, ), .unix = .{ .mode = parseModeString(text[1..10]), .link_count = std.fmt.parseInt(u64, fields[1].text, 10) catch null, }, }; if (entry.name.len == 0) return error.InvalidEntry; // Between the link count and the size are the owner and the group -- or // just the owner, on the servers that omit one, or neither. switch (date_at - 1) { 4 => { entry.unix.owner = fields[2].text; entry.unix.group = fields[3].text; }, 3 => entry.unix.owner = fields[2].text, else => {}, } if (kind == .symlink) { if (std.mem.find(u8, entry.name, " -> ")) |arrow| { entry.link_target = entry.name[arrow + 4 ..]; entry.name = entry.name[0..arrow]; } } return entry; } /// Reads one line in the layout IIS and other DOS-descended servers use: /// `02-11-25 03:05PM folder`. pub fn parseDosEntry(line: []const u8, options: ParseOptions) ParseError!Entry { // The DOS layout always carries a full date, so unlike the Unix one it // never has to guess a year and never needs `options.now`. _ = options; const text = std.mem.trimEnd(u8, line, "\r\n"); var fields: [8]Field = undefined; const found = tokenize(text, &fields); if (found < 4) return error.InvalidEntry; const date = try parseDosDate(fields[0].text); const clock = try parseDosTime(fields[1].text); const size_field = fields[2].text; const is_dir = std.mem.eql(u8, size_field, "") or std.mem.eql(u8, size_field, ""); const name = std.mem.trimStart(u8, text[fields[2].end..], " "); if (name.len == 0) return error.InvalidEntry; return .{ .name = name, .kind = if (is_dir) .dir else .file, .size = if (is_dir) null else parseGroupedInt(size_field), .modified = (time.DateTime{ .year = date.year, .month = date.month, .day = date.day, .hour = clock.hour, .minute = clock.minute, .second = 0, }).toUnixSeconds(), // The DOS listing has no permission column at all, so nothing about // `unix` may be guessed at from it. `options` is taken for symmetry // with the Unix parser and because a future field may need it. .unix = .{}, }; } const Field = struct { text: []const u8, /// Where the field ends in the line, so that the name -- which may hold /// spaces and so cannot be a field -- can be taken as the remainder. end: usize, }; /// Splits on runs of spaces, filling at most `fields.len` of them and /// returning how many were found. fn tokenize(text: []const u8, fields: []Field) usize { var count: usize = 0; var i: usize = 0; while (i < text.len and count < fields.len) { while (i < text.len and text[i] == ' ') i += 1; if (i == text.len) break; const start = i; while (i < text.len and text[i] != ' ') i += 1; fields[count] = .{ .text = text[start..i], .end = i }; count += 1; } return count; } fn isAllDigits(text: []const u8) bool { if (text.len == 0) return false; for (text) |c| if (!ascii.isDigit(c)) return false; return true; } fn monthNumber(text: []const u8) ?u4 { if (text.len != 3) return null; for (month_names, 1..) |name, number| { if (ascii.eqlIgnoreCase(text, name)) return @intCast(number); } return null; } const TimeOrYear = union(enum) { /// `03:04`, which means this year or last year. clock: struct { hour: u5, minute: u6 }, /// `2024`, which means midnight on that date. year: i32, }; fn parseTimeOrYear(text: []const u8) ?TimeOrYear { if (std.mem.findScalar(u8, text, ':')) |colon| { const hour = std.fmt.parseInt(u5, text[0..colon], 10) catch return null; const minute = std.fmt.parseInt(u6, text[colon + 1 ..], 10) catch return null; if (hour > 23 or minute > 59) return null; return .{ .clock = .{ .hour = hour, .minute = minute } }; } if (text.len != 4 or !isAllDigits(text)) return null; return .{ .year = std.fmt.parseInt(i32, text, 10) catch return null }; } /// Turns the month, day and time-or-year of a `LIST` line into a timestamp. /// /// When the line gave a time of day it gave no year, and the year has to be /// guessed: `ls` prints the time only for the last six months, so the answer /// is this year unless that would be in the future, in which case it is last /// year. Without a `now` to compare against there is no guess to make, and the /// entry is better off with no timestamp than with a wrong one. fn resolveListDate(month: u4, day: u5, when: TimeOrYear, now: ?i64) ?i64 { switch (when) { .year => |year| return (time.DateTime{ .year = year, .month = month, .day = day, .hour = 0, .minute = 0, .second = 0, }).toUnixSeconds(), .clock => |clock| { const reference = now orelse return null; const this_year: time.DateTime = .fromUnixSeconds(reference); var candidate: time.DateTime = .{ .year = this_year.year, .month = month, .day = day, .hour = clock.hour, .minute = clock.minute, .second = 0, }; if (!candidate.isValid()) return null; var seconds = candidate.toUnixSeconds(); // A day of slack, because the server's clock and ours need not // agree and a file written a minute ago must not be dated a year // ago for it. if (seconds > reference + 24 * 60 * 60) { candidate.year -= 1; if (!candidate.isValid()) return null; seconds = candidate.toUnixSeconds(); } return seconds; }, } } fn parseModeString(text: []const u8) ?u16 { var mode: u16 = 0; for (text, 0..) |c, i| { const bit: u16 = @as(u16, 1) << @intCast(8 - i); switch (c) { '-' => {}, 'r', 'w', 'x' => mode |= bit, // setuid, setgid and sticky all imply the execute bit is set for // the lower case spelling and clear for the upper. 's', 't' => mode |= bit, 'S', 'T' => {}, else => return null, } } return mode; } fn parseDosDate(text: []const u8) ParseError!struct { year: i32, month: u4, day: u5 } { // `MM-DD-YY`, and occasionally `MM/DD/YY`. if (text.len != 8) return error.InvalidEntry; if ((text[2] != '-' and text[2] != '/') or text[2] != text[5]) return error.InvalidEntry; const month = std.fmt.parseInt(u4, text[0..2], 10) catch return error.InvalidEntry; const day = std.fmt.parseInt(u5, text[3..5], 10) catch return error.InvalidEntry; const short_year = std.fmt.parseInt(u8, text[6..8], 10) catch return error.InvalidEntry; // The DOS window: 70 to 99 are the twentieth century, 00 to 69 the // twenty-first. It is the convention every client uses and it will be // wrong in 2070. const year: i32 = if (short_year >= 70) 1900 + @as(i32, short_year) else 2000 + @as(i32, short_year); if (month < 1 or month > 12 or day < 1 or day > 31) return error.InvalidEntry; return .{ .year = year, .month = month, .day = day }; } fn parseDosTime(text: []const u8) ParseError!struct { hour: u5, minute: u6 } { // `HH:MMAM` or `HH:MMPM`, and a bare `HH:MM` from the servers that use a // 24-hour clock. const colon = std.mem.findScalar(u8, text, ':') orelse return error.InvalidEntry; var hour = std.fmt.parseInt(u5, text[0..colon], 10) catch return error.InvalidEntry; const rest = text[colon + 1 ..]; if (rest.len < 2) return error.InvalidEntry; const minute = std.fmt.parseInt(u6, rest[0..2], 10) catch return error.InvalidEntry; const suffix = rest[2..]; if (suffix.len == 2) { if (hour > 12) return error.InvalidEntry; if (ascii.eqlIgnoreCase(suffix, "PM")) { if (hour != 12) hour += 12; } else if (ascii.eqlIgnoreCase(suffix, "AM")) { if (hour == 12) hour = 0; } else return error.InvalidEntry; } else if (suffix.len != 0) return error.InvalidEntry; if (hour > 23 or minute > 59) return error.InvalidEntry; return .{ .hour = hour, .minute = minute }; } /// Reads a size that may have thousands separators in it, as IIS writes them. fn parseGroupedInt(text: []const u8) ?u64 { var value: u64 = 0; var digits: usize = 0; for (text) |c| { if (c == ',' or c == '.') continue; if (!ascii.isDigit(c)) return null; value = std.math.mul(u64, value, 10) catch return null; value = std.math.add(u64, value, c - '0') catch return null; digits += 1; } return if (digits == 0) null else value; } // -- tests ---------------------------------------------------------------- const testing = std.testing; /// 2025-06-15 12:00:00 UTC. The dates in a `LIST` line are read relative to a /// "test_now", so the tests need one that does not move. const test_now: i64 = 1750_000_000; fn expectMachine(entry: Entry, expected: []const u8) !void { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeMachineEntry(&w, entry); try testing.expectEqualStrings(expected, w.buffered()); } test "MLSD lines" { try expectMachine(.{ .name = "readme.txt", .kind = .file, .size = 1234, .modified = test_now, .permissions = .{ .retrieve = true, .delete = true }, }, "type=file;size=1234;modify=20250615150640;perm=dr; readme.txt"); try expectMachine(.{ .name = "pub", .kind = .dir, .permissions = .{ .enter = true, .list = true }, }, "type=dir;perm=el; pub"); try expectMachine(.{ .name = ".", .kind = .current_dir }, "type=cdir; ."); try expectMachine(.{ .name = "..", .kind = .parent_dir }, "type=pdir; .."); try expectMachine( .{ .name = "link", .kind = .symlink, .link_target = "/etc/passwd" }, "type=OS.unix=slink:/etc/passwd; link", ); try expectMachine( .{ .name = "f", .unix = .{ .mode = 0o644, .owner = "jeff", .group = "users" } }, "type=file;UNIX.mode=0644;UNIX.owner=jeff;UNIX.group=users; f", ); } test "MLSD round trip" { const entries = [_]Entry{ .{ .name = "readme.txt", .kind = .file, .size = 1234, .modified = test_now }, .{ .name = "name with spaces.txt", .kind = .file, .size = 0 }, .{ .name = "pub", .kind = .dir, .permissions = .{ .enter = true, .list = true, .make_dir = true } }, .{ .name = "link", .kind = .symlink, .link_target = "../target" }, .{ .name = "f", .kind = .file, .created = test_now, .unique = "AQkAAAAAAAABCAAA" }, }; for (entries) |entry| { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeMachineEntry(&w, entry); const parsed = try parseMachineEntry(w.buffered()); try testing.expectEqualStrings(entry.name, parsed.name); try testing.expectEqual(entry.kind, parsed.kind); try testing.expectEqual(entry.size, parsed.size); try testing.expectEqual(entry.modified, parsed.modified); try testing.expectEqual(entry.created, parsed.created); try testing.expectEqual(entry.permissions, parsed.permissions); if (entry.link_target) |target| try testing.expectEqualStrings(target, parsed.link_target.?); if (entry.unique) |unique| try testing.expectEqualStrings(unique, parsed.unique.?); } } test "MLSD lines from real servers" { // proftpd, which sends the facts in a different order and includes ones // this library does not model. const entry = try parseMachineEntry( "modify=20240102030405;perm=adfr;size=2048;type=file;unique=802g4e19f;UNIX.group=0;UNIX.mode=0644;UNIX.owner=0; welcome.msg", ); try testing.expectEqualStrings("welcome.msg", entry.name); try testing.expectEqual(Kind.file, entry.kind); try testing.expectEqual(@as(?u64, 2048), entry.size); try testing.expectEqual(@as(?i64, 1704164645), entry.modified); try testing.expectEqual(@as(?u16, 0o644), entry.unix.mode); try testing.expectEqualStrings("0", entry.unix.owner.?); const perm = entry.permissions.?; try testing.expect(perm.append and perm.delete and perm.rename and perm.retrieve); try testing.expect(!perm.store); } test "an MLST reply's entry is indented by the reply framing" { const entry = try parseMachineEntry(" type=file;size=1; readme.txt"); try testing.expectEqualStrings("readme.txt", entry.name); try testing.expectEqual(Kind.file, entry.kind); } test "an MLSD name may hold spaces and semicolons" { const entry = try parseMachineEntry("type=file;size=1; a;b c;d"); try testing.expectEqualStrings("a;b c;d", entry.name); } test "an MLSD line with facts this library does not know" { const entry = try parseMachineEntry("type=file;lang=en-US;media-type=text/plain;charset=UTF-8; x"); try testing.expectEqualStrings("x", entry.name); try testing.expectEqual(Kind.file, entry.kind); } test "an MLSD line with no facts at all still names a file" { // RFC 3659 §7.2 permits it, and a client still learns the name. const entry = try parseMachineEntry("; x"); try testing.expectEqualStrings("x", entry.name); try testing.expectEqual(Kind.other, entry.kind); // And with the facts section genuinely empty, which on an `MLST` line // means two leading spaces: one framing, one separator. const empty = try parseMachineEntry(" x"); try testing.expectEqualStrings("x", empty.name); } test "MLSD lines that are not entries" { try testing.expectError(error.InvalidEntry, parseMachineEntry("")); try testing.expectError(error.InvalidEntry, parseMachineEntry("type=file;size=1;")); try testing.expectError(error.InvalidEntry, parseMachineEntry("type=file;size=1; ")); } test "a fact whose value is nonsense leaves that field unset" { // A malformed size must not make the whole entry unreadable: the name is // still right, and a client can ask for the size with SIZE. const entry = try parseMachineEntry("type=file;size=banana;modify=nope; x"); try testing.expectEqualStrings("x", entry.name); try testing.expectEqual(@as(?u64, null), entry.size); try testing.expectEqual(@as(?i64, null), entry.modified); } test "perm letters" { var buffer: [16]u8 = undefined; const all: Permissions = .{ .append = true, .create = true, .delete = true, .enter = true, .rename = true, .list = true, .make_dir = true, .purge = true, .retrieve = true, .store = true, }; try testing.expectEqualStrings("acdeflmprw", try std.fmt.bufPrint(&buffer, "{f}", .{all})); try testing.expectEqual(all, Permissions.parse("acdeflmprw")); try testing.expectEqual(all, Permissions.parse("WRPMLFEDCA")); try testing.expectEqual(Permissions{}, Permissions.parse("")); // A letter nobody has defined is ignored rather than refused. try testing.expectEqual(Permissions{ .retrieve = true }, Permissions.parse("rz")); } fn expectUnixLine(entry: Entry, expected: []const u8) !void { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeUnixEntry(&w, entry, test_now); try testing.expectEqualStrings(expected, w.buffered()); } test "LIST lines in the ls layout" { try expectUnixLine(.{ .name = "readme.txt", .kind = .file, .size = 1234, .modified = test_now - 60, .unix = .{ .mode = 0o644, .owner = "jeff", .group = "users", .link_count = 1 }, }, "-rw-r--r-- 1 jeff users 1234 Jun 15 15:05 readme.txt"); // Older than six months, so the year replaces the time of day. try expectUnixLine(.{ .name = "pub", .kind = .dir, .size = 4096, .modified = 1600000000, .unix = .{ .mode = 0o755, .owner = "ftp", .group = "ftp", .link_count = 2 }, }, "drwxr-xr-x 2 ftp ftp 4096 Sep 13 2020 pub"); try expectUnixLine(.{ .name = "link", .kind = .symlink, .link_target = "/etc/passwd", .modified = test_now, .unix = .{ .mode = 0o777 }, }, "lrwxrwxrwx 1 ftp ftp 0 Jun 15 15:06 link -> /etc/passwd"); } test "LIST round trip" { const entries = [_]Entry{ .{ .name = "readme.txt", .kind = .file, .size = 1234, .modified = test_now - 60, .unix = .{ .mode = 0o644, .owner = "jeff", .group = "users", .link_count = 1 } }, .{ .name = "two words.txt", .kind = .file, .size = 0, .modified = 1600000000, .unix = .{ .mode = 0o600, .owner = "a", .group = "b", .link_count = 1 } }, .{ .name = "pub", .kind = .dir, .size = 4096, .modified = 1600000000, .unix = .{ .mode = 0o755, .owner = "ftp", .group = "ftp", .link_count = 2 } }, .{ .name = "link", .kind = .symlink, .size = 11, .link_target = "/etc/passwd", .modified = 1600000000, .unix = .{ .mode = 0o777, .owner = "r", .group = "r", .link_count = 1 } }, }; for (entries) |entry| { var buffer: [256]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeUnixEntry(&w, entry, test_now); const parsed = try parseEntry(w.buffered(), .{ .now = test_now }); try testing.expectEqualStrings(entry.name, parsed.name); try testing.expectEqual(entry.kind, parsed.kind); try testing.expectEqual(entry.size, parsed.size); try testing.expectEqual(entry.unix.mode, parsed.unix.mode); try testing.expectEqualStrings(entry.unix.owner.?, parsed.unix.owner.?); try testing.expectEqualStrings(entry.unix.group.?, parsed.unix.group.?); if (entry.link_target) |target| try testing.expectEqualStrings(target, parsed.link_target.?); // What survives depends on which date column `ls` chose: a recent // file keeps its time of day but not its seconds, and an old one // keeps only its date, because that is all the column holds. const recent = entry.modified.? > test_now - recent_seconds; const granularity: i64 = if (recent) 60 else 24 * 60 * 60; try testing.expectEqual( @divFloor(entry.modified.?, granularity) * granularity, parsed.modified.?, ); } } test "LIST lines from real servers" { const entry = try parseEntry( "-rw-r--r-- 1 0 0 2048 Jan 02 2024 welcome.msg", .{ .now = test_now }, ); try testing.expectEqualStrings("welcome.msg", entry.name); try testing.expectEqual(Kind.file, entry.kind); try testing.expectEqual(@as(?u64, 2048), entry.size); try testing.expectEqual(@as(?u64, 1), entry.unix.link_count); try testing.expectEqualStrings("0", entry.unix.owner.?); try testing.expectEqual(@as(?i64, 1704153600), entry.modified); } test "LIST lines whose names hold spaces" { const entry = try parseEntry( "-rw-r--r-- 1 jeff users 1234 Jun 15 15:05 two spaces.txt", .{ .now = test_now }, ); try testing.expectEqualStrings("two spaces.txt", entry.name); } test "LIST lines with no group column" { const entry = try parseEntry( "-rw-r--r-- 1 jeff 1234 Jun 15 15:05 x", .{ .now = test_now }, ); try testing.expectEqualStrings("x", entry.name); try testing.expectEqual(@as(?u64, 1234), entry.size); try testing.expectEqualStrings("jeff", entry.unix.owner.?); try testing.expectEqual(@as(?[]const u8, null), entry.unix.group); } test "LIST symbolic links" { const entry = try parseEntry( "lrwxrwxrwx 1 root root 11 Jan 02 2024 passwd -> /etc/passwd", .{ .now = test_now }, ); try testing.expectEqual(Kind.symlink, entry.kind); try testing.expectEqualStrings("passwd", entry.name); try testing.expectEqualStrings("/etc/passwd", entry.link_target.?); } test "a LIST date with no year is placed in the past, never the future" { // December, read in June: last December, not this one, which has not // happened yet. const december = try parseEntry( "-rw-r--r-- 1 a b 1 Dec 25 09:00 x", .{ .now = test_now }, ); try testing.expect(december.modified.? < test_now); try testing.expectEqual(@as(i32, 2024), time.DateTime.fromUnixSeconds(december.modified.?).year); // March, read in June: this March. const march = try parseEntry( "-rw-r--r-- 1 a b 1 Mar 25 09:00 x", .{ .now = test_now }, ); try testing.expectEqual(@as(i32, 2025), time.DateTime.fromUnixSeconds(march.modified.?).year); } test "a LIST date with no year and no clock to compare it to" { const entry = try parseEntry("-rw-r--r-- 1 a b 1 Dec 25 09:00 x", .{}); try testing.expectEqualStrings("x", entry.name); try testing.expectEqual(@as(?i64, null), entry.modified); } test "the setuid and sticky bits in a mode column" { const entry = try parseEntry( "-rwsr-xr-t 1 root root 1234 Jan 02 2024 x", .{ .now = test_now }, ); try testing.expectEqual(@as(?u16, 0o755), entry.unix.mode); const off = try parseEntry( "-rwSr-xr-T 1 root root 1234 Jan 02 2024 x", .{ .now = test_now }, ); try testing.expectEqual(@as(?u16, 0o654), off.unix.mode); } test "lines that are not LIST entries" { // The header ls prints above the listing. try testing.expectError(error.InvalidEntry, parseEntry("total 12", .{ .now = test_now })); try testing.expectError(error.InvalidEntry, parseEntry("", .{ .now = test_now })); try testing.expectError(error.InvalidEntry, parseEntry("-rw-r--r--", .{ .now = test_now })); try testing.expectError(error.InvalidEntry, parseEntry("?rw-r--r-- 1 a b 1 Jan 2 03:04 x", .{ .now = test_now })); // A mode column with a character that is not a permission. try testing.expectError(error.InvalidEntry, parseEntry("-rw-r--r?- 1 a b 1 Jan 2 03:04 x", .{ .now = test_now })); // No name after the date. try testing.expectError(error.InvalidEntry, parseEntry("-rw-r--r-- 1 a b 1 Jan 2 03:04 ", .{ .now = test_now })); } test "LIST lines in the DOS layout" { const dir = try parseEntry("02-11-25 03:05PM folder", .{ .now = test_now }); try testing.expectEqualStrings("folder", dir.name); try testing.expectEqual(Kind.dir, dir.kind); try testing.expectEqual(@as(?u64, null), dir.size); try testing.expectEqual( time.DateTime{ .year = 2025, .month = 2, .day = 11, .hour = 15, .minute = 5, .second = 0 }, time.DateTime.fromUnixSeconds(dir.modified.?), ); const file = try parseEntry("02-11-25 03:05AM 1,234 file.txt", .{ .now = test_now }); try testing.expectEqualStrings("file.txt", file.name); try testing.expectEqual(Kind.file, file.kind); try testing.expectEqual(@as(?u64, 1234), file.size); try testing.expectEqual(@as(u5, 3), time.DateTime.fromUnixSeconds(file.modified.?).hour); } test "DOS midnight and noon" { const midnight = try parseEntry("01-01-25 12:00AM 1 x", .{ .now = test_now }); try testing.expectEqual(@as(u5, 0), time.DateTime.fromUnixSeconds(midnight.modified.?).hour); const noon = try parseEntry("01-01-25 12:00PM 1 x", .{ .now = test_now }); try testing.expectEqual(@as(u5, 12), time.DateTime.fromUnixSeconds(noon.modified.?).hour); } test "the DOS two-digit year window" { const nineties = try parseEntry("01-01-99 12:00PM 1 x", .{ .now = test_now }); try testing.expectEqual(@as(i32, 1999), time.DateTime.fromUnixSeconds(nineties.modified.?).year); const twenties = try parseEntry("01-01-25 12:00PM 1 x", .{ .now = test_now }); try testing.expectEqual(@as(i32, 2025), time.DateTime.fromUnixSeconds(twenties.modified.?).year); } test "DOS lines that are not entries" { try testing.expectError(error.InvalidEntry, parseEntry("02-11-25", .{ .now = test_now })); try testing.expectError(error.InvalidEntry, parseEntry("02-11-25 25:00PM 1 x", .{ .now = test_now })); try testing.expectError(error.InvalidEntry, parseEntry("13-11-25 03:05PM 1 x", .{ .now = test_now })); try testing.expectError(error.InvalidEntry, parseEntry("02-11-25 03:05XM 1 x", .{ .now = test_now })); } test "self and parent" { try testing.expect((Entry{ .name = ".", .kind = .current_dir }).isSelfOrParent()); try testing.expect((Entry{ .name = "..", .kind = .dir }).isSelfOrParent()); try testing.expect(!(Entry{ .name = "...", .kind = .dir }).isSelfOrParent()); } test { _ = time; }