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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561// SPDX-FileCopyrightText: © 2022 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The machinery a transfer runs on, whichever end started it.//!//! A client downloading a file does what a server receiving an upload does,//! and a client uploading one does what a server serving a download does://! after the opening exchange, the side that receives acknowledges blocks and//! the side that sends retransmits them, and nothing else about the two ends//! differs. So `receiveFile` and `sendFile` are both ends' loops, and each is//! handed the packet that opens its side of the exchange://!//! | End | First packet | May an OACK answer it? |//! | ------------------- | ---------------- | ---------------------- |//! | Server, receiving | ACK 0 or OACK | No |//! | Client, receiving | RRQ | Yes, answered by ACK 0 |//! | Server, sending | OACK, or nothing | No |//! | Client, sending | WRQ | Yes, answered by DATA 1|//!//! What they share is everything that took getting right: retransmission,//! duplicates, block numbers that wrap, the final acknowledgment that may be//! lost, packets from the wrong port, and telling the other end why a//! transfer failed.
const std = @import("std");const testing = std.testing;
const Packet = @import("packet.zig").Packet;const netascii = @import("netascii.zig");
const log = std.log.scoped(.transfer);
/// What the other end said when it ended a transfer with an ERROR packet.pub const Diagnostics = struct { /// The error code it sent. code: Packet.ErrorCode = .not_defined, /// The first bytes of the message it sent. buffer: [255]u8 = undefined, len: usize = 0,
/// The message the other end sent, which may have been cut short. pub fn message(self: *const Diagnostics) []const u8 { return self.buffer[0..self.len]; }
fn record(self: *Diagnostics, err: Packet.Err) void { self.code = err.code; const msg = err.msg orelse ""; self.len = @min(msg.len, self.buffer.len); @memcpy(self.buffer[0..self.len], msg[0..self.len]); }};
/// How a transfer that finished went.pub const Outcome = struct { /// The file's bytes as they crossed the network, which in `netascii` /// mode is not the same count as the file's own. bytes: u64, /// The options in force: those the other end acknowledged, or none. options: Packet.Options,};
/// Sends `packet` to `remote` over `socket`.pub fn sendTo(io: std.Io, socket: std.Io.net.Socket, remote: *const std.Io.net.IpAddress, packet: Packet) !void { var buf: Packet.Buffer = undefined; try socket.send(io, remote, try packet.encode(&buf));}
/// The ERROR packet that tells the other end a transfer failed with `err`,/// using the closest code RFC 1350 has.pub fn errorPacket(err: anyerror) Packet.Err { return switch (err) { error.FileNotFound => .{ .code = .file_not_found }, error.PermissionDenied, error.AccessDenied => .{ .code = .access_violation }, error.NoSpaceLeft, error.DiskQuota, error.FileTooBig => .{ .code = .disk_full }, error.PathAlreadyExists => .{ .code = .file_exists }, error.MalformedNetascii => .{ .code = .illegal_operation, .msg = "Malformed netascii" }, error.BadOptionAcknowledgment => .{ .code = .term_option, .msg = "Unacceptable option acknowledgment" }, error.ReadFailed => .{ .code = .not_defined, .msg = "Read failed" }, error.WriteFailed => .{ .code = .not_defined, .msg = "Write failed" }, else => .{ .code = .not_defined, .msg = @errorName(err) }, };}
/// The ERROR packet that answers a packet which failed to decode with `err`.pub fn malformed(err: Packet.DecodeErrors) Packet.Err { return .{ .code = .illegal_operation, .msg = switch (err) { error.InvalidOpcode => "Unknown opcode", error.InvalidMode => "Unknown transfer mode", error.PacketTooLong => "DATA longer than the block size", else => "Malformed packet", } };}
/// Whether two addresses are the same host, whatever their ports.fn sameHost(a: std.Io.net.IpAddress, b: std.Io.net.IpAddress) bool { var x = a; var y = b; x.setPort(0); y.setPort(0); return x.eql(&y);}
/// The network side of a single transfer: its socket, the other end, and/// when to give up on it.pub const Transfer = struct { io: std.Io, /// The socket of this transfer alone. socket: std.Io.net.Socket, /// The other end. Its address and port together are its transfer ID. remote: std.Io.net.IpAddress, /// Whether `remote`'s port is the other end's transfer ID yet. A server /// knows its client's from the request. A client sends its request to /// the server's well known port and learns the transfer ID from the /// first answer, which may come from any port on the server's host. locked: bool, retransmit: Retransmit, /// How the other end's packets are decoded. decode_options: Packet.DecodeOptions, /// Where an ERROR from the other end is recorded, if anywhere. diagnostics: ?*Diagnostics = null,
/// A transfer in `mode` with `remote` over `socket`, under `options`. pub fn init( io: std.Io, socket: std.Io.net.Socket, remote: std.Io.net.IpAddress, locked: bool, mode: Packet.Mode, options: Packet.Options, ) Transfer { return .{ .io = io, .socket = socket, .remote = remote, .locked = locked, .retransmit = .init(options.timeout), .decode_options = .{ .mode = mode, .blocksize = options.blocksize }, }; }
/// Puts the options the other end acknowledged into force. fn negotiated(self: *Transfer, options: Packet.Options) void { self.retransmit = .init(options.timeout); self.decode_options.blocksize = options.blocksize; }
/// Sends `packet` to the other end. pub fn send(self: *const Transfer, packet: Packet) !void { try sendTo(self.io, self.socket, &self.remote, packet); }
/// Tells the other end about `err` with the ERROR packet `errorPacket` /// chooses, and returns `err` for the transfer to end with. Sending is /// best effort, since the transfer is failing already. pub fn fail(self: *const Transfer, err: anyerror) anyerror { self.send(.{ .err = errorPacket(err) }) catch {}; return err; }
/// Sends the other end an ERROR packet with the standard message for /// `code`. pub fn sendError(self: *const Transfer, code: Packet.ErrorCode) !void { try self.send(.{ .err = .{ .code = code } }); }
/// Ends the transfer because the other end sent `err`. fn received(self: *const Transfer, err: Packet.Err) error{ErrorReceived} { log.info("{f} ended the transfer: {t} {s}", .{ self.remote, err.code, err.msg orelse "" }); if (self.diagnostics) |d| d.record(err); return error.ErrorReceived; }
/// Ends the transfer because the other end sent a packet that has no /// place in it. fn illegal(self: *const Transfer, packet: Packet) anyerror { log.info("illegal {t} packet from {f}", .{ packet, self.remote }); self.sendError(.illegal_operation) catch {}; return error.IllegalPacketType; }
/// Waits one retransmission interval for the next packet from the other /// end, decoding it into `buf`. Returns `null` if none arrives, when the /// caller should retransmit, and `error.Timeout` once it has done so too /// often. pub fn receive(self: *Transfer, buf: *Packet.Buffer) !?Packet { if (try self.receiveBefore(self.retransmit.timeout().toDeadline(self.io), buf)) |packet| return packet; try self.retransmit.expired(); return null; }
/// Waits until `deadline` for the next packet from the other end, /// returning `null` if none arrives. /// /// A packet from the other end that does not decode is answered with an /// illegal operation error, and ends the transfer with the reason it did /// not decode. A packet from any other address is answered with an /// unknown transfer ID error, as RFC 1350 requires, and otherwise /// ignored; it does not end the transfer, and cannot extend the wait. pub fn receiveBefore(self: *Transfer, deadline: std.Io.Timeout, buf: *Packet.Buffer) !?Packet { while (true) { var message_buf: Packet.Buffer = undefined; const message = self.socket.receiveTimeout(self.io, &message_buf, deadline) catch |err| switch (err) { error.Timeout => return null, else => |e| return e, };
if (!self.locked and sameHost(self.remote, message.from)) { self.remote = message.from; self.locked = true; } if (!self.remote.eql(&message.from)) { log.info("packet from unknown transfer ID {f}", .{message.from}); // Best effort: the stray's trouble is not this transfer's. sendTo(self.io, self.socket, &message.from, .{ .err = .{ .code = .tid_unknown } }) catch {}; continue; }
return Packet.decode(message.data, buf, self.decode_options) catch |err| { self.send(.{ .err = malformed(err) }) catch {}; return err; }; } }
/// Waits one retransmission interval after the final acknowledgment, /// answering `final` again if the other end sends the last block again /// because the first answer was lost (RFC 1350, section 6). pub fn dally(self: *Transfer, final: Packet) !void { const deadline = self.retransmit.timeout().toDeadline(self.io); while (true) { var packet_buf: Packet.Buffer = undefined; const packet = try self.receiveBefore(deadline, &packet_buf) orelse return; if (packet == .data and packet.data.block == final.ack.block) try self.send(final); } }};
/// Checks an OACK against what was asked for (RFC 2347). The other end may/// decline an option by leaving it out, and may lower the block size, but/// may not raise it, change the timeout, or acknowledge an option that was/// not asked for.fn checkAcknowledgment(requested: Packet.Options, got: Packet.Options) error{BadOptionAcknowledgment}!void { if (got.blocksize) |b| { const asked = requested.blocksize orelse return error.BadOptionAcknowledgment; if (b > asked) return error.BadOptionAcknowledgment; } if (got.timeout) |t| { if (requested.timeout != t) return error.BadOptionAcknowledgment; } if (got.transfer_size != null and requested.transfer_size == null) return error.BadOptionAcknowledgment;}
/// Why a write through `decoder` in `mode` failed: the other end's fault if/// the decoder refused what it sent, and the writer's otherwise. The decoder/// is only looked at in the modes that use it.fn writeFailure(mode: Packet.Mode, decoder: *const netascii.Decoder) anyerror { return switch (mode) { .netascii, .mail => if (decoder.err) |_| error.MalformedNetascii else error.WriteFailed, .octet => error.WriteFailed, };}
/// Receives a file into `writer`.////// `first` is the packet that asks for the first block, sent and resent until/// the block comes: a server's ACK 0 or OACK, or a client's RRQ. `requested`/// is what a client asked for, which an OACK may answer; a server passes/// `null`, since an OACK is not a server's to receive, and a client that/// asked for nothing passes `null` too. `agreed` is the options in force/// before any OACK: what a server's `first` acknowledged, or none for a/// client. `decoder` is the/// netascii decoder `writer` belongs to, if there is one, which is how a/// failed write is told apart as the other end's fault.////// Each DATA packet is acknowledged, and the acknowledgment is resent while/// waiting for the next block. A block that arrives again is acknowledged/// again but not written again. `finish.finish()` is called once the last/// block has been written and flushed, before the final acknowledgment/// claims it has been, and then the transfer waits one retransmission/// interval in case that acknowledgment was lost.pub fn receiveFile( transfer: *Transfer, writer: *std.Io.Writer, decoder: *const netascii.Decoder, first: Packet, requested: ?Packet.Options, agreed: Packet.Options, finish: anytype,) !Outcome { const mode = transfer.decode_options.mode.?; var options = agreed; var blocksize: u16 = options.blocksize orelse 512; // Until an OACK says otherwise, a client may be sent a block as large as // it asked for, so one too large for the default is decoded, and then // refused for its length, rather than failing to decode at all. if (requested) |r| transfer.decode_options.blocksize = @max(r.blocksize orelse 512, 512);
// The last block written, which is also the last acknowledged. var block: u16 = 0; var bytes: u64 = 0; var reply = first; var acknowledged = false;
send: while (true) { try transfer.send(reply);
while (true) { var packet_buf: Packet.Buffer = undefined; const packet = try transfer.receive(&packet_buf) orelse continue :send;
switch (packet) { .oack => |oack| { const asked = requested orelse return transfer.illegal(packet); if (block != 0 or acknowledged) return transfer.illegal(packet); checkAcknowledgment(asked, oack.options) catch |err| return transfer.fail(err); acknowledged = true; options = oack.options; blocksize = options.blocksize orelse 512; transfer.negotiated(options); transfer.retransmit.progress(); reply = .{ .ack = .{ .block = 0 } }; continue :send; }, .data => |data| { // The acknowledgment was lost and the block has come // again. if (data.block == block and block != 0) continue :send; // Anything else out of sequence is a stray. if (data.block != block +% 1) continue; if (data.data.len > blocksize) { transfer.send(.{ .err = malformed(error.PacketTooLong) }) catch {}; return error.PacketTooLong; } if (block == 0 and requested != null and !acknowledged) { // The server ignored the options and went straight // to the data, which declines them all. transfer.negotiated(.{}); }
transfer.retransmit.progress(); block = data.block; writer.writeAll(data.data) catch return transfer.fail(writeFailure(mode, decoder)); bytes += data.data.len; reply = .{ .ack = .{ .block = block } };
if (data.data.len < blocksize) { // Everything is written before the final // acknowledgment claims that it has been. writer.flush() catch return transfer.fail(writeFailure(mode, decoder)); finish.finish() catch |err| return transfer.fail(err); try transfer.send(reply); try transfer.dally(reply); return .{ .bytes = bytes, .options = options }; } continue :send; }, .err => |err| return transfer.received(err), .rrq, .wrq, .ack => return transfer.illegal(packet), } } }}
/// Sends the file `reader` supplies.////// `first` is the packet that has to be acknowledged before the first block/// is sent: a client's WRQ, a server's OACK, or nothing, when a server goes/// straight to the data. `requested` is what a client asked for, which an/// OACK may answer, and `null` for a server or a client that asked for/// nothing. `agreed` is the options in force before any OACK: what a/// server's `first` offers, or none for a client.////// Each DATA packet is resent until it is acknowledged, and the transfer/// ends when the block shorter than the block size is. An acknowledgment of/// any other block is ignored.pub fn sendFile( transfer: *Transfer, reader: *std.Io.Reader, first: ?Packet, requested: ?Packet.Options, agreed: Packet.Options,) !Outcome { const mode = transfer.decode_options.mode.?; var options = agreed; var data_buffer_raw: Packet.Buffer = undefined; var outgoing: Outgoing = .{ .reader = reader, .buffer = data_buffer_raw[0 .. options.blocksize orelse 512], }; var bytes: u64 = 0;
// The packet waiting to be acknowledged before the first block. It shares // block number zero with nothing else, so it cannot be told apart from // the data by the block number alone. var pending = first; if (pending == null) outgoing.advance() catch |err| return transfer.fail(err);
send: while (true) { try transfer.send(pending orelse .{ .data = .{ .block = outgoing.block, .data = outgoing.data(), .mode = mode, .last = outgoing.last(), } });
while (true) { var packet_buf: Packet.Buffer = undefined; const packet = try transfer.receive(&packet_buf) orelse continue :send;
switch (packet) { .oack => |oack| { // For a WRQ, the OACK stands in for the ACK of block // zero, and the answer to it is the first block. const asked = requested orelse return transfer.illegal(packet); if (pending == null) return transfer.illegal(packet); checkAcknowledgment(asked, oack.options) catch |err| return transfer.fail(err); options = oack.options; transfer.negotiated(options); }, .ack => |ack| { // A duplicate or a stray. Answering it with a // retransmission is the Sorcerer's Apprentice bug // (RFC 1123, section 4.2.3.1), which sends every block // twice from then on. if (ack.block != outgoing.block) continue; if (pending == null) { bytes += outgoing.len; if (outgoing.last()) return .{ .bytes = bytes, .options = options }; } else if (requested != null) { // A plain ACK of a WRQ that asked for options // declines them all. options = .{}; transfer.negotiated(options); } }, .err => |err| return transfer.received(err), .data, .rrq, .wrq => return transfer.illegal(packet), }
transfer.retransmit.progress(); if (pending != null) { pending = null; outgoing.buffer = data_buffer_raw[0 .. options.blocksize orelse 512]; } outgoing.advance() catch |err| return transfer.fail(err); continue :send; } }}
/// The block in flight on the sending side of a transfer.const Outgoing = struct { /// Where the file comes from. reader: *std.Io.Reader, /// Room for one block, exactly the block size long. buffer: []u8, /// The block number, zero until the first block is read. block: u16 = 0, /// How much of `buffer` the block fills. len: usize = 0,
/// Reads the next block. Block numbers wrap from 65535 to zero, as most /// clients expect, so a file of any size can be sent. fn advance(self: *Outgoing) !void { self.block +%= 1; self.len = try self.reader.readSliceShort(self.buffer); }
/// The contents of the block. fn data(self: *const Outgoing) []const u8 { return self.buffer[0..self.len]; }
/// Whether this is the final block, which is shorter than the block size. fn last(self: *const Outgoing) bool { return self.len < self.buffer.len; }};
/// When to retransmit, and when to give up.////// If a `timeout` was negotiated (RFC 2349), every wait is exactly that many/// seconds. Otherwise the first is 250 milliseconds and each one after it/// twice the one before. Either way the transfer is abandoned after/// `max_retries` retransmissions in a row, which without a negotiated timeout/// is about 32 seconds.pub const Retransmit = struct { /// How long the next wait will be. interval: std.Io.Duration, /// Whether `interval` was negotiated, in which case it does not grow. negotiated: bool, /// Retransmissions since the other end last made progress. retries: u8 = 0,
pub const initial: std.Io.Duration = .fromMilliseconds(250); pub const max_retries = 6;
/// The timing for a transfer that negotiated `timeout` seconds, or none. pub fn init(timeout_: ?u8) Retransmit { if (timeout_) |seconds| return .{ .interval = .fromSeconds(seconds), .negotiated = true }; return .{ .interval = initial, .negotiated = false }; }
/// The timeout for the next wait. pub fn timeout(self: *const Retransmit) std.Io.Timeout { return .{ .duration = .{ .clock = .awake, .raw = self.interval } }; }
/// Records a wait that ended with nothing received, returning /// `error.Timeout` if there have been too many. pub fn expired(self: *Retransmit) error{Timeout}!void { if (self.retries == max_retries) return error.Timeout; self.retries += 1; if (!self.negotiated) self.interval.nanoseconds *= 2; }
/// Records progress by the other end, which starts the count again. pub fn progress(self: *Retransmit) void { self.retries = 0; if (!self.negotiated) self.interval = initial; }};
test "retransmission timing" { { var retransmit: Retransmit = .init(null); var total: i96 = 0; for (0..Retransmit.max_retries) |_| { total += retransmit.interval.nanoseconds; try retransmit.expired(); } total += retransmit.interval.nanoseconds; try testing.expectError(error.Timeout, retransmit.expired()); // 250 ms doubled six times over, about half a minute in all. try testing.expectEqual(std.Io.Duration.fromMilliseconds(250 * 127).nanoseconds, total);
retransmit.progress(); try testing.expectEqual(Retransmit.initial, retransmit.interval); try testing.expectEqual(0, retransmit.retries); } { var retransmit: Retransmit = .init(3); for (0..Retransmit.max_retries) |_| try retransmit.expired(); try testing.expectEqual(std.Io.Duration.fromSeconds(3), retransmit.interval); try testing.expectError(error.Timeout, retransmit.expired()); }}
test "option acknowledgments" { const asked: Packet.Options = .{ .blocksize = 1428, .timeout = 5, .transfer_size = 0 }; try checkAcknowledgment(asked, .{}); try checkAcknowledgment(asked, asked); try checkAcknowledgment(asked, .{ .blocksize = 512, .transfer_size = 1234 }); try testing.expectError(error.BadOptionAcknowledgment, checkAcknowledgment(asked, .{ .blocksize = 1429 })); try testing.expectError(error.BadOptionAcknowledgment, checkAcknowledgment(asked, .{ .timeout = 6 })); try testing.expectError(error.BadOptionAcknowledgment, checkAcknowledgment(.{}, .{ .blocksize = 512 })); try testing.expectError(error.BadOptionAcknowledgment, checkAcknowledgment(.{}, .{ .transfer_size = 1 }));}