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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315// SPDX-FileCopyrightText: © 2022 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! TFTP packets: decoding them from a datagram and encoding them into one.
const std = @import("std");
const Allocator = std.mem.Allocator;const testing = std.testing;
const netascii = @import("netascii.zig");
/// Reads a NUL terminated netascii filename from `input`, decoding it into a/// slice allocated from `alloc`.fn decodeFilenameZ(alloc: Allocator, input: *std.Io.Reader) (Allocator.Error || netascii.DecodeSentinelErrors)![]const u8 { var buf: std.Io.Writer.Allocating = .init(alloc); errdefer buf.deinit(); const output = &buf.writer; _ = try netascii.decodeZ(input, output); return buf.toOwnedSlice();}
/// Writes `filename` to `output` as NUL terminated netascii.fn encodeFilenameZ(filename: []const u8, output: *std.Io.Writer) !void { var input: std.Io.Reader = .fixed(filename); try netascii.encodeZ(&input, output);}
/// A TFTP packet, tagged by its opcode.////// The slices a decoded packet holds point into the buffer it was decoded with,/// so they live exactly as long as that buffer does.pub const Packet = union(Opcode) { /// The size of a buffer large enough for any packet, since no UDP payload /// can be longer than 65535 bytes. pub const BUFFER_LENGTH = std.math.maxInt(u16); /// A buffer large enough for any packet. pub const Buffer = [BUFFER_LENGTH]u8; pub const Options = @import("Options.zig"); pub const Mode = @import("mode.zig").Mode; pub const Opcode = @import("opcode.zig").Opcode; pub const ErrorCode = @import("errorcode.zig").ErrorCode;
/// The errors `decode` can return. pub const DecodeErrors = error{ UnterminatedFilename, UnterminatedMode, ModeRequired, } || Opcode.DecodeErrors || Mode.DecodeErrors || std.Io.Reader.LimitedAllocError;
/// What `decode` has to know from the rest of the transfer. A DATA packet /// does not say what mode it is in or how large a full block is, so both /// come from the request that started the transfer. pub const DecodeOptions = struct { /// The transfer's mode. Required to decode a DATA packet. mode: ?Mode = null, /// The negotiated block size, or `null` for the default of 512. blocksize: ?u16 = null, // timeout: ?u8 = null, // transfer_size: ?u64 = null,
/// No mode, and the default block size. pub const default: @This() = .{}; /// The `netascii` mode, and the default block size. pub const netascii: @This() = .{ .mode = .netascii }; /// The `mail` mode, and the default block size. pub const mail: @This() = .{ .mode = .mail }; /// The `octet` mode, and the default block size. pub const octet: @This() = .{ .mode = .octet }; };
/// A read request. rrq: Rrq, /// A write request. wrq: Wrq, /// A block of file data. data: Data, /// An acknowledgment. ack: Ack, /// An error. err: Err, /// An option acknowledgment. oack: Oack,
/// A read request: the client asks for `filename`. pub const Rrq = struct { /// The name of the file, decoded from netascii. filename: []const u8, /// The mode the file is to be transferred in. mode: Mode, /// The options requested alongside it. options: Options, };
/// A write request: the client offers to send `filename`. pub const Wrq = struct { /// The name of the file, decoded from netascii. filename: []const u8, /// The mode the file is to be transferred in. mode: Mode, /// The options requested alongside it. options: Options, };
/// A block of file data. pub const Data = struct { /// The block number, counting from one. block: u16, /// The transfer's mode. mode: Mode, /// The block's contents, exactly as they are on the wire. data: []const u8, /// Whether this is the final block, which is shorter than the block /// size. Set by `decode`; `encode` does not use it. last: bool = false, };
/// An acknowledgment. pub const Ack = struct { /// The block acknowledged, or zero for a write request. block: u16, };
/// An error, which ends the transfer. pub const Err = struct { /// What went wrong. code: ErrorCode, /// A human readable explanation. When encoding, `null` means the /// standard message for `code`. msg: ?[]const u8 = null, };
/// An option acknowledgment (RFC 2347). pub const Oack = struct { /// The options the server has accepted. options: Options, };
/// The opcode of the packet. pub fn opcode(self: *const Packet) Opcode { return switch (self.*) { .rrq => .rrq, .wrq => .wrq, .data => .data, .ack => .ack, .err => .err, .oack => .oack, }; }
/// Decodes the packet in the datagram `data`. /// /// Anything the packet holds that has to be copied or decoded (the /// filename, a DATA packet's contents, an ERROR packet's message) is /// placed in `buf`, and the returned packet points into it. A `buf` of /// `Buffer` size is always large enough. /// /// A DATA packet decodes only if `decode_options` names the transfer's /// mode, and is marked `last` if it is shorter than the block size given /// there. One longer than the block size is `error.PacketTooLong`. pub fn decode(data: []const u8, buf: []u8, decode_options: DecodeOptions) DecodeErrors!Packet { var input: std.Io.Reader = .fixed(data); var fba: std.heap.FixedBufferAllocator = .init(buf); const alloc = fba.allocator();
switch (try Opcode.decode(&input)) { .rrq, .wrq => |code| { const filename = try decodeFilenameZ(alloc, &input); const mode: Mode = try .decodeZ(&input); const options: Options = try .decode(&input);
switch (code) { .rrq => { return .{ .rrq = .{ .filename = filename, .mode = mode, .options = options, }, }; },
.wrq => { return .{ .wrq = .{ .filename = filename, .mode = mode, .options = options, }, }; },
.data, .ack, .err, .oack, => unreachable, } },
.data => { const block = try input.takeInt(u16, .big); const mode = decode_options.mode orelse return error.ModeRequired; const blocksize: u16 = decode_options.blocksize orelse 512;
var buffer: std.Io.Writer.Allocating = .init(alloc); const output = &buffer.writer;
// const len = switch (mode) { // .mail, .netascii => try netascii.decode(&input, output), // .octet => try input.streamRemaining(output), // }; const len = try input.streamRemaining(output); if (len > blocksize) return error.PacketTooLong;
return .{ .data = .{ .block = block, .mode = mode, .data = buffer.written(), .last = len < blocksize, }, }; },
.ack => { const block = try input.takeInt(u16, .big);
return .{ .ack = .{ .block = block, }, }; },
.err => { const code: ErrorCode = try .decode(&input);
var msgbuf: std.Io.Writer.Allocating = .init(alloc); const output = &msgbuf.writer; _ = try netascii.decodeZ(&input, output);
return .{ .err = .{ .code = code, .msg = try msgbuf.toOwnedSlice(), }, }; },
.oack => { return .{ .oack = .{ .options = try .decode(&input), }, }; }, } unreachable; }
/// Encodes the packet into `buf`, returning the slice of it that holds the /// datagram. A `buf` of `Buffer` size is always large enough. pub fn encode(self: *const Packet, buf: []u8) ![]const u8 { var output: std.Io.Writer = .fixed(buf); try self.opcode().encode(&output);
switch (self.*) { inline .rrq, .wrq => |p| { try encodeFilenameZ(p.filename, &output); try p.mode.encodeZ(&output); try p.options.encode(&output); }, .data => |p| { try output.writeInt(u16, p.block, .big); try output.writeAll(p.data); }, .ack => |p| { try output.writeInt(u16, p.block, .big); }, .err => |p| { try p.code.encode(&output); const msg = p.msg orelse p.code.message(); var input: std.Io.Reader = .fixed(msg); try netascii.encodeZ(&input, &output); }, .oack => |p| { try p.options.encode(&output); }, }
try output.flush();
return output.buffered(); }
test "data longer than the block size" { var buf: Packet.Buffer = undefined; const input = [_]u8{ 0, 3, 0, 1 } ++ "123456789".*; try testing.expectError(error.PacketTooLong, Packet.decode(&input, &buf, .{ .mode = .octet, .blocksize = 8 })); const packet: Packet = try .decode(&input, &buf, .{ .mode = .octet, .blocksize = 9 }); try testing.expectEqualStrings("123456789", packet.data.data); try testing.expect(!packet.data.last); }
test "datagram decode 1" { var buf: Packet.Buffer = undefined; const input = &[_]u8{ 0x0, 0x1, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x74, 0x78, 0x74, 0x0, 0x6e, 0x65, 0x74, 0x61, 0x73, 0x63, 0x69, 0x69, 0x0 }; const packet: Packet = try .decode(input, &buf, .default); try testing.expect(packet == .rrq); try testing.expectEqualStrings("test.txt", packet.rrq.filename); try testing.expectEqual(.netascii, packet.rrq.mode); }};