From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 30D871FF0B6 for ; Thu, 12 Nov 2026 13:45:31 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 757F72187E; Thu, 12 Nov 2026 13:43:47 +0100 (CET) From: Hannes Laimer To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox-ve-rs v7 19/21] sdn-dhcp: add the crate that runs the eBPF DHCP responder Date: Thu, 12 Nov 2026 13:41:59 +0100 Message-ID: <20261112124201.2844423-20-h.laimer@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261112124201.2844423-1-h.laimer@proxmox.com> References: <20261112124201.2844423-1-h.laimer@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1794487351453 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.287 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) KAM_SHORT 0.001 Use of a URL Shortener for very short URL RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: 7PMENNRSVH6MCED25LATDCPEPAFSYYSC X-Message-ID-Hash: 7PMENNRSVH6MCED25LATDCPEPAFSYYSC X-MailFrom: h.laimer@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: The crate loads the responder program pve-network ships, pins a map holding the answer of each guest interface and attaches the program to the interfaces it serves. Callers run a full pass over the guest interfaces to serve, plug or unplug one interface, or change the records of a guest's interfaces. A load starts with an empty map, and only a full pass is handed every interface to serve. So only a full pass loads. It fills the new map before any link moves. A plug or a record change that finds nothing loaded reports that a full pass has to run first. A hotplug moves a tap while its new bridge or MAC is still a pending change in the guest config, and no lock closes that gap. So the caller detaches the program at the move and attaches it again once the change is applied, and a pass is only handed interfaces that sit on the bridge their config names. Every answer then comes from a config that names the bridge the interface is on, and a pass removes the entry of every interface it is not handed. A plug holds the lock shared, so plugs run next to each other. A mapping edit takes it exclusively, so no plug that read the older address writes after it. Signed-off-by: Hannes Laimer --- Cargo.toml | 2 + proxmox-sdn-dhcp/Cargo.toml | 18 + proxmox-sdn-dhcp/debian/changelog | 5 + proxmox-sdn-dhcp/debian/control | 42 ++ proxmox-sdn-dhcp/debian/copyright | 18 + proxmox-sdn-dhcp/debian/debcargo.toml | 7 + proxmox-sdn-dhcp/src/lib.rs | 688 ++++++++++++++++++++++++++ proxmox-sdn-dhcp/src/types.rs | 42 ++ 8 files changed, 822 insertions(+) create mode 100644 proxmox-sdn-dhcp/Cargo.toml create mode 100644 proxmox-sdn-dhcp/debian/changelog create mode 100644 proxmox-sdn-dhcp/debian/control create mode 100644 proxmox-sdn-dhcp/debian/copyright create mode 100644 proxmox-sdn-dhcp/debian/debcargo.toml create mode 100644 proxmox-sdn-dhcp/src/lib.rs create mode 100644 proxmox-sdn-dhcp/src/types.rs diff --git a/Cargo.toml b/Cargo.toml index 72d4cb6812e7..022236063ff3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ members = [ "proxmox-ve-config", "proxmox-frr", + "proxmox-sdn-dhcp", "proxmox-sdn-types", ] exclude = [ @@ -24,6 +25,7 @@ regex = "1.7" serde = { version = "1" } thiserror = "2.0.0" +proxmox-ebpf = { version = "0.1" } proxmox-fixed-string = { version = "0.1.1" } proxmox-frr = { version = "0.6.0", path = "proxmox-frr" } proxmox-network-types = { version = "1.1.2" } diff --git a/proxmox-sdn-dhcp/Cargo.toml b/proxmox-sdn-dhcp/Cargo.toml new file mode 100644 index 000000000000..4ce2ccbf2c7d --- /dev/null +++ b/proxmox-sdn-dhcp/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "proxmox-sdn-dhcp" +description = "Per-tap eBPF DHCPv4 responder of the SDN stack" +version = "0.1.0" +authors.workspace = true +edition = "2024" +license.workspace = true +homepage.workspace = true +exclude.workspace = true +rust-version = "1.88" + +[dependencies] +anyhow = { workspace = true } +aya = "0.13" +log = "0.4.17" +nix = { version = "0.29", features = [ "net" ] } + +proxmox-ebpf = { workspace = true } diff --git a/proxmox-sdn-dhcp/debian/changelog b/proxmox-sdn-dhcp/debian/changelog new file mode 100644 index 000000000000..f7b51db859de --- /dev/null +++ b/proxmox-sdn-dhcp/debian/changelog @@ -0,0 +1,5 @@ +rust-proxmox-sdn-dhcp (0.1.0-1) trixie; urgency=medium + + * Initial release. + + -- Proxmox Support Team Fri, 06 Nov 2026 14:00:00 +0100 diff --git a/proxmox-sdn-dhcp/debian/control b/proxmox-sdn-dhcp/debian/control new file mode 100644 index 000000000000..d47cbbbea57c --- /dev/null +++ b/proxmox-sdn-dhcp/debian/control @@ -0,0 +1,42 @@ +Source: rust-proxmox-sdn-dhcp +Section: rust +Priority: optional +Build-Depends: debhelper-compat (= 13), + dh-sequence-cargo +Build-Depends-Arch: cargo:native , + rustc:native (>= 1.88) , + libstd-rust-dev , + librust-anyhow-1+default-dev , + librust-aya-0.13+default-dev , + librust-log-0.4+default-dev (>= 0.4.17-~~) , + librust-nix-0.29+default-dev , + librust-nix-0.29+net-dev , + librust-proxmox-ebpf-0.1+default-dev +Maintainer: Proxmox Support Team +Standards-Version: 4.7.2 +Vcs-Git: git://git.proxmox.com/git/proxmox-ve-rs.git +Vcs-Browser: https://git.proxmox.com/?p=proxmox-ve-rs.git +Homepage: https://proxmox.com +X-Cargo-Crate: proxmox-sdn-dhcp + +Package: librust-proxmox-sdn-dhcp-dev +Architecture: any +Multi-Arch: same +Depends: + ${misc:Depends}, + librust-anyhow-1+default-dev, + librust-aya-0.13+default-dev, + librust-log-0.4+default-dev (>= 0.4.17-~~), + librust-nix-0.29+default-dev, + librust-nix-0.29+net-dev, + librust-proxmox-ebpf-0.1+default-dev +Provides: + librust-proxmox-sdn-dhcp+default-dev (= ${binary:Version}), + librust-proxmox-sdn-dhcp-0-dev (= ${binary:Version}), + librust-proxmox-sdn-dhcp-0+default-dev (= ${binary:Version}), + librust-proxmox-sdn-dhcp-0.1-dev (= ${binary:Version}), + librust-proxmox-sdn-dhcp-0.1+default-dev (= ${binary:Version}), + librust-proxmox-sdn-dhcp-0.1.0-dev (= ${binary:Version}), + librust-proxmox-sdn-dhcp-0.1.0+default-dev (= ${binary:Version}) +Description: Per-tap eBPF DHCPv4 responder of the SDN stack - Rust source code + Source code for Debianized Rust crate "proxmox-sdn-dhcp" diff --git a/proxmox-sdn-dhcp/debian/copyright b/proxmox-sdn-dhcp/debian/copyright new file mode 100644 index 000000000000..77952eba571e --- /dev/null +++ b/proxmox-sdn-dhcp/debian/copyright @@ -0,0 +1,18 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ + +Files: + * +Copyright: 2019 - 2026 Proxmox Server Solutions GmbH +License: AGPL-3.0-or-later + This program is free software: you can redistribute it and/or modify it under + the terms of the GNU Affero General Public License as published by the Free + Software Foundation, either version 3 of the License, or (at your option) any + later version. + . + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more + details. + . + You should have received a copy of the GNU Affero General Public License along + with this program. If not, see . diff --git a/proxmox-sdn-dhcp/debian/debcargo.toml b/proxmox-sdn-dhcp/debian/debcargo.toml new file mode 100644 index 000000000000..87a787e6d03e --- /dev/null +++ b/proxmox-sdn-dhcp/debian/debcargo.toml @@ -0,0 +1,7 @@ +overlay = "." +crate_src_path = ".." +maintainer = "Proxmox Support Team " + +[source] +vcs_git = "git://git.proxmox.com/git/proxmox-ve-rs.git" +vcs_browser = "https://git.proxmox.com/?p=proxmox-ve-rs.git" diff --git a/proxmox-sdn-dhcp/src/lib.rs b/proxmox-sdn-dhcp/src/lib.rs new file mode 100644 index 000000000000..38fb96b006ff --- /dev/null +++ b/proxmox-sdn-dhcp/src/lib.rs @@ -0,0 +1,688 @@ +//! The dhcp subsystem, a per-tap DHCPv4 responder answering from a pinned map of one entry per +//! interface. +//! +//! The map holds nothing of its own. The SDN side hands in the guest interfaces to serve, each +//! with the answer it gets, if any. A full pass loads the program and a fresh map from the object +//! file `/usr/lib/proxmox-ebpf/dhcp.bpf.o` and replaces the running ones with them. It fills the +//! new map before any link moves. Afterward every interface it was handed has a link, and those +//! with an answer have an entry. A record change or a plug writes its own interfaces only. +//! +//! A plug runs under the shared lock and a pass under the exclusive one. An edit pushes its +//! record change under the exclusive lock as well, so no plug that read the older address writes +//! after it. A guest's own start holds the guest lock, so nothing else plugs its interfaces +//! meanwhile and it writes its records under the shared lock. +//! +//! The SDN side reads a guest config without its pending changes, and during a hotplug the +//! interface's new bridge is still one of them. So it detaches the program when the interface +//! moves, and attaches the program again once the change is applied to the config. In between +//! the interface has no entry. A full pass leaves it out as well, since it is not on the bridge +//! its config names. So every answer is built from a config that names the bridge the interface +//! is on. +mod types; + +use std::collections::{HashMap, HashSet}; +use std::io::ErrorKind; +use std::net::Ipv4Addr; + +use anyhow::{Context, bail}; +use aya::maps::MapError; + +use proxmox_ebpf::subsystem::{ + ApplyLock, Exclusive, MapHandle, NotLoaded, Shared, Staged, TcPrograms, +}; +use proxmox_ebpf::tc::{Direction, LinkPin}; + +use self::types::*; + +/// One guest interface to serve. `mac` is the NIC's MAC, which a record needs. `record` is the +/// answer it gets. Without one the interface gets a link and no entry. +pub struct Iface { + pub name: String, + pub mac: Option<[u8; 6]>, + pub record: Option, +} + +/// One interface's answer, the address and every option the reply carries. +pub struct Record { + pub ip: Ipv4Addr, + pub prefixlen: u8, + pub server_id: Ipv4Addr, + pub lease: u32, + pub router: Option, + pub dns: Option, + pub mtu: Option, +} + +/// What a single-entry step did. +#[derive(Debug, PartialEq, Eq)] +pub enum Outcome { + /// Nothing is left to do. The entry is in place, or its interface is not here. + Done, + /// Nothing is loaded to write into. Only a full pass loads, so the caller runs one and retries. + NeedsFullPass, +} + +const RECORDS_MAP: &str = "dhcp_iface_records"; +const MAPS: [&str; 1] = [RECORDS_MAP]; + +// bump with any change to the key or value layout of a map in pve-network's +// src/bpf/dhcp/dhcp.bpf.c, together with DHCP_SCHEMA_VERSION in its types.h +const SCHEMA_VERSION: u32 = 1; + +// requests only arrive from the guest side and replies leave through a redirect, so only ingress +// carries a program +const PROGRAM_NAMES: [(Direction, &str); 1] = [(Direction::Ingress, "tc_dhcp_ingress")]; + +type RecordsMap<'a> = MapHandle<'a, u32, DhcpRecord>; + +static PROGRAMS: TcPrograms = TcPrograms::new("dhcp", &PROGRAM_NAMES, &MAPS, SCHEMA_VERSION); + +/// The lock a plug runs under, held until [`attach`](SharedLock::attach) returns. Plugs run next +/// to each other and wait only behind an exclusive holder. +pub fn lock_shared() -> anyhow::Result { + Ok(SharedLock { + lock: PROGRAMS.lock_shared()?, + }) +} + +/// The lock a full pass or a record change runs under, held until the change is written. +pub fn lock_exclusive() -> anyhow::Result { + Ok(ExclusiveLock { + lock: PROGRAMS.lock_exclusive()?, + }) +} + +/// A tap unplug, the interface loses its link and its entry. It may be gone by then, so its link +/// is found by the name the pin carries. +pub fn detach(iface: &str) -> anyhow::Result<()> { + // resolved before the lock wait, an interface recreated under the name meanwhile is not + // this unplug's and keeps its link + let now = ifindex_of(iface)?; + // every guest unplug on the host lands here. Most never had a link and must not wait + // behind a pass. One without a link whose interface is gone leaves its entry to the + // next pass. A failed listing takes the lock like a pinned link does + if matches!(PROGRAMS.is_link_pinned(iface), Ok(false)) && now.is_none() { + return Ok(()); + } + detach_under(&PROGRAMS.lock_shared()?, iface, now) +} + +/// The shared lock of the responder, what a plug holds, and the record change of a guest's own +/// start. +pub struct SharedLock { + lock: ApplyLock<'static, Shared>, +} + +impl SharedLock { + /// A plug onto a bridge the responder does not serve, decided under this lock. See + /// [`detach`](crate::detach). + pub fn detach(&self, iface: &str) -> anyhow::Result<()> { + detach_under(&self.lock, iface, ifindex_of(iface)?) + } + + /// A tap plug, the entry goes in and the program on. The plug loads nothing, so with nothing + /// pinned the caller runs a full pass first. + pub fn attach(&self, iface: &Iface) -> anyhow::Result { + if !self.lock.is_current() { + return Ok(Outcome::NeedsFullPass); + } + let Some(ifindex) = ifindex_of(iface.name.as_str())? else { + log::info!("dhcp attach: {} is gone, nothing to do", iface.name); + return Ok(Outcome::Done); + }; + // the entry goes in before the program runs. An interface whose record the reply cannot + // carry gets none, since a guest start must not fail on a bad record + let mut map: RecordsMap = self.lock.hash_map(RECORDS_MAP)?; + let entry = match iface.entry() { + Ok(entry) => entry, + Err(e) => { + log::warn!( + "dhcp: {} attaches with nothing to answer: {e:#}", + iface.name + ); + None + } + }; + write_entry(&mut map, ifindex, entry)?; + match self.lock.attach_iface(ifindex) { + Ok(()) => Ok(Outcome::Done), + Err(e) if e.downcast_ref::().is_some() => Ok(Outcome::NeedsFullPass), + Err(e) => Err(e).with_context(|| format!("dhcp responder for {}", iface.name)), + } + } + + /// A record change for a caller that holds the guest lock. Nothing else plugs the guest's + /// interfaces under that lock, so the shared lock is enough. It writes like + /// [`ExclusiveLock::update`]. + pub fn update(&self, ifaces: &[Iface]) -> anyhow::Result { + update_entries(&self.lock, ifaces) + } +} + +/// The exclusive lock of the responder, what a full pass and a record change hold. +pub struct ExclusiveLock { + lock: ApplyLock<'static, Exclusive>, +} + +impl ExclusiveLock { + /// The full pass. Afterward the program and the map are new, loaded from the object file. Every + /// interface handed in that exists here has a link, and an entry if it has a record. Every + /// other link and entry is gone. A record that cannot be built leaves its interface the entry + /// it had, with a warning. A failed write fails the pass, and the old program and map keep + /// serving. + pub fn apply(&mut self, ifaces: &[Iface]) -> anyhow::Result<()> { + let present = present_ifindexes(ifaces)?; + let live = read_records(&self.lock)?; + let entries = desired_entries(&live, &present); + let wanted: HashSet = present.keys().copied().collect(); + self.lock + .replace_state(&wanted, |staged| write_entries(staged, &entries)) + } + + /// A record change. Interfaces not found here are skipped. The rest are written whether they + /// have a link yet or not. One without a record loses its entry. A record the reply cannot + /// carry leaves its interface as it is. With nothing loaded the caller runs a full pass first, + /// like a plug. + pub fn update(&self, ifaces: &[Iface]) -> anyhow::Result { + update_entries(&self.lock, ifaces) + } + + /// Detach everywhere and drop the pinned state, for the last zone leaving the backend. + pub fn clear(&mut self) -> anyhow::Result<()> { + self.lock.clear() + } +} + +fn detach_under( + lock: &ApplyLock<'static, Shared>, + iface: &str, + now: Option, +) -> anyhow::Result<()> { + if !lock.is_current() { + log::debug!("dhcp detach: nothing current, {iface} is left to the next full pass"); + return Ok(()); + } + // the map is opened before the links go, so a failure there leaves them attached + let mut map: RecordsMap = lock.hash_map(RECORDS_MAP)?; + let mut ifindexes = lock.detach_named(iface, |pin| { + Some(pin.ifindex) != now && pin_alive(pin).unwrap_or(false) + })?; + // the entry goes in before the link, so an attach that failed in between leaves an entry + // without a link + if let Some(now) = now.filter(|now| !ifindexes.contains(now)) { + ifindexes.push(now); + } + remove_entries(&mut map, &ifindexes) +} + +fn update_entries(lock: &ApplyLock<'static, M>, ifaces: &[Iface]) -> anyhow::Result { + if !lock.is_current() { + return Ok(Outcome::NeedsFullPass); + } + let mut map: RecordsMap = lock.hash_map(RECORDS_MAP)?; + let mut failed = 0usize; + for iface in ifaces { + let ifindex = match ifindex_of(iface.name.as_str()) { + Ok(Some(ifindex)) => ifindex, + Ok(None) => continue, + Err(e) => { + log::warn!("dhcp: {e:#}"); + failed += 1; + continue; + } + }; + let entry = match iface.entry() { + Ok(entry) => entry, + Err(e) => { + log::warn!("dhcp: {} is left as it is: {e:#}", iface.name); + continue; + } + }; + if let Err(e) = write_entry(&mut map, ifindex, entry) { + log::warn!("dhcp: could not write the entry of {}: {e:#}", iface.name); + failed += 1; + } + } + if failed > 0 { + bail!("{failed} interfaces could not be updated"); + } + Ok(Outcome::Done) +} + +const NO_MAC: [u8; 6] = [0; 6]; + +fn remove_entries(map: &mut impl RecordStore, ifindexes: &[u32]) -> anyhow::Result<()> { + for &ifindex in ifindexes { + map.remove(ifindex)?; + } + Ok(()) +} + +// the record map as the single-entry writers see it, so their decisions run against a plain map in +// tests +trait RecordStore { + fn insert(&mut self, ifindex: u32, rec: DhcpRecord) -> anyhow::Result<()>; + // a missing entry is removed already + fn remove(&mut self, ifindex: u32) -> anyhow::Result<()>; +} + +impl RecordStore for RecordsMap<'_> { + fn insert(&mut self, ifindex: u32, rec: DhcpRecord) -> anyhow::Result<()> { + aya::maps::HashMap::insert(self, ifindex, rec, 0)?; + Ok(()) + } + + fn remove(&mut self, ifindex: u32) -> anyhow::Result<()> { + match aya::maps::HashMap::remove(self, &ifindex) { + Ok(()) => Ok(()), + // the kernel answers a missing key with ENOENT, and aya passes that through as is + Err(MapError::SyscallError(e)) if e.io_error.kind() == ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } + } +} + +fn write_entry( + map: &mut impl RecordStore, + ifindex: u32, + entry: Option, +) -> anyhow::Result<()> { + match entry { + Some(entry) => map.insert(ifindex, entry), + None => map.remove(ifindex), + } +} + +// the entries of the live map, none when nothing is pinned. A record the listing cannot read is one +// the pass cannot carry over, so the pass fails before it replaces anything +fn read_records(lock: &ApplyLock<'static, Exclusive>) -> anyhow::Result> { + let map: RecordsMap = match lock.hash_map(RECORDS_MAP) { + Ok(map) => map, + Err(e) if e.downcast_ref::().is_some() => return Ok(HashMap::new()), + Err(e) => return Err(e), + }; + map.iter() + .collect::>() + .context("listing the records") +} + +fn desired_entries( + live: &HashMap, + present: &HashMap, +) -> HashMap { + let mut entries = HashMap::new(); + for (ifindex, iface) in present { + let entry = match iface.entry() { + Ok(entry) => entry, + // one bad record must not fail the pass + Err(e) => { + log::warn!("dhcp: {} is left as it is: {e:#}", iface.name); + live.get(ifindex).copied() + } + }; + if let Some(entry) = entry { + entries.insert(*ifindex, entry); + } + } + + let dropped = live + .keys() + .filter(|ifindex| !entries.contains_key(ifindex)) + .count(); + log::info!("dhcp: {} entries, {dropped} dropped", entries.len()); + entries +} + +fn write_entries(staged: &Staged<'_>, entries: &HashMap) -> anyhow::Result<()> { + let mut map: RecordsMap = staged.hash_map(RECORDS_MAP)?; + for (ifindex, entry) in entries { + aya::maps::HashMap::insert(&mut map, *ifindex, *entry, 0) + .with_context(|| format!("write the entry of ifindex {ifindex}"))?; + } + Ok(()) +} + +// the interface's index here, none when it does not exist. Any other failure says nothing about +// the interface, and a step taking it for gone would detach what it could not resolve +fn ifindex_of(name: &str) -> anyhow::Result> { + match nix::net::if_::if_nametoindex(name) { + Ok(ifindex) => Ok(Some(ifindex)), + Err(nix::errno::Errno::ENODEV) => Ok(None), + Err(e) => Err(e).with_context(|| format!("resolve interface {name}")), + } +} + +// the handed-in interfaces that still exist, by index +fn present_ifindexes(ifaces: &[Iface]) -> anyhow::Result> { + let local = nix::net::if_::if_nameindex().context("list interfaces")?; + let by_name: HashMap<&str, u32> = local + .iter() + .filter_map(|i| i.name().to_str().ok().map(|name| (name, i.index()))) + .collect(); + Ok(ifaces + .iter() + .filter_map(|iface| { + by_name + .get(iface.name.as_str()) + .map(|&ifindex| (ifindex, iface)) + }) + .collect()) +} + +// whether the link's interface still exists under the name and index its pin carries +fn pin_alive(pin: &LinkPin) -> anyhow::Result { + Ok(ifindex_of(pin.name.as_str())? == Some(pin.ifindex)) +} + +impl Iface { + fn entry(&self) -> anyhow::Result> { + let Some(record) = &self.record else { + return Ok(None); + }; + record + .entry(self.mac.unwrap_or(NO_MAC)) + .with_context(|| format!("record for {}", self.name)) + .map(Some) + } +} + +impl Record { + // refused here is what the reply cannot carry. Zero stands for absent in the entry, so an + // address or an MTU of zero cannot be told from none + fn entry(&self, mac: [u8; 6]) -> anyhow::Result { + if self.prefixlen == 0 || self.prefixlen > 32 { + bail!("prefixlen {} out of range", self.prefixlen); + } + if self.ip.is_unspecified() { + bail!("no address"); + } + if self.server_id.is_unspecified() { + bail!("no server address"); + } + if self.lease == 0 { + bail!("lease of zero seconds"); + } + if self.mtu.is_some_and(|mtu| mtu < 68) { + bail!("mtu below the IPv4 minimum of 68"); + } + if mac == NO_MAC { + bail!("no MAC"); + } + let netmask = u32::MAX << (32 - self.prefixlen); + Ok(DhcpRecord { + ip: u32::from(self.ip).to_be(), + netmask: netmask.to_be(), + router: u32::from(self.router.unwrap_or(Ipv4Addr::UNSPECIFIED)).to_be(), + dns: u32::from(self.dns.unwrap_or(Ipv4Addr::UNSPECIFIED)).to_be(), + server_id: u32::from(self.server_id).to_be(), + lease: self.lease.to_be(), + mtu: self.mtu.unwrap_or(0).to_be(), + mac, + }) + } +} + +#[cfg(test)] +mod test { + use std::collections::BTreeMap; + + use super::*; + + fn record() -> Record { + Record { + ip: Ipv4Addr::new(10, 0, 0, 100), + prefixlen: 24, + server_id: Ipv4Addr::new(10, 0, 0, 1), + lease: 300, + router: Some(Ipv4Addr::new(10, 0, 0, 1)), + dns: Some(Ipv4Addr::new(1, 1, 1, 1)), + mtu: Some(1500), + } + } + + const MAC: [u8; 6] = [0xda, 0x65, 0x8f, 0x18, 0x9b, 0x6f]; + + #[test] + fn converts_full_record() { + let rec = record().entry(MAC).unwrap(); + assert_eq!( + u32::from_be(rec.ip), + u32::from(Ipv4Addr::new(10, 0, 0, 100)) + ); + assert_eq!(u32::from_be(rec.netmask), 0xffffff00); + assert_eq!( + u32::from_be(rec.router), + u32::from(Ipv4Addr::new(10, 0, 0, 1)) + ); + assert_eq!(u32::from_be(rec.dns), u32::from(Ipv4Addr::new(1, 1, 1, 1))); + assert_eq!( + u32::from_be(rec.server_id), + u32::from(Ipv4Addr::new(10, 0, 0, 1)) + ); + assert_eq!(u32::from_be(rec.lease), 300); + assert_eq!(u16::from_be(rec.mtu), 1500); + assert_eq!(rec.mac, MAC); + + let rec = Record { + router: None, + dns: None, + mtu: None, + ..record() + } + .entry(MAC) + .unwrap(); + assert_eq!(rec.router, 0); + assert_eq!(rec.dns, 0); + assert_eq!(rec.mtu, 0); + } + + #[test] + fn refuses_what_the_reply_cannot_carry() { + for (what, rec) in [ + ( + "a prefix above 32", + Record { + prefixlen: 33, + ..record() + }, + ), + ( + "a prefix of 0", + Record { + prefixlen: 0, + ..record() + }, + ), + ( + "no server address", + Record { + server_id: Ipv4Addr::UNSPECIFIED, + ..record() + }, + ), + ( + "a lease of 0", + Record { + lease: 0, + ..record() + }, + ), + ( + "no address", + Record { + ip: Ipv4Addr::UNSPECIFIED, + ..record() + }, + ), + ( + "an MTU of 67", + Record { + mtu: Some(67), + ..record() + }, + ), + ] { + assert!(rec.entry(MAC).is_err(), "accepted {what}"); + } + assert!(record().entry(NO_MAC).is_err()); + let iface = Iface { + mac: None, + ..iface("a", Some(record())) + }; + assert!(iface.entry().is_err()); + } + + #[test] + fn accepts_the_bounds_the_reply_can_carry() { + let rec = Record { + mtu: Some(68), + ..record() + }; + assert_eq!(u16::from_be(rec.entry(MAC).unwrap().mtu), 68); + + let rec = Record { + prefixlen: 32, + ..record() + }; + assert_eq!(u32::from_be(rec.entry(MAC).unwrap().netmask), u32::MAX); + let rec = Record { + prefixlen: 1, + ..rec + }; + assert_eq!(u32::from_be(rec.entry(MAC).unwrap().netmask), 1 << 31); + } + + impl RecordStore for BTreeMap { + fn insert(&mut self, ifindex: u32, rec: DhcpRecord) -> anyhow::Result<()> { + BTreeMap::insert(self, ifindex, rec); + Ok(()) + } + + fn remove(&mut self, ifindex: u32) -> anyhow::Result<()> { + BTreeMap::remove(self, &ifindex); + Ok(()) + } + } + + fn entry() -> DhcpRecord { + record().entry(MAC).unwrap() + } + + fn other_answer() -> DhcpRecord { + Record { + ip: Ipv4Addr::new(10, 0, 0, 200), + ..record() + } + .entry(MAC) + .unwrap() + } + + const OTHER_MAC: [u8; 6] = [0xda, 0x65, 0x8f, 0x18, 0x9b, 0x70]; + + fn other_mac() -> DhcpRecord { + record().entry(OTHER_MAC).unwrap() + } + + fn bad_record() -> Record { + Record { + lease: 0, + ..record() + } + } + + #[test] + fn a_plug_or_record_change_writes_whatever_is_there() { + let mut map = BTreeMap::new(); + write_entry(&mut map, 1, Some(entry())).unwrap(); + assert_eq!(map[&1], entry()); + map.insert(1, other_mac()); + write_entry(&mut map, 1, Some(other_answer())).unwrap(); + assert_eq!(map[&1], other_answer()); + } + + #[test] + fn a_plug_or_record_change_without_a_record_removes_the_entry() { + let mut map = BTreeMap::new(); + map.insert(1, entry()); + let iface = iface("a", None); + write_entry(&mut map, 1, iface.entry().unwrap()).unwrap(); + assert!(map.is_empty()); + // a missing entry is removed already + write_entry(&mut map, 1, iface.entry().unwrap()).unwrap(); + assert!(map.is_empty()); + } + + #[test] + fn a_detach_removes_the_entries_of_every_index_it_was_given() { + let mut map = BTreeMap::new(); + map.insert(1, entry()); + map.insert(2, entry()); + map.insert(3, entry()); + remove_entries(&mut map, &[1, 2]).unwrap(); + assert_eq!(map.keys().copied().collect::>(), [3]); + // a missing entry is removed already + remove_entries(&mut map, &[1, 4]).unwrap(); + assert_eq!(map.keys().copied().collect::>(), [3]); + } + + fn iface(name: &str, record: Option) -> Iface { + Iface { + name: name.into(), + mac: Some(MAC), + record, + } + } + + #[test] + fn the_pass_syncs_the_records_it_knows() { + let mut live = HashMap::new(); + live.insert(1, entry()); // same answer as the config + live.insert(2, other_answer()); // a changed answer + live.insert(3, other_mac()); // a MAC the config does not name + let ifaces = [ + iface("a", Some(record())), + iface("b", Some(record())), + iface("c", Some(record())), + iface("d", Some(record())), // no entry yet + ]; + let present: HashMap = (1..=4).zip(ifaces.iter()).collect(); + let entries = desired_entries(&live, &present); + + assert_eq!(entries[&1], entry()); + assert_eq!(entries[&2], entry(), "a changed answer is rewritten"); + assert_eq!(entries[&3], entry(), "the MAC follows the config"); + assert_eq!(entries[&4], entry(), "a new interface gets its entry"); + } + + #[test] + fn the_pass_keeps_only_handed_in_interfaces_with_a_record() { + let mut live = HashMap::new(); + live.insert(1, entry()); // handed in with a record + live.insert(2, entry()); // handed in without one + live.insert(3, entry()); // not handed in + let ifaces = [iface("a", Some(record())), iface("b", None)]; + let present: HashMap = (1..=2).zip(ifaces.iter()).collect(); + let entries = desired_entries(&live, &present); + + assert_eq!( + entries.keys().copied().collect::>(), + HashSet::from([1]) + ); + } + + #[test] + fn bad_input_leaves_its_interface_alone() { + let mut live = HashMap::new(); + live.insert(1, other_answer()); + let ifaces = [ + iface("a", Some(bad_record())), + iface("b", Some(record())), + iface("c", Some(bad_record())), + ]; + let present: HashMap = (1..=3).zip(ifaces.iter()).collect(); + let entries = desired_entries(&live, &present); + assert_eq!(entries[&1], other_answer(), "the old entry stays"); + assert_eq!(entries[&2], entry(), "the rest is written"); + assert!(!entries.contains_key(&3), "one without an entry gets none"); + } +} diff --git a/proxmox-sdn-dhcp/src/types.rs b/proxmox-sdn-dhcp/src/types.rs new file mode 100644 index 000000000000..9d3503b599bf --- /dev/null +++ b/proxmox-sdn-dhcp/src/types.rs @@ -0,0 +1,42 @@ +//! Keep in sync with 'src/bpf/dhcp/types.h' in pve-network. + +/// Addresses, lease and mtu are stored in network byte order, so a reply copies them into the +/// packet as-is. +#[repr(C)] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct DhcpRecord { + pub ip: u32, + pub netmask: u32, + /// 0 = not served + pub router: u32, + /// 0 = not served + pub dns: u32, + pub server_id: u32, + pub lease: u32, + /// 0 = not served + pub mtu: u16, + /// The NIC's MAC, a request carrying another is passed on. + pub mac: [u8; 6], +} + +unsafe impl aya::Pod for DhcpRecord {} + +#[cfg(test)] +mod layout { + use core::mem::{offset_of, size_of}; + + use super::*; + + #[test] + fn matches_bpf_abi() { + assert_eq!(size_of::(), 32); + assert_eq!(offset_of!(DhcpRecord, ip), 0); + assert_eq!(offset_of!(DhcpRecord, netmask), 4); + assert_eq!(offset_of!(DhcpRecord, router), 8); + assert_eq!(offset_of!(DhcpRecord, dns), 12); + assert_eq!(offset_of!(DhcpRecord, server_id), 16); + assert_eq!(offset_of!(DhcpRecord, lease), 20); + assert_eq!(offset_of!(DhcpRecord, mtu), 24); + assert_eq!(offset_of!(DhcpRecord, mac), 26); + } +} -- 2.47.3