// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reading and writing the IP header's ECN field, which QUIC needs and cannot //! reach on its own. //! //! §13.4 of RFC 9000 is the one part of the transport that lives outside the //! packet: the two bits are in the IP header, not in anything QUIC writes, so //! a library with no sockets can count them and react to them but can never //! see or set one. This file is the seam -- everything here is ancillary data //! on a datagram, and everything above it is arithmetic. //! //! §13.4.1 says in as many words that some platforms cannot do this at all: //! "The use of ECN requires the receiving endpoint to read the ECN field from //! an IP packet, which is not possible on all platforms." So every function //! here reports failure by doing nothing, and an endpoint that cannot read //! the field reports no counts, which is the conforming answer rather than a //! degraded one. const std = @import("std"); const builtin = @import("builtin"); const posix = std.posix; const quic = @import("quic"); /// Whether this platform is one this file knows how to ask. pub const available = builtin.os.tag == .linux; const linux = std.os.linux; /// The control message carrying one datagram's ECN field, in the shape /// `sendmsg` wants it. /// /// Sized for the header plus a `c_int`, aligned as the kernel requires, and /// built fresh for each datagram because the codepoint is a per-packet /// decision: §13.4.2 has an endpoint mark "early outgoing packets sent on a /// new path" and stop when validation fails, which a socket-wide option could /// not express for one connection without changing every other connection on /// the same socket. pub const Control = struct { bytes: [hdr_len + align_to(@sizeOf(c_int))]u8 align(@alignOf(usize)) = @splat(0), const hdr_len = align_to(@sizeOf(linux.cmsghdr)); fn align_to(n: usize) usize { return (n + @alignOf(usize) - 1) & ~@as(usize, @alignOf(usize) - 1); } /// Fills this in to ask for `codepoint` on one datagram to `address`, and /// answers the slice to put in that datagram's `OutgoingMessage.control` /// for `sendMany`. The slice points into `c`, so `c` has to live until the /// send has been made. /// /// Empty when there is nothing to ask for -- Not-ECT is the absence of a /// marking rather than a marking of its own, so it is expressed by sending /// no control message at all -- and on a platform this file does not know /// how to ask. `IPV6_TCLASS` for an IPv6 address and `IP_TOS` for an IPv4 /// one, since the option is per family. pub fn forSend(c: *Control, address: *const std.Io.net.IpAddress, codepoint: quic.ack.Codepoint) []const u8 { if (!available or codepoint == .not_ect) return &.{}; const ip6 = address.* == .ip6; const value: c_int = @backingInt(codepoint); const header: *linux.cmsghdr = @ptrCast(@alignCast(&c.bytes)); header.* = .{ .len = hdr_len + @sizeOf(c_int), .level = if (ip6) posix.IPPROTO.IPV6 else posix.IPPROTO.IP, .type = if (ip6) linux.IPV6.TCLASS else linux.IP.TOS, }; @memcpy(c.bytes[hdr_len..][0..@sizeOf(c_int)], std.mem.asBytes(&value)); return &c.bytes; } test forSend { // One control buffer per datagram, because the marking is decided per // datagram: ECT(0) on this one, which is what §13.4.2 has an endpoint // send while it finds out whether the path will carry the marks. var control: Control = .{}; const peer: std.Io.net.IpAddress = try .parse("127.0.0.1", 4433); const ancillary = control.forSend(&peer, .ect0); if (!available) return testing.expectEqual(@as(usize, 0), ancillary.len); try testing.expect(ancillary.len > 0); // What it asked for reads back as itself. try testing.expectEqual(quic.ack.Codepoint.ect0, fromControl(ancillary)); } }; /// Asks the kernel to report the ECN field of every datagram this socket /// receives. /// /// Both families, because a socket bound to the unspecified address answers /// both and the option is per family. A failure is not an error: §13.4.1's /// endpoint without access to the field is a conforming endpoint, and the /// whole of what it loses is the ability to report counts. pub fn requestOnReceive(handle: posix.fd_t) void { if (!available) return; const on: c_int = 1; posix.setsockopt(handle, posix.IPPROTO.IP, linux.IP.RECVTOS, std.mem.asBytes(&on)) catch {}; posix.setsockopt(handle, posix.IPPROTO.IPV6, linux.IPV6.RECVTCLASS, std.mem.asBytes(&on)) catch {}; } test requestOnReceive { const io = testing.io; const loopback: std.Io.net.IpAddress = try .parse("127.0.0.1", 0); var socket = try loopback.bind(io, .{ .mode = .dgram }); defer socket.close(io); // Once, before the first receive; there is no failure to handle. requestOnReceive(socket.handle); if (!available) return; var value: c_int = 0; var len: posix.socklen_t = @sizeOf(c_int); const rc = linux.getsockopt(socket.handle, posix.IPPROTO.IP, linux.IP.RECVTOS, std.mem.asBytes(&value), &len); try testing.expectEqual(@as(usize, 0), rc); try testing.expectEqual(@as(c_int, 1), value); } /// The ECN field of a received datagram, out of the ancillary data that came /// with it. /// /// `control` is what the kernel wrote into `IncomingMessage.control` on a /// socket `requestOnReceive` was called for. The first `IP_TOS` or /// `IPV6_TCLASS` message in it is the one read, and anything else is passed /// over. /// /// Not-ECT when the platform said nothing, which is both the honest answer /// and the harmless one: it is what an unmarked packet carries, and counting /// it is `countEcn`'s one no-op. A buffer that is truncated or lies about its /// lengths says nothing in the same way, rather than being read past. pub fn fromControl(control: []const u8) quic.ack.Codepoint { if (!available) return .not_ect; var at: usize = 0; while (at + @sizeOf(linux.cmsghdr) <= control.len) { const header: *const linux.cmsghdr = @ptrCast(@alignCast(control.ptr + at)); if (header.len < @sizeOf(linux.cmsghdr)) return .not_ect; if (at + header.len > control.len) return .not_ect; const body_at = at + Control.hdr_len; const is_tos = header.level == posix.IPPROTO.IP and header.type == linux.IP.TOS; const is_tclass = header.level == posix.IPPROTO.IPV6 and header.type == linux.IPV6.TCLASS; if ((is_tos or is_tclass) and body_at < control.len) { // The kernel sends a `c_int` for IPV6_TCLASS and a single octet // for IP_TOS, and the two bits wanted are the low ones either // way on a little-endian machine. Reading the first octet is // right for both and wrong on a big-endian one, which is why the // width is checked rather than assumed. const body = control[body_at..@min(control.len, at + header.len)]; if (body.len >= @sizeOf(c_int)) { var value: c_int = undefined; @memcpy(std.mem.asBytes(&value), body[0..@sizeOf(c_int)]); return @fromBackingInt(@intCast(@as(u2, @truncate(@as(u32, @bitCast(value)))))); } if (body.len >= 1) return @fromBackingInt(@intCast(@as(u2, @truncate(body[0])))); } at += Control.align_to(header.len); } return .not_ect; } test fromControl { // A CE mark, in the shape the kernel delivers one -- which is the shape // `forSend` builds -- and which §13.4.1 has the receiver count and report // back in its ACK frames. var control: Control = .{}; const peer: std.Io.net.IpAddress = try .parse("127.0.0.1", 4433); const ancillary = control.forSend(&peer, .ce); const expected: quic.ack.Codepoint = if (available) .ce else .not_ect; try testing.expectEqual(expected, fromControl(ancillary)); // No ancillary data at all is an unmarked datagram. try testing.expectEqual(quic.ack.Codepoint.not_ect, fromControl(&.{})); } const testing = std.testing; test "an empty control buffer is not a marking" { try testing.expectEqual(quic.ack.Codepoint.not_ect, fromControl(&.{})); } test "a control buffer that lies about its length is not read past" { // Ancillary data comes from the kernel, but the buffer it was written // into is this library's, and a length longer than the buffer would walk // off the end of it. var bytes: [@sizeOf(linux.cmsghdr) + 8]u8 align(@alignOf(usize)) = @splat(0); const header: *linux.cmsghdr = @ptrCast(@alignCast(&bytes)); header.* = .{ .len = 1 << 20, .level = posix.IPPROTO.IP, .type = linux.IP.TOS }; try testing.expectEqual(quic.ack.Codepoint.not_ect, fromControl(&bytes)); } test "Not-ECT asks for no control message at all" { // The absence of a marking rather than a marking of its own, so there is // nothing to say and saying nothing is how it is said. var control: Control = .{}; const address: std.Io.net.IpAddress = try .parse("127.0.0.1", 0); try testing.expectEqual(@as(usize, 0), control.forSend(&address, .not_ect).len); }