// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The TFTP client. const std = @import("std"); const Packet = @import("packet.zig").Packet; const netascii = @import("netascii.zig"); const transfer_ = @import("transfer.zig"); const Transfer = transfer_.Transfer; /// A TFTP client for one server. /// /// It holds nothing but the server's address, so one client can run any /// number of transfers, one after another or at once; each has a socket and /// a port of its own for as long as it lasts. /// /// ```zig /// const client: tftp.Client = .init(try .parseLiteral("192.0.2.1:69")); /// var diagnostics: tftp.Client.Diagnostics = .{}; /// const result = client.get(io, "pxelinux.0", &file_writer.interface, .{ /// .blocksize = 1428, /// .diagnostics = &diagnostics, /// }) catch |err| switch (err) { /// error.ErrorReceived => { /// std.log.err("server said {t}: {s}", .{ diagnostics.code, diagnostics.message() }); /// return err; /// }, /// else => return err, /// }; /// ``` pub const Client = struct { /// The server's address and port, usually 69. server: std.Io.net.IpAddress, /// What the server said when it ended a transfer with an ERROR packet, /// which is `error.ErrorReceived` to the caller. pub const Diagnostics = transfer_.Diagnostics; /// A client for the server at `server`. pub fn init(server: std.Io.net.IpAddress) Client { return .{ .server = server }; } /// How a transfer went. pub const Result = struct { /// The file's bytes as they crossed the network. In `netascii` mode /// that is not the same count as the file's own. bytes: u64, /// The options the server acknowledged, which are the ones the /// transfer ran under. A `get` that asked for the size finds it in /// `options.transfer_size`, if the server knew it. options: Packet.Options, }; /// What `get` asks for. pub const GetOptions = struct { /// How the file is represented on the network. In `netascii` and /// `mail` modes what arrives is decoded into local text before it /// reaches the writer. mode: Packet.Mode = .octet, /// The block size to ask for (RFC 2348), from 8 to 65464. The server /// may answer with a smaller one, or decline. blocksize: ?u16 = null, /// The retransmission interval to ask for, in seconds (RFC 2349). timeout: ?u8 = null, /// Whether to ask the server for the file's size (RFC 2349). size: bool = false, /// Where to record the server's ERROR, if it sends one. diagnostics: ?*Diagnostics = null, }; /// Downloads `filename` from the server into `writer`, which is flushed /// once the whole file has been written to it. /// /// Fails with `error.ErrorReceived` if the server refuses or ends the /// transfer, with what it said in `options.diagnostics`, and with /// `error.Timeout` if it stops answering. pub fn get( self: Client, io: std.Io, filename: []const u8, writer: *std.Io.Writer, options: GetOptions, ) !Result { const requested: Packet.Options = .{ .blocksize = options.blocksize, .timeout = options.timeout, .transfer_size = if (options.size) 0 else null, }; const socket = try self.bind(io); defer socket.close(io); var transfer: Transfer = .init(io, socket, self.server, false, options.mode, .{}); transfer.diagnostics = options.diagnostics; var netascii_buffer: [128]u8 = undefined; var netascii_decoder: netascii.Decoder = undefined; const destination = switch (options.mode) { .netascii, .mail => destination: { netascii_decoder = .init(writer, &netascii_buffer); break :destination &netascii_decoder.interface; }, .octet => writer, }; const outcome = try transfer_.receiveFile( &transfer, destination, &netascii_decoder, .{ .rrq = .{ .filename = filename, .mode = options.mode, .options = requested } }, if (requested.empty()) null else requested, .{}, NoFinish{}, ); return .{ .bytes = outcome.bytes, .options = outcome.options }; } /// What `put` asks for. pub const PutOptions = struct { /// How the file is represented on the network. In `netascii` and /// `mail` modes what the reader supplies is local text, encoded /// before it is sent. mode: Packet.Mode = .octet, /// The block size to ask for (RFC 2348), from 8 to 65464. The server /// may answer with a smaller one, or decline. blocksize: ?u16 = null, /// The retransmission interval to ask for, in seconds (RFC 2349). timeout: ?u8 = null, /// The size of the file, to tell the server (RFC 2349), which may /// refuse a file it has no room for before any of it is sent. In /// `netascii` mode it is the size as sent, not as read. size: ?u64 = null, /// Where to record the server's ERROR, if it sends one. diagnostics: ?*Diagnostics = null, }; /// Uploads what `reader` supplies to the server as `filename`. The /// reader must have a buffer of at least two bytes in `netascii` mode, /// since encoding looks two bytes ahead. /// /// Fails with `error.ErrorReceived` if the server refuses or ends the /// transfer, with what it said in `options.diagnostics`, and with /// `error.Timeout` if it stops answering. pub fn put( self: Client, io: std.Io, filename: []const u8, reader: *std.Io.Reader, options: PutOptions, ) !Result { const requested: Packet.Options = .{ .blocksize = options.blocksize, .timeout = options.timeout, .transfer_size = options.size, }; const socket = try self.bind(io); defer socket.close(io); var transfer: Transfer = .init(io, socket, self.server, false, options.mode, .{}); transfer.diagnostics = options.diagnostics; var netascii_buffer: [128]u8 = undefined; var netascii_encoder: netascii.EncodeReader = undefined; const source: *std.Io.Reader = switch (options.mode) { .netascii, .mail => source: { netascii_encoder = .init(reader, &netascii_buffer); break :source &netascii_encoder.interface; }, .octet => reader, }; const outcome = try transfer_.sendFile( &transfer, source, .{ .wrq = .{ .filename = filename, .mode = options.mode, .options = requested } }, if (requested.empty()) null else requested, .{}, ); return .{ .bytes = outcome.bytes, .options = outcome.options }; } /// A socket for one transfer, on any port of the unspecified address of /// the server's family. fn bind(self: Client, io: std.Io) !std.Io.net.Socket { const any: std.Io.net.IpAddress = switch (self.server) { .ip4 => .{ .ip4 = .{ .bytes = @splat(0), .port = 0 } }, .ip6 => .{ .ip6 = .{ .bytes = @splat(0), .port = 0 } }, }; return any.bind(io, .{ .mode = .dgram, .protocol = .udp }); } /// A client has nothing to finish once a download is written. const NoFinish = struct { pub fn finish(_: NoFinish) !void {} }; }; // -- tests ------------------------------------------------------------------- const testing = std.testing; const Server = @import("server.zig").Server; const Request = @import("server.zig").Request; /// An application serving one file and collecting another, for the client /// to talk to. const TestApp = struct { content: []const u8, written: std.Io.Writer.Allocating, capacity: ?u64 = null, pub const Read = struct { interface: std.Io.Reader, pub fn reader(self: *Read, _: std.Io, _: std.mem.Allocator) !*std.Io.Reader { return &self.interface; } pub fn size(self: *Read, _: std.Io) ?u64 { return self.interface.buffer.len; } pub fn deinit(_: *Read, _: std.Io, _: std.mem.Allocator) void {} }; pub fn readFrom(self: *TestApp, _: std.Io, _: std.mem.Allocator, request: Request) !Read { if (!std.mem.eql(u8, request.filename, "file")) return error.FileNotFound; return .{ .interface = .fixed(self.content) }; } pub const Write = struct { app: *TestApp, pub fn writer(self: *Write, _: std.Io, _: std.mem.Allocator) !*std.Io.Writer { return &self.app.written.writer; } pub fn reserve(self: *Write, _: std.Io, size: u64) !void { if (size > self.app.capacity orelse return) return error.NoSpaceLeft; } pub fn finish(_: *Write, _: std.Io) !void {} pub fn deinit(_: *Write, _: std.Io, _: std.mem.Allocator) void {} }; pub fn writeTo(self: *TestApp, _: std.Io, _: std.mem.Allocator, _: Request) !Write { return .{ .app = self }; } }; /// A free UDP port on the loopback interface, found by binding and letting /// go of it. fn freePort(io: std.Io) !std.Io.net.IpAddress { const any = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0"); const probe = try any.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer probe.close(io); return probe.address; } /// A server of `TestApp` running on a free port, and a client for it. const Pair = struct { threaded: std.Io.Threaded, app: TestApp, server: Server(TestApp), future: std.Io.Future(anyerror!void), client: Client, fn start(self: *Pair, content: []const u8) !void { // The server logs every transfer that fails, and failing is what // several of these are for. testing.log_level = .err; self.threaded = .init(testing.allocator, .{}); errdefer self.threaded.deinit(); const io = self.threaded.io(); const address = try freePort(io); self.app = .{ .content = content, .written = .init(testing.allocator) }; self.server = .init(&self.app, address); self.future = try io.concurrent(runServer, .{self}); self.client = .init(address); } fn runServer(self: *Pair) anyerror!void { return self.server.run(self.threaded.io(), testing.allocator); } fn getIo(self: *Pair) std.Io { return self.threaded.io(); } fn stop(self: *Pair) void { self.future.cancel(self.threaded.io()) catch {}; self.app.written.deinit(); self.threaded.deinit(); testing.log_level = .warn; } }; test "get" { var pair: Pair = undefined; // Three blocks at the default size, the last one short. const hex = "0123456789abcdef"; const content = std.mem.asBytes(&@as([70][hex.len]u8, @splat(hex.*))); try pair.start(content); defer pair.stop(); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const result = try pair.client.get(pair.getIo(), "file", &out.writer, .{}); try testing.expectEqualStrings(content, out.written()); try testing.expectEqual(content.len, result.bytes); try testing.expect(result.options.empty()); } test "get with options" { var pair: Pair = undefined; try pair.start("abcdefghijklmnop"); defer pair.stop(); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); // Sixteen bytes in blocks of eight: two full blocks, then an empty one. const result = try pair.client.get(pair.getIo(), "file", &out.writer, .{ .blocksize = 8, .timeout = 2, .size = true }); try testing.expectEqualStrings("abcdefghijklmnop", out.written()); try testing.expectEqual(Packet.Options{ .blocksize = 8, .timeout = 2, .transfer_size = 16 }, result.options); } test "get in netascii" { var pair: Pair = undefined; try pair.start("one\ntwo\n"); defer pair.stop(); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const result = try pair.client.get(pair.getIo(), "file", &out.writer, .{ .mode = .netascii }); // Encoded by the server, and decoded again by the client. try testing.expectEqualStrings("one\ntwo\n", out.written()); try testing.expectEqual("one\r\ntwo\r\n".len, result.bytes); } test "get of a file the server does not have" { var pair: Pair = undefined; try pair.start(""); defer pair.stop(); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var diagnostics: Client.Diagnostics = .{}; try testing.expectError(error.ErrorReceived, pair.client.get(pair.getIo(), "nope", &out.writer, .{ .diagnostics = &diagnostics })); try testing.expectEqual(.file_not_found, diagnostics.code); try testing.expectEqualStrings("File not found", diagnostics.message()); } test "put" { var pair: Pair = undefined; try pair.start(""); defer pair.stop(); const phrase = "put me "; const content = std.mem.asBytes(&@as([100][phrase.len]u8, @splat(phrase.*))); var source: std.Io.Reader = .fixed(content); const result = try pair.client.put(pair.getIo(), "file", &source, .{ .blocksize = 64, .size = content.len }); try testing.expectEqual(Packet.Options{ .blocksize = 64, .transfer_size = content.len }, result.options); try testing.expectEqual(content.len, result.bytes); try testing.expectEqualStrings(content, pair.app.written.written()); } test "put in netascii" { var pair: Pair = undefined; try pair.start(""); defer pair.stop(); var source: std.Io.Reader = .fixed("one\ntwo\n"); _ = try pair.client.put(pair.getIo(), "file", &source, .{ .mode = .netascii }); try testing.expectEqualStrings("one\ntwo\n", pair.app.written.written()); } test "put refused for its size" { var pair: Pair = undefined; try pair.start(""); defer pair.stop(); pair.app.capacity = 4; var source: std.Io.Reader = .fixed("hello"); var diagnostics: Client.Diagnostics = .{}; try testing.expectError(error.ErrorReceived, pair.client.put(pair.getIo(), "file", &source, .{ .size = 5, .diagnostics = &diagnostics })); try testing.expectEqual(.disk_full, diagnostics.code); try testing.expectEqual(0, pair.app.written.written().len); } /// A server of one scripted exchange: it waits for a request, answers it /// from a port of its own with `answer`, and records what the client sends /// back. const Fake = struct { threaded: std.Io.Threaded, listener: std.Io.net.Socket, future: std.Io.Future(anyerror!Packet), reply_buf: Packet.Buffer = undefined, fn start(self: *Fake, answer: Packet) !void { self.threaded = .init(testing.allocator, .{}); const io = self.threaded.io(); const any = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0"); self.listener = try any.bind(io, .{ .mode = .dgram, .protocol = .udp }); self.future = try io.concurrent(serve, .{ self, answer }); } fn serve(self: *Fake, answer: Packet) anyerror!Packet { const io = self.threaded.io(); var buf: Packet.Buffer = undefined; const request = try self.listener.receive(io, &buf); const any = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0"); const socket = try any.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer socket.close(io); var out: Packet.Buffer = undefined; try socket.send(io, &request.from, try answer.encode(&out)); const reply = try socket.receive(io, &buf); return Packet.decode(reply.data, &self.reply_buf, .{ .mode = .octet, .blocksize = 65464 }); } fn getIo(self: *Fake) std.Io { return self.threaded.io(); } fn stop(self: *Fake) void { _ = self.future.cancel(self.threaded.io()) catch {}; self.listener.close(self.threaded.io()); self.threaded.deinit(); } }; test "an OACK raising the block size is refused" { var fake: Fake = undefined; try fake.start(.{ .oack = .{ .options = .{ .blocksize = 2048 } } }); defer fake.stop(); testing.log_level = .err; defer testing.log_level = .warn; const client: Client = .init(fake.listener.address); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try testing.expectError(error.BadOptionAcknowledgment, client.get(fake.getIo(), "f", &out.writer, .{ .blocksize = 1024 })); // RFC 2347: the client ends it with error 8. const reply = try fake.future.await(fake.getIo()); try testing.expect(reply == .err); try testing.expectEqual(.term_option, reply.err.code); } test "an OACK to a client that asked for nothing is refused" { var fake: Fake = undefined; try fake.start(.{ .oack = .{ .options = .{ .blocksize = 512 } } }); defer fake.stop(); testing.log_level = .err; defer testing.log_level = .warn; const client: Client = .init(fake.listener.address); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); try testing.expectError(error.IllegalPacketType, client.get(fake.getIo(), "f", &out.writer, .{})); const reply = try fake.future.await(fake.getIo()); try testing.expectEqual(.illegal_operation, reply.err.code); } test "a server that ignores the options is answered at the default block size" { // A server from before RFC 2347 goes straight to the data, which // declines every option. var fake: Fake = undefined; try fake.start(.{ .data = .{ .block = 1, .mode = .octet, .data = "short" } }); defer fake.stop(); const client: Client = .init(fake.listener.address); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const result = try client.get(fake.getIo(), "f", &out.writer, .{ .blocksize = 1024, .size = true }); try testing.expectEqualStrings("short", out.written()); try testing.expect(result.options.empty()); const reply = try fake.future.await(fake.getIo()); try testing.expectEqual(1, reply.ack.block); } test "against tftp-hpa's server" { // The reference implementation, from the development shell. Without it // on the PATH there is nothing to test against. var threaded: std.Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); const root = try tmp.dir.realPathFileAlloc(io, ".", testing.allocator); defer testing.allocator.free(root); // Larger than a block at any size asked for below, and not a multiple of // any of them. const content = try testing.allocator.alloc(u8, 70_001); defer testing.allocator.free(content); for (content, 0..) |*byte, index| byte.* = @truncate(index *% 7); try tmp.dir.writeFile(io, .{ .sub_path = "binary", .data = content }); try tmp.dir.writeFile(io, .{ .sub_path = "text", .data = "one\ntwo\n" }); const address = try freePort(io); var address_buf: [64]u8 = undefined; const listen = try std.fmt.bufPrint(&address_buf, "{f}", .{address}); const user = testing.environ.getPosix("USER") orelse return error.SkipZigTest; // Spawned through the testing `Io`, which carries the environment, and // so the PATH to find it on; a bare `Io.Threaded` has none. var child = std.process.spawn(testing.io, .{ .argv = &.{ "in.tftpd", "-L", "-a", listen, "-c", "-p", "-u", user, root }, }) catch |err| switch (err) { error.FileNotFound => return error.SkipZigTest, else => |e| return e, }; defer child.kill(testing.io); const client: Client = .init(address); var path_buf: [std.fs.max_path_bytes]u8 = undefined; { const path = try std.fmt.bufPrint(&path_buf, "{s}/binary", .{root}); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); const result = try client.get(io, path, &out.writer, .{ .blocksize = 1428, .size = true }); try testing.expectEqualSlices(u8, content, out.written()); try testing.expectEqual(Packet.Options{ .blocksize = 1428, .transfer_size = content.len }, result.options); } { const path = try std.fmt.bufPrint(&path_buf, "{s}/text", .{root}); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); _ = try client.get(io, path, &out.writer, .{ .mode = .netascii }); try testing.expectEqualStrings("one\ntwo\n", out.written()); } { const path = try std.fmt.bufPrint(&path_buf, "{s}/uploaded", .{root}); var source: std.Io.Reader = .fixed(content); const result = try client.put(io, path, &source, .{ .blocksize = 512, .timeout = 2, .size = content.len }); try testing.expectEqual(Packet.Options{ .blocksize = 512, .timeout = 2, .transfer_size = content.len }, result.options); const written = try tmp.dir.readFileAlloc(io, "uploaded", testing.allocator, .unlimited); defer testing.allocator.free(written); try testing.expectEqualSlices(u8, content, written); } { const path = try std.fmt.bufPrint(&path_buf, "{s}/missing", .{root}); var out: std.Io.Writer.Allocating = .init(testing.allocator); defer out.deinit(); var diagnostics: Client.Diagnostics = .{}; testing.log_level = .err; defer testing.log_level = .warn; try testing.expectError(error.ErrorReceived, client.get(io, path, &out.writer, .{ .diagnostics = &diagnostics })); try testing.expectEqual(.file_not_found, diagnostics.code); } }