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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! An FTP client: one control connection, and the data connections it opens.//!//! The control connection is held as an `Io.Reader` and an `Io.Writer` rather//! than as a socket, so that a TLS layer can sit between the two ends without//! anything here changing. `Connection` is the convenience that opens a plain//! TCP one and wires it up.//!//! Every command is a round trip and the connection is a state machine, so//! nothing here is safe to call from two places at once. One `Client` is one//! conversation.//!//! ```//! var connection: ftp.Client.Connection = undefined;//! try connection.connect(io, gpa, server_address, .{});//! defer connection.close();//! const client = &connection.client;//!//! try client.login("anonymous", "nobody@example.com", null);//! var listing = try client.list(gpa, null);//! defer listing.deinit(gpa);//! for (listing.entries) |entry| std.debug.print("{s}\n", .{entry.name});//! ```
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 TimeoutReader = @import("TimeoutReader.zig");const TimeoutWriter = @import("TimeoutWriter.zig");
const Client = @This();
io: Io,gpa: Allocator,/// The control connection.reader: *Io.Reader,writer: *Io.Writer,/// Where the control connection goes. A passive data connection is made to/// this host, because a 229 reply gives only a port and a 227 reply gives an/// address that is often wrong — see `passiveAddress`.server_address: net.IpAddress,/// This end of the control connection. An active data connection is listened/// for on this host, because it is the address the server already knows how/// to reach.local_address: net.IpAddress,options: Options,
/// The reply to the last command, valid until the next one is sent. When a/// call returns `error.CommandFailed` this is what says why.last_reply: Reply,/// The error behind the last `error.DataConnectionFailed`, which is otherwise/// lost: the network error sets are large and none of their members is/// something a caller can act on differently. Also `error.Timeout` when a/// transfer failed with `error.ReadFailed` or `error.WriteFailed` because/// `Options.data_timeout` ran out.data_error: ?anyerror,/// What the server said it supports. Empty until `readFeatures` is called,/// which `login` does.features: Features,/// The representation type the server is in. Tracked so that `retrieve` and/// `store` know whether to convert line endings, and so that `setType` can/// skip the round trip when nothing would change.transfer_type: transfer.Type,
/// Scratch that reply text is gathered into. `last_reply.text` borrows from/// it, which is why one reply does not outlive the next.reply_buffer: std.ArrayList(u8),/// The text of the last `FEAT` reply, which `features.mlst_facts` borrows/// from. Kept separately so that reading a feature does not have to happen/// before the next command.feature_buffer: std.ArrayList(u8),
pub const Options = struct { /// Open data connections passively: the client connects to the server. /// /// This is what you want. An active data connection has the *server* /// connect back to the client, which was reasonable in 1985 and which /// today is refused by every NAT and most firewalls. Active mode is here /// because a few servers still only offer it. passive: bool = true, /// Use `EPSV` and `EPRT` in preference to `PASV` and `PORT` when the /// server has them. Required for IPv6, and worth having over IPv4 too: /// a 229 reply carries only a port, so it cannot carry a wrong address. extended_addressing: bool = true, /// How much reply text to accept before giving up on a server that is /// not going to stop talking. reply_max_len: usize = Reply.default_max_len, /// How much of a directory listing to accept. listing_max_len: usize = 16 * 1024 * 1024, /// The size of the buffers 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 given up /// on: a download the server stops sending, or an upload it stops /// reading. Null waits forever. Needs an `Io` that can time a socket /// operation out; see `TimeoutReader` and `TimeoutWriter`. data_timeout: ?Io.Duration = null,};
pub const ReplyError = Reply.ReceiveError;pub const SendError = Command.WriteError;pub const CommandError = SendError || ReplyError;pub const RequestError = CommandError || error{ /// The server answered with something other than the success this command /// needed. `last_reply` holds the code and the text. CommandFailed,};pub const DataError = RequestError || error{ /// The data connection could not be made. `data_error` holds why. DataConnectionFailed, /// The server's 227 or 229 reply did not hold an address. InvalidAddress,};pub const TransferError = DataError || error{ ReadFailed, WriteFailed };
/// Wraps an existing control connection. See `Connection.connect` for one/// that opens the socket too.////// `reader` and `writer` must stay put and stay valid for as long as the/// client is used. `reader`'s buffer bounds the length of a single reply/// line; `Reply.min_control_buffer_len` is the floor.pub fn init( io: Io, gpa: Allocator, reader: *Io.Reader, writer: *Io.Writer, addresses: struct { server: net.IpAddress, local: net.IpAddress }, options: Options,) Client { return .{ .io = io, .gpa = gpa, .reader = reader, .writer = writer, .server_address = addresses.server, .local_address = addresses.local, .options = options, .last_reply = .{ .code = .{ .value = 0 }, .text = "" }, .data_error = null, .features = .{}, .transfer_type = .{ .ascii = .non_print }, .reply_buffer = .empty, .feature_buffer = .empty, };}
pub fn deinit(c: *Client) void { c.reply_buffer.deinit(c.gpa); c.feature_buffer.deinit(c.gpa); c.* = undefined;}
// -- the control connection ------------------------------------------------
/// Sends a command. Does not wait for the reply; see `receive`.pub fn send(c: *Client, verb: Command.Verb, arg: ?[]const u8) SendError!void { try Command.write(c.writer, verb, arg); try c.writer.flush();}
/// Sends a command whose verb this library does not know, which is how a/// caller reaches a `SITE` subcommand or an extension particular to one/// server.pub fn sendName(c: *Client, name: []const u8, arg: ?[]const u8) SendError!void { try Command.writeName(c.writer, name, arg); try c.writer.flush();}
/// Reads one reply, of whatever class. A transfer command produces two — a/// 1yz when the data connection opens and a 2yz when it closes — and this is/// how each of them is taken in turn.pub fn receive(c: *Client) ReplyError!Reply { c.last_reply = try Reply.receive(c.reader, c.gpa, &c.reply_buffer, .{ .max_len = c.options.reply_max_len, }); return c.last_reply;}
/// Reads replies until one of them is final, discarding the preliminary ones./// The greeting of a server that is not ready yet is a 120 followed by a 220,/// and this is what waits it out.pub fn receiveFinal(c: *Client) ReplyError!Reply { while (true) { const reply = try c.receive(); if (reply.code.isFinal()) return reply; }}
/// Sends a command and reads the final reply to it.pub fn command(c: *Client, verb: Command.Verb, arg: ?[]const u8) CommandError!Reply { try c.send(verb, arg); return c.receiveFinal();}
/// Sends a command and requires it to have succeeded outright.pub fn request(c: *Client, verb: Command.Verb, arg: ?[]const u8) RequestError!Reply { const reply = try c.command(verb, arg); if (reply.code.severity() != .completion) return error.CommandFailed; return reply;}
/// Reads the greeting a server sends as soon as the control connection opens./// Must be called once, before anything else.pub fn readGreeting(c: *Client) RequestError!Reply { const reply = try c.receiveFinal(); if (reply.code.severity() != .completion) return error.CommandFailed; return reply;}
// -- logging in ------------------------------------------------------------
/// Logs in, and reads the server's feature list.////// `password` is sent only if the server asks for one, and `account` only if/// it asks for that — a server that logs the user in on the name alone gets/// neither, which matters because a password sent to a server that did not/// want it is a password in a log file somewhere.pub fn login(c: *Client, user: []const u8, password: ?[]const u8, account: ?[]const u8) RequestError!void { var reply = try c.command(.user, user); if (reply.code.value == Code.need_password.value) { reply = try c.command(.pass, password orelse ""); } if (reply.code.value == Code.need_account.value) { reply = try c.command(.acct, account orelse return error.CommandFailed); } if (reply.code.severity() != .completion) return error.CommandFailed;
// Ask once, here, rather than at each command that might want an // extension: everything after this point can then choose the better // command without a round trip of its own. _ = c.readFeatures() catch |err| switch (err) { // A server old enough to have no `FEAT` has none of the extensions // either, which is exactly what an empty feature set says. error.CommandFailed => {}, else => |e| return e, };}
/// Ends the session, politely. The server closes the control connection after/// replying, so nothing may be sent afterwards.pub fn quit(c: *Client) RequestError!void { _ = try c.request(.quit, null);}
/// Does nothing, successfully. What to send to keep an idle session from being/// timed out.pub fn noop(c: *Client) RequestError!void { _ = try c.request(.noop, null);}
/// Asks the server what it can do, and remembers the answer in `features`.pub fn readFeatures(c: *Client) RequestError!Features { const reply = try c.request(.feat, null); // The reply text is about to be overwritten by the next command, and // `features.mlst_facts` points into it, so it is copied out first. c.feature_buffer.clearRetainingCapacity(); c.feature_buffer.appendSlice(c.gpa, reply.text) catch return error.OutOfMemory; c.features = .parse(c.feature_buffer.items); return c.features;}
/// The text of the last `FEAT` reply, for the features `Features` has no/// field for. See `Features.has`.pub fn featureText(c: *const Client) []const u8 { return c.feature_buffer.items;}
/// The server's operating system, from `SYST`. Copied into `buffer` because/// the reply text does not survive the next command.pub fn systemType(c: *Client, buffer: []u8) RequestError![]u8 { const reply = try c.request(.syst, null); const line = reply.firstLine(); const len = @min(line.len, buffer.len); @memcpy(buffer[0..len], line[0..len]); return buffer[0..len];}
// -- moving about ----------------------------------------------------------
/// The server's working directory, from `PWD`. Copied into `buffer`.////// Unlike `makeDirectory` this refuses a 257 that quotes nothing, because/// there is nothing to fall back on: the whole point of the command is to/// learn a path the client does not already know, and guessing at the prose/// around it is how `257 "/pub" is current directory` becomes the path/// `/pub" is current directory`.pub fn workingDirectory(c: *Client, buffer: []u8) (RequestError || path.UnquoteError)![]u8 { const reply = try c.request(.pwd, null); return path.unquote(buffer, reply.firstLine());}
pub fn changeDirectory(c: *Client, directory: []const u8) RequestError!void { _ = try c.request(.cwd, directory);}
pub fn changeToParent(c: *Client) RequestError!void { _ = try c.request(.cdup, null);}
/// Creates a directory and returns the path the server made, copied into/// `buffer`. It need not be the path asked for: a relative path is resolved/// against the working directory, and a server may have transformed it.////// RFC 959 §5.3.2 asks the 257 reply to quote the path, and a good many/// servers answer `257 Directory created` and leave it at that. That is not a/// failure -- the directory is there -- so the path asked for is returned/// instead, which is the name the caller can address it by either way.pub fn makeDirectory( c: *Client, directory: []const u8, buffer: []u8,) (RequestError || error{PathTooLong})![]u8 { const reply = try c.request(.mkd, directory); return path.unquote(buffer, reply.firstLine()) catch |err| switch (err) { error.PathTooLong => error.PathTooLong, error.NoQuotedName => { if (directory.len > buffer.len) return error.PathTooLong; @memcpy(buffer[0..directory.len], directory); return buffer[0..directory.len]; }, };}
pub fn removeDirectory(c: *Client, directory: []const u8) RequestError!void { _ = try c.request(.rmd, directory);}
pub fn deleteFile(c: *Client, file: []const u8) RequestError!void { _ = try c.request(.dele, file);}
/// Renames a file. Two commands, and the pair is not atomic: a server that/// accepts the `RNFR` and then fails the `RNTO` leaves a session with a/// rename half-begun, which the next `RNFR` discards.pub fn rename(c: *Client, from: []const u8, to: []const u8) RequestError!void { const reply = try c.command(.rnfr, from); if (reply.code.severity() != .intermediate) return error.CommandFailed; _ = try c.request(.rnto, to);}
/// The size of a file, from `SIZE`.////// Switches to `TYPE I` first, and leaves the session there. RFC 3659 §4/// defines the answer as the number of bytes that *would be sent*, which in/// `TYPE A` depends on line endings the server would have to read the whole/// file to count -- so §4.2 tells a server not to answer at all in that type,/// and a client that wants an answer to ask in this one. Send `TYPE` yourself/// afterwards if the session needed to stay where it was.pub fn size(c: *Client, file: []const u8) (RequestError || error{InvalidReply})!u64 { try c.setType(.image); const reply = try c.request(.size, file); const text = std.mem.trim(u8, reply.firstLine(), " "); return std.fmt.parseInt(u64, text, 10) catch error.InvalidReply;}
/// The modification time of a file, from `MDTM`, in seconds since/// 1970-01-01 UTC.pub fn modificationTime(c: *Client, file: []const u8) (RequestError || error{InvalidReply})!i64 { const reply = try c.request(.mdtm, file); const text = std.mem.trim(u8, reply.firstLine(), " "); return protocol.time.parseTimeval(text) catch error.InvalidReply;}
/// Selects the representation type, if it is not already selected.pub fn setType(c: *Client, new_type: transfer.Type) RequestError!void { if (std.meta.eql(c.transfer_type, new_type)) return; var buffer: [8]u8 = undefined; var w: Io.Writer = .fixed(&buffer); w.print("{f}", .{new_type}) catch unreachable; // No type prints longer than "L 255". _ = try c.request(.type, w.buffered()); c.transfer_type = new_type;}
// -- data connections ------------------------------------------------------
/// A data connection that has been arranged but not yet used.////// The two halves of the protocol differ in when the connection exists./// Passively, the client connects as soon as the server has named a port, so/// the socket is already open when the transfer command is sent. Actively, the/// client can only listen, and the connection does not exist until the server/// makes it — which it does after reading the transfer command. So one of/// these is a socket and the other is a promise of one.const Channel = union(enum) { /// Taken, or never arranged. Closing this does nothing, which is what lets /// `take` and a `defer close` coexist. none, connected: net.Stream, listening: net.Server,
fn close(channel: *Channel, io: Io) void { switch (channel.*) { .none => {}, .connected => |stream| stream.close(io), .listening => |*server| server.deinit(io), } channel.* = .none; }
/// Completes the connection and hands it over: accepts, if we were the one /// listening. fn take(channel: *Channel, c: *Client) DataError!net.Stream { switch (channel.*) { .none => unreachable, // Nothing was arranged. .connected => |stream| { channel.* = .none; return stream; }, .listening => |*server| { const stream = server.accept(c.io) catch |err| { c.data_error = err; return error.DataConnectionFailed; }; // The listening socket has done its work; leaving it open // would let a second connection queue behind the transfer. server.deinit(c.io); channel.* = .none; return stream; }, } }};
/// Arranges a data connection: `EPSV`/`PASV` and connect, or listen and then/// `EPRT`/`PORT`.fn prepare(c: *Client) DataError!Channel { return if (c.options.passive) c.preparePassive() else c.prepareActive();}
fn preparePassive(c: *Client) DataError!Channel { const target = try c.passiveAddress(); const stream = net.IpAddress.connect(&target, c.io, .{ .mode = .stream }) catch |err| { c.data_error = err; return error.DataConnectionFailed; }; return .{ .connected = stream };}
/// Asks the server where to connect, and works out the address to use.////// The host is taken from the control connection rather than from the reply,/// even when `PASV` supplied one. A server behind a NAT reports the address it/// sees on itself, which is not reachable from here; a server that has been/// told its external address reports that, which is reachable but is the/// address we already have. Either way the host we came in on is the right/// one, and it is the only one an attacker cannot use to point the transfer/// somewhere else. Only the port comes from the reply — which is all a 229/// reply carries in the first place, and one of the reasons `EPSV` is better.fn passiveAddress(c: *Client) DataError!net.IpAddress { var target = c.server_address; if (c.options.extended_addressing) { const reply = try c.command(.epsv, null); if (reply.code.severity() == .completion) { target.setPort(address.parseExtendedPassiveReply(reply.firstLine()) catch return error.InvalidAddress); return target; } // A 5yz to `EPSV` is an old server, and `PASV` is what it has. Over // IPv6 there is no such fallback: `PASV` has no way to say the // address, so a server without `EPSV` cannot be reached that way. if (c.server_address == .ip6) return error.CommandFailed; } const reply = try c.request(.pasv, null); const reported = address.parsePassiveReply(reply.firstLine()) catch return error.InvalidAddress; target.setPort(reported.port); return target;}
fn prepareActive(c: *Client) DataError!Channel { // Port zero, so that the kernel picks one; `listen` fills in which. var bind_address = c.local_address; bind_address.setPort(0); var server = net.IpAddress.listen(&bind_address, c.io, .{ .kernel_backlog = 1 }) catch |err| { c.data_error = err; return error.DataConnectionFailed; }; errdefer server.deinit(c.io);
var buffer: [128]u8 = undefined; if (c.options.extended_addressing) { var w: Io.Writer = .fixed(&buffer); address.writeExtendedHostPort(&w, server.socket.address) catch unreachable; const reply = try c.command(.eprt, w.buffered()); if (reply.code.severity() == .completion) return .{ .listening = server }; if (c.local_address == .ip6) return error.CommandFailed; } var w: Io.Writer = .fixed(&buffer); switch (server.socket.address) { .ip4 => |ip4| address.writeHostPort(&w, ip4) catch unreachable, // `PORT` has no way to say an IPv6 address either. .ip6 => return error.CommandFailed, } _ = try c.request(.port, w.buffered()); return .{ .listening = server };}
/// What a download can fail with: everything a transfer can, plus whatever the/// context that consumes the data adds. `Collector` adds `ListingTooLong`.fn DownloadError(comptime Context: type) type { const signature = @typeInfo(@TypeOf(Context.receive)).@"fn"; return TransferError || @typeInfo(signature.return_type.?).error_union.error_set;}
/// Runs a command whose reply arrives over a data connection the server sends/// on, and hands the connection to `context.receive`.////// The shape is fixed by RFC 959 §3.2: the transfer command is answered by a/// 1yz when the data connection opens, the data follows, and a 2yz comes when/// it closes. The second reply is read whatever happened to the transfer,/// because leaving it in the stream would desynchronise every command after/// this one.fn runDownload( c: *Client, verb: Command.Verb, arg: ?[]const u8, context: anytype,) DownloadError(@TypeOf(context))!u64 { const buffer = c.gpa.alloc(u8, c.options.data_buffer_len) catch return error.OutOfMemory; defer c.gpa.free(buffer);
var channel = try c.prepare(); defer channel.close(c.io);
try c.send(verb, arg); if (!(try c.receive()).code.isPositive()) return error.CommandFailed;
const stream = try channel.take(c); const moved = blk: { var stream_reader: TimeoutReader = .init(stream, c.io, buffer, TimeoutReader.idle(c.options.data_timeout)); const moved = context.receive(&stream_reader.interface); if (stream_reader.timedOut()) c.data_error = error.Timeout; break :blk moved; }; stream.close(c.io);
const closing = try c.receiveFinal(); const bytes = try moved; if (closing.code.severity() != .completion) return error.CommandFailed; return bytes;}
/// The same, for a command the client sends on: `STOR`, `STOU` and `APPE`.fn runUpload(c: *Client, verb: Command.Verb, arg: ?[]const u8, context: anytype) TransferError!u64 { const buffer = c.gpa.alloc(u8, c.options.data_buffer_len) catch return error.OutOfMemory; defer c.gpa.free(buffer);
var channel = try c.prepare(); defer channel.close(c.io);
try c.send(verb, arg); if (!(try c.receive()).code.isPositive()) return error.CommandFailed;
const stream = try channel.take(c); const moved = blk: { var stream_writer: TimeoutWriter = .init(stream, c.io, buffer, TimeoutWriter.idle(c.options.data_timeout)); const moved = context.send(&stream_writer.interface); if (stream_writer.timedOut()) c.data_error = error.Timeout; break :blk moved; }; // In stream mode the close *is* the end-of-file marker (RFC 959 §3.4.1), // so this is what tells the server the file is complete. stream.close(c.io);
const closing = try c.receiveFinal(); const bytes = try moved; if (closing.code.severity() != .completion) return error.CommandFailed; return bytes;}
pub const TransferOptions = struct { /// Where in the file to start, sent as `REST` before the transfer. /// /// The server must have advertised `REST STREAM`; `Features.rest_stream` /// says whether it did. A non-zero offset with `.type = .ascii` is very /// nearly meaningless — the offset counts bytes on the wire, and the wire /// is not where the line endings are — so restart binary transfers only. offset: u64 = 0, /// The representation type to transfer in. `.image` moves bytes and is /// what anything that is not text wants; `.{ .ascii = .non_print }` /// converts line endings between the local `\n` and the wire's `\r\n`. type: transfer.Type = .image,};
/// Fetches a file, writing it to `destination`. Returns the number of bytes/// written there, which in ASCII mode is not the number that crossed the/// network.pub fn retrieve( c: *Client, file: []const u8, destination: *Io.Writer, options: TransferOptions,) TransferError!u64 { try c.setType(options.type); try c.restart(options.offset); return c.runDownload(.retr, file, Receiver{ .destination = destination, .text = options.type.isText(), });}
/// Sends a file, reading it from `source`. Returns the number of bytes put on/// the data connection.pub fn store( c: *Client, file: []const u8, source: *Io.Reader, options: TransferOptions,) TransferError!u64 { try c.setType(options.type); try c.restart(options.offset); return c.runUpload(.stor, file, Sender{ .source = source, .text = options.type.isText(), });}
/// Sends a file, adding to whatever is already there rather than replacing it./// `options.offset` is ignored: `APPE` means the end, wherever that is.pub fn append( c: *Client, file: []const u8, source: *Io.Reader, options: TransferOptions,) TransferError!u64 { try c.setType(options.type); return c.runUpload(.appe, file, Sender{ .source = source, .text = options.type.isText(), });}
const Receiver = struct { destination: *Io.Writer, text: bool,
fn receive(r: Receiver, data: *Io.Reader) TransferError!u64 { if (r.text) return transfer.decodeAscii(data, r.destination); return data.streamRemaining(r.destination); }};
const Sender = struct { source: *Io.Reader, text: bool,
fn send(s: Sender, data: *Io.Writer) TransferError!u64 { const moved = if (s.text) try transfer.encodeAscii(s.source, data) else try s.source.streamRemaining(data); data.flush() catch return error.WriteFailed; return moved; }};
fn restart(c: *Client, offset: u64) RequestError!void { if (offset == 0) return; var buffer: [24]u8 = undefined; const text = std.fmt.bufPrint(&buffer, "{d}", .{offset}) catch unreachable; const reply = try c.command(.rest, text); if (reply.code.severity() != .intermediate) return error.CommandFailed;}
/// Aborts the transfer in progress.////// RFC 959 §4.1.3 has this preceded by a TELNET interrupt and a Synch, sent as/// urgent data. Only the in-band half is sent here — `std.Io.net` has no way/// to send out-of-band data — which is enough for the servers that read their/// control connection while transferring, and is ignored until the transfer/// finishes by the ones that do not.pub fn abort(c: *Client) CommandError!Reply { try c.writer.writeAll(&.{ Command.iac, 0xf4, Command.iac, 0xf2 }); return c.command(.abor, null);}
// -- listings --------------------------------------------------------------
/// A directory listing: the bytes the server sent, and the entries parsed out/// of them.pub const Listing = struct { /// The raw listing, which every entry's slices point into. text: []u8, entries: []listing.Entry, /// Which command produced it, since what the entries hold depends on /// that: a machine listing's fields are read, a human one's are guessed. format: Format,
pub const Format = enum { machine, human };
pub fn deinit(l: *Listing, gpa: Allocator) void { gpa.free(l.text); gpa.free(l.entries); l.* = undefined; }};
pub const ListError = TransferError || error{ /// The listing ran past `Options.listing_max_len`. ListingTooLong,};
/// Lists a directory, or the working directory when `directory` is null.////// Uses `MLSD` when the server has it and `LIST` otherwise, which is the/// difference between reading a defined format and guessing at somebody's/// display output. `login` is what discovers which; a client that has not/// logged in through this library should call `readFeatures` first or it will/// get the guessing.////// Lines that cannot be parsed are skipped rather than failing the listing:/// one unreadable entry in a directory of a thousand should not lose the other/// nine hundred and ninety-nine.pub fn list(c: *Client, gpa: Allocator, directory: ?[]const u8) ListError!Listing { const machine = c.features.mlst; var gathered: std.ArrayList(u8) = .empty; errdefer gathered.deinit(gpa); _ = try c.download(if (machine) .mlsd else .list, directory, gpa, &gathered);
// Taken ownership of *before* anything is parsed out of it: shrinking the // list to fit can move the allocation, and every entry is a slice into it. const text = gathered.toOwnedSlice(gpa) catch return error.OutOfMemory; errdefer gpa.free(text);
var entries: std.ArrayList(listing.Entry) = .empty; errdefer entries.deinit(gpa); const now = protocol.time.secondsFromTimestamp(Io.Timestamp.now(c.io, .real)); var lines = std.mem.splitScalar(u8, text, '\n'); while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, "\r"); if (line.len == 0) continue; const entry = if (machine) listing.parseMachineEntry(line) catch continue else listing.parseEntry(line, .{ .now = now }) catch continue; entries.append(gpa, entry) catch return error.OutOfMemory; }
return .{ .text = text, .entries = entries.toOwnedSlice(gpa) catch return error.OutOfMemory, .format = if (machine) .machine else .human, };}
/// The names in a directory and nothing else, from `NLST`.////// The names are appended to `names` and borrow from `text`, which holds the/// listing as it arrived. Both belong to the caller.pub fn nameList( c: *Client, gpa: Allocator, directory: ?[]const u8, text: *std.ArrayList(u8), names: *std.ArrayList([]const u8),) ListError!void { _ = try c.download(.nlst, directory, gpa, text); var lines = std.mem.splitScalar(u8, text.items, '\n'); while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, "\r"); if (line.len == 0) continue; names.append(gpa, line) catch return error.OutOfMemory; }}
/// Facts about one path, from `MLST`, or about the working directory when/// `file` is null.////// Unlike every other listing command this answers on the control connection,/// so no data connection is opened — which is what makes it the cheap way to/// ask whether a path is a directory. The returned entry borrows from/// `buffer`, into which the reply is copied.pub fn statPath( c: *Client, file: ?[]const u8, buffer: []u8,) (RequestError || listing.ParseError)!listing.Entry { const reply = try c.request(.mlst, file); // RFC 3659 §7.2: the reply is a multi-line one whose first and last lines // are prose and whose middle line is the entry. var lines = std.mem.splitScalar(u8, reply.text, '\n'); _ = lines.first(); const line = lines.next() orelse return error.InvalidEntry; const len = @min(line.len, buffer.len); @memcpy(buffer[0..len], line[0..len]); return listing.parseMachineEntry(buffer[0..len]);}
/// Runs a command whose output arrives on the data connection and gathers all/// of it into `text`.fn download( c: *Client, verb: Command.Verb, arg: ?[]const u8, gpa: Allocator, text: *std.ArrayList(u8),) ListError!u64 { // A listing is text and every server sends it with CRLF whatever the // type, so this changes nothing about what arrives -- but a few servers // refuse to list in a type they consider binary, and every client sends // this, so it is what they expect to see. try c.setType(.{ .ascii = .non_print }); return c.runDownload(verb, arg, Collector{ .gpa = gpa, .text = text, .limit = c.options.listing_max_len, });}
const Collector = struct { gpa: Allocator, text: *std.ArrayList(u8), limit: usize,
fn receive(collector: Collector, data: *Io.Reader) ListError!u64 { var writer: Io.Writer.Allocating = .fromArrayList(collector.gpa, collector.text); defer collector.text.* = writer.toArrayList(); const before = writer.writer.end; // One byte past the limit, so that a listing of exactly the limit is // accepted and one of limit plus one is caught rather than truncated. var remaining: usize = collector.limit - @min(collector.limit, before) + 1; while (remaining > 0) { const n = data.stream(&writer.writer, .limited(remaining)) catch |err| switch (err) { error.EndOfStream => break, error.ReadFailed => return error.ReadFailed, error.WriteFailed => return error.OutOfMemory, }; remaining -= n; } else return error.ListingTooLong; return writer.writer.end - before; }};
// -- tests -----------------------------------------------------------------
const testing = std.testing;
/// A client talking to a transcript rather than to a server, for the replies/// that are awkward to get a real server to produce.////// Must not be moved once `init` has returned: the client holds pointers into/// it, the same as `Connection` does.const Canned = struct { reader: Io.Reader, writer: Io.Writer, sent: [512]u8, client: Client,
fn init(canned: *Canned, replies: []const u8) void { canned.reader = .fixed(replies); canned.writer = .fixed(&canned.sent); canned.client = .init(testing.io, testing.allocator, &canned.reader, &canned.writer, .{ .server = .{ .ip4 = .loopback(21) }, .local = .{ .ip4 = .loopback(0) }, }, .{}); }
fn deinit(canned: *Canned) void { canned.client.deinit(); }};
test "MKD against a server that quotes the path it made" { var canned: Canned = undefined; canned.init("257 \"/pub/new\" created\r\n"); defer canned.deinit();
var buffer: [64]u8 = undefined; try testing.expectEqualStrings("/pub/new", try canned.client.makeDirectory("new", &buffer));}
test "MKD against a server that quotes nothing" { // rclone's `serve ftp` answers exactly this. RFC 959 §5.3.2 asks for the // quoted path, the command still succeeded without it, so the name asked // for comes back rather than the call failing. var canned: Canned = undefined; canned.init("257 Directory created\r\n"); defer canned.deinit();
var buffer: [64]u8 = undefined; try testing.expectEqualStrings("/pub/new", try canned.client.makeDirectory("/pub/new", &buffer));}
test "MKD that actually failed still fails" { var canned: Canned = undefined; canned.init("550 Permission denied\r\n"); defer canned.deinit();
var buffer: [64]u8 = undefined; try testing.expectError(error.CommandFailed, canned.client.makeDirectory("/pub/new", &buffer));}
test "PWD refuses a reply that quotes nothing, since there is nothing to guess" { var canned: Canned = undefined; canned.init("257 /pub is the current directory\r\n"); defer canned.deinit();
var buffer: [64]u8 = undefined; try testing.expectError(error.NoQuotedName, canned.client.workingDirectory(&buffer));}
// -- an owned control connection -------------------------------------------
/// A `Client` with the socket and the buffers it needs, for the common case of/// a plain TCP control connection this program opened itself.////// The client holds pointers into the reader and the writer, so a `Connection`/// must not be moved once `connect` has returned.pub const Connection = struct { stream: net.Stream, /// `reader.timedOut()` says whether a failed request failed because the /// server stopped answering. reader: TimeoutReader, /// Likewise `writer.timedOut()`, for a server that stopped reading. writer: TimeoutWriter, read_buffer: []u8, write_buffer: []u8, client: Client,
pub const ConnectOptions = struct { client: Options = .{}, /// The control connection's read buffer, which is what bounds the /// length of a single reply line. read_buffer_len: usize = 4096, write_buffer_len: usize = 1024, /// How long to wait for a server that has stopped answering before a /// request fails with `error.ReadFailed` — or has stopped reading, /// with `error.WriteFailed`. Null waits forever. It /// bounds silence, so a slow multi-line reply is not cut off, but it /// does cover the wait for the reply that ends a transfer, which must /// be longer than the transfer's own last pause. Needs an `Io` that can /// time a socket operation out; see `TimeoutReader`. reply_timeout: ?Io.Duration = null, };
pub const ConnectError = error{ OutOfMemory, ConnectFailed } || Client.RequestError;
/// Opens a control connection and reads the greeting. pub fn connect( connection: *Connection, io: Io, gpa: Allocator, server: net.IpAddress, options: ConnectOptions, ) ConnectError!void { std.debug.assert(options.read_buffer_len >= Reply.min_control_buffer_len); const read_buffer = gpa.alloc(u8, options.read_buffer_len) catch return error.OutOfMemory; errdefer gpa.free(read_buffer); const write_buffer = gpa.alloc(u8, options.write_buffer_len) catch return error.OutOfMemory; errdefer gpa.free(write_buffer);
const stream = net.IpAddress.connect(&server, io, .{ .mode = .stream }) catch return error.ConnectFailed; errdefer stream.close(io);
connection.* = .{ .stream = stream, .reader = .init(stream, io, read_buffer, TimeoutReader.idle(options.reply_timeout)), .writer = .init(stream, io, write_buffer, TimeoutWriter.idle(options.reply_timeout)), .read_buffer = read_buffer, .write_buffer = write_buffer, .client = undefined, }; connection.client = .init( io, gpa, &connection.reader.interface, &connection.writer.interface, .{ .server = server, .local = stream.socket.address }, options.client, ); errdefer connection.client.deinit(); _ = try connection.client.readGreeting(); }
/// Closes the control connection and frees everything `connect` /// allocated. Does not send `QUIT`; call `Client.quit` first to leave /// politely. pub fn close(connection: *Connection) void { const gpa = connection.client.gpa; const io = connection.client.io; connection.client.deinit(); connection.stream.close(io); gpa.free(connection.read_buffer); gpa.free(connection.write_buffer); connection.* = undefined; }};
test { _ = protocol;}