garage44.eu/jeroen/pinnacle

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

.. /net/src/ipv6.rs

raw

//! IPv6's own parts: the addresses a stack gives itself, and the ICMPv6
//! messages of neighbour discovery (RFC 4861) and stateless address
//! autoconfiguration (RFC 4862) that find them, with the name servers a
//! router names (RDNSS, RFC 8106).

use crate::{Ipv6, Mac};
use alloc::vec::Vec;

pub const ETHERTYPE: u16 = 0x86dd;
pub const PROTO_ICMPV6: u8 = 58;
pub const HOP_BY_HOP: u8 = 0;
const ROUTING: u8 = 43;
const DESTINATION_OPTIONS: u8 = 60;

pub const ECHO_REQUEST: u8 = 128;
pub const ECHO_REPLY: u8 = 129;
pub const ROUTER_SOLICITATION: u8 = 133;
pub const ROUTER_ADVERTISEMENT: u8 = 134;
pub const NEIGHBOR_SOLICITATION: u8 = 135;
pub const NEIGHBOR_ADVERTISEMENT: u8 = 136;
const MLD2_REPORT: u8 = 143;

const OPTION_SOURCE_LINK: u8 = 1;
const OPTION_TARGET_LINK: u8 = 2;
const OPTION_PREFIX: u8 = 3;
const OPTION_RDNSS: u8 = 25;

pub const ALL_NODES: Ipv6 = [0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
pub const ALL_ROUTERS: Ipv6 = [0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2];
const ALL_MLD2_ROUTERS: Ipv6 = [0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x16];

/// Router solicitations sent before waiting for an unasked advertisement,
/// and how far apart (RFC 4861's MAX_RTR_SOLICITATIONS and
/// RTR_SOLICITATION_INTERVAL).
pub const SOLICITATIONS: u8 = 3;
pub const SOLICITATION_MS: u64 = 4000;

/// What the stack knows of IPv6 on its link.
pub struct State {
    /// The interface identifier, the low half of every address: random for
    /// each start, so the address does not follow the device from network
    /// to network (as RFC 8981's temporary addresses).
    pub iid: [u8; 8],
    /// Switched on: the link-local address is in use.
    pub on: bool,
    /// A global address from a router's prefix, and the prefix's length.
    pub global: Option<Ipv6>,
    /// The default router (its link-local address).
    pub router: Option<Ipv6>,
    /// The first name server the router named.
    pub dns: Option<Ipv6>,
    /// Neighbours' link addresses, as found by solicitation.
    pub neighbours: Vec<(Ipv6, Mac)>,
    /// Router solicitations sent so far, and when the last.
    pub solicited: (u8, u64),
}

impl State {
    pub fn new(seed: u64) -> State {
        let mut x = seed ^ 0x9e37_79b9_7f4a_7c15;
        x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        x ^= x >> 31;
        let mut iid = x.to_be_bytes();
        // Not the universal/local bit of a hardware identifier, never all
        // zeros (the subnet-router anycast address).
        iid[0] &= !0x02;
        iid[7] |= 1;
        State {
            iid,
            on: false,
            global: None,
            router: None,
            dns: None,
            neighbours: Vec::new(),
            solicited: (0, 0),
        }
    }

    pub fn link_local(&self) -> Ipv6 {
        let mut a = [0u8; 16];
        a[..2].copy_from_slice(&[0xfe, 0x80]);
        a[8..].copy_from_slice(&self.iid);
        a
    }

    /// Off: no address in use, nothing known of the link.
    pub fn reset(&mut self) {
        self.on = false;
        self.global = None;
        self.router = None;
        self.dns = None;
        self.neighbours.clear();
        self.solicited = (0, 0);
    }

    /// Whether `ip` is one of this stack's addresses.
    pub fn mine(&self, ip: &Ipv6) -> bool {
        self.on && (*ip == self.link_local() || Some(*ip) == self.global)
    }

    /// Whether a packet to `ip` is for this stack: one of its addresses, or
    /// a group it is in (all nodes, its solicited-node group).
    pub fn accepts(&self, ip: &Ipv6) -> bool {
        self.mine(ip) || (self.on && (*ip == ALL_NODES || *ip == solicited_node(&self.link_local())))
    }

    /// Which of its addresses to send to `to` from: the link-local one on
    /// the link, the global one beyond it (none yet: nowhere to send).
    pub fn source_for(&self, to: &Ipv6) -> Option<Ipv6> {
        if !self.on {
            return None;
        }
        if link_scoped(to) {
            Some(self.link_local())
        } else {
            self.global
        }
    }

    /// The neighbour a packet to `to` goes to first: `to` itself on the
    /// link, the router beyond it.
    pub fn next_hop(&self, to: &Ipv6) -> Option<Ipv6> {
        let on_link = link_scoped(to) || self.global.is_some_and(|g| g[..8] == to[..8]);
        if on_link { Some(*to) } else { self.router }
    }

    pub fn neighbour(&self, ip: &Ipv6) -> Option<Mac> {
        self.neighbours.iter().find(|(i, _)| i == ip).map(|(_, m)| *m)
    }

    pub fn learn(&mut self, ip: Ipv6, mac: Mac) {
        match self.neighbours.iter_mut().find(|(i, _)| *i == ip) {
            Some(entry) => entry.1 = mac,
            None => self.neighbours.push((ip, mac)),
        }
    }

    /// When the next router solicitation is due, while one is.
    pub fn deadline(&self) -> Option<u64> {
        let (sent, at) = self.solicited;
        (self.on && self.router.is_none() && sent < SOLICITATIONS).then_some(at + SOLICITATION_MS)
    }
}

/// Link-local (fe80::/10) or a multicast group on the link (ff02::/16).
pub fn link_scoped(ip: &Ipv6) -> bool {
    (ip[0] == 0xfe && ip[1] & 0xc0 == 0x80) || (ip[0] == 0xff && ip[1] & 0x0f == 2)
}

pub fn multicast(ip: &Ipv6) -> bool {
    ip[0] == 0xff
}

/// The group a neighbour solicitation for `ip` is sent to.
pub fn solicited_node(ip: &Ipv6) -> Ipv6 {
    let mut g = [0xff, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0xff, 0, 0, 0];
    g[13..].copy_from_slice(&ip[13..]);
    g
}

/// The Ethernet address a multicast group is sent to (RFC 2464).
pub fn multicast_mac(ip: &Ipv6) -> Mac {
    [0x33, 0x33, ip[12], ip[13], ip[14], ip[15]]
}

/// An IPv6 packet: header, then `body` after `next`.
pub fn packet(source: &Ipv6, destination: &Ipv6, next: u8, hop_limit: u8, body: &[u8]) -> Vec<u8> {
    let mut p = Vec::with_capacity(40 + body.len());
    p.extend_from_slice(&[0x60, 0, 0, 0]);
    p.extend_from_slice(&(body.len() as u16).to_be_bytes());
    p.push(next);
    p.push(hop_limit);
    p.extend_from_slice(source);
    p.extend_from_slice(destination);
    p.extend_from_slice(body);
    p
}

/// The upper-layer protocol and its bytes, past the extension headers
/// that may come first. None for a fragment, which is not reassembled.
pub fn upper_layer(mut next: u8, mut body: &[u8]) -> Option<(u8, &[u8])> {
    loop {
        match next {
            HOP_BY_HOP | ROUTING | DESTINATION_OPTIONS => {
                let len = (usize::from(*body.get(1)?) + 1) * 8;
                next = *body.first()?;
                body = body.get(len..)?;
            }
            44 => return None,
            _ => return Some((next, body)),
        }
    }
}

/// ICMPv6 message options: (type, value past the type and length bytes).
pub fn options(mut o: &[u8]) -> impl Iterator<Item = (u8, &[u8])> {
    core::iter::from_fn(move || {
        let len = usize::from(*o.get(1)?) * 8;
        if len == 0 || len > o.len() {
            return None;
        }
        let (option, rest) = o.split_at(len);
        o = rest;
        Some((option[0], &option[2..]))
    })
}

fn link_option(kind: u8, mac: &Mac) -> [u8; 8] {
    let mut o = [kind, 1, 0, 0, 0, 0, 0, 0];
    o[2..].copy_from_slice(mac);
    o
}

/// What a router advertisement says, as far as a host needs it.
pub struct Advertisement {
    /// How long the sender stays a default router (s); 0: it is not one.
    pub lifetime: u16,
    pub router_mac: Option<Mac>,
    /// An autonomous /64 prefix and its valid lifetime (s).
    pub prefix: Option<([u8; 8], u32)>,
    pub dns: Option<Ipv6>,
}

pub fn parse_advertisement(m: &[u8]) -> Option<Advertisement> {
    let mut ad = Advertisement {
        lifetime: u16::from_be_bytes(m.get(6..8)?.try_into().ok()?),
        router_mac: None,
        prefix: None,
        dns: None,
    };
    for (kind, value) in options(m.get(16..)?) {
        match kind {
            OPTION_SOURCE_LINK if value.len() >= 6 => ad.router_mac = value[..6].try_into().ok(),
            // Length 64, the autonomous flag, a prefix that is not link-local.
            OPTION_PREFIX if value.len() >= 30 && value[0] == 64 && value[1] & 0x40 != 0 => {
                let prefix: [u8; 8] = value[14..22].try_into().unwrap();
                let valid = u32::from_be_bytes(value[2..6].try_into().unwrap());
                if !(prefix[0] == 0xfe && prefix[1] & 0xc0 == 0x80) {
                    ad.prefix = Some((prefix, valid));
                }
            }
            OPTION_RDNSS if value.len() >= 22 && ad.dns.is_none() => {
                let lifetime = u32::from_be_bytes(value[2..6].try_into().unwrap());
                if lifetime > 0 {
                    ad.dns = value[6..22].try_into().ok();
                }
            }
            _ => {}
        }
    }
    Some(ad)
}

/// A neighbour solicitation's target and the sender's link address.
pub fn parse_solicitation(m: &[u8]) -> Option<(Ipv6, Option<Mac>)> {
    let target = m.get(8..24)?.try_into().ok()?;
    let mac = options(m.get(24..)?)
        .find(|(kind, v)| *kind == OPTION_SOURCE_LINK && v.len() >= 6)
        .and_then(|(_, v)| v[..6].try_into().ok());
    Some((target, mac))
}

/// A neighbour advertisement's target and its link address.
pub fn parse_neighbour_advertisement(m: &[u8]) -> Option<(Ipv6, Option<Mac>)> {
    let target = m.get(8..24)?.try_into().ok()?;
    let mac = options(m.get(24..)?)
        .find(|(kind, v)| *kind == OPTION_TARGET_LINK && v.len() >= 6)
        .and_then(|(_, v)| v[..6].try_into().ok());
    Some((target, mac))
}

/// The ICMPv6 bodies a stack sends (their checksum still zero).
pub fn router_solicitation(mac: &Mac) -> Vec<u8> {
    let mut m = alloc::vec![ROUTER_SOLICITATION, 0, 0, 0, 0, 0, 0, 0];
    m.extend_from_slice(&link_option(OPTION_SOURCE_LINK, mac));
    m
}

pub fn neighbour_solicitation(target: &Ipv6, mac: &Mac) -> Vec<u8> {
    let mut m = alloc::vec![NEIGHBOR_SOLICITATION, 0, 0, 0, 0, 0, 0, 0];
    m.extend_from_slice(target);
    m.extend_from_slice(&link_option(OPTION_SOURCE_LINK, mac));
    m
}

/// Answering a solicitation (`solicited`), or announcing unasked.
pub fn neighbour_advertisement(target: &Ipv6, mac: &Mac, solicited: bool) -> Vec<u8> {
    // Override, and Solicited when it answers one.
    let flags = 0x20 | if solicited { 0x40 } else { 0 };
    let mut m = alloc::vec![NEIGHBOR_ADVERTISEMENT, 0, 0, 0, flags, 0, 0, 0];
    m.extend_from_slice(target);
    m.extend_from_slice(&link_option(OPTION_TARGET_LINK, mac));
    m
}

/// An MLDv2 report joining `group`, so that a switch that listens for
/// them passes the group's packets (solicitations for this stack) on, and
/// where it goes; it is sent with a hop-by-hop router alert, as
/// [`mld_hop_by_hop`].
pub fn mld_report(group: &Ipv6) -> (Ipv6, Vec<u8>) {
    let mut m = alloc::vec![MLD2_REPORT, 0, 0, 0, 0, 0, 0, 1];
    // CHANGE_TO_EXCLUDE_MODE with no sources: every sender.
    m.extend_from_slice(&[4, 0, 0, 0]);
    m.extend_from_slice(group);
    (ALL_MLD2_ROUTERS, m)
}

/// The hop-by-hop header carrying a router alert (MLD) before ICMPv6.
pub fn mld_hop_by_hop() -> [u8; 8] {
    [PROTO_ICMPV6, 0, 5, 2, 0, 0, 1, 0]
}