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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! One control connection: read a command, do it, reply, repeat.//!//! Like `Client`, this holds the control connection as an `Io.Reader` and an//! `Io.Writer` rather than as a socket, so that it can be driven over a//! loopback socket, over a TLS layer somebody else wrote, or over a pair of//! fixed buffers in a test with no network at all.//!//! Nothing here touches a file: `Filesystem` is what does, and the pathname it//! is handed has already been resolved into the virtual name space by//! `protocol.path.resolve`, so a backend cannot be talked out of its own tree//! however the client spells the argument.//!//! A session is a large struct — it carries two path buffers — so it wants to//! be heap-allocated or owned by the fiber that runs it, which is what//! `Server` does.
const std = @import("std");const Io = std.Io;const net = Io.net;const Allocator = std.mem.Allocator;
const protocol = @import("../protocol.zig");const Code = protocol.Code;const Command = protocol.Command;const Features = protocol.Features;const Reply = protocol.Reply;const address = protocol.address;const listing = protocol.listing;const path = protocol.path;const transfer = protocol.transfer;
const Auth = @import("Auth.zig");const Filesystem = @import("Filesystem.zig");const TimeoutReader = @import("../TimeoutReader.zig");const TimeoutWriter = @import("../TimeoutWriter.zig");
const Session = @This();
io: Io,gpa: Allocator,config: *const Config,/// The control connection.reader: *Io.Reader,writer: *Io.Writer,/// Who connected. Used to log, and to refuse an active data connection that/// names somebody else — see `Config.restrict_active_to_peer`.peer_address: net.IpAddress,/// This end of the control connection: where a passive data connection is/// listened for, and what a 227 reply advertises when nothing else says/// otherwise.local_address: net.IpAddress,
/// Scratch for one command's worth of allocation — a directory listing,/// mostly. Reset after every command.arena: std.heap.ArenaAllocator,
/// The name from `USER`, kept because `PASS` needs it.user_buffer: [max_user_len]u8,user_len: usize,logged_in: bool,access: Auth.Access,
/// The working directory, always an absolute virtual path.cwd_buffer: [path.max_len]u8,cwd_len: usize,
/// The path from `RNFR`, waiting for its `RNTO`.rename_buffer: [path.max_len]u8,rename_len: ?usize,
/// The offset from `REST`, consumed by the next transfer.restart_offset: u64,transfer_type: transfer.Type,structure: transfer.Structure,mode: transfer.Mode,
/// The data connection that has been arranged and not yet used.data: Data,/// Whether the client has sent `EPSV ALL`, after which RFC 2428 §4 says it/// may use no other way of opening a data connection.extended_passive_only: bool,
/// Set by `QUIT`, and by anything that closes the session.finished: bool,
/// The longest user name accepted. Longer ones are refused rather than/// truncated, because truncating one is how `jeff` and `jeffrey` become the/// same account.pub const max_user_len = 255;
pub const Config = struct { /// What the server serves. filesystem: Filesystem = .empty, /// Who may log in, and what they may do. auth: Auth = .anonymous, /// The text of the 220 greeting. May be several lines. greeting: []const u8 = "zig-ftp ready", /// What `SYST` answers. The IANA operating system registry is the source /// of the names; "UNIX Type: L8" is what a client expects to hear from /// anything whose paths look like these. system_type: []const u8 = "UNIX Type: L8",
/// The address a 227 reply advertises for a passive data connection. /// /// A server behind a NAT must set this to its *external* address, because /// the client will connect to whatever this says and cannot reach the /// internal one. A server listening on the unspecified address (0.0.0.0) /// must set it too: there is no portable way to ask a socket which of the /// machine's addresses a particular client reached it on, so without this /// the server has nothing true to say and answers `PASV` with a 502. /// /// `EPSV` needs none of this — a 229 reply carries only a port — which is /// one more reason to prefer it, and why a client that speaks it is /// unaffected either way. passive_address: ?net.Ip4Address = null, /// The range of local ports a passive data connection may be listened on, /// for a server whose firewall has to have them opened. Null lets the /// kernel choose, which is what a server with no firewall in front of it /// should do. passive_ports: ?PortRange = null,
/// Whether `PORT` and `EPRT` are accepted at all. /// /// Active mode has the server open a connection to an address the client /// chose, which is a request to make outbound connections on demand. With /// `restrict_active_to_peer` on, that is only ever back to the client that /// asked; with it off, the server is an open relay for port scans (the /// "FTP bounce" attack). Leave both as they are unless a client that /// cannot do passive mode makes it necessary. allow_active: bool = true, /// Refuse an active data connection to any host but the one the control /// connection came from. restrict_active_to_peer: bool = true,
/// The size of the buffer a data connection is read and written through. data_buffer_len: usize = 64 * 1024, /// How long a transfer may go without moving a byte before it is /// abandoned and answered 426: an upload the client stops sending, or a /// download or listing it stops reading. Null waits forever, and a client /// that does either then holds the session until it disconnects. Needs an /// `Io` that can time a socket operation out; see `TimeoutReader` and /// `TimeoutWriter`. data_timeout: ?Io.Duration = null, /// The most entries a listing may hold before the session refuses to send /// it and answers 451 instead. /// /// This bounds what goes on the wire and not what is allocated: the /// `Filesystem` builds the whole list before anything here can count it, /// so a backend that may be asked for an unboundedly large directory has /// to bound itself. listing_max_entries: usize = 1 << 20,
pub const PortRange = struct { first: u16, last: u16 };};
pub const Error = error{ /// The control connection could not be read. ReadFailed, /// The control connection could not be written. WriteFailed, OutOfMemory,};
/// Sets up a session. `run` is what drives it.pub fn init( io: Io, gpa: Allocator, config: *const Config, reader: *Io.Reader, writer: *Io.Writer, addresses: struct { peer: net.IpAddress, local: net.IpAddress },) Session { var session: Session = .{ .io = io, .gpa = gpa, .config = config, .reader = reader, .writer = writer, .peer_address = addresses.peer, .local_address = addresses.local, .arena = .init(gpa), .user_buffer = undefined, .user_len = 0, .logged_in = false, .access = .none, .cwd_buffer = undefined, .cwd_len = path.root.len, .rename_buffer = undefined, .rename_len = null, .restart_offset = 0, // RFC 959 §3.4: a session begins in ASCII, non-print, file structure, // stream mode, whether or not anybody wants it to. .transfer_type = .{ .ascii = .non_print }, .structure = .file, .mode = .stream, .data = .none, .extended_passive_only = false, .finished = false, }; @memcpy(session.cwd_buffer[0..path.root.len], path.root); return session;}
pub fn deinit(s: *Session) void { s.data.close(s.io); s.arena.deinit(); s.* = undefined;}
/// Sends the greeting and then serves commands until the client leaves.////// Returns when the client sends `QUIT`, when it closes the connection, or/// when the connection fails. A command that fails is answered and does not/// end the session — that is the whole point of the reply codes.////// There is no idle timeout in here, because the session reads through an/// `Io.Reader` it was handed and cannot put a deadline on it. The timeout/// belongs to whoever made the reader: `Server` makes a `TimeoutReader` with/// `Options.idle_timeout`, and answers 421 when it fires. A caller driving/// `Session` over a socket of its own can do the same. A server on a public/// network wants one.pub fn run(s: *Session) Error!void { try s.reply(.service_ready, s.config.greeting); while (!s.finished) { defer _ = s.arena.reset(.retain_capacity); const cmd = Command.receive(s.reader) catch |err| switch (err) { // The client hung up. Not an error: plenty of clients do it // instead of sending `QUIT`. error.EndOfStream => return, error.ReadFailed => return error.ReadFailed, error.InvalidCommand => { try s.reply(.syntax_error, "Not a command"); continue; }, error.StreamTooLong => { // The rest of the line is still in the stream and would // otherwise be read as the next command. _ = s.reader.discardDelimiterInclusive('\n') catch |e| switch (e) { error.EndOfStream => return, error.ReadFailed => return error.ReadFailed, }; try s.reply(.bad_arguments, "Command line too long"); continue; }, }; try s.dispatch(cmd); }}
// -- replying --------------------------------------------------------------
fn reply(s: *Session, code: Code, text: []const u8) Error!void { Reply.write(s.writer, code, text) catch return error.WriteFailed; s.writer.flush() catch return error.WriteFailed;}
fn replyPrint(s: *Session, code: Code, comptime fmt: []const u8, args: anytype) Error!void { Reply.print(s.writer, code, fmt, args) catch return error.WriteFailed; s.writer.flush() catch return error.WriteFailed;}
/// Turns a file system error into the reply a client can act on.fn replyForError(s: *Session, err: Filesystem.Error) Error!void { return switch (err) { error.NotFound => s.reply(.file_unavailable, "No such file or directory"), error.AccessDenied => s.reply(.file_unavailable, "Permission denied"), error.NotADirectory => s.reply(.file_unavailable, "Not a directory"), error.IsADirectory => s.reply(.file_unavailable, "Is a directory"), error.AlreadyExists => s.reply(.file_unavailable, "File exists"), error.NotEmpty => s.reply(.file_unavailable, "Directory not empty"), error.NoSpaceLeft => s.reply(.insufficient_storage, "No space left"), error.ReadOnly => s.reply(.file_unavailable, "Read-only file system"), // Not 550: a client told "not implemented" tries something else, // where one told "unavailable" gives up on the path. error.Unsupported => s.reply(.not_implemented, "Not supported here"), error.SystemResources, error.OutOfMemory => s.reply(.local_error, "Out of resources"), error.InputOutput => s.reply(.local_error, "Input/output error"), // The data connection broke rather than the store. error.WriteFailed, error.ReadFailed => s.reply(.transfer_aborted, "Transfer aborted"), };}
// -- dispatch --------------------------------------------------------------
fn dispatch(s: *Session, cmd: Command) Error!void { const verb = (cmd.verb orelse return s.replyPrint( .syntax_error, "{s}: command not understood", .{cmd.name}, )).canonical();
if (verb.requiresLogin() and !s.logged_in) { return s.reply(.not_logged_in, "Please log in with USER and PASS"); }
switch (verb) { .user => try s.doUser(cmd), .pass => try s.doPass(cmd), .acct => try s.doAcct(cmd), .rein => try s.doRein(), .quit => { s.finished = true; try s.reply(.closing_control, "Goodbye"); }, .noop => try s.reply(.command_okay, "NOOP okay"), .syst => try s.reply(.system_type, s.config.system_type), .feat => try s.doFeat(), .opts => try s.doOpts(cmd), .help => try s.doHelp(cmd), .stat => try s.doStat(cmd), .allo => try s.reply(.command_superfluous, "ALLO not needed"),
.type => try s.doType(cmd), .stru => try s.doStru(cmd), .mode => try s.doMode(cmd),
.pwd => try s.doPwd(), .cwd => try s.doCwd(cmd), .cdup => try s.doCdup(),
.pasv => try s.doPasv(), .epsv => try s.doEpsv(cmd), .port => try s.doPort(cmd), .eprt => try s.doEprt(cmd),
.rest => try s.doRest(cmd), .retr => try s.doRetr(cmd), .stor => try s.doStore(cmd, .replace), .appe => try s.doStore(cmd, .append), .stou => try s.doStore(cmd, .unique),
.list => try s.doList(cmd, .human), .nlst => try s.doList(cmd, .names), .mlsd => try s.doList(cmd, .machine), .mlst => try s.doMlst(cmd),
.size => try s.doSize(cmd), .mdtm => try s.doMdtm(cmd), .mkd => try s.doMkd(cmd), .rmd => try s.doRmd(cmd), .dele => try s.doDele(cmd), .rnfr => try s.doRnfr(cmd), .rnto => try s.doRnto(cmd),
// Nothing is running concurrently with the command loop, so by the // time an `ABOR` is read the transfer it meant to stop has finished. .abor => try s.reply(.closing_data_connection, "Nothing to abort"),
// Named so that they can be refused precisely. A 502 tells a client to // stop asking; a 500 makes it wonder whether it spelled the command // wrong. .auth, .adat, .pbsz, .prot, .ccc => try s.reply( .not_implemented, "This server does not offer TLS", ), .site, .smnt, .lprt, .lpsv, .lang => try s.replyPrint( .not_implemented, "{s} not implemented", .{cmd.name}, ), // The X-prefixed aliases are folded away by `canonical`, so reaching // one here would mean `canonical` had missed it. .xpwd, .xcwd, .xcup, .xmkd, .xrmd => unreachable, }}
// -- logging in ------------------------------------------------------------
fn doUser(s: *Session, cmd: Command) Error!void { const name = cmd.arg orelse return s.reply(.bad_arguments, "USER needs a user name"); if (name.len > max_user_len) return s.reply(.bad_arguments, "User name too long");
// A second `USER` abandons whatever login was in progress or in force, // which is what RFC 959 §4.1.1 means by it being usable at any time. s.logged_in = false; s.access = .none; @memcpy(s.user_buffer[0..name.len], name); s.user_len = name.len;
try s.finishLogin(s.config.auth.user(s.authContext()));}
fn doPass(s: *Session, cmd: Command) Error!void { if (s.user_len == 0) return s.reply(.bad_sequence, "Send USER first"); const secret = cmd.arg orelse ""; try s.finishLogin(s.config.auth.password(s.authContext(), secret));}
fn doAcct(s: *Session, cmd: Command) Error!void { if (s.user_len == 0) return s.reply(.bad_sequence, "Send USER first"); const name = cmd.arg orelse return s.reply(.bad_arguments, "ACCT needs an account"); try s.finishLogin(s.config.auth.account(s.authContext(), name));}
fn doRein(s: *Session) Error!void { s.logged_in = false; s.access = .none; s.user_len = 0; s.rename_len = null; s.restart_offset = 0; s.transfer_type = .{ .ascii = .non_print }; s.data.close(s.io); s.cwd_len = path.root.len; @memcpy(s.cwd_buffer[0..path.root.len], path.root); try s.reply(.service_ready, s.config.greeting);}
fn authContext(s: *const Session) Auth.Context { return .{ .user = s.user_buffer[0..s.user_len], // This library speaks no TLS, so the control connection is never // protected. When something wraps it in one, this is where it says so. .protected = false, };}
fn finishLogin(s: *Session, outcome: Auth.Outcome) Error!void { switch (outcome) { .accepted => |access| { s.logged_in = true; s.access = access; try s.replyPrint(.user_logged_in, "User {s} logged in", .{s.user_buffer[0..s.user_len]}); }, .need_password => try s.reply(.need_password, "Password required"), .need_account => try s.reply(.need_account, "Account required"), .rejected => { s.logged_in = false; s.access = .none; // Deliberately the same text whether the name was wrong or the // password was: telling them apart is how a list of valid user // names is harvested. try s.reply(.not_logged_in, "Login incorrect"); }, }}
// -- telling the client about itself ---------------------------------------
fn doFeat(s: *Session) Error!void { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); features().write(&w) catch return error.WriteFailed; try s.reply(.system_status, w.buffered());}
/// What this server can do, which is fixed: everything here is implemented or/// it is not, and none of it depends on how the server was configured.pub fn features() Features { return .{ .mlst = true, .mlst_facts = mlst_facts, .size = true, .mdtm = true, .rest_stream = true, .tvfs = true, .utf8 = true, .epsv = true, .eprt = true, };}
/// The facts `MLSD` and `MLST` send, in the form RFC 3659 §7.8 asks for: a/// star marks one that is sent unless the client turns it off.const mlst_facts = "modify*;perm*;size*;type*;unique*;UNIX.group*;UNIX.mode*;UNIX.owner*;";
fn doOpts(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "OPTS needs a command name"); const end = std.mem.findScalar(u8, arg, ' ') orelse arg.len; const name = arg[0..end]; const parameters = std.mem.trim(u8, arg[end..], " ");
if (std.ascii.eqlIgnoreCase(name, "UTF8")) { // Pathnames here are opaque bytes, which is what UTF-8 pathnames look // like to something that does not interpret them, so this is true // whichever way the client asks. return s.reply(.command_okay, "UTF8 always on"); } if (std.ascii.eqlIgnoreCase(name, "MLST")) { // RFC 2389 §4 wants the resulting fact list echoed back. A server may // send more facts than were asked for, and this one always sends the // same set, so what is echoed is what will actually arrive rather // than what was requested. _ = parameters; return s.replyPrint(.command_okay, "MLST OPTS {s}", .{mlst_facts}); } try s.replyPrint(.bad_arguments, "{s}: no options for that command", .{name});}
fn doHelp(s: *Session, cmd: Command) Error!void { if (cmd.arg) |arg| { if (Command.Verb.fromName(std.mem.trim(u8, arg, " "))) |verb| { return s.replyPrint(.help_message, "{s} is supported", .{verb.name()}); } return s.replyPrint(.help_message, "{s} is not a command here", .{arg}); } var buffer: [1024]u8 = undefined; var w: Io.Writer = .fixed(&buffer); w.writeAll("The following commands are recognised") catch return error.WriteFailed; var column: usize = 0; for (std.enums.values(Command.Verb)) |verb| { if (verb != verb.canonical()) continue; w.writeAll(if (column == 0) "\n " else " ") catch return error.WriteFailed; w.writeAll(verb.name()) catch return error.WriteFailed; column = (column + 1) % 8; } w.writeAll("\nHelp okay") catch return error.WriteFailed; try s.reply(.help_message, w.buffered());}
fn doStat(s: *Session, cmd: Command) Error!void { if (cmd.arg) |arg| { if (!s.logged_in) return s.reply(.not_logged_in, "Please log in first"); if (!s.access.read) return s.reply(.file_unavailable, "Permission denied"); // `STAT <path>` is a listing on the *control* connection, which is // what makes it the one way to see a directory without one. return s.listOnControl(arg); } var buffer: [1024]u8 = undefined; var w: Io.Writer = .fixed(&buffer); w.print("zig-ftp status\n Connected from {f}\n Logged in as {s}\n TYPE: {f}, STRU: {c}, MODE: {c}\nEnd of status", .{ s.peer_address, if (s.logged_in) s.user_buffer[0..s.user_len] else "nobody", s.transfer_type, s.structure.letter(), s.mode.letter(), }) catch return error.WriteFailed; try s.reply(.system_status, w.buffered());}
// -- transfer parameters ---------------------------------------------------
fn doType(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "TYPE needs a parameter"); const new_type = transfer.Type.parse(arg) catch |err| return switch (err) { error.InvalidType => s.replyPrint(.bad_arguments, "{s}: not a type", .{arg}), error.UnsupportedType => s.replyPrint(.parameter_not_implemented, "TYPE {s} not supported", .{arg}), }; s.transfer_type = new_type; try s.replyPrint(.command_okay, "Type set to {f}", .{new_type});}
fn doStru(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "STRU needs a parameter"); const structure = transfer.Structure.parse(arg) catch return s.replyPrint(.bad_arguments, "{s}: not a structure", .{arg}); if (structure != .file) { return s.replyPrint(.parameter_not_implemented, "STRU {c} not supported", .{structure.letter()}); } s.structure = structure; try s.reply(.command_okay, "Structure set to F");}
fn doMode(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "MODE needs a parameter"); const mode = transfer.Mode.parse(arg) catch return s.replyPrint(.bad_arguments, "{s}: not a mode", .{arg}); if (mode != .stream) { return s.replyPrint(.parameter_not_implemented, "MODE {c} not supported", .{mode.letter()}); } s.mode = mode; try s.reply(.command_okay, "Mode set to S");}
fn doRest(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "REST needs an offset"); const offset = std.fmt.parseInt(u64, std.mem.trim(u8, arg, " "), 10) catch return s.replyPrint(.bad_arguments, "{s}: not an offset", .{arg}); s.restart_offset = offset; try s.replyPrint(.pending_further_information, "Restarting at {d}; send the transfer command", .{offset});}
// -- moving about ----------------------------------------------------------
fn cwd(s: *const Session) []const u8 { return s.cwd_buffer[0..s.cwd_len];}
/// Resolves a client's pathname into the virtual name space. The result/// borrows `buffer`, which must be `path.max_len` bytes.fn resolve(s: *Session, buffer: *[path.max_len]u8, arg: []const u8) ?[]u8 { return path.resolve(buffer, s.cwd(), arg) catch null;}
fn doPwd(s: *Session) Error!void { try s.replyPrint(.pathname_created, "{f} is the current directory", .{path.quoted(s.cwd())});}
fn doCwd(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "CWD needs a directory"); try s.changeTo(arg);}
fn doCdup(s: *Session) Error!void { try s.changeTo("..");}
fn changeTo(s: *Session, arg: []const u8) Error!void { var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path");
// The root always exists, whatever the backend thinks: a session must be // able to get back to somewhere it can be. if (!path.isRoot(target)) { const entry = s.config.filesystem.stat(s.io, s.arena.allocator(), target) catch |err| return s.replyForError(err); if (!entry.kind.isDirectory()) return s.reply(.file_unavailable, "Not a directory"); }
@memcpy(s.cwd_buffer[0..target.len], target); s.cwd_len = target.len; try s.replyPrint(.file_action_okay, "Directory changed to {s}", .{s.cwd()});}
fn doMkd(s: *Session, cmd: Command) Error!void { if (!s.access.make_directory) return s.reply(.file_unavailable, "Permission denied"); const arg = cmd.arg orelse return s.reply(.bad_arguments, "MKD needs a directory"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); s.config.filesystem.makeDirectory(s.io, target) catch |err| return s.replyForError(err); // RFC 959 §5.3.2 wants the created path quoted, and the path the server // made rather than the one the client asked for. try s.replyPrint(.pathname_created, "{f} created", .{path.quoted(target)});}
fn doRmd(s: *Session, cmd: Command) Error!void { if (!s.access.delete) return s.reply(.file_unavailable, "Permission denied"); const arg = cmd.arg orelse return s.reply(.bad_arguments, "RMD needs a directory"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); if (path.isRoot(target)) return s.reply(.file_unavailable, "Cannot remove the root"); s.config.filesystem.removeDirectory(s.io, target) catch |err| return s.replyForError(err); try s.reply(.file_action_okay, "Directory removed");}
fn doDele(s: *Session, cmd: Command) Error!void { if (!s.access.delete) return s.reply(.file_unavailable, "Permission denied"); const arg = cmd.arg orelse return s.reply(.bad_arguments, "DELE needs a file"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); s.config.filesystem.removeFile(s.io, target) catch |err| return s.replyForError(err); try s.reply(.file_action_okay, "File deleted");}
fn doRnfr(s: *Session, cmd: Command) Error!void { if (!s.access.rename) return s.reply(.file_unavailable, "Permission denied"); const arg = cmd.arg orelse return s.reply(.bad_arguments, "RNFR needs a file"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); // Checked now rather than at `RNTO`, so that a client renaming something // that is not there hears about it before it has named the destination. _ = s.config.filesystem.stat(s.io, s.arena.allocator(), target) catch |err| return s.replyForError(err); @memcpy(s.rename_buffer[0..target.len], target); s.rename_len = target.len; try s.reply(.pending_further_information, "Send RNTO with the new name");}
fn doRnto(s: *Session, cmd: Command) Error!void { if (!s.access.rename) return s.reply(.file_unavailable, "Permission denied"); const from_len = s.rename_len orelse return s.reply(.bad_sequence, "Send RNFR first"); // Whatever happens next, the pending rename is spent: leaving it set would // let a failed `RNTO` be retried against a path that may have changed. s.rename_len = null; const arg = cmd.arg orelse return s.reply(.bad_arguments, "RNTO needs a file"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); s.config.filesystem.rename(s.io, s.rename_buffer[0..from_len], target) catch |err| return s.replyForError(err); try s.reply(.file_action_okay, "Renamed");}
fn doSize(s: *Session, cmd: Command) Error!void { if (!s.access.read) return s.reply(.file_unavailable, "Permission denied"); const arg = cmd.arg orelse return s.reply(.bad_arguments, "SIZE needs a file"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); const entry = s.config.filesystem.stat(s.io, s.arena.allocator(), target) catch |err| return s.replyForError(err); if (entry.kind.isDirectory()) return s.reply(.file_unavailable, "Is a directory"); // RFC 3659 §4.2 forbids answering in ASCII, because the size on the wire // is not the size on disk and the server would have to read the whole // file to know it. if (s.transfer_type.isText()) { return s.reply(.file_unavailable, "SIZE is not meaningful in ASCII mode; send TYPE I first"); } try s.replyPrint(.file_status, "{d}", .{entry.size orelse 0});}
fn doMdtm(s: *Session, cmd: Command) Error!void { if (!s.access.read) return s.reply(.file_unavailable, "Permission denied"); const arg = cmd.arg orelse return s.reply(.bad_arguments, "MDTM needs a file"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); const entry = s.config.filesystem.stat(s.io, s.arena.allocator(), target) catch |err| return s.replyForError(err); const modified = entry.modified orelse return s.reply(.file_unavailable, "No modification time for that path"); try s.replyPrint(.file_status, "{f}", .{protocol.time.timeval(modified)});}
fn doMlst(s: *Session, cmd: Command) Error!void { if (!s.access.read) return s.reply(.file_unavailable, "Permission denied"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, cmd.arg orelse ".") orelse return s.reply(.bad_arguments, "Path too long or not a path"); var entry = s.config.filesystem.stat(s.io, s.arena.allocator(), target) catch |err| return s.replyForError(err); // RFC 3659 §7.2 has `MLST` name the path the client asked about, which // for a path rather than a directory entry means the whole path. entry.name = target; entry.permissions = s.permissionsFor(entry);
var text: [1024]u8 = undefined; var w: Io.Writer = .fixed(&text); // The entry goes on a line of its own between two lines of prose, which // is what makes it a middle line of a multi-line reply and is why it // arrives at the client indented by one space. w.print("Listing {s}\n ", .{target}) catch return error.WriteFailed; listing.writeMachineEntry(&w, entry) catch return error.WriteFailed; w.writeAll("\nEnd") catch return error.WriteFailed; try s.reply(.file_action_okay, w.buffered());}
/// What this session may do with an entry, which is what the `perm` fact/// reports. It is the session's access rights narrowed by what the entry is,/// not the file's own permissions: the client wants to know whether a command/// will work, and this is the server's answer to that.fn permissionsFor(s: *const Session, entry: Filesystem.Entry) listing.Permissions { const directory = entry.kind.isDirectory(); return .{ .retrieve = s.access.read and !directory, .list = s.access.read and directory, .enter = directory, .append = s.access.write and !directory, .store = s.access.write and !directory, .create = s.access.write and directory, .make_dir = s.access.make_directory and directory, .delete = s.access.delete, .purge = s.access.delete and directory, .rename = s.access.rename, };}
// -- the data connection ---------------------------------------------------
/// A data connection that has been arranged and not yet used.pub const Data = union(enum) { none, /// From `PORT` or `EPRT`: where to connect when the transfer starts. active: net.IpAddress, /// From `PASV` or `EPSV`: a listener the client will connect to. passive: net.Server,
pub fn close(d: *Data, io: Io) void { switch (d.*) { .none, .active => {}, .passive => |*server| server.deinit(io), } d.* = .none; }};
fn doPasv(s: *Session) Error!void { if (s.extended_passive_only) return s.reply(.bad_arguments, "EPSV ALL is in force"); const advertised = s.advertisedIp4() orelse return s.reply( .not_implemented, "This server cannot name its own address for PASV; use EPSV", ); const server = s.listenForData() orelse return s.reply(.cannot_open_data_connection, "No port available"); s.data.close(s.io); s.data = .{ .passive = server };
var buffer: [128]u8 = undefined; var w: Io.Writer = .fixed(&buffer); address.writePassiveReply(&w, .{ .bytes = advertised.bytes, .port = server.socket.address.getPort(), }) catch return error.WriteFailed; try s.reply(.passive_mode, w.buffered());}
fn doEpsv(s: *Session, cmd: Command) Error!void { if (cmd.arg) |arg| { const parameter = std.mem.trim(u8, arg, " "); if (std.ascii.eqlIgnoreCase(parameter, "ALL")) { // RFC 2428 §4: after this the client promises to use nothing else, // and the server may refuse everything else. Worth honouring // because it is what lets a firewall in the middle stop looking // for addresses in the control connection. s.extended_passive_only = true; return s.reply(.command_okay, "EPSV ALL okay"); } // A network protocol number: 1 for IPv4, 2 for IPv6. Answering // anything but the family we are already on is impossible. const wanted = std.fmt.parseInt(u8, parameter, 10) catch return s.reply(.bad_arguments, "EPSV takes ALL or a protocol number"); const current: u8 = switch (s.local_address) { .ip4 => 1, .ip6 => 2, }; if (wanted != current) { return s.replyPrint(.parameter_not_implemented, "Network protocol not supported, use ({d})", .{current}); } } const server = s.listenForData() orelse return s.reply(.cannot_open_data_connection, "No port available"); s.data.close(s.io); s.data = .{ .passive = server };
var buffer: [64]u8 = undefined; var w: Io.Writer = .fixed(&buffer); address.writeExtendedPassiveReply(&w, server.socket.address.getPort()) catch return error.WriteFailed; try s.reply(.extended_passive_mode, w.buffered());}
fn doPort(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "PORT needs an address"); const parsed = address.parseHostPort(arg) catch return s.reply(.bad_arguments, "Not a PORT address"); try s.setActive(.{ .ip4 = parsed });}
fn doEprt(s: *Session, cmd: Command) Error!void { const arg = cmd.arg orelse return s.reply(.bad_arguments, "EPRT needs an address"); const parsed = address.parseExtendedHostPort(arg) catch return s.reply(.bad_arguments, "Not an EPRT address"); try s.setActive(parsed);}
fn setActive(s: *Session, target: net.IpAddress) Error!void { if (s.extended_passive_only) return s.reply(.bad_arguments, "EPSV ALL is in force"); if (!s.config.allow_active) { return s.reply(.not_implemented, "Active mode is disabled; use PASV or EPSV"); } if (s.config.restrict_active_to_peer and !sameHost(target, s.peer_address)) { // The FTP bounce attack: without this, anyone who can log in can have // the server open connections to any address and port they name, using // it to scan a network it can reach and they cannot. return s.reply(.bad_arguments, "Data connections must go back to the control connection's host"); } // Port 0 has no meaning as a destination, and a port below 1024 is asking // the server to connect to somebody's privileged service. if (target.getPort() < 1024) { return s.reply(.bad_arguments, "Data port must be above 1023"); } s.data.close(s.io); s.data = .{ .active = target }; try s.reply(.command_okay, "Address noted");}
fn sameHost(a: net.IpAddress, b: net.IpAddress) bool { var without_ports_a = a; var without_ports_b = b; without_ports_a.setPort(0); without_ports_b.setPort(0); return without_ports_a.eql(&without_ports_b);}
/// The IPv4 address a 227 reply should advertise, or null when the server has/// nothing true to say. See `Config.passive_address`.fn advertisedIp4(s: *const Session) ?net.Ip4Address { if (s.config.passive_address) |configured| return configured; return switch (s.local_address) { .ip4 => |ip4| if (std.mem.eql(u8, &ip4.bytes, &.{ 0, 0, 0, 0 })) null else ip4, .ip6 => null, };}
/// Opens a listening socket for a passive data connection, on a port from the/// configured range or one the kernel picks.fn listenForData(s: *Session) ?net.Server { var bind_address = s.local_address; const range = s.config.passive_ports orelse { bind_address.setPort(0); return net.IpAddress.listen(&bind_address, s.io, .{ .kernel_backlog = 1 }) catch null; }; // Walk the range rather than picking at random: a range is configured to // match a firewall rule, and every port in it is equally open. var port = range.first; while (true) : (port += 1) { bind_address.setPort(port); if (net.IpAddress.listen(&bind_address, s.io, .{ .kernel_backlog = 1 })) |server| { return server; } else |_| {} if (port == range.last) return null; }}
const OpenDataError = error{ /// No `PASV`, `EPSV`, `PORT` or `EPRT` came first. NoDataConnection, /// The connection could not be made. DataConnectionFailed,};
/// Completes the data connection: accepts the client's, or makes ours.////// Consumes the arrangement either way, so the next transfer needs a fresh/// `PASV` or `PORT`. That is what RFC 959 expects and what every client does.fn openData(s: *Session) OpenDataError!net.Stream { defer s.data.close(s.io); switch (s.data) { .none => return error.NoDataConnection, .active => |target| { return net.IpAddress.connect(&target, s.io, .{ .mode = .stream }) catch error.DataConnectionFailed; }, .passive => |*server| { return server.accept(s.io) catch error.DataConnectionFailed; }, }}
/// The 426 for a data connection that failed part way, saying whether it/// broke or was given up on.fn replyForBrokenData(s: *Session, timed_out: bool) Error!void { return s.reply(.transfer_aborted, if (timed_out) "Data connection timed out" else "Data connection failed");}
fn replyForDataError(s: *Session, err: OpenDataError) Error!void { return switch (err) { error.NoDataConnection => s.reply( .cannot_open_data_connection, "Send PASV, EPSV, PORT or EPRT first", ), error.DataConnectionFailed => s.reply( .cannot_open_data_connection, "Could not open the data connection", ), };}
// -- transfers -------------------------------------------------------------
fn doRetr(s: *Session, cmd: Command) Error!void { if (!s.access.read) return s.reply(.file_unavailable, "Permission denied"); const arg = cmd.arg orelse return s.reply(.bad_arguments, "RETR needs a file"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); const offset = s.takeRestartOffset();
// Checked before the 150 rather than after. RFC 959 allows a 150 to be // followed by a 550, but a client that has been told the transfer is // starting has generally already created the file it means to write into, // and would be left holding an empty one. const entry = s.config.filesystem.stat(s.io, s.arena.allocator(), target) catch |err| return s.replyForError(err); if (entry.kind.isDirectory()) return s.reply(.file_unavailable, "Is a directory");
try s.replyPrint(.file_status_okay, "Opening {f} mode data connection for {s}", .{ s.transfer_type, target, }); const stream = s.openData() catch |err| return s.replyForDataError(err); defer stream.close(s.io);
const data_buffer = s.gpa.alloc(u8, s.config.data_buffer_len) catch return error.OutOfMemory; defer s.gpa.free(data_buffer); var data_writer: TimeoutWriter = .init(stream, s.io, data_buffer, TimeoutWriter.idle(s.config.data_timeout));
const moved = if (s.transfer_type.isText()) blk: { var scratch: [4096]u8 = undefined; var encoder: transfer.AsciiEncoder = .init(&data_writer.interface, &scratch); const n = s.config.filesystem.retrieve(s.io, target, offset, &encoder.interface); if (n) |_| encoder.interface.flush() catch return error.WriteFailed else |_| {} break :blk n; } else s.config.filesystem.retrieve(s.io, target, offset, &data_writer.interface);
const bytes = moved catch |err| { if (data_writer.timedOut()) return s.replyForBrokenData(true); return s.replyForError(err); }; data_writer.interface.flush() catch return s.replyForBrokenData(data_writer.timedOut()); try s.replyPrint(.closing_data_connection, "Transfer complete, {d} bytes", .{bytes});}
fn doStore(s: *Session, cmd: Command, store_mode: Filesystem.StoreMode) Error!void { if (!s.access.write) return s.reply(.file_unavailable, "Permission denied"); // `STOU` names a directory to create in, and defaults to the working one. const arg = cmd.arg orelse if (store_mode == .unique) "." else return s.reply(.bad_arguments, "A file name is required"); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, arg) orelse return s.reply(.bad_arguments, "Path too long or not a path"); const offset = if (store_mode == .replace) s.takeRestartOffset() else blk: { s.restart_offset = 0; break :blk 0; };
try s.replyPrint(.file_status_okay, "Opening {f} mode data connection for {s}", .{ s.transfer_type, target, }); const stream = s.openData() catch |err| return s.replyForDataError(err); defer stream.close(s.io);
const data_buffer = s.gpa.alloc(u8, s.config.data_buffer_len) catch return error.OutOfMemory; defer s.gpa.free(data_buffer); var data_reader: TimeoutReader = .init(stream, s.io, data_buffer, TimeoutReader.idle(s.config.data_timeout));
var name_buffer: [path.max_len]u8 = undefined; var unique_name: ?[]const u8 = null; const moved = if (s.transfer_type.isText()) blk: { var scratch: [64]u8 = undefined; var decoder: transfer.AsciiDecoder = .init(&data_reader.interface, &scratch); break :blk s.config.filesystem.store( s.io, target, offset, store_mode, &decoder.interface, &name_buffer, &unique_name, ); } else s.config.filesystem.store( s.io, target, offset, store_mode, &data_reader.interface, &name_buffer, &unique_name, );
const bytes = moved catch |err| { if (data_reader.timedOut()) return s.replyForBrokenData(true); return s.replyForError(err); }; if (store_mode == .unique) { // RFC 1123 §4.1.2.9: the client cannot know what it stored unless the // server says, and it must say so in this exact shape. return s.replyPrint(.closing_data_connection, "FILE: {s} ({d} bytes)", .{ unique_name orelse target, bytes, }); } try s.replyPrint(.closing_data_connection, "Transfer complete, {d} bytes", .{bytes});}
/// Takes the pending `REST` offset and clears it. RFC 3659 §5.4 has the/// offset apply to the next transfer and to nothing after it.fn takeRestartOffset(s: *Session) u64 { defer s.restart_offset = 0; return s.restart_offset;}
// -- listings --------------------------------------------------------------
const ListingFormat = enum { /// `LIST`: whatever a person would like to read, which means `ls -l`. human, /// `NLST`: bare names. names, /// `MLSD`: facts. machine,};
fn doList(s: *Session, cmd: Command, format: ListingFormat) Error!void { if (!s.access.read) return s.reply(.file_unavailable, "Permission denied"); const argument = listArgument(cmd, format); var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, argument) orelse return s.reply(.bad_arguments, "Path too long or not a path");
const arena = s.arena.allocator(); var entries: std.ArrayList(Filesystem.Entry) = .empty; s.config.filesystem.list(s.io, arena, target, &entries) catch |err| switch (err) { // `LIST` and `NLST` on a file name that one file, the way `ls` does. // This is not a nicety: a client's `mget` expands its arguments by // sending `NLST` for each of them, so a server that answers 550 here // cannot be fetched from with `mget` at all. // // `MLSD` is excluded deliberately. RFC 3659 §7.2 gives it directories // and gives `MLST` the single path, and a client that asked for one // knows which it wanted. error.NotADirectory => { if (format == .machine) return s.replyForError(err); var entry = s.config.filesystem.stat(s.io, arena, target) catch |e| return s.replyForError(e); // Named as the client named it, so that what comes back is // something it can turn round and send in a `RETR`. The basename // `stat` reports would be wrong for `NLST pub/deep.txt`. entry.name = argument; entries.append(arena, entry) catch return error.OutOfMemory; }, else => return s.replyForError(err), }; if (entries.items.len > s.config.listing_max_entries) { return s.reply(.local_error, "Directory too large to list"); }
try s.replyPrint(.file_status_okay, "Opening data connection for {s}", .{target}); const stream = s.openData() catch |err| return s.replyForDataError(err); defer stream.close(s.io);
const data_buffer = s.gpa.alloc(u8, s.config.data_buffer_len) catch return error.OutOfMemory; defer s.gpa.free(data_buffer); var data_writer: TimeoutWriter = .init(stream, s.io, data_buffer, TimeoutWriter.idle(s.config.data_timeout)); const w = &data_writer.interface;
s.writeListing(w, target, entries.items, format) catch return s.replyForBrokenData(data_writer.timedOut()); w.flush() catch return s.replyForBrokenData(data_writer.timedOut()); try s.replyPrint(.closing_data_connection, "Listing complete, {d} entries", .{entries.items.len});}
/// The argument of a listing command, which is not simply the pathname.////// Clients send `LIST -la` and `LIST -l /pub`, because for thirty years the/// argument went to a shell that ran `ls` with it. Nothing here runs a shell,/// but the flags still arrive, and a server that took them for a pathname/// would answer "no such file or directory" to a great many working clients.fn listArgument(cmd: Command, format: ListingFormat) []const u8 { const arg = std.mem.trim(u8, cmd.arg orelse "", " "); // `MLSD` was specified after all that and takes a pathname and nothing // else, so a leading hyphen there is part of a name. if (format == .machine) return if (arg.len == 0) "." else arg;
var rest = arg; while (std.mem.startsWith(u8, rest, "-")) { const end = std.mem.findScalar(u8, rest, ' ') orelse return "."; rest = std.mem.trimStart(u8, rest[end..], " "); } return if (rest.len == 0) "." else rest;}
fn writeListing( s: *Session, w: *Io.Writer, directory: []const u8, entries: []const Filesystem.Entry, format: ListingFormat,) Io.Writer.Error!void { const now = protocol.time.secondsFromTimestamp(Io.Timestamp.now(s.io, .real)); if (format == .machine) { // RFC 3659 §7.5.1: a machine listing describes the directory and its // parent as well as its contents, so that a client can learn what it // may do with them without a second command. var self: Filesystem.Entry = .{ .name = ".", .kind = .current_dir }; self.permissions = s.permissionsFor(self); try listing.writeMachineEntry(w, self); try w.writeAll("\r\n"); if (!path.isRoot(directory)) { var parent: Filesystem.Entry = .{ .name = "..", .kind = .parent_dir }; parent.permissions = s.permissionsFor(parent); try listing.writeMachineEntry(w, parent); try w.writeAll("\r\n"); } } for (entries) |entry| { var with_permissions = entry; if (with_permissions.permissions == null) { with_permissions.permissions = s.permissionsFor(entry); } switch (format) { .machine => try listing.writeMachineEntry(w, with_permissions), .human => try listing.writeUnixEntry(w, with_permissions, now), .names => try w.writeAll(entry.name), } try w.writeAll("\r\n"); }}
/// `STAT <path>`: the same listing, on the control connection, as the middle/// lines of a multi-line reply.fn listOnControl(s: *Session, arg: []const u8) Error!void { var buffer: [path.max_len]u8 = undefined; const target = s.resolve(&buffer, std.mem.trim(u8, arg, " ")) orelse return s.reply(.bad_arguments, "Path too long or not a path");
var entries: std.ArrayList(Filesystem.Entry) = .empty; const arena = s.arena.allocator(); s.config.filesystem.list(s.io, arena, target, &entries) catch |err| switch (err) { // A path that is not a directory is still a legitimate thing to ask // about, and `ls` answers with the one entry. error.NotADirectory => { var entry = s.config.filesystem.stat(s.io, arena, target) catch |e| return s.replyForError(e); entry.name = target; entries.append(arena, entry) catch return error.OutOfMemory; }, else => return s.replyForError(err), };
var text: Io.Writer.Allocating = .init(arena); const w = &text.writer; w.print("Status of {s}", .{target}) catch return error.OutOfMemory; const now = protocol.time.secondsFromTimestamp(Io.Timestamp.now(s.io, .real)); for (entries.items) |entry| { var with_permissions = entry; if (with_permissions.permissions == null) { with_permissions.permissions = s.permissionsFor(entry); } w.writeAll("\n") catch return error.OutOfMemory; listing.writeUnixEntry(w, with_permissions, now) catch return error.OutOfMemory; } w.writeAll("\nEnd of status") catch return error.OutOfMemory; try s.reply(.directory_status, text.written());}
test { _ = Auth; _ = Filesystem;}