// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A reply on the control connection: a three-digit code and the human text //! that came with it. //! //! RFC 959 §4.2 gives a reply one of two shapes. A single line is the code, a //! space and the text. Several lines are the code, a hyphen and the first //! line, then any number of lines of anything at all, then the same code, a //! space and the last line. Nothing marks the middle lines as belonging to the //! reply, so the *only* way to find the end is to look for the code again with //! a space after it — which is why a middle line whose own text starts with //! three digits has to be padded, and why `write` does that padding. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const Code = @import("Code.zig"); const Reply = @This(); code: Code, /// Every line of the reply, joined by `\n`, with the framing removed: the /// code and its separator are gone from the first and last lines, and the /// space that padded an ambiguous middle line is gone from that line. /// /// Borrows from the buffer it was read into, so it does not outlive the next /// call that reuses that buffer. text: []const u8, /// Whether the command was accepted; see `Code.Severity.isPositive`. pub fn isPositive(r: Reply) bool { return r.code.isPositive(); } /// The first line of `text`, which for a multi-line reply is the summary the /// rest elaborates on, and for a single-line reply is all of it. pub fn firstLine(r: Reply) []const u8 { return r.text[0 .. std.mem.findScalar(u8, r.text, '\n') orelse r.text.len]; } /// A reply is at most this many bytes by default. Nothing in the protocol /// bounds the length of a multi-line reply, so a client that does not impose /// its own bound can be made to allocate without limit by a hostile server. /// `HELP` and `FEAT` are the long ones and neither comes near this. pub const default_max_len = 64 * 1024; /// The framing of one physical line, which is what tells a reader whether the /// reply has ended. pub const Framing = enum { /// `NNN text`: this line ends the reply. last, /// `NNN-text`: the reply continues. more, }; /// The `NNN-` or `NNN ` at the head of a line. pub const Header = struct { code: Code, framing: Framing, /// What followed the separator. text: []const u8, }; pub const ParseHeaderError = error{ /// The line does not begin with three digits followed by a space or a /// hyphen, so it is not the first or last line of a reply. NotAHeader, }; /// Reads the `NNN-` or `NNN ` framing from the front of a line, if it is /// there. `line` must already have had its line terminator removed. /// /// A bare three-digit line with nothing after it is accepted as a final line /// with empty text: it is not what RFC 959 asks for, since the space is /// mandatory, but servers send it and refusing it gains nothing. pub fn parseHeader(line: []const u8) ParseHeaderError!Header { if (line.len < 3) return error.NotAHeader; var value: u16 = 0; for (line[0..3]) |c| { if (c < '0' or c > '9') return error.NotAHeader; value = value * 10 + (c - '0'); } const code: Code = .{ .value = value }; if (line.len == 3) return .{ .code = code, .framing = .last, .text = "" }; return switch (line[3]) { ' ' => .{ .code = code, .framing = .last, .text = line[4..] }, '-' => .{ .code = code, .framing = .more, .text = line[4..] }, else => error.NotAHeader, }; } pub const ReceiveError = error{ /// The first line of the reply was not `NNN ` or `NNN-`. The peer is /// either not speaking FTP or has lost sync with us. InvalidReply, /// The reply ran past `max_len`, or a multi-line reply never terminated. ReplyTooLong, /// A single line was longer than the reader's buffer. Give the control /// connection a bigger one; `min_control_buffer_len` is the floor. StreamTooLong, /// The connection closed in the middle of a reply. EndOfStream, ReadFailed, OutOfMemory, }; pub const ReceiveOptions = struct { max_len: usize = default_max_len, }; /// The smallest control-connection read buffer worth using. RFC 959 §4.2 /// bounds nothing about reply length, but the reader must hold one whole line /// at a time, and 512 is the bound the same document puts on a *command* — so /// a server that answers in kind fits. Real servers stay well inside it except /// for `HELP`, which is multi-line anyway. pub const min_control_buffer_len = 512; /// Reads one complete reply, gathering its text into `buffer`. /// /// `buffer` is cleared first and the returned `Reply` borrows from it, so it /// stays valid exactly as long as `buffer` is left alone. Passing the same /// list to every call is the intended use: the reply text is the only thing /// that needs to outlive the read, and reusing the list means a session /// allocates once rather than once per command. pub fn receive( r: *Io.Reader, gpa: Allocator, buffer: *std.ArrayList(u8), options: ReceiveOptions, ) ReceiveError!Reply { buffer.clearRetainingCapacity(); const first = try takeLine(r); const header = parseHeader(first) catch return error.InvalidReply; try append(gpa, buffer, header.text, options.max_len); if (header.framing == .last) return .{ .code = header.code, .text = buffer.items }; while (true) { const line = try takeLine(r); // A middle line is anything that is not this reply's code followed by // a space. Checking the code as well as the shape matters: a server // may quote another reply inside its own, and only its own code ends // it. if (parseHeader(line)) |h| { if (h.framing == .last and h.code.value == header.code.value) { try append(gpa, buffer, "\n", options.max_len); try append(gpa, buffer, h.text, options.max_len); return .{ .code = header.code, .text = buffer.items }; } } else |_| {} try append(gpa, buffer, "\n", options.max_len); // Undo the padding `write` and every other server adds to a line that // would otherwise have looked like a terminator. Only a leading space // before three digits can have been padding; a line that is merely // indented, as `FEAT` indents its feature names, is left alone. try append(gpa, buffer, unpad(line), options.max_len); } } /// Reads one line and strips its terminator. RFC 959 says CRLF; a bare LF is /// accepted because servers send it and there is nothing to gain by refusing. /// /// *Every* trailing CR goes, not just the one the terminator needs. A reply's /// text is a sentence for a person to read and a CR at the end of it means /// nothing, so `211 End\r\r\n` says "End" — and taking only one would leave a /// CR in the text that `write` then drops, which would make the codec lossy in /// one direction and not the other. A fuzz round trip found that. fn takeLine(r: *Io.Reader) ReceiveError![]const u8 { const line = r.takeDelimiterInclusive('\n') catch |err| switch (err) { // The distinction matters to a caller: too long is a buffer that // needs growing, end of stream is a connection that has gone. error.StreamTooLong => return error.StreamTooLong, error.EndOfStream => return error.EndOfStream, error.ReadFailed => return error.ReadFailed, }; return std.mem.trimEnd(u8, line[0 .. line.len - 1], "\r"); } fn unpad(line: []const u8) []const u8 { if (line.len < 4 or line[0] != ' ') return line; for (line[1..4]) |c| if (c < '0' or c > '9') return line; return line[1..]; } fn append(gpa: Allocator, buffer: *std.ArrayList(u8), bytes: []const u8, max_len: usize) ReceiveError!void { if (buffer.items.len + bytes.len > max_len) return error.ReplyTooLong; try buffer.appendSlice(gpa, bytes); } /// Writes a reply, framing it as RFC 959 requires. /// /// A `text` with no newline in it becomes a single line. A `text` with /// newlines becomes a multi-line reply, and any middle line that would have /// been mistaken for the terminator is padded with a space, which `receive` /// takes back off at the other end. /// /// This is also what makes the reply text safe to build out of a path or a /// user name: a newline someone smuggled into a filename becomes another line /// *of this reply*, never the start of a second one, so no client can be told /// it is logged in by a file called "evil\r\n230 ok". pub fn write(w: *Io.Writer, code: Code, text: []const u8) Io.Writer.Error!void { // `text` is allowed to arrive with CRLF in it -- a caller passing through // something read from elsewhere should not have to normalise first -- so // split on LF and drop a CR that was only there as half of a pair. var lines = std.mem.splitScalar(u8, text, '\n'); var line = lines.first(); var first = true; while (lines.next()) |next| { const body = chomp(line); if (first) { try w.print("{f}-{s}\r\n", .{ code, body }); first = false; } else { // Pad anything a reader would take for the end of the reply. It // costs a byte and removes the whole class of servers that // truncate a reply because someone's error message began with a // number. if (parseHeader(body)) |_| try w.writeByte(' ') else |_| {} try w.print("{s}\r\n", .{body}); } line = next; } try w.print("{f} {s}\r\n", .{ code, chomp(line) }); } /// How much formatted text `print` can hold. Longer text is truncated with an /// ellipsis rather than allocated for: a reply is a sentence for a person to /// read, and the one caller that produces long replies -- `FEAT` -- builds its /// text itself and passes it to `write`. pub const print_buffer_len = 1024; /// Writes a reply whose text comes from a format string. /// /// The text is built on the stack first, because `write` has to see all of it /// to frame it, and is truncated to `print_buffer_len` bytes. Truncation /// cannot corrupt the framing: whatever survives is still framed by `write`. pub fn print(w: *Io.Writer, code: Code, comptime fmt: []const u8, args: anytype) Io.Writer.Error!void { var buffer: [print_buffer_len]u8 = undefined; var text: Io.Writer = .fixed(&buffer); const ellipsis = "..."; text.print(fmt, args) catch { // `Writer.fixed` fails only by running out of room, and it leaves // everything that did fit behind. const kept = @min(text.buffered().len, buffer.len - ellipsis.len); @memcpy(buffer[kept..][0..ellipsis.len], ellipsis); return write(w, code, buffer[0 .. kept + ellipsis.len]); }; return write(w, code, text.buffered()); } fn chomp(line: []const u8) []const u8 { return if (std.mem.endsWith(u8, line, "\r")) line[0 .. line.len - 1] else line; } // -- tests ---------------------------------------------------------------- const testing = std.testing; fn expectReceive(wire: []const u8, expected_code: u16, expected_text: []const u8) !void { var reader: Io.Reader = .fixed(wire); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(testing.allocator); const reply = try receive(&reader, testing.allocator, &buffer, .{}); try testing.expectEqual(expected_code, reply.code.value); try testing.expectEqualStrings(expected_text, reply.text); } test "single line" { try expectReceive("220 ready\r\n", 220, "ready"); } test "bare LF is accepted" { try expectReceive("220 ready\n", 220, "ready"); } test "a run of carriage returns before the terminator is all terminator" { // Nothing sends this, but the codec has to be total either way: taking // only one CR leaves the text ending in a CR that `write` then drops, so // a reply passed through would not come out as it went in. try expectReceive("220 ready\r\r\n", 220, "ready"); try expectReceive("211-one\r\r\ntwo\r\r\n211 End\r\r\n", 211, "one\ntwo\nEnd"); } test "three digits and nothing else" { try expectReceive("226\r\n", 226, ""); } test "multi-line" { try expectReceive( "211-Features:\r\n MDTM\r\n SIZE\r\n211 End\r\n", 211, "Features:\n MDTM\n SIZE\nEnd", ); } test "a middle line holding another code does not end the reply" { // The 500 here is quoted inside a 211, and a reader that looked only for // "three digits and a space" would stop at it and leave the rest of the // reply in the stream, desynchronising every command after this one. try expectReceive( "211-Status:\r\n500 was the last error\r\n211 End\r\n", 211, "Status:\n500 was the last error\nEnd", ); } test "padding of an ambiguous middle line is removed" { try expectReceive( "211-Status:\r\n 211 was the last reply\r\n211 End\r\n", 211, "Status:\n211 was the last reply\nEnd", ); } test "an indented line that is not padding is left alone" { // FEAT indents its feature names, and none of them start with digits, so // none of that indentation may be taken for padding. try expectReceive("211-Features:\r\n MLST\r\n211 End\r\n", 211, "Features:\n MLST\nEnd"); } test "truncated reply" { var reader: Io.Reader = .fixed("220 ready"); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(testing.allocator); try testing.expectError(error.EndOfStream, receive(&reader, testing.allocator, &buffer, .{})); } test "unterminated multi-line reply" { var reader: Io.Reader = .fixed("211-one\r\ntwo\r\n"); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(testing.allocator); try testing.expectError(error.EndOfStream, receive(&reader, testing.allocator, &buffer, .{})); } test "a reply longer than max_len is refused rather than allocated" { var reader: Io.Reader = .fixed("211-one\r\ntwo\r\nthree\r\n211 end\r\n"); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(testing.allocator); try testing.expectError( error.ReplyTooLong, receive(&reader, testing.allocator, &buffer, .{ .max_len = 8 }), ); } test "garbage is not a reply" { var reader: Io.Reader = .fixed("\r\n"); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(testing.allocator); try testing.expectError(error.InvalidReply, receive(&reader, testing.allocator, &buffer, .{})); } fn expectWrite(code: Code, text: []const u8, expected: []const u8) !void { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try write(&w, code, text); try testing.expectEqualStrings(expected, w.buffered()); } test "write single line" { try expectWrite(.service_ready, "ready", "220 ready\r\n"); } test "write multi-line" { try expectWrite( .system_status, "Features:\n MDTM\nEnd", "211-Features:\r\n MDTM\r\n211 End\r\n", ); } test "write pads an ambiguous middle line" { try expectWrite( .system_status, "Status:\n211 was the last reply\nEnd", "211-Status:\r\n 211 was the last reply\r\n211 End\r\n", ); } test "write accepts text that already has CRLF in it" { try expectWrite(.system_status, "one\r\ntwo", "211-one\r\n211 two\r\n"); } test "round trip" { const cases = [_]struct { Code, []const u8 }{ .{ .service_ready, "zig-ftp ready" }, .{ .system_status, "Features:\n MDTM\n SIZE\n UTF8\nEnd" }, .{ .file_unavailable, "550 is what this line starts with" }, .{ .help_message, "" }, .{ .system_status, "a\nb\nc\nd\ne" }, }; for (cases) |case| { const code, const text = case; var wire: [512]u8 = undefined; var w: Io.Writer = .fixed(&wire); try write(&w, code, text); var reader: Io.Reader = .fixed(w.buffered()); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(testing.allocator); const reply = try receive(&reader, testing.allocator, &buffer, .{}); try testing.expectEqual(code.value, reply.code.value); try testing.expectEqualStrings(text, reply.text); } } test "firstLine" { const reply: Reply = .{ .code = .system_status, .text = "Features:\n MDTM\nEnd" }; try testing.expectEqualStrings("Features:", reply.firstLine()); const single: Reply = .{ .code = .service_ready, .text = "ready" }; try testing.expectEqualStrings("ready", single.firstLine()); }