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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Which of the host's addresses a datagram was sent to.//!//! A socket bound to the unspecified address, `0.0.0.0` or `::`, receives//! datagrams sent to any of the host's addresses, and `recvfrom` says only//! where each one came from. The kernel will say where it was going as well,//! as a control message alongside the data, if the socket asks: `IP_PKTINFO`//! for IPv4, `IPV6_RECVPKTINFO` for IPv6 (RFC 3542). Zig 0.17 wraps neither,//! but its `recvmsg` already hands back whatever control messages arrive, so//! all that is missing is asking for them and reading them.//!//! A TFTP server wants the answer twice over. The application is told it, so//! that an access control list or a log can tell the host's addresses apart.//! And a transfer's socket is bound to it, so that the replies come from the//! address the client sent its request to: on a host with several, the//! kernel would otherwise choose the source address by the route back, and a//! client that checks where the answer came from would reject it.//!//! Linux and Apple's platforms are supported; the socket options and the//! layouts differ between them only in their constants. Anywhere else,//! `enable` says no and the caller falls back on the address it bound.
const std = @import("std");const builtin = @import("builtin");const testing = std.testing;const IpAddress = std.Io.net.IpAddress;
const native_os = builtin.os.tag;
const apple = switch (native_os) { .macos, .ios, .tvos, .watchos, .visionos, .maccatalyst, .driverkit => true, else => false,};
/// Whether this platform can report a datagram's destination at all.pub const supported = native_os == .linux or apple;
/// The system interface: Linux's own when not linking libc, and libc's/// otherwise, which is always the case on Apple's platforms.const system = if (native_os == .linux and !builtin.link_libc) std.os.linux else std.c;
const IPPROTO_IP = 0;const IPPROTO_IPV6 = 41;
/// The socket option constants. On Apple's platforms Zig 0.17's `std.c.IPV6`/// calls the RFC 3542 `IPV6_PKTINFO` `@"3542PKTINFO"`, a name no other/// platform shares, so Apple's are written out here. They are the values of/// `<netinet/in.h>` and `<netinet6/in6.h>`, and the same as `std.c`'s.const IP = if (apple) struct { const PKTINFO = 26; const RECVPKTINFO = PKTINFO;} else if (supported) system.IP else void;const IPV6 = if (apple) struct { const RECVPKTINFO = 61; const PKTINFO = 46;} else if (supported) system.IPV6 else void;
/// The option that asks for IPv4 destinations, and the type of the control/// message that answers. Linux uses one name for both; Apple has a separate/// option to ask with.const ip_request: u32 = if (!supported) 0 else if (@hasDecl(IP, "RECVPKTINFO")) IP.RECVPKTINFO else IP.PKTINFO;const ip_answer: i32 = if (!supported) 0 else IP.PKTINFO;const ipv6_request: u32 = if (!supported) 0 else IPV6.RECVPKTINFO;const ipv6_answer: i32 = if (!supported) 0 else IPV6.PKTINFO;
const Cmsghdr = if (!supported) void else system.cmsghdr;const InPktinfo = if (!supported) void else system.in_pktinfo;const In6Pktinfo = if (!supported) void else system.in6_pktinfo;
/// Control messages are aligned to this: a `size_t` on Linux, and four bytes/// on Apple's platforms, whatever the width of a pointer.const cmsg_align = if (apple) 4 else @sizeOf(usize);
/// Room for the control messages one datagram can bring: its destination, in/// either family, with space to spare for anything else the socket was asked/// for.pub const control_len = 128;
/// Asks the kernel to report the destination of every datagram `socket`/// receives. Returns whether it will; a platform without support, or a/// kernel that refuses, is not an error, only a server that knows less.pub fn enable(socket: std.Io.net.Socket) bool { if (!supported) return false; const one: c_int = 1; const level: i32, const option: u32 = switch (socket.address) { .ip4 => .{ IPPROTO_IP, ip_request }, .ip6 => .{ IPPROTO_IPV6, ipv6_request }, }; const rc = system.setsockopt(socket.handle, level, option, @ptrCast(&one), @sizeOf(c_int)); return std.posix.errno(rc) == .SUCCESS;}
/// Where a datagram was going, as its control messages report it.pub const Destination = struct { /// The address the datagram was sent to, which may be a broadcast or /// multicast address as well as one of the host's own. address: IpAddress, /// The host's own address to answer it from. The same as `address` /// unless that is not one a socket can be bound to: for IPv4 the kernel /// names the interface's address, and for an IPv6 multicast there is /// nothing better than the unspecified address. reply_from: IpAddress,};
/// The destination reported in `control`, the control messages `recvmsg`/// returned with a datagram, with its port set to `port`, which is the/// receiving socket's own; or `null` if there is none.pub fn destination(control: []const u8, port: u16) ?Destination { if (!supported) return null; const header_space = std.mem.alignForward(usize, @sizeOf(Cmsghdr), cmsg_align);
var offset: usize = 0; while (offset + @sizeOf(Cmsghdr) <= control.len) { const header = std.mem.bytesToValue(Cmsghdr, control[offset..][0..@sizeOf(Cmsghdr)]); const len: usize = @intCast(header.len); // Checked as a subtraction: a header can claim any length at all. if (len < @sizeOf(Cmsghdr) or len > control.len - offset) return null; const data = control[offset + @min(header_space, len) .. offset + len];
if (header.level == IPPROTO_IP and header.type == ip_answer and data.len >= @sizeOf(InPktinfo)) { const info = std.mem.bytesToValue(InPktinfo, data[0..@sizeOf(InPktinfo)]); // Both are in network order, which is the order of the bytes. const to: [4]u8 = @bitCast(info.addr); const local: [4]u8 = @bitCast(info.spec_dst); return .{ .address = .{ .ip4 = .{ .bytes = to, .port = port } }, .reply_from = .{ .ip4 = .{ .bytes = local, .port = port } }, }; } if (header.level == IPPROTO_IPV6 and header.type == ipv6_answer and data.len >= @sizeOf(In6Pktinfo)) { const info = std.mem.bytesToValue(In6Pktinfo, data[0..@sizeOf(In6Pktinfo)]); var to: std.Io.net.Ip6Address = .{ .bytes = info.addr, .port = port }; // A link-local address means nothing without its interface. // Linux declares the index an `i32` and Apple a `u32`; it is an // unsigned index either way, so the bits are taken as they are // rather than cast, which would panic on a negative one. if (to.isLinkLocal()) to.interface = .{ .index = @bitCast(info.ifindex) }; const multicast = info.addr[0] == 0xff; return .{ .address = .{ .ip6 = to }, .reply_from = if (multicast) .{ .ip6 = .{ .bytes = @splat(0), .port = port } } else .{ .ip6 = to }, }; }
offset += @min(std.mem.alignForward(usize, len, cmsg_align), control.len - offset); } return null;}
/// Lays out one control message the way the kernel would, for the tests.fn testMessage(out: []u8, level: i32, kind: anytype, payload: []const u8) []u8 { const header_space = std.mem.alignForward(usize, @sizeOf(Cmsghdr), cmsg_align); const len = header_space + payload.len; var header: Cmsghdr = std.mem.zeroes(Cmsghdr); header.len = @intCast(len); header.level = level; header.type = @intCast(kind); @memset(out, 0); @memcpy(out[0..@sizeOf(Cmsghdr)], std.mem.asBytes(&header)); @memcpy(out[header_space..][0..payload.len], payload); return out[0..std.mem.alignForward(usize, len, cmsg_align)];}
test "an IPv4 destination" { if (!supported) return error.SkipZigTest; var info: InPktinfo = std.mem.zeroes(InPktinfo); info.addr = @bitCast([4]u8{ 255, 255, 255, 255 }); info.spec_dst = @bitCast([4]u8{ 192, 0, 2, 7 }); var buf: [control_len]u8 = undefined; const control = testMessage(&buf, IPPROTO_IP, ip_answer, std.mem.asBytes(&info));
const got = destination(control, 69).?; try testing.expectEqual([4]u8{ 255, 255, 255, 255 }, got.address.ip4.bytes); try testing.expectEqual([4]u8{ 192, 0, 2, 7 }, got.reply_from.ip4.bytes); try testing.expectEqual(69, got.address.getPort());}
test "an IPv6 destination, after a message of another kind" { if (!supported) return error.SkipZigTest; var buf: [control_len]u8 = undefined; const other = testMessage(&buf, IPPROTO_IPV6, 1, "abcdefgh");
var info: In6Pktinfo = std.mem.zeroes(In6Pktinfo); info.addr = .{ 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; info.ifindex = 3; var rest: [control_len]u8 = undefined; const pktinfo = testMessage(&rest, IPPROTO_IPV6, ipv6_answer, std.mem.asBytes(&info)); @memcpy(buf[other.len..][0..pktinfo.len], pktinfo);
const got = destination(buf[0 .. other.len + pktinfo.len], 69).?; try testing.expectEqual(info.addr, got.address.ip6.bytes); try testing.expectEqual(3, got.address.ip6.interface.index); try testing.expect(got.reply_from.eql(&got.address));}
test "an IPv6 multicast destination is answered from the unspecified address" { if (!supported) return error.SkipZigTest; var info: In6Pktinfo = std.mem.zeroes(In6Pktinfo); info.addr = .{ 0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; var buf: [control_len]u8 = undefined; const control = testMessage(&buf, IPPROTO_IPV6, ipv6_answer, std.mem.asBytes(&info));
const got = destination(control, 69).?; try testing.expectEqual(@as([16]u8, @splat(0)), got.reply_from.ip6.bytes);}
test "no destination, and nonsense" { try testing.expectEqual(null, destination(&.{}, 69)); if (!supported) return; // A header claiming more than there is. var buf: [control_len]u8 = @splat(0xff); try testing.expectEqual(null, destination(buf[0..@sizeOf(Cmsghdr)], 69)); // A header claiming less than itself. @memset(&buf, 0); try testing.expectEqual(null, destination(&buf, 69));}
test "any bytes at all are either a destination or none" { // The kernel writes these bytes, but a parser that trusts them is a // parser with a bug waiting for a kernel to find it. var prng: std.Random.DefaultPrng = .init(0x7f7f); const random = prng.random(); var buf: [control_len]u8 align(@alignOf(usize)) = undefined; for (0..100_000) |_| { const len = random.uintAtMost(usize, buf.len); random.bytes(buf[0..len]); // Plausible headers now and then, so that the parser gets past them. if (supported and len >= @sizeOf(Cmsghdr) and random.boolean()) { var header: Cmsghdr = std.mem.zeroes(Cmsghdr); header.len = @intCast(random.uintAtMost(usize, len)); header.level = if (random.boolean()) IPPROTO_IP else IPPROTO_IPV6; header.type = if (random.boolean()) ip_answer else ipv6_answer; @memcpy(buf[0..@sizeOf(Cmsghdr)], std.mem.asBytes(&header)); } if (destination(buf[0..len], 69)) |got| { try testing.expectEqual(69, got.address.getPort()); try testing.expectEqual(69, got.reply_from.getPort()); } }}