Files
OpenPXE/crates/dhcp-proxy/src/reply.rs
T
Miles Ward 49d0b00a8a v0.2.0 — pre-beta: per-MAC bindings, /metrics, themes, animated forge
This is the bulk pre-beta cleanup pass. Bumps the workspace to 0.2.0.
Test count is 56 -> 66 (+10), clippy is fully clean across the
workspace (was several dozen warnings).

## New features

**Per-MAC host bindings** (Tinkerbell smee pattern). New
`HostBindings` registry maps a MAC -> preferred boot target, persisted
to <work_dir>/hosts.json. The DHCP reply now embeds `?mac=${mac}` in
the boot.ipxe URL; iPXE substitutes the literal MAC client-side, so
the HTTP layer can short-circuit straight to the bound target instead
of rendering the menu. Reserved menu shortcuts (`_local`, `_gate`,
`_tools_menu`) are valid targets too. New /api/hosts CRUD + a Hosts
tab in the sidebar.

**Prometheus `/metrics`** endpoint. Tiny lock-free implementation —
just AtomicU64s and a Display impl, no `prometheus` / `metrics-rs`
dep. Counters: DHCP replies (per arch label), DHCP declined, TFTP
transfers (per status), TFTP bytes, HTTP requests (per route).
Gauges: ISO count, client count, gate count, gate-imaging, NFS active
mounts, uptime, build info. Plain text exposition format,
text/plain;version=0.0.4 content-type, no auth (all metric values are
non-sensitive counts).

**Light + dark themes**. CSS tokens on `:root` and
`:root[data-theme=light]`, swap by toggle button (top-right) or `T`
hotkey. Persisted in localStorage; pre-paint inline script avoids
dark<->light flash. Light palette designed against the Netbox Labs
reference screenshot — near-white surfaces, soft grey dividers,
accent unchanged for brand consistency. Terminal pane stays dark in
both themes (it's a console, that's the right read).

**Animated SVG logo + forge widget**. New `logo.svg` is a refined
silver/grey anvil. New `anvil-forge.svg` adds rising sparks and a
pulsing underglow via SMIL — pure SVG, no GIF, no JS animation loop.
Used:
  - in the **forge progress** widget on Dashboard + Forge Gate, paired
    with a `linear-gradient(warn -> accent)` bar with a moving sheen;
    goes idle (greyscale, no sheen) at zero imaging load
  - in the page-load `<div class=loader>` that replaces the old
    "Loading..." text

## Code cleanup pass

`cargo clippy --workspace --all-targets` is now warning-free. Spot
fixes across the tree:
  - `format!()`-into-`String` -> `std::fmt::Write::write!`
  - manual reverse comparators -> `Reverse`
  - `map_or(false, ...)` -> `is_some_and`
  - redundant closures -> method references
  - `r#"..."#` raw strings without `"` -> `r"..."`
  - `std::io::Error::new(Other, ...)` -> `Error::other`
  - `as i32` on `c.id()` -> `cast_signed()`
  - merged identical match arms

## Windows workflow validation

New integration test synthesizes an ISO9660 with the SOURCES\\BOOT.WIM
sentinel, uploads it, asserts:
  1. introspection labels it `windows_pe` with has_boot_wim=true,
  2. the boot entry is `BootKind::Wimboot` with all five canonical
     files (bootmgr, bootmgr.efi, bcd, boot.sdi, boot.wim),
  3. the rendered iPXE script chains wimboot with `initrd --name`
     entries for each file, and
  4. NO trust-store strings appear in the rendered output: bcdedit,
     testsigning, certutil, httpdisk, and test-signed are all
     explicitly forbidden as a hard guarantee.

WinPE bootstrap (startnet.cmd) picks up the Bootimus v0.1.58 lessons:
explicit `net start Workstation` before `net use` to avoid the SMB
client lazy-init race, and surfaces errors instead of blind retries.

## Docs

architecture.md gains a "Phase 5" section explaining the host-bindings
+ metrics + theming + Windows-test work, plus a refreshed "deferred
to Phase 6" list (real-hardware integration, autounattend library,
distro profile manifest, WoL trigger, syslog receiver, IPv6).
README updates the status line, the "what it does" list, and adds
the new Hosts/Terminal tab names.
2026-04-30 02:28:10 -04:00

130 lines
5.1 KiB
Rust

//! Build DHCP proxy replies.
//!
//! Proxy replies look like a normal DHCPOFFER/ACK except:
//! - `yiaddr` (your IP) is 0 — we don't lease.
//! - `siaddr` (server IP) is us — the client will TFTP from here.
//! - option 60 (vendor class) MUST be echoed as `PXEClient` or clients drop.
//! - option 66 (TFTP server name) points at us.
//! - option 67 (bootfile name) is per-architecture iPXE binary on first
//! pass, or the HTTP URL of the boot script once iPXE has chained.
use dhcproto::v4::{DhcpOption, Message, MessageType, Opcode, OptionCode};
use pxeforge_core::{ClientArch, FirmwareClass};
use std::net::Ipv4Addr;
/// Where the reply directs the client next.
#[derive(Debug, Clone)]
pub enum BootDirective {
/// Serve an iPXE binary over TFTP (first-stage chainload).
TftpIpxe { filename: String },
/// Serve an iPXE boot script directly over HTTP. Used when the client is
/// iPXE itself (option 77 = "iPXE") or UEFI HTTP boot (option 60 starts
/// with "HTTPClient").
HttpScript { url: String },
/// Refuse to respond (architecture we don't have a binary for, or
/// not-a-PXE-client). Caller should skip sending anything.
Ignore,
}
pub struct ReplyContext<'a> {
pub request: &'a Message,
pub our_ip: Ipv4Addr,
pub arch: ClientArch,
pub class: FirmwareClass,
/// Public base URL (scheme://host[:port]) used in HTTP directives.
pub public_base_url: &'a str,
}
/// Decide what to do for an incoming request. Pure function — easy to unit
/// test. Does NOT send anything.
#[must_use]
pub fn decide(ctx: &ReplyContext<'_>) -> BootDirective {
match ctx.class {
FirmwareClass::IpxeUserClass => BootDirective::HttpScript {
// Pass the client's MAC in the query string so the HTTP
// layer can short-circuit to a per-MAC binding when one
// exists. iPXE substitutes `${mac}` literally before issuing
// the GET, so this stays static across firmwares.
url: format!(
"{}/boot.ipxe?mac=${{mac}}",
ctx.public_base_url.trim_end_matches('/')
),
},
FirmwareClass::HttpClient => {
// UEFI HTTP boot: client wants an http:// URL in option 67
// pointing at an EFI executable. We serve ipxe.efi over HTTP;
// it'll then do the same script-fetch the iPXE path does.
let name = ctx.arch.ipxe_bootfile().unwrap_or("snponly.efi");
BootDirective::HttpScript {
url: format!("{}/ipxe/{}", ctx.public_base_url.trim_end_matches('/'), name),
}
}
FirmwareClass::PxeClient => match ctx.arch.ipxe_bootfile() {
Some(name) => BootDirective::TftpIpxe { filename: name.to_string() },
None => BootDirective::Ignore,
},
FirmwareClass::Other => BootDirective::Ignore,
}
}
/// Build the outgoing DHCPOFFER (or ACK, matching request type) for a
/// directive. Caller is responsible for sending the bytes on the wire.
pub fn build_reply(ctx: &ReplyContext<'_>, directive: &BootDirective) -> Option<Message> {
let reply_type = match request_message_type(ctx.request)? {
MessageType::Discover => MessageType::Offer,
MessageType::Request | MessageType::Inform => MessageType::Ack,
_ => return None,
};
let mut msg = Message::default();
msg.set_opcode(Opcode::BootReply)
.set_htype(ctx.request.htype())
.set_hops(0)
.set_xid(ctx.request.xid())
.set_secs(0)
.set_flags(ctx.request.flags())
.set_ciaddr(Ipv4Addr::UNSPECIFIED)
.set_yiaddr(Ipv4Addr::UNSPECIFIED) // proxy does not lease
.set_siaddr(ctx.our_ip)
.set_giaddr(ctx.request.giaddr())
.set_chaddr(ctx.request.chaddr());
// Set the BOOTP `file` field for legacy PXE stacks before we take the
// options borrow (the two borrows can't overlap).
if let BootDirective::TftpIpxe { filename } = directive {
msg.set_fname_str(filename);
}
let class_echo: &[u8] = match ctx.class {
FirmwareClass::HttpClient => b"HTTPClient",
_ => b"PXEClient",
};
let opts = msg.opts_mut();
opts.insert(DhcpOption::MessageType(reply_type));
opts.insert(DhcpOption::ServerIdentifier(ctx.our_ip));
// Echo the vendor class — REQUIRED by spec for the client to accept.
opts.insert(DhcpOption::ClassIdentifier(class_echo.to_vec()));
match directive {
BootDirective::TftpIpxe { filename } => {
opts.insert(DhcpOption::TFTPServerName(ctx.our_ip.to_string().into_bytes()));
opts.insert(DhcpOption::BootfileName(filename.as_bytes().to_vec()));
}
BootDirective::HttpScript { url } => {
opts.insert(DhcpOption::BootfileName(url.as_bytes().to_vec()));
opts.insert(DhcpOption::TFTPServerName(ctx.our_ip.to_string().into_bytes()));
}
BootDirective::Ignore => return None,
}
opts.insert(DhcpOption::End);
Some(msg)
}
fn request_message_type(m: &Message) -> Option<MessageType> {
m.opts().get(OptionCode::MessageType).and_then(|o| match o {
DhcpOption::MessageType(t) => Some(*t),
_ => None,
})
}