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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// 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 <command> [options] \\ \\ ls <host>[:port] [path] list a directory \\ get <host>[:port] <path> [out] fetch a file; "-" or omitted means stdout \\ put <host>[:port] <path> [in] send a file; "-" or omitted means stdin \\ mkdir <host>[:port] <path> create a directory; prints the path made \\ rmdir <host>[:port] <path> remove a directory \\ rm <host>[:port] <path> delete a file \\ mv <host>[:port] <from> <to> rename \\ size <host>[:port] <path> the size of a file \\ mdtm <host>[:port] <path> the modification time of a file \\ stat <host>[:port] [path] machine-readable facts, from MLST \\ feat <host>[:port] what the server says it supports \\ pwd <host>[: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;}