garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /net/src/lib.rs

raw

//! Pinnacle's network stack, as pure state machines: frames go in through
//! [`Stack::receive`], frames to send come out of [`Stack::transmit`], and
//! what happened for the sockets comes out of [`Stack::event`]. Time is a
//! parameter (milliseconds), so the same code runs in the kernel and in
//! host tests with no network at all.
//!
//! Ethernet II; ARP; IPv4 (no fragments, no options); IPv6 (no fragments)
//! with its addresses from the routers' prefixes and its neighbours found by
//! solicitation (`ipv6`); ICMP and ICMPv6 echo replies; UDP for DHCP (the
//! stack configures itself) and DNS (A and AAAA records); TCP over either
//! family with active and passive open, retransmission with exponential
//! backoff, a fixed receive window, and an orderly close.

#![no_std]

extern crate alloc;

pub mod hpack;
pub mod http;
pub mod http2;
mod ip;
mod ipv6;
pub mod ntp;
pub mod nts;
mod tcp;
mod wire;

use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;
pub use ip::{IpAddr, parse_ip, parse_ipv4, parse_ipv6};
pub use tcp::TcpState;
use wire::*;

pub type Ipv4 = [u8; 4];
pub type Ipv6 = [u8; 16];
pub type Mac = [u8; 6];
pub type SocketId = u32;

const BROADCAST_MAC: Mac = [0xff; 6];
const ETHERTYPE_IPV4: u16 = 0x0800;
const ETHERTYPE_ARP: u16 = 0x0806;
const PROTO_ICMP: u8 = 1;
const PROTO_TCP: u8 = 6;
const PROTO_UDP: u8 = 17;
const DHCP_CLIENT: u16 = 68;
const DHCP_SERVER: u16 = 67;
const DNS_PORT: u16 = 53;
const DNS_LOCAL_PORT: u16 = 53_053;
const DHCP_RETRY_MS: u64 = 2000;
const ARP_RETRY_MS: u64 = 1000;
const DNS_RETRY_MS: u64 = 3000;
/// Frames waiting for a neighbour's address, at most.
const ARP_QUEUE: usize = 64;
/// DNS record types.
const DNS_A: u16 = 1;
const DNS_AAAA: u16 = 28;

/// What the stack tells its user.
#[derive(Debug, PartialEq, Eq)]
pub enum Event {
    /// DHCP gave the stack its address.
    Configured {
        ip: Ipv4,
        router: Ipv4,
        dns: Ipv4,
    },
    /// A router's prefix gave the stack a global IPv6 address.
    Configured6 {
        ip: Ipv6,
        router: Option<Ipv6>,
        dns: Option<Ipv6>,
    },
    /// A connection is open (after `connect`, or accepted on a listening port).
    Connected {
        socket: SocketId,
    },
    /// A listening port accepted a connection: `socket` is the new one.
    Accepted {
        listener: u16,
        socket: SocketId,
    },
    Data {
        socket: SocketId,
        data: Vec<u8>,
    },
    /// The peer will send nothing more (it closed, or reset the connection,
    /// or it never answered).
    Closed {
        socket: SocketId,
        reset: bool,
    },
    /// A name's address, of a family this stack can reach: IPv4 first while
    /// it has an IPv4 address, for with no Happy Eyeballs (RFC 8305) to fall
    /// back, an IPv6 path that is broken would leave the name unreachable;
    /// IPv6 on a network without IPv4, or for a name with no IPv4 address.
    Resolved {
        query: u16,
        address: Option<IpAddr>,
    },
    /// A datagram for a bound UDP port.
    Datagram {
        socket: SocketId,
        from: IpAddr,
        port: u16,
        data: Vec<u8>,
    },
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Dhcp {
    Off,
    Discovering {
        xid: u32,
        sent: u64,
    },
    Requesting {
        xid: u32,
        offered: Ipv4,
        server: Ipv4,
        sent: u64,
    },
    Bound,
}

pub struct Config {
    pub ip: Ipv4,
    pub mask: Ipv4,
    pub router: Ipv4,
    pub dns: Ipv4,
}

/// The IPv6 side, once a router has given an address.
pub struct Config6 {
    pub ip: Ipv6,
    pub link_local: Ipv6,
    pub router: Option<Ipv6>,
    pub dns: Option<Ipv6>,
}

/// One record type's answer to a lookup.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Answer {
    /// Not asked: the stack cannot reach that family.
    Unasked,
    Waiting {
        id: u16,
    },
    Got(Option<IpAddr>),
}

struct Query {
    id: u16,
    name: String,
    sent: u64,
    tries: u8,
    /// A, then AAAA.
    answers: [Answer; 2],
}

pub struct Stack {
    mac: Mac,
    config: Option<Config>,
    dhcp: Dhcp,
    v6: ipv6::State,
    arp: Vec<(Ipv4, Mac)>,
    /// IP packets waiting for a neighbour's address: next hop, packet,
    /// when it was last asked for.
    unresolved: VecDeque<(IpAddr, Vec<u8>, u64)>,
    out: VecDeque<Vec<u8>>,
    events: VecDeque<Event>,
    sockets: Vec<tcp::Socket>,
    listening: Vec<u16>,
    /// Bound UDP ports and their sockets.
    udp: Vec<(u16, SocketId)>,
    next_socket: SocketId,
    next_port: u16,
    queries: Vec<Query>,
    next_query: u16,
    /// The next DNS message's id (two to a lookup, one for each type).
    next_dns: u16,
    ip_id: u16,
}

impl Stack {
    /// A stack with no address yet; [`Stack::start`] or
    /// [`Stack::configure`] gives it one.
    pub fn new(mac: Mac, seed: u64) -> Stack {
        Stack {
            mac,
            config: None,
            dhcp: Dhcp::Off,
            v6: ipv6::State::new(seed),
            arp: Vec::new(),
            unresolved: VecDeque::new(),
            out: VecDeque::new(),
            events: VecDeque::new(),
            sockets: Vec::new(),
            listening: Vec::new(),
            udp: Vec::new(),
            next_socket: 1,
            next_port: 49_152 + (seed % 10_000) as u16,
            queries: Vec::new(),
            next_query: (seed % 60_000) as u16 + 1,
            next_dns: (seed >> 16) as u16,
            ip_id: seed as u16,
        }
    }

    /// An IPv4 address given, not asked for.
    pub fn configure(&mut self, config: Config) {
        self.config = Some(config);
        self.dhcp = Dhcp::Bound;
    }

    pub fn config(&self) -> Option<&Config> {
        self.config.as_ref()
    }

    /// The IPv6 side, once a router gave a global address.
    pub fn config6(&self) -> Option<Config6> {
        Some(Config6 {
            ip: self.v6.global?,
            link_local: self.v6.link_local(),
            router: self.v6.router,
            dns: self.v6.dns,
        })
    }

    /// Whether it has an address it can reach the internet from, of
    /// either family.
    pub fn online(&self) -> bool {
        self.config.is_some() || self.v6.global.is_some()
    }

    /// Onto the network: asks DHCP for an IPv4 address and the routers for
    /// IPv6 prefixes, taking its IPv6 link-local address at once.
    pub fn start(&mut self, now: u64) {
        let xid = u32::from_be_bytes([self.mac[2], self.mac[3], self.mac[4], self.mac[5]]) ^ now as u32;
        self.dhcp = Dhcp::Discovering { xid, sent: now };
        self.send_dhcp(1, xid, None, None);
        self.v6.on = true;
        self.join_groups();
        self.solicit_routers(now);
    }

    /// Off the network: its addresses, every connection, socket, listening
    /// port and lookup gone, nothing more sent and no timer left. Socket and
    /// query numbers go on from where they were, so one given before is
    /// never mistaken for one given after [`Stack::start`] brings it
    /// back.
    pub fn stop(&mut self) {
        self.config = None;
        self.dhcp = Dhcp::Off;
        self.v6.reset();
        self.arp.clear();
        self.unresolved.clear();
        self.out.clear();
        self.events.clear();
        self.sockets.clear();
        self.listening.clear();
        self.udp.clear();
        self.queries.clear();
    }

    pub fn transmit(&mut self) -> Option<Vec<u8>> {
        self.out.pop_front()
    }

    pub fn event(&mut self) -> Option<Event> {
        self.events.pop_front()
    }

    /// When [`poll`](Self::poll) has something to do next (ms, the clock it
    /// is given), or `None` while no timer runs: the kernel sleeps until then
    /// rather than polling.
    pub fn next_deadline(&self) -> Option<u64> {
        let dhcp = match self.dhcp {
            Dhcp::Discovering { sent, .. } | Dhcp::Requesting { sent, .. } => Some(sent + DHCP_RETRY_MS),
            _ => None,
        };
        let arp = self.unresolved.iter().map(|(_, _, at)| at + ARP_RETRY_MS);
        let tcp = self.sockets.iter().filter_map(|s| s.deadline());
        let dns = self.queries.iter().map(|q| q.sent + DNS_RETRY_MS);
        dhcp.into_iter()
            .chain(self.v6.deadline())
            .chain(arp)
            .chain(tcp)
            .chain(dns)
            .min()
    }

    /// Timers: DHCP, router solicitation and neighbour retries, TCP
    /// retransmission, DNS.
    pub fn poll(&mut self, now: u64) {
        match self.dhcp {
            Dhcp::Discovering { sent, .. } if now - sent >= DHCP_RETRY_MS => {
                let xid =
                    u32::from_be_bytes([self.mac[2], self.mac[3], self.mac[4], self.mac[5]]) ^ now as u32;
                self.dhcp = Dhcp::Discovering { xid, sent: now };
                self.send_dhcp(1, xid, None, None);
            }
            Dhcp::Requesting {
                xid,
                offered,
                server,
                sent,
            } if now - sent >= DHCP_RETRY_MS => {
                self.dhcp = Dhcp::Requesting {
                    xid,
                    offered,
                    server,
                    sent: now,
                };
                self.send_dhcp(3, xid, Some(offered), Some(server));
            }
            _ => {}
        }
        if self.v6.deadline().is_some_and(|d| now >= d) {
            self.solicit_routers(now);
        }
        let mut retry: Vec<IpAddr> = Vec::new();
        for (ip, _, at) in &self.unresolved {
            if now - at >= ARP_RETRY_MS && !retry.contains(ip) {
                retry.push(*ip);
            }
        }
        for ip in retry {
            self.unresolved
                .iter_mut()
                .filter(|(i, ..)| *i == ip)
                .for_each(|(_, _, at)| *at = now);
            self.ask_neighbour(ip);
        }
        for i in 0..self.sockets.len() {
            let segments = self.sockets[i].poll(now);
            self.send_segments(i, segments);
        }
        self.reap();
        let due: Vec<u16> = self
            .queries
            .iter()
            .filter(|q| now - q.sent >= DNS_RETRY_MS)
            .map(|q| q.id)
            .collect();
        for id in due {
            let Some(i) = self.queries.iter().position(|q| q.id == id) else {
                continue;
            };
            if self.queries[i].tries >= 2 {
                // Asked three times: what is still unanswered has no answer.
                for a in &mut self.queries[i].answers {
                    if matches!(a, Answer::Waiting { .. }) {
                        *a = Answer::Got(None);
                    }
                }
                self.settle(i);
                continue;
            }
            let q = &mut self.queries[i];
            q.sent = now;
            q.tries += 1;
            let name = q.name.clone();
            let waiting: Vec<(u16, u16)> = [DNS_A, DNS_AAAA]
                .iter()
                .zip(q.answers)
                .filter_map(|(&kind, a)| match a {
                    Answer::Waiting { id } => Some((id, kind)),
                    _ => None,
                })
                .collect();
            for (wire_id, kind) in waiting {
                self.send_dns(wire_id, &name, kind);
            }
        }
    }

    // ---- TCP ----

    /// Opens a connection to `ip:port`. Its `Connected` event follows.
    pub fn connect(&mut self, ip: impl Into<IpAddr>, port: u16, now: u64) -> SocketId {
        let id = self.next_socket;
        self.next_socket += 1;
        let local = self.next_port;
        self.next_port = if self.next_port == u16::MAX {
            49_152
        } else {
            self.next_port + 1
        };
        let (socket, segment) = tcp::Socket::connect(id, local, ip.into(), port, now);
        self.sockets.push(socket);
        let i = self.sockets.len() - 1;
        self.send_segments(i, alloc::vec![segment]);
        id
    }

    /// Accepts connections on `port`, of either family, each announced by
    /// `Accepted`.
    pub fn listen(&mut self, port: u16) {
        if !self.listening.contains(&port) {
            self.listening.push(port);
        }
    }

    /// Stops accepting connections on `port`; those made stay.
    pub fn unlisten(&mut self, port: u16) {
        self.listening.retain(|&p| p != port);
    }

    pub fn send(&mut self, socket: SocketId, data: &[u8], now: u64) {
        if let Some(i) = self.sockets.iter().position(|s| s.id == socket) {
            let segments = self.sockets[i].send(data, now);
            self.send_segments(i, segments);
        }
    }

    /// Closes the sending side once everything queued is sent.
    pub fn close(&mut self, socket: SocketId, now: u64) {
        if let Some(i) = self.sockets.iter().position(|s| s.id == socket) {
            let segments = self.sockets[i].close(now);
            self.send_segments(i, segments);
            self.reap();
        }
    }

    pub fn state(&self, socket: SocketId) -> Option<TcpState> {
        self.sockets.iter().find(|s| s.id == socket).map(|s| s.state)
    }

    fn reap(&mut self) {
        self.sockets.retain(|s| s.state != TcpState::Closed);
    }

    fn send_segments(&mut self, index: usize, segments: Vec<tcp::Segment>) {
        let (remote, events) = {
            let s = &mut self.sockets[index];
            (s.remote, core::mem::take(&mut s.events))
        };
        self.events.extend(events);
        for segment in segments {
            let Some(source) = self.source_for(&remote) else {
                continue;
            };
            let bytes = segment.encode(&source, &remote);
            self.send_ip(source, remote, PROTO_TCP, &bytes);
        }
    }

    // ---- UDP ----

    /// Binds a UDP port (0: any free one), for either family. Its datagrams
    /// come as `Datagram` events. Returns the socket and the port, or `None`
    /// if taken.
    pub fn udp_bind(&mut self, port: u16) -> Option<(SocketId, u16)> {
        let port = if port == 0 {
            (49_152..=u16::MAX).find(|p| !self.udp.iter().any(|(q, _)| q == p))?
        } else {
            port
        };
        if self.udp.iter().any(|(p, _)| *p == port) || port == DNS_LOCAL_PORT || port == DHCP_CLIENT {
            return None;
        }
        let id = self.next_socket;
        self.next_socket += 1;
        self.udp.push((port, id));
        Some((id, port))
    }

    pub fn udp_unbind(&mut self, socket: SocketId) {
        self.udp.retain(|(_, s)| *s != socket);
    }

    pub fn udp_send_to(&mut self, socket: SocketId, to: impl Into<IpAddr>, port: u16, data: &[u8]) {
        if let Some(&(from, _)) = self.udp.iter().find(|(_, s)| *s == socket) {
            self.send_udp(to.into(), from, port, data);
        }
    }

    // ---- DNS ----

    /// Looks up `name`'s address; its `Resolved` event follows.
    pub fn resolve(&mut self, name: &str, now: u64) -> u16 {
        let id = self.next_query;
        self.next_query = self.next_query.wrapping_add(1).max(1);
        if let Some(ip) = parse_ip(name) {
            self.events.push_back(Event::Resolved {
                query: id,
                address: Some(ip),
            });
            return id;
        }
        // Ask for the families it can reach; for A all the same when it
        // can reach none yet, which a later address may make useful.
        let (v4, v6) = (self.config.is_some(), self.v6_routable());
        let mut answers = [Answer::Unasked; 2];
        for (i, (wanted, kind)) in [(v4 || !v6, DNS_A), (v6, DNS_AAAA)].into_iter().enumerate() {
            if wanted {
                let wire_id = self.next_dns;
                self.next_dns = self.next_dns.wrapping_add(1);
                answers[i] = Answer::Waiting { id: wire_id };
                self.send_dns(wire_id, name, kind);
            }
        }
        self.queries.push(Query {
            id,
            name: name.into(),
            sent: now,
            tries: 0,
            answers,
        });
        id
    }

    /// Whether IPv6 reaches beyond the link: a global address and a router.
    fn v6_routable(&self) -> bool {
        self.v6.global.is_some() && self.v6.router.is_some()
    }

    /// The name server: DHCP's, else the one a router named.
    fn dns_server(&self) -> Option<IpAddr> {
        match (&self.config, self.v6.dns) {
            (Some(c), _) => Some(IpAddr::V4(c.dns)),
            (None, Some(d)) => Some(IpAddr::V6(d)),
            (None, None) => None,
        }
    }

    fn send_dns(&mut self, id: u16, name: &str, kind: u16) {
        let Some(dns) = self.dns_server() else {
            return;
        };
        let mut q = Vec::new();
        q.extend_from_slice(&id.to_be_bytes());
        q.extend_from_slice(&[0x01, 0x00, 0, 1, 0, 0, 0, 0, 0, 0]);
        for label in name.split('.').filter(|l| !l.is_empty()) {
            q.push(label.len().min(63) as u8);
            q.extend_from_slice(&label.as_bytes()[..label.len().min(63)]);
        }
        q.push(0);
        q.extend_from_slice(&kind.to_be_bytes());
        q.extend_from_slice(&[0, 1]);
        self.send_udp(dns, DNS_LOCAL_PORT, DNS_PORT, &q);
    }

    fn receive_dns(&mut self, data: &[u8]) {
        let Some(wire_id) = be16(data, 0) else { return };
        let found = self.queries.iter().enumerate().find_map(|(i, q)| {
            let slot = q
                .answers
                .iter()
                .position(|a| *a == Answer::Waiting { id: wire_id })?;
            Some((i, slot))
        });
        let Some((i, slot)) = found else { return };
        let kind = if slot == 0 { DNS_A } else { DNS_AAAA };
        self.queries[i].answers[slot] = Answer::Got(parse_dns_answer(data, kind));
        self.settle(i);
    }

    /// Answers lookup `i` once its answers decide it: the preferred
    /// family's address (see [`Event::Resolved`]), or the other's when that
    /// one has none.
    fn settle(&mut self, i: usize) {
        let [a, aaaa] = self.queries[i].answers;
        let order = if self.config.is_some() {
            [a, aaaa]
        } else {
            [aaaa, a]
        };
        let mut address = None;
        for answer in order {
            match answer {
                Answer::Waiting { .. } => return,
                Answer::Got(Some(ip)) => {
                    address = Some(ip);
                    break;
                }
                Answer::Got(None) | Answer::Unasked => {}
            }
        }
        let q = self.queries.remove(i);
        self.events.push_back(Event::Resolved { query: q.id, address });
    }

    // ---- Receiving ----

    pub fn receive(&mut self, frame: &[u8], now: u64) {
        let Some(ethertype) = be16(frame, 12) else { return };
        let from: Mac = frame[6..12].try_into().unwrap();
        let payload = &frame[14..];
        match ethertype {
            ETHERTYPE_ARP => self.receive_arp(payload),
            ETHERTYPE_IPV4 => self.receive_ipv4(payload, now),
            ipv6::ETHERTYPE => self.receive_ipv6(payload, from, now),
            _ => {}
        }
    }

    fn receive_arp(&mut self, p: &[u8]) {
        if p.len() < 28 || be16(p, 0) != Some(1) || be16(p, 2) != Some(ETHERTYPE_IPV4) {
            return;
        }
        let op = be16(p, 6).unwrap();
        let sender_mac: Mac = p[8..14].try_into().unwrap();
        let sender_ip: Ipv4 = p[14..18].try_into().unwrap();
        let target_ip: Ipv4 = p[24..28].try_into().unwrap();
        self.learn_v4(sender_ip, sender_mac);
        let mine = self.config.as_ref().map(|c| c.ip);
        if op == 1 && Some(target_ip) == mine {
            let mut reply = Vec::with_capacity(28);
            reply.extend_from_slice(&[0, 1, 8, 0, 6, 4, 0, 2]);
            reply.extend_from_slice(&self.mac);
            reply.extend_from_slice(&target_ip);
            reply.extend_from_slice(&sender_mac);
            reply.extend_from_slice(&sender_ip);
            self.send_frame(sender_mac, ETHERTYPE_ARP, &reply);
        }
    }

    fn learn_v4(&mut self, ip: Ipv4, mac: Mac) {
        match self.arp.iter_mut().find(|(i, _)| *i == ip) {
            Some(entry) => entry.1 = mac,
            None => self.arp.push((ip, mac)),
        }
        self.release(IpAddr::V4(ip), mac);
    }

    fn learn_v6(&mut self, ip: Ipv6, mac: Mac) {
        self.v6.learn(ip, mac);
        self.release(IpAddr::V6(ip), mac);
    }

    /// Sends what waited for this neighbour.
    fn release(&mut self, ip: IpAddr, mac: Mac) {
        let ethertype = match ip {
            IpAddr::V4(_) => ETHERTYPE_IPV4,
            IpAddr::V6(_) => ipv6::ETHERTYPE,
        };
        let mut kept = VecDeque::new();
        while let Some((hop, packet, at)) = self.unresolved.pop_front() {
            if hop == ip {
                self.send_frame(mac, ethertype, &packet);
            } else {
                kept.push_back((hop, packet, at));
            }
        }
        self.unresolved = kept;
    }

    fn receive_ipv4(&mut self, p: &[u8], now: u64) {
        if p.len() < 20 || p[0] >> 4 != 4 {
            return;
        }
        let header = usize::from(p[0] & 0xf) * 4;
        let total = usize::from(be16(p, 2).unwrap()).min(p.len());
        if header < 20 || total < header || checksum(&p[..header]) != 0 {
            return;
        }
        let fragment = be16(p, 6).unwrap();
        if fragment & 0x3fff != 0 {
            return; // fragments are not reassembled
        }
        let protocol = p[9];
        let source: Ipv4 = p[12..16].try_into().unwrap();
        let destination: Ipv4 = p[16..20].try_into().unwrap();
        let mine = self.config.as_ref().map(|c| c.ip);
        let broadcast = destination == [255; 4];
        if Some(destination) != mine && !broadcast && mine.is_some() {
            return;
        }
        let body = &p[header..total];
        let (from, to) = (IpAddr::V4(source), IpAddr::V4(destination));
        match protocol {
            PROTO_ICMP if Some(destination) == mine => self.receive_icmp(source, body),
            PROTO_UDP => self.receive_udp(from, to, body, now),
            PROTO_TCP if Some(destination) == mine => self.receive_tcp(from, to, body, now),
            _ => {}
        }
    }

    fn receive_ipv6(&mut self, p: &[u8], from_mac: Mac, now: u64) {
        if p.len() < 40 || p[0] >> 4 != 6 {
            return;
        }
        let len = usize::from(be16(p, 4).unwrap());
        let Some(payload) = p.get(40..40 + len) else {
            return;
        };
        let (next, hop_limit) = (p[6], p[7]);
        let source: Ipv6 = p[8..24].try_into().unwrap();
        let destination: Ipv6 = p[24..40].try_into().unwrap();
        if !self.v6.accepts(&destination) {
            return;
        }
        let Some((protocol, body)) = ipv6::upper_layer(next, payload) else {
            return;
        };
        let (from, to) = (IpAddr::V6(source), IpAddr::V6(destination));
        let unicast = !ipv6::multicast(&destination);
        match protocol {
            ipv6::PROTO_ICMPV6 if transport_checksum(&from, &to, ipv6::PROTO_ICMPV6, body) == 0 => {
                self.receive_icmpv6(source, destination, hop_limit, body, from_mac, now)
            }
            PROTO_UDP => self.receive_udp(from, to, body, now),
            PROTO_TCP if unicast => self.receive_tcp(from, to, body, now),
            _ => {}
        }
    }

    fn receive_icmp(&mut self, source: Ipv4, body: &[u8]) {
        if body.len() < 8 || body[0] != 8 || checksum(body) != 0 {
            return;
        }
        let mut reply = body.to_vec();
        reply[0] = 0;
        reply[2..4].copy_from_slice(&[0, 0]);
        let sum = checksum(&reply);
        reply[2..4].copy_from_slice(&sum.to_be_bytes());
        if let Some(mine) = self.config.as_ref().map(|c| c.ip) {
            self.send_ip(IpAddr::V4(mine), IpAddr::V4(source), PROTO_ICMP, &reply);
        }
    }

    fn receive_icmpv6(
        &mut self,
        source: Ipv6,
        destination: Ipv6,
        hop_limit: u8,
        m: &[u8],
        from_mac: Mac,
        now: u64,
    ) {
        let Some(&kind) = m.first() else { return };
        // Neighbour discovery comes only from the link: a hop limit of 255
        // is one no router has forwarded (RFC 4861, 6.1).
        let on_link = hop_limit == 255;
        match kind {
            ipv6::ECHO_REQUEST if m.len() >= 8 => {
                let mut reply = m.to_vec();
                reply[0] = ipv6::ECHO_REPLY;
                let from = if ipv6::multicast(&destination) {
                    self.v6.source_for(&source)
                } else {
                    Some(destination)
                };
                if let Some(from) = from {
                    let reply = icmpv6(&from, &source, reply);
                    self.send_ip(IpAddr::V6(from), IpAddr::V6(source), ipv6::PROTO_ICMPV6, &reply);
                }
            }
            ipv6::ROUTER_ADVERTISEMENT if on_link && ipv6::link_scoped(&source) => {
                if let Some(ad) = ipv6::parse_advertisement(m) {
                    self.advertised(source, ad, now);
                }
            }
            ipv6::NEIGHBOR_SOLICITATION if on_link => {
                let Some((target, mac)) = ipv6::parse_solicitation(m) else {
                    return;
                };
                let unspecified = source == [0; 16];
                if let Some(mac) = mac.filter(|_| !unspecified) {
                    self.learn_v6(source, mac);
                }
                if !self.v6.mine(&target) {
                    return;
                }
                let to = if unspecified { ipv6::ALL_NODES } else { source };
                let reply = ipv6::neighbour_advertisement(&target, &self.mac, !unspecified);
                let reply = icmpv6(&target, &to, reply);
                let packet = ipv6::packet(&target, &to, ipv6::PROTO_ICMPV6, 255, &reply);
                let mac = if unspecified {
                    ipv6::multicast_mac(&to)
                } else {
                    mac.unwrap_or(from_mac)
                };
                self.send_frame(mac, ipv6::ETHERTYPE, &packet);
            }
            ipv6::NEIGHBOR_ADVERTISEMENT if on_link => {
                if let Some((target, mac)) = ipv6::parse_neighbour_advertisement(m) {
                    self.learn_v6(target, mac.unwrap_or(from_mac));
                }
            }
            _ => {}
        }
    }

    /// A router said what the link is: its prefix gives the global address,
    /// it is the default router while its lifetime runs, it may name a
    /// name server.
    fn advertised(&mut self, router: Ipv6, ad: ipv6::Advertisement, _now: u64) {
        if let Some(mac) = ad.router_mac {
            self.learn_v6(router, mac);
        }
        if ad.lifetime > 0 {
            self.v6.router = Some(router);
        } else if self.v6.router == Some(router) {
            self.v6.router = None;
        }
        if ad.dns.is_some() {
            self.v6.dns = ad.dns;
        }
        let before = self.v6.global;
        match ad.prefix {
            Some((prefix, valid)) if valid > 0 => {
                let mut ip = [0u8; 16];
                ip[..8].copy_from_slice(&prefix);
                ip[8..].copy_from_slice(&self.v6.iid);
                self.v6.global = Some(ip);
            }
            Some((prefix, _)) if self.v6.global.is_some_and(|g| g[..8] == prefix) => self.v6.global = None,
            _ => {}
        }
        if let Some(ip) = self.v6.global.filter(|&g| Some(g) != before) {
            self.events.push_back(Event::Configured6 {
                ip,
                router: self.v6.router,
                dns: self.v6.dns,
            });
        }
    }

    fn receive_udp(&mut self, source: IpAddr, destination: IpAddr, u: &[u8], now: u64) {
        if u.len() < 8 {
            return;
        }
        // IPv6 makes UDP's checksum compulsory (RFC 8200, 8.1).
        if matches!(source, IpAddr::V6(_)) && transport_checksum(&source, &destination, PROTO_UDP, u) != 0 {
            return;
        }
        let (src_port, dst_port) = (be16(u, 0).unwrap(), be16(u, 2).unwrap());
        let len = usize::from(be16(u, 4).unwrap()).clamp(8, u.len());
        let data = &u[8..len];
        match (src_port, dst_port) {
            (DHCP_SERVER, DHCP_CLIENT) if matches!(source, IpAddr::V4(_)) => self.receive_dhcp(data, now),
            (DNS_PORT, DNS_LOCAL_PORT) if self.dns_server() == Some(source) => self.receive_dns(data),
            (from, to) => {
                if let Some(&(_, socket)) = self.udp.iter().find(|(p, _)| *p == to) {
                    self.events.push_back(Event::Datagram {
                        socket,
                        from: source,
                        port: from,
                        data: data.to_vec(),
                    });
                }
            }
        }
    }

    fn receive_tcp(&mut self, source: IpAddr, destination: IpAddr, t: &[u8], now: u64) {
        if tcp_checksum(&source, &destination, t) != 0 {
            return;
        }
        let Some(segment) = tcp::Segment::decode(t) else {
            return;
        };
        let index = self.sockets.iter().position(|s| {
            s.remote == source
                && s.remote_port == segment.source_port
                && s.local_port == segment.destination_port
        });
        match index {
            Some(i) => {
                let replies = self.sockets[i].receive(&segment, now);
                self.send_segments(i, replies);
                self.reap();
            }
            None if segment.flags & tcp::SYN != 0
                && segment.flags & tcp::ACK == 0
                && self.listening.contains(&segment.destination_port) =>
            {
                let id = self.next_socket;
                self.next_socket += 1;
                let (socket, reply) = tcp::Socket::accept(id, &segment, source, now);
                self.events.push_back(Event::Accepted {
                    listener: segment.destination_port,
                    socket: id,
                });
                self.sockets.push(socket);
                let i = self.sockets.len() - 1;
                self.send_segments(i, alloc::vec![reply]);
            }
            None if segment.flags & tcp::RST == 0 => {
                // Nothing here: reset it, from the address it came to.
                let reset = tcp::Segment::reset_for(&segment);
                let bytes = reset.encode(&destination, &source);
                self.send_ip(destination, source, PROTO_TCP, &bytes);
            }
            None => {}
        }
    }

    // ---- DHCP ----

    fn send_dhcp(&mut self, kind: u8, xid: u32, requested: Option<Ipv4>, server: Option<Ipv4>) {
        let mut m = alloc::vec![0u8; 240];
        m[0] = 1; // request
        m[1] = 1; // Ethernet
        m[2] = 6;
        m[4..8].copy_from_slice(&xid.to_be_bytes());
        m[10] = 0x80; // ask for a broadcast answer
        m[28..34].copy_from_slice(&self.mac);
        m[236..240].copy_from_slice(&[99, 130, 83, 99]);
        m.extend_from_slice(&[53, 1, kind]);
        if let Some(ip) = requested {
            m.extend_from_slice(&[50, 4]);
            m.extend_from_slice(&ip);
        }
        if let Some(ip) = server {
            m.extend_from_slice(&[54, 4]);
            m.extend_from_slice(&ip);
        }
        m.extend_from_slice(&[55, 3, 1, 3, 6, 255]);
        let (from, to) = (IpAddr::V4([0; 4]), IpAddr::V4([255; 4]));
        let udp = udp_packet(&from, &to, DHCP_CLIENT, DHCP_SERVER, &m);
        let ip = ipv4_packet(&mut self.ip_id, [0; 4], [255; 4], PROTO_UDP, &udp);
        self.send_frame(BROADCAST_MAC, ETHERTYPE_IPV4, &ip);
    }

    fn receive_dhcp(&mut self, m: &[u8], now: u64) {
        if m.len() < 240 || m[0] != 2 || m[28..34] != self.mac || m[236..240] != [99, 130, 83, 99] {
            return;
        }
        let xid = u32::from_be_bytes(m[4..8].try_into().unwrap());
        let offered: Ipv4 = m[16..20].try_into().unwrap();
        let (mut kind, mut mask, mut router, mut dns, mut server) = (0, [255, 255, 255, 0], None, None, None);
        let mut at = 240;
        while at < m.len() {
            let code = m[at];
            if code == 255 {
                break;
            }
            if code == 0 {
                at += 1;
                continue;
            }
            let Some(&len) = m.get(at + 1) else { break };
            let value = &m[(at + 2).min(m.len())..(at + 2 + usize::from(len)).min(m.len())];
            let ip = || -> Option<Ipv4> { value.get(..4)?.try_into().ok() };
            match code {
                53 => kind = value.first().copied().unwrap_or(0),
                1 => mask = ip().unwrap_or(mask),
                3 => router = ip(),
                6 => dns = ip(),
                54 => server = ip(),
                _ => {}
            }
            at += 2 + usize::from(len);
        }
        match (self.dhcp, kind) {
            (Dhcp::Discovering { xid: x, .. }, 2) if x == xid => {
                let server = server.unwrap_or([255; 4]);
                self.dhcp = Dhcp::Requesting {
                    xid,
                    offered,
                    server,
                    sent: now,
                };
                self.send_dhcp(3, xid, Some(offered), Some(server));
            }
            (Dhcp::Requesting { xid: x, .. }, 5) if x == xid => {
                let router = router.unwrap_or([0; 4]);
                let dns = dns.unwrap_or(router);
                self.config = Some(Config {
                    ip: offered,
                    mask,
                    router,
                    dns,
                });
                self.dhcp = Dhcp::Bound;
                self.events.push_back(Event::Configured {
                    ip: offered,
                    router,
                    dns,
                });
            }
            _ => {}
        }
    }

    // ---- IPv6 neighbour discovery ----

    /// Asks the routers on the link to say what it is.
    fn solicit_routers(&mut self, now: u64) {
        self.v6.solicited = (self.v6.solicited.0 + 1, now);
        let from = self.v6.link_local();
        let m = icmpv6(&from, &ipv6::ALL_ROUTERS, ipv6::router_solicitation(&self.mac));
        let packet = ipv6::packet(&from, &ipv6::ALL_ROUTERS, ipv6::PROTO_ICMPV6, 255, &m);
        self.send_frame(ipv6::multicast_mac(&ipv6::ALL_ROUTERS), ipv6::ETHERTYPE, &packet);
    }

    /// Joins the solicited-node group, which the link-local and global
    /// addresses share (one interface identifier).
    fn join_groups(&mut self) {
        let from = self.v6.link_local();
        let (to, report) = ipv6::mld_report(&ipv6::solicited_node(&from));
        let report = icmpv6(&from, &to, report);
        let mut body = ipv6::mld_hop_by_hop().to_vec();
        body.extend_from_slice(&report);
        let packet = ipv6::packet(&from, &to, ipv6::HOP_BY_HOP, 1, &body);
        self.send_frame(ipv6::multicast_mac(&to), ipv6::ETHERTYPE, &packet);
    }

    fn ask_neighbour(&mut self, ip: IpAddr) {
        match ip {
            IpAddr::V4(ip) => self.arp_request(ip),
            IpAddr::V6(target) => {
                let Some(from) = self.v6.source_for(&target) else {
                    return;
                };
                let group = ipv6::solicited_node(&target);
                let m = icmpv6(&from, &group, ipv6::neighbour_solicitation(&target, &self.mac));
                let packet = ipv6::packet(&from, &group, ipv6::PROTO_ICMPV6, 255, &m);
                self.send_frame(ipv6::multicast_mac(&group), ipv6::ETHERTYPE, &packet);
            }
        }
    }

    // ---- Sending ----

    /// Which of its addresses to send to `to` from, if it has one.
    fn source_for(&self, to: &IpAddr) -> Option<IpAddr> {
        match to {
            IpAddr::V4(_) => self.config.as_ref().map(|c| IpAddr::V4(c.ip)),
            IpAddr::V6(to) => self.v6.source_for(to).map(IpAddr::V6),
        }
    }

    fn send_udp(&mut self, to: IpAddr, from_port: u16, to_port: u16, data: &[u8]) {
        let Some(source) = self.source_for(&to) else {
            return;
        };
        let udp = udp_packet(&source, &to, from_port, to_port, data);
        self.send_ip(source, to, PROTO_UDP, &udp);
    }

    fn send_ip(&mut self, source: IpAddr, to: IpAddr, protocol: u8, body: &[u8]) {
        let (hop, packet, ethertype) = match (source, to) {
            (IpAddr::V4(source), IpAddr::V4(to)) => {
                let Some(config) = &self.config else { return };
                let on_link = (0..4).all(|i| to[i] & config.mask[i] == config.ip[i] & config.mask[i]);
                let hop = if on_link || to == [255; 4] {
                    to
                } else {
                    config.router
                };
                let packet = ipv4_packet(&mut self.ip_id, source, to, protocol, body);
                if to == [255; 4] {
                    return self.send_frame(BROADCAST_MAC, ETHERTYPE_IPV4, &packet);
                }
                let mac = self.arp.iter().find(|(ip, _)| *ip == hop).map(|(_, m)| *m);
                (IpAddr::V4(hop), packet, (ETHERTYPE_IPV4, mac))
            }
            (IpAddr::V6(source), IpAddr::V6(to)) => {
                let packet = ipv6::packet(&source, &to, protocol, 64, body);
                if ipv6::multicast(&to) {
                    return self.send_frame(ipv6::multicast_mac(&to), ipv6::ETHERTYPE, &packet);
                }
                let Some(hop) = self.v6.next_hop(&to) else {
                    return; // no router: nowhere beyond the link
                };
                (
                    IpAddr::V6(hop),
                    packet,
                    (ipv6::ETHERTYPE, self.v6.neighbour(&hop)),
                )
            }
            _ => return,
        };
        match ethertype {
            (ethertype, Some(mac)) => self.send_frame(mac, ethertype, &packet),
            (_, None) => {
                let asked = self.unresolved.iter().any(|(ip, ..)| *ip == hop);
                if self.unresolved.len() < ARP_QUEUE {
                    self.unresolved.push_back((hop, packet, 0));
                }
                if !asked {
                    self.ask_neighbour(hop);
                }
            }
        }
    }

    fn arp_request(&mut self, ip: Ipv4) {
        let Some(mine) = self.config.as_ref().map(|c| c.ip) else {
            return;
        };
        let mut p = Vec::with_capacity(28);
        p.extend_from_slice(&[0, 1, 8, 0, 6, 4, 0, 1]);
        p.extend_from_slice(&self.mac);
        p.extend_from_slice(&mine);
        p.extend_from_slice(&[0; 6]);
        p.extend_from_slice(&ip);
        self.send_frame(BROADCAST_MAC, ETHERTYPE_ARP, &p);
    }

    fn send_frame(&mut self, to: Mac, ethertype: u16, payload: &[u8]) {
        let mut frame = Vec::with_capacity(14 + payload.len().max(46));
        frame.extend_from_slice(&to);
        frame.extend_from_slice(&self.mac);
        frame.extend_from_slice(&ethertype.to_be_bytes());
        frame.extend_from_slice(payload);
        frame.resize(frame.len().max(60), 0);
        self.out.push_back(frame);
    }
}

/// The first record of `kind` (A or AAAA) in a DNS response.
fn parse_dns_answer(d: &[u8], kind: u16) -> Option<IpAddr> {
    if d.get(3)? & 0x0f != 0 {
        return None; // an error code
    }
    let (questions, answers) = (be16(d, 4)?, be16(d, 6)?);
    let mut at = 12;
    let skip_name = |mut at: usize| -> Option<usize> {
        loop {
            let len = *d.get(at)?;
            if len & 0xc0 == 0xc0 {
                return Some(at + 2);
            }
            if len == 0 {
                return Some(at + 1);
            }
            at += 1 + usize::from(len);
        }
    };
    for _ in 0..questions {
        at = skip_name(at)? + 4;
    }
    for _ in 0..answers {
        at = skip_name(at)?;
        let (found, class, len) = (be16(d, at)?, be16(d, at + 2)?, usize::from(be16(d, at + 8)?));
        let data = d.get(at + 10..at + 10 + len)?;
        match (found == kind && class == 1, len) {
            (true, 4) => return Some(IpAddr::V4(data.try_into().ok()?)),
            (true, 16) => return Some(IpAddr::V6(data.try_into().ok()?)),
            _ => {}
        }
        at += 10 + len;
    }
    None
}

#[cfg(test)]
mod tests;