Something went wrong. Try again.
A TFTP server and client library for Zig 0.16: RFC 1350 with blksize, timeout and tsize options, netascii, fuzz-tested.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352// SPDX-FileCopyrightText: © 2022 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A demonstration of the library: a TFTP server, and a client.//!//! ```console//! zig-tftp [serve [ADDRESS]]//! zig-tftp get SERVER REMOTE [LOCAL] [OPTIONS]//! zig-tftp put SERVER LOCAL [REMOTE] [OPTIONS]//! ```//!//! The server listens on 127.0.0.1 port 6969 unless told otherwise. Writes//! are kept in memory and discarded, and every read returns the text of//! RFC 1350. A filename beginning with `bad` is refused either way.//!//! The client talks to SERVER, an IP address with the port defaulting to 69.//! LOCAL defaults to the last component of REMOTE, and `-` is standard output//! for `get` and standard input for `put`.
const std = @import("std");const tftp = @import("tftp");
const log = std.log.scoped(.main);
/// The client says how a transfer ended, so the library saying it again at/// `info` is only noise.pub const std_options: std.Options = .{ .log_scope_levels = &.{.{ .scope = .transfer, .level = .warn }},};
const usage = \\usage: zig-tftp [serve [ADDRESS]] \\ zig-tftp get SERVER REMOTE [LOCAL] [OPTIONS] \\ zig-tftp put SERVER LOCAL [REMOTE] [OPTIONS] \\ \\ADDRESS is where the demonstration server listens (default 127.0.0.1:6969). \\SERVER is the address of the server to talk to; the port defaults to 69. \\LOCAL defaults to the last component of REMOTE; `-` is stdout or stdin. \\ \\OPTIONS: \\ --mode octet|netascii how the file is represented (default octet) \\ --blksize N ask for a block size of N bytes (8 to 65464) \\ --timeout N ask for a retransmission interval of N seconds \\ --tsize ask for the size (get) or send it (put) \\;
/// What the command line asked for.const Command = union(enum) { serve: std.Io.net.IpAddress, get: Transfer, put: Transfer,
/// A `get` or `put`: the server, the file's name there and here, and the /// options to ask for. const Transfer = struct { server: std.Io.net.IpAddress, remote: []const u8, local: []const u8, mode: tftp.Packet.Mode = .octet, blocksize: ?u16 = null, timeout: ?u8 = null, size: bool = false, };
const Error = error{Usage};
/// Parses `args`, which do not include the program's name. fn parse(args: []const []const u8) Error!Command { if (args.len == 0) return .{ .serve = default_address }; const verb = args[0]; if (std.mem.eql(u8, verb, "serve")) { if (args.len > 2) return error.Usage; return .{ .serve = if (args.len == 2) try address(args[1], 6969) else default_address }; } const uploading = std.mem.eql(u8, verb, "put"); if (!uploading and !std.mem.eql(u8, verb, "get")) return error.Usage;
var positional: [3][]const u8 = undefined; var count: usize = 0; var mode: tftp.Packet.Mode = .octet; var blocksize: ?u16 = null; var timeout: ?u8 = null; var size = false;
var index: usize = 1; while (index < args.len) : (index += 1) { const arg = args[index]; if (std.mem.eql(u8, arg, "--tsize")) { size = true; } else if (std.mem.eql(u8, arg, "--mode") or std.mem.eql(u8, arg, "--blksize") or std.mem.eql(u8, arg, "--timeout")) { index += 1; if (index == args.len) return error.Usage; const value = args[index]; if (std.mem.eql(u8, arg, "--mode")) { mode = if (std.mem.eql(u8, value, "octet")) .octet else if (std.mem.eql(u8, value, "netascii")) .netascii else return error.Usage; } else if (std.mem.eql(u8, arg, "--blksize")) { const b = std.fmt.parseUnsigned(u16, value, 10) catch return error.Usage; if (b < 8 or b > 65464) return error.Usage; blocksize = b; } else { const t = std.fmt.parseUnsigned(u8, value, 10) catch return error.Usage; if (t < 1) return error.Usage; timeout = t; } } else if (std.mem.startsWith(u8, arg, "--")) { return error.Usage; } else { if (count == positional.len) return error.Usage; positional[count] = arg; count += 1; } } if (count < 2) return error.Usage;
// `get SERVER REMOTE [LOCAL]`, and `put SERVER LOCAL [REMOTE]`: the // one named first is the source, and the destination defaults to its // last component. const source = positional[1]; const destination = if (count == 3) positional[2] else basename(source); if (destination.len == 0) return error.Usage; const transfer: Transfer = .{ .server = try address(positional[0], 69), .remote = if (uploading) destination else source, .local = if (uploading) source else destination, .mode = mode, .blocksize = blocksize, .timeout = timeout, .size = size, }; return if (uploading) .{ .put = transfer } else .{ .get = transfer }; }
const default_address = std.Io.net.IpAddress.parseLiteral("127.0.0.1:6969") catch unreachable;
/// An IP address, with or without a port, and `port` if without. A bare /// address is tried first: `parseLiteral` accepts one too, as port zero. fn address(text: []const u8, port: u16) Error!std.Io.net.IpAddress { return std.Io.net.IpAddress.parse(text, port) catch std.Io.net.IpAddress.parseLiteral(text) catch error.Usage; }
/// The last component of a path, which is what a file is called here when /// only its name there was given. fn basename(path: []const u8) []const u8 { const start = if (std.mem.findScalarLast(u8, path, '/')) |slash| slash + 1 else 0; return path[start..]; }};
/// Runs the demonstration server, or a client, as the command line says.pub fn main(init: std.process.Init) !void { const io = init.io; const alloc = init.gpa;
const args = try init.minimal.args.toSlice(init.arena.allocator()); const command = Command.parse(args[1..]) catch { std.debug.print("{s}", .{usage}); std.process.exit(2); };
switch (command) { .serve => |address| { var app: App = .{}; var server: tftp.Server(App) = .init(&app, address); log.info("listening on {f}", .{address}); try server.run(io, alloc); }, .get => |transfer| get(io, transfer) catch |err| exit(err), .put => |transfer| put(io, transfer) catch |err| exit(err), }}
/// What a failed `get` or `put` says as it goes.var diagnostics: tftp.Client.Diagnostics = .{};
fn exit(err: anyerror) noreturn { switch (err) { error.ErrorReceived => std.debug.print("server: {t}: {s}\n", .{ diagnostics.code, diagnostics.message() }), error.Timeout => std.debug.print("the server stopped answering\n", .{}), else => std.debug.print("failed: {t}\n", .{err}), } std.process.exit(1);}
fn get(io: std.Io, transfer: Command.Transfer) !void { const to_stdout = std.mem.eql(u8, transfer.local, "-"); const file = if (to_stdout) std.Io.File.stdout() else try std.Io.Dir.cwd().createFile(io, transfer.local, .{}); defer if (!to_stdout) file.close(io); var buffer: [64 * 1024]u8 = undefined; var writer = if (to_stdout) file.writerStreaming(io, &buffer) else file.writer(io, &buffer);
const client: tftp.Client = .init(transfer.server); const result = try client.get(io, transfer.remote, &writer.interface, .{ .mode = transfer.mode, .blocksize = transfer.blocksize, .timeout = transfer.timeout, .size = transfer.size, .diagnostics = &diagnostics, }); report("received", transfer.remote, result);}
fn put(io: std.Io, transfer: Command.Transfer) !void { const from_stdin = std.mem.eql(u8, transfer.local, "-"); const file = if (from_stdin) std.Io.File.stdin() else try std.Io.Dir.cwd().openFile(io, transfer.local, .{}); defer if (!from_stdin) file.close(io); var buffer: [64 * 1024]u8 = undefined; var reader = if (from_stdin) file.readerStreaming(io, &buffer) else file.reader(io, &buffer);
// The size as sent, which in netascii mode nobody knows until it has // been sent, so it is only offered in octet mode, and only for a file. const size: ?u64 = if (transfer.size and transfer.mode == .octet and !from_stdin) (try file.stat(io)).size else null; if (transfer.size and size == null) log.warn("--tsize needs a file in octet mode; not sending one", .{});
const client: tftp.Client = .init(transfer.server); const result = try client.put(io, transfer.remote, &reader.interface, .{ .mode = transfer.mode, .blocksize = transfer.blocksize, .timeout = transfer.timeout, .size = size, .diagnostics = &diagnostics, }); report("sent", transfer.remote, result);}
/// Says how a transfer went, on standard error so that `get ... -` leaves/// standard output to the file.fn report(verb: []const u8, name: []const u8, result: tftp.Client.Result) void { std.debug.print("{s} {s}: {d} bytes", .{ verb, name, result.bytes }); if (result.options.blocksize) |b| std.debug.print(", block size {d}", .{b}); if (result.options.timeout) |t| std.debug.print(", timeout {d}s", .{t}); if (result.options.transfer_size) |t| std.debug.print(", size {d}", .{t}); std.debug.print("\n", .{});}
test "the command line" { const t = std.testing; try t.expectEqual(Command.default_address, (try Command.parse(&.{})).serve); try t.expectEqual(6969, (try Command.parse(&.{ "serve", "0.0.0.0" })).serve.getPort()); try t.expectEqual(1069, (try Command.parse(&.{ "serve", "[::]:1069" })).serve.getPort());
const g = (try Command.parse(&.{ "get", "192.0.2.1", "boot/pxelinux.0", "--blksize", "1428", "--tsize" })).get; try t.expectEqual(69, g.server.getPort()); try t.expectEqualStrings("boot/pxelinux.0", g.remote); try t.expectEqualStrings("pxelinux.0", g.local); try t.expectEqual(1428, g.blocksize.?); try t.expect(g.size);
const p = (try Command.parse(&.{ "put", "--mode", "netascii", "192.0.2.1:1069", "notes.txt", "upload/notes.txt" })).put; try t.expectEqual(1069, p.server.getPort()); try t.expectEqualStrings("notes.txt", p.local); try t.expectEqualStrings("upload/notes.txt", p.remote); try t.expectEqual(.netascii, p.mode);
const bad = [_][]const []const u8{ &.{"fetch"}, &.{ "get", "192.0.2.1" }, &.{ "get", "not an address", "f" }, &.{ "get", "192.0.2.1", "f", "--blksize", "7" }, &.{ "get", "192.0.2.1", "f", "--mode", "mail" }, &.{ "get", "192.0.2.1", "f", "--timeout" }, &.{ "get", "192.0.2.1", "dir/" }, &.{ "get", "192.0.2.1", "a", "b", "c" }, &.{ "serve", "a", "b" }, }; for (bad) |args| try t.expectError(error.Usage, Command.parse(args));}
/// The application behind the demonstration server. See `tftp.Server` for what/// the server asks of it.pub const App = struct { /// A write request, collected in memory. pub const Write = struct { /// Where the file's contents accumulate. interface: std.Io.Writer.Allocating, /// The requested filename, owned by the request. filename: []const u8,
/// A request for `filename`, which is copied. pub fn init(alloc: std.mem.Allocator, filename: []const u8) !Write { return .{ .interface = .init(alloc), .filename = try alloc.dupe(u8, filename), }; }
/// The writer the server delivers the file's contents to. pub fn writer(self: *Write, _: std.Io, _: std.mem.Allocator) !*std.Io.Writer { return &self.interface.writer; }
/// Logs how much was received. pub fn finish(self: *Write, _: std.Io) !void { log.warn("{s} finished, {d} bytes written", .{ self.filename, self.interface.written().len }); }
/// Frees the filename and everything received. pub fn deinit(self: *Write, _: std.Io, alloc: std.mem.Allocator) void { alloc.free(self.filename); self.interface.deinit(); } };
/// Logs who asked, and accepts a write of any file whose name does not /// begin with `bad`. pub fn writeTo(_: *const App, _: std.Io, alloc: std.mem.Allocator, request: tftp.Request) !Write { log.info("{f} writes {s} ({t}) via {f}", .{ request.remote, request.filename, request.mode, request.local }); if (std.mem.startsWith(u8, request.filename, "bad")) return error.PermissionDenied; return try .init(alloc, request.filename); }
/// A read request, answered from the embedded text of RFC 1350. pub const Read = struct { /// A reader over the embedded text. interface: std.Io.Reader, /// The requested filename, owned by the request. filename: []const u8,
/// A request for `filename`, which is copied. pub fn init(alloc: std.mem.Allocator, filename: []const u8) !Read { return .{ .interface = .fixed(@embedFile("rfc1350.txt")), .filename = try alloc.dupe(u8, filename), }; }
/// The reader the server takes the file's contents from. pub fn reader(self: *Read, _: std.Io, _: std.mem.Allocator) !*std.Io.Reader { return &self.interface; }
/// The length of the embedded text. pub fn size(self: *Read, _: std.Io) ?u64 { return self.interface.buffer.len; }
/// Frees the filename. pub fn deinit(self: *Read, _: std.Io, alloc: std.mem.Allocator) void { alloc.free(self.filename); } };
/// Logs who asked, and accepts a read of any file whose name does not /// begin with `bad`. pub fn readFrom(_: *const App, _: std.Io, alloc: std.mem.Allocator, request: tftp.Request) !Read { log.info("{f} reads {s} ({t}) via {f}", .{ request.remote, request.filename, request.mode, request.local }); if (std.mem.startsWith(u8, request.filename, "bad")) return error.PermissionDenied; return try .init(alloc, request.filename); }};