Something went wrong. Try again.
FTP for Zig 0.16: a client, a server, and the wire protocol as a layer you can use on its own, all built on std.Io.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A command on the control connection: a verb and at most one argument.//!//! RFC 959 §5.3 makes this simpler than it looks. A command is a verb, then —//! if the verb takes one — a single space and everything up to the CRLF. There//! is no quoting and no escaping, so the argument is whatever bytes lie//! between that space and the end of the line, spaces and all. A file called//! `two spaces ` is retrieved by `RETR two spaces ` and nothing else.
const std = @import("std");const Io = std.Io;const ascii = std.ascii;
const Command = @This();
/// The verb, if it is one this library knows. A server answers `null` with a/// 500; a proxy or a logger may still want `name`.verb: ?Verb,/// The verb exactly as it arrived, before case folding. Borrows from the/// buffer the command was read into.name: []const u8,/// Everything after the single space that separates the verb from its/// argument, or `null` when the line held no space at all.////// The distinction matters: `CWD` with no argument is a syntax error, while/// `CWD ` names the empty path, and only the presence of the space tells them/// apart. Borrows from the buffer the command was read into.arg: ?[]const u8,
/// The verbs this library knows, from RFC 959 and the extensions in common/// use. The names are the wire spellings lowercased; `Verb.name` gives the/// spelling back.pub const Verb = enum { // -- access control (RFC 959 §4.1.1) -- /// The user name to log in as. Begins every session. user, /// The password for the name given by `user`. pass, /// The account to charge, for the few servers that have such a notion. acct, /// Change working directory. cwd, /// Change to the parent directory. Takes no argument, which is the only /// reason it exists alongside `CWD ..`. cdup, /// Mount a different file system data structure. smnt, /// Reinitialise: end the current login without dropping the connection. rein, /// End the session. quit,
// -- transfer parameters (RFC 959 §4.1.2) -- /// The address the server should connect to for data: active mode. port, /// Ask the server for an address to connect to for data: passive mode. pasv, /// The representation type: `A` for ASCII, `I` for image (binary). type, /// File structure. Only `F`, unstructured, is worth supporting. stru, /// Transfer mode. Only `S`, stream, is worth supporting. mode,
// -- service (RFC 959 §4.1.3) -- /// Send a file to the client. retr, /// Receive a file from the client. stor, /// Receive a file, under a name the server picks and reports. stou, /// Receive a file, appending if it exists. appe, /// Reserve space for what is about to be stored. Advisory, and almost /// always answered with a 202. allo, /// The offset the next transfer restarts at. rest, /// The name to rename from; `rnto` follows. rnfr, /// The name to rename to; follows `rnfr`. rnto, /// Abort the transfer in progress. abor, /// Delete a file. dele, /// Remove a directory. rmd, /// Create a directory. mkd, /// Report the working directory. pwd, /// A human-readable directory listing, over the data connection. list, /// A bare list of names, over the data connection. nlst, /// A site-specific command. `SITE CHMOD` is the common one. site, /// Report the server's operating system. syst, /// Status: of the server, of a transfer in progress, or of a path — and /// unusually, the last of those answers on the *control* connection. stat, /// Help. help, /// Do nothing, successfully. What a client sends to keep a session alive. noop,
// -- extensions -- /// The features the server supports (RFC 2389). feat, /// Set an option for another command; `OPTS UTF8 ON` (RFC 2389). opts, /// Active mode over any address family (RFC 2428). eprt, /// Passive mode over any address family (RFC 2428). epsv, /// The modification time of a file (RFC 3659). mdtm, /// The size of a file, in the current representation type (RFC 3659). size, /// Machine-readable facts about one path, on the control connection /// (RFC 3659). mlst, /// Machine-readable facts about a directory's contents, over the data /// connection (RFC 3659). What `LIST` should have been. mlsd, /// Active mode with long addresses (RFC 1639). Superseded by `EPRT`. lprt, /// Passive mode with long addresses (RFC 1639). Superseded by `EPSV`. lpsv, /// The language of the server's replies (RFC 2640). lang, /// Begin a security mechanism; `AUTH TLS` (RFC 2228, RFC 4217). auth, /// Security data, base 64 encoded (RFC 2228). adat, /// The protection buffer size; always `0` for TLS (RFC 2228, RFC 4217). pbsz, /// The data channel protection level; `C` clear or `P` private /// (RFC 2228, RFC 4217). prot, /// Clear the command channel (RFC 2228). ccc,
// -- the X-prefixed originals -- // // These predate RFC 959 and are the same commands under older names. A // few clients still send them, and answering them costs an alias. /// `PWD` under its older name. xpwd, /// `CWD` under its older name. xcwd, /// `CDUP` under its older name. xcup, /// `MKD` under its older name. xmkd, /// `RMD` under its older name. xrmd,
/// The wire spelling: the enum name in upper case. pub fn name(v: Verb) []const u8 { return switch (v) { inline else => |tag| comptime blk: { var upper: [@tagName(tag).len]u8 = undefined; for (@tagName(tag), &upper) |c, *u| u.* = ascii.toUpper(c); const frozen = upper; break :blk &frozen; }, }; }
/// The command this is an older name for, or the verb itself. pub fn canonical(v: Verb) Verb { return switch (v) { .xpwd => .pwd, .xcwd => .cwd, .xcup => .cdup, .xmkd => .mkd, .xrmd => .rmd, else => v, }; }
/// Whether a server must refuse this command with a 530 before the client /// has logged in. RFC 959 does not say in so many words; this is the set /// every server agrees on, being the commands needed to *reach* a login, /// to negotiate security before one, and to leave. pub fn requiresLogin(v: Verb) bool { return switch (v.canonical()) { .user, .pass, .acct, .quit, .feat, .opts, .auth, .adat, .pbsz, .prot, .ccc, .noop, .syst, .help => false, else => true, }; }
/// Whether the command's reply travels over a data connection rather than /// the control connection. `STAT` is deliberately absent: given a path it /// produces a listing, but on the control connection, which is the whole /// point of it. pub fn usesDataConnection(v: Verb) bool { return switch (v.canonical()) { .retr, .stor, .stou, .appe, .list, .nlst, .mlsd => true, else => false, }; }
const table = blk: { const values = @typeInfo(Verb).@"enum".field_values; var entries: [values.len]struct { []const u8, Verb } = undefined; for (values, &entries) |value, *entry| { const v: Verb = @fromBackingInt(value); entry.* = .{ v.name(), v }; } const frozen = entries; break :blk std.StaticStringMap(Verb).initComptime(frozen); };
/// Looks up a verb by its wire spelling, in any case. pub fn fromName(text: []const u8) ?Verb { if (text.len > max_verb_len) return null; var upper: [max_verb_len]u8 = undefined; for (text, upper[0..text.len]) |c, *u| u.* = ascii.toUpper(c); return table.get(upper[0..text.len]); }};
/// The longest verb this library knows, which bounds the case-folding buffer/// `Verb.fromName` needs. Every verb in RFC 959 is four characters; the/// extensions have kept to it.pub const max_verb_len = blk: { var longest: usize = 0; for (@typeInfo(Verb).@"enum".field_names) |name| longest = @max(longest, name.len); break :blk longest;};
/// RFC 959 §4.2 bounds a command line, terminator included, at 512 bytes. It/// is a bound worth *sending* within and not worth enforcing on receipt: paths/// longer than 500 bytes exist, and a server that refuses them for the letter/// of a 40-year-old limit is simply a server that cannot serve those files. A/// server bounds what it accepts by the size of the buffer it reads into.pub const rfc959_max_line_len = 512;
pub const ParseError = error{ /// The line was empty, or the verb held something that is not a letter or /// a digit. Either way there is no command here to answer. InvalidCommand,};
/// Splits a command line into a verb and its argument. `line` must already/// have had its line terminator removed and its TELNET escapes undone; see/// `receive`, which does both.pub fn parse(line: []const u8) ParseError!Command { const end = std.mem.findScalar(u8, line, ' ') orelse line.len; const name = line[0..end]; if (name.len == 0) return error.InvalidCommand; for (name) |c| if (!ascii.isAlphanumeric(c)) return error.InvalidCommand; return .{ .verb = Verb.fromName(name), .name = name, // Exactly one space separates the verb from the argument. A second // space belongs to the argument, because a file may be named with one. .arg = if (end == line.len) null else line[end + 1 ..], };}
/// The argument, or `error.MissingArgument` if there was none. Most commands/// want this rather than `arg`, since the reply to a missing argument and to/// an unusable one is the same 501.pub fn requireArg(c: Command) error{MissingArgument}![]const u8 { return c.arg orelse error.MissingArgument;}
pub const ReceiveError = error{ InvalidCommand, /// The line was longer than the reader's buffer. StreamTooLong, /// The connection closed between commands, which is how a client that /// forgot to send `QUIT` leaves, or mid-line, which is not. EndOfStream, ReadFailed,};
/// Reads one command line and parses it.////// The returned `Command` borrows from the reader's buffer, so it is good/// until the next read from `r` and no longer. A server that wants to keep an/// argument — the pathname of `RNFR`, say — must copy it.pub fn receive(r: *Io.Reader) ReceiveError!Command { const raw = r.takeDelimiterInclusive('\n') catch |err| switch (err) { error.StreamTooLong => return error.StreamTooLong, error.EndOfStream => return error.EndOfStream, error.ReadFailed => return error.ReadFailed, }; const without_lf = raw[0 .. raw.len - 1]; const line = if (std.mem.endsWith(u8, without_lf, "\r")) without_lf[0 .. without_lf.len - 1] else without_lf; return parse(stripTelnet(line));}
/// The TELNET escape byte, which the control connection inherits from being a/// TELNET connection in RFC 959's telling.pub const iac = 0xff;
/// Removes TELNET command sequences from a line, in place, and returns what is/// left of it.////// The control connection is nominally a TELNET connection, and the one place/// that still shows is `ABOR`: RFC 959 §4.1.3 has the client precede it with/// `IAC IP` and `IAC DM`, so a server that does not skip those sees a command/// beginning with two 0xFF bytes and answers 500 to the one command that must/// not be ignored. Real clients also send option negotiation this way.////// Only the in-band part is handled. The Synch that accompanies `ABOR` is sent/// as urgent data, which a stream reader never sees separately; skipping it/// here is enough in practice because the `ABOR` itself arrives in band.pub fn stripTelnet(line: []u8) []u8 { if (std.mem.findScalar(u8, line, iac) == null) return line; var out: usize = 0; var i: usize = 0; while (i < line.len) { if (line[i] != iac) { line[out] = line[i]; out += 1; i += 1; continue; } // A trailing IAC with nothing after it is malformed; drop it. if (i + 1 >= line.len) break; switch (line[i + 1]) { // IAC IAC is a literal 0xFF in the data. iac => { line[out] = iac; out += 1; i += 2; }, // WILL, WONT, DO, DONT each take an option byte. 0xfb, 0xfc, 0xfd, 0xfe => i += @min(3, line.len - i), // Everything else -- IP, DM, AYT, and the rest -- is two bytes. else => i += 2, } } return line[0..out];}
pub const WriteError = error{ /// The argument held a CR, an LF or a NUL. Writing it would let the /// argument end the command line and start another one, so a path that /// came from somewhere untrusted could send any command it liked. InvalidArgument,} || Io.Writer.Error;
/// Writes a command line.pub fn write(w: *Io.Writer, verb: Verb, arg: ?[]const u8) WriteError!void { return writeName(w, verb.name(), arg);}
/// Writes a command line for a verb this library does not know, which is how/// a caller reaches a `SITE` subcommand's cousins and anything else a/// particular server has invented.////// A 0xFF byte in the argument is written twice, because the control/// connection is a TELNET connection and a single one begins an escape: a file/// whose name holds that byte would otherwise arrive at the server with the/// byte and whatever followed it eaten by `stripTelnet`.pub fn writeName(w: *Io.Writer, name: []const u8, arg: ?[]const u8) WriteError!void { for (name) |c| if (!ascii.isAlphanumeric(c)) return error.InvalidArgument; if (arg == null) return w.print("{s}\r\n", .{name});
const a = arg.?; for (a) |c| if (c == '\r' or c == '\n' or c == 0) return error.InvalidArgument; try w.print("{s} ", .{name}); var rest = a; while (std.mem.findScalar(u8, rest, iac)) |i| { try w.writeAll(rest[0 .. i + 1]); try w.writeByte(iac); rest = rest[i + 1 ..]; } try w.writeAll(rest); try w.writeAll("\r\n");}
// -- tests ----------------------------------------------------------------
const testing = std.testing;
test "verb spellings" { try testing.expectEqualStrings("USER", Verb.user.name()); try testing.expectEqualStrings("MLSD", Verb.mlsd.name()); try testing.expectEqualStrings("XPWD", Verb.xpwd.name()); try testing.expectEqual(Verb.retr, Verb.fromName("RETR").?); try testing.expectEqual(Verb.retr, Verb.fromName("retr").?); try testing.expectEqual(Verb.retr, Verb.fromName("ReTr").?); try testing.expectEqual(@as(?Verb, null), Verb.fromName("XYZZY")); try testing.expectEqual(@as(?Verb, null), Verb.fromName("a very long thing"));}
test "X-prefixed aliases fold to the command they name" { try testing.expectEqual(Verb.pwd, Verb.xpwd.canonical()); try testing.expectEqual(Verb.pwd, Verb.pwd.canonical()); try testing.expect(Verb.xcwd.requiresLogin()); try testing.expect(!Verb.user.requiresLogin());}
test "parse with an argument" { const c = try parse("RETR file.txt"); try testing.expectEqual(Verb.retr, c.verb.?); try testing.expectEqualStrings("RETR", c.name); try testing.expectEqualStrings("file.txt", c.arg.?);}
test "parse without an argument" { const c = try parse("PWD"); try testing.expectEqual(Verb.pwd, c.verb.?); try testing.expectEqual(@as(?[]const u8, null), c.arg); try testing.expectError(error.MissingArgument, c.requireArg());}
test "an empty argument is not a missing one" { const c = try parse("CWD "); try testing.expectEqualStrings("", try c.requireArg());}
test "spaces in a pathname are part of it" { const c = try parse("RETR two spaces "); try testing.expectEqualStrings("two spaces ", c.arg.?);}
test "an unknown verb still parses" { const c = try parse("XYZZY plugh"); try testing.expectEqual(@as(?Verb, null), c.verb); try testing.expectEqualStrings("XYZZY", c.name); try testing.expectEqualStrings("plugh", c.arg.?);}
test "a verb that is not a word is not a command" { try testing.expectError(error.InvalidCommand, parse("")); try testing.expectError(error.InvalidCommand, parse(" RETR x")); try testing.expectError(error.InvalidCommand, parse("RE-TR x")); try testing.expectError(error.InvalidCommand, parse("<!DOCTYPE html>"));}
test "TELNET escapes are stripped" { // What a client actually sends to abort a transfer. var line = [_]u8{ 0xff, 0xf4, 0xff, 0xf2 } ++ "ABOR".*; const stripped = stripTelnet(&line); try testing.expectEqualStrings("ABOR", stripped); try testing.expectEqual(Verb.abor, (try parse(stripped)).verb.?);}
test "TELNET option negotiation takes three bytes" { var line = [_]u8{ 0xff, 0xfb, 0x01 } ++ "NOOP".*; try testing.expectEqualStrings("NOOP", stripTelnet(&line));}
test "a doubled IAC is a literal byte in the argument" { var line = "RETR a".* ++ [_]u8{ 0xff, 0xff } ++ "b".*; try testing.expectEqualStrings("RETR a\xffb", stripTelnet(&line));}
test "a line with no IAC is returned untouched" { var line = "NOOP".*; try testing.expectEqualStrings("NOOP", stripTelnet(&line));}
test "a trailing IAC is dropped rather than read past the end" { var line = "NOOP".* ++ [_]u8{0xff}; try testing.expectEqualStrings("NOOP", stripTelnet(&line));}
test "receive" { var reader: Io.Reader = .fixed("USER anonymous\r\nPWD\r\n"); const first = try receive(&reader); try testing.expectEqual(Verb.user, first.verb.?); try testing.expectEqualStrings("anonymous", first.arg.?); const second = try receive(&reader); try testing.expectEqual(Verb.pwd, second.verb.?); try testing.expectError(error.EndOfStream, receive(&reader));}
test "write" { var buffer: [64]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try write(&w, .user, "anonymous"); try write(&w, .pwd, null); try testing.expectEqualStrings("USER anonymous\r\nPWD\r\n", w.buffered());}
test "a 0xFF byte in an argument is doubled on the wire" { var buffer: [64]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try write(&w, .retr, "a\xffb"); try testing.expectEqualStrings("RETR a\xff\xffb\r\n", w.buffered());
// And comes back as the byte it was. var line = "RETR a".* ++ [_]u8{ 0xff, 0xff } ++ "b".*; try testing.expectEqualStrings("a\xffb", (try parse(stripTelnet(&line))).arg.?);}
test "an argument may not smuggle in another command" { var buffer: [64]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try testing.expectError(error.InvalidArgument, write(&w, .retr, "evil\r\nDELE everything")); try testing.expectError(error.InvalidArgument, write(&w, .retr, "evil\nDELE everything")); try testing.expectError(error.InvalidArgument, write(&w, .retr, "evil\x00")); try testing.expectEqualStrings("", w.buffered());}