// SPDX-FileCopyrightText: © 2022 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The TFTP server: the listening loop, and the two halves of a transfer. const std = @import("std"); const builtin = @import("builtin"); const log = std.log.scoped(.server); const Packet = @import("packet.zig").Packet; const netascii = @import("netascii.zig"); const pktinfo = @import("pktinfo.zig"); const transfer_ = @import("transfer.zig"); const Transfer = transfer_.Transfer; const sendTo = transfer_.sendTo; const malformed = transfer_.malformed; /// A TFTP server that hands each request to an application of type `T`. /// /// The server owns the protocol and `T` owns the files. `T` provides one or /// both of two methods, each of which returns a request object that the server /// drives and then deinitializes. A server whose `T` lacks one refuses that /// kind of request with an access violation, so a read-only server is just a /// `T` without `writeTo`: /// /// ```zig /// fn writeTo(self: *const T, io: std.Io, alloc: std.mem.Allocator, request: Request) !Write /// fn readFrom(self: *const T, io: std.Io, alloc: std.mem.Allocator, request: Request) !Read /// ``` /// /// `request` says what was asked for and by whom: the filename, the mode and /// options, and the addresses at both ends, which is what an access control /// list or a log needs. See `Request`. /// /// A `Write` has `writer(io, alloc) !*std.Io.Writer`, which receives the /// file's contents, `finish(io) !void`, called once the last block has been /// written and flushed, and `deinit(io, alloc) void`. It may also have /// `reserve(io, size: u64) !void`, which is told the size of the file when the /// client offers it with the `tsize` option (RFC 2349) and can refuse the /// write before any of it is sent. In `netascii` mode the size is that of the /// file as it is sent, not as it will be written. /// /// A `Read` has `reader(io, alloc) !*std.Io.Reader`, which supplies the file's /// contents, and `deinit(io, alloc) void`. It may also have `size(io) ?u64`, /// the length of the file if it is known, which is how a client asking for /// the `tsize` option is told it. /// /// Any error from the application ends the transfer, and the client is told /// why with the closest error code RFC 1350 has: `error.FileNotFound` is /// "file not found", `error.PermissionDenied` and `error.AccessDenied` are an /// access violation, `error.NoSpaceLeft`, `error.DiskQuota` and /// `error.FileTooBig` are "disk full", and `error.PathAlreadyExists` is "file /// already exists". Anything else is sent as "not defined", with the error's /// name for its message. /// /// In `netascii` and `mail` modes the application deals only in local text: /// what a client sends is decoded before it reaches a `Write`, and what a /// `Read` supplies is encoded before it is sent. Encoding looks two bytes /// ahead, so the reader a `Read` hands back must have a buffer of at least two /// bytes. /// A read or write request, as the application is asked to serve it. /// /// Everything in it lives only as long as the call to `readFrom` or /// `writeTo` it is passed to; copy what has to be kept. pub const Request = struct { /// The file the client asked for, decoded from netascii. filename: []const u8, /// The mode it is to be transferred in. mode: Packet.Mode, /// The options the client asked for, those this library understands and /// found in range. Unrecognized and invalid ones have already been dropped. options: Packet.Options, /// The client's address and port. remote: std.Io.net.IpAddress, /// The address and port the request was sent to. /// /// On Linux and Apple's platforms the kernel reports each request's /// destination, so this is the one of the host's addresses the client /// used even when the server listens on all of them, and may be a /// broadcast or multicast address. Elsewhere it is the address the server /// is bound to, which for `0.0.0.0` or `::` says only which family. The /// port is always the one the listener was actually given. local: std.Io.net.IpAddress, /// The local address and port the rest of the transfer runs on, which is /// a port of its own, as RFC 1350 requires. The client learns it from the /// server's first answer. transfer: std.Io.net.IpAddress, }; pub fn Server(comptime T: type) type { return struct { pub const Self = @This(); /// The application that serves the files. app: *T, /// The address the server listens on. Each transfer is answered from /// the address its request was sent to, where the platform reports /// it, and from this one otherwise, on a port of its own. address: std.Io.net.IpAddress, /// A server for `app`, listening on `address`. pub fn init(app: *T, address: std.Io.net.IpAddress) Self { return .{ .app = app, .address = address, }; } /// Binds `address` and serves requests until an error other than a /// receive timeout occurs. Each request is handled as a concurrent task /// in `io`, on a socket of its own, as RFC 1350 requires; the tasks are /// canceled when this returns. pub fn run( self: *Self, io: std.Io, alloc: std.mem.Allocator, ) !void { const socket = try self.address.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer socket.close(io); // Ask where each request was sent, which is what tells a server // listening on every address which one a client used. const destinations = pktinfo.enable(socket); if (!destinations and !isUnspecified(socket.address)) log.debug("no per request destinations; using {f}", .{socket.address}); var group: std.Io.Group = .init; defer group.cancel(io); while (true) { const packet_queue_size = 5; var messages: [packet_queue_size]std.Io.net.IncomingMessage = @splat(.init); var buffer: [packet_queue_size * Packet.BUFFER_LENGTH]u8 = undefined; var controls: [packet_queue_size][pktinfo.control_len]u8 align(@alignOf(usize)) = undefined; if (destinations) for (&messages, &controls) |*message, *control| { message.control = control; }; const err_, const count = socket.receiveManyTimeout(io, &messages, &buffer, .{}, .{ .duration = .{ .clock = .real, .raw = .fromMilliseconds(250), }, }); for (messages[0..count]) |message| { const to: pktinfo.Destination = if (destinations) pktinfo.destination(message.control, socket.address.getPort()) orelse .{ .address = socket.address, .reply_from = socket.address } else .{ .address = socket.address, .reply_from = socket.address }; const data = try alloc.dupe(u8, message.data); try group.concurrent(io, handleIncomingMessage, .{ self, io, alloc, to.address, to.reply_from, message.from, data, }); } if (err_) |err| { switch (err) { error.Timeout => {}, else => return err, } } } } /// Handles the first packet of a transfer, which arrived at `local` /// from `remote` as the datagram `data`, and then the rest of the /// transfer, which is answered from `reply_from` on a port of its own. /// /// `local` is what the application is told the request was sent to. /// `reply_from` is usually the same address, and differs when that is /// one a socket cannot be bound to, a broadcast or a multicast. `run` /// passes the destination the kernel reported, where it reports one, /// and otherwise the address its socket is bound to for both. /// /// Takes ownership of `data`, which must have been allocated from /// `alloc`. A failed transfer is logged rather than returned, since /// nothing is waiting on the task to hear about it. pub fn handleIncomingMessage( self: *Self, io: std.Io, alloc: std.mem.Allocator, local: std.Io.net.IpAddress, reply_from: std.Io.net.IpAddress, remote: std.Io.net.IpAddress, data: []const u8, ) error{Canceled}!void { self._handleIncomingMessage(io, alloc, local, reply_from, remote, data) catch |err| switch (err) { // The server is stopping, which is not the transfer failing. error.Canceled => return error.Canceled, else => |e| { log.warn("handle incoming message failed with {t}", .{e}); }, }; } /// `handleIncomingMessage`, with the errors returned: binds the /// transfer's socket, decodes the request and dispatches it. A packet /// that does not decode, or is anything but a read or write request, /// is answered with an illegal operation error, except that an ERROR /// is ignored. fn _handleIncomingMessage( self: *Self, io: std.Io, alloc: std.mem.Allocator, local: std.Io.net.IpAddress, reply_from: std.Io.net.IpAddress, remote: std.Io.net.IpAddress, initial_data: []const u8, ) !void { defer alloc.free(initial_data); // A socket of the transfer's own, on a port the kernel chooses, // and on the address the client sent its request to, so that the // answers come from where the client expects them. var transfer_address = reply_from; transfer_address.setPort(0); const socket = try transfer_address.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer socket.close(io); var input_buf: Packet.Buffer = undefined; // Any mode and block size, so that a packet which is well formed // but not a request decodes, and is refused as the wrong kind. const initial: Packet = Packet.decode(initial_data, &input_buf, .{ .mode = .octet, .blocksize = std.math.maxInt(u16), }) catch |err| { sendTo(io, socket, &remote, .{ .err = malformed(err) }) catch {}; return err; }; log.info("initial {t} packet from {f}", .{ initial, remote }); switch (initial) { // Chosen at compile time, so that a `T` without one of the // methods never has the handler that calls it analyzed. .wrq => |*wrq| { log.info("wrq: {s}", .{wrq.filename}); if (comptime @hasDecl(T, "writeTo")) { try self.handleWrite(io, alloc, socket, local, &remote, wrq); } else { try sendTo(io, socket, &remote, .{ .err = .{ .code = .access_violation } }); return error.PermissionDenied; } }, .rrq => |*rrq| { log.info("rrq: {s}", .{rrq.filename}); if (comptime @hasDecl(T, "readFrom")) { try self.handleRead(io, alloc, socket, local, &remote, rrq); } else { try sendTo(io, socket, &remote, .{ .err = .{ .code = .access_violation } }); return error.PermissionDenied; } }, // An ERROR is never answered, lest two ends answer each // other forever. .err => return, .data, .ack, .oack => { try sendTo(io, socket, &remote, .{ .err = .{ .code = .illegal_operation } }); return error.IllegalPacketType; }, } } /// Receives the file named by `wrq` from `remote` over `socket` and /// writes it to the application's `Write`, with `transfer.receiveFile`. fn handleWrite( self: *Self, io: std.Io, alloc: std.mem.Allocator, socket: std.Io.net.Socket, local: std.Io.net.IpAddress, remote: *const std.Io.net.IpAddress, wrq: *const Packet.Wrq, ) !void { var transfer: Transfer = .init(io, socket, remote.*, true, wrq.mode, wrq.options); var request = self.app.writeTo(io, alloc, .{ .filename = wrq.filename, .mode = wrq.mode, .options = wrq.options, .remote = remote.*, .local = local, .transfer = socket.address, }) catch |err| return transfer.fail(err); defer request.deinit(io, alloc); if (wrq.options.transfer_size) |size| { if (@hasDecl(@TypeOf(request), "reserve")) request.reserve(io, size) catch |err| return transfer.fail(err); } const child = request.writer(io, alloc) catch |err| return transfer.fail(err); var netascii_buffer: [128]u8 = undefined; var netascii_decoder: netascii.Decoder = undefined; const writer = switch (wrq.mode) { .netascii, .mail => writer: { netascii_decoder = .init(child, &netascii_buffer); break :writer &netascii_decoder.interface; }, .octet => child, }; const outcome = try transfer_.receiveFile( &transfer, writer, &netascii_decoder, if (wrq.options.empty()) .{ .ack = .{ .block = 0 } } else .{ .oack = .{ .options = wrq.options } }, null, wrq.options, Finish(@TypeOf(request)){ .request = &request, .io = io }, ); log.info("received {s}, {d} bytes from the network", .{ wrq.filename, outcome.bytes }); } /// What `receiveFile` calls once the last block is written, which is /// the application's `finish`. fn Finish(comptime Write: type) type { return struct { request: *Write, io: std.Io, pub fn finish(self: @This()) !void { try self.request.finish(self.io); } }; } /// Sends the file named by `rrq`, as read from the application's /// `Read`, to `remote` over `socket`, with `transfer.sendFile`. fn handleRead( self: *Self, io: std.Io, alloc: std.mem.Allocator, socket: std.Io.net.Socket, local: std.Io.net.IpAddress, remote: *const std.Io.net.IpAddress, rrq: *const Packet.Rrq, ) !void { var transfer: Transfer = .init(io, socket, remote.*, true, rrq.mode, rrq.options); var request = self.app.readFrom(io, alloc, .{ .filename = rrq.filename, .mode = rrq.mode, .options = rrq.options, .remote = remote.*, .local = local, .transfer = socket.address, }) catch |err| return transfer.fail(err); defer request.deinit(io, alloc); const child = request.reader(io, alloc) catch |err| return transfer.fail(err); var netascii_buffer: [128]u8 = undefined; var netascii_encoder: netascii.EncodeReader = undefined; const reader: *std.Io.Reader = switch (rrq.mode) { .netascii, .mail => reader: { netascii_encoder = .init(child, &netascii_buffer); break :reader &netascii_encoder.interface; }, .octet => child, }; var options = rrq.options; if (options.transfer_size != null) { // RFC 2349: a client asks for the size by sending zero, and the // server answers with the real one. If there is none to give, // the option is left out of the OACK, which declines it. options.transfer_size = if (rrq.mode == .octet and @hasDecl(@TypeOf(request), "size")) request.size(io) else null; } const outcome = try transfer_.sendFile( &transfer, reader, if (options.empty()) null else .{ .oack = .{ .options = options } }, null, options, ); log.info("sent {s}, {d} bytes to the network", .{ rrq.filename, outcome.bytes }); } }; } /// Whether `address` is `0.0.0.0` or `::`, which a socket bound to listens on /// every address the host has. fn isUnspecified(address: std.Io.net.IpAddress) bool { return switch (address) { .ip4 => |a| std.mem.allEqual(u8, &a.bytes, 0), .ip6 => |a| std.mem.allEqual(u8, &a.bytes, 0), }; } /// An application serving one file and collecting another, for driving the /// server in tests. const TestApp = struct { /// What every read is answered with, or `null` for there to be no file. content: ?[]const u8, /// Everything written. written: std.Io.Writer.Allocating, /// Whether a write has been finished. finished: bool = false, /// The largest write `reserve` accepts, if there is a limit. capacity: ?u64 = null, /// The request `readFrom` or `writeTo` was last handed, less its /// filename, which does not outlive the call. last: Request = undefined, /// If set, writes go to a writer that fails once this many bytes have /// been written, rather than to `written`. fail_after: ?usize = null, full: std.Io.Writer = undefined, full_buf: [64]u8 = undefined, /// A read of `content`. 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 {} }; /// Answers every read request with `content`. pub fn readFrom(self: *TestApp, _: std.Io, _: std.mem.Allocator, request: Request) !Read { self.last = request; self.last.filename = ""; return .{ .interface = .fixed(self.content orelse return error.FileNotFound) }; } /// A write into `written`. pub const Write = struct { app: *TestApp, pub fn writer(self: *Write, _: std.Io, _: std.mem.Allocator) !*std.Io.Writer { const app = self.app; if (app.fail_after) |limit| { app.full = .fixed(app.full_buf[0..limit]); return &app.full; } return &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(self: *Write, _: std.Io) !void { self.app.finished = true; } pub fn deinit(_: *Write, _: std.Io, _: std.mem.Allocator) void {} }; /// Accepts every write request into `written`. pub fn writeTo(self: *TestApp, _: std.Io, _: std.mem.Allocator, request: Request) !Write { self.last = request; self.last.filename = ""; return .{ .app = self }; } }; /// A server transfer running against a client played by the test over the /// loopback interface. The test sends and receives the client's packets, and /// the transfer runs concurrently on its own socket. const Harness = struct { const testing = std.testing; io: std.Io, app: TestApp, server: Server(TestApp), /// The transfer's socket. server_socket: std.Io.net.Socket, /// The client's socket. client_socket: std.Io.net.Socket, /// How packets from the server are decoded. decode_options: Packet.DecodeOptions, /// The transfer in progress. future: std.Io.Future(anyerror!void), const loopback = std.Io.net.IpAddress.parseLiteral("127.0.0.1:0") catch unreachable; /// What the transfers are told their request was sent to. Nothing /// listens there; it only has to arrive unchanged. const listening = std.Io.net.IpAddress.parseLiteral("127.0.0.1:69") catch unreachable; const receive_timeout: std.Io.Timeout = .{ .duration = .{ .clock = .awake, .raw = .fromSeconds(5) } }; fn init(self: *Harness, io: std.Io, content: ?[]const u8) !void { self.io = io; self.decode_options = .{}; self.app = .{ .content = content, .written = .init(testing.allocator) }; self.server = .init(&self.app, loopback); self.server_socket = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); self.client_socket = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); } fn deinit(self: *Harness) void { self.client_socket.close(self.io); self.server_socket.close(self.io); self.app.written.deinit(); } /// Starts serving `rrq`, which must outlive the transfer. fn read(self: *Harness, rrq: *const Packet.Rrq) !void { self.decode_options = .{ .mode = rrq.mode, .blocksize = rrq.options.blocksize }; self.future = try self.io.concurrent(serveRead, .{ self, rrq }); } /// Starts serving `wrq`, which must outlive the transfer. fn write(self: *Harness, wrq: *const Packet.Wrq) !void { self.decode_options = .{ .mode = wrq.mode, .blocksize = wrq.options.blocksize }; self.future = try self.io.concurrent(serveWrite, .{ self, wrq }); } fn serveRead(self: *Harness, rrq: *const Packet.Rrq) anyerror!void { return self.server.handleRead(self.io, testing.allocator, self.server_socket, listening, &self.client_socket.address, rrq); } fn serveWrite(self: *Harness, wrq: *const Packet.Wrq) anyerror!void { return self.server.handleWrite(self.io, testing.allocator, self.server_socket, listening, &self.client_socket.address, wrq); } /// Waits for the transfer to end, returning how it ended. fn wait(self: *Harness) anyerror!void { return self.future.await(self.io); } /// Abandons the transfer. fn cancel(self: *Harness) void { self.future.cancel(self.io) catch {}; } /// Sends `packet` to the server as the client. fn send(self: *Harness, packet: Packet) !void { var buf: Packet.Buffer = undefined; try self.client_socket.send(self.io, &self.server_socket.address, try packet.encode(&buf)); } /// Receives the server's next packet as the client, decoding it into `buf`. fn receive(self: *Harness, buf: *Packet.Buffer) !Packet { var message_buf: Packet.Buffer = undefined; const message = try self.client_socket.receiveTimeout(self.io, &message_buf, receive_timeout); return .decode(message.data, buf, self.decode_options); } fn expectOack(self: *Harness, options: Packet.Options) !void { var buf: Packet.Buffer = undefined; const packet = try self.receive(&buf); try testing.expect(packet == .oack); try testing.expectEqual(options, packet.oack.options); } fn expectData(self: *Harness, block: u16, data: []const u8) !void { var buf: Packet.Buffer = undefined; const packet = try self.receive(&buf); try testing.expect(packet == .data); try testing.expectEqual(block, packet.data.block); try testing.expectEqualStrings(data, packet.data.data); } fn expectAck(self: *Harness, block: u16) !void { var buf: Packet.Buffer = undefined; const packet = try self.receive(&buf); try testing.expect(packet == .ack); try testing.expectEqual(block, packet.ack.block); } fn expectError(self: *Harness, code: Packet.ErrorCode, msg: ?[]const u8) !void { var buf: Packet.Buffer = undefined; const packet = try self.receive(&buf); try testing.expect(packet == .err); try testing.expectEqual(code, packet.err.code); if (msg) |expected| try testing.expectEqualStrings(expected, packet.err.msg.?); } /// Sends `bytes` to the server as the client, whether they make a packet /// or not. fn sendRaw(self: *Harness, bytes: []const u8) !void { try self.client_socket.send(self.io, &self.server_socket.address, bytes); } fn sendAck(self: *Harness, block: u16) !void { try self.send(.{ .ack = .{ .block = block } }); } fn sendData(self: *Harness, block: u16, bytes: []const u8) !void { try self.send(.{ .data = .{ .block = block, .mode = self.decode_options.mode.?, .data = bytes } }); } }; test "read request without options" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "hello"); defer h.deinit(); const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = .{} }; try h.read(&rrq); errdefer h.cancel(); try h.expectData(1, "hello"); try h.sendAck(1); try h.wait(); } test "read request with options is answered with an OACK and then the data" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "abcdefghijkl"); defer h.deinit(); const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = .{ .blocksize = 8 } }; try h.read(&rrq); errdefer h.cancel(); try h.expectOack(.{ .blocksize = 8 }); try h.sendAck(0); try h.expectData(1, "abcdefgh"); try h.sendAck(1); try h.expectData(2, "ijkl"); try h.sendAck(2); try h.wait(); } test "netascii read request is encoded" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "one\ntwo"); defer h.deinit(); const rrq: Packet.Rrq = .{ .filename = "f", .mode = .netascii, .options = .{ .blocksize = 8 } }; try h.read(&rrq); errdefer h.cancel(); // Encodes to exactly eight bytes, so a full block is followed by an empty // one, which is how a transfer that is a multiple of the block size ends. try h.expectOack(.{ .blocksize = 8 }); try h.sendAck(0); try h.expectData(1, "one\r\ntwo"); try h.sendAck(1); try h.expectData(2, ""); try h.sendAck(2); try h.wait(); } test "read ignores a duplicate ACK rather than retransmitting" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "abcdefghijklmnopqrst"); defer h.deinit(); // A long negotiated timeout, so that no retransmission is due while the // test is running and anything that arrives is an answer to the ACKs. const options: Packet.Options = .{ .blocksize = 8, .timeout = 5 }; const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = options }; try h.read(&rrq); errdefer h.cancel(); try h.expectOack(options); try h.sendAck(0); try h.expectData(1, "abcdefgh"); try h.sendAck(1); try h.expectData(2, "ijklmnop"); // The duplicate is ignored, so the next packet is the answer to the ACK of // block 2 rather than a second copy of block 2. try h.sendAck(1); try h.sendAck(2); try h.expectData(3, "qrst"); try h.sendAck(3); try h.wait(); } test "read reports the transfer size in octet mode" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "hello"); defer h.deinit(); const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = .{ .transfer_size = 0 } }; try h.read(&rrq); errdefer h.cancel(); try h.expectOack(.{ .transfer_size = 5 }); try h.sendAck(0); try h.expectData(1, "hello"); try h.sendAck(1); try h.wait(); } test "read declines the transfer size in netascii mode" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "one\ntwo"); defer h.deinit(); // The encoded size is not known until the file has been sent, and with // the only option declined there is no OACK at all. const rrq: Packet.Rrq = .{ .filename = "f", .mode = .netascii, .options = .{ .transfer_size = 0 } }; try h.read(&rrq); errdefer h.cancel(); try h.expectData(1, "one\r\ntwo"); try h.sendAck(1); try h.wait(); } test "read block numbers wrap to zero" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); // Blocks of eight bytes, so that 65536 of them is only 512 KiB. const content = try std.testing.allocator.alloc(u8, 65537 * 8 + 1); defer std.testing.allocator.free(content); for (content, 0..) |*byte, index| byte.* = @truncate(index); var h: Harness = undefined; try h.init(threaded.io(), content); defer h.deinit(); const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = .{ .blocksize = 8 } }; try h.read(&rrq); errdefer h.cancel(); try h.expectOack(.{ .blocksize = 8 }); try h.sendAck(0); var block: u16 = 1; var offset: usize = 0; while (offset <= content.len) : ({ block +%= 1; offset += 8; }) { try h.expectData(block, content[offset..@min(offset + 8, content.len)]); try h.sendAck(block); } // 65538 blocks: the 65536th went out as zero, and the last as two. try std.testing.expectEqual(3, block); try h.wait(); } test "a packet from another port is refused without disturbing the transfer" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var h: Harness = undefined; try h.init(io, "abcdefghijkl"); defer h.deinit(); const options: Packet.Options = .{ .blocksize = 8, .timeout = 5 }; const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = options }; try h.read(&rrq); errdefer h.cancel(); try h.expectOack(options); try h.sendAck(0); try h.expectData(1, "abcdefgh"); const stray = try Harness.loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer stray.close(io); { var buf: Packet.Buffer = undefined; const packet: Packet = .{ .ack = .{ .block = 1 } }; try stray.send(io, &h.server_socket.address, try packet.encode(&buf)); var message_buf: Packet.Buffer = undefined; const message = try stray.receiveTimeout(io, &message_buf, Harness.receive_timeout); const answer: Packet = try .decode(message.data, &buf, .{}); try std.testing.expect(answer == .err); try std.testing.expectEqual(.tid_unknown, answer.err.code); } // The stray's ACK did not move the transfer on; the client's does. try h.sendAck(1); try h.expectData(2, "ijkl"); try h.sendAck(2); try h.wait(); } test "write request" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), ""); defer h.deinit(); const wrq: Packet.Wrq = .{ .filename = "f", .mode = .octet, .options = .{} }; try h.write(&wrq); errdefer h.cancel(); try h.expectAck(0); try h.sendData(1, "hello"); try h.expectAck(1); try h.wait(); try std.testing.expectEqualStrings("hello", h.app.written.written()); try std.testing.expect(h.app.finished); } test "write acknowledges a repeated block without writing it twice" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), ""); defer h.deinit(); const options: Packet.Options = .{ .blocksize = 8, .timeout = 5 }; const wrq: Packet.Wrq = .{ .filename = "f", .mode = .octet, .options = options }; try h.write(&wrq); errdefer h.cancel(); try h.expectOack(options); try h.sendData(1, "abcdefgh"); try h.expectAck(1); // As if the ACK had been lost. try h.sendData(1, "abcdefgh"); try h.expectAck(1); try h.sendData(2, "ijkl"); try h.expectAck(2); // The final ACK lost too: the server is still dallying to answer again. try h.sendData(2, "ijkl"); try h.expectAck(2); try h.wait(); try std.testing.expectEqualStrings("abcdefghijkl", h.app.written.written()); } test "read of a missing file is refused" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), null); defer h.deinit(); const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = .{} }; try h.read(&rrq); errdefer h.cancel(); try h.expectError(.file_not_found, "File not found"); try std.testing.expectError(error.FileNotFound, h.wait()); } test "write the application cannot hold is refused" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), ""); defer h.deinit(); h.app.fail_after = 4; const wrq: Packet.Wrq = .{ .filename = "f", .mode = .octet, .options = .{} }; try h.write(&wrq); errdefer h.cancel(); try h.expectAck(0); try h.sendData(1, "hello"); try h.expectError(.not_defined, "Write failed"); try std.testing.expectError(error.WriteFailed, h.wait()); try std.testing.expect(!h.app.finished); } test "write of malformed netascii is refused" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), ""); defer h.deinit(); const wrq: Packet.Wrq = .{ .filename = "f", .mode = .netascii, .options = .{} }; try h.write(&wrq); errdefer h.cancel(); try h.expectAck(0); // A bare CR in the middle of a short, and so final, block. try h.sendData(1, "foo\rbar"); try h.expectError(.illegal_operation, "Malformed netascii"); try std.testing.expectError(error.MalformedNetascii, h.wait()); try std.testing.expect(!h.app.finished); } test "write is refused by its transfer size" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), ""); defer h.deinit(); h.app.capacity = 4; const wrq: Packet.Wrq = .{ .filename = "f", .mode = .octet, .options = .{ .transfer_size = 5 } }; try h.write(&wrq); errdefer h.cancel(); // Refused before any data is sent: no OACK, and "disk full". try h.expectError(.disk_full, null); try std.testing.expectError(error.NoSpaceLeft, h.wait()); } test "write within its transfer size is accepted" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), ""); defer h.deinit(); h.app.capacity = 5; const wrq: Packet.Wrq = .{ .filename = "f", .mode = .octet, .options = .{ .transfer_size = 5 } }; try h.write(&wrq); errdefer h.cancel(); try h.expectOack(.{ .transfer_size = 5 }); try h.sendData(1, "hello"); try h.expectAck(1); try h.wait(); try std.testing.expectEqualStrings("hello", h.app.written.written()); } test "a malformed packet ends the transfer with an error" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "hello"); defer h.deinit(); const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = .{} }; try h.read(&rrq); errdefer h.cancel(); try h.expectData(1, "hello"); try h.sendRaw(&.{ 0, 9 }); try h.expectError(.illegal_operation, "Unknown opcode"); try std.testing.expectError(error.InvalidOpcode, h.wait()); } test "DATA longer than the block size ends the transfer with an error" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), ""); defer h.deinit(); const wrq: Packet.Wrq = .{ .filename = "f", .mode = .octet, .options = .{ .blocksize = 8 } }; try h.write(&wrq); errdefer h.cancel(); try h.expectOack(.{ .blocksize = 8 }); try h.sendData(1, "123456789"); try h.expectError(.illegal_operation, "DATA longer than the block size"); try std.testing.expectError(error.PacketTooLong, h.wait()); } test "a malformed request is answered with an error" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var h: Harness = undefined; try h.init(io, ""); defer h.deinit(); // The failure is logged, which is expected here and not worth a warning. std.testing.log_level = .err; defer std.testing.log_level = .warn; const request = "\x00\x01f\x00bogus\x00"; try h.server.handleIncomingMessage(io, std.testing.allocator, Harness.listening, Harness.loopback, h.client_socket.address, try std.testing.allocator.dupe(u8, request)); try h.expectError(.illegal_operation, "Unknown transfer mode"); } test "a server without writeTo refuses writes" { const ReadOnly = struct { pub const Read = TestApp.Read; pub fn readFrom(_: *const @This(), _: std.Io, _: std.mem.Allocator, _: Request) !Read { return .{ .interface = .fixed("hello") }; } }; var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); std.testing.log_level = .err; defer std.testing.log_level = .warn; var h: Harness = undefined; try h.init(io, ""); defer h.deinit(); var app: ReadOnly = .{}; var server: Server(ReadOnly) = .init(&app, Harness.loopback); var buf: Packet.Buffer = undefined; const wrq: Packet = .{ .wrq = .{ .filename = "f", .mode = .octet, .options = .{} } }; try server.handleIncomingMessage(io, std.testing.allocator, Harness.listening, Harness.loopback, h.client_socket.address, try std.testing.allocator.dupe(u8, try wrq.encode(&buf))); try h.expectError(.access_violation, "Access violation"); } test "the application is told who is asking, and where" { var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); var h: Harness = undefined; try h.init(threaded.io(), "hello"); defer h.deinit(); const options: Packet.Options = .{ .blocksize = 8, .transfer_size = 0 }; const rrq: Packet.Rrq = .{ .filename = "f", .mode = .octet, .options = options }; try h.read(&rrq); errdefer h.cancel(); try h.expectOack(.{ .blocksize = 8, .transfer_size = 5 }); try h.sendAck(0); try h.expectData(1, "hello"); try h.sendAck(1); try h.wait(); const last = h.app.last; try std.testing.expectEqual(.octet, last.mode); // As the client asked, before the server filled in the size. try std.testing.expectEqual(options, last.options); try std.testing.expect(last.remote.eql(&h.client_socket.address)); try std.testing.expect(last.local.eql(&Harness.listening)); try std.testing.expect(last.transfer.eql(&h.server_socket.address)); try std.testing.expect(last.transfer.getPort() != 0); } /// Starts `run` listening on `listen` (with a free port chosen for it), sends /// it a read request at `send_to` (on that same port), and returns what the /// application was told and where the answer came from. fn runOnce(listen_literal: []const u8, send_to_literal: []const u8) !struct { seen: Request, answered_from: std.Io.net.IpAddress, port: u16 } { const App = struct { seen: ?Request = null, pub const Read = TestApp.Read; pub fn readFrom(self: *@This(), _: std.Io, _: std.mem.Allocator, request: Request) !Read { self.seen = request; self.seen.?.filename = ""; return error.FileNotFound; } }; var threaded: std.Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); std.testing.log_level = .err; defer std.testing.log_level = .warn; // A free port, found by binding and letting go of it, so that the test // knows where `run` is listening. var listen = try std.Io.net.IpAddress.parseLiteral(listen_literal); const port = port: { const probe = listen.bind(io, .{ .mode = .dgram, .protocol = .udp }) catch return error.SkipZigTest; defer probe.close(io); break :port probe.address.getPort(); }; listen.setPort(port); var send_to = try std.Io.net.IpAddress.parseLiteral(send_to_literal); send_to.setPort(port); var app: App = .{}; var server: Server(App) = .init(&app, listen); var future = try io.concurrent(Server(App).run, .{ &server, io, std.testing.allocator }); defer future.cancel(io) catch {}; var client_address = send_to; client_address.setPort(0); const client = client_address.bind(io, .{ .mode = .dgram, .protocol = .udp }) catch return error.SkipZigTest; defer client.close(io); // `run` may not have bound yet, so the request is sent until answered. var buf: Packet.Buffer = undefined; const rrq: Packet = .{ .rrq = .{ .filename = "f", .mode = .octet, .options = .{} } }; for (0..50) |_| { try client.send(io, &send_to, try rrq.encode(&buf)); var message_buf: Packet.Buffer = undefined; const message = client.receiveTimeout(io, &message_buf, .{ .duration = .{ .clock = .awake, .raw = .fromMilliseconds(100) }, }) catch |err| switch (err) { error.Timeout => continue, else => |e| return e, }; const answer: Packet = try .decode(message.data, &buf, .{}); try std.testing.expect(answer == .err); try std.testing.expectEqual(.file_not_found, answer.err.code); const seen = app.seen.?; try std.testing.expect(seen.remote.eql(&client.address)); return .{ .seen = seen, .answered_from = message.from, .port = port }; } return error.NoAnswer; } /// 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); } test "run tells the application the address it listens on" { const got = try runOnce("127.0.0.1:0", "127.0.0.1:0"); try std.testing.expect(sameHost(got.seen.local, try .parseLiteral("127.0.0.1:0"))); try std.testing.expectEqual(got.port, got.seen.local.getPort()); } test "listening on every address, the request says which one was used" { if (!pktinfo.supported) return error.SkipZigTest; const got = try runOnce("0.0.0.0:0", "127.0.0.1:0"); try std.testing.expect(sameHost(got.seen.local, try .parseLiteral("127.0.0.1:0"))); try std.testing.expectEqual(got.port, got.seen.local.getPort()); try std.testing.expect(sameHost(got.seen.transfer, got.seen.local)); try std.testing.expect(sameHost(got.answered_from, got.seen.local)); } test "listening on every address, the answer comes from the address used" { // All of 127.0.0.0/8 is the loopback interface on Linux, which makes a // second address to send to without configuring one. if (!pktinfo.supported or builtin.os.tag != .linux) return error.SkipZigTest; const got = try runOnce("0.0.0.0:0", "127.0.0.2:0"); const used: std.Io.net.IpAddress = try .parseLiteral("127.0.0.2:0"); try std.testing.expect(sameHost(got.seen.local, used)); try std.testing.expect(sameHost(got.seen.transfer, used)); // Not 127.0.0.1, which is where the route back would have sent it from. try std.testing.expect(sameHost(got.answered_from, used)); } test "listening on every IPv6 address, the request says which one was used" { if (!pktinfo.supported) return error.SkipZigTest; const got = try runOnce("[::]:0", "[::1]:0"); const used: std.Io.net.IpAddress = try .parseLiteral("[::1]:0"); try std.testing.expect(sameHost(got.seen.local, used)); try std.testing.expect(sameHost(got.answered_from, used)); }