// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A small FTP client and server, which exist to show what the library looks //! like from outside and to be something to point a real client or a real //! server at. //! //! Neither is trying to be `lftp` or `proftpd`. There is no `.netrc`, no //! resume, no configuration file, no privilege separation — the interesting //! parts are all in the library, and everything here is the twenty lines it //! takes to reach them. const std = @import("std"); const Io = std.Io; const net = Io.net; const Allocator = std.mem.Allocator; const ftp = @import("ftp"); const usage = \\usage: zig-ftp [options] \\ \\ ls [:port] [path] list a directory \\ get [:port] [out] fetch a file; "-" or omitted means stdout \\ put [:port] [in] send a file; "-" or omitted means stdin \\ mkdir [:port] create a directory; prints the path made \\ rmdir [:port] remove a directory \\ rm [:port] delete a file \\ mv [:port] rename \\ size [:port] the size of a file \\ mdtm [:port] the modification time of a file \\ stat [:port] [path] machine-readable facts, from MLST \\ feat [:port] what the server says it supports \\ pwd [:port] the server's working directory \\ serve [options] serve a directory \\ \\client options: \\ -u, --user NAME log in as NAME (default "anonymous") \\ -p, --password PASS the password (default "anonymous@") \\ -a, --active open data connections actively, with PORT or EPRT \\ -t, --text transfer in ASCII mode, converting line endings \\ -o, --old use PASV and LIST rather than EPSV and MLSD \\ -T, --timeout S give up on a server silent for S seconds (default 0: never) \\ \\serve options: \\ --root DIR the directory to serve (default ".") \\ --bind ADDR the address to listen on (default "127.0.0.1") \\ --port N the port to listen on (default 2121) \\ --write allow uploads, deletion and renaming \\ --user NAME require this name (default: anonymous) \\ --password PASS require this password \\ --idle-timeout S disconnect a client silent for S seconds (default 300; 0: never) \\ --data-timeout S abandon a transfer stalled for S seconds (default 300; 0: never) \\ ; pub fn main(init: std.process.Init) !void { const gpa = init.arena.allocator(); const io = init.io; const args = try init.minimal.args.toSlice(gpa); var stdout_buffer: [16 * 1024]u8 = undefined; var stdout_file: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_file.interface; defer stdout.flush() catch {}; if (args.len < 2) { try stdout.writeAll(usage); try stdout.flush(); return error.MissingCommand; } const command = args[1]; const rest = args[2..]; if (std.mem.eql(u8, command, "ls")) { try list(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "get")) { try get(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "put")) { try put(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "mkdir")) { try simple(io, gpa, stdout, rest, .mkdir, 1); } else if (std.mem.eql(u8, command, "rmdir")) { try simple(io, gpa, stdout, rest, .rmdir, 1); } else if (std.mem.eql(u8, command, "rm")) { try simple(io, gpa, stdout, rest, .rm, 1); } else if (std.mem.eql(u8, command, "mv")) { try simple(io, gpa, stdout, rest, .mv, 2); } else if (std.mem.eql(u8, command, "size")) { try simple(io, gpa, stdout, rest, .size, 1); } else if (std.mem.eql(u8, command, "mdtm")) { try simple(io, gpa, stdout, rest, .mdtm, 1); } else if (std.mem.eql(u8, command, "stat")) { try simple(io, gpa, stdout, rest, .stat, 0); } else if (std.mem.eql(u8, command, "feat")) { try simple(io, gpa, stdout, rest, .feat, 0); } else if (std.mem.eql(u8, command, "pwd")) { try simple(io, gpa, stdout, rest, .pwd, 0); } else if (std.mem.eql(u8, command, "serve")) { try serve(io, gpa, stdout, rest); } else if (std.mem.eql(u8, command, "help") or std.mem.eql(u8, command, "-h") or std.mem.eql(u8, command, "--help")) { try stdout.writeAll(usage); } else { try stdout.print("zig-ftp: unknown command \"{s}\"\n\n{s}", .{ command, usage }); try stdout.flush(); return error.UnknownCommand; } } // -- the client side ------------------------------------------------------- const ClientOptions = struct { user: []const u8 = "anonymous", password: []const u8 = "anonymous@", passive: bool = true, text: bool = false, old: bool = false, timeout: ?Io.Duration = null, /// Everything that was not an option, in order. positional: [][]const u8 = &.{}, fn parse(gpa: Allocator, args: []const [:0]const u8) !ClientOptions { var options: ClientOptions = .{}; var positional: std.ArrayList([]const u8) = .empty; var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, arg, "-u") or std.mem.eql(u8, arg, "--user")) { i += 1; options.user = if (i < args.len) args[i] else return error.MissingValue; } else if (std.mem.eql(u8, arg, "-p") or std.mem.eql(u8, arg, "--password")) { i += 1; options.password = if (i < args.len) args[i] else return error.MissingValue; } else if (std.mem.eql(u8, arg, "-a") or std.mem.eql(u8, arg, "--active")) { options.passive = false; } else if (std.mem.eql(u8, arg, "-t") or std.mem.eql(u8, arg, "--text")) { options.text = true; } else if (std.mem.eql(u8, arg, "-o") or std.mem.eql(u8, arg, "--old")) { options.old = true; } else if (std.mem.eql(u8, arg, "-T") or std.mem.eql(u8, arg, "--timeout")) { i += 1; options.timeout = try parseSeconds(if (i < args.len) args[i] else return error.MissingValue); } else { try positional.append(gpa, arg); } } options.positional = try positional.toOwnedSlice(gpa); return options; } fn transferType(options: ClientOptions) ftp.protocol.transfer.Type { return if (options.text) .{ .ascii = .non_print } else .image; } }; /// Opens a control connection, logs in, and hands the client to `body`. /// /// The connection is on the stack here rather than in the caller because a /// `Client` holds pointers into it and so it must not move; keeping the whole /// lifetime in one function is the simplest way to guarantee that. fn withClient( io: Io, gpa: Allocator, target: []const u8, options: ClientOptions, context: anytype, comptime body: fn (@TypeOf(context), *ftp.Client) anyerror!void, ) !void { const address = try resolve(io, target); var connection: ftp.Client.Connection = undefined; connection.connect(io, gpa, address, .{ .client = .{ .passive = options.passive, .extended_addressing = !options.old, .data_timeout = options.timeout, }, .reply_timeout = options.timeout, }) catch |err| { // Only a read failure is known to have got as far as filling in the // reader; before that, `connection` is undefined. if (err == error.ReadFailed and connection.reader.timedOut()) std.debug.print("zig-ftp: the server stopped answering\n", .{}); return err; }; defer connection.close(); const client = &connection.client; login(client, options) catch |err| return report(&connection, err); if (options.old) client.features.mlst = false; defer client.quit() catch {}; body(context, client) catch |err| return report(&connection, err); } /// A timeout option: whole seconds, with 0 meaning none. fn parseSeconds(text: []const u8) !?Io.Duration { const seconds = try std.fmt.parseInt(u32, text, 10); return if (seconds == 0) null else .fromSeconds(seconds); } fn login(client: *ftp.Client, options: ClientOptions) !void { try client.login(options.user, options.password, null); } /// Says what the server said before giving up. /// /// `error.CommandFailed` on its own tells nobody anything: the reply code and /// the text beside it are the whole of what the server had to say about why, /// and a client that swallows them makes every failure look the same. fn report(connection: *ftp.Client.Connection, err: anyerror) anyerror { const client = &connection.client; const data_timed_out = if (client.data_error) |e| e == error.Timeout else false; if (connection.reader.timedOut() or data_timed_out) { std.debug.print("zig-ftp: the server stopped answering\n", .{}); } else if (err == error.CommandFailed) { std.debug.print("zig-ftp: server said: {f} {s}\n", .{ client.last_reply.code, client.last_reply.firstLine(), }); } return err; } /// Turns `host`, `host:port`, or `[::1]:port` into an address, looking the /// name up if it is not already one. fn resolve(io: Io, target: []const u8) !net.IpAddress { // An IP literal, with or without a port, is settled without asking // anybody. `parseLiteral` requires the brackets for IPv6, which is what // tells its colons apart from a port separator. if (net.IpAddress.parseLiteral(target)) |literal| { var address = literal; if (address.getPort() == 0) address.setPort(ftp.default_port); return address; } else |_| {} var host = target; var port: u16 = ftp.default_port; if (std.mem.findScalarLast(u8, target, ':')) |colon| { // Only a colon with digits after it and none before it is a port; a // bare IPv6 address has several and no port at all. if (std.mem.findScalar(u8, target, ':').? == colon) { port = std.fmt.parseInt(u16, target[colon + 1 ..], 10) catch ftp.default_port; host = target[0..colon]; } } if (net.IpAddress.parse(host, port)) |parsed| return parsed else |_| {} const name = try net.HostName.init(host); var results: [16]net.HostName.LookupResult = undefined; var queue: Io.Queue(net.HostName.LookupResult) = .init(&results); // A queue of 16 is documented not to block, so the lookup completes here // and the answers are read out afterwards. try name.lookup(io, &queue, .{ .port = port }); while (queue.getOne(io)) |result| switch (result) { .address => |address| return address, .canonical_name => {}, } else |_| {} return error.UnknownHostName; } fn list(io: Io, gpa: Allocator, stdout: *Io.Writer, args: []const [:0]const u8) !void { const options = try ClientOptions.parse(gpa, args); if (options.positional.len < 1) return error.MissingHost; const directory: ?[]const u8 = if (options.positional.len > 1) options.positional[1] else null; const Context = struct { gpa: Allocator, stdout: *Io.Writer, directory: ?[]const u8, fn body(context: @This(), client: *ftp.Client) anyerror!void { var listing = try client.list(context.gpa, context.directory); defer listing.deinit(context.gpa); const now = ftp.protocol.time.secondsFromTimestamp( Io.Timestamp.now(client.io, .real), ); for (listing.entries) |entry| { if (entry.isSelfOrParent()) continue; try ftp.protocol.listing.writeUnixEntry(context.stdout, entry, now); try context.stdout.writeByte('\n'); } try context.stdout.flush(); } }; try withClient(io, gpa, options.positional[0], options, Context{ .gpa = gpa, .stdout = stdout, .directory = directory, }, Context.body); } fn get(io: Io, gpa: Allocator, stdout: *Io.Writer, args: []const [:0]const u8) !void { const options = try ClientOptions.parse(gpa, args); if (options.positional.len < 2) return error.MissingPath; const Context = struct { io: Io, stdout: *Io.Writer, remote: []const u8, local: ?[]const u8, type: ftp.protocol.transfer.Type, fn body(context: @This(), client: *ftp.Client) anyerror!void { const local = context.local orelse { _ = try client.retrieve(context.remote, context.stdout, .{ .type = context.type }); try context.stdout.flush(); return; }; const file = try Io.Dir.cwd().createFile(context.io, local, .{}); defer file.close(context.io); var buffer: [64 * 1024]u8 = undefined; var writer = file.writer(context.io, &buffer); _ = try client.retrieve(context.remote, &writer.interface, .{ .type = context.type }); try writer.interface.flush(); } }; const local: ?[]const u8 = if (options.positional.len > 2 and !std.mem.eql(u8, options.positional[2], "-")) options.positional[2] else null; try withClient(io, gpa, options.positional[0], options, Context{ .io = io, .stdout = stdout, .remote = options.positional[1], .local = local, .type = options.transferType(), }, Context.body); } fn put(io: Io, gpa: Allocator, stdout: *Io.Writer, args: []const [:0]const u8) !void { _ = stdout; const options = try ClientOptions.parse(gpa, args); if (options.positional.len < 2) return error.MissingPath; const Context = struct { io: Io, remote: []const u8, local: ?[]const u8, type: ftp.protocol.transfer.Type, fn body(context: @This(), client: *ftp.Client) anyerror!void { var buffer: [64 * 1024]u8 = undefined; if (context.local) |local| { const file = try Io.Dir.cwd().openFile(context.io, local, .{}); defer file.close(context.io); var reader = file.reader(context.io, &buffer); _ = try client.store(context.remote, &reader.interface, .{ .type = context.type }); } else { var reader: Io.File.Reader = .initStreaming(.stdin(), context.io, &buffer); _ = try client.store(context.remote, &reader.interface, .{ .type = context.type }); } } }; const local: ?[]const u8 = if (options.positional.len > 2 and !std.mem.eql(u8, options.positional[2], "-")) options.positional[2] else null; try withClient(io, gpa, options.positional[0], options, Context{ .io = io, .remote = options.positional[1], .local = local, .type = options.transferType(), }, Context.body); } /// The commands that are one round trip and a line of output. const Action = enum { mkdir, rmdir, rm, mv, size, mdtm, stat, feat, pwd }; fn simple( io: Io, gpa: Allocator, stdout: *Io.Writer, args: []const [:0]const u8, action: Action, /// How many pathnames the action needs after the host. arity: usize, ) !void { const options = try ClientOptions.parse(gpa, args); if (options.positional.len < 1 + arity) return error.MissingArgument; const Context = struct { stdout: *Io.Writer, action: Action, first: []const u8, second: []const u8, fn body(context: @This(), client: *ftp.Client) anyerror!void { switch (context.action) { .mkdir => { var buffer: [ftp.protocol.path.max_len]u8 = undefined; try context.stdout.print("{s}\n", .{try client.makeDirectory(context.first, &buffer)}); }, .rmdir => try client.removeDirectory(context.first), .rm => try client.deleteFile(context.first), .mv => try client.rename(context.first, context.second), .size => try context.stdout.print("{d}\n", .{try client.size(context.first)}), .mdtm => try context.stdout.print("{f}\n", .{ ftp.protocol.time.timeval(try client.modificationTime(context.first)), }), .stat => { var buffer: [4096]u8 = undefined; const path: ?[]const u8 = if (context.first.len == 0) null else context.first; const entry = try client.statPath(path, &buffer); try ftp.protocol.listing.writeMachineEntry(context.stdout, entry); try context.stdout.writeByte('\n'); }, .feat => try context.stdout.print("{s}\n", .{client.featureText()}), .pwd => { var buffer: [ftp.protocol.path.max_len]u8 = undefined; try context.stdout.print("{s}\n", .{try client.workingDirectory(&buffer)}); }, } try context.stdout.flush(); } }; try withClient(io, gpa, options.positional[0], options, Context{ .stdout = stdout, .action = action, .first = if (options.positional.len > 1) options.positional[1] else "", .second = if (options.positional.len > 2) options.positional[2] else "", }, Context.body); } // -- the server side ------------------------------------------------------- fn serve(io: Io, gpa: Allocator, stdout: *Io.Writer, args: []const [:0]const u8) !void { var root_path: []const u8 = "."; var bind: []const u8 = "127.0.0.1"; // Not 21: that needs privilege, and a demonstration server should not ask // for any. 2121 is the conventional unprivileged stand-in. var port: u16 = 2121; var writable = false; var user: ?[]const u8 = null; var password: ?[]const u8 = null; // vsftpd's defaults for the same two things, and long enough that nobody // at a keyboard trips over them. var idle_timeout: ?Io.Duration = .fromSeconds(300); var data_timeout: ?Io.Duration = .fromSeconds(300); var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (std.mem.eql(u8, arg, "--root")) { i += 1; root_path = if (i < args.len) args[i] else return error.MissingValue; } else if (std.mem.eql(u8, arg, "--bind")) { i += 1; bind = if (i < args.len) args[i] else return error.MissingValue; } else if (std.mem.eql(u8, arg, "--port")) { i += 1; port = try std.fmt.parseInt(u16, if (i < args.len) args[i] else return error.MissingValue, 10); } else if (std.mem.eql(u8, arg, "--write")) { writable = true; } else if (std.mem.eql(u8, arg, "--user")) { i += 1; user = if (i < args.len) args[i] else return error.MissingValue; } else if (std.mem.eql(u8, arg, "--password")) { i += 1; password = if (i < args.len) args[i] else return error.MissingValue; } else if (std.mem.eql(u8, arg, "--idle-timeout")) { i += 1; idle_timeout = try parseSeconds(if (i < args.len) args[i] else return error.MissingValue); } else if (std.mem.eql(u8, arg, "--data-timeout")) { i += 1; data_timeout = try parseSeconds(if (i < args.len) args[i] else return error.MissingValue); } else { return error.UnknownOption; } } var root = try Io.Dir.cwd().openDir(io, root_path, .{ .iterate = true }); defer root.close(io); var backing: ftp.server.DirFilesystem = .init(root, .{}); var credentials: ftp.server.Auth.Simple = undefined; const access: ftp.server.Auth.Access = if (writable) .all else .read_only; const auth: ftp.server.Auth = if (user) |name| .single(&credentials, name, password orelse "", access) else .anonymousWith(&credentials, access); const address = try net.IpAddress.parse(bind, port); var server: ftp.server.Server = try .listen(io, gpa, address, .{ .filesystem = backing.filesystem(), .auth = auth, .greeting = "zig-ftp", // A server bound to the unspecified address cannot work out what to // put in a 227 reply, and says so rather than guessing. Pointing it at // the bound address covers the ordinary case of binding to one. .passive_address = switch (address) { .ip4 => |ip4| ip4, .ip6 => null, }, .data_timeout = data_timeout, }, .{ .idle_timeout = idle_timeout }); defer server.deinit(); try stdout.print("zig-ftp serving {s} on {f}, {s}, {s}\n", .{ root_path, server.localAddress(), if (writable) "writable" else "read-only", if (user) |name| name else "anonymous", }); try stdout.flush(); try server.serve(); } test { _ = ftp; }