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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! How an address for the data connection is written on the control//! connection.//!//! There are two encodings and four commands. RFC 959 puts an IPv4 address and//! port into six decimal bytes for `PORT`, and answers `PASV` with the same//! six inside a 227 reply. RFC 2428 replaces both with `EPRT` and `EPSV`,//! which carry an address family and a printed address between delimiters and//! so work for IPv6 — and whose passive form sends no address at all, only a//! port, because the client is already connected to the server and knows where//! it is.//!//! RFC 1639's `LPRT` and `LPSV` are the third encoding and are not here.//! They were the interim answer to IPv6 before RFC 2428, were reclassified//! Historic, and no server that speaks them fails to speak `PASV` as well.
const std = @import("std");const Io = std.Io;const net = Io.net;
/// The address family byte of `EPRT` and `EPSV` (RFC 2428 §2).pub const NetworkProtocol = enum(u8) { ip4 = 1, ip6 = 2,
pub fn of(address: net.IpAddress) NetworkProtocol { return switch (address) { .ip4 => .ip4, .ip6 => .ip6, }; }};
pub const ParseError = error{ /// The text held no address in the expected encoding. InvalidAddress,};
// -- PORT and the 227 reply to PASV ---------------------------------------
/// Writes an IPv4 address as the six decimal bytes `PORT` takes:/// `h1,h2,h3,h4,p1,p2`, most significant byte of the port first.pub fn writeHostPort(w: *Io.Writer, address: net.Ip4Address) Io.Writer.Error!void { try w.print("{d},{d},{d},{d},{d},{d}", .{ address.bytes[0], address.bytes[1], address.bytes[2], address.bytes[3], address.port >> 8, address.port & 0xff, });}
/// Formats an IPv4 address for `{f}` as `PORT` takes it. See `writeHostPort`.pub fn hostPort(address: net.Ip4Address) HostPort { return .{ .address = address };}
pub const HostPort = struct { address: net.Ip4Address,
pub fn format(hp: HostPort, w: *Io.Writer) Io.Writer.Error!void { return writeHostPort(w, hp.address); }};
/// Reads the six decimal bytes of a `PORT` argument.pub fn parseHostPort(text: []const u8) ParseError!net.Ip4Address { var fields: [6]u8 = undefined; var it = std.mem.splitScalar(u8, text, ','); for (&fields) |*field| { const token = std.mem.trim(u8, it.next() orelse return error.InvalidAddress, " "); field.* = std.fmt.parseInt(u8, token, 10) catch return error.InvalidAddress; } if (it.next() != null) return error.InvalidAddress; return .{ .bytes = fields[0..4].*, .port = @as(u16, fields[4]) << 8 | fields[5], };}
/// The text of a 227 reply, whose shape RFC 959 §4.1.2 leaves loose enough/// that every server writes it differently. This is the wording clients have/// the least trouble with.pub fn writePassiveReply(w: *Io.Writer, address: net.Ip4Address) Io.Writer.Error!void { try w.writeAll("Entering Passive Mode ("); try writeHostPort(w, address); try w.writeAll(").");}
/// Reads the address out of a 227 reply.////// The six numbers are found rather than parsed from a fixed position,/// because the sentence around them is not standardised and servers differ on/// the parentheses, the wording and the full stop. What is reliable is that/// the numbers are the last run of digits and commas in the line, so that is/// what this looks for.pub fn parsePassiveReply(text: []const u8) ParseError!net.Ip4Address { const line = text[0 .. std.mem.findScalar(u8, text, '\n') orelse text.len]; // Prefer what is inside the parentheses when there are any: it is the one // part of the reply that is deliberately delimited. if (std.mem.findScalar(u8, line, '(')) |open| { if (std.mem.findScalarPos(u8, line, open + 1, ')')) |close| { return parseHostPort(std.mem.trim(u8, line[open + 1 .. close], " ")); } } // Otherwise take the trailing run of digits and commas. Anything before // it is prose. var end = line.len; while (end > 0 and !std.ascii.isDigit(line[end - 1])) end -= 1; var start = end; while (start > 0 and (std.ascii.isDigit(line[start - 1]) or line[start - 1] == ',')) start -= 1; if (start == end) return error.InvalidAddress; return parseHostPort(line[start..end]);}
// -- EPRT and the 229 reply to EPSV ---------------------------------------
/// The delimiter `EPRT` and `EPSV` put around their fields. RFC 2428 §2 lets/// it be any character in the ASCII range 33 to 126 that does not appear in/// the fields; `|` is what everything uses and no printed address contains it.pub const eprt_delimiter = '|';
/// Writes the argument of an `EPRT` command: `|1|192.0.2.1|21|` for IPv4,/// `|2|2001:db8::1|21|` for IPv6.pub fn writeExtendedHostPort(w: *Io.Writer, address: net.IpAddress) Io.Writer.Error!void { const d = eprt_delimiter; // The address is printed without its port and without an IPv6 scope, // because the port has a field of its own and a scope is meaningless to // the other end of the connection. try w.print("{c}{d}{c}{f}{c}{d}{c}", .{ d, @backingInt(NetworkProtocol.of(address)), d, bare(address), d, address.getPort(), d, });}
/// Formats an address for `{f}` as `EPRT` takes it. See `writeExtendedHostPort`.pub fn extendedHostPort(address: net.IpAddress) ExtendedHostPort { return .{ .address = address };}
pub const ExtendedHostPort = struct { address: net.IpAddress,
pub fn format(ehp: ExtendedHostPort, w: *Io.Writer) Io.Writer.Error!void { return writeExtendedHostPort(w, ehp.address); }};
/// Formats an address on its own, with no port and no brackets.////// `net.IpAddress.format` always prints the port, and an IPv6 address in/// brackets so that the port can be told apart from the colons -- neither of/// which belongs in an `EPRT` field, since the port has a field of its own.pub fn bare(address: net.IpAddress) Bare { return .{ .address = address };}
pub const Bare = struct { address: net.IpAddress,
pub fn format(b: Bare, w: *Io.Writer) Io.Writer.Error!void { switch (b.address) { .ip4 => |a| try w.print("{d}.{d}.{d}.{d}", .{ a.bytes[0], a.bytes[1], a.bytes[2], a.bytes[3] }), // A scope ("%eno1") is left off deliberately: it names an // interface on *this* host, and the peer that has to connect to // the address has no way to make sense of it. .ip6 => |a| { const unresolved: net.Ip6Address.Unresolved = .{ .bytes = a.bytes, .interface_name = null }; try w.print("{f}", .{&unresolved}); }, } }};
/// Reads the argument of an `EPRT` command.pub fn parseExtendedHostPort(text: []const u8) ParseError!net.IpAddress { if (text.len < 2) return error.InvalidAddress; const d = text[0]; // The delimiter is chosen by the sender, so take it from the text rather // than assuming the `|` everyone in fact uses. var it = std.mem.splitScalar(u8, text[1..], d); const protocol_text = it.next() orelse return error.InvalidAddress; const address_text = it.next() orelse return error.InvalidAddress; const port_text = it.next() orelse return error.InvalidAddress;
const protocol: NetworkProtocol = switch (std.fmt.parseInt(u8, protocol_text, 10) catch return error.InvalidAddress) { 1 => .ip4, 2 => .ip6, else => return error.InvalidAddress, }; const port = std.fmt.parseInt(u16, port_text, 10) catch return error.InvalidAddress;
return switch (protocol) { .ip4 => net.IpAddress.parseIp4(address_text, port) catch error.InvalidAddress, .ip6 => net.IpAddress.parseIp6(address_text, port) catch error.InvalidAddress, };}
/// The text of a 229 reply. Only the port is sent: the client already has a/// control connection to this server, so it knows the address to use, and/// sending one again is how a server behind a NAT tells the client to connect/// somewhere it cannot reach.pub fn writeExtendedPassiveReply(w: *Io.Writer, port: u16) Io.Writer.Error!void { const d = eprt_delimiter; try w.print("Entering Extended Passive Mode ({c}{c}{c}{d}{c})", .{ d, d, d, port, d });}
/// Reads the port out of a 229 reply.pub fn parseExtendedPassiveReply(text: []const u8) ParseError!u16 { const line = text[0 .. std.mem.findScalar(u8, text, '\n') orelse text.len]; const open = std.mem.findScalar(u8, line, '(') orelse return error.InvalidAddress; const close = std.mem.findScalarPos(u8, line, open + 1, ')') orelse return error.InvalidAddress; const inside = line[open + 1 .. close]; if (inside.len < 2) return error.InvalidAddress; const d = inside[0]; // `<d><d><d>port<d>`: the protocol and address fields are empty, so the // port is the last field with anything in it. var it = std.mem.splitScalar(u8, inside[1..], d); var port_text: ?[]const u8 = null; while (it.next()) |field| if (field.len != 0) { port_text = field; }; return std.fmt.parseInt(u16, port_text orelse return error.InvalidAddress, 10) catch error.InvalidAddress;}
// -- tests ----------------------------------------------------------------
const testing = std.testing;
fn expectPrints(expected: []const u8, value: anytype) !void { var buffer: [128]u8 = undefined; try testing.expectEqualStrings(expected, try std.fmt.bufPrint(&buffer, "{f}", .{value}));}
test "PORT argument" { const address: net.Ip4Address = .{ .bytes = .{ 192, 0, 2, 1 }, .port = 4141 }; try expectPrints("192,0,2,1,16,45", hostPort(address)); const parsed = try parseHostPort("192,0,2,1,16,45"); try testing.expectEqual(address.bytes, parsed.bytes); try testing.expectEqual(address.port, parsed.port);}
test "PORT with the low port byte alone" { const parsed = try parseHostPort("127,0,0,1,0,20"); try testing.expectEqual(@as(u16, 20), parsed.port);}
test "PORT arguments that are not addresses" { try testing.expectError(error.InvalidAddress, parseHostPort("")); try testing.expectError(error.InvalidAddress, parseHostPort("1,2,3,4,5")); try testing.expectError(error.InvalidAddress, parseHostPort("1,2,3,4,5,6,7")); try testing.expectError(error.InvalidAddress, parseHostPort("1,2,3,4,5,256")); try testing.expectError(error.InvalidAddress, parseHostPort("1,2,3,4,5,x")); try testing.expectError(error.InvalidAddress, parseHostPort("-1,2,3,4,5,6"));}
test "227 replies as servers actually word them" { const cases = [_][]const u8{ // proftpd, vsftpd, pyftpdlib and IIS respectively. "Entering Passive Mode (192,0,2,1,16,45).", "Entering Passive Mode (192,0,2,1,16,45)", "Entering passive mode (192,0,2,1,16,45)", "Entering Passive Mode 192,0,2,1,16,45", }; for (cases) |case| { const parsed = try parsePassiveReply(case); try testing.expectEqual([4]u8{ 192, 0, 2, 1 }, parsed.bytes); try testing.expectEqual(@as(u16, 4141), parsed.port); }}
test "227 round trip" { var buffer: [128]u8 = undefined; var w: Io.Writer = .fixed(&buffer); const address: net.Ip4Address = .{ .bytes = .{ 10, 0, 0, 7 }, .port = 50000 }; try writePassiveReply(&w, address); const parsed = try parsePassiveReply(w.buffered()); try testing.expectEqual(address.bytes, parsed.bytes); try testing.expectEqual(address.port, parsed.port);}
test "227 replies that hold no address" { try testing.expectError(error.InvalidAddress, parsePassiveReply("Entering Passive Mode")); try testing.expectError(error.InvalidAddress, parsePassiveReply("()")); try testing.expectError(error.InvalidAddress, parsePassiveReply(""));}
test "EPRT argument" { try expectPrints("|1|192.0.2.1|4141|", extendedHostPort(.{ .ip4 = .{ .bytes = .{ 192, 0, 2, 1 }, .port = 4141 }, })); try expectPrints("|2|2001:db8::1|4141|", extendedHostPort( try net.IpAddress.parseIp6("2001:db8::1", 4141), ));}
test "EPRT round trip" { for ([_][]const u8{ "192.0.2.1", "2001:db8::1", "::1", "127.0.0.1" }) |text| { const address = try net.IpAddress.parse(text, 4141); var buffer: [128]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeExtendedHostPort(&w, address); const parsed = try parseExtendedHostPort(w.buffered()); try testing.expect(parsed.eql(&address)); try testing.expectEqual(@as(u16, 4141), parsed.getPort()); }}
test "EPRT with a delimiter that is not a pipe" { // RFC 2428 lets the sender pick, and a parser that assumes `|` will one // day meet a client that did. const parsed = try parseExtendedHostPort("!1!192.0.2.1!4141!"); try testing.expectEqual([4]u8{ 192, 0, 2, 1 }, parsed.ip4.bytes); try testing.expectEqual(@as(u16, 4141), parsed.getPort());}
test "EPRT arguments that are not addresses" { try testing.expectError(error.InvalidAddress, parseExtendedHostPort("")); try testing.expectError(error.InvalidAddress, parseExtendedHostPort("|")); try testing.expectError(error.InvalidAddress, parseExtendedHostPort("|1|192.0.2.1|")); try testing.expectError(error.InvalidAddress, parseExtendedHostPort("|3|192.0.2.1|21|")); try testing.expectError(error.InvalidAddress, parseExtendedHostPort("|1|not an address|21|")); try testing.expectError(error.InvalidAddress, parseExtendedHostPort("|1|192.0.2.1|99999|"));}
test "229 reply" { var buffer: [128]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try writeExtendedPassiveReply(&w, 6446); try testing.expectEqualStrings("Entering Extended Passive Mode (|||6446|)", w.buffered()); try testing.expectEqual(@as(u16, 6446), try parseExtendedPassiveReply(w.buffered()));}
test "229 replies as servers actually word them" { try testing.expectEqual(@as(u16, 6446), try parseExtendedPassiveReply( "Entering Extended Passive Mode (|||6446|).", )); // Some servers fill in the family and address even though RFC 2428 §3 // says not to. The port is still the last field with anything in it. try testing.expectEqual(@as(u16, 6446), try parseExtendedPassiveReply( "Entering Extended Passive Mode (|1|192.0.2.1|6446|)", ));}
test "229 replies that hold no port" { try testing.expectError(error.InvalidAddress, parseExtendedPassiveReply("no parentheses")); try testing.expectError(error.InvalidAddress, parseExtendedPassiveReply("(|||)")); try testing.expectError(error.InvalidAddress, parseExtendedPassiveReply("(|||99999|)"));}