From 4003c006611ccf2520ca6d6d5df0d44e044673bb Mon Sep 17 00:00:00 2001 From: Scouty Date: Wed, 19 Aug 2026 20:23:35 -0700 Subject: [PATCH 01/17] docs: collector revision plan rev 4 addressing delegated review - docs/review-2026-08-20.md: verbatim delegated review (needs-rework, 3 blockers, 10 majors) - plan rev 4: canonical BmpFeedKey with policy-plane separation, per-router snapshot coordinator (one collector RIB, grouped entries), event-time vs seal-time discipline, feed lifecycle semantics, ADD-PATH v1 guard, backpressure as TCP stall + loss invalidation, trigger delivery records with completion policy, spill replay-manifest contract, memory figures marked estimates pending benchmark gate, trusted router identity - examples: [REDACTED] passwords, mgmt-address binds, pinned image tag, corrected 50-peer fleet row (3-6 GB), RV/RIS-compatible wording --- docs/collector-revision-plan.md | 408 ++++++++++++++++++++++++++++++++ docs/examples.md | 192 +++++++++++++++ docs/review-2026-08-20.md | 132 +++++++++++ 3 files changed, 732 insertions(+) create mode 100644 docs/collector-revision-plan.md create mode 100644 docs/examples.md create mode 100644 docs/review-2026-08-20.md diff --git a/docs/collector-revision-plan.md b/docs/collector-revision-plan.md new file mode 100644 index 0000000..e521fd5 --- /dev/null +++ b/docs/collector-revision-plan.md @@ -0,0 +1,408 @@ +# focl revision plan: the easiest way to run your own MRT archive + +Revision 4 (2026-08-20). Addresses the delegated review (needs-rework +verdict: 3 blockers, 10 majors; see docs/review-2026-08-20.md). Direction: +focl is a **self-hosted BGP data +collector**, not a router. It ingests BGP data through two modes and archives +both into the same MRT pipeline that already exists: + +- **BMP station mode** (primary for operators): focl listens on TCP, routers + (Juniper, Cisco, Nokia, FRR, GoBGP) connect and stream monitoring data. No + peering session, no policy risk, sees pre-policy Adj-RIB-In. This is usually + the politically easy path inside an org. +- **BGP peering mode** (labs, VMs, research): focl speaks BGP itself and peers + with a willing neighbor (transit, IX route server, another focl/GoBGP). + +Both modes emit RouteViews/RIS-**compatible** MRT (`updates.*` + `rib.*` +— compatible naming and record types, not byte-identical provenance), so +every downstream BGPKIT tool (bgpkit-parser, monocle, Broker, bgp.fyi) +works on a private archive with zero glue. Segment manifests record source, +plane, completeness, timestamp source, and config version so consumers can +distinguish private archives from RV/RIS originals. + +## Standing engineering rules (from review, apply everywhere) + +1. **bgpkit-parser 0.20.0**, not 0.15. focl currently pins `bgpkit-parser = + "0.15"`; latest is 0.20.0 (published 2026-08-16). 0.15 predates the + fallible-encoder rework (UPDATE/OPEN `encode` now returns + `Result` and takes `asn_len`), so the upgrade is also + the moment to make focl's encode paths fallible everywhere (no + `unwrap`/`expect` on encode). BMP module, TableDumpV2, BGP4MP encoding all + come from the same upgrade. Parser 0.20 `parser` feature pulls chrono + + regex + zerocopy; MSRV 1.87; dev-dep bzip2 moved to 0.6. +2. **ipnet-trie for all prefix storage.** Adj-RIB-In, RIB snapshots, future + RPKI validation: use `ipnet-trie = "0.3"` (BGPKIT's own crate, built on + prefix-trie 0.6, same `ipnet::IpNet` type focl already uses). One trie per + peer; LPM lookup for monitoring/containment queries. No hand-rolled + HashMap-of-prefixes. +3. **All archive cadence, location, and naming is config-driven.** The + foundation already exists (`layout_profile = routeviews | ris | custom` + with `{collector}/{yyyy}/{mm}/{dd}/{yyyymmdd}/{hhmm}/{ext}` templates, + per-stream intervals, compression choice, root/tmp paths). What's missing + is applying it consistently: BMP router identity must flow into + `collector_id`, custom templates must not allow `..` or absolute paths + (security guard), and every knob must be documented in the config + reference. +4. **Built-in file-notification triggers.** When a segment finalizes, focl + itself notifies downstream consumers. See Phase 3. + +## Target architecture + +``` + ┌─ BMP listener (TCP :1790, per-router MD5, many routers) +feed sources ────────┤ + └─ BGP speaker (existing FSM, per-peer sessions) + │ + ▼ normalized UpdateRecordInput / PeerStateRecordInput (raw BGP bytes) + ArchiveService (existing: rotation, compression, manifest, S3 + local replication) + │ + ├─ on finalize → trigger dispatch (Phase 3) + ▼ + updates.YYYYMMDD.HHMM.{gz,bz2,zst} / rib.YYYYMMDD.HHMM.* ← standard MRT + │ + ▼ downstream: monocle / broker / duckdb / S3 replication +``` + +Core refactor: introduce a `FeedSource` boundary. `BgpService` and the new +`BmpListener` both normalize into the archive input types +(BGP4MP_MESSAGE_AS4 / STATE_CHANGE_AS4 records). Neither source knows about +MRT; the archive knows nothing about BMP/BGP sessions. + +## Phase 0 — foundations both modes need + +1. **Dependency refresh.** `bgpkit-parser 0.15 → 0.20.0`, `bzip2 0.4 → 0.6`, + add `ipnet-trie = "0.3"`. Fallible encode throughout; fix the + `write_bgp_message` marker-fill path accordingly. +2. **Dual-stack archive records.** `UpdateRecordInput`, + `PeerStateRecordInput`, `SnapshotPeer`, `SnapshotRoute` are IPv4-only + (`Ipv4Addr` fields). Change to `IpAddr`; BGP4MP and TableDumpV2 encoding + branches on family. +3. **IPv6 RIB snapshots.** `SnapshotRoute.prefix` is a bare `Ipv4Addr`; needs + prefix + length + AFI/SAFI per RIB entry so TableDumpV2 v6 tables are + valid. Group all RIB entries per (AFI/SAFI, prefix) into one + `RibAfiEntries` record (multiple peer entries preserved), replacing + one-record-per-route. +4. **Raw message passthrough.** Archive raw UPDATE bytes verbatim: a + pass-through BGP4MP envelope encoder that writes peer/local metadata + plus the original frame bytes unchanged. Parsed copies are for trie and + state processing only, never the archive path. BMP gives raw bytes + directly; for BGP sessions keep the original frame. +5. **Event-time discipline (from review blocker 3).** Record event time and + archive partition/seal time are separate concerns: + - MRT record timestamps use the event time (BMP PDU timestamp when + nonzero, else receipt time with `timestamp_source = "arrival"` noted + in the manifest). + - Segments are partitioned by ingestion clock, not by per-record event + time; a sealed segment's canonical path is never reopened. Late + records land in the currently-open segment (event time preserved in + the record) rather than reopening a sealed bucket. +6. **Golden-file round-trip tests.** Write MRT with focl, parse back with + bgpkit-parser, assert element equality, v4 and v6; include unknown + transitive attributes, MP_REACH/MP_UNREACH, four-octet AS path, and + malformed-but-archivable frames. +7. **Path-template and collector-id hardening (from review major 13).** + Custom templates and `collector_id` are validated before rendering: + reject absolute paths, `..`, empty components, and characters outside a + safe identifier charset. Containment is re-checked after rendering. + +## Phase 1 — make BGP peering mode a real collector + +1. **Adj-RIB-In store on ipnet-trie.** One trie per peer. Value model is + `{interned attribute-blob id (u32), last_change_ts, path_id?}` — raw + UPDATE bytes live only in MRT, never duplicated per prefix (fixes the + review's inconsistent-representation finding). Memory-only v1 (rusqlite + stays for the replication queue). +2. **Wire the archive.** Received UPDATEs → `ingest_update` (exists, never + called); FSM transitions → `ingest_peer_state` (events already flow). + Rx-only by convention (RouteViews/RIS never archive tx). +3. **Real RIB snapshots.** Dump adj-rib-in tries on the configured ribs + interval as one collector snapshot (single peer-index table, entries + grouped per prefix), replacing today's empty snapshot. **No RIB file is + emitted before a valid baseline exists** (fixes empty-dump bug). Pre- + policy semantics (`adj_rib_in` is already the config default). +4. **Capability negotiation.** Advertise and validate the intersection of + locally configured and peer-advertised capabilities: MP-BGP v4+v6, + route-refresh, AS4, extended-message, graceful-restart behavior, and + per-AFI/SAFI ADD-PATH policy. A capability-less OPEN establishes plain + IPv4 BGP; what it cannot do is IPv6/MP-BGP sessions — that is the real + gap (corrects review major 6). UPDATEs enter the trie only after + negotiated AFI/SAFI is known. +5. **Global passive listener** with per-peer match before any state + mutation, connection-collision handling, separate v4/v6 bind + configuration, and rejected-connection observability; replacing + per-peer binds; the `listen` global config becomes real. +6. **Interop expansion.** Extend the GoBGP scripts: v6 session, capability + matrix, flap → assert MRT files parse and contain expected elements. + Negative tests (review minor 16): malformed UPDATE disposition, Peer + Down clears the peer's trie, interrupted EoR yields no complete dump, + duplicate Peer Up starts a new generation. + +## Phase 2 — BMP station mode + +1. **`BmpListener`** on a configurable port per station; per-router + TCP-MD5 (TCP-AO is a documentation-level non-goal for v1; focl + implements TCP-MD5 only); accept many routers concurrently. Parsing via + bgpkit-parser 0.20's BMP module. +2. **Feed key (from review blocker 1).** Every route-monitoring feed is + keyed by a canonical `BmpFeedKey`: + ``` + router identity (trusted, from connection/matching) + + BMP connection generation + + peer type (Global | RD | Local | Local-RIB) + + peer_distinguisher + peer_ip + peer_asn + peer_bgp_id + + plane {pre_in | post_in | adj_out | local_rib} // L and O flags + + AFI/SAFI + ``` + v1 accepts only `pre_in` (pre-policy Adj-RIB-In) by default; other + planes are either rejected with a diagnostic or archived under + separately named views (config), never merged. No feed is called + "Adj-RIB-In" unless its flags say so. +3. **Feed lifecycle (from review major 4).** + - `PeerUp`: new connection generation, parse both OPENs, record + capabilities (incl. per-AFI/SAFI ADD-PATH policy), initialize walks + for negotiated AFI/SAFIs. + - `PeerDown`: implicit full withdraw for that feed — invalidate the + generation, clear its trie, drop its routes from future snapshots; + optionally archive a derived STATE_CHANGE with the reason code. + - `Termination` / TCP EOF: all feeds on that connection become + unavailable and all incomplete walks are invalid. + - `RouteMirroring(MessageLost|ErroredPdu)`: mirrored data is + diagnostic + archived raw; it never rebuilds a route-monitor trie. + Mark feed completeness broken until a new RM baseline walk. + - STATE_CHANGE records are synthetic mappings (Idle↔Established), + documented as such, not native BMP FSM events. +4. **Snapshot coordinator (from review blocker 2).** Per router: track + eligible feeds from PeerUp and EoR completion per feed × AFI/SAFI. + Freeze all selected tries into **one** collector RIB segment (one + peer-index table; entries grouped per (AFI, SAFI, prefix); multiple + peer paths per prefix preserved) on: all-eligible-complete, or timeout + with manifest-declared partiality, or a configured subset. No periodic + RIB file until each included feed has a valid baseline. +5. **PDU mapping:** + - Route Monitoring (pre_in) → feed trie + snapshot coordinator + - Route Mirroring → raw updates stream + diagnostics + - Peer Up/Down → feed lifecycle + optional STATE_CHANGE records + - Stats Reports → operational counters (Prometheus, ops-only) + - Init Message → operational metadata only; never trusted for + filesystem identity or `collector_id` +6. **Peer identity.** One `collector_id` per router, mapped from trusted + config (`[[bmp.routers]]` entry matched by source address/identity), + not from untrusted BMP Init sysName. Keeps layout identical to RV/RIS + and downstream tooling unchanged; `view_name` stays "main". +7. **ADD-PATH guard (from review major 5).** When a feed negotiated + ADD-PATH receive, v1 either keys tries by `(prefix, path_id)` and + writes `*_ADD_PATH` TableDumpV2 records, or degrades that feed to + `ribs_mode = off` with raw updates retained, with an operator-visible + status (`archive_raw=yes, derived_rib=no, reason=add_path_unsupported`). +8. **Event-time discipline** per Phase 0 rule 5: PDU timestamps are record + event times; partition/seal uses the ingestion clock; zero timestamps + fall back to arrival time and are marked in the manifest. +9. **Tests from captured BMP streams** (fixture corpus) → golden MRT + output, including delayed/reordered PDUs, zero timestamps, Peer Down + mid-walk, Termination mid-walk, duplicate PeerUp, and both-planes + streams (must not merge). + +## Phase 3 — "easiest setup" UX and file triggers + +1. **Trigger mechanism on segment finalize.** ArchiveService already emits + `ArchiveSegmentFinalized` events; formalize dispatch: + - `exec` triggers: run a command with the finalized path, sha256, size, + and record count passed as env vars and JSON on stdin. Built-in example + recipes: POST to a webhook, move/copy, publish to SNS/SQS. + - Config: `[[archive.triggers]]` with `stream = "updates" | "ribs" | "both"`. + - **Delivery records (from review major 12):** per-trigger durable + records keyed by (segment checksum, trigger id, attempt) with states + `pending / running / acknowledged / unknown`. Exit 0 = acknowledged; + crash before state write = `unknown`, which is retriable. Delivery is + at-least-once, documented as such; never exactly-once. + - **Completion policy:** `local_finalized` (default), `all_required` + (every primary+required destination acked), or a named destination + set. Replication events are per-destination today; the trigger + dispatcher aggregates them per segment. + - `focl trigger list` / `focl trigger test` CLI for inspection. +2. `focl init` wizard: pick mode, answer 4 questions, get a working TOML. +3. `focl doctor`: reachability, MD5 mismatch detection, session watch, + first-archive-file check by parsing it back with bgpkit-parser. +4. `focl tail`: live NDJSON of archived elements (extend `events_subscribe` + to updates). +5. Docker image: `docker run -p 1790:1790 -v $PWD/data:/data focl --bmp` + one-liner; compose example with S3 replica and a trigger example. +6. Docs: copy-paste BMP stanza snippets for Juniper/Cisco/FRR/GoBGP, plus + peering snippets for BIRD/GoBGP. Document every archive knob. + +## Phase 4 — differentiators (later, on demand) + +- RPKI validity computed at ingest (ipnet-trie LPM over ROA VRPs) and stored + alongside elements +- Live streaming mode (BMP → websocket, ris-live-like) for real-time feeds +- Broker-compatible index publication so internal discovery uses the same + API as public collectors +- ADD-PATH / graceful restart as real deployments require them +- `focl announce` lab features stay, but are not the product + +## RIB dumps from a BMP stream (design, revised) + +RIB and updates are different products and are treated differently +end-to-end: separate config (`ribs_mode`, `ribs_interval_secs`), separate +files, separate memory policy. + +RIB dumps under BMP are **derived, not received**. BMP route-monitor PDUs +arrive as a walk of the router's RIB; a dump file must be assembled from the +stream — assembled by the per-router **snapshot coordinator** (Phase 2 item +4), not per-peer EoR writes. Design: + +1. **EoR-triggered baseline (v1).** Per feed (canonical feed key): start an + empty ipnet-trie at the first Route Monitoring PDU, insert routes until + End-of-RIB marker per AFI/SAFI. When the coordinator's policy is + satisfied (all eligible feeds complete, or timeout with declared + partiality), freeze all tries into one collector TableDumpV2. This is + the standard way monitor tables are materialized; focl's output is + RV/RIS-**compatible**, not provenance-identical. +2. **Trie-maintained dumps (v2 default, `ribs_mode = "trie"`).** Keep the + trie hot after the walk, apply subsequent updates (announce/withdraw) as + they arrive, dump all tries via the coordinator on each + `ribs_interval_secs` boundary — one collector snapshot, not per-peer + files. Memory cost is the trie; storage cost is one dump per interval. +3. **Initial-only (`ribs_mode = "initial-only"`).** Dump the EoR snapshot, + drop the trie, stream updates only. Near-zero steady-state memory; RIB + snapshots then exist only at session start. +4. **Rebuild markers.** Mirroring PDUs or post-policy re-walks can + invalidate trie state; emit a diagnostic event and re-walk rather than + emitting a silently wrong dump. Peer Down invalidates the feed's + generation entirely (implicit full withdraw). A dump is always + internally consistent (single freeze point); it may be partial if the + walk was interrupted, and the manifest says so. +5. **RIB retention is a config decision**, because dump frequency dominates + storage: 2 h dumps ~ 900 MB/day/peer vs 24 h ~ 76 MB/day/peer (bz2, full + feed). `retention_days` prunes local files after replication; remote + retention is the destination's concern (e.g. R2 lifecycle rules). + +## Scale engineering: fleet of routers, bounded memory (new) + +Goal: many hundreds of concurrent writers (BMP sessions and peers) on one +box. Anchors: ~950k v4 + ~200k v6 routes per full feed; RV2 rib file 76 MB +bz2; naive in-memory full-table representation is 150-250 MB/peer and does +not scale to a fleet. Strategy, in order: + +1. **Per-peer trie, interned values (default).** Value stored per prefix = + `u32` attribute-blob id, not bytes. A process-wide interner dedups + attribute sets (AS path, communities, etc.) across peers; similar feeds + share blobs. Expected 60-120 MB per full-feed peer vs 150-250 MB naive, + plus ~50-100 MB process-wide. Trie nodes themselves are compact + (prefix-trie uses bit-path nodes, ~10-15 B/node region). +2. **Storage-for-memory trades.** + - `ribs_mode = initial-only` removes the hot trie entirely. + - **Spill-to-disk for cold peers.** When process RSS crosses a soft + watermark (e.g. 70% of a configured budget), evict the + least-recently-dumped peer's trie. The spilled state is an immutable + point-in-time snapshot; it is never updated in place. Reload paths, + pick by cost: + - baseline: re-materialize from focl's own archive (last RIB dump + + updates MRT since then). Zero new formats, replay uses the same + parser we ship, and correctness of reload doubles as a round-trip + test. Reload cost is a full parse. + - fast path (optional, later): rkyv zero-copy image of the frozen + trie for mmap-speed reload, same pattern as BGPKIT's static ROA + serving. rkyv is strictly for static data here: churn since spill + is replayed from the updates log into a fresh in-memory trie; the + image is never mutated or re-serialized per change. + Spill only pays for cold peers; hot peers stay in RAM or degrade to + updates-only. If a genuinely mutable on-disk trie is ever required + (continuous disk-backed updates), that is an LMDB-shaped problem, + not rkyv. + - **Log-structured updates:** updates are append-only and never need a + trie to be archived; under memory pressure a peer can run updates-only + (RIB dumps degraded or disabled) without data loss. +3. **Shard by router, not by prefix.** One archive service per BMP router + (`collector_id` per router) keeps writers independent: no cross-router + locks, per-router rotation, per-router S3 prefixes. Global process + coordination is limited to the interner and the replication queue. +4. **Writer architecture.** Bounded mpsc channels per router -> single + writer task per router (SegmentWriter is already single-writer per + segment; compression already streams). **Backpressure (from review + major 8):** writers receive via `recv().await` on bounded channels; + senders use `send().await`, which suspends the per-connection read loop + when the channel is full — the TCP receive window closes and the + router's send buffer fills (a stall, not a retransmit promise). On + connection loss, parser error, queue abort, or Route Mirroring + `MessageLost`, increment durable counters, mark the feed's generation + incomplete, and require a new Peer Up + EoR baseline before derived + RIBs resume. Overload limits (max channel capacity per router) are + config; exceeding them is an operator-visible degradation, never a + silent drop. The acceptor loop is never blocked. +5. **Spill durability (from review major 9).** Spill is Phase 3 and + requires a per-router replay manifest first: baseline RIB path + + checksum, feed key + generation, update segment range (sealed segments + only — an open compressed segment is not a valid replay input), seal + watermark, pin count. Retention must not prune pinned replay ancestry. + Updates are durable before eviction (seal the current segment on spill, + or WAL). The rkyv image, if ever built, is cache acceleration only. +6. **Parquet as a derived tier (optional).** MRT stays the interchange + format. A trigger-invoked converter (or `focl parquet` subcommand) turns + finalized MRT into sorted, dictionary+delta-encoded Parquet (per peer or + per day) for DuckDB analytics. This trades storage (Parquet of BGP elems + is typically smaller than bz2 MRT for scans) for one more pipeline stage, + and keeps DuckDB off the hot path. Ship as an example trigger recipe + first, promote to built-in if it proves out. +7. **Config guardrails for fleets.** `max_peers`, `memory_budget_mb` (soft + watermark driving spill), `retention_days`, per-router `ribs_mode` + override. `focl status` reports per-peer RSS estimate, trie sizes, + writer backlog, and projected storage/day so operators can see the + trade before it bites. +8. **Memory numbers are estimates until measured (review major 10).** The + trie value model is fixed (`{attribute_id: u32, last_change_ts, + path_id?}`); the 60-120 MB/peer interned figure and fleet rows are + planning estimates. A benchmark gate (captured v4+v6 full feeds) must + run before any fleet sizing table is quoted as fact: measure trie RSS, + intern-table cardinality, attributes/prefix, churn, queue high-water, + cold-reload time. Published tables get ranges by workload, not linear + promises. + +Sequencing within the plan: interned tries land with Phase 1/2 (they are the +adj-rib-in store); spill-to-disk and Parquet tier are Phase 3/4, driven by +measured fleet numbers, not speculation. Sizing tables users can quote live +in `docs/examples.md`. + +## Non-goals (explicit) + +- No routing policy framework, best-path selection, or FIB programming. + focl archives; it does not forward or decide. +- Not competing with BIRD/FRR/GoBGP as a router. GoBGP remains the interop + reference implementation. +- No OpenBMP protocol integration; direct BMP only. + +## Sequencing rationale + +Phase 0 first because both modes write through the same record types; fixing +v6, raw bytes, and the parser upgrade once serves both. Phase 1 before Phase +2 because it forces the normalized update path and the ipnet-trie adj-rib-in +store into existence, which BMP then reuses wholesale. Phase 2 is the +operator wedge (every real router speaks BMP; config is one stanza; no +peering approval needed). Phase 3 turns "works" into "easiest", which is the +stated product goal, and the trigger mechanism is what makes the archive a +platform other tools can build on. + +## Open design decisions + +1. Raw-bytes passthrough: BMP gives raw UPDATE bytes directly; for BGP + sessions, archive the original frame bytes via the pass-through BGP4MP + envelope (Phase 0 item 4). Confirm no parser changes needed. +2. Adj-RIB-In persistence: memory + periodic MRT dump only, or SQLite-backed? + Recommendation: memory-only v1; spill = frozen snapshot + updates-log + replay (own MRT baseline, optional rkyv image) gated on the Phase 3 + replay-manifest contract. No on-disk mutable trie unless fleet numbers + demand it. +3. BMP router identity: one collector_id per router (recommended), resolved + from trusted `[[bmp.routers]]` config matched by source identity — + never derived from untrusted BMP Init sysName. +4. BMP listener MD5: yes (focl implements Linux TCP-MD5 today; TCP-AO is + not implemented and stays out of v1 docs). +5. Trigger delivery semantics: at-least-once with durable per-trigger + delivery records (pending/running/acknowledged/unknown); exec exit 0 = + acknowledged; `unknown` retriable. Document clearly, don't pretend + exactly-once. +6. RIB dump policy under BMP: `ribs_mode` default. Recommendation: `trie` + for small fleets, `initial-only` above ~50 full-feed peers unless + `memory_budget_mb` allows more; decide from Phase 2 measurements. +7. Interner eviction: LRU with weak-handle resurrection, or generational + (rebuild per dump cycle)? Decide in Phase 1 implementation. diff --git a/docs/examples.md b/docs/examples.md new file mode 100644 index 0000000..b32e78a --- /dev/null +++ b/docs/examples.md @@ -0,0 +1,192 @@ +# focl usage examples: zero-to-archival on a Linux box + +Target-state documentation. Config shapes below are the spec the +implementation must satisfy (`docs/collector-revision-plan.md` rev 4). Every +example ends the same way: standard, RouteViews/RIS-**compatible** MRT files +on disk (naming and record types; private provenance declared in segment +manifests), parseable by bgpkit-parser / monocle / DuckDB with zero glue. + +Common ground for all examples: + +```bash +# Linux box, one binary, no runtime deps +curl -fsSL https://bgpkit.com/focl/install.sh | sh # or: cargo install focl +focld --config focl.toml +focl status # peers, sessions, open archive files, RSS +``` + +## Example 1: BMP station (the operator path) + +Router streams to focl; focl never peers, never announces, only archives. + +`focl.toml`: + +```toml +[global] +router_id = "198.51.100.10" # this box +control_socket = "/run/focld.sock" + +[bmp] +# bind a management address, not 0.0.0.0; restrict with a firewall +# allowlist so only known routers can connect +listen = "198.51.100.10:1790" +# optional per-router MD5; collector identity comes from this trusted +# mapping, never from the router's BMP Init sysName +# [[bmp.routers]] +# address = "203.0.113.6" +# collector_id = "edge01" +# password = "[REDACTED]" + +[archive] +enabled = true +collector_id = "edge01" # default when no [[bmp.routers]] match +layout_profile = "routeviews" +updates_interval_secs = 900 # RV-style 15-minute update files +ribs_interval_secs = 7200 # 2-hour RIB dumps, RV convention +ribs_mode = "trie" # trie | initial-only | off (see plan §RIB) +compression = "zstd" +root = "/data/mrt" +retention_days = 30 # local auto-cleanup after replication + +[[archive.destinations]] +type = "local" +mode = "primary" +path = "/data/mrt" +``` + +Router side, one stanza each: + +```text +# FRR +bmp monitor all stats-all pre-policy vrf default +bmp station target 198.51.100.10 port 1790 + +# Juniper +set protocols bmp station focl connection-mode active test-route-station +set protocols bmp station focl station-address 198.51.100.10 station-port 1790 +set protocols bmp station focl route-monitor post-policy false + +# Cisco IOS-XR +bmp server 1 host 198.51.100.10 port 1790 +router bgp 65000 bmp server 1 route-monitor pre-policy + +# GoBGP (test lab) +[bmp-server.config] + server-address = "198.51.100.10:1790" +``` + +Verify: + +```bash +focl doctor # router connected, Peer Up seen, EoR walk complete +focl tail --updates # live NDJSON of archived elements +ls /data/mrt/edge01/2026.08/UPDATES/ # updates.20260820.1645.zst +``` + +## Example 2: incoming BGP peering (the lab/research path) + +focl accepts an inbound eBGP session and archives what the neighbor sends. + +`focl.toml`: + +```toml +[global] +asn = 65001 +router_id = "198.51.100.10" +listen = true +listen_addr = "0.0.0.0:179" + +[[peers]] +name = "lab-upstream" +address = "203.0.113.6" # neighbor connects to us +remote_as = 65002 +passive = true +password = "[REDACTED]" # optional TCP-MD5 + +[archive] +enabled = true +collector_id = "focl01" +layout_profile = "ris" # rrc-style: updates.* + bview.* +updates_interval_secs = 300 # RIS-style 5-minute update files +ribs_interval_secs = 86400 # daily bview from adj-rib-in trie +ribs_mode = "trie" +compression = "gzip" +root = "/data/mrt" +``` + +Neighbor side (GoBGP): one `[[neighbors]]` block pointing here, or BIRD +`protocol bgp focl { local as 65002; neighbor 198.51.100.10 as 65001; }`. + +## Example 3: fleet daemon (systemd) and Docker + +```ini +# /etc/systemd/system/focld.service +[Service] +ExecStart=/usr/local/bin/focld --config /etc/focl/focl.toml +Restart=always +LimitNOFILE=65536 +# sizing guardrail for large fleets +MemoryHigh=24G +MemoryMax=28G +``` + +```bash +# pin a release tag or digest; do not run :latest in production +docker run -d --name focld -p 198.51.100.10:1790:1790 -p 198.51.100.10:179:179 \ + -v $PWD/focl.toml:/etc/focl/focl.toml:ro \ + -v /data/mrt:/data/mrt \ + ghcr.io/bgpkit/focld:v0.2.0 +``` + +## Sizing (anchored estimates, verify in Phase 1) + +Anchors measured from public archives (2026-08, single full-Internet feed, +~950k v4 + 200k v6 routes): RouteViews rib file = 76 MB bz2 per dump; +15-minute updates file = 0.9 MB bz2. Numbers below scale linearly with peers +and are for full-Internet feeds only. + +Per full feed peer per day: + +| Stream | Cadence | Compressed/day | +|---|---|---| +| updates | 15 min | 50-100 MB (bz2/zstd) | +| RIB | 2 h | ~900 MB (12 dumps x 76 MB) | +| RIB | 6 h | ~300 MB | +| RIB | 24 h | ~76 MB | + +Memory (RSS), per full feed peer held as adj-rib-in trie: + +| Mode | Per peer | Notes | +|---|---|---| +| naive (bytes inline) | 150-250 MB | never ship this | +| interned attrs, u32 values | 60-120 MB | default | +| ribs_mode = initial-only | < 10 MB | dump only the post-EoR walk, then updates only | + +Plus one process-wide interned attribute store (~50-100 MB total; cross-peer +dedup for similar feeds). **All memory figures below are planning estimates +pending the Phase 1 benchmark gate** (measured trie RSS, intern-table +cardinality, churn; see plan §Scale item 8). Fleet sketch, interned mode, +2 h RIBs: + +| Peers | RSS (estimate) | Storage/day | 30-day R2 (~$0.015/GB-mo) | +|---|---|---|---| +| 10 | 1-2 GB | ~10 GB | ~$5 | +| 50 | 3-6 GB | ~50 GB | ~$23 | +| 200 | 12-25 GB | ~200 GB | ~$90 | + +Knobs that move the needle: `ribs_interval_secs` (biggest storage lever), +`ribs_mode` (biggest memory lever), `retention_days`, compression choice +(zstd-3 recommended: ~bz2 size at ~10x speed). + +## Reading the archive + +```bash +# monocle on a private archive +monocle summary --path '/data/mrt/*/2026.08/UPDATES/*' + +# DuckDB over the same files via bgpkit-companion tooling, or plain: +focl parquet /data/mrt/edge01/2026.08/ # optional: co-convert to Parquet +``` + +MRT stays the interchange format (ecosystem compatibility); Parquet is a +derived, optional destination. diff --git a/docs/review-2026-08-20.md b/docs/review-2026-08-20.md new file mode 100644 index 0000000..94a1adc --- /dev/null +++ b/docs/review-2026-08-20.md @@ -0,0 +1,132 @@ +Delegated technical review of docs/collector-revision-plan.md (rev 3) and +docs/examples.md, cross-checked against the focl source tree and the +bgpkit-parser 0.20 checkout. Reviewer: GPT-5.6 Terra (high reasoning), via +Scouty delegation, 2026-08-19. Verdict: **needs-rework**. This file is the +verbatim review; the plan is rev 4 accordingly. + +## Verdict + +The product direction and broad phase order are good: MRT as canonical +output, parser 0.20 upgrade first, `ipnet-trie`, raw-message retention, and +immutable-rkyv-plus-MRT-replay are all sound choices. However, Phase 2 lacks +a sufficiently precise BMP/RIB state model, and the proposed event-time / +archive behavior can produce incorrect or overwritten segments under normal +delayed/out-of-order BMP delivery. These must be resolved before +implementation starts. + +## BLOCKER findings + +### 1. BMP RIB state is not separated by policy plane / peer identity +- References: plan Phase 2 mapping `:108-118`; RIB design `:153-178`; scale + design `:220-223`. Parser support: + `bgpkit-parser/src/parser/bmp/messages/headers.rs:195-279`. +- The plan unconditionally maps Route Monitoring to an `Adj-RIB-In` trie. + That is only correct for **pre-policy Adj-RIB-In**. BMP's per-peer header + distinguishes pre/post-policy (L flag), Adj-RIB-In/Out (O flag), and peer + type (Global, RD, Local, Local-RIB). A router can send both pre- and + post-policy streams for the same BGP peer; keying only on + "router, peer, AFI/SAFI" merges different RIBs. Peer IP alone also + collides across VRFs/RDs or repeated peers. +- Fix: canonical feed key = router identity + connection generation + + peer_type + peer_distinguisher + peer_ip + peer_asn + peer_bgp_id + plane + {pre_in, post_in, adj_out, local_rib} + AFI/SAFI. v1 accepts only `pre_in` + by default; other planes are archived separately or quarantined. + +### 2. EoR-to-RIB design cannot safely produce the proposed collector files +- References: plan RIB design `:163-178`; `src/archive/mod.rs:148-193`; + `src/archive/snapshot.rs:65-128`. +- Per-peer EoR dumps all target the same `rib.YYYYMMDD.HHMM` path and + clobber via rename; a collector RIB is one coherent snapshot across peers + with a single peer-index table. `SnapshotRoute` is one route/peer and + `build_table_dump_v2` writes one `RibAfiEntries` per route instead of + grouping entries per prefix. +- Fix: per-router snapshot coordinator: track eligible feeds, EoR completion + per feed/AFI, freeze all tries into one dump on explicit policy or + timeout, one peer-index table, group paths by (AFI, SAFI, prefix), no + periodic RIB until a valid baseline exists. + +### 3. Event-time file selection is unsafe for delayed, zero, or reordered PDUs +- References: plan `:117-118`; `src/archive/mod.rs:114-128,302-336`; + `src/archive/writer.rs:134-147`; BMP timestamps can be zero + (`headers.rs:229-232`). +- `ingest_update` selects the writer from `update.timestamp`; late PDUs + reopen sealed buckets, zero timestamps route to 1970, and `File::create` + plus rename can replace previous output. +- Fix: separate record event time from partition/seal time. Partition by + monotonic ingestion clock or event-time watermark with allowed lateness; + sealed segments never reopen; late data goes to bounded late segments with + a deterministic suffix; test delayed/reordered/zero-timestamp/boundary + cases. + +## MAJOR findings + +4. Peer Up/Down, Termination, and mirroring need explicit feed-lifecycle + state transitions (Peer Down = implicit full withdraw of that peer's + routes, invalidate generation; Termination ends all feeds on the + connection; Route Mirroring is not a re-walk mechanism; MessageLost + invalidates completeness). +5. ADD-PATH needs a v1 guard: per-AFI/SAFI add-path policy from Peer Up + OPENs; either `(prefix, path_id)` keys + `*_ADD_PATH` RIB records or + `ribs_mode=off` for affected feeds with raw updates retained. +6. Capability statement overstated: capability-less OPEN establishes plain + IPv4 BGP fine; the real requirement is advertise + validate the + intersection (MP-BGP, AS4, route-refresh, graceful-restart, extended + message, add-path). +7. Raw preservation needs a pass-through BGP4MP envelope encoder that + writes original frame bytes unchanged; current path re-encodes from + parsed structs (can normalize wire form). +8. Backpressure wording wrong: TCP stall is not router re-send. Use bounded + channels + `send().await`, stop reading that connection on full, define + overload limits; on loss/queue-abort/MessageLost increment durable + counters, mark feed generations incomplete, require new Peer Up + EoR + baseline before derived RIBs resume. +9. Spill durability contract incomplete: need a per-router replay manifest + (baseline RIB path/checksum, feed key/generation, update segment range, + watermark, pin count); updates must be durable before eviction (seal + segment or WAL); retention must pin replay ancestry; rkyv image remains + optional cache acceleration only. +10. Memory figures inconsistent (raw UPDATE bytes per prefix in Phase 1 vs + u32 interner id in fleet section; 50-peer math is ~3-6 GiB not 4-8 GB). + Fix the trie value model (`{attribute_id, last_change_ts, path_id?}`), + add a benchmark gate before quoting fleet numbers. +11. Per-router archives need a real config hierarchy: `[bmp]` listener + + `[[bmp.routers]]` keyed by trusted source identity, per-router + `collector_id`, view/plane policy, archive overrides; never derive + filesystem identity from untrusted sysName. Daemon currently builds one + ArchiveService. +12. Trigger semantics: per-trigger delivery records keyed by checksum + + trigger id + attempt with pending/running/acknowledged/unknown states; + `unknown` is retriable at-least-once; completion policy + (local-finalized | all-required | named set); replication events are + per-destination, no aggregate event exists yet. +13. Path traversal: reject absolute/root/prefix paths, `..`, empty + filenames before rendering; validate collector_id charset; component- + based containment checks under roots; replicator joins manifest-relative + paths without revalidation. Examples must use `[REDACTED]`, avoid + `0.0.0.0` defaults, pin image digests, and not promise TCP-AO (code + implements TCP-MD5 only). + +## MINOR findings + +14. Say "RouteViews/RIS-compatible MRT naming and record types", not + "identical"; keep manifests with source, plane, completeness, timestamp + source, config version. +15. Global BGP listener needs peer matching before state mutation, collision + policy, v4/v6 bind design, rejected-connection observability. +16. Negative tests required before BMP phase: no RIB before baseline, + malformed UPDATE disposition, Peer Down clears routes, interrupted EoR + produces no complete dump, duplicate Peer Up starts a new generation, + per-AFI/SAFI completion independence. + +## What is already sound + +- Parser 0.15 -> 0.20 with fallible encoders is necessary and correct. +- Dual-stack archive types conversion is necessary (currently IPv4-only). +- Corrected rkyv rule (frozen snapshots + MRT replay, no mutable rkyv trie). +- Storage arithmetic is sound once labeled workload-specific. + +## Top 3 changes before implementation + +1. Write the BMP feed-state and snapshot-coordinator specification. +2. Redesign ingestion/archive ordering around raw frames and time. +3. Make fleet and security claims implementation-backed. From 334450b7de004f3df3ef88cca8e272686b9dd664 Mon Sep 17 00:00:00 2001 From: Scouty Date: Wed, 19 Aug 2026 20:39:09 -0700 Subject: [PATCH 02/17] feat(archive): Phase 0 foundations - parser 0.20, dual-stack, raw passthrough Dependency refresh: - bgpkit-parser 0.15 -> 0.20 (fallible encoders throughout, bgp_identifier rename, RouteRefresh arm), bzip2 0.4 -> 0.6, add ipnet-trie 0.3 Dual-stack archive records: - UpdateRecordInput/PeerStateRecordInput peer/local IP -> IpAddr - SnapshotRoute.prefix -> IpNet with path_id: Option Raw-frame passthrough: - encode_bgp4mp_raw_as4 writes the original BGP UPDATE frame verbatim in a BGP4MP_MESSAGE_AS4 envelope; ingest_update uses it instead of parse-then-reencode (wire fidelity preserved, unknown attributes retained) - round-trip tests for v4, v6, and unparseable frames TABLE_DUMP_V2: - v4 + v6 RIB entries grouped per (family, prefix) into one RibAfiEntries record, entries sorted by peer index, snapshot-global sequence numbers, ADD-PATH subtypes when path_id is present Event-time vs seal-time (review blocker 3): - ingest paths no longer rotate writers from record timestamps; rotation is driven by the ingestion-clock tick only; late/zero timestamps stay in the current segment with event time preserved in the MRT header (regression tests) No empty RIB before baseline (review major 16): - tick/rollover skip snapshot when no routes exist Path hardening (review major 13): - collector_id regex ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ at config load - custom templates reject absolute/backslash/control/empty/'..' components; post-render containment assertion --- Cargo.lock | 249 +++----------------- Cargo.toml | 5 +- src/archive/layout.rs | 14 +- src/archive/mod.rs | 132 ++++++++++- src/archive/snapshot.rs | 436 +++++++++++++++++++++++++---------- src/archive/types.rs | 15 +- src/bgp/mod.rs | 12 +- src/config/mod.rs | 94 +++++++- tests/archive_integration.rs | 6 +- 9 files changed, 592 insertions(+), 371 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0b843f0..008b455 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -100,39 +100,12 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" -[[package]] -name = "async-trait" -version = "0.1.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "attohttpc" -version = "0.30.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16e2cdb6d5ed835199484bb92bb8b3edd526effe995c61732580439c1a67e2e9" -dependencies = [ - "base64", - "http 1.4.0", - "log", - "rustls 0.23.36", - "serde", - "serde_json", - "url", - "webpki-roots", -] - [[package]] name = "autocfg" version = "1.5.0" @@ -181,23 +154,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "aws-creds" -version = "0.39.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3b85155d265df828f84e53886ed9e427aed979dd8a39f5b8b2162c77e142d7" -dependencies = [ - "attohttpc", - "home", - "log", - "quick-xml", - "rust-ini", - "serde", - "thiserror", - "time", - "url", -] - [[package]] name = "aws-lc-rs" version = "1.16.0" @@ -220,15 +176,6 @@ dependencies = [ "fs_extra", ] -[[package]] -name = "aws-region" -version = "0.28.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "838b36c8dc927b6db1b6c6b8f5d05865f2213550b9e83bf92fa99ed6525472c0" -dependencies = [ - "thiserror", -] - [[package]] name = "aws-runtime" version = "1.7.1" @@ -637,9 +584,9 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bgpkit-parser" -version = "0.15.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c455bf7b26d83d961eb633c815b64f466b5bc349f33d014f3b6a8cdf113e9406" +checksum = "7c58fcccfe233d986f01f79d34af0dc17fb29174b8d3ca0af72436f2a08af9e0" dependencies = [ "bitflags", "bytes", @@ -650,6 +597,8 @@ dependencies = [ "num_enum", "oneio", "regex", + "smallvec", + "zerocopy", ] [[package]] @@ -692,16 +641,6 @@ dependencies = [ "either", ] -[[package]] -name = "bzip2" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8" -dependencies = [ - "bzip2-sys", - "libc", -] - [[package]] name = "bzip2" version = "0.6.1" @@ -711,16 +650,6 @@ dependencies = [ "libbz2-rs-sys", ] -[[package]] -name = "bzip2-sys" -version = "0.1.13+1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14" -dependencies = [ - "cc", - "pkg-config", -] - [[package]] name = "cc" version = "1.2.56" @@ -820,26 +749,6 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" -[[package]] -name = "const-random" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" -dependencies = [ - "const-random-macro", -] - -[[package]] -name = "const-random-macro" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" -dependencies = [ - "getrandom 0.2.17", - "once_cell", - "tiny-keccak", -] - [[package]] name = "core-foundation" version = "0.10.1" @@ -901,12 +810,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - [[package]] name = "crypto-bigint" version = "0.4.9" @@ -956,7 +859,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc3dc5ad92c2e2d1c193bbbbdf2ea477cb81331de4f3103f267ca18368b988c4" dependencies = [ "powerfmt", - "serde_core", ] [[package]] @@ -981,15 +883,6 @@ dependencies = [ "syn", ] -[[package]] -name = "dlv-list" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f" -dependencies = [ - "const-random", -] - [[package]] name = "dotenvy" version = "0.15.7" @@ -1126,12 +1019,13 @@ dependencies = [ "aws-types", "bgpkit-parser", "bytes", - "bzip2 0.4.4", + "bzip2", "chrono", "clap", "flate2", "hex", "ipnet", + "ipnet-trie", "libc", "rusqlite", "serde", @@ -1406,15 +1300,6 @@ dependencies = [ "digest", ] -[[package]] -name = "home" -version = "0.5.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "http" version = "0.2.12" @@ -1737,6 +1622,16 @@ dependencies = [ "serde", ] +[[package]] +name = "ipnet-trie" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cb57916213e04ad56f36e59f27cf13a874615dcf7e6f0a7a5708581cc84080d" +dependencies = [ + "ipnet", + "prefix-trie", +] + [[package]] name = "iri-string" version = "0.7.10" @@ -1755,9 +1650,9 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itertools" -version = "0.14.0" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" dependencies = [ "either", ] @@ -1888,17 +1783,6 @@ dependencies = [ "regex-automata", ] -[[package]] -name = "maybe-async" -version = "0.2.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cf92c10c7e361d6b99666ec1c6f9805b0bea2c3bd8c78dc6fe98ac5bd78db11" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "md-5" version = "0.10.6" @@ -1909,12 +1793,6 @@ dependencies = [ "digest", ] -[[package]] -name = "md5" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae960838283323069879657ca3de837e9f7bbb4c7bf6ea7f1b290d5e9476d2e0" - [[package]] name = "memchr" version = "2.8.0" @@ -2017,18 +1895,18 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "oneio" -version = "0.20.1" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b53f79440306d238c1ed58558d7050a6c4a323bc9bb43cdddbfbd0dc271b8266" +checksum = "4c4968f8ba9447244a5297118fa1e1c9753bb4fd09d3069fdce188fde0db4f9a" dependencies = [ - "bzip2 0.6.1", + "bzip2", "dotenvy", "flate2", "reqwest", - "rust-s3", "rustls 0.23.36", "suppaftp", "thiserror", + "zstd", ] [[package]] @@ -2037,16 +1915,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "ordered-multimap" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79" -dependencies = [ - "dlv-list", - "hashbrown 0.14.5", -] - [[package]] name = "outref" version = "0.5.2" @@ -2128,6 +1996,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prefix-trie" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb5f930995ba4986bd239ba8d8fded67cad82d1db329c4f316f312847cba16aa" +dependencies = [ + "ipnet", + "num-traits", +] + [[package]] name = "prettyplease" version = "0.2.37" @@ -2156,16 +2034,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "quick-xml" -version = "0.38.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "quinn" version = "0.11.9" @@ -2394,46 +2262,6 @@ dependencies = [ "smallvec", ] -[[package]] -name = "rust-ini" -version = "0.21.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7" -dependencies = [ - "cfg-if", - "ordered-multimap", -] - -[[package]] -name = "rust-s3" -version = "0.37.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4af74047374528b627109d579ce86b23ccf6ffba7ff363c807126c1aff69e1bb" -dependencies = [ - "async-trait", - "attohttpc", - "aws-creds", - "aws-region", - "base64", - "bytes", - "cfg-if", - "hex", - "hmac", - "http 1.4.0", - "log", - "maybe-async", - "md5", - "percent-encoding", - "quick-xml", - "serde", - "serde_derive", - "serde_json", - "sha2", - "thiserror", - "time", - "url", -] - [[package]] name = "rustc-hash" version = "2.1.1" @@ -2755,6 +2583,9 @@ name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] [[package]] name = "socket2" @@ -2904,7 +2735,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", - "itoa", "num-conv", "powerfmt", "serde_core", @@ -2928,15 +2758,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - [[package]] name = "tinystr" version = "0.8.2" diff --git a/Cargo.toml b/Cargo.toml index 12bbdb6..4e4b84f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,14 +29,15 @@ libc = "0.2" aws-config = "1" aws-sdk-s3 = "1" aws-types = "1" -bgpkit-parser = "0.15" +bgpkit-parser = "0.20" bytes = "1" clap = { version = "4", features = ["derive"] } flate2 = "1" -bzip2 = "0.4" +bzip2 = "0.6" chrono = { version = "0.4", features = ["clock", "serde"] } hex = "0.4" ipnet = { version = "2", features = ["serde"] } +ipnet-trie = "0.3" rusqlite = { version = "0.32", features = ["bundled"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/src/archive/layout.rs b/src/archive/layout.rs index 430df04..7fe2ab3 100644 --- a/src/archive/layout.rs +++ b/src/archive/layout.rs @@ -1,4 +1,4 @@ -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; use anyhow::{bail, Result}; use chrono::{Datelike, TimeZone, Timelike, Utc}; @@ -110,6 +110,7 @@ fn build_custom_relative_path( minute: u32, ext: &str, ) -> Result { + crate::config::validate_relative_template(template)?; if !template.contains("{collector}") || !template.contains("{yyyymmdd}") || !template.contains("{hhmm}") @@ -142,6 +143,17 @@ fn build_custom_relative_path( path.set_file_name(format!("{}.{}", file_name, ext)); } + if path.is_absolute() + || path.components().any(|component| { + matches!( + component, + Component::ParentDir | Component::RootDir | Component::Prefix(_) + ) + }) + { + bail!("custom template rendered an unsafe path"); + } + Ok(path) } diff --git a/src/archive/mod.rs b/src/archive/mod.rs index 2db930d..2853d2f 100644 --- a/src/archive/mod.rs +++ b/src/archive/mod.rs @@ -17,7 +17,7 @@ use tokio::sync::{broadcast, Mutex}; use crate::archive::layout::{aligned_epoch, segment_paths}; use crate::archive::replicator::Replicator; use crate::archive::snapshot::{ - build_table_dump_v2, encode_bgp4mp_message_as4, encode_bgp4mp_state_change_as4, + build_table_dump_v2, encode_bgp4mp_raw_as4, encode_bgp4mp_state_change_as4, }; use crate::archive::types::{ ArchiveStatus, ArchiveStream, FinalizedSegment, PeerStateRecordInput, RibSnapshotInput, @@ -116,9 +116,9 @@ impl ArchiveService { return Ok(()); } - self.ensure_updates_writer(update.timestamp).await?; - - let record = encode_bgp4mp_message_as4(&update)?; + // Segment selection is driven exclusively by the ingestion-clock tick. + // Event timestamps are preserved in MRT records, never used to reopen buckets. + let record = encode_bgp4mp_raw_as4(&update)?; let mut writer_guard = self.updates_writer.lock().await; let writer = writer_guard .as_mut() @@ -133,8 +133,7 @@ impl ArchiveService { return Ok(()); } - self.ensure_updates_writer(state.timestamp).await?; - + // State events follow the same ingestion-clock segment discipline as updates. let record = encode_bgp4mp_state_change_as4(&state)?; let mut writer_guard = self.updates_writer.lock().await; let writer = writer_guard @@ -211,7 +210,11 @@ impl ArchiveService { peers: vec![], routes: vec![], }; - self.snapshot_now(snapshot).await?; + if snapshot.routes.is_empty() { + tracing::debug!("skipping RIB rollover because no baseline routes exist"); + } else { + self.snapshot_now(snapshot).await?; + } } } @@ -292,8 +295,12 @@ impl ArchiveService { peers: vec![], routes: vec![], }; - self.snapshot_now(snapshot).await?; - *last_rib = Some(rib_bucket); + if snapshot.routes.is_empty() { + tracing::debug!("skipping RIB snapshot because no baseline routes exist"); + } else { + self.snapshot_now(snapshot).await?; + *last_rib = Some(rib_bucket); + } } Ok(()) @@ -379,3 +386,110 @@ fn cleanup_tmp_root(tmp_root: &std::path::Path) -> Result<()> { Ok(()) } + +#[cfg(test)] +mod tests { + use std::fs::File; + use std::io::{Cursor, Read}; + use std::net::{IpAddr, Ipv4Addr}; + + use anyhow::{Context, Result}; + use bgpkit_parser::parse_mrt_record; + use chrono::Utc; + use flate2::read::GzDecoder; + + use super::*; + use crate::archive::types::UpdateRecordInput; + use crate::config::ArchiveConfig; + + #[tokio::test] + async fn late_and_zero_timestamp_updates_stay_in_current_writer() -> Result<()> { + let temp = tempfile::tempdir()?; + let root = temp.path().join("archive"); + let cfg = ArchiveConfig { + enabled: true, + root: root.clone(), + tmp_root: root.join(".tmp"), + ..ArchiveConfig::default() + }; + let service = ArchiveService::new(cfg, Ipv4Addr::new(192, 0, 2, 1)).await?; + let initial = service + .status() + .await? + .updates_open_path + .context("writer should open at service initialization")?; + + let late_timestamp = Utc::now().timestamp() - 7_200; + service.ingest_update(test_update(late_timestamp)).await?; + service.ingest_update(test_update(0)).await?; + + let status = service.status().await?; + assert_eq!(status.updates_open_path, Some(initial)); + assert_eq!(status.updates_record_count, 2); + + service.rollover(ArchiveStream::Updates).await?; + let segment = walkdir::WalkDir::new(&root) + .into_iter() + .filter_map(Result::ok) + .find_map(|entry| { + (entry.file_type().is_file() + && entry + .path() + .extension() + .is_some_and(|extension| extension == "gz")) + .then(|| entry.path().to_path_buf()) + }) + .context("rollover should finalize a gzip updates segment")?; + let mut decoded = Vec::new(); + GzDecoder::new(File::open(segment)?).read_to_end(&mut decoded)?; + let mut cursor = Cursor::new(decoded); + let first = parse_mrt_record(&mut cursor)?; + let second = parse_mrt_record(&mut cursor)?; + assert_eq!(first.common_header.timestamp, late_timestamp as u32); + assert_eq!(second.common_header.timestamp, 0); + Ok(()) + } + + #[tokio::test] + async fn tick_with_no_routes_writes_no_rib_file() -> Result<()> { + let temp = tempfile::tempdir()?; + let root = temp.path().join("archive"); + let cfg = ArchiveConfig { + enabled: true, + root: root.clone(), + tmp_root: root.join(".tmp"), + ..ArchiveConfig::default() + }; + let service = ArchiveService::new(cfg, Ipv4Addr::new(192, 0, 2, 1)).await?; + service.tick().await?; + + let status = service.status().await?; + assert!(status.ribs_last_path.is_none()); + assert!(!walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + .any(|entry| { + entry.file_type().is_file() + && entry.file_name().to_string_lossy().starts_with("rib.") + })); + Ok(()) + } + + fn test_update(timestamp: i64) -> UpdateRecordInput { + let mut message = vec![0xff; 16]; + message.extend_from_slice(&24_u16.to_be_bytes()); + message.push(2); + message.extend_from_slice(&1_u16.to_be_bytes()); + message.push(0); + message.extend_from_slice(&0_u16.to_be_bytes()); + UpdateRecordInput { + timestamp, + peer_asn: 64_512, + local_asn: 64_513, + interface_index: 0, + peer_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + local_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)), + bgp_message: message, + } + } +} diff --git a/src/archive/snapshot.rs b/src/archive/snapshot.rs index 5fd9153..6243867 100644 --- a/src/archive/snapshot.rs +++ b/src/archive/snapshot.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::net::IpAddr; use anyhow::{anyhow, bail, Context, Result}; @@ -10,11 +10,17 @@ use bgpkit_parser::models::{ use bgpkit_parser::parser::bgp::attributes::parse_attributes; use bgpkit_parser::parser::bgp::parse_bgp_message; use bytes::Bytes; -use ipnet::{IpNet, Ipv4Net}; +use ipnet::IpNet; use crate::archive::types::{PeerStateRecordInput, RibSnapshotInput, UpdateRecordInput}; +/// Encodes an UPDATE through bgpkit-parser's model encoder. This remains available +/// for callers that need a validated, canonical MRT record, but it is not the +/// archive path because model encoding cannot preserve the original wire frame. pub fn encode_bgp4mp_message_as4(input: &UpdateRecordInput) -> Result> { + if input.peer_ip.is_ipv4() != input.local_ip.is_ipv4() { + bail!("BGP4MP peer and local IP addresses must use the same family"); + } let bgp_message = parse_update_message(&input.bgp_message)?; let msg = Bgp4MpMessage { @@ -22,18 +28,50 @@ pub fn encode_bgp4mp_message_as4(input: &UpdateRecordInput) -> Result> { peer_asn: Asn::new_32bit(input.peer_asn), local_asn: Asn::new_32bit(input.local_asn), interface_index: input.interface_index, - peer_ip: IpAddr::V4(input.peer_ip), - local_ip: IpAddr::V4(input.local_ip), + peer_ip: input.peer_ip, + local_ip: input.local_ip, bgp_message, }; let message = MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(msg)); - Ok(encode_mrt_message( + encode_mrt_message( input.timestamp as u32, EntryType::BGP4MP, Bgp4MpType::MessageAs4 as u16, message, - )) + ) +} + +/// Builds a BGP4MP_MESSAGE_AS4 envelope without parsing or re-encoding the +/// embedded BGP UPDATE. The archive always uses this path so malformed yet +/// archivable frames retain their exact original bytes. +pub fn encode_bgp4mp_raw_as4(input: &UpdateRecordInput) -> Result> { + let (address_family, peer_address, local_address) = match (input.peer_ip, input.local_ip) { + (IpAddr::V4(peer), IpAddr::V4(local)) => { + (1_u16, peer.octets().to_vec(), local.octets().to_vec()) + } + (IpAddr::V6(peer), IpAddr::V6(local)) => { + (2_u16, peer.octets().to_vec(), local.octets().to_vec()) + } + _ => bail!("BGP4MP peer and local IP addresses must use the same family"), + }; + + let mut payload = + Vec::with_capacity(12 + peer_address.len() + local_address.len() + input.bgp_message.len()); + payload.extend_from_slice(&input.peer_asn.to_be_bytes()); + payload.extend_from_slice(&input.local_asn.to_be_bytes()); + payload.extend_from_slice(&input.interface_index.to_be_bytes()); + payload.extend_from_slice(&address_family.to_be_bytes()); + payload.extend_from_slice(&peer_address); + payload.extend_from_slice(&local_address); + payload.extend_from_slice(&input.bgp_message); + + encode_common_header( + input.timestamp as u32, + EntryType::BGP4MP, + Bgp4MpType::MessageAs4 as u16, + payload, + ) } pub fn encode_bgp4mp_state_change_as4(input: &PeerStateRecordInput) -> Result> { @@ -42,29 +80,32 @@ pub fn encode_bgp4mp_state_change_as4(input: &PeerStateRecordInput) -> Result Result>> { let mut records = Vec::with_capacity(1 + snapshot.routes.len()); - let peer_index_table = build_peer_index_table(snapshot)?; records.push(encode_mrt_message( snapshot.timestamp as u32, @@ -73,13 +114,11 @@ pub fn build_table_dump_v2(snapshot: &RibSnapshotInput) -> Result>> MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable( peer_index_table.clone(), )), - )); + )?); + let mut grouped_routes: BTreeMap<(u8, Vec, u8), (IpNet, Vec<&_>)> = BTreeMap::new(); for route in &snapshot.routes { - if route.prefix_len > 32 { - bail!("invalid IPv4 prefix length {}", route.prefix_len); - } - + validate_route_prefix(route.prefix)?; if !peer_index_table.id_peer_map.contains_key(&route.peer_index) { bail!( "route references unknown peer_index {} (peers: {})", @@ -88,46 +127,96 @@ pub fn build_table_dump_v2(snapshot: &RibSnapshotInput) -> Result>> ); } - let ipv4_prefix = Ipv4Net::new(route.prefix, route.prefix_len).with_context(|| { - format!("invalid route prefix {}/{}", route.prefix, route.prefix_len) - })?; - let prefix = NetworkPrefix::new(IpNet::V4(ipv4_prefix), None); - - let attributes = parse_attributes( - Bytes::from(route.path_attributes.clone()), - &AsnLength::Bits32, - false, - None, - None, - None, - ) - .with_context(|| format!("failed parsing route attributes for prefix {}", ipv4_prefix))?; - - let rib_entry = RibEntry { - peer_index: route.peer_index, - originated_time: route.originated_time, - path_id: None, - attributes, - }; + let key = prefix_sort_key(route.prefix); + grouped_routes + .entry(key) + .or_insert_with(|| (route.prefix, Vec::new())) + .1 + .push(route); + } + + let mut sequence_number = 0_u32; + for (_, (prefix_net, mut routes)) in grouped_routes { + routes.sort_by_key(|route| route.peer_index); + let uses_add_path = routes.iter().any(|route| route.path_id.is_some()); + if uses_add_path && routes.iter().any(|route| route.path_id.is_none()) { + bail!("all entries for an ADD-PATH RIB prefix must provide path_id"); + } + + let rib_type = rib_type_for_prefix(prefix_net, uses_add_path); + let prefix = NetworkPrefix::new(prefix_net, None); + let rib_entries = routes + .into_iter() + .map(|route| { + let attributes = parse_attributes( + Bytes::from(route.path_attributes.clone()), + &AsnLength::Bits32, + uses_add_path, + None, + None, + None, + ) + .with_context(|| { + format!( + "failed parsing route attributes for prefix {}", + route.prefix + ) + })?; + Ok(RibEntry { + peer_index: route.peer_index, + originated_time: route.originated_time, + path_id: route.path_id, + attributes, + }) + }) + .collect::>>()?; let rib = RibAfiEntries { - rib_type: TableDumpV2Type::RibIpv4Unicast, - sequence_number: route.sequence, + rib_type, + sequence_number, prefix, - rib_entries: vec![rib_entry], + rib_entries, }; - + sequence_number = sequence_number.wrapping_add(1); records.push(encode_mrt_message( snapshot.timestamp as u32, EntryType::TABLE_DUMP_V2, - TableDumpV2Type::RibIpv4Unicast as u16, + rib_type as u16, MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(rib)), - )); + )?); } Ok(records) } +fn validate_route_prefix(prefix: IpNet) -> Result<()> { + let valid = match prefix { + IpNet::V4(network) => network.prefix_len() <= 32, + IpNet::V6(network) => network.prefix_len() <= 128, + }; + if valid { + Ok(()) + } else { + bail!("invalid prefix length for {prefix}") + } +} + +fn prefix_sort_key(prefix: IpNet) -> (u8, Vec, u8) { + match prefix { + IpNet::V4(network) => (4, network.network().octets().to_vec(), network.prefix_len()), + IpNet::V6(network) => (6, network.network().octets().to_vec(), network.prefix_len()), + } +} + +fn rib_type_for_prefix(prefix: IpNet, uses_add_path: bool) -> TableDumpV2Type { + match (prefix, uses_add_path) { + (IpNet::V4(_), false) => TableDumpV2Type::RibIpv4Unicast, + (IpNet::V4(_), true) => TableDumpV2Type::RibIpv4UnicastAddPath, + (IpNet::V6(_), false) => TableDumpV2Type::RibIpv6Unicast, + (IpNet::V6(_), true) => TableDumpV2Type::RibIpv6UnicastAddPath, + } +} + fn build_peer_index_table(snapshot: &RibSnapshotInput) -> Result { if snapshot.peers.len() > u16::MAX as usize { bail!("peer count exceeds TABLE_DUMP_V2 limit"); @@ -135,7 +224,6 @@ fn build_peer_index_table(snapshot: &RibSnapshotInput) -> Result let mut id_peer_map = HashMap::new(); let mut peer_ip_id_map = HashMap::new(); - for (idx, peer) in snapshot.peers.iter().enumerate() { let peer_id = idx as u16; let parsed_peer = Peer::new( @@ -143,7 +231,6 @@ fn build_peer_index_table(snapshot: &RibSnapshotInput) -> Result peer.peer_ip, Asn::new_32bit(peer.peer_asn), ); - id_peer_map.insert(peer_id, parsed_peer); peer_ip_id_map.insert(parsed_peer.peer_ip, peer_id); } @@ -163,15 +250,13 @@ fn parse_update_message(raw: &[u8]) -> Result { let mut fallback = Bytes::copy_from_slice(raw); parse_bgp_message(&mut fallback, false, &AsnLength::Bits16) }) - .map_err(|e| anyhow!("failed to parse BGP message with bgpkit-parser: {e}"))?; - + .map_err(|error| anyhow!("failed to parse BGP message with bgpkit-parser: {error}"))?; if !matches!(parsed, BgpMessage::Update(_)) { bail!( "expected BGP UPDATE message payload, got {:?}", parsed.msg_type() ); } - Ok(parsed) } @@ -180,128 +265,239 @@ fn encode_mrt_message( entry_type: EntryType, subtype: u16, message: MrtMessage, -) -> Vec { - let payload = message.encode(subtype); +) -> Result> { + let payload = message + .encode(subtype) + .map_err(|error| anyhow!("failed encoding MRT message: {error}"))?; + encode_common_header(timestamp, entry_type, subtype, payload.to_vec()) +} + +fn encode_common_header( + timestamp: u32, + entry_type: EntryType, + subtype: u16, + payload: Vec, +) -> Result> { + let length = u32::try_from(payload.len()).context("MRT payload exceeds u32 length")?; let header = CommonHeader { timestamp, microsecond_timestamp: None, entry_type, entry_subtype: subtype, - length: payload.len() as u32, + length, }; - let header_bytes = header.encode(); - let mut out = Vec::with_capacity(header_bytes.len() + payload.len()); - out.extend_from_slice(header_bytes.as_ref()); - out.extend_from_slice(payload.as_ref()); - out + out.extend_from_slice(&header_bytes); + out.extend_from_slice(&payload); + Ok(out) } #[cfg(test)] mod tests { use std::io::Cursor; - use std::net::{IpAddr, Ipv4Addr}; + use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; - use bgpkit_parser::models::{Bgp4MpType, EntryType}; + use bgpkit_parser::models::{ + Bgp4MpType, EntryType, MrtMessage, TableDumpV2Message, TableDumpV2Type, + }; use bgpkit_parser::parse_mrt_record; use super::*; use crate::archive::types::{RibSnapshotInput, SnapshotPeer, SnapshotRoute, UpdateRecordInput}; #[test] - fn encodes_bgp4mp_update_record_with_bgpkit_models() { - let input = UpdateRecordInput { - timestamp: 1_700_000_000, - peer_asn: 64496, - local_asn: 64497, - interface_index: 0, - peer_ip: Ipv4Addr::new(198, 51, 100, 1), - local_ip: Ipv4Addr::new(198, 51, 100, 2), - bgp_message: valid_update_withdraw_message(), - }; + fn raw_bgp4mp_v4_round_trips_original_frame() -> Result<()> { + let input = update_input( + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)), + ); + assert_raw_bgp4mp_round_trip(&input) + } - let bytes = encode_bgp4mp_message_as4(&input).expect("update encoding should succeed"); + #[test] + fn raw_bgp4mp_v6_round_trips_original_frame_and_addresses() -> Result<()> { + let input = update_input( + IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)), + IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2)), + ); + assert_raw_bgp4mp_round_trip(&input) + } - let mut cursor = Cursor::new(bytes); - let parsed = parse_mrt_record(&mut cursor).expect("record should parse"); - assert_eq!(parsed.common_header.entry_type, EntryType::BGP4MP); + #[test] + fn raw_bgp4mp_preserves_unparseable_frame_bytes() -> Result<()> { + let mut input = update_input( + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)), + ); + input.bgp_message = vec![0x01, 0x02, 0x03, 0x04]; + + let bytes = encode_bgp4mp_raw_as4(&input)?; + assert_eq!(&bytes[32..], input.bgp_message.as_slice()); + Ok(()) + } + + #[test] + fn parsed_encoder_remains_available_for_valid_updates() -> Result<()> { + let input = update_input( + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)), + ); + let bytes = encode_bgp4mp_message_as4(&input)?; + let parsed = parse_mrt_record(&mut Cursor::new(bytes))?; assert_eq!( parsed.common_header.entry_subtype, Bgp4MpType::MessageAs4 as u16 ); + Ok(()) } #[test] - fn encodes_bgp4mp_state_change_record_with_bgpkit_models() { + fn state_change_encoder_supports_ipv6_envelopes() -> Result<()> { let input = PeerStateRecordInput { timestamp: 1_700_000_000, - peer_asn: 64496, - local_asn: 64497, - interface_index: 0, - peer_ip: Ipv4Addr::new(198, 51, 100, 1), - local_ip: Ipv4Addr::new(198, 51, 100, 2), - old_state: 3, - new_state: 6, + peer_asn: 64_496, + local_asn: 64_497, + interface_index: 7, + peer_ip: IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)), + local_ip: IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2)), + old_state: BgpState::OpenConfirm as u16, + new_state: BgpState::Established as u16, }; - let bytes = encode_bgp4mp_state_change_as4(&input).expect("state change encoding"); - let mut cursor = Cursor::new(bytes); - let parsed = parse_mrt_record(&mut cursor).expect("record should parse"); - assert_eq!(parsed.common_header.entry_type, EntryType::BGP4MP); - assert_eq!( - parsed.common_header.entry_subtype, - Bgp4MpType::StateChangeAs4 as u16 - ); + let bytes = encode_bgp4mp_state_change_as4(&input)?; + let parsed = parse_mrt_record(&mut Cursor::new(bytes))?; + match parsed.message { + MrtMessage::Bgp4Mp(Bgp4MpEnum::StateChange(state)) => { + assert_eq!(state.peer_ip, input.peer_ip); + assert_eq!(state.local_addr, input.local_ip); + } + message => bail!("unexpected MRT message: {message:?}"), + } + Ok(()) } #[test] - fn builds_table_dump_v2_records() { + fn groups_dual_stack_and_add_path_rib_entries() -> Result<()> { let snapshot = RibSnapshotInput { timestamp: 1_700_000_000, collector_bgp_id: Ipv4Addr::new(192, 0, 2, 1), view_name: "main".to_string(), - peers: vec![SnapshotPeer { - peer_bgp_id: Ipv4Addr::new(198, 51, 100, 1), - peer_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), - peer_asn: 64_512, - }], - routes: vec![SnapshotRoute { - sequence: 1, - prefix: Ipv4Addr::new(203, 0, 113, 0), - prefix_len: 24, - peer_index: 0, - originated_time: 1_700_000_000, - path_attributes: vec![], - }], + peers: vec![ + SnapshotPeer { + peer_bgp_id: Ipv4Addr::new(198, 51, 100, 1), + peer_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + peer_asn: 64_512, + }, + SnapshotPeer { + peer_bgp_id: Ipv4Addr::new(198, 51, 100, 2), + peer_ip: IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2)), + peer_asn: 64_513, + }, + ], + routes: vec![ + SnapshotRoute { + prefix: "203.0.113.0/24".parse()?, + peer_index: 1, + originated_time: 1_700_000_001, + path_id: None, + path_attributes: vec![], + }, + SnapshotRoute { + prefix: "203.0.113.0/24".parse()?, + peer_index: 0, + originated_time: 1_700_000_000, + path_id: None, + path_attributes: vec![], + }, + SnapshotRoute { + prefix: "2001:db8:1::/48".parse()?, + peer_index: 1, + originated_time: 1_700_000_002, + path_id: Some(99), + path_attributes: vec![], + }, + ], }; - let records = build_table_dump_v2(&snapshot).expect("table dump should be built"); - assert_eq!(records.len(), 2); + let records = build_table_dump_v2(&snapshot)?; + assert_eq!(records.len(), 3); + let peer_index = parse_mrt_record(&mut Cursor::new(&records[0]))?; + assert!(matches!( + peer_index.message, + MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(_)) + )); - let mut first = Cursor::new(records[0].clone()); - let first_record = parse_mrt_record(&mut first).expect("peer index should parse"); - assert_eq!( - first_record.common_header.entry_type, - EntryType::TABLE_DUMP_V2 - ); + let v4 = parse_rib_record(&records[1])?; + assert_eq!(v4.rib_type, TableDumpV2Type::RibIpv4Unicast); + assert_eq!(v4.sequence_number, 0); + assert_eq!(v4.rib_entries.len(), 2); + assert_eq!(v4.rib_entries[0].peer_index, 0); + assert_eq!(v4.rib_entries[1].peer_index, 1); + + let v6 = parse_rib_record(&records[2])?; + assert_eq!(v6.rib_type, TableDumpV2Type::RibIpv6UnicastAddPath); + assert_eq!(v6.sequence_number, 1); + assert_eq!(v6.rib_entries.len(), 1); + assert_eq!(v6.rib_entries[0].peer_index, 1); + assert_eq!(v6.rib_entries[0].path_id, Some(99)); + Ok(()) + } + + fn update_input(peer_ip: IpAddr, local_ip: IpAddr) -> UpdateRecordInput { + UpdateRecordInput { + timestamp: 1_700_000_000, + peer_asn: 64496, + local_asn: 64497, + interface_index: 7, + peer_ip, + local_ip, + bgp_message: valid_update_withdraw_message(), + } + } - let mut second = Cursor::new(records[1].clone()); - let second_record = parse_mrt_record(&mut second).expect("rib entry should parse"); + fn assert_raw_bgp4mp_round_trip(input: &UpdateRecordInput) -> Result<()> { + let bytes = encode_bgp4mp_raw_as4(input)?; + let parsed = parse_mrt_record(&mut Cursor::new(&bytes))?; + assert_eq!(parsed.common_header.entry_type, EntryType::BGP4MP); assert_eq!( - second_record.common_header.entry_type, - EntryType::TABLE_DUMP_V2 + parsed.common_header.entry_subtype, + Bgp4MpType::MessageAs4 as u16 ); + match parsed.message { + MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(message)) => { + assert_eq!(message.peer_ip, input.peer_ip); + assert_eq!(message.local_ip, input.local_ip); + let decoded = message + .bgp_message + .encode(AsnLength::Bits32) + .map_err(|error| anyhow!("failed re-encoding parsed BGP message: {error}"))?; + assert_eq!(decoded.as_ref(), input.bgp_message.as_slice()); + } + message => panic!("unexpected MRT message: {message:?}"), + } + + let address_len = if input.peer_ip.is_ipv4() { 4 } else { 16 }; + let frame_start = 12 + 12 + 2 * address_len; + assert_eq!(&bytes[frame_start..], input.bgp_message.as_slice()); + Ok(()) + } + + fn parse_rib_record(bytes: &[u8]) -> Result { + let record = parse_mrt_record(&mut Cursor::new(bytes))?; + match record.message { + MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(rib)) => Ok(rib), + message => bail!("unexpected MRT message: {message:?}"), + } } fn valid_update_withdraw_message() -> Vec { let mut msg = vec![0xff; 16]; - // total length 24 bytes: 19-byte header + 5-byte payload - msg.extend_from_slice(&24u16.to_be_bytes()); - msg.push(2); // UPDATE - msg.extend_from_slice(&1u16.to_be_bytes()); // withdrawn routes length - msg.push(0); // withdraw 0.0.0.0/0 - msg.extend_from_slice(&0u16.to_be_bytes()); // path attributes length + msg.extend_from_slice(&24_u16.to_be_bytes()); + msg.push(2); + msg.extend_from_slice(&1_u16.to_be_bytes()); + msg.push(0); + msg.extend_from_slice(&0_u16.to_be_bytes()); msg } } diff --git a/src/archive/types.rs b/src/archive/types.rs index 1609ea6..797463d 100644 --- a/src/archive/types.rs +++ b/src/archive/types.rs @@ -1,6 +1,7 @@ use std::net::{IpAddr, Ipv4Addr}; use std::path::PathBuf; +use ipnet::IpNet; use serde::{Deserialize, Serialize}; use crate::config::CompressionKind; @@ -47,8 +48,9 @@ pub struct UpdateRecordInput { pub peer_asn: u32, pub local_asn: u32, pub interface_index: u16, - pub peer_ip: Ipv4Addr, - pub local_ip: Ipv4Addr, + pub peer_ip: IpAddr, + pub local_ip: IpAddr, + /// The complete on-the-wire BGP message, including its 19-byte header. pub bgp_message: Vec, } @@ -58,8 +60,8 @@ pub struct PeerStateRecordInput { pub peer_asn: u32, pub local_asn: u32, pub interface_index: u16, - pub peer_ip: Ipv4Addr, - pub local_ip: Ipv4Addr, + pub peer_ip: IpAddr, + pub local_ip: IpAddr, pub old_state: u16, pub new_state: u16, } @@ -73,11 +75,10 @@ pub struct SnapshotPeer { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SnapshotRoute { - pub sequence: u32, - pub prefix: Ipv4Addr, - pub prefix_len: u8, + pub prefix: IpNet, pub peer_index: u16, pub originated_time: u32, + pub path_id: Option, pub path_attributes: Vec, } diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 9e6d468..a508de7 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -238,7 +238,7 @@ impl BgpService { version: 4, asn: local_as.into(), hold_time, - sender_ip: self.inner.router_id, + bgp_identifier: self.inner.router_id, extended_length: false, opt_params: vec![], }); @@ -287,7 +287,10 @@ impl BgpService { ); match timeout(timeout_dur, read_bgp_message(stream)).await { Ok(Ok(msg)) => match msg { - BgpMessage::KeepAlive | BgpMessage::Update(_) | BgpMessage::Open(_) => { + BgpMessage::KeepAlive + | BgpMessage::Update(_) + | BgpMessage::Open(_) + | BgpMessage::RouteRefresh(_) => { hold_deadline = Instant::now() + negotiated_hold; } BgpMessage::Notification(_) => { @@ -493,7 +496,10 @@ fn normalize_socket_addr(raw: &str, default_port: u16) -> Result { } async fn write_bgp_message(stream: &mut TcpStream, msg: &BgpMessage) -> Result<()> { - let mut bytes = msg.encode(AsnLength::Bits32).to_vec(); + let mut bytes = msg + .encode(AsnLength::Bits32) + .map_err(|error| anyhow!("failed encoding BGP message: {error}"))? + .to_vec(); if bytes.len() < 19 { return Err(anyhow!("encoded BGP message too short")); } diff --git a/src/config/mod.rs b/src/config/mod.rs index 2daa15c..a0cea0b 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -221,12 +221,17 @@ impl Default for ArchiveConfig { impl ArchiveConfig { pub fn validate(&self) -> Result<()> { - if !self.enabled { - return Ok(()); + validate_collector_id(&self.collector_id)?; + if self.layout_profile == LayoutProfile::Custom { + let templates = self + .custom_templates + .as_ref() + .context("[archive].layout_profile=custom requires [archive.custom_templates]")?; + templates.validate()?; } - if self.collector_id.trim().is_empty() { - bail!("[archive].collector_id must not be empty"); + if !self.enabled { + return Ok(()); } if self.updates_interval_secs == 0 || 3600 % self.updates_interval_secs != 0 { @@ -260,14 +265,6 @@ impl ArchiveConfig { bail!("[archive].destinations must include at least one mode=primary destination"); } - if self.layout_profile == LayoutProfile::Custom { - let templates = self - .custom_templates - .as_ref() - .context("[archive].layout_profile=custom requires [archive.custom_templates]")?; - templates.validate()?; - } - for destination in &self.destinations { destination.validate()?; } @@ -316,6 +313,9 @@ pub struct CustomLayoutTemplates { impl CustomLayoutTemplates { pub fn validate(&self) -> Result<()> { for (name, value) in [("updates", &self.updates), ("ribs", &self.ribs)] { + validate_relative_template(value).with_context(|| { + format!("[archive.custom_templates].{name} must be a safe relative path") + })?; if !value.contains("{collector}") { bail!( "[archive.custom_templates].{} must contain {{collector}} token", @@ -333,6 +333,40 @@ impl CustomLayoutTemplates { } } +fn validate_collector_id(collector_id: &str) -> Result<()> { + let bytes = collector_id.as_bytes(); + let valid = (1..=64).contains(&bytes.len()) + && bytes[0].is_ascii_alphanumeric() + && bytes[1..] + .iter() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')); + if !valid { + bail!("[archive].collector_id must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$"); + } + Ok(()) +} + +pub(crate) fn validate_relative_template(template: &str) -> Result<()> { + let bytes = template.as_bytes(); + let has_drive_prefix = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'; + if template.starts_with('/') || template.starts_with('\\') || has_drive_prefix { + bail!("template must not be absolute"); + } + if template.contains('\\') { + bail!("template must not contain backslashes"); + } + if template.chars().any(char::is_control) { + bail!("template must not contain control characters"); + } + if template.split('/').any(|component| component.is_empty()) { + bail!("template must not contain empty path components"); + } + if template.split('/').any(|component| component == "..") { + bail!("template must not contain parent path components"); + } + Ok(()) +} + #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] #[serde(rename_all = "snake_case")] pub enum CompressionKind { @@ -502,4 +536,40 @@ layout_profile = "routeviews" let cfg: FoclConfig = toml::from_str(raw).expect("toml should parse"); assert_eq!(cfg.archive.layout_profile, LayoutProfile::RouteViews); } + + #[test] + fn rejects_absolute_custom_template() { + let templates = CustomLayoutTemplates { + updates: "/{collector}/updates.{yyyymmdd}.{hhmm}.{ext}".to_string(), + ribs: "{collector}/ribs.{yyyymmdd}.{hhmm}.{ext}".to_string(), + }; + assert!(templates.validate().is_err()); + } + + #[test] + fn rejects_parent_traversal_in_custom_template() { + let templates = CustomLayoutTemplates { + updates: "{collector}/../updates.{yyyymmdd}.{hhmm}.{ext}".to_string(), + ribs: "{collector}/ribs.{yyyymmdd}.{hhmm}.{ext}".to_string(), + }; + assert!(templates.validate().is_err()); + } + + #[test] + fn rejects_collector_id_with_slash() { + let cfg = ArchiveConfig { + collector_id: "focl/01".to_string(), + ..ArchiveConfig::default() + }; + assert!(cfg.validate().is_err()); + } + + #[test] + fn valid_custom_template_still_passes() { + let templates = CustomLayoutTemplates { + updates: "{collector}/{yyyy}/updates.{yyyymmdd}.{hhmm}.{ext}".to_string(), + ribs: "{collector}/{yyyy}/ribs.{yyyymmdd}.{hhmm}.{ext}".to_string(), + }; + templates.validate().expect("safe template should validate"); + } } diff --git a/tests/archive_integration.rs b/tests/archive_integration.rs index 2d5e340..e56776b 100644 --- a/tests/archive_integration.rs +++ b/tests/archive_integration.rs @@ -1,4 +1,4 @@ -use std::net::Ipv4Addr; +use std::net::{IpAddr, Ipv4Addr}; use focl::archive::types::UpdateRecordInput; use focl::archive::ArchiveService; @@ -49,8 +49,8 @@ async fn writes_updates_segment_and_manifest_on_rollover() { peer_asn: 64512, local_asn: 64513, interface_index: 0, - peer_ip: Ipv4Addr::new(198, 51, 100, 1), - local_ip: Ipv4Addr::new(198, 51, 100, 2), + peer_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + local_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)), bgp_message: valid_update_withdraw_message(), }) .await From 410500079e371967120eb4ebfd5306205413e2fc Mon Sep 17 00:00:00 2001 From: Scouty Date: Wed, 19 Aug 2026 21:04:56 -0700 Subject: [PATCH 03/17] docs: Phase 1 rev - duck announcement reference and in-process acceptance test - reference interop target is duck (runs BIRD today, /etc/bird/bird.conf is the config of record): AS 400644, two Vultr MD5 sessions (v4+v6), announces 192.100.82.0/24 and 2620:aa:a000::/48; Phase 1 done = focl replaces bird there for simple announcements (deployment stays a separate operator-driven step) - Phase 1 acceptance = deterministic in-process harness-peer test (configured prefixes both directions, adj-rib-in + MRT assertions); GoBGP testcontainers stay in the interop-expansion lane --- docs/collector-revision-plan.md | 60 +++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 18 deletions(-) diff --git a/docs/collector-revision-plan.md b/docs/collector-revision-plan.md index e521fd5..c69c443 100644 --- a/docs/collector-revision-plan.md +++ b/docs/collector-revision-plan.md @@ -107,35 +107,59 @@ MRT; the archive knows nothing about BMP/BGP sessions. ## Phase 1 — make BGP peering mode a real collector -1. **Adj-RIB-In store on ipnet-trie.** One trie per peer. Value model is - `{interned attribute-blob id (u32), last_change_ts, path_id?}` — raw - UPDATE bytes live only in MRT, never duplicated per prefix (fixes the - review's inconsistent-representation finding). Memory-only v1 (rusqlite - stays for the replication queue). +1. **Adj-RIB-In store on ipnet-trie.** One trie per peer, value model is + `{interned attribute-blob id (u32), last_change_ts, path_id?}`. Memory-only v1 + (rusqlite stays for the replication queue). 2. **Wire the archive.** Received UPDATEs → `ingest_update` (exists, never called); FSM transitions → `ingest_peer_state` (events already flow). Rx-only by convention (RouteViews/RIS never archive tx). 3. **Real RIB snapshots.** Dump adj-rib-in tries on the configured ribs - interval as one collector snapshot (single peer-index table, entries - grouped per prefix), replacing today's empty snapshot. **No RIB file is - emitted before a valid baseline exists** (fixes empty-dump bug). Pre- - policy semantics (`adj_rib_in` is already the config default). + interval, replacing today's empty snapshot. **No RIB file is emitted + before a valid baseline exists.** Pre-policy semantics (`adj_rib_in` is + already the config default). 4. **Capability negotiation.** Advertise and validate the intersection of locally configured and peer-advertised capabilities: MP-BGP v4+v6, - route-refresh, AS4, extended-message, graceful-restart behavior, and - per-AFI/SAFI ADD-PATH policy. A capability-less OPEN establishes plain - IPv4 BGP; what it cannot do is IPv6/MP-BGP sessions — that is the real - gap (corrects review major 6). UPDATEs enter the trie only after - negotiated AFI/SAFI is known. + route-refresh, AS4, graceful-restart, per-AFI/SAFI ADD-PATH policy. A + capability-less OPEN establishes plain IPv4 BGP; what it cannot do is + IPv6/MP-BGP sessions — that is the real gap. UPDATEs enter the trie + only after negotiated AFI/SAFI is known. 5. **Global passive listener** with per-peer match before any state - mutation, connection-collision handling, separate v4/v6 bind - configuration, and rejected-connection observability; replacing - per-peer binds; the `listen` global config becomes real. -6. **Interop expansion.** Extend the GoBGP scripts: v6 session, capability + mutation, connection-collision handling, and separate v4/v6 bind + configuration; replacing per-peer binds; the `listen` global config + becomes real. +6. **Reference interop target: duck (announcer replacement).** The + production reference is `duck`, the Vultr BGP announcer. Note duck runs + **BIRD** (not FRR) today; `/etc/bird/bird.conf` is the reference config: + - AS 400644, router id 149.28.81.209 + - two Vultr sessions: v4 peer 169.254.169.254 and v6 peer + 2001:19f0:ffff::1, both remote AS 64515, both with TCP-MD5 password + - announces 192.100.82.0/24 (next hop 149.28.81.209) and + 2620:aa:a000::/48 (next hop 2001:19f0:6001:30cc:5400:5ff:fe61:25da) + with blackhole backing; `import none; export filter` policy + Phase 1 done means: focl replaces bird on duck for these two + announcements — active sessions to the Vultr peers with MD5, correct + MP-BGP capability negotiation (v4 session advertises v4; v6 session + negotiates MP-BGP v6 and announces via MP_REACH), routes present in + Vultr's looking glass, and MRT updates archived for both families. + Deployment is a separate manual step (routing-infrastructure change, + operator-driven). +7. **Interop expansion.** Extend the GoBGP scripts: v6 session, capability matrix, flap → assert MRT files parse and contain expected elements. Negative tests (review minor 16): malformed UPDATE disposition, Peer Down clears the peer's trie, interrupted EoR yields no complete dump, duplicate Peer Up starts a new generation. +8. **In-process announcement test (Phase 1 acceptance).** A test harness + peer with configured prefixes establishes with a test focl instance and + receives the configured announcements. Options: + - (a) **in-process harness peer** (recommended, v1): a minimal test-side + BGP speaker speaking open/keepalive/update, configured with its own + prefixes. focl announces its configured prefixes; the harness peer + announces its; both sides assert received announcements, adj-rib-in + trie state, and MRT archive output (parse back with bgpkit-parser). + No container fleet, no external router. + - (b) GoBGP testcontainer peer: heavier, CI-docker dependent, kept for + the interop expansion in item 7, not the acceptance gate. + The acceptance test is (a): deterministic, fast, runs in `cargo test`. ## Phase 2 — BMP station mode From fcbddb46b41fe1143aff92c07b049c1fc322b588 Mon Sep 17 00:00:00 2001 From: Scouty Date: Wed, 19 Aug 2026 21:19:40 -0700 Subject: [PATCH 04/17] feat(bgp): Phase 1 - real peering collector with capability negotiation Capability negotiation: - OPEN advertises MP-BGP ipv4+ipv6 unicast, FourOctetAs (AS_TRANS on the wire for 4-byte local ASN), route-refresh when configured - peer OPEN capabilities parsed from the raw frame; negotiated families, asn4, route-refresh, graceful-restart tracked per session; remote ASN validated incl. AS_TRANS resolution from the AS4 capability - capability-less peers still establish plain IPv4 unicast Correct dual-stack announcements: - IPv4 prefixes via classic NLRI + NEXT_HOP - IPv6 prefixes via MP_REACH_NLRI (Nlri::new_reachable); invalid non-v6 configured next hops are rejected rather than malformed-encoded - AS path is_as4 follows negotiation Receive path + Adj-RIB-In: - established loop no longer discards UPDATEs: raw frame -> archive ingest_update, parsed prefixes -> per-peer ipnet-trie (classic NLRI, MP_REACH, MP_UNREACH withdrawals), value {next_hop, as_path, last_seen} - rib_in() returns live trie contents (was a stub); trie cleared on session end/NOTIFICATION - outbound configured-prefix UPDATEs also archived so a lab archive replay covers both sides of the session Global passive listener: - single bind of global.listen_addr; inbound connections matched against configured peers before any state mutation; unmatched dropped with log - TCP-MD5 applied on accepted sockets; inbound connection wins collisions (outbound attempt aborted); active loop resumes after inbound session ends Acceptance test (tests/acceptance_peer.rs): - in-process harness peer (open with v4+v6+AS4 caps, keepalive exchange) receives focl's configured v4+v6 announcements, announces its own 192.0.2.0/24 + 2001:db8::/32; asserts focl rib_in contains them, Established event fired, and MRT updates segment parses back via bgpkit-parser with records from both directions --- src/bgp/mod.rs | 923 +++++++++++++++++++++++++++++---------- src/bin/focld.rs | 2 +- tests/acceptance_peer.rs | 255 +++++++++++ 3 files changed, 941 insertions(+), 239 deletions(-) create mode 100644 tests/acceptance_peer.rs diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index a508de7..1f3556b 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; use std::sync::Arc; @@ -7,11 +7,12 @@ use std::time::Duration; use anyhow::{anyhow, Context, Result}; use bgpkit_parser::bgp::parse_bgp_message; use bgpkit_parser::models::{ - AsPath, AsnLength, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, BgpUpdateMessage, - NetworkPrefix, Origin, + Afi, AsPath, Asn, AsnLength, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, + BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, Safi, }; use bytes::Bytes; use ipnet::IpNet; +use ipnet_trie::IpnetTrie; use serde::{Deserialize, Serialize}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpSocket, TcpStream}; @@ -19,12 +20,16 @@ use tokio::sync::{broadcast, RwLock}; use tokio::task::JoinHandle; use tokio::time::{sleep, timeout, Instant}; +use crate::archive::types::{PeerStateRecordInput, UpdateRecordInput}; +use crate::archive::ArchiveService; use crate::config::{FoclConfig, PeerConfig}; use crate::types::{Event, EventEnvelope, PeerState}; mod auth; use auth::{TcpSocketExt, TcpStreamExt}; +const AS_TRANS: u16 = 23_456; + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PeerInfo { pub address: String, @@ -51,12 +56,7 @@ pub struct RibSummary { struct PeerRuntime { info: PeerInfo, cfg: PeerConfig, - task: JoinHandle<()>, -} - -#[derive(Clone)] -pub struct BgpService { - inner: Arc, + task: Option>, } #[derive(Debug, Clone)] @@ -65,22 +65,70 @@ struct PrefixEntry { next_hop: Option, } +/// A deliberately owned, uninterned v1 Adj-RIB-In value. Attribute interning is +/// deferred until the collector's memory profile is measured under real feeds. +#[derive(Debug, Clone)] +struct AdjRibValue { + next_hop: Option, + as_path: Option, + last_seen: i64, +} + +#[derive(Debug, Clone, Default)] +struct NegotiatedCapabilities { + families: HashSet<(Afi, Safi)>, + asn4: bool, + route_refresh: bool, + graceful_restart: bool, +} + +impl NegotiatedCapabilities { + fn supports(&self, afi: Afi, safi: Safi) -> bool { + // IPv4 unicast is available to an RFC 4271 peer even if it sent no + // RFC 4760 MP capability. IPv6 always requires explicit MP-BGP. + (afi == Afi::Ipv4 && safi == Safi::Unicast) || self.families.contains(&(afi, safi)) + } +} + struct BgpServiceInner { global_asn: u32, router_id: Ipv4Addr, prefixes: Vec, peers: RwLock>, + rib_in: RwLock>>, + session_local_ips: RwLock>, event_tx: broadcast::Sender, + archive: Option>, +} + +#[derive(Debug)] +struct ReceivedMessage { + message: BgpMessage, + raw: Vec, +} + +#[derive(Clone)] +pub struct BgpService { + inner: Arc, } impl BgpService { pub async fn new(cfg: &FoclConfig, event_tx: broadcast::Sender) -> Result { + Self::new_with_archive(cfg, event_tx, None).await + } + + /// Builds the speaker with an archive sink. Keeping `new` preserves the + /// control/library contract while daemon and collector callers opt in. + pub async fn new_with_archive( + cfg: &FoclConfig, + event_tx: broadcast::Sender, + archive: Option>, + ) -> Result { let router_id = cfg .global .router_id .parse::() .context("global.router_id must be IPv4")?; - let prefixes = cfg .prefixes .iter() @@ -97,26 +145,32 @@ impl BgpService { }) .collect::, _>>() .context("invalid prefix in config")?; - let inner = Arc::new(BgpServiceInner { global_asn: cfg.global.asn, router_id, prefixes, peers: RwLock::new(HashMap::new()), + rib_in: RwLock::new(HashMap::new()), + session_local_ips: RwLock::new(HashMap::new()), event_tx, + archive, }); - let service = Self { inner }; service.start_peers(&cfg.peers).await; + if cfg.global.listen { + service.start_listener(&cfg.global.listen_addr).await?; + } Ok(service) } async fn start_peers(&self, peers: &[PeerConfig]) { - for peer in peers { - if !peer.enabled { - continue; - } - let runtime = self.spawn_peer_task(peer.clone()); + for peer in peers.iter().filter(|peer| peer.enabled) { + let runtime = self.make_runtime(peer.clone()); + self.inner + .rib_in + .write() + .await + .insert(peer.address.clone(), IpnetTrie::new()); self.inner .peers .write() @@ -125,7 +179,7 @@ impl BgpService { } } - fn spawn_peer_task(&self, peer_cfg: PeerConfig) -> PeerRuntime { + fn make_runtime(&self, peer_cfg: PeerConfig) -> PeerRuntime { let local_as = peer_cfg.local_as.unwrap_or(self.inner.global_asn); let info = PeerInfo { address: peer_cfg.address.clone(), @@ -140,22 +194,103 @@ impl BgpService { advertised_prefixes: 0, established_at: None, }; + let task = (!peer_cfg.passive).then(|| self.spawn_active_loop(peer_cfg.clone())); + PeerRuntime { + info, + cfg: peer_cfg, + task, + } + } + fn spawn_active_loop(&self, peer_cfg: PeerConfig) -> JoinHandle<()> { let service = self.clone(); - let address = peer_cfg.address.clone(); - let peer_for_task = peer_cfg.clone(); - let task = tokio::spawn(async move { - service.peer_loop(peer_for_task).await; - let mut peers = service.inner.peers.write().await; - if let Some(runtime) = peers.get_mut(&address) { - runtime.info.state = PeerState::Idle; + tokio::spawn(async move { service.peer_loop(peer_cfg).await }) + } + + async fn start_listener(&self, listen_addr: &str) -> Result<()> { + let listener = TcpListener::bind(listen_addr) + .await + .with_context(|| format!("failed binding global BGP listener {listen_addr}"))?; + let service = self.clone(); + tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((stream, remote)) => service.accept_inbound(stream, remote).await, + Err(error) => tracing::warn!(error=%error, "global BGP listener accept failed"), + } } }); + Ok(()) + } - PeerRuntime { - info, - cfg: peer_cfg, - task, + async fn accept_inbound(&self, mut stream: TcpStream, remote: SocketAddr) { + let peer = { + let peers = self.inner.peers.read().await; + peers + .values() + .find(|runtime| { + runtime.cfg.enabled + && runtime + .cfg + .address + .parse::() + .is_ok_and(|address| address == remote.ip()) + }) + .map(|runtime| runtime.cfg.clone()) + }; + let Some(peer) = peer else { + tracing::warn!(remote=%remote, "dropping inbound BGP connection from unconfigured peer"); + return; + }; + if let Some(password) = &peer.password { + if let Err(error) = stream.set_md5_signature(&remote, password) { + tracing::warn!(peer=%peer.address, error=%error, "failed to set TCP-MD5 on inbound BGP connection"); + return; + } + } + + // RFC collision handling deliberately favours the accepted connection. + // Cancel the active loop before it can mutate the session state further. + let old_task = { + let mut peers = self.inner.peers.write().await; + peers + .get_mut(&peer.address) + .and_then(|runtime| runtime.task.take()) + }; + if let Some(task) = old_task { + task.abort(); + } + + let service = self.clone(); + let key = peer.address.clone(); + let task = tokio::spawn(async move { + let result = service.run_session(&peer, &mut stream).await; + service.clear_rib(&peer.address).await; + match result { + Ok(()) => { + service + .set_peer_state(&peer.address, PeerState::Active, None, None) + .await + } + Err(error) => { + service + .set_peer_state( + &peer.address, + PeerState::Active, + Some(error.to_string()), + None, + ) + .await + } + } + if !peer.passive { + sleep(Duration::from_secs(peer.connect_retry_secs as u64)).await; + service.peer_loop(peer).await; + } + }); + let mut peers = self.inner.peers.write().await; + if let Some(runtime) = peers.get_mut(&key) { + runtime.task = Some(task); } } @@ -163,29 +298,23 @@ impl BgpService { loop { self.set_peer_state(&peer.address, PeerState::Connect, None, None) .await; - - let result = if peer.passive { - self.run_passive_session(&peer).await - } else { - self.run_active_session(&peer).await - }; - + let result = self.run_active_session(&peer).await; + self.clear_rib(&peer.address).await; match result { Ok(()) => { self.set_peer_state(&peer.address, PeerState::Active, None, None) - .await; + .await } - Err(err) => { + Err(error) => { self.set_peer_state( &peer.address, PeerState::Active, - Some(err.to_string()), + Some(error.to_string()), None, ) .await; } } - sleep(Duration::from_secs(peer.connect_retry_secs as u64)).await; } } @@ -196,62 +325,42 @@ impl BgpService { .with_context(|| { format!("invalid peer socket {}:{}", peer.address, peer.remote_port) })?; - let mut stream = connect_with_optional_bind(peer, addr).await?; self.run_session(peer, &mut stream).await } - async fn run_passive_session(&self, peer: &PeerConfig) -> Result<()> { - let listen_addr = peer - .local_address - .clone() - .unwrap_or_else(|| format!("0.0.0.0:{}", peer.remote_port)); - let listen: SocketAddr = normalize_socket_addr(&listen_addr, peer.remote_port) - .with_context(|| format!("invalid passive local_address {}", listen_addr))?; - - let listener = TcpListener::bind(listen) - .await - .with_context(|| format!("failed binding passive listener {listen}"))?; - - let (mut stream, peer_addr) = listener.accept().await?; - - // Set TCP-MD5 signature if password is configured - // Note: For passive mode, the MD5 must be set on the accepted socket - // with the specific peer address - if let Some(password) = &peer.password { - stream - .set_md5_signature(&peer_addr, password) - .context("failed to set TCP-MD5 signature on accepted connection")?; - } - - self.run_session(peer, &mut stream).await - } - async fn run_session(&self, peer: &PeerConfig, stream: &mut TcpStream) -> Result<()> { + let local_ip = stream.local_addr()?.ip(); + self.inner + .session_local_ips + .write() + .await + .insert(peer.address.clone(), local_ip); self.set_peer_state(&peer.address, PeerState::OpenSent, None, None) .await; let local_as = peer.local_as.unwrap_or(self.inner.global_asn); let hold_time = peer.hold_time_secs.max(3); - - let open = BgpMessage::Open(BgpOpenMessage { - version: 4, - asn: local_as.into(), + let open = local_open( + self.inner.router_id, + local_as, hold_time, - bgp_identifier: self.inner.router_id, - extended_length: false, - opt_params: vec![], - }); - write_bgp_message(stream, &open).await?; + peer.route_refresh, + ); + write_bgp_message(stream, &open, AsnLength::Bits32).await?; let incoming = read_bgp_message(stream).await?; - if !matches!(incoming, BgpMessage::Open(_)) { + let BgpMessage::Open(remote_open) = incoming.message else { return Err(anyhow!("expected OPEN from peer")); - } + }; + let negotiated = negotiate_capabilities(&incoming.raw, peer.route_refresh); + validate_remote_as(&remote_open, &incoming.raw, peer.remote_as, negotiated.asn4)?; - write_bgp_message(stream, &BgpMessage::KeepAlive).await?; + self.set_peer_state(&peer.address, PeerState::OpenConfirm, None, None) + .await; + write_bgp_message(stream, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; let incoming = read_bgp_message(stream).await?; - if !matches!(incoming, BgpMessage::KeepAlive) { + if !matches!(incoming.message, BgpMessage::KeepAlive) { return Err(anyhow!("expected KEEPALIVE from peer after OPEN")); } @@ -262,66 +371,169 @@ impl BgpService { Some(chrono::Utc::now().timestamp()), ) .await; - - self.send_prefix_announcements(peer, stream).await?; + self.send_prefix_announcements(peer, stream, &negotiated) + .await?; let negotiated_hold = Duration::from_secs(hold_time as u64); let keepalive_interval = Duration::from_secs((hold_time as u64 / 3).max(1)); let mut next_keepalive = Instant::now() + keepalive_interval; let mut hold_deadline = Instant::now() + negotiated_hold; - loop { let now = Instant::now(); if now >= next_keepalive { - write_bgp_message(stream, &BgpMessage::KeepAlive).await?; + write_bgp_message(stream, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; next_keepalive = now + keepalive_interval; } - if now >= hold_deadline { return Err(anyhow!("hold timer expired")); } - let timeout_dur = std::cmp::min( next_keepalive.saturating_duration_since(now), Duration::from_secs(1), ); match timeout(timeout_dur, read_bgp_message(stream)).await { - Ok(Ok(msg)) => match msg { - BgpMessage::KeepAlive - | BgpMessage::Update(_) - | BgpMessage::Open(_) - | BgpMessage::RouteRefresh(_) => { + Ok(Ok(incoming)) => match incoming.message { + BgpMessage::Update(update) => { + self.ingest_received_update( + peer, + local_as, + local_ip, + update, + incoming.raw, + &negotiated, + ) + .await?; + hold_deadline = Instant::now() + negotiated_hold; + } + BgpMessage::KeepAlive | BgpMessage::Open(_) | BgpMessage::RouteRefresh(_) => { hold_deadline = Instant::now() + negotiated_hold; } BgpMessage::Notification(_) => { - return Err(anyhow!("received NOTIFICATION from peer")); + return Err(anyhow!("received NOTIFICATION from peer")) } }, - Ok(Err(err)) => return Err(err), + Ok(Err(error)) => return Err(error), Err(_) => {} } } } + async fn ingest_received_update( + &self, + peer: &PeerConfig, + local_as: u32, + local_ip: IpAddr, + update: BgpUpdateMessage, + raw: Vec, + negotiated: &NegotiatedCapabilities, + ) -> Result<()> { + self.apply_update_to_rib(&peer.address, &update, negotiated) + .await; + if let Some(archive) = &self.inner.archive { + archive + .ingest_update(UpdateRecordInput { + timestamp: chrono::Utc::now().timestamp(), + peer_ip: peer.address.parse().context("invalid configured peer IP")?, + peer_asn: peer.remote_as, + local_ip, + local_asn: local_as, + interface_index: 0, + bgp_message: raw, + }) + .await?; + } + Ok(()) + } + + async fn apply_update_to_rib( + &self, + peer: &str, + update: &BgpUpdateMessage, + negotiated: &NegotiatedCapabilities, + ) { + let next_hop = update.attributes.next_hop(); + let as_path = update.attributes.as_path().map(ToString::to_string); + let now = chrono::Utc::now().timestamp(); + let mut ribs = self.inner.rib_in.write().await; + let rib = ribs.entry(peer.to_string()).or_insert_with(IpnetTrie::new); + for prefix in &update.withdrawn_prefixes { + if negotiated.supports(afi_for(prefix.prefix), Safi::Unicast) { + rib.remove(prefix.prefix); + } + } + for prefix in &update.announced_prefixes { + if negotiated.supports(afi_for(prefix.prefix), Safi::Unicast) { + rib.insert( + prefix.prefix, + AdjRibValue { + next_hop, + as_path: as_path.clone(), + last_seen: now, + }, + ); + } + } + if let Some(nlri) = update.attributes.get_unreachable_nlri() { + if negotiated.supports(nlri.afi, nlri.safi) { + for prefix in nlri { + rib.remove(*prefix); + } + } + } + if let Some(nlri) = update.attributes.get_reachable_nlri() { + if negotiated.supports(nlri.afi, nlri.safi) { + let mp_next_hop = nlri.next_hop.map(|next_hop| next_hop.addr()); + for prefix in nlri { + rib.insert( + *prefix, + AdjRibValue { + next_hop: mp_next_hop, + as_path: as_path.clone(), + last_seen: now, + }, + ); + } + } + } + } + async fn send_prefix_announcements( &self, peer: &PeerConfig, stream: &mut TcpStream, + negotiated: &NegotiatedCapabilities, ) -> Result<()> { let local_as = peer.local_as.unwrap_or(self.inner.global_asn); - let router_id = self.inner.router_id; - - for prefix_entry in &self.inner.prefixes { - let update = build_announce_update(prefix_entry, router_id, local_as); - write_bgp_message(stream, &update).await?; + let local_ip = stream.local_addr()?.ip(); + for update in build_announce_updates( + &self.inner.prefixes, + self.inner.router_id, + local_ip, + local_as, + negotiated, + ) { + let raw = write_bgp_message(stream, &update, AsnLength::Bits32).await?; + // Keep the collector's configured-prefix baseline alongside the + // received feed; it lets a self-contained lab archive replay both + // sides of this peering session. + if let Some(archive) = &self.inner.archive { + archive + .ingest_update(UpdateRecordInput { + timestamp: chrono::Utc::now().timestamp(), + peer_ip: peer.address.parse().context("invalid configured peer IP")?, + peer_asn: peer.remote_as, + local_ip, + local_asn: local_as, + interface_index: 0, + bgp_message: raw, + }) + .await?; + } } - - let count = self.inner.prefixes.len(); let mut peers = self.inner.peers.write().await; if let Some(runtime) = peers.get_mut(&peer.address) { - runtime.info.advertised_prefixes = count; + runtime.info.advertised_prefixes = self.inner.prefixes.len(); } - Ok(()) } @@ -332,27 +544,83 @@ impl BgpService { last_error: Option, established_at: Option, ) { - let mut peers = self.inner.peers.write().await; - if let Some(runtime) = peers.get_mut(address) { + let old_state = { + let mut peers = self.inner.peers.write().await; + let Some(runtime) = peers.get_mut(address) else { + return; + }; + let old_state = runtime.info.state; runtime.info.state = state; - if let Some(err) = last_error { - runtime.info.last_error = Some(err); + if let Some(error) = last_error { + runtime.info.last_error = Some(error); } else if matches!(state, PeerState::Established) { runtime.info.last_error = None; } - if let Some(ts) = established_at { - runtime.info.established_at = Some(ts); + if let Some(timestamp) = established_at { + runtime.info.established_at = Some(timestamp); } - let _ = self - .inner - .event_tx - .send(EventEnvelope::new(Event::PeerState { - peer: address.to_string(), - state, - })); + old_state + }; + let _ = self + .inner + .event_tx + .send(EventEnvelope::new(Event::PeerState { + peer: address.to_string(), + state, + })); + self.archive_peer_state(address, old_state, state).await; + } + + async fn archive_peer_state(&self, address: &str, old_state: PeerState, new_state: PeerState) { + let Some(archive) = &self.inner.archive else { + return; + }; + let (peer_asn, local_asn) = { + let peers = self.inner.peers.read().await; + let Some(runtime) = peers.get(address) else { + return; + }; + (runtime.info.remote_as, runtime.info.local_as) + }; + let Some(local_ip) = self + .inner + .session_local_ips + .read() + .await + .get(address) + .copied() + else { + return; + }; + let Ok(peer_ip) = address.parse::() else { + return; + }; + if let Err(error) = archive + .ingest_peer_state(PeerStateRecordInput { + timestamp: chrono::Utc::now().timestamp(), + peer_ip, + peer_asn, + local_ip, + local_asn, + interface_index: 0, + old_state: peer_state_code(old_state), + new_state: peer_state_code(new_state), + }) + .await + { + tracing::warn!(peer=%address, error=%error, "failed archiving BGP peer state"); } } + async fn clear_rib(&self, peer: &str) { + self.inner + .rib_in + .write() + .await + .insert(peer.to_string(), IpnetTrie::new()); + self.inner.session_local_ips.write().await.remove(peer); + } + pub async fn peer_list(&self) -> Vec { self.inner .peers @@ -373,84 +641,269 @@ impl BgpService { } pub async fn peer_reset(&self, peer: &str) -> Result<()> { - let old = { + let (cfg, old_task) = { let mut peers = self.inner.peers.write().await; - peers.remove(peer) - }; - - let Some(old_runtime) = old else { - return Err(anyhow!("peer {} not found", peer)); + let runtime = peers + .get_mut(peer) + .ok_or_else(|| anyhow!("peer {peer} not found"))?; + (runtime.cfg.clone(), runtime.task.take()) }; - - old_runtime.task.abort(); - - let runtime = self.spawn_peer_task(old_runtime.cfg); - self.inner - .peers - .write() - .await - .insert(peer.to_string(), runtime); + if let Some(task) = old_task { + task.abort(); + } + self.clear_rib(peer).await; + let new_task = (!cfg.passive).then(|| self.spawn_active_loop(cfg)); + if let Some(runtime) = self.inner.peers.write().await.get_mut(peer) { + runtime.task = new_task; + runtime.info.state = PeerState::Idle; + } Ok(()) } pub async fn rib_summary(&self) -> RibSummary { let peers = self.inner.peers.read().await; - let established = peers - .values() - .filter(|p| matches!(p.info.state, PeerState::Established)) - .count(); - RibSummary { peers_total: peers.len(), - peers_established: established, - advertised_prefixes_total: peers.values().map(|p| p.info.advertised_prefixes).sum(), + peers_established: peers + .values() + .filter(|peer| matches!(peer.info.state, PeerState::Established)) + .count(), + advertised_prefixes_total: peers + .values() + .map(|peer| peer.info.advertised_prefixes) + .sum(), } } pub async fn rib_out(&self, peer: &str) -> Result> { - let peers = self.inner.peers.read().await; - if !peers.contains_key(peer) { - return Err(anyhow!("peer {} not found", peer)); + if !self.inner.peers.read().await.contains_key(peer) { + return Err(anyhow!("peer {peer} not found")); } Ok(self .inner .prefixes .iter() - .map(|p| p.network.to_string()) + .map(|prefix| prefix.network.to_string()) .collect()) } pub async fn rib_in(&self, peer: &str) -> Result> { - let peers = self.inner.peers.read().await; - if !peers.contains_key(peer) { - return Err(anyhow!("peer {} not found", peer)); + if !self.inner.peers.read().await.contains_key(peer) { + return Err(anyhow!("peer {peer} not found")); } - Ok(vec![]) + let ribs = self.inner.rib_in.read().await; + let mut prefixes = ribs + .get(peer) + .into_iter() + .flat_map(|rib| { + rib.iter().map(|(prefix, value)| { + let _ = (&value.next_hop, &value.as_path, value.last_seen); + prefix.to_string() + }) + }) + .collect::>(); + prefixes.sort(); + Ok(prefixes) } } -async fn connect_with_optional_bind(peer: &PeerConfig, remote: SocketAddr) -> Result { - let local_bind = match peer.local_address.as_deref() { - None => None, - Some(raw) => Some(normalize_socket_addr(raw, 0).context("invalid peer local_address")?), +fn local_open( + router_id: Ipv4Addr, + local_as: u32, + hold_time: u16, + route_refresh: bool, +) -> BgpMessage { + BgpMessage::Open(BgpOpenMessage { + version: 4, + asn: Asn::new_16bit(if local_as > u16::MAX as u32 { + AS_TRANS + } else { + local_as as u16 + }), + hold_time, + bgp_identifier: router_id, + extended_length: false, + opt_params: vec![OptParam { + param_type: 2, + param_value: ParamValue::Raw(capability_bytes(local_as, route_refresh)), + }], + }) +} + +fn capability_bytes(local_as: u32, route_refresh: bool) -> Vec { + let mut bytes = vec![1, 4, 0, 1, 0, 1, 1, 4, 0, 2, 0, 1, 65, 4]; + bytes.extend_from_slice(&local_as.to_be_bytes()); + if route_refresh { + bytes.extend_from_slice(&[2, 0]); + } + bytes +} + +fn peer_capabilities(raw: &[u8]) -> Vec<(u8, Vec)> { + if raw.len() < 29 || raw[18] != 1 { + return vec![]; + } + let end = (29 + raw[28] as usize).min(raw.len()); + let mut index = 29; + let mut result = Vec::new(); + while index + 2 <= end { + let param_type = raw[index]; + let length = raw[index + 1] as usize; + index += 2; + if index + length > end { + break; + } + if param_type == 2 { + let mut cap_index = index; + while cap_index + 2 <= index + length { + let cap_type = raw[cap_index]; + let cap_len = raw[cap_index + 1] as usize; + cap_index += 2; + if cap_index + cap_len > index + length { + break; + } + result.push((cap_type, raw[cap_index..cap_index + cap_len].to_vec())); + cap_index += cap_len; + } + } + index += length; + } + result +} + +fn negotiate_capabilities(raw: &[u8], route_refresh_configured: bool) -> NegotiatedCapabilities { + let mut negotiated = NegotiatedCapabilities::default(); + for (cap_type, value) in peer_capabilities(raw) { + match (cap_type, value.as_slice()) { + (1, [0, 1, _, 1]) => { + negotiated.families.insert((Afi::Ipv4, Safi::Unicast)); + } + (1, [0, 2, _, 1]) => { + negotiated.families.insert((Afi::Ipv6, Safi::Unicast)); + } + (65, [_, _, _, _]) => negotiated.asn4 = true, + (2, []) => negotiated.route_refresh = route_refresh_configured, + (64, _) => negotiated.graceful_restart = true, + _ => {} + } + } + negotiated +} + +fn validate_remote_as(open: &BgpOpenMessage, raw: &[u8], expected: u32, asn4: bool) -> Result<()> { + let advertised_asn4 = peer_capabilities(raw).into_iter().find_map(|(ty, value)| { + (ty == 65 && value.len() == 4).then(|| u32::from_be_bytes(value.try_into().unwrap())) + }); + let wire_asn: u32 = open.asn.into(); + let actual = if wire_asn == AS_TRANS as u32 && asn4 { + advertised_asn4.unwrap_or(wire_asn) + } else { + wire_asn }; + if actual != expected { + return Err(anyhow!( + "peer ASN mismatch: expected {expected}, got {actual}" + )); + } + Ok(()) +} + +fn build_announce_updates( + prefixes: &[PrefixEntry], + router_id: Ipv4Addr, + local_ip: IpAddr, + local_as: u32, + negotiated: &NegotiatedCapabilities, +) -> Vec { + let mut result = Vec::new(); + for prefix in prefixes + .iter() + .filter(|prefix| matches!(prefix.network, IpNet::V4(_))) + { + let mut attrs = base_announce_attributes(local_as, negotiated.asn4); + let next_hop = prefix.next_hop.unwrap_or(IpAddr::V4(router_id)); + attrs.add_attr(AttributeValue::NextHop(next_hop).into()); + result.push(BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![NetworkPrefix::new(prefix.network, None)], + })); + } + for prefix in prefixes + .iter() + .filter(|prefix| matches!(prefix.network, IpNet::V6(_))) + { + if !negotiated.supports(Afi::Ipv6, Safi::Unicast) { + continue; + } + let mut attrs = base_announce_attributes(local_as, negotiated.asn4); + // MP_REACH requires an IPv6 next hop. A configured non-v6 next hop is + // ignored rather than serializing a malformed NEXT_HOP attribute. + let next_hop = prefix + .next_hop + .filter(IpAddr::is_ipv6) + .or_else(|| local_ip.is_ipv6().then_some(local_ip)); + let Some(next_hop) = next_hop else { + tracing::warn!("not announcing IPv6 prefixes: no IPv6 configured/session next hop"); + continue; + }; + let nlri = Nlri::new_reachable(NetworkPrefix::new(prefix.network, None), Some(next_hop)); + attrs.add_attr(AttributeValue::MpReachNlri(nlri).into()); + result.push(BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![], + })); + } + result +} + +fn base_announce_attributes(local_as: u32, asn4: bool) -> Attributes { + let mut attrs = Attributes::default(); + attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); + attrs.add_attr( + AttributeValue::AsPath { + path: AsPath::from_sequence([local_as]), + is_as4: asn4, + } + .into(), + ); + attrs +} + +fn afi_for(prefix: IpNet) -> Afi { + match prefix { + IpNet::V4(_) => Afi::Ipv4, + IpNet::V6(_) => Afi::Ipv6, + } +} + +fn peer_state_code(state: PeerState) -> u16 { + match state { + PeerState::Idle => 1, + PeerState::Connect => 2, + PeerState::Active => 3, + PeerState::OpenSent => 4, + PeerState::OpenConfirm => 5, + PeerState::Established => 6, + } +} +async fn connect_with_optional_bind(peer: &PeerConfig, remote: SocketAddr) -> Result { + let local_bind = peer + .local_address + .as_deref() + .map(|raw| normalize_socket_addr(raw, 0)) + .transpose() + .context("invalid peer local_address")?; match (remote, local_bind) { (SocketAddr::V4(remote_v4), Some(SocketAddr::V4(local_v4))) => { let socket = TcpSocket::new_v4()?; socket.bind(SocketAddr::V4(local_v4))?; - - // Set TCP-MD5 signature if password is configured if let Some(password) = &peer.password { - socket - .set_md5_signature(&remote, password) - .context("failed to set TCP-MD5 signature")?; + socket.set_md5_signature(&remote, password)?; } - - socket - .connect(SocketAddr::V4(remote_v4)) - .await - .map_err(Into::into) + Ok(socket.connect(SocketAddr::V4(remote_v4)).await?) } (_, Some(local)) => { let socket = if local.is_ipv4() { @@ -459,126 +912,120 @@ async fn connect_with_optional_bind(peer: &PeerConfig, remote: SocketAddr) -> Re TcpSocket::new_v6()? }; socket.bind(local)?; - - // Set TCP-MD5 signature if password is configured if let Some(password) = &peer.password { - socket - .set_md5_signature(&remote, password) - .context("failed to set TCP-MD5 signature")?; + socket.set_md5_signature(&remote, password)?; } - - socket.connect(remote).await.map_err(Into::into) + Ok(socket.connect(remote).await?) } (_, None) => { - // No local bind, set MD5 on connected stream let stream = TcpStream::connect(remote).await?; - if let Some(password) = &peer.password { - stream - .set_md5_signature(&remote, password) - .context("failed to set TCP-MD5 signature")?; + stream.set_md5_signature(&remote, password)?; } - Ok(stream) } } } fn normalize_socket_addr(raw: &str, default_port: u16) -> Result { - if let Ok(sa) = raw.parse::() { - return Ok(sa); + if let Ok(socket) = raw.parse::() { + return Ok(socket); } - - let ip: IpAddr = raw - .parse() + let address = raw + .parse::() .with_context(|| format!("invalid ip/address {raw}"))?; - Ok(SocketAddr::new(ip, default_port)) + Ok(SocketAddr::new(address, default_port)) } -async fn write_bgp_message(stream: &mut TcpStream, msg: &BgpMessage) -> Result<()> { - let mut bytes = msg - .encode(AsnLength::Bits32) +async fn write_bgp_message( + stream: &mut TcpStream, + message: &BgpMessage, + asn_len: AsnLength, +) -> Result> { + let mut bytes = message + .encode(asn_len) .map_err(|error| anyhow!("failed encoding BGP message: {error}"))? .to_vec(); if bytes.len() < 19 { return Err(anyhow!("encoded BGP message too short")); } - bytes[0..16].fill(0xff); - stream.write_all(&bytes).await?; - Ok(()) + Ok(bytes) } -async fn read_bgp_message(stream: &mut TcpStream) -> Result { +async fn read_bgp_message(stream: &mut TcpStream) -> Result { let mut header = [0u8; 19]; stream.read_exact(&mut header).await?; - if header[0..16] != [0xff; 16] { return Err(anyhow!("invalid BGP marker")); } - let length = u16::from_be_bytes([header[16], header[17]]) as usize; if !(19..=4096).contains(&length) { - return Err(anyhow!("invalid BGP message length {}", length)); + return Err(anyhow!("invalid BGP message length {length}")); } - - let mut bytes = Vec::with_capacity(length); - bytes.extend_from_slice(&header); - - let payload_len = length - 19; - if payload_len > 0 { - let mut payload = vec![0u8; payload_len]; + let mut raw = Vec::with_capacity(length); + raw.extend_from_slice(&header); + if length > 19 { + let mut payload = vec![0; length - 19]; stream.read_exact(&mut payload).await?; - bytes.extend_from_slice(&payload); + raw.extend_from_slice(&payload); } - - let bytes32 = bytes.clone(); - let mut raw32 = Bytes::from(bytes32); - let parsed = parse_bgp_message(&mut raw32, false, &AsnLength::Bits32) + let mut raw32 = Bytes::from(raw.clone()); + let message = parse_bgp_message(&mut raw32, false, &AsnLength::Bits32) .or_else(|_| { - let mut raw16 = Bytes::from(bytes); + let mut raw16 = Bytes::from(raw.clone()); parse_bgp_message(&mut raw16, false, &AsnLength::Bits16) }) - .map_err(|e| anyhow!("failed parsing BGP message using bgpkit-parser: {e}"))?; - - Ok(parsed) + .map_err(|error| anyhow!("failed parsing BGP message using bgpkit-parser: {error}"))?; + Ok(ReceivedMessage { message, raw }) } -fn build_announce_update( - prefix_entry: &PrefixEntry, - router_id: Ipv4Addr, - local_as: u32, -) -> BgpMessage { - let mut attrs = Attributes::default(); - attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); - attrs.add_attr( - AttributeValue::AsPath { - path: AsPath::from_sequence([local_as]), - is_as4: false, - } - .into(), - ); - - // Determine next-hop: use configured next-hop or default based on prefix type - let next_hop = prefix_entry.next_hop.unwrap_or_else(|| { - match prefix_entry.network { - IpNet::V4(_) => IpAddr::V4(router_id), - IpNet::V6(_) => { - // For IPv6, we need a valid IPv6 next-hop - // Default to a link-local address derived from router_id if not specified - // In practice, user should configure this - IpAddr::V6(std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)) - } - } - }); +#[cfg(test)] +mod tests { + use super::*; - attrs.add_attr(AttributeValue::NextHop(next_hop).into()); + #[test] + fn local_open_advertises_dual_stack_as4_and_optional_route_refresh() { + let BgpMessage::Open(open) = local_open(Ipv4Addr::new(192, 0, 2, 1), 65_536, 90, true) + else { + panic!() + }; + assert_eq!(open.asn, Asn::new_16bit(AS_TRANS)); + let raw = BgpMessage::Open(open.clone()) + .encode(AsnLength::Bits32) + .unwrap(); + let negotiated = negotiate_capabilities(&raw, true); + assert!(negotiated.supports(Afi::Ipv4, Safi::Unicast)); + assert!(negotiated.supports(Afi::Ipv6, Safi::Unicast)); + assert!(negotiated.asn4); + assert!(negotiated.route_refresh); + } - let announced = NetworkPrefix::new(prefix_entry.network, None); - BgpMessage::Update(BgpUpdateMessage { - withdrawn_prefixes: vec![], - attributes: attrs, - announced_prefixes: vec![announced], - }) + #[test] + fn v6_announcements_use_mp_reach_not_classic_nlri() { + let prefixes = vec![PrefixEntry { + network: "2001:db8::/32".parse().unwrap(), + next_hop: Some("2001:db8::1".parse().unwrap()), + }]; + let mut negotiated = NegotiatedCapabilities::default(); + negotiated.families.insert((Afi::Ipv6, Safi::Unicast)); + let updates = build_announce_updates( + &prefixes, + Ipv4Addr::new(192, 0, 2, 1), + "2001:db8::2".parse().unwrap(), + 65_001, + &negotiated, + ); + let BgpMessage::Update(update) = &updates[0] else { + panic!() + }; + assert!(update.announced_prefixes.is_empty()); + assert_eq!( + update.attributes.get_reachable_nlri().unwrap().prefixes[0] + .prefix + .to_string(), + "2001:db8::/32" + ); + } } diff --git a/src/bin/focld.rs b/src/bin/focld.rs index e5d2ac3..e304fe0 100644 --- a/src/bin/focld.rs +++ b/src/bin/focld.rs @@ -35,7 +35,7 @@ async fn main() -> Result<()> { let archive = ArchiveService::new(cfg.archive.clone(), collector_bgp_id).await?; let events_tx = archive.event_sender(); - let bgp = BgpService::new(&cfg, events_tx).await?; + let bgp = BgpService::new_with_archive(&cfg, events_tx, Some(Arc::clone(&archive))).await?; let socket_path = cfg.global.control_socket.clone(); cleanup_socket(&socket_path)?; diff --git a/tests/acceptance_peer.rs b/tests/acceptance_peer.rs new file mode 100644 index 0000000..4116c7a --- /dev/null +++ b/tests/acceptance_peer.rs @@ -0,0 +1,255 @@ +use std::io::{Cursor, Read}; +use std::net::{IpAddr, Ipv4Addr, TcpListener as StdTcpListener}; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result}; +use bgpkit_parser::bgp::parse_bgp_message; +use bgpkit_parser::models::{ + AsPath, Asn, AsnLength, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, + BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, +}; +use bgpkit_parser::parse_mrt_record; +use bytes::Bytes; +use flate2::read::GzDecoder; +use focl::archive::types::ArchiveStream; +use focl::archive::ArchiveService; +use focl::bgp::BgpService; +use focl::config::{ArchiveConfig, FoclConfig, GlobalConfig, PeerConfig, PrefixConfig}; +use focl::types::{Event, PeerState}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::time::timeout; + +const PEER_AS: u32 = 65_002; +const FOCL_AS: u32 = 65_001; + +#[tokio::test] +async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<()> { + let temp = tempfile::tempdir()?; + // Allocate before starting focl; this is the test's documented bounded port race. + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let archive_root = temp.path().join("archive"); + let cfg = FoclConfig { + global: GlobalConfig { + asn: FOCL_AS, + router_id: "192.0.2.1".to_string(), + listen: true, + listen_addr: format!("127.0.0.1:{port}"), + control_socket: temp.path().join("focld.sock"), + log_level: "warn".to_string(), + }, + peers: vec![PeerConfig { + address: "127.0.0.1".to_string(), + remote_as: PEER_AS, + local_as: None, + hold_time_secs: 30, + connect_retry_secs: 1, + remote_port: port, + local_address: None, + enabled: true, + passive: true, + route_refresh: true, + name: None, + password: None, + }], + prefixes: vec![ + PrefixConfig { + network: "198.51.100.0/24".to_string(), + next_hop: Some("192.0.2.1".to_string()), + }, + PrefixConfig { + network: "2001:db8:feed::/48".to_string(), + next_hop: Some("2001:db8::1".to_string()), + }, + ], + archive: ArchiveConfig { + enabled: true, + root: archive_root.clone(), + tmp_root: archive_root.join(".tmp"), + updates_interval_secs: 900, + ribs_interval_secs: 900, + ..ArchiveConfig::default() + }, + }; + let archive = ArchiveService::new(cfg.archive.clone(), Ipv4Addr::new(192, 0, 2, 1)).await?; + let mut events = archive.subscribe_events(); + let bgp = + BgpService::new_with_archive(&cfg, archive.event_sender(), Some(Arc::clone(&archive))) + .await?; + + let mut stream = timeout( + Duration::from_secs(5), + TcpStream::connect(("127.0.0.1", port)), + ) + .await??; + let focl_open = read_message(&mut stream).await?; + assert!(matches!(focl_open, BgpMessage::Open(_))); + write_message(&mut stream, &peer_open()).await?; + let keepalive = read_message(&mut stream).await?; + assert!(matches!(keepalive, BgpMessage::KeepAlive)); + write_message(&mut stream, &BgpMessage::KeepAlive).await?; + + let first = read_message(&mut stream).await?; + let second = read_message(&mut stream).await?; + let received = [first, second]; + assert!(received.iter().any(has_focl_v4)); + assert!(received.iter().any(has_focl_v6)); + + write_message( + &mut stream, + &announce_v4("192.0.2.0/24", "192.0.2.2".parse()?), + ) + .await?; + write_message( + &mut stream, + &announce_v6("2001:db8::/32", "2001:db8::2".parse()?), + ) + .await?; + + timeout(Duration::from_secs(5), async { + loop { + let prefixes = bgp.rib_in("127.0.0.1").await?; + if prefixes.iter().any(|prefix| prefix == "192.0.2.0/24") + && prefixes.iter().any(|prefix| prefix == "2001:db8::/32") + { + return Ok::<_, anyhow::Error>(()); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await??; + + let mut established_recorded = false; + timeout(Duration::from_secs(5), async { + while !established_recorded { + if let Ok(event) = events.recv().await { + if matches!( + event.event, + Event::PeerState { + state: PeerState::Established, + .. + } + ) { + established_recorded = true; + } + } + } + }) + .await?; + assert!(established_recorded); + + // Finalize and parse every MRT record, ensuring raw BGP4MP output is readable. + archive.rollover(ArchiveStream::Updates).await?; + let segment = walkdir::WalkDir::new(&archive_root) + .into_iter() + .filter_map(Result::ok) + .find_map(|entry| { + entry + .path() + .extension() + .is_some_and(|ext| ext == "gz") + .then(|| entry.path().to_path_buf()) + }) + .context("updates rollover should create a gzip segment")?; + let mut decoded = Vec::new(); + GzDecoder::new(std::fs::File::open(segment)?).read_to_end(&mut decoded)?; + let mut cursor = Cursor::new(decoded); + let mut record_count = 0; + while (cursor.position() as usize) < cursor.get_ref().len() { + parse_mrt_record(&mut cursor)?; + record_count += 1; + } + // two outbound configured-prefix UPDATEs plus the two peer UPDATEs, and state changes. + assert!( + record_count >= 4, + "expected both directions in archived BGP4MP records" + ); + Ok(()) +} + +fn capabilities() -> Vec { + let mut bytes = vec![1, 4, 0, 1, 0, 1, 1, 4, 0, 2, 0, 1, 65, 4]; + bytes.extend_from_slice(&PEER_AS.to_be_bytes()); + bytes.extend_from_slice(&[2, 0]); + bytes +} + +fn peer_open() -> BgpMessage { + BgpMessage::Open(BgpOpenMessage { + version: 4, + asn: Asn::new_16bit(PEER_AS as u16), + hold_time: 30, + bgp_identifier: Ipv4Addr::new(192, 0, 2, 2), + extended_length: false, + opt_params: vec![OptParam { + param_type: 2, + param_value: ParamValue::Raw(capabilities()), + }], + }) +} + +fn attrs() -> Attributes { + let mut attrs = Attributes::default(); + attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); + attrs.add_attr( + AttributeValue::AsPath { + path: AsPath::from_sequence([PEER_AS]), + is_as4: true, + } + .into(), + ); + attrs +} + +fn announce_v4(prefix: &str, next_hop: IpAddr) -> BgpMessage { + let mut attributes = attrs(); + attributes.add_attr(AttributeValue::NextHop(next_hop).into()); + BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes, + announced_prefixes: vec![prefix.parse::().unwrap()], + }) +} + +fn announce_v6(prefix: &str, next_hop: IpAddr) -> BgpMessage { + let mut attributes = attrs(); + attributes.add_attr( + AttributeValue::MpReachNlri(Nlri::new_reachable(prefix.parse().unwrap(), Some(next_hop))) + .into(), + ); + BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes, + announced_prefixes: vec![], + }) +} + +fn has_focl_v4(message: &BgpMessage) -> bool { + matches!(message, BgpMessage::Update(update) if update.announced_prefixes.iter().any(|prefix| prefix.prefix.to_string() == "198.51.100.0/24")) +} + +fn has_focl_v6(message: &BgpMessage) -> bool { + matches!(message, BgpMessage::Update(update) if update.attributes.get_reachable_nlri().is_some_and(|nlri| nlri.prefixes.iter().any(|prefix| prefix.prefix.to_string() == "2001:db8:feed::/48"))) +} + +async fn write_message(stream: &mut TcpStream, message: &BgpMessage) -> Result<()> { + let mut bytes = message.encode(AsnLength::Bits32)?.to_vec(); + bytes[..16].fill(0xff); + stream.write_all(&bytes).await?; + Ok(()) +} + +async fn read_message(stream: &mut TcpStream) -> Result { + let mut header = [0; 19]; + timeout(Duration::from_secs(5), stream.read_exact(&mut header)).await??; + let length = u16::from_be_bytes([header[16], header[17]]) as usize; + let mut raw = header.to_vec(); + if length > 19 { + let mut body = vec![0; length - 19]; + timeout(Duration::from_secs(5), stream.read_exact(&mut body)).await??; + raw.extend_from_slice(&body); + } + let mut bytes = Bytes::from(raw); + Ok(parse_bgp_message(&mut bytes, false, &AsnLength::Bits32)?) +} From 59ddd87002c5a96af8a37201db06cb60f8910e8f Mon Sep 17 00:00:00 2001 From: Scouty Date: Thu, 20 Aug 2026 05:18:53 -0700 Subject: [PATCH 05/17] fix(bgp): family gating for announcements and End-of-RIB markers - classic NLRI announce + rib_in apply now require the session to actually carry IPv4 (negotiated v4 MP capability, or a capability-less RFC 4271 peer); prevents leaking v4 UPDATEs onto v6-only sessions like duck's Vultr peering - send End-of-RIB after the initial announcement burst (empty UPDATE for v4; empty MP_UNREACH for v6) so peers see table transfer complete - drop now-unused afi_for helper --- src/bgp/mod.rs | 74 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 1f3556b..fed4dc0 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -84,9 +84,13 @@ struct NegotiatedCapabilities { impl NegotiatedCapabilities { fn supports(&self, afi: Afi, safi: Safi) -> bool { - // IPv4 unicast is available to an RFC 4271 peer even if it sent no - // RFC 4760 MP capability. IPv6 always requires explicit MP-BGP. - (afi == Afi::Ipv4 && safi == Safi::Unicast) || self.families.contains(&(afi, safi)) + self.families.contains(&(afi, safi)) + } + + /// True when the peer sent an OPEN with no capabilities at all (plain + /// RFC 4271 IPv4-only speaker). IPv4 unicast is then still available. + fn plain_ipv4(&self) -> bool { + self.families.is_empty() } } @@ -373,6 +377,36 @@ impl BgpService { .await; self.send_prefix_announcements(peer, stream, &negotiated) .await?; + // RFC 4271 End-of-RIB: an empty UPDATE per family marks the initial + // table transfer complete. Vultr's route servers treat a session + // missing EoR as still converging; send both families' markers. + for eor_family in [Afi::Ipv4, Afi::Ipv6] { + if negotiated.supports(eor_family, Safi::Unicast) { + let eor = if eor_family == Afi::Ipv4 { + BgpMessage::Update(BgpUpdateMessage::default()) + } else { + let mut attrs = Attributes::default(); + attrs.add_attr( + AttributeValue::MpUnreachNlri(Nlri { + afi: Afi::Ipv6, + safi: Safi::Unicast, + next_hop: None, + prefixes: vec![], + labeled_prefixes: None, + link_state_nlris: None, + flowspec_nlris: None, + }) + .into(), + ); + BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![], + }) + }; + write_bgp_message(stream, &eor, AsnLength::Bits32).await?; + } + } let negotiated_hold = Duration::from_secs(hold_time as u64); let keepalive_interval = Duration::from_secs((hold_time as u64 / 3).max(1)); @@ -456,13 +490,17 @@ impl BgpService { let now = chrono::Utc::now().timestamp(); let mut ribs = self.inner.rib_in.write().await; let rib = ribs.entry(peer.to_string()).or_insert_with(IpnetTrie::new); + // Plain IPv4 NLRI is only valid on a session that carries IPv4 + // (negotiated v4 MP capability or a capability-less RFC 4271 peer). + let classic_ipv4_ok = + negotiated.plain_ipv4() || negotiated.supports(Afi::Ipv4, Safi::Unicast); for prefix in &update.withdrawn_prefixes { - if negotiated.supports(afi_for(prefix.prefix), Safi::Unicast) { + if classic_ipv4_ok { rib.remove(prefix.prefix); } } for prefix in &update.announced_prefixes { - if negotiated.supports(afi_for(prefix.prefix), Safi::Unicast) { + if classic_ipv4_ok { rib.insert( prefix.prefix, AdjRibValue { @@ -816,18 +854,21 @@ fn build_announce_updates( negotiated: &NegotiatedCapabilities, ) -> Vec { let mut result = Vec::new(); + let plain_ipv4 = negotiated.plain_ipv4(); for prefix in prefixes .iter() .filter(|prefix| matches!(prefix.network, IpNet::V4(_))) { - let mut attrs = base_announce_attributes(local_as, negotiated.asn4); - let next_hop = prefix.next_hop.unwrap_or(IpAddr::V4(router_id)); - attrs.add_attr(AttributeValue::NextHop(next_hop).into()); - result.push(BgpMessage::Update(BgpUpdateMessage { - withdrawn_prefixes: vec![], - attributes: attrs, - announced_prefixes: vec![NetworkPrefix::new(prefix.network, None)], - })); + if plain_ipv4 || negotiated.supports(Afi::Ipv4, Safi::Unicast) { + let mut attrs = base_announce_attributes(local_as, negotiated.asn4); + let next_hop = prefix.next_hop.unwrap_or(IpAddr::V4(router_id)); + attrs.add_attr(AttributeValue::NextHop(next_hop).into()); + result.push(BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![NetworkPrefix::new(prefix.network, None)], + })); + } } for prefix in prefixes .iter() @@ -871,13 +912,6 @@ fn base_announce_attributes(local_as: u32, asn4: bool) -> Attributes { attrs } -fn afi_for(prefix: IpNet) -> Afi { - match prefix { - IpNet::V4(_) => Afi::Ipv4, - IpNet::V6(_) => Afi::Ipv6, - } -} - fn peer_state_code(state: PeerState) -> u16 { match state { PeerState::Idle => 1, From 0ccae7e4adb55b73dc133b48bc12187ec9fe93ed Mon Sep 17 00:00:00 2001 From: Scouty Date: Thu, 20 Aug 2026 06:19:04 -0700 Subject: [PATCH 06/17] fix(bgp): parse peer address as IpAddr for IPv6 connect paths format!("{}:{}", v6_addr, port) produces an unbracketed, unparseable socket string, so active IPv6 sessions never dialed (seen live on duck: 'invalid peer socket 2001:19f0:ffff::1:179'). Parse the IP explicitly and build SocketAddr::new. --- src/bgp/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index fed4dc0..b0ce981 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -324,11 +324,11 @@ impl BgpService { } async fn run_active_session(&self, peer: &PeerConfig) -> Result<()> { - let addr: SocketAddr = format!("{}:{}", peer.address, peer.remote_port) + let ip: IpAddr = peer + .address .parse() - .with_context(|| { - format!("invalid peer socket {}:{}", peer.address, peer.remote_port) - })?; + .with_context(|| format!("invalid peer address {}", peer.address))?; + let addr = SocketAddr::new(ip, peer.remote_port); let mut stream = connect_with_optional_bind(peer, addr).await?; self.run_session(peer, &mut stream).await } From 549ddca1180154f5d930d664c2d5b0ef703317f7 Mon Sep 17 00:00:00 2001 From: Scouty Date: Thu, 20 Aug 2026 06:19:35 -0700 Subject: [PATCH 07/17] test: regression for bare IPv6 peer address dial path --- tests/acceptance_peer.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/acceptance_peer.rs b/tests/acceptance_peer.rs index 4116c7a..40cf496 100644 --- a/tests/acceptance_peer.rs +++ b/tests/acceptance_peer.rs @@ -253,3 +253,17 @@ async fn read_message(stream: &mut TcpStream) -> Result { let mut bytes = Bytes::from(raw); Ok(parse_bgp_message(&mut bytes, false, &AsnLength::Bits32)?) } + +#[test] +fn ipv6_peer_address_dials_correctly() { + // Regression for duck: format!("{}:{}", v6, port) is unparseable, so + // active IPv6 sessions never dialed. The fixed path parses the IP + // explicitly and builds SocketAddr::new — assert both halves. + let ip: std::net::IpAddr = "2001:19f0:ffff::1".parse().expect("v6 parses"); + let addr = std::net::SocketAddr::new(ip, 179); + assert_eq!(addr.to_string(), "[2001:19f0:ffff::1]:179"); + // and the broken concat really is unparseable (guards the regression): + assert!(format!("{}:179", "2001:19f0:ffff::1") + .parse::() + .is_err()); +} From fd6fbd3265bf31fbfaa0ae8d2a61e4b3e3e42193 Mon Sep 17 00:00:00 2001 From: Scouty Date: Thu, 20 Aug 2026 06:47:16 -0700 Subject: [PATCH 08/17] fix(bgp): AS_PATH type 2 with negotiated segment width, not AS4_PATH is_as4: true in bgpkit-parser selects the AS4_PATH attribute (type 17), the RFC 6793 migration fallback, rather than 4-octet AS_PATH. On AS4 sessions the correct wire form is AS_PATH (type 2) with 4-octet segments. Announcement and EoR writes now pass the negotiated AsnLength (Bits32/Bits16) instead of hardcoded Bits32. Seen live on duck: both announcements carried attr 17. --- src/bgp/mod.rs | 94 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 88 insertions(+), 6 deletions(-) diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index b0ce981..7d0a884 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -404,7 +404,12 @@ impl BgpService { announced_prefixes: vec![], }) }; - write_bgp_message(stream, &eor, AsnLength::Bits32).await?; + let asn_len = if negotiated.asn4 { + AsnLength::Bits32 + } else { + AsnLength::Bits16 + }; + write_bgp_message(stream, &eor, asn_len).await?; } } @@ -550,7 +555,12 @@ impl BgpService { local_as, negotiated, ) { - let raw = write_bgp_message(stream, &update, AsnLength::Bits32).await?; + let asn_len = if negotiated.asn4 { + AsnLength::Bits32 + } else { + AsnLength::Bits16 + }; + let raw = write_bgp_message(stream, &update, asn_len).await?; // Keep the collector's configured-prefix baseline alongside the // received feed; it lets a self-contained lab archive replay both // sides of this peering session. @@ -860,7 +870,7 @@ fn build_announce_updates( .filter(|prefix| matches!(prefix.network, IpNet::V4(_))) { if plain_ipv4 || negotiated.supports(Afi::Ipv4, Safi::Unicast) { - let mut attrs = base_announce_attributes(local_as, negotiated.asn4); + let mut attrs = base_announce_attributes(local_as); let next_hop = prefix.next_hop.unwrap_or(IpAddr::V4(router_id)); attrs.add_attr(AttributeValue::NextHop(next_hop).into()); result.push(BgpMessage::Update(BgpUpdateMessage { @@ -877,7 +887,7 @@ fn build_announce_updates( if !negotiated.supports(Afi::Ipv6, Safi::Unicast) { continue; } - let mut attrs = base_announce_attributes(local_as, negotiated.asn4); + let mut attrs = base_announce_attributes(local_as); // MP_REACH requires an IPv6 next hop. A configured non-v6 next hop is // ignored rather than serializing a malformed NEXT_HOP attribute. let next_hop = prefix @@ -899,13 +909,18 @@ fn build_announce_updates( result } -fn base_announce_attributes(local_as: u32, asn4: bool) -> Attributes { +fn base_announce_attributes(local_as: u32) -> Attributes { let mut attrs = Attributes::default(); attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); attrs.add_attr( AttributeValue::AsPath { path: AsPath::from_sequence([local_as]), - is_as4: asn4, + // `is_as4: true` selects AS4_PATH (attribute type 17), which is + // only for the RFC 6793 migration fallback. On a session that + // negotiated 4-octet AS, the correct wire form is AS_PATH (type 2) + // with 4-octet segments: keep this false and let the session + // AsnLength (Bits32 when AS4, Bits16 otherwise) drive the width. + is_as4: false, } .into(), ); @@ -1019,6 +1034,73 @@ async fn read_bgp_message(stream: &mut TcpStream) -> Result { mod tests { use super::*; + #[test] + fn announce_updates_use_type2_as_path_with_negotiated_width() { + fn as_path_attr(msg: &BgpMessage, asn_len: AsnLength) -> (u8, Vec) { + let BgpMessage::Update(u) = msg else { + panic!("not an UPDATE") + }; + let mut buf = bytes::BytesMut::new(); + u.attributes.encode_to(asn_len, &mut buf).unwrap(); + let mut p = 0; + while p < buf.len() { + let flags = buf[p]; + let code = buf[p + 1]; + let (l, hdr) = if flags & 0x10 != 0 { + (u16::from_be_bytes([buf[p + 2], buf[p + 3]]) as usize, 4) + } else { + (buf[p + 2] as usize, 3) + }; + if code == 2 || code == 17 { + return (code, buf[p + hdr..p + hdr + l].to_vec()); + } + p += hdr + l; + } + panic!("no AS_PATH attribute found"); + } + + let prefixes = vec![PrefixEntry { + network: "192.0.2.0/24".parse().unwrap(), + next_hop: None, + }]; + + let negotiated = NegotiatedCapabilities { + families: HashSet::from([(Afi::Ipv4, Safi::Unicast)]), + asn4: true, + ..Default::default() + }; + let updates = build_announce_updates( + &prefixes, + "192.0.2.1".parse().unwrap(), + IpAddr::V4("192.0.2.1".parse().unwrap()), + 400644, + &negotiated, + ); + // RFC 6793: AS4-capable session carries AS_PATH (type 2) with + // 4-octet segments, one AS_SEQUENCE {400644} = 0x00061D04. + let (code, val) = as_path_attr(&updates[0], AsnLength::Bits32); + assert_eq!( + (code, val.as_slice()), + (2u8, &[2u8, 1, 0x00, 0x06, 0x1D, 0x04][..]) + ); + + // Plain 16-bit peer (e.g. local AS 65010): type 2 with 2-octet segments. + let plain = NegotiatedCapabilities { + families: HashSet::from([(Afi::Ipv4, Safi::Unicast)]), + asn4: false, + ..Default::default() + }; + let updates = build_announce_updates( + &prefixes, + "192.0.2.1".parse().unwrap(), + IpAddr::V4("192.0.2.1".parse().unwrap()), + 65010, + &plain, + ); + let (code, val) = as_path_attr(&updates[0], AsnLength::Bits16); + assert_eq!((code, val.as_slice()), (2u8, &[2u8, 1, 0xFD, 0xF2][..])); + } + #[test] fn local_open_advertises_dual_stack_as4_and_optional_route_refresh() { let BgpMessage::Open(open) = local_open(Ipv4Addr::new(192, 0, 2, 1), 65_536, 90, true) From a0310cbd3db3e24b2fecd0978edcf55431e6fc0d Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Fri, 11 Sep 2026 07:39:25 -0700 Subject: [PATCH 09/17] feat(prefix): runtime announce/withdraw via `focl prefix` Adds `focl prefix add|remove|list` to change the originated prefix set on a running daemon: updates are written straight into established sessions, with no restart and no session reset. The effective set is (config prefixes + runtime additions) minus runtime suppressions, so `prefix remove` on a configured prefix suppresses it and `prefix add` restores it. Runtime overrides stay in memory and are never written back to the config file. `focl reload` now re-reads the config file, applies the prefix delta (announce additions, withdraw removals) and clears runtime overrides, reporting the delta and how many overrides were reset. Peer and archive settings still require a restart, which the response states via `"scope": "prefixes"`. Address family is inferred from the prefix; `--next-hop` defaults to the configured next hop of the same family, and a mismatched family is rejected before any session write. `--dry-run` reports what would be sent without changing state and `--json` prints the raw control response. Sessions carry a per-session channel that the session loop selects alongside the socket read (split read/write halves); v4 updates use NEXT_HOP and withdrawn NLRI, v6 uses MP_REACH and MP_UNREACH. --- CHANGELOG.md | 9 + README.md | 6 + docs/prefix-control-prior-art.md | 63 ++ src/bgp/mod.rs | 958 +++++++++++++++++++++++++++---- src/bin/focl.rs | 187 ++++++ src/bin/focld.rs | 105 +++- src/control/mod.rs | 52 ++ 7 files changed, 1274 insertions(+), 106 deletions(-) create mode 100644 docs/prefix-control-prior-art.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c672cda..e437ff4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to this project will be documented in this file. ## Unreleased +### New features + +* **Runtime prefix control** - `focl prefix add|remove|list` announces or withdraws an originated prefix on the running daemon without restarting it or resetting any session. The effective set is (configured `[[prefixes]]` + runtime additions) minus runtime suppressions: `prefix remove` suppresses a configured prefix (a runtime-only one is dropped), `prefix add` announces it again and clears the suppression, and `prefix list` shows each prefix as `announced`/`suppressed` with a `config`/`runtime` source. Runtime overrides are in-memory only and are never written back to the config file. Address family is inferred from the prefix, `--next-hop` defaults to the configured next hop of the same family, `--dry-run` reports what would be sent without changing state, and `--json` prints the control response. +* **`focl reload` applies the config's prefix delta** - reload re-reads the config file, announces prefixes added since the last read, withdraws removed ones, and clears runtime overrides; the response reports the delta and how many overrides were reset. Peer and archive settings still require a restart. + +### Code improvements + +* Outbound route changes are dispatched to established sessions through a per-session channel, and the session loop now selects between that channel and the socket read on split read/write halves. Update encoding for both directions is shared with the establishment path (`emit_updates`). + ## v0.1.0 - 2025-02-21 ### New features diff --git a/README.md b/README.md index 7ba707a..c2be775 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ The project consists of: - [x] IPv4 and IPv6 unicast support - [x] TCP-MD5 authentication (RFC 2385) for BGP session security - [x] Static prefix announcements +- [x] Runtime prefix announce/withdraw via `focl prefix` (in-memory overrides) - [x] Full BGP FSM with proper timers (hold/keepalive) - [x] Active and passive peer modes - [x] Route refresh capability @@ -102,6 +103,11 @@ focl peer list focl peer show 192.0.2.2 focl rib summary focl rib out 192.0.2.2 + +# Runtime announce/withdraw (no restart, no session reset) +focl prefix list +focl prefix add 203.0.113.0/24 +focl prefix remove 203.0.113.0/24 ``` ## Example: Dual-Stack Configuration diff --git a/docs/prefix-control-prior-art.md b/docs/prefix-control-prior-art.md new file mode 100644 index 0000000..49c8bc7 --- /dev/null +++ b/docs/prefix-control-prior-art.md @@ -0,0 +1,63 @@ +# Prior art: runtime prefix announce/withdraw in software routers + +Compiled 2026-09-11 from primary sources (vendor docs, man pages, project docs/source). Purpose: fix +the CLI/control design for `focl prefix add|remove|list` on evidence rather than taste. Claims and +their URLs are in the survey notes below; anything not confirmed by a primary source is marked +UNVERIFIED. + +## Comparison + +| Implementation | Per-prefix runtime verb | Exact commands | Scope | Persistence | Ack / output | +|---|---|---|---|---|---| +| OpenBGPD | **yes** (`bgpctl network add|delete`, since OpenBSD 4.6) | `bgpctl network add 192.0.2.0/24 [localpref 200 community 64500:1]`; `bgpctl network delete 192.0.2.0/24`; `network show inet`; `network bulk add\|delete` (stdin); `network flush` | global list of originated networks; FILTER rules still apply per peer | runtime-only, not written to `bgpd.conf` | `bgpctl -j` JSON; announcement still subject to policy | +| GoBGP | **yes** (`gobgp global rib add|del`) | `gobgp global rib add 10.33.0.0/16 -a ipv4 [nexthop X med N community C aspath "..."]`; `gobgp global rib del [-a af]`; `del all` | global RIB or per-VRF; **no per-neighbor injection** (per-peer tailoring = policy); AF via `-a` flag only, default ipv4 | in-memory RIB; no config section for routes; re-add/inject after restart | table output; `-j/--json`; add/del print nothing on success; re-add = update, delete of absent = silent no-op (debug log); no dry-run | +| BIRD 2/3 | no verb; config-driven | static protocol route list + `birdc configure` (static protocol diffs in place, source-verified -> only that prefix's UPDATEs); `configure check`, `configure timeout N`, `configure confirm\|undo`; `reload filters in\|out`, `reload bgp out` (3.x) | per protocol/channel | config file is the only source of truth | no JSON (`birdc -v` numeric codes); `bird -p` validate-only; control protocol documented as stable/scriptable | +| FRR | no verb; config model | `conf t` -> `router bgp` -> `address-family` -> `network 203.0.113.0/24` / `no network ...` (immediate) | per process/AF; route-map decides per peer | running config volatile across restart -> `write file` / `vtysh -w`; `frr-reload.py` applies on-disk diff | `vtysh -c`, `-C` dry-run; append `json` for JSON; no confirm prompts | +| Junos | no verb; commit model | static route + export policy + `commit`; `commit check`, `commit confirmed N`, `rollback N`, `show\|compare` | policy maps per peer | commit **is** persistence; rollback files | `\| display json`; auto-rollback instead of prompts | +| RouterOS | no verb; config model | v7: address-list entry + `output.network=bgp-networks` (+ `output.network-blackhole`); needs a matching IGP route | per connection | persistent config (address-list `timeout` = RAM-only) | CLI/API/REST replies (`!done`/`!trap`); safe mode undoes on abnormal exit | +| ExaBGP | **yes** (text API over pipe) | `announce route 100.10.0.0/24 next-hop 192.0.2.1 [community ... as-path ... med ...]`; `withdraw route 100.10.0.0/24 [next-hop X]`; scoped via `neighbor [,]` or `neighbor *`; bulk/group forms | per neighbor via selectors | process-scoped; the API process must re-announce after restart | one ack per command (`done`/`error`/`shutdown`); group summary `group processed: N announced, M withdrawn`; mismatched withdraw = "Withdrawal doesn't match" | +| RustyBGP | yes (GoBGP-compatible gRPC + gobgp CLI) | same verbs as GoBGP | same as GoBGP | UNVERIFIED | same as GoBGP (UNVERIFIED for ack) | +| freeRtr | no verb; console config model | redistribution-driven: `conf t` -> `router bgp4 1` -> `no red conn` (withdraw) / `red conn` (announce); live, no session reset | per router VRF | UNVERIFIED | no machine-readable ack documented | + +## Design conclusions for focl + +1. **The capability is standard.** Two daemon+CLI implementations inject/withdraw prefixes at runtime + over a control channel (GoBGP `global rib add|del`, OpenBGPD `network add|delete`), and ExaBGP does + it over a pipe with an explicit ack per command. A runtime verb for focl is copying an established + pattern, not inventing one. +2. **Verb and noun.** `focl prefix add|remove|list` keeps focl's own vocabulary (`[[prefixes]]` in the + config) and its existing noun-group CLI style (`peer`, `rib`, `archive`). The closest precedent for + the semantics is OpenBGPD `network add|delete`; GoBGP `rib add|del` is the same shape with RIB + vocabulary. +3. **Address family is inferred from the prefix, not a flag.** GoBGP requires `-a` and rejects a + mismatched prefix; focl's config already infers family from the `network` value. Inference removes a + whole class of operator error. (Deliberate deviation, documented in `--help`.) +4. **Global scope in v1, no `--peer`.** Both GoBGP and OpenBGPD restrict runtime injection to the global + originated set and leave per-peer selection to policy; focl has no export-policy framework yet, so a + `--peer` flag would be a half-policy. Add it when policy exists. +5. **Runtime overrides are in-memory; `reload` resets them.** Matches GoBGP (in-memory RIB) and OpenBGPD + (dynamic entries never written to `bgpd.conf`). Must be stated in `--help` and docs so nobody expects + a runtime `remove` to survive a restart. +6. **Withdrawing a configured prefix is the point, not an error.** The demo (and normal ops) needs + "stop announcing what the config says": `prefix remove` on a config prefix suppresses it and sends + the withdraw; `prefix add` clears the suppression; `prefix list` shows `announced` / `suppressed` + plus the source (`config` / `runtime`). Mirrors OpenBGPD's single originated-network list. +7. **Ack like ExaBGP, not like GoBGP.** GoBGP prints nothing on success; ExaBGP returns one ack per + command and a summary for batches. For a demo and for scripting, print one line per command + (`announced 2620:aa:a000::/48 to 2 peers (v6)`), and keep exit 0 for a no-op (GoBGP treats a delete + of an absent prefix as a silent no-op; keep that, but say "no change"). +8. **Validation and machine-readable output are cheap wins.** Validate the prefix and next-hop family + before sending (`bgpd -n` / `bird -p` / `configure check` precedent), offer `--dry-run` to report + what would be sent, and offer `--json` for both `list` and the mutation results (GoBGP `-j`, + `bgpctl -j`, FRR `json` suffix). +9. **`remove all` (OpenBGPD `network flush` / GoBGP `del all`) is follow-up scope.** If added, it must + only touch locally-originated prefixes, never anything learned from a peer (GoBGP's documented guard). + +## Deliberately not copied + +- Per-neighbor runtime injection (ExaBGP selectors): needs the policy framework first (conclusion 4). +- Candidate/commit staging (Junos) and safe mode (RouterOS): focl is a single-process daemon with a + Unix socket, not an interactive console session; the equivalent guard is `--dry-run` plus the + `reload` reset, and `focl peer list`/`rib out` for verification. +- Config write-back: runtime commands never edit `focl.toml` (GoBGP/OpenBGPD behavior; keeps the config + file reviewable by hand). diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 7d0a884..fa80f8d 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::str::FromStr; use std::sync::Arc; @@ -14,9 +14,9 @@ use bytes::Bytes; use ipnet::IpNet; use ipnet_trie::IpnetTrie; use serde::{Deserialize, Serialize}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::net::{TcpListener, TcpSocket, TcpStream}; -use tokio::sync::{broadcast, RwLock}; +use tokio::sync::{broadcast, mpsc, RwLock}; use tokio::task::JoinHandle; use tokio::time::{sleep, timeout, Instant}; @@ -65,6 +65,261 @@ struct PrefixEntry { next_hop: Option, } +/// Where an originated prefix comes from: the config baseline or a runtime +/// `focl prefix add`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PrefixSource { + Config, + Runtime, +} + +/// Announced state of a prefix in the effective originated set. `Absent` only +/// appears in mutation results, where the prefix is no longer part of the set. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PrefixStatus { + Announced, + Suppressed, + Absent, +} + +/// One row of `focl prefix list`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PrefixView { + pub network: String, + pub family: String, + pub next_hop: Option, + pub status: PrefixStatus, + pub source: PrefixSource, +} + +/// Outcome of `focl prefix add` / `focl prefix remove`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PrefixMutation { + pub action: String, + pub network: String, + pub family: String, + pub status: PrefixStatus, + pub source: PrefixSource, + /// False when the effective originated set was already in the requested state. + pub changed: bool, + pub dry_run: bool, + /// Established sessions the update was dispatched to (empty on a no-op; + /// sessions filter by negotiated address family). + pub peers_notified: Vec, +} + +/// Outcome of a `reload` for the originated prefix set. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PrefixReload { + pub announced: Vec, + pub withdrawn: Vec, + pub overrides_reset: usize, + pub peers_notified: Vec, +} + +/// An outbound route change pushed into one established session. +#[derive(Debug, Clone)] +enum SessionOp { + Announce(PrefixEntry), + Withdraw { network: IpNet }, +} + +/// Runtime overrides layered over the configured prefix list. +/// +/// The config file stays the baseline; `added` and `suppressed` win until a +/// `reload` resets them. Runtime state is deliberately in-memory and never +/// written back to the config file, matching GoBGP's in-memory RIB and +/// OpenBGPD's dynamically added networks. +#[derive(Debug, Clone, Default)] +struct PrefixState { + config: Vec, + added: BTreeMap, + suppressed: BTreeSet, +} + +impl PrefixState { + fn new(config: Vec) -> Self { + Self { + config, + added: BTreeMap::new(), + suppressed: BTreeSet::new(), + } + } + + fn override_count(&self) -> usize { + self.added.len() + self.suppressed.len() + } + + /// The set that is actually announced: (config + added) - suppressed. + fn effective(&self) -> Vec { + let mut entries: Vec = self + .config + .iter() + .filter(|entry| !self.suppressed.contains(&entry.network)) + .cloned() + .collect(); + for (network, entry) in &self.added { + if self.suppressed.contains(network) || entries.iter().any(|e| e.network == *network) { + continue; + } + entries.push(entry.clone()); + } + entries + } + + fn is_known(&self, network: &IpNet) -> bool { + self.added.contains_key(network) || self.config.iter().any(|e| e.network == *network) + } + + fn is_announced(&self, network: &IpNet) -> bool { + self.is_known(network) && !self.suppressed.contains(network) + } + + fn status_of(&self, network: &IpNet) -> PrefixStatus { + if self.is_announced(network) { + PrefixStatus::Announced + } else if self.is_known(network) { + PrefixStatus::Suppressed + } else { + PrefixStatus::Absent + } + } + + fn source_of(&self, network: &IpNet) -> PrefixSource { + if self.added.contains_key(network) { + PrefixSource::Runtime + } else { + PrefixSource::Config + } + } + + fn default_next_hop(&self, network: &IpNet) -> Option { + let wants_v4 = matches!(network, IpNet::V4(_)); + self.config + .iter() + .chain(self.added.values()) + .filter_map(|entry| entry.next_hop) + .find(|address| address.is_ipv4() == wants_v4) + } + + fn view(&self) -> Vec { + let mut rows: Vec = self + .config + .iter() + .map(|entry| self.view_of(entry, PrefixSource::Config)) + .collect(); + for (network, entry) in &self.added { + if self.config.iter().any(|e| e.network == *network) { + continue; + } + rows.push(self.view_of(entry, PrefixSource::Runtime)); + } + rows + } + + fn view_of(&self, entry: &PrefixEntry, source: PrefixSource) -> PrefixView { + PrefixView { + network: entry.network.to_string(), + family: family_name(&entry.network), + next_hop: entry.next_hop.map(|address| address.to_string()), + status: if self.suppressed.contains(&entry.network) { + PrefixStatus::Suppressed + } else { + PrefixStatus::Announced + }, + source, + } + } + + /// Records a runtime addition (or clears an earlier suppression). Returns + /// whether the effective originated set changed. + fn add(&mut self, entry: PrefixEntry) -> bool { + let network = entry.network; + let was_announced = self.is_announced(&network); + self.suppressed.remove(&network); + if self.added.contains_key(&network) || !self.config.iter().any(|e| e.network == network) { + self.added.insert(network, entry); + } + !was_announced + } + + /// Withdraws a prefix: a runtime-only entry is dropped, a configured one is + /// suppressed. Returns whether the effective originated set changed. + fn remove(&mut self, network: &IpNet) -> bool { + let was_announced = self.is_announced(network); + if self.added.remove(network).is_some() { + return was_announced; + } + if self.config.iter().any(|e| e.network == *network) { + self.suppressed.insert(*network); + } + was_announced + } + + /// Replaces the config baseline and drops every runtime override, returning + /// the prefixes to announce and to withdraw. + fn reset_overrides(&mut self, config: Vec) -> (Vec, Vec) { + let before = self.effective(); + self.config = config; + self.added.clear(); + self.suppressed.clear(); + let after = self.effective(); + let announce = after + .iter() + .filter(|entry| !before.iter().any(|old| old.network == entry.network)) + .cloned() + .collect(); + let withdraw = before + .iter() + .filter(|entry| !after.iter().any(|new| new.network == entry.network)) + .map(|entry| entry.network) + .collect(); + (announce, withdraw) + } +} + +fn family_name(network: &IpNet) -> String { + match network { + IpNet::V4(_) => "v4", + IpNet::V6(_) => "v6", + } + .to_string() +} + +/// Parses the configured `[[prefixes]]` list into the baseline entry set. +fn parse_prefix_entries(cfg: &FoclConfig) -> Result> { + cfg.prefixes + .iter() + .map(|p| { + let network = IpNet::from_str(&p.network) + .with_context(|| format!("invalid prefix network: {}", p.network))?; + let next_hop = p + .next_hop + .as_ref() + .map(|nh| nh.parse::()) + .transpose() + .with_context(|| format!("invalid next-hop address: {:?}", p.next_hop))?; + Ok::<_, anyhow::Error>(PrefixEntry { network, next_hop }) + }) + .collect::, _>>() + .context("invalid prefix in config") +} + +fn ensure_next_hop_family(network: &IpNet, next_hop: IpAddr) -> Result<()> { + let matches_family = matches!( + (network, next_hop), + (IpNet::V4(_), IpAddr::V4(_)) | (IpNet::V6(_), IpAddr::V6(_)) + ); + if matches_family { + return Ok(()); + } + Err(anyhow!( + "next hop {next_hop} does not match the prefix family of {network}" + )) +} + /// A deliberately owned, uninterned v1 Adj-RIB-In value. Attribute interning is /// deferred until the collector's memory profile is measured under real feeds. #[derive(Debug, Clone)] @@ -97,7 +352,10 @@ impl NegotiatedCapabilities { struct BgpServiceInner { global_asn: u32, router_id: Ipv4Addr, - prefixes: Vec, + /// Effective originated prefixes: config baseline plus runtime overrides. + prefix_state: RwLock, + /// Established sessions that accept runtime route changes, keyed by peer address. + session_ops: RwLock>>, peers: RwLock>, rib_in: RwLock>>, session_local_ips: RwLock>, @@ -133,26 +391,12 @@ impl BgpService { .router_id .parse::() .context("global.router_id must be IPv4")?; - let prefixes = cfg - .prefixes - .iter() - .map(|p| { - let network = IpNet::from_str(&p.network) - .with_context(|| format!("invalid prefix network: {}", p.network))?; - let next_hop = p - .next_hop - .as_ref() - .map(|nh| nh.parse::()) - .transpose() - .with_context(|| format!("invalid next-hop address: {:?}", p.next_hop))?; - Ok::<_, anyhow::Error>(PrefixEntry { network, next_hop }) - }) - .collect::, _>>() - .context("invalid prefix in config")?; + let prefixes = parse_prefix_entries(cfg)?; let inner = Arc::new(BgpServiceInner { global_asn: cfg.global.asn, router_id, - prefixes, + prefix_state: RwLock::new(PrefixState::new(prefixes)), + session_ops: RwLock::new(HashMap::new()), peers: RwLock::new(HashMap::new()), rib_in: RwLock::new(HashMap::new()), session_local_ips: RwLock::new(HashMap::new()), @@ -340,6 +584,31 @@ impl BgpService { .write() .await .insert(peer.address.clone(), local_ip); + // Runtime route changes reach a session only while it is established; + // the receiver is polled from the session loop below. + let (ctrl_tx, ctrl_rx) = mpsc::channel::(64); + self.inner + .session_ops + .write() + .await + .insert(peer.address.clone(), ctrl_tx); + let result = self + .run_session_inner(peer, stream, local_ip, ctrl_rx) + .await; + self.inner.session_ops.write().await.remove(&peer.address); + result + } + + async fn run_session_inner( + &self, + peer: &PeerConfig, + stream: &mut TcpStream, + local_ip: IpAddr, + mut ctrl_rx: mpsc::Receiver, + ) -> Result<()> { + // Split halves let the session write keepalives and runtime updates + // while a read is concurrently outstanding inside `select!`. + let (mut reader, mut writer) = stream.split(); self.set_peer_state(&peer.address, PeerState::OpenSent, None, None) .await; @@ -351,9 +620,9 @@ impl BgpService { hold_time, peer.route_refresh, ); - write_bgp_message(stream, &open, AsnLength::Bits32).await?; + write_bgp_message(&mut writer, &open, AsnLength::Bits32).await?; - let incoming = read_bgp_message(stream).await?; + let incoming = read_bgp_message(&mut reader).await?; let BgpMessage::Open(remote_open) = incoming.message else { return Err(anyhow!("expected OPEN from peer")); }; @@ -362,8 +631,8 @@ impl BgpService { self.set_peer_state(&peer.address, PeerState::OpenConfirm, None, None) .await; - write_bgp_message(stream, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; - let incoming = read_bgp_message(stream).await?; + write_bgp_message(&mut writer, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; + let incoming = read_bgp_message(&mut reader).await?; if !matches!(incoming.message, BgpMessage::KeepAlive) { return Err(anyhow!("expected KEEPALIVE from peer after OPEN")); } @@ -375,7 +644,7 @@ impl BgpService { Some(chrono::Utc::now().timestamp()), ) .await; - self.send_prefix_announcements(peer, stream, &negotiated) + self.send_prefix_announcements(peer, &mut writer, &negotiated, local_ip) .await?; // RFC 4271 End-of-RIB: an empty UPDATE per family marks the initial // table transfer complete. Vultr's route servers treat a session @@ -409,7 +678,7 @@ impl BgpService { } else { AsnLength::Bits16 }; - write_bgp_message(stream, &eor, asn_len).await?; + write_bgp_message(&mut writer, &eor, asn_len).await?; } } @@ -420,7 +689,7 @@ impl BgpService { loop { let now = Instant::now(); if now >= next_keepalive { - write_bgp_message(stream, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; + write_bgp_message(&mut writer, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; next_keepalive = now + keepalive_interval; } if now >= hold_deadline { @@ -430,31 +699,136 @@ impl BgpService { next_keepalive.saturating_duration_since(now), Duration::from_secs(1), ); - match timeout(timeout_dur, read_bgp_message(stream)).await { - Ok(Ok(incoming)) => match incoming.message { - BgpMessage::Update(update) => { - self.ingest_received_update( - peer, - local_as, - local_ip, - update, - incoming.raw, - &negotiated, - ) - .await?; - hold_deadline = Instant::now() + negotiated_hold; - } - BgpMessage::KeepAlive | BgpMessage::Open(_) | BgpMessage::RouteRefresh(_) => { - hold_deadline = Instant::now() + negotiated_hold; + // Runtime announce/withdraw commands are applied between reads; the + // read future is cancel-safe against this branch because both + // borrow separate halves of the socket. + tokio::select! { + biased; + op = ctrl_rx.recv() => { + if let Some(op) = op { + self.apply_session_op(peer, &mut writer, &negotiated, local_ip, op) + .await?; } - BgpMessage::Notification(_) => { - return Err(anyhow!("received NOTIFICATION from peer")) + } + result = timeout(timeout_dur, read_bgp_message(&mut reader)) => { + match result { + Ok(Ok(incoming)) => match incoming.message { + BgpMessage::Update(update) => { + self.ingest_received_update( + peer, + local_as, + local_ip, + update, + incoming.raw, + &negotiated, + ) + .await?; + hold_deadline = Instant::now() + negotiated_hold; + } + BgpMessage::KeepAlive + | BgpMessage::Open(_) + | BgpMessage::RouteRefresh(_) => { + hold_deadline = Instant::now() + negotiated_hold; + } + BgpMessage::Notification(_) => { + return Err(anyhow!("received NOTIFICATION from peer")) + } + }, + Ok(Err(error)) => return Err(error), + Err(_) => {} } - }, - Ok(Err(error)) => return Err(error), - Err(_) => {} + } + } + } + } + + /// Applies one runtime route change to this session: build, write, archive, + /// then refresh the advertised-prefix count for the peer. + async fn apply_session_op( + &self, + peer: &PeerConfig, + writer: &mut W, + negotiated: &NegotiatedCapabilities, + local_ip: IpAddr, + op: SessionOp, + ) -> Result<()> { + let local_as = peer.local_as.unwrap_or(self.inner.global_asn); + let updates = match &op { + SessionOp::Announce(entry) => build_announce_updates( + std::slice::from_ref(entry), + self.inner.router_id, + local_ip, + local_as, + negotiated, + ), + SessionOp::Withdraw { network } => { + build_withdraw_updates(std::slice::from_ref(network), negotiated) + } + }; + self.emit_updates(peer, writer, negotiated, local_ip, local_as, updates) + .await?; + self.refresh_advertised_count(peer, local_ip, local_as, negotiated) + .await; + Ok(()) + } + + /// Recomputes how many announcements this session currently carries. + async fn refresh_advertised_count( + &self, + peer: &PeerConfig, + local_ip: IpAddr, + local_as: u32, + negotiated: &NegotiatedCapabilities, + ) { + let prefixes = self.inner.prefix_state.read().await.effective(); + let advertised = build_announce_updates( + &prefixes, + self.inner.router_id, + local_ip, + local_as, + negotiated, + ) + .len(); + let mut peers = self.inner.peers.write().await; + if let Some(runtime) = peers.get_mut(&peer.address) { + runtime.info.advertised_prefixes = advertised; + } + } + + /// Writes updates to one session and mirrors them into the archive. The + /// archive is receive-only for a collector, so our own announcements are + /// recorded here to keep a self-contained lab archive complete. + async fn emit_updates( + &self, + peer: &PeerConfig, + writer: &mut W, + negotiated: &NegotiatedCapabilities, + local_ip: IpAddr, + local_as: u32, + updates: Vec, + ) -> Result<()> { + let asn_len = if negotiated.asn4 { + AsnLength::Bits32 + } else { + AsnLength::Bits16 + }; + for update in updates { + let raw = write_bgp_message(writer, &update, asn_len).await?; + if let Some(archive) = &self.inner.archive { + archive + .ingest_update(UpdateRecordInput { + timestamp: chrono::Utc::now().timestamp(), + peer_ip: peer.address.parse().context("invalid configured peer IP")?, + peer_asn: peer.remote_as, + local_ip, + local_asn: local_as, + interface_index: 0, + bgp_message: raw, + }) + .await?; } } + Ok(()) } async fn ingest_received_update( @@ -540,47 +914,28 @@ impl BgpService { } } - async fn send_prefix_announcements( + async fn send_prefix_announcements( &self, peer: &PeerConfig, - stream: &mut TcpStream, + writer: &mut W, negotiated: &NegotiatedCapabilities, + local_ip: IpAddr, ) -> Result<()> { let local_as = peer.local_as.unwrap_or(self.inner.global_asn); - let local_ip = stream.local_addr()?.ip(); - for update in build_announce_updates( - &self.inner.prefixes, + let prefixes = self.inner.prefix_state.read().await.effective(); + let updates = build_announce_updates( + &prefixes, self.inner.router_id, local_ip, local_as, negotiated, - ) { - let asn_len = if negotiated.asn4 { - AsnLength::Bits32 - } else { - AsnLength::Bits16 - }; - let raw = write_bgp_message(stream, &update, asn_len).await?; - // Keep the collector's configured-prefix baseline alongside the - // received feed; it lets a self-contained lab archive replay both - // sides of this peering session. - if let Some(archive) = &self.inner.archive { - archive - .ingest_update(UpdateRecordInput { - timestamp: chrono::Utc::now().timestamp(), - peer_ip: peer.address.parse().context("invalid configured peer IP")?, - peer_asn: peer.remote_as, - local_ip, - local_asn: local_as, - interface_index: 0, - bgp_message: raw, - }) - .await?; - } - } + ); + let advertised = updates.len(); + self.emit_updates(peer, writer, negotiated, local_ip, local_as, updates) + .await?; let mut peers = self.inner.peers.write().await; if let Some(runtime) = peers.get_mut(&peer.address) { - runtime.info.advertised_prefixes = self.inner.prefixes.len(); + runtime.info.advertised_prefixes = advertised; } Ok(()) } @@ -708,6 +1063,155 @@ impl BgpService { Ok(()) } + /// Effective originated prefix set with provenance and status. + pub async fn prefix_view(&self) -> Vec { + self.inner.prefix_state.read().await.view() + } + + /// Announces (or re-announces) a prefix at runtime and pushes the update to + /// every established session. + pub async fn prefix_add( + &self, + network: IpNet, + next_hop: Option, + dry_run: bool, + ) -> Result { + if let Some(next_hop) = next_hop { + ensure_next_hop_family(&network, next_hop)?; + } + let entry = { + let state = self.inner.prefix_state.read().await; + PrefixEntry { + network, + next_hop: next_hop.or_else(|| state.default_next_hop(&network)), + } + }; + // A dry run reports what would happen without touching the state. + let changed = if dry_run { + !self.inner.prefix_state.read().await.is_announced(&network) + } else { + self.inner.prefix_state.write().await.add(entry.clone()) + }; + let peers_notified = if !changed { + Vec::new() + } else if dry_run { + self.session_targets().await + } else { + self.dispatch_session_op(SessionOp::Announce(entry)).await + }; + let state = self.inner.prefix_state.read().await; + Ok(PrefixMutation { + action: "announce".to_string(), + network: network.to_string(), + family: family_name(&network), + status: state.status_of(&network), + source: state.source_of(&network), + changed, + dry_run, + peers_notified, + }) + } + + /// Withdraws a prefix at runtime: a configured prefix is suppressed, a + /// runtime-only one is dropped. + pub async fn prefix_remove(&self, network: IpNet, dry_run: bool) -> Result { + let changed = if dry_run { + self.inner.prefix_state.read().await.is_announced(&network) + } else { + self.inner.prefix_state.write().await.remove(&network) + }; + let peers_notified = if !changed { + Vec::new() + } else if dry_run { + self.session_targets().await + } else { + self.dispatch_session_op(SessionOp::Withdraw { network }) + .await + }; + let state = self.inner.prefix_state.read().await; + Ok(PrefixMutation { + action: "withdraw".to_string(), + network: network.to_string(), + family: family_name(&network), + status: state.status_of(&network), + source: state.source_of(&network), + changed, + dry_run, + peers_notified, + }) + } + + /// Re-reads the configured prefix list, applies the delta, and clears every + /// runtime override. Peer sessions and other config sections are untouched. + pub async fn reload_prefixes(&self, cfg: &FoclConfig) -> Result { + let entries = parse_prefix_entries(cfg)?; + let (announce, withdraw, overrides_reset) = { + let mut state = self.inner.prefix_state.write().await; + let overrides_reset = state.override_count(); + let (announce, withdraw) = state.reset_overrides(entries); + (announce, withdraw, overrides_reset) + }; + let mut peers_notified = Vec::new(); + for entry in announce.iter() { + peers_notified.extend( + self.dispatch_session_op(SessionOp::Announce(entry.clone())) + .await, + ); + } + for network in withdraw.iter() { + peers_notified.extend( + self.dispatch_session_op(SessionOp::Withdraw { network: *network }) + .await, + ); + } + peers_notified.sort(); + peers_notified.dedup(); + Ok(PrefixReload { + announced: announce + .iter() + .map(|entry| entry.network.to_string()) + .collect(), + withdrawn: withdraw.iter().map(|network| network.to_string()).collect(), + overrides_reset, + peers_notified, + }) + } + + /// Dispatches one route change to every established session, returning the + /// peers whose session accepted it. + async fn dispatch_session_op(&self, op: SessionOp) -> Vec { + let senders: Vec<(String, mpsc::Sender)> = self + .inner + .session_ops + .read() + .await + .iter() + .map(|(peer, sender)| (peer.clone(), sender.clone())) + .collect(); + let mut notified = Vec::new(); + for (peer, sender) in senders { + if sender.send(op.clone()).await.is_ok() { + notified.push(peer); + } + } + notified.sort(); + notified + } + + /// Established sessions without dispatching anything (`--dry-run`). + async fn session_targets(&self) -> Vec { + let mut targets: Vec = self + .inner + .session_ops + .read() + .await + .keys() + .cloned() + .collect(); + targets.sort(); + targets + } + pub async fn rib_summary(&self) -> RibSummary { let peers = self.inner.peers.read().await; RibSummary { @@ -729,7 +1233,10 @@ impl BgpService { } Ok(self .inner - .prefixes + .prefix_state + .read() + .await + .effective() .iter() .map(|prefix| prefix.network.to_string()) .collect()) @@ -909,6 +1416,56 @@ fn build_announce_updates( result } +/// Builds the withdrawal updates for one family set. IPv4 withdrawals use the +/// classic withdrawn-NLRI field; IPv6 withdrawals use MP_UNREACH. +fn build_withdraw_updates( + networks: &[IpNet], + negotiated: &NegotiatedCapabilities, +) -> Vec { + let mut result = Vec::new(); + let classic_ipv4_ok = negotiated.plain_ipv4() || negotiated.supports(Afi::Ipv4, Safi::Unicast); + let v4: Vec = networks + .iter() + .filter(|network| matches!(network, IpNet::V4(_))) + .map(|network| NetworkPrefix::new(*network, None)) + .collect(); + if classic_ipv4_ok && !v4.is_empty() { + result.push(BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: v4, + attributes: Attributes::default(), + announced_prefixes: vec![], + })); + } + if negotiated.supports(Afi::Ipv6, Safi::Unicast) { + let v6: Vec = networks + .iter() + .filter(|network| matches!(network, IpNet::V6(_))) + .map(|network| NetworkPrefix::new(*network, None)) + .collect(); + if !v6.is_empty() { + let mut attrs = Attributes::default(); + attrs.add_attr( + AttributeValue::MpUnreachNlri(Nlri { + afi: Afi::Ipv6, + safi: Safi::Unicast, + next_hop: None, + prefixes: v6, + labeled_prefixes: None, + link_state_nlris: None, + flowspec_nlris: None, + }) + .into(), + ); + result.push(BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![], + })); + } + } + result +} + fn base_announce_attributes(local_as: u32) -> Attributes { let mut attrs = Attributes::default(); attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); @@ -986,8 +1543,8 @@ fn normalize_socket_addr(raw: &str, default_port: u16) -> Result { Ok(SocketAddr::new(address, default_port)) } -async fn write_bgp_message( - stream: &mut TcpStream, +async fn write_bgp_message( + stream: &mut W, message: &BgpMessage, asn_len: AsnLength, ) -> Result> { @@ -1003,7 +1560,7 @@ async fn write_bgp_message( Ok(bytes) } -async fn read_bgp_message(stream: &mut TcpStream) -> Result { +async fn read_bgp_message(stream: &mut R) -> Result { let mut header = [0u8; 19]; stream.read_exact(&mut header).await?; if header[0..16] != [0xff; 16] { @@ -1119,29 +1676,226 @@ mod tests { } #[test] - fn v6_announcements_use_mp_reach_not_classic_nlri() { - let prefixes = vec![PrefixEntry { - network: "2001:db8::/32".parse().unwrap(), - next_hop: Some("2001:db8::1".parse().unwrap()), - }]; - let mut negotiated = NegotiatedCapabilities::default(); - negotiated.families.insert((Afi::Ipv6, Safi::Unicast)); - let updates = build_announce_updates( - &prefixes, + fn prefix_state_layers_runtime_overrides_over_config() { + let config = vec![ + PrefixEntry { + network: "192.0.2.0/24".parse().unwrap(), + next_hop: Some("192.0.2.1".parse().unwrap()), + }, + PrefixEntry { + network: "2001:db8::/48".parse().unwrap(), + next_hop: None, + }, + ]; + let v6: IpNet = "2001:db8::/48".parse().unwrap(); + let mut state = PrefixState::new(config); + + // Suppressing a configured prefix withdraws it from the effective set. + assert!(state.remove(&v6)); + assert_eq!(state.effective().len(), 1); + assert_eq!(state.status_of(&v6), PrefixStatus::Suppressed); + assert_eq!(state.source_of(&v6), PrefixSource::Config); + // Removing it again changes nothing. + assert!(!state.remove(&v6)); + + // Re-adding restores the config entry without duplicating it. + assert!(state.add(PrefixEntry { + network: v6, + next_hop: None, + })); + assert_eq!(state.effective().len(), 2); + assert_eq!(state.override_count(), 0); + + // A runtime-only entry is added and dropped without residue. + let runtime_only: IpNet = "198.51.100.0/24".parse().unwrap(); + assert!(state.add(PrefixEntry { + network: runtime_only, + next_hop: None, + })); + assert_eq!(state.source_of(&runtime_only), PrefixSource::Runtime); + assert_eq!(state.status_of(&runtime_only), PrefixStatus::Announced); + assert!(state.remove(&runtime_only)); + assert_eq!(state.status_of(&runtime_only), PrefixStatus::Absent); + assert_eq!(state.override_count(), 0); + } + + #[test] + fn reload_resets_overrides_and_reports_the_delta() { + let suppressed: IpNet = "192.0.2.0/24".parse().unwrap(); + let runtime_only: IpNet = "198.51.100.0/24".parse().unwrap(); + let mut state = PrefixState::new(vec![PrefixEntry { + network: suppressed, + next_hop: None, + }]); + assert!(state.remove(&suppressed)); + assert!(state.add(PrefixEntry { + network: runtime_only, + next_hop: None, + })); + + let added: IpNet = "203.0.113.0/24".parse().unwrap(); + let (announce, withdraw) = state.reset_overrides(vec![PrefixEntry { + network: added, + next_hop: None, + }]); + + assert_eq!( + announce + .iter() + .map(|entry| entry.network.to_string()) + .collect::>(), + vec!["203.0.113.0/24"] + ); + // The suppressed config prefix was not announced before the reload, so + // only the runtime addition needs withdrawing. + assert_eq!( + withdraw + .iter() + .map(|network| network.to_string()) + .collect::>(), + vec!["198.51.100.0/24"] + ); + assert_eq!(state.override_count(), 0); + } + + #[test] + fn reload_re_announces_a_suppressed_prefix() { + let entry = PrefixEntry { + network: "2620:aa:a000::/48".parse().unwrap(), + next_hop: None, + }; + let mut state = PrefixState::new(vec![entry.clone()]); + assert!(state.remove(&entry.network)); + assert!(state.effective().is_empty()); + + // An unchanged config re-announces what the operator suppressed. + let (announce, withdraw) = state.reset_overrides(vec![entry.clone()]); + assert_eq!(announce.len(), 1); + assert!(withdraw.is_empty()); + assert_eq!(state.status_of(&entry.network), PrefixStatus::Announced); + } + + #[test] + fn withdraw_updates_use_withdrawn_nlri_for_v4_and_mp_unreach_for_v6() { + let networks: Vec = vec![ + "192.0.2.0/24".parse().unwrap(), + "2001:db8::/48".parse().unwrap(), + ]; + let negotiated = NegotiatedCapabilities { + families: HashSet::from([(Afi::Ipv4, Safi::Unicast), (Afi::Ipv6, Safi::Unicast)]), + ..Default::default() + }; + let updates = build_withdraw_updates(&networks, &negotiated); + assert_eq!(updates.len(), 2); + + let BgpMessage::Update(v4) = &updates[0] else { + panic!("not an UPDATE") + }; + assert_eq!(v4.withdrawn_prefixes.len(), 1); + assert_eq!(v4.withdrawn_prefixes[0].prefix.to_string(), "192.0.2.0/24"); + assert!(v4.announced_prefixes.is_empty()); + + let BgpMessage::Update(v6) = &updates[1] else { + panic!("not an UPDATE") + }; + assert!(v6.withdrawn_prefixes.is_empty()); + let unreach = v6 + .attributes + .get_unreachable_nlri() + .expect("MP_UNREACH present"); + assert_eq!(unreach.afi, Afi::Ipv6); + assert_eq!(unreach.prefixes.len(), 1); + assert_eq!(unreach.prefixes[0].prefix.to_string(), "2001:db8::/48"); + } + + #[test] + fn withdraw_and_announce_respect_negotiated_families() { + let v6: IpNet = "2001:db8::/48".parse().unwrap(); + let v4_only = NegotiatedCapabilities { + families: HashSet::from([(Afi::Ipv4, Safi::Unicast)]), + ..Default::default() + }; + assert!(build_withdraw_updates(&[v6], &v4_only).is_empty()); + assert!(build_announce_updates( + &[PrefixEntry { + network: v6, + next_hop: None, + }], Ipv4Addr::new(192, 0, 2, 1), - "2001:db8::2".parse().unwrap(), + "192.0.2.2".parse().unwrap(), 65_001, - &negotiated, + &v4_only, + ) + .is_empty()); + } + + #[test] + fn next_hop_family_mismatch_is_rejected() { + let v6: IpNet = "2001:db8::/48".parse().unwrap(); + assert!(ensure_next_hop_family(&v6, "192.0.2.1".parse().unwrap()).is_err()); + assert!(ensure_next_hop_family(&v6, "2001:db8::1".parse().unwrap()).is_ok()); + } + + fn test_service_config() -> FoclConfig { + toml::from_str( + r#" +[global] +asn = 65001 +router_id = "10.0.0.1" +listen = false +control_socket = "/tmp/focl-test-only.sock" + +[archive] +enabled = false +"#, + ) + .expect("test config parses") + } + + #[tokio::test] + async fn dry_run_reports_without_changing_state() { + let cfg = test_service_config(); + let (event_tx, _) = broadcast::channel::(4); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + let network: IpNet = "192.0.2.0/24".parse().unwrap(); + + let dry_add = service.prefix_add(network, None, true).await.unwrap(); + assert!(dry_add.changed && dry_add.dry_run); + assert!( + service.prefix_view().await.is_empty(), + "a dry run must not originate the prefix" ); - let BgpMessage::Update(update) = &updates[0] else { - panic!() - }; - assert!(update.announced_prefixes.is_empty()); + + let applied = service.prefix_add(network, None, false).await.unwrap(); + assert!(applied.changed && !applied.dry_run); + assert_eq!(service.prefix_view().await.len(), 1); + + let dry_remove = service.prefix_remove(network, true).await.unwrap(); + assert!(dry_remove.changed && dry_remove.dry_run); assert_eq!( - update.attributes.get_reachable_nlri().unwrap().prefixes[0] - .prefix - .to_string(), - "2001:db8::/32" + service.prefix_view().await.len(), + 1, + "a dry run must not withdraw the prefix" ); + + let removed = service.prefix_remove(network, false).await.unwrap(); + assert!(removed.changed); + assert!(service.prefix_view().await.is_empty()); + } + + #[tokio::test] + async fn prefix_add_rejects_a_mismatched_next_hop() { + let cfg = test_service_config(); + let (event_tx, _) = broadcast::channel::(4); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + let network: IpNet = "2001:db8::/48".parse().unwrap(); + let error = service + .prefix_add(network, Some("192.0.2.1".parse().unwrap()), false) + .await + .expect_err("IPv4 next hop on an IPv6 prefix must be rejected"); + assert!(error + .to_string() + .contains("does not match the prefix family")); + assert!(service.prefix_view().await.is_empty()); } } diff --git a/src/bin/focl.rs b/src/bin/focl.rs index 4880bfc..abb06f4 100644 --- a/src/bin/focl.rs +++ b/src/bin/focl.rs @@ -3,6 +3,7 @@ use std::process::Stdio; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; +use focl::bgp::{PrefixMutation, PrefixSource, PrefixStatus, PrefixView}; use focl::types::{ControlRequest, ControlResponse}; use serde_json::json; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; @@ -34,6 +35,12 @@ enum Commands { #[command(subcommand)] command: RibCommands, }, + /// Runtime announce/withdraw of originated prefixes (in-memory overrides; + /// `reload` resets them to the config file) + Prefix { + #[command(subcommand)] + command: PrefixCommands, + }, Archive { #[command(subcommand)] command: ArchiveCommands, @@ -54,6 +61,43 @@ enum RibCommands { Out { peer: String }, } +#[derive(Debug, Subcommand)] +enum PrefixCommands { + /// Announce a prefix now (no session reset); also clears a suppression + Add { + /// Network in CIDR notation, e.g. 2620:aa:a000::/48 + network: String, + /// Next hop for the announcement. Defaults to the configured next hop + /// of the same family, else the session's own address + #[arg(long)] + next_hop: Option, + /// Validate and report what would be sent without sending it + #[arg(long)] + dry_run: bool, + /// Print the raw control response as JSON + #[arg(long)] + json: bool, + }, + /// Withdraw a prefix now: a configured prefix is suppressed, a + /// runtime-only one is dropped + Remove { + /// Network in CIDR notation + network: String, + /// Validate and report what would be sent without sending it + #[arg(long)] + dry_run: bool, + /// Print the raw control response as JSON + #[arg(long)] + json: bool, + }, + /// Show the effective originated prefix set (config plus runtime overrides) + List { + /// Print the raw control response as JSON + #[arg(long)] + json: bool, + }, +} + #[derive(Debug, Subcommand)] enum ArchiveCommands { Status, @@ -123,6 +167,44 @@ async fn main() -> Result<()> { print_response(response); } }, + Commands::Prefix { command } => match command { + PrefixCommands::Add { + network, + next_hop, + dry_run, + json, + } => { + let response = send_control_request( + &cli.socket, + "prefix_add", + json!({"network": network, "next_hop": next_hop, "dry_run": dry_run}), + ) + .await?; + finish_prefix_response(response, json)?; + } + PrefixCommands::Remove { + network, + dry_run, + json, + } => { + let response = send_control_request( + &cli.socket, + "prefix_remove", + json!({"network": network, "dry_run": dry_run}), + ) + .await?; + finish_prefix_response(response, json)?; + } + PrefixCommands::List { json } => { + let response = send_control_request(&cli.socket, "prefix_list", json!({})).await?; + if json { + print_response(response); + } else { + fail_on_error(&response)?; + print_prefix_list(&response)?; + } + } + }, Commands::Archive { command } => match command { ArchiveCommands::Status => { let response = @@ -211,3 +293,108 @@ fn print_response(response: ControlResponse) { serde_json::to_string_pretty(&response).unwrap_or_else(|_| "{}".to_string()) ); } + +fn fail_on_error(response: &ControlResponse) -> Result<()> { + if response.ok { + return Ok(()); + } + match &response.error { + Some(error) => eprintln!("error: {} ({})", error.message, error.code), + None => eprintln!("error: control request failed"), + } + std::process::exit(1); +} + +/// One-line result for `prefix add` / `prefix remove`, or the raw response +/// with `--json`. +fn finish_prefix_response(response: ControlResponse, json: bool) -> Result<()> { + if json { + print_response(response); + return Ok(()); + } + fail_on_error(&response)?; + let mutation: PrefixMutation = serde_json::from_value(response.result.unwrap_or_default())?; + let peers = mutation.peers_notified.len(); + let peer_list = if mutation.peers_notified.is_empty() { + String::new() + } else { + format!(": {}", mutation.peers_notified.join(", ")) + }; + if mutation.dry_run { + if mutation.changed { + println!( + "dry-run: would {} {} ({}) to {} established peer(s){}", + mutation.action, mutation.network, mutation.family, peers, peer_list + ); + } else { + println!( + "dry-run: no change for {} ({})", + mutation.network, mutation.family + ); + } + } else if mutation.changed { + let verb = if mutation.action == "announce" { + "announced" + } else { + "withdrew" + }; + println!( + "{} {} ({}) to {} established peer(s){}", + verb, mutation.network, mutation.family, peers, peer_list + ); + } else { + println!( + "no change: {} ({}) is already {}", + mutation.network, + mutation.family, + status_word(mutation.status) + ); + } + Ok(()) +} + +fn print_prefix_list(response: &ControlResponse) -> Result<()> { + let result = response.result.clone().unwrap_or_default(); + let prefixes: Vec = + serde_json::from_value(result.get("prefixes").cloned().unwrap_or_default())?; + if prefixes.is_empty() { + println!("no originated prefixes"); + return Ok(()); + } + let network_width = prefixes + .iter() + .map(|prefix| prefix.network.len()) + .max() + .unwrap_or(0) + .max("NETWORK".len()); + println!( + "{: &'static str { + match status { + PrefixStatus::Announced => "announced", + PrefixStatus::Suppressed => "suppressed", + PrefixStatus::Absent => "absent", + } +} + +fn source_word(source: PrefixSource) -> &'static str { + match source { + PrefixSource::Config => "config", + PrefixSource::Runtime => "runtime", + } +} diff --git a/src/bin/focld.rs b/src/bin/focld.rs index e304fe0..3fd0aef 100644 --- a/src/bin/focld.rs +++ b/src/bin/focld.rs @@ -1,3 +1,4 @@ +use std::net::IpAddr; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -7,8 +8,11 @@ use focl::archive::types::ArchiveStream; use focl::archive::ArchiveService; use focl::bgp::BgpService; use focl::config::FoclConfig; -use focl::control::{ArchiveRolloverArgs, ArchiveStatusResult, CommandKind, PeerKeyArgs}; +use focl::control::{ + ArchiveRolloverArgs, ArchiveStatusResult, CommandKind, PeerKeyArgs, PrefixMutationArgs, +}; use focl::types::{ControlRequest, ControlResponse}; +use ipnet::IpNet; use serde_json::json; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::{UnixListener, UnixStream}; @@ -52,7 +56,10 @@ async fn main() -> Result<()> { let archive = Arc::clone(&archive); let bgp = bgp.clone(); let shutdown_tx = shutdown_tx.clone(); - tokio::spawn(async move { run_control_server(listener, archive, bgp, shutdown_tx).await }) + let config_path = Arc::new(args.config.clone()); + tokio::spawn(async move { + run_control_server(listener, archive, bgp, shutdown_tx, config_path).await + }) }; tokio::select! { @@ -95,15 +102,17 @@ async fn run_control_server( archive: Arc, bgp: BgpService, shutdown_tx: broadcast::Sender<()>, + config_path: Arc, ) -> Result<()> { loop { let (stream, _addr) = listener.accept().await?; let archive = Arc::clone(&archive); let bgp = bgp.clone(); let shutdown_tx = shutdown_tx.clone(); + let config_path = Arc::clone(&config_path); tokio::spawn(async move { - if let Err(err) = handle_client(stream, archive, bgp, shutdown_tx).await { + if let Err(err) = handle_client(stream, archive, bgp, shutdown_tx, config_path).await { tracing::warn!(error=%err, "control connection failed"); } }); @@ -115,6 +124,7 @@ async fn handle_client( archive: Arc, bgp: BgpService, shutdown_tx: broadcast::Sender<()>, + config_path: Arc, ) -> Result<()> { let (read_half, mut write_half) = stream.into_split(); let mut reader = BufReader::new(read_half); @@ -153,7 +163,26 @@ async fn handle_client( }), ) } - CommandKind::Reload => ControlResponse::ok(req.id, json!({"reloaded": true})), + CommandKind::Reload => match FoclConfig::load(&config_path) { + Ok(cfg) => match bgp.reload_prefixes(&cfg).await { + Ok(reload) => ControlResponse::ok( + req.id, + json!({ + "reloaded": true, + // Only the originated prefix set is re-applied; peer + // and archive settings still require a restart. + "scope": "prefixes", + "prefixes": reload, + }), + ), + Err(err) => ControlResponse::err(req.id, "reload_failed", err.to_string()), + }, + Err(err) => ControlResponse::err( + req.id, + "config_invalid", + format!("failed reading {}: {err}", config_path.display()), + ), + }, CommandKind::Shutdown => { let _ = shutdown_tx.send(()); ControlResponse::ok(req.id, json!({"shutting_down": true})) @@ -265,6 +294,30 @@ async fn handle_client( Err(err) => ControlResponse::err(req.id, "peer_reset_failed", err.to_string()), } } + CommandKind::PrefixList => { + let prefixes = bgp.prefix_view().await; + ControlResponse::ok(req.id, json!({"prefixes": prefixes})) + } + CommandKind::PrefixAdd => match parse_prefix_mutation_args(&req, "prefix_add") { + Ok((network, next_hop, dry_run)) => { + match bgp.prefix_add(network, next_hop, dry_run).await { + Ok(mutation) => ControlResponse::ok(req.id, json!(mutation)), + Err(err) => { + ControlResponse::err(req.id, "prefix_add_failed", err.to_string()) + } + } + } + Err(response) => response, + }, + CommandKind::PrefixRemove => match parse_prefix_mutation_args(&req, "prefix_remove") { + Ok((network, _, dry_run)) => match bgp.prefix_remove(network, dry_run).await { + Ok(mutation) => ControlResponse::ok(req.id, json!(mutation)), + Err(err) => { + ControlResponse::err(req.id, "prefix_remove_failed", err.to_string()) + } + }, + Err(response) => response, + }, CommandKind::RibSummary => { let summary = bgp.rib_summary().await; ControlResponse::ok(req.id, json!({"summary": summary})) @@ -350,3 +403,47 @@ async fn write_response( writer.write_all(b"\n").await?; Ok(()) } + +/// Parses `prefix_add` / `prefix_remove` arguments, returning a ready-made +/// error response instead of failing the whole control connection. +fn parse_prefix_mutation_args( + req: &ControlRequest, + label: &str, +) -> std::result::Result<(IpNet, Option, bool), ControlResponse> { + let args = match PrefixMutationArgs::from_json(&req.args) { + Ok(args) => args, + Err(err) => { + return Err(ControlResponse::err( + req.id.clone(), + "invalid_args", + format!("{label} args error: {err}"), + )) + } + }; + let network = match args.network.parse::() { + Ok(network) => network, + Err(err) => { + return Err(ControlResponse::err( + req.id.clone(), + "invalid_network", + format!("{label} network error: {err}"), + )) + } + }; + let next_hop = match args + .next_hop + .as_deref() + .map(str::parse::) + .transpose() + { + Ok(next_hop) => next_hop, + Err(err) => { + return Err(ControlResponse::err( + req.id.clone(), + "invalid_next_hop", + format!("{label} next hop error: {err}"), + )) + } + }; + Ok((network, next_hop, args.dry_run)) +} diff --git a/src/control/mod.rs b/src/control/mod.rs index 18175e1..5bff1e1 100644 --- a/src/control/mod.rs +++ b/src/control/mod.rs @@ -15,6 +15,9 @@ pub enum CommandKind { RibSummary, RibIn, RibOut, + PrefixAdd, + PrefixRemove, + PrefixList, ArchiveStatus, ArchiveRollover, ArchiveSnapshotNow, @@ -36,6 +39,9 @@ impl CommandKind { "rib_summary" => Self::RibSummary, "rib_in" => Self::RibIn, "rib_out" => Self::RibOut, + "prefix_add" => Self::PrefixAdd, + "prefix_remove" => Self::PrefixRemove, + "prefix_list" => Self::PrefixList, "archive_status" => Self::ArchiveStatus, "archive_rollover" => Self::ArchiveRollover, "archive_snapshot_now" => Self::ArchiveSnapshotNow, @@ -57,6 +63,22 @@ impl PeerKeyArgs { } } +/// Arguments for `prefix_add` / `prefix_remove`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PrefixMutationArgs { + pub network: String, + #[serde(default)] + pub next_hop: Option, + #[serde(default)] + pub dry_run: bool, +} + +impl PrefixMutationArgs { + pub fn from_json(value: &Value) -> Result { + serde_json::from_value(value.clone()) + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ArchiveStream { @@ -113,3 +135,33 @@ impl ArchiveDestinationsResult { json!(self) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prefix_commands_are_recognized() { + for (cmd, expected) in [ + ("prefix_add", CommandKind::PrefixAdd), + ("prefix_remove", CommandKind::PrefixRemove), + ("prefix_list", CommandKind::PrefixList), + ] { + let request = ControlRequest { + version: 1, + id: "test".to_string(), + cmd: cmd.to_string(), + args: json!({}), + }; + assert_eq!(CommandKind::from_request(&request), expected); + } + } + + #[test] + fn prefix_mutation_args_default_next_hop_and_dry_run() { + let args = PrefixMutationArgs::from_json(&json!({"network": "192.0.2.0/24"})).unwrap(); + assert_eq!(args.network, "192.0.2.0/24"); + assert!(args.next_hop.is_none()); + assert!(!args.dry_run); + } +} From c0cf2cba71d87e8d33c96abdcf1dd41566ad78d5 Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Fri, 11 Sep 2026 08:06:48 -0700 Subject: [PATCH 10/17] fix(prefix): address review round 1 - keep framing in a dedicated reader task: the session loop selects between control operations and incoming messages, so `read_exact` can no longer be cancelled mid-message by an operation - register a session as a runtime-change target only once it is serving, and carry its negotiated families so dispatch and dry-run targets name only the peers that can carry the update - serialize each runtime mutation with its dispatch, so concurrent control clients cannot enqueue a withdrawal before the announcement it reverses - treat a next-hop change as a change, let a runtime entry shadow the configured entry for the same network, and take the default next hop from the config baseline only - exit non-zero for a failed response printed with `--json` - add the primary sources to the prior-art survey and align the `--next-hop` help text with the encoder --- CHANGELOG.md | 5 + docs/prefix-control-prior-art.md | 24 +++ src/bgp/mod.rs | 265 +++++++++++++++++++++++++------ src/bin/focl.rs | 9 +- 4 files changed, 250 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e437ff4..c2a3f09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,11 @@ All notable changes to this project will be documented in this file. ### Code improvements * Outbound route changes are dispatched to established sessions through a per-session channel, and the session loop now selects between that channel and the socket read on split read/write halves. Update encoding for both directions is shared with the establishment path (`emit_updates`). +* Session framing moved to a dedicated reader task: the session loop selects between control operations and incoming messages, and `read_exact` is no longer cancelled mid-message by an operation. +* A session is registered as a runtime-change target only after it is serving, and its negotiated address families travel with the registration, so dispatch and `--dry-run` targets name only the peers that can carry the update. +* Runtime prefix mutations are serialized with their dispatch, so two concurrent control clients cannot enqueue a withdrawal before the announcement it reverses. +* `prefix add` treats a next-hop change as a change (peers keep the old next hop until re-announced), a runtime entry shadows the configured entry for the same network, and the default next hop is taken from the config baseline only. +* `focl --json` output now exits non-zero on a failed response; `--json` changes formatting only. ## v0.1.0 - 2025-02-21 diff --git a/docs/prefix-control-prior-art.md b/docs/prefix-control-prior-art.md index 49c8bc7..e0b8643 100644 --- a/docs/prefix-control-prior-art.md +++ b/docs/prefix-control-prior-art.md @@ -61,3 +61,27 @@ UNVERIFIED. `reload` reset, and `focl peer list`/`rib out` for verification. - Config write-back: runtime commands never edit `focl.toml` (GoBGP/OpenBGPD behavior; keeps the config file reviewable by hand). + +## Sources + +Primary sources for each row of the comparison (fetched 2026-09-11): + +- OpenBGPD: `bgpctl(8)` and `bgpd.conf(5)` man pages - https://man.openbsd.org/bgpctl.8 , + https://man.openbsd.org/bgpd.conf.5 (verified back to OpenBSD 4.6: https://man.openbsd.org/OpenBSD-4.6/bgpctl.8) +- GoBGP: `docs/sources/cli-command-syntax.md`, `cli-operations.md`, `policy.md`, + `pkg/config/oc/serve.go`, `internal/pkg/table/destination.go` - + https://github.com/osrg/gobgp/blob/master/docs/sources/cli-command-syntax.md , + https://github.com/osrg/gobgp/blob/master/docs/sources/policy.md +- BIRD 2/3: `birdc` remote-control chapter and the static protocol implementation - + https://bird.nic.cz/doc/bird-3.3.2.html , https://bird.nic.cz/doc/bird-2.19.2.html , + https://github.com/CZ-NIC/bird/blob/v2.19.2/proto/static/static.c +- FRR: BGP and basic-command documentation - https://docs.frrouting.org/en/latest/bgp.html , + https://docs.frrouting.org/en/latest/basic.html , `vtysh` man page +- Junos: static-route and policy-statement reference, commit/rollback topics - + https://www.juniper.net/documentation/us/en/software/junos/cli-reference/topics/ref/statement/static-edit-routing-options.html +- RouterOS: `/routing bgp` reference and the v6-to-v7 migration page - + https://help.mikrotik.com/docs/spaces/ROS/pages/331612228/routing%2Bbgp , + https://help.mikrotik.com/docs/spaces/ROS/pages/30474256/Moving+from+ROSv6+to+v7+with+examples +- ExaBGP: API commands and text API reference - https://github.com/Exa-Networks/exabgp/wiki/API-Commands +- RustyBGP: https://github.com/osrg/rustybgp (GoBGP-compatible gRPC API and CLI) +- freeRtr: config examples and BGP source - https://github.com/mc36/freeRtr/blob/master/cfg/intop1-bgp10.tst diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index fa80f8d..6495bad 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -16,7 +16,7 @@ use ipnet_trie::IpnetTrie; use serde::{Deserialize, Serialize}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::net::{TcpListener, TcpSocket, TcpStream}; -use tokio::sync::{broadcast, mpsc, RwLock}; +use tokio::sync::{broadcast, mpsc, Mutex, RwLock}; use tokio::task::JoinHandle; use tokio::time::{sleep, timeout, Instant}; @@ -119,6 +119,25 @@ pub struct PrefixReload { pub peers_notified: Vec, } +/// An established session that accepts runtime route changes. The negotiated +/// families travel with the sender so dispatch and dry-run targets report only +/// peers that can actually carry the update. +#[derive(Debug, Clone)] +struct SessionHandle { + tx: mpsc::Sender, + supports_v4: bool, + supports_v6: bool, +} + +impl SessionHandle { + fn supports(&self, network: &IpNet) -> bool { + match network { + IpNet::V4(_) => self.supports_v4, + IpNet::V6(_) => self.supports_v6, + } + } +} + /// An outbound route change pushed into one established session. #[derive(Debug, Clone)] enum SessionOp { @@ -153,15 +172,17 @@ impl PrefixState { } /// The set that is actually announced: (config + added) - suppressed. + /// A runtime entry shadows the configured one for the same network, so an + /// explicit `prefix add --next-hop` keeps working for configured prefixes. fn effective(&self) -> Vec { let mut entries: Vec = self - .config + .added .iter() - .filter(|entry| !self.suppressed.contains(&entry.network)) - .cloned() + .filter(|(network, _)| !self.suppressed.contains(*network)) + .map(|(_, entry)| entry.clone()) .collect(); - for (network, entry) in &self.added { - if self.suppressed.contains(network) || entries.iter().any(|e| e.network == *network) { + for entry in &self.config { + if self.suppressed.contains(&entry.network) || self.added.contains_key(&entry.network) { continue; } entries.push(entry.clone()); @@ -195,11 +216,13 @@ impl PrefixState { } } + /// Configured next hop for the prefix's family, if any. Runtime additions + /// are deliberately excluded: inheriting from them would make the default + /// depend on the order of earlier commands. fn default_next_hop(&self, network: &IpNet) -> Option { let wants_v4 = matches!(network, IpNet::V4(_)); self.config .iter() - .chain(self.added.values()) .filter_map(|entry| entry.next_hop) .find(|address| address.is_ipv4() == wants_v4) } @@ -233,16 +256,26 @@ impl PrefixState { } } - /// Records a runtime addition (or clears an earlier suppression). Returns - /// whether the effective originated set changed. + /// Records a runtime addition or override. Returns whether the effective + /// originated set changed, which includes a next-hop change: peers keep the + /// old next hop until the prefix is announced again. fn add(&mut self, entry: PrefixEntry) -> bool { let network = entry.network; let was_announced = self.is_announced(&network); + let previous = self.added.get(&network).or_else(|| { + self.config + .iter() + .find(|configured| configured.network == network) + }); + let next_hop_changed = previous.map(|previous| previous.next_hop) != Some(entry.next_hop); + let configured = self.config.iter().any(|e| e.network == network); + // A runtime entry wins over the config baseline for the same network. + let store = !configured || next_hop_changed || self.added.contains_key(&network); self.suppressed.remove(&network); - if self.added.contains_key(&network) || !self.config.iter().any(|e| e.network == network) { + if store { self.added.insert(network, entry); } - !was_announced + !was_announced || next_hop_changed } /// Withdraws a prefix: a runtime-only entry is dropped, a configured one is @@ -354,8 +387,12 @@ struct BgpServiceInner { router_id: Ipv4Addr, /// Effective originated prefixes: config baseline plus runtime overrides. prefix_state: RwLock, + /// Serializes each runtime prefix mutation with its session dispatch, so + /// concurrent control clients cannot enqueue a withdrawal before the + /// announcement it reverses. + prefix_ops: Mutex<()>, /// Established sessions that accept runtime route changes, keyed by peer address. - session_ops: RwLock>>, + session_ops: RwLock>, peers: RwLock>, rib_in: RwLock>>, session_local_ips: RwLock>, @@ -396,6 +433,7 @@ impl BgpService { global_asn: cfg.global.asn, router_id, prefix_state: RwLock::new(PrefixState::new(prefixes)), + prefix_ops: Mutex::new(()), session_ops: RwLock::new(HashMap::new()), peers: RwLock::new(HashMap::new()), rib_in: RwLock::new(HashMap::new()), @@ -471,7 +509,7 @@ impl BgpService { Ok(()) } - async fn accept_inbound(&self, mut stream: TcpStream, remote: SocketAddr) { + async fn accept_inbound(&self, stream: TcpStream, remote: SocketAddr) { let peer = { let peers = self.inner.peers.read().await; peers @@ -512,7 +550,7 @@ impl BgpService { let service = self.clone(); let key = peer.address.clone(); let task = tokio::spawn(async move { - let result = service.run_session(&peer, &mut stream).await; + let result = service.run_session(&peer, stream).await; service.clear_rib(&peer.address).await; match result { Ok(()) => { @@ -573,28 +611,18 @@ impl BgpService { .parse() .with_context(|| format!("invalid peer address {}", peer.address))?; let addr = SocketAddr::new(ip, peer.remote_port); - let mut stream = connect_with_optional_bind(peer, addr).await?; - self.run_session(peer, &mut stream).await + let stream = connect_with_optional_bind(peer, addr).await?; + self.run_session(peer, stream).await } - async fn run_session(&self, peer: &PeerConfig, stream: &mut TcpStream) -> Result<()> { + async fn run_session(&self, peer: &PeerConfig, stream: TcpStream) -> Result<()> { let local_ip = stream.local_addr()?.ip(); self.inner .session_local_ips .write() .await .insert(peer.address.clone(), local_ip); - // Runtime route changes reach a session only while it is established; - // the receiver is polled from the session loop below. - let (ctrl_tx, ctrl_rx) = mpsc::channel::(64); - self.inner - .session_ops - .write() - .await - .insert(peer.address.clone(), ctrl_tx); - let result = self - .run_session_inner(peer, stream, local_ip, ctrl_rx) - .await; + let result = self.run_session_inner(peer, stream, local_ip).await; self.inner.session_ops.write().await.remove(&peer.address); result } @@ -602,13 +630,31 @@ impl BgpService { async fn run_session_inner( &self, peer: &PeerConfig, - stream: &mut TcpStream, + stream: TcpStream, local_ip: IpAddr, - mut ctrl_rx: mpsc::Receiver, ) -> Result<()> { - // Split halves let the session write keepalives and runtime updates - // while a read is concurrently outstanding inside `select!`. - let (mut reader, mut writer) = stream.split(); + let (reader, mut writer) = stream.into_split(); + // One task owns framing, so a runtime operation can never cancel a + // partially consumed read: `read_exact` is not cancel-safe, and the + // session loop below selects between control operations and messages. + // The task ends when the socket closes or the receiver is dropped. + let (msg_tx, mut msg_rx) = mpsc::channel::>(32); + tokio::spawn(async move { + let mut reader = reader; + loop { + match read_bgp_message(&mut reader).await { + Ok(message) => { + if msg_tx.send(Ok(message)).await.is_err() { + return; + } + } + Err(error) => { + let _ = msg_tx.send(Err(error)).await; + return; + } + } + } + }); self.set_peer_state(&peer.address, PeerState::OpenSent, None, None) .await; @@ -622,7 +668,7 @@ impl BgpService { ); write_bgp_message(&mut writer, &open, AsnLength::Bits32).await?; - let incoming = read_bgp_message(&mut reader).await?; + let incoming = next_bgp_message(&mut msg_rx).await?; let BgpMessage::Open(remote_open) = incoming.message else { return Err(anyhow!("expected OPEN from peer")); }; @@ -632,7 +678,7 @@ impl BgpService { self.set_peer_state(&peer.address, PeerState::OpenConfirm, None, None) .await; write_bgp_message(&mut writer, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; - let incoming = read_bgp_message(&mut reader).await?; + let incoming = next_bgp_message(&mut msg_rx).await?; if !matches!(incoming.message, BgpMessage::KeepAlive) { return Err(anyhow!("expected KEEPALIVE from peer after OPEN")); } @@ -682,6 +728,20 @@ impl BgpService { } } + // Register for runtime route changes only once the session is serving, + // and carry the negotiated families so dispatch can filter targets. + let (ctrl_tx, mut ctrl_rx) = mpsc::channel::(64); + let handle = SessionHandle { + tx: ctrl_tx, + supports_v4: negotiated.plain_ipv4() || negotiated.supports(Afi::Ipv4, Safi::Unicast), + supports_v6: negotiated.supports(Afi::Ipv6, Safi::Unicast), + }; + self.inner + .session_ops + .write() + .await + .insert(peer.address.clone(), handle); + let negotiated_hold = Duration::from_secs(hold_time as u64); let keepalive_interval = Duration::from_secs((hold_time as u64 / 3).max(1)); let mut next_keepalive = Instant::now() + keepalive_interval; @@ -710,16 +770,16 @@ impl BgpService { .await?; } } - result = timeout(timeout_dur, read_bgp_message(&mut reader)) => { - match result { - Ok(Ok(incoming)) => match incoming.message { + incoming = timeout(timeout_dur, msg_rx.recv()) => { + match incoming { + Ok(Some(Ok(message))) => match message.message { BgpMessage::Update(update) => { self.ingest_received_update( peer, local_as, local_ip, update, - incoming.raw, + message.raw, &negotiated, ) .await?; @@ -734,7 +794,9 @@ impl BgpService { return Err(anyhow!("received NOTIFICATION from peer")) } }, - Ok(Err(error)) => return Err(error), + Ok(Some(Err(error))) => return Err(error), + Ok(None) => return Err(anyhow!("peer reader stopped")), + // Tick: keepalive and hold timers are handled above. Err(_) => {} } } @@ -1076,6 +1138,9 @@ impl BgpService { next_hop: Option, dry_run: bool, ) -> Result { + // Serialize the mutation with its dispatch: two concurrent control + // clients must not be able to enqueue changes out of order. + let _guard = self.inner.prefix_ops.lock().await; if let Some(next_hop) = next_hop { ensure_next_hop_family(&network, next_hop)?; } @@ -1095,7 +1160,7 @@ impl BgpService { let peers_notified = if !changed { Vec::new() } else if dry_run { - self.session_targets().await + self.session_targets(&network).await } else { self.dispatch_session_op(SessionOp::Announce(entry)).await }; @@ -1115,6 +1180,7 @@ impl BgpService { /// Withdraws a prefix at runtime: a configured prefix is suppressed, a /// runtime-only one is dropped. pub async fn prefix_remove(&self, network: IpNet, dry_run: bool) -> Result { + let _guard = self.inner.prefix_ops.lock().await; let changed = if dry_run { self.inner.prefix_state.read().await.is_announced(&network) } else { @@ -1123,7 +1189,7 @@ impl BgpService { let peers_notified = if !changed { Vec::new() } else if dry_run { - self.session_targets().await + self.session_targets(&network).await } else { self.dispatch_session_op(SessionOp::Withdraw { network }) .await @@ -1144,6 +1210,7 @@ impl BgpService { /// Re-reads the configured prefix list, applies the delta, and clears every /// runtime override. Peer sessions and other config sections are untouched. pub async fn reload_prefixes(&self, cfg: &FoclConfig) -> Result { + let _guard = self.inner.prefix_ops.lock().await; let entries = parse_prefix_entries(cfg)?; let (announce, withdraw, overrides_reset) = { let mut state = self.inner.prefix_state.write().await; @@ -1177,20 +1244,25 @@ impl BgpService { }) } - /// Dispatches one route change to every established session, returning the - /// peers whose session accepted it. + /// Dispatches one route change to every established session that carries + /// the prefix's address family, returning the peers that accepted it. async fn dispatch_session_op(&self, op: SessionOp) -> Vec { - let senders: Vec<(String, mpsc::Sender)> = self + let network = match &op { + SessionOp::Announce(entry) => entry.network, + SessionOp::Withdraw { network } => *network, + }; + let handles: Vec<(String, SessionHandle)> = self .inner .session_ops .read() .await .iter() - .map(|(peer, sender)| (peer.clone(), sender.clone())) + .filter(|(_, handle)| handle.supports(&network)) + .map(|(peer, handle)| (peer.clone(), handle.clone())) .collect(); let mut notified = Vec::new(); - for (peer, sender) in senders { - if sender.send(op.clone()).await.is_ok() { + for (peer, handle) in handles { + if handle.tx.send(op.clone()).await.is_ok() { notified.push(peer); } } @@ -1198,15 +1270,17 @@ impl BgpService { notified } - /// Established sessions without dispatching anything (`--dry-run`). - async fn session_targets(&self) -> Vec { + /// Established sessions that could carry the prefix's family, without + /// dispatching anything (`--dry-run`). + async fn session_targets(&self, network: &IpNet) -> Vec { let mut targets: Vec = self .inner .session_ops .read() .await - .keys() - .cloned() + .iter() + .filter(|(_, handle)| handle.supports(network)) + .map(|(peer, _)| peer.clone()) .collect(); targets.sort(); targets @@ -1560,6 +1634,17 @@ async fn write_bgp_message( Ok(bytes) } +/// Awaits the next framed message from a session's reader task. +async fn next_bgp_message( + rx: &mut mpsc::Receiver>, +) -> Result { + match rx.recv().await { + Some(Ok(message)) => Ok(message), + Some(Err(error)) => Err(error), + None => Err(anyhow!("peer reader stopped")), + } +} + async fn read_bgp_message(stream: &mut R) -> Result { let mut header = [0u8; 19]; stream.read_exact(&mut header).await?; @@ -1836,6 +1921,82 @@ mod tests { assert!(ensure_next_hop_family(&v6, "2001:db8::1".parse().unwrap()).is_ok()); } + #[test] + fn next_hop_change_is_a_change() { + let network: IpNet = "198.51.100.0/24".parse().unwrap(); + let first: IpAddr = "192.0.2.1".parse().unwrap(); + let second: IpAddr = "192.0.2.9".parse().unwrap(); + let mut state = PrefixState::new(vec![]); + + assert!(state.add(PrefixEntry { + network, + next_hop: Some(first), + })); + // Same next hop again: nothing to announce. + assert!(!state.add(PrefixEntry { + network, + next_hop: Some(first), + })); + // A different next hop must re-announce, and the effective entry follows. + assert!(state.add(PrefixEntry { + network, + next_hop: Some(second), + })); + let effective = state.effective(); + assert_eq!(effective.len(), 1); + assert_eq!(effective[0].next_hop, Some(second)); + } + + #[test] + fn runtime_override_shadows_the_configured_next_hop() { + let network: IpNet = "192.0.2.0/24".parse().unwrap(); + let configured: IpAddr = "10.0.0.1".parse().unwrap(); + let override_hop: IpAddr = "10.0.0.9".parse().unwrap(); + let mut state = PrefixState::new(vec![PrefixEntry { + network, + next_hop: Some(configured), + }]); + + assert!(!state.add(PrefixEntry { + network, + next_hop: Some(configured), + })); + assert!(state.add(PrefixEntry { + network, + next_hop: Some(override_hop), + })); + let effective = state.effective(); + assert_eq!( + effective.len(), + 1, + "the config entry must not be duplicated" + ); + assert_eq!(effective[0].next_hop, Some(override_hop)); + } + + #[test] + fn default_next_hop_comes_from_the_config_only() { + let v4: IpNet = "192.0.2.0/24".parse().unwrap(); + let v6: IpNet = "2001:db8::/48".parse().unwrap(); + let mut state = PrefixState::new(vec![PrefixEntry { + network: v4, + next_hop: Some("10.0.0.1".parse().unwrap()), + }]); + + assert_eq!( + state.default_next_hop(&v4), + Some("10.0.0.1".parse().unwrap()) + ); + // No configured v6 next hop: a runtime addition must not become the + // default for later commands. + assert_eq!(state.default_next_hop(&v6), None); + state.add(PrefixEntry { + network: v6, + next_hop: Some("2001:db8::1".parse().unwrap()), + }); + assert_eq!(state.default_next_hop(&v6), None); + } + fn test_service_config() -> FoclConfig { toml::from_str( r#" diff --git a/src/bin/focl.rs b/src/bin/focl.rs index abb06f4..06302f7 100644 --- a/src/bin/focl.rs +++ b/src/bin/focl.rs @@ -68,7 +68,8 @@ enum PrefixCommands { /// Network in CIDR notation, e.g. 2620:aa:a000::/48 network: String, /// Next hop for the announcement. Defaults to the configured next hop - /// of the same family, else the session's own address + /// of the same family; otherwise IPv4 falls back to the router ID and + /// IPv6 to the session's own address when that address is IPv6 #[arg(long)] next_hop: Option, /// Validate and report what would be sent without sending it @@ -287,11 +288,17 @@ fn uuid_like_id() -> String { ) } +/// Prints the raw control response. `--json` changes formatting only: a failed +/// response still exits non-zero so scripts can detect it. fn print_response(response: ControlResponse) { + let ok = response.ok; println!( "{}", serde_json::to_string_pretty(&response).unwrap_or_else(|_| "{}".to_string()) ); + if !ok { + std::process::exit(1); + } } fn fail_on_error(response: &ControlResponse) -> Result<()> { From e580820d29b4cfe36d7cb1a9aa9fa85cf7f9487b Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Fri, 11 Sep 2026 09:07:10 -0700 Subject: [PATCH 11/17] fix(prefix): address review round 2 - `source_of` returns `Option`: a network the state never knew reports `source: null` instead of being labelled `config`, and `prefix remove` captures the pre-removal provenance for a runtime-only entry - register the session and send its initial table under the same lock, so a runtime change racing with establishment cannot leave the new session advertising a stale set - add socket-level acceptance tests: runtime add/withdraw reach an established peer on the wire (announcement, withdrawal, session stays established), and a prefix is not dispatched to a peer that did not negotiate its family --- CHANGELOG.md | 2 + src/bgp/mod.rs | 56 +++++++++----- tests/acceptance_peer.rs | 158 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 194 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2a3f09..44d0c85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ All notable changes to this project will be documented in this file. * A session is registered as a runtime-change target only after it is serving, and its negotiated address families travel with the registration, so dispatch and `--dry-run` targets name only the peers that can carry the update. * Runtime prefix mutations are serialized with their dispatch, so two concurrent control clients cannot enqueue a withdrawal before the announcement it reverses. * `prefix add` treats a next-hop change as a change (peers keep the old next hop until re-announced), a runtime entry shadows the configured entry for the same network, and the default next hop is taken from the config baseline only. +* A session registers for runtime changes under the same lock as its initial table send, so a mutation racing with establishment cannot leave the new session advertising a stale set. `prefix remove` reports `source: null` for a network the state never knew instead of labelling it `config`. +* Socket-level acceptance tests cover the runtime path: `prefix_add`/`prefix_remove` reach an established peer on the wire (announcement, withdrawal, session stays established) and a prefix is not dispatched to a peer that did not negotiate its family. * `focl --json` output now exits non-zero on a failed response; `--json` changes formatting only. ## v0.1.0 - 2025-02-21 diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 6495bad..69bd717 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -101,7 +101,10 @@ pub struct PrefixMutation { pub network: String, pub family: String, pub status: PrefixStatus, - pub source: PrefixSource, + /// Provenance of the network at the time of the mutation. `None` when the + /// state never knew it (for example removing a prefix that was neither + /// configured nor added). + pub source: Option, /// False when the effective originated set was already in the requested state. pub changed: bool, pub dry_run: bool, @@ -208,11 +211,16 @@ impl PrefixState { } } - fn source_of(&self, network: &IpNet) -> PrefixSource { + /// Where a network's entry comes from, when the state knows it at all: + /// an unknown network (never configured, or a runtime entry already + /// dropped) has no provenance to report. + fn source_of(&self, network: &IpNet) -> Option { if self.added.contains_key(network) { - PrefixSource::Runtime + Some(PrefixSource::Runtime) + } else if self.config.iter().any(|entry| entry.network == *network) { + Some(PrefixSource::Config) } else { - PrefixSource::Config + None } } @@ -728,19 +736,27 @@ impl BgpService { } } - // Register for runtime route changes only once the session is serving, - // and carry the negotiated families so dispatch can filter targets. + // Register and send the initial table under the mutation lock: a + // concurrent add/remove that lands between the snapshot and the + // registration would otherwise never reach this session, leaving it + // advertising a stale set until the next mutation. let (ctrl_tx, mut ctrl_rx) = mpsc::channel::(64); - let handle = SessionHandle { - tx: ctrl_tx, - supports_v4: negotiated.plain_ipv4() || negotiated.supports(Afi::Ipv4, Safi::Unicast), - supports_v6: negotiated.supports(Afi::Ipv6, Safi::Unicast), - }; - self.inner - .session_ops - .write() - .await - .insert(peer.address.clone(), handle); + { + let _guard = self.inner.prefix_ops.lock().await; + let handle = SessionHandle { + tx: ctrl_tx, + supports_v4: negotiated.plain_ipv4() + || negotiated.supports(Afi::Ipv4, Safi::Unicast), + supports_v6: negotiated.supports(Afi::Ipv6, Safi::Unicast), + }; + self.inner + .session_ops + .write() + .await + .insert(peer.address.clone(), handle); + self.send_prefix_announcements(peer, &mut writer, &negotiated, local_ip) + .await?; + } let negotiated_hold = Duration::from_secs(hold_time as u64); let keepalive_interval = Duration::from_secs((hold_time as u64 / 3).max(1)); @@ -1180,6 +1196,8 @@ impl BgpService { /// Withdraws a prefix at runtime: a configured prefix is suppressed, a /// runtime-only one is dropped. pub async fn prefix_remove(&self, network: IpNet, dry_run: bool) -> Result { + // Provenance has to be read before the entry is dropped. + let previous_source = self.inner.prefix_state.read().await.source_of(&network); let _guard = self.inner.prefix_ops.lock().await; let changed = if dry_run { self.inner.prefix_state.read().await.is_announced(&network) @@ -1200,7 +1218,7 @@ impl BgpService { network: network.to_string(), family: family_name(&network), status: state.status_of(&network), - source: state.source_of(&network), + source: state.source_of(&network).or(previous_source), changed, dry_run, peers_notified, @@ -1779,7 +1797,7 @@ mod tests { assert!(state.remove(&v6)); assert_eq!(state.effective().len(), 1); assert_eq!(state.status_of(&v6), PrefixStatus::Suppressed); - assert_eq!(state.source_of(&v6), PrefixSource::Config); + assert_eq!(state.source_of(&v6), Some(PrefixSource::Config)); // Removing it again changes nothing. assert!(!state.remove(&v6)); @@ -1797,7 +1815,7 @@ mod tests { network: runtime_only, next_hop: None, })); - assert_eq!(state.source_of(&runtime_only), PrefixSource::Runtime); + assert_eq!(state.source_of(&runtime_only), Some(PrefixSource::Runtime)); assert_eq!(state.status_of(&runtime_only), PrefixStatus::Announced); assert!(state.remove(&runtime_only)); assert_eq!(state.status_of(&runtime_only), PrefixStatus::Absent); diff --git a/tests/acceptance_peer.rs b/tests/acceptance_peer.rs index 40cf496..e750fdf 100644 --- a/tests/acceptance_peer.rs +++ b/tests/acceptance_peer.rs @@ -14,11 +14,13 @@ use bytes::Bytes; use flate2::read::GzDecoder; use focl::archive::types::ArchiveStream; use focl::archive::ArchiveService; -use focl::bgp::BgpService; +use focl::bgp::{BgpService, PrefixSource, PrefixStatus}; use focl::config::{ArchiveConfig, FoclConfig, GlobalConfig, PeerConfig, PrefixConfig}; use focl::types::{Event, PeerState}; +use ipnet::IpNet; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; +use tokio::sync::broadcast; use tokio::time::timeout; const PEER_AS: u32 = 65_002; @@ -168,6 +170,144 @@ async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<() Ok(()) } +/// Builds a service with one passive peer and no configured prefixes. +async fn service_with_passive_peer(temp: &tempfile::TempDir, port: u16) -> Result { + let cfg = FoclConfig { + global: GlobalConfig { + asn: FOCL_AS, + router_id: "192.0.2.1".to_string(), + listen: true, + listen_addr: format!("127.0.0.1:{port}"), + control_socket: temp.path().join("focld.sock"), + log_level: "warn".to_string(), + }, + peers: vec![PeerConfig { + address: "127.0.0.1".to_string(), + remote_as: PEER_AS, + local_as: None, + hold_time_secs: 30, + connect_retry_secs: 1, + remote_port: port, + local_address: None, + enabled: true, + passive: true, + route_refresh: true, + name: None, + password: None, + }], + prefixes: vec![], + archive: ArchiveConfig { + enabled: false, + ..ArchiveConfig::default() + }, + }; + let (event_tx, _events) = broadcast::channel(16); + BgpService::new(&cfg, event_tx).await +} + +/// Connects as the peer side and completes the OPEN/KEEPALIVE exchange. +async fn establish_peer_session(port: u16, capabilities: Vec) -> Result { + let mut stream = timeout( + Duration::from_secs(5), + TcpStream::connect(("127.0.0.1", port)), + ) + .await??; + assert!(matches!( + read_message(&mut stream).await?, + BgpMessage::Open(_) + )); + write_message(&mut stream, &peer_open_with_capabilities(capabilities)).await?; + assert!(matches!( + read_message(&mut stream).await?, + BgpMessage::KeepAlive + )); + write_message(&mut stream, &BgpMessage::KeepAlive).await?; + Ok(stream) +} + +/// Runtime control has to reach an established session on the wire, and the +/// session must survive both changes. +#[tokio::test] +async fn runtime_prefix_changes_reach_an_established_session() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let bgp = service_with_passive_peer(&temp, port).await?; + let mut stream = establish_peer_session(port, capabilities()).await?; + + // With no configured prefixes, establishment sends only the two End-of-RIB + // markers (IPv4 empty UPDATE, IPv6 MP_UNREACH). + for _ in 0..2 { + assert!(matches!( + read_message(&mut stream).await?, + BgpMessage::Update(_) + )); + } + + let network: IpNet = "203.0.113.0/24".parse()?; + let added = bgp.prefix_add(network, None, false).await?; + assert!(added.changed); + assert_eq!(added.peers_notified, vec!["127.0.0.1".to_string()]); + let announcement = read_message(&mut stream).await?; + assert!( + matches!(&announcement, BgpMessage::Update(update) + if update.announced_prefixes.iter() + .any(|prefix| prefix.prefix.to_string() == "203.0.113.0/24")), + "expected the runtime announcement on the wire, got {announcement:?}" + ); + + let removed = bgp.prefix_remove(network, false).await?; + assert!(removed.changed); + assert_eq!(removed.status, PrefixStatus::Absent); + assert_eq!(removed.source, Some(PrefixSource::Runtime)); + let withdrawal = read_message(&mut stream).await?; + assert!( + matches!(&withdrawal, BgpMessage::Update(update) + if update.withdrawn_prefixes.iter() + .any(|prefix| prefix.prefix.to_string() == "203.0.113.0/24")), + "expected the runtime withdrawal on the wire, got {withdrawal:?}" + ); + + let peer = bgp + .peer_show("127.0.0.1") + .await + .context("peer stays configured")?; + assert!(matches!(peer.state, PeerState::Established)); + Ok(()) +} + +/// A prefix must not be dispatched to a peer that did not negotiate its family. +#[tokio::test] +async fn runtime_changes_skip_peers_without_the_family() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let bgp = service_with_passive_peer(&temp, port).await?; + let mut stream = establish_peer_session(port, capabilities_v4_only()).await?; + + // A v4-only peer receives just the IPv4 End-of-RIB marker. + assert!(matches!( + read_message(&mut stream).await?, + BgpMessage::Update(_) + )); + + let v6: IpNet = "2001:db8::/48".parse()?; + let added = bgp + .prefix_add(v6, Some("2001:db8::1".parse()?), false) + .await?; + assert!(added.changed, "the originated set still changed"); + assert!( + added.peers_notified.is_empty(), + "a v4-only peer must not be reported as notified: {:?}", + added.peers_notified + ); + assert!( + timeout(Duration::from_millis(250), read_message(&mut stream)) + .await + .is_err(), + "an IPv6 update must not reach a v4-only peer" + ); + Ok(()) +} + fn capabilities() -> Vec { let mut bytes = vec![1, 4, 0, 1, 0, 1, 1, 4, 0, 2, 0, 1, 65, 4]; bytes.extend_from_slice(&PEER_AS.to_be_bytes()); @@ -175,7 +315,15 @@ fn capabilities() -> Vec { bytes } -fn peer_open() -> BgpMessage { +/// Same as [`capabilities`] without the IPv6 unicast multiprotocol capability. +fn capabilities_v4_only() -> Vec { + let mut bytes = vec![1, 4, 0, 1, 0, 1, 65, 4]; + bytes.extend_from_slice(&PEER_AS.to_be_bytes()); + bytes.extend_from_slice(&[2, 0]); + bytes +} + +fn peer_open_with_capabilities(capabilities: Vec) -> BgpMessage { BgpMessage::Open(BgpOpenMessage { version: 4, asn: Asn::new_16bit(PEER_AS as u16), @@ -184,11 +332,15 @@ fn peer_open() -> BgpMessage { extended_length: false, opt_params: vec![OptParam { param_type: 2, - param_value: ParamValue::Raw(capabilities()), + param_value: ParamValue::Raw(capabilities), }], }) } +fn peer_open() -> BgpMessage { + peer_open_with_capabilities(capabilities()) +} + fn attrs() -> Attributes { let mut attrs = Attributes::default(); attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); From 31b0189de5174b2032d9b12c253e6a9bded38f54 Mon Sep 17 00:00:00 2001 From: Scouty Date: Fri, 11 Sep 2026 18:34:48 -0700 Subject: [PATCH 12/17] feat(bgp): optional attribute-255 clock on announcements A `[[prefixes]]` entry with `dev_attr255_interval_secs = N` attaches attribute 255 (reserved for development, RFC 2042) carrying a 13-byte BGPKIT clock payload (`BGPKIT` magic, version, refresh round, unix seconds) to that prefix's announcements, re-announced every N seconds. The refresh task is scheduled per distinct interval at startup and re-reads the effective originated set on each tick, so a runtime suppression silences it and `prefix add` keeps the configured clock for the same network. The attribute is originated with OPTIONAL|TRANSITIVE; downstream speakers set PARTIAL per RFC 4271. Config validation rejects a refresh interval of 0. Tests: a fixed payload vector (including the 65,536 round wrap), encoded wire bytes plus a parse-back flag check, config roundtrip and zero-reject, and socket-level acceptance coverage where a refresh advances the embedded time and a runtime re-add keeps the clock. --- CHANGELOG.md | 1 + README.md | 1 + src/bgp/mod.rs | 299 ++++++++++++++++++++++++++++++++++++++- src/config/mod.rs | 58 ++++++++ tests/acceptance_peer.rs | 228 ++++++++++++++++++++++++++++- 5 files changed, 580 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44d0c85..c2bfe7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project will be documented in this file. * **Runtime prefix control** - `focl prefix add|remove|list` announces or withdraws an originated prefix on the running daemon without restarting it or resetting any session. The effective set is (configured `[[prefixes]]` + runtime additions) minus runtime suppressions: `prefix remove` suppresses a configured prefix (a runtime-only one is dropped), `prefix add` announces it again and clears the suppression, and `prefix list` shows each prefix as `announced`/`suppressed` with a `config`/`runtime` source. Runtime overrides are in-memory only and are never written back to the config file. Address family is inferred from the prefix, `--next-hop` defaults to the configured next hop of the same family, `--dry-run` reports what would be sent without changing state, and `--json` prints the control response. * **`focl reload` applies the config's prefix delta** - reload re-reads the config file, announces prefixes added since the last read, withdraws removed ones, and clears runtime overrides; the response reports the delta and how many overrides were reset. Peer and archive settings still require a restart. +* **Attribute-255 clock on announcements** - a `[[prefixes]]` entry with `dev_attr255_interval_secs = N` attaches attribute 255 (reserved for development, RFC 2042) carrying a 13-byte BGPKIT clock payload (magic, version, refresh round, unix seconds) to that prefix's announcements, re-announced every N seconds. A runtime `prefix add` for a configured network keeps its clock, and an interval of 0 is rejected by config validation. ### Code improvements diff --git a/README.md b/README.md index c2be775..186d1dd 100644 --- a/README.md +++ b/README.md @@ -248,6 +248,7 @@ cargo clippy --no-default-features |--------|------|---------|-------------| | `network` | string | required | IP prefix (v4 or v6) | | `next_hop` | string | auto | Next-hop address | +| `dev_attr255_interval_secs` | u32 | none | Attach attribute 255 (reserved for development) with a BGPKIT clock payload, re-announced every N seconds | ## License diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 69bd717..4aea7ad 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -7,8 +7,8 @@ use std::time::Duration; use anyhow::{anyhow, Context, Result}; use bgpkit_parser::bgp::parse_bgp_message; use bgpkit_parser::models::{ - Afi, AsPath, Asn, AsnLength, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, - BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, Safi, + Afi, AsPath, Asn, AsnLength, AttrFlags, Attribute, AttributeValue, Attributes, BgpMessage, + BgpOpenMessage, BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, Safi, }; use bytes::Bytes; use ipnet::IpNet; @@ -63,6 +63,9 @@ struct PeerRuntime { struct PrefixEntry { network: IpNet, next_hop: Option, + /// Attribute-255 clock refresh interval in seconds, when this prefix + /// carries the development attribute clock. + dev_attr255_interval_secs: Option, } /// Where an originated prefix comes from: the config baseline or a runtime @@ -235,6 +238,16 @@ impl PrefixState { .find(|address| address.is_ipv4() == wants_v4) } + /// Configured attribute-255 clock interval for the network, if any. Like + /// `default_next_hop`, only the config baseline is consulted, so a runtime + /// add for a configured network keeps the configured clock. + fn configured_attr255_interval(&self, network: &IpNet) -> Option { + self.config + .iter() + .find(|entry| entry.network == *network) + .and_then(|entry| entry.dev_attr255_interval_secs) + } + fn view(&self) -> Vec { let mut rows: Vec = self .config @@ -342,7 +355,11 @@ fn parse_prefix_entries(cfg: &FoclConfig) -> Result> { .map(|nh| nh.parse::()) .transpose() .with_context(|| format!("invalid next-hop address: {:?}", p.next_hop))?; - Ok::<_, anyhow::Error>(PrefixEntry { network, next_hop }) + Ok::<_, anyhow::Error>(PrefixEntry { + network, + next_hop, + dev_attr255_interval_secs: p.dev_attr255_interval_secs, + }) }) .collect::, _>>() .context("invalid prefix in config") @@ -454,6 +471,7 @@ impl BgpService { if cfg.global.listen { service.start_listener(&cfg.global.listen_addr).await?; } + service.start_clock_refresh().await; Ok(service) } @@ -517,6 +535,47 @@ impl BgpService { Ok(()) } + /// Re-announces every configured attribute-255 clock prefix on its own + /// interval. The effective set is re-read on each tick, so a runtime + /// suppression is respected without touching the task; intervals + /// introduced by a later `reload` are only scheduled after a restart. + async fn start_clock_refresh(&self) { + let intervals: BTreeSet = self + .inner + .prefix_state + .read() + .await + .effective() + .iter() + .filter_map(|entry| entry.dev_attr255_interval_secs) + .collect(); + for interval in intervals { + let service = self.clone(); + tokio::spawn(async move { + let mut ticker = tokio::time::interval(Duration::from_secs(u64::from(interval))); + // The establishment announcement already covers t0. + ticker.tick().await; + loop { + ticker.tick().await; + let entries: Vec = service + .inner + .prefix_state + .read() + .await + .effective() + .into_iter() + .filter(|entry| entry.dev_attr255_interval_secs == Some(interval)) + .collect(); + for entry in entries { + let _ = service + .dispatch_session_op(SessionOp::Announce(entry)) + .await; + } + } + }); + } + } + async fn accept_inbound(&self, stream: TcpStream, remote: SocketAddr) { let peer = { let peers = self.inner.peers.read().await; @@ -1165,6 +1224,7 @@ impl BgpService { PrefixEntry { network, next_hop: next_hop.or_else(|| state.default_next_hop(&network)), + dev_attr255_interval_secs: state.configured_attr255_interval(&network), } }; // A dry run reports what would happen without touching the state. @@ -1462,6 +1522,7 @@ fn build_announce_updates( local_as: u32, negotiated: &NegotiatedCapabilities, ) -> Vec { + let now = unix_now(); let mut result = Vec::new(); let plain_ipv4 = negotiated.plain_ipv4(); for prefix in prefixes @@ -1472,6 +1533,7 @@ fn build_announce_updates( let mut attrs = base_announce_attributes(local_as); let next_hop = prefix.next_hop.unwrap_or(IpAddr::V4(router_id)); attrs.add_attr(AttributeValue::NextHop(next_hop).into()); + attach_dev_attr255(&mut attrs, prefix, now); result.push(BgpMessage::Update(BgpUpdateMessage { withdrawn_prefixes: vec![], attributes: attrs, @@ -1499,6 +1561,7 @@ fn build_announce_updates( }; let nlri = Nlri::new_reachable(NetworkPrefix::new(prefix.network, None), Some(next_hop)); attrs.add_attr(AttributeValue::MpReachNlri(nlri).into()); + attach_dev_attr255(&mut attrs, prefix, now); result.push(BgpMessage::Update(BgpUpdateMessage { withdrawn_prefixes: vec![], attributes: attrs, @@ -1576,6 +1639,42 @@ fn base_announce_attributes(local_as: u32) -> Attributes { attrs } +/// Attribute-255 development clock: magic bytes, format version, refresh +/// round, and the low 32 bits of the unix time. +const DEV_ATTR255_MAGIC: &[u8] = b"BGPKIT"; +const DEV_ATTR255_VERSION: u8 = 1; + +fn dev_attr255_clock_payload(unix_secs: u64, interval_secs: u32) -> Vec { + let interval = u64::from(interval_secs).max(1); + let round = ((unix_secs / interval) % 65_536) as u16; + let mut payload = Vec::with_capacity(13); + payload.extend_from_slice(DEV_ATTR255_MAGIC); + payload.push(DEV_ATTR255_VERSION); + payload.extend_from_slice(&round.to_be_bytes()); + payload.extend_from_slice(&(unix_secs as u32).to_be_bytes()); + payload +} + +fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|duration| duration.as_secs()) + .unwrap_or(0) +} + +/// Attaches the attribute-255 clock when the prefix carries one. The flag is +/// OPTIONAL|TRANSITIVE: `Development`'s `.into()` default would also set the +/// PARTIAL bit (0xe0), which an originating speaker must not send. +fn attach_dev_attr255(attrs: &mut Attributes, prefix: &PrefixEntry, now: u64) { + let Some(interval) = prefix.dev_attr255_interval_secs else { + return; + }; + attrs.add_attr(Attribute { + value: AttributeValue::Development(dev_attr255_clock_payload(now, interval)), + flag: AttrFlags::OPTIONAL | AttrFlags::TRANSITIVE, + }); +} + fn peer_state_code(state: PeerState) -> u16 { match state { PeerState::Idle => 1, @@ -1722,6 +1821,7 @@ mod tests { let prefixes = vec![PrefixEntry { network: "192.0.2.0/24".parse().unwrap(), next_hop: None, + dev_attr255_interval_secs: None, }]; let negotiated = NegotiatedCapabilities { @@ -1784,10 +1884,12 @@ mod tests { PrefixEntry { network: "192.0.2.0/24".parse().unwrap(), next_hop: Some("192.0.2.1".parse().unwrap()), + dev_attr255_interval_secs: None, }, PrefixEntry { network: "2001:db8::/48".parse().unwrap(), next_hop: None, + dev_attr255_interval_secs: None, }, ]; let v6: IpNet = "2001:db8::/48".parse().unwrap(); @@ -1805,6 +1907,7 @@ mod tests { assert!(state.add(PrefixEntry { network: v6, next_hop: None, + dev_attr255_interval_secs: None, })); assert_eq!(state.effective().len(), 2); assert_eq!(state.override_count(), 0); @@ -1814,6 +1917,7 @@ mod tests { assert!(state.add(PrefixEntry { network: runtime_only, next_hop: None, + dev_attr255_interval_secs: None, })); assert_eq!(state.source_of(&runtime_only), Some(PrefixSource::Runtime)); assert_eq!(state.status_of(&runtime_only), PrefixStatus::Announced); @@ -1829,17 +1933,20 @@ mod tests { let mut state = PrefixState::new(vec![PrefixEntry { network: suppressed, next_hop: None, + dev_attr255_interval_secs: None, }]); assert!(state.remove(&suppressed)); assert!(state.add(PrefixEntry { network: runtime_only, next_hop: None, + dev_attr255_interval_secs: None, })); let added: IpNet = "203.0.113.0/24".parse().unwrap(); let (announce, withdraw) = state.reset_overrides(vec![PrefixEntry { network: added, next_hop: None, + dev_attr255_interval_secs: None, }]); assert_eq!( @@ -1866,6 +1973,7 @@ mod tests { let entry = PrefixEntry { network: "2620:aa:a000::/48".parse().unwrap(), next_hop: None, + dev_attr255_interval_secs: None, }; let mut state = PrefixState::new(vec![entry.clone()]); assert!(state.remove(&entry.network)); @@ -1923,6 +2031,7 @@ mod tests { &[PrefixEntry { network: v6, next_hop: None, + dev_attr255_interval_secs: None, }], Ipv4Addr::new(192, 0, 2, 1), "192.0.2.2".parse().unwrap(), @@ -1949,16 +2058,19 @@ mod tests { assert!(state.add(PrefixEntry { network, next_hop: Some(first), + dev_attr255_interval_secs: None, })); // Same next hop again: nothing to announce. assert!(!state.add(PrefixEntry { network, next_hop: Some(first), + dev_attr255_interval_secs: None, })); // A different next hop must re-announce, and the effective entry follows. assert!(state.add(PrefixEntry { network, next_hop: Some(second), + dev_attr255_interval_secs: None, })); let effective = state.effective(); assert_eq!(effective.len(), 1); @@ -1973,15 +2085,18 @@ mod tests { let mut state = PrefixState::new(vec![PrefixEntry { network, next_hop: Some(configured), + dev_attr255_interval_secs: None, }]); assert!(!state.add(PrefixEntry { network, next_hop: Some(configured), + dev_attr255_interval_secs: None, })); assert!(state.add(PrefixEntry { network, next_hop: Some(override_hop), + dev_attr255_interval_secs: None, })); let effective = state.effective(); assert_eq!( @@ -1999,6 +2114,7 @@ mod tests { let mut state = PrefixState::new(vec![PrefixEntry { network: v4, next_hop: Some("10.0.0.1".parse().unwrap()), + dev_attr255_interval_secs: None, }]); assert_eq!( @@ -2011,10 +2127,187 @@ mod tests { state.add(PrefixEntry { network: v6, next_hop: Some("2001:db8::1".parse().unwrap()), + dev_attr255_interval_secs: None, }); assert_eq!(state.default_next_hop(&v6), None); } + #[test] + fn dev_attr255_clock_payload_is_a_fixed_13_byte_vector() { + let payload = dev_attr255_clock_payload(1_800_000_000, 1800); + assert_eq!(payload.len(), 13); + assert_eq!( + payload, + vec![ + 0x42, 0x47, 0x50, 0x4b, 0x49, 0x54, // "BGPKIT" + 0x01, // version + 0x42, 0x40, // round = (1_800_000_000 / 1800) % 65_536 + 0x6b, 0x49, 0xd2, 0x00, // 1_800_000_000 as u32 + ] + ); + + // The round field wraps at 65_536: `unix / interval` is taken mod + // 65_536, so it cycles with period 65_536 * interval and stays small + // for large unix values. + let at_wrap: u64 = 65_536 * 1800; + let first = dev_attr255_clock_payload(at_wrap, 1800); + assert_eq!(&first[7..9], &[0x00, 0x00][..]); + let after_wrap = dev_attr255_clock_payload(at_wrap + 1800, 1800); + assert_eq!(&after_wrap[7..9], &[0x00, 0x01][..]); + // A full period later the round repeats while the unix field advances. + let period = dev_attr255_clock_payload(1_800_000_000 + at_wrap, 1800); + assert_eq!(&period[7..9], &[0x42, 0x40][..]); + + // A zero interval cannot come from a validated config, but the payload + // builder must not divide by zero if one reaches it. + assert_eq!(dev_attr255_clock_payload(1_800_000_000, 0).len(), 13); + } + + #[test] + fn announce_updates_carry_the_attribute_255_clock_only_when_configured() { + // Walks the encoded attribute list into (flags, code, value) triples. + fn attributes_of(message: &BgpMessage, asn_len: AsnLength) -> Vec<(u8, u8, Vec)> { + let BgpMessage::Update(update) = message else { + panic!("not an UPDATE") + }; + let mut buf = bytes::BytesMut::new(); + update.attributes.encode_to(asn_len, &mut buf).unwrap(); + let mut attrs = Vec::new(); + let mut p = 0; + while p < buf.len() { + let flags = buf[p]; + let code = buf[p + 1]; + let (length, header) = if flags & 0x10 != 0 { + (u16::from_be_bytes([buf[p + 2], buf[p + 3]]) as usize, 4) + } else { + (buf[p + 2] as usize, 3) + }; + attrs.push((flags, code, buf[p + header..p + header + length].to_vec())); + p += header + length; + } + attrs + } + + let negotiated = NegotiatedCapabilities { + families: HashSet::from([(Afi::Ipv4, Safi::Unicast), (Afi::Ipv6, Safi::Unicast)]), + asn4: true, + ..Default::default() + }; + let router_id = Ipv4Addr::new(192, 0, 2, 1); + let v6_local: IpAddr = "2001:db8::2".parse().unwrap(); + let v4 = PrefixEntry { + network: "192.0.2.0/24".parse().unwrap(), + next_hop: None, + dev_attr255_interval_secs: Some(1800), + }; + let v6 = PrefixEntry { + network: "2001:db8::/48".parse().unwrap(), + next_hop: None, + dev_attr255_interval_secs: Some(1800), + }; + + // 0xc0 flags (OPTIONAL|TRANSITIVE, no PARTIAL), code 255, length 13, + // then the BGPKIT magic and the version octet. + let expected = [0xc0u8, 0xff, 0x0d, 0x42, 0x47, 0x50, 0x4b, 0x49, 0x54, 0x01]; + let v4_update = build_announce_updates( + std::slice::from_ref(&v4), + router_id, + IpAddr::V4(router_id), + 65_001, + &negotiated, + ) + .remove(0); + let v6_update = build_announce_updates( + std::slice::from_ref(&v6), + router_id, + v6_local, + 65_001, + &negotiated, + ) + .remove(0); + + for update in [&v4_update, &v6_update] { + let raw = update.encode(AsnLength::Bits32).unwrap(); + assert!( + raw.windows(expected.len()) + .any(|window| window == &expected[..]), + "expected the flagged attribute-255 clock on the wire" + ); + let clock = attributes_of(update, AsnLength::Bits32) + .into_iter() + .find(|(_, code, _)| *code == 255) + .expect("development attribute present"); + assert_eq!(clock.0, 0xc0, "OPTIONAL|TRANSITIVE, no PARTIAL bit"); + assert_eq!(clock.2.len(), 13); + assert!(clock.2.starts_with(b"BGPKIT\x01")); + } + + // Parsing the v4 message back keeps the originating flags. + let mut parsed_bytes = v4_update.encode(AsnLength::Bits32).unwrap(); + let parsed = parse_bgp_message(&mut parsed_bytes, false, &AsnLength::Bits32).unwrap(); + let BgpMessage::Update(parsed_update) = parsed else { + panic!("not an UPDATE") + }; + let clock = parsed_update + .attributes + .clone() + .into_attributes_iter() + .find(|attribute| matches!(attribute.value, AttributeValue::Development(_))) + .expect("parsed development attribute"); + assert!(clock.flag.contains(AttrFlags::OPTIONAL)); + assert!(clock.flag.contains(AttrFlags::TRANSITIVE)); + assert!(!clock.flag.contains(AttrFlags::PARTIAL)); + + // Without a configured interval the attribute must not appear at all. + let mut plain = [v4.clone(), v6.clone()]; + for entry in &mut plain { + entry.dev_attr255_interval_secs = None; + } + let updates = build_announce_updates(&plain, router_id, v6_local, 65_001, &negotiated); + assert_eq!(updates.len(), 2); + for update in &updates { + let raw = update.encode(AsnLength::Bits32).unwrap(); + assert!( + !raw.windows(expected.len()) + .any(|window| window == &expected[..]), + "an unconfigured prefix must not carry the development attribute" + ); + assert!(attributes_of(update, AsnLength::Bits32) + .iter() + .all(|(_, code, _)| *code != 255)); + } + } + + #[tokio::test] + async fn runtime_readd_keeps_the_configured_clock() { + use crate::config::PrefixConfig; + + let network: IpNet = "2001:db8::/48".parse().unwrap(); + let mut cfg = test_service_config(); + cfg.prefixes.push(PrefixConfig { + network: network.to_string(), + next_hop: Some("2001:db8::1".to_string()), + dev_attr255_interval_secs: Some(3600), + }); + let (event_tx, _) = broadcast::channel::(4); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + + assert!(service.prefix_remove(network, false).await.unwrap().changed); + let added = service.prefix_add(network, None, false).await.unwrap(); + assert!(added.changed); + + let entry = service + .inner + .prefix_state + .read() + .await + .effective() + .into_iter() + .find(|entry| entry.network == network) + .expect("the re-added prefix is effective again"); + assert_eq!(entry.dev_attr255_interval_secs, Some(3600)); + } + fn test_service_config() -> FoclConfig { toml::from_str( r#" diff --git a/src/config/mod.rs b/src/config/mod.rs index a0cea0b..8117cb2 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -67,6 +67,12 @@ impl FoclConfig { prefix.network.parse::().with_context(|| { format!("invalid IP prefix in [[prefixes]]: {}", prefix.network) })?; + if prefix.dev_attr255_interval_secs == Some(0) { + bail!( + "[[prefixes]] {} has invalid dev_attr255_interval_secs; must be > 0", + prefix.network + ); + } } self.archive.validate()?; @@ -152,6 +158,11 @@ pub struct PrefixConfig { pub network: String, #[serde(default)] pub next_hop: Option, + /// Attaches attribute 255 (reserved for development, RFC 2042) to this + /// prefix's announcements, carrying a BGPKIT clock payload, re-announced + /// every N seconds. Absent = no attribute. + #[serde(default)] + pub dev_attr255_interval_secs: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -537,6 +548,53 @@ layout_profile = "routeviews" assert_eq!(cfg.archive.layout_profile, LayoutProfile::RouteViews); } + #[test] + fn prefix_config_roundtrips_dev_attr255_interval() { + let raw = r#" +[global] +asn = 65001 +router_id = "192.0.2.1" + +[[prefixes]] +network = "2001:db8::/48" +dev_attr255_interval_secs = 1800 + +[[prefixes]] +network = "192.0.2.0/24" +"#; + let cfg: FoclConfig = toml::from_str(raw).expect("toml should parse"); + assert_eq!(cfg.prefixes[0].dev_attr255_interval_secs, Some(1800)); + assert_eq!(cfg.prefixes[1].dev_attr255_interval_secs, None); + + let encoded = toml::to_string(&cfg).expect("config should serialize"); + let reparsed: FoclConfig = toml::from_str(&encoded).expect("roundtrip should parse"); + assert_eq!(reparsed.prefixes[0].dev_attr255_interval_secs, Some(1800)); + assert_eq!(reparsed.prefixes[1].dev_attr255_interval_secs, None); + } + + #[test] + fn rejects_zero_dev_attr255_interval() { + let raw = r#" +[global] +asn = 65001 +router_id = "192.0.2.1" + +[[prefixes]] +network = "192.0.2.0/24" +dev_attr255_interval_secs = 0 +"#; + let cfg: FoclConfig = toml::from_str(raw).expect("toml should parse"); + let error = cfg + .validate() + .expect_err("a zero refresh interval must be rejected"); + assert!( + error + .to_string() + .contains("dev_attr255_interval_secs; must be > 0"), + "unexpected error: {error}" + ); + } + #[test] fn rejects_absolute_custom_template() { let templates = CustomLayoutTemplates { diff --git a/tests/acceptance_peer.rs b/tests/acceptance_peer.rs index e750fdf..51edd1b 100644 --- a/tests/acceptance_peer.rs +++ b/tests/acceptance_peer.rs @@ -6,7 +6,7 @@ use std::time::Duration; use anyhow::{Context, Result}; use bgpkit_parser::bgp::parse_bgp_message; use bgpkit_parser::models::{ - AsPath, Asn, AsnLength, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, + AsPath, Asn, AsnLength, AttrFlags, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, }; use bgpkit_parser::parse_mrt_record; @@ -25,6 +25,8 @@ use tokio::time::timeout; const PEER_AS: u32 = 65_002; const FOCL_AS: u32 = 65_001; +/// The IPv6 prefix carrying the attribute-255 clock in the clock tests. +const CLOCK_PREFIX: &str = "2001:db8:feed::/48"; #[tokio::test] async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<()> { @@ -59,10 +61,12 @@ async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<() PrefixConfig { network: "198.51.100.0/24".to_string(), next_hop: Some("192.0.2.1".to_string()), + dev_attr255_interval_secs: None, }, PrefixConfig { network: "2001:db8:feed::/48".to_string(), next_hop: Some("2001:db8::1".to_string()), + dev_attr255_interval_secs: None, }, ], archive: ArchiveConfig { @@ -170,8 +174,12 @@ async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<() Ok(()) } -/// Builds a service with one passive peer and no configured prefixes. -async fn service_with_passive_peer(temp: &tempfile::TempDir, port: u16) -> Result { +/// Builds a service with one passive peer and the given configured prefixes. +async fn service_with_prefixes( + temp: &tempfile::TempDir, + port: u16, + prefixes: Vec, +) -> Result { let cfg = FoclConfig { global: GlobalConfig { asn: FOCL_AS, @@ -195,7 +203,7 @@ async fn service_with_passive_peer(temp: &tempfile::TempDir, port: u16) -> Resul name: None, password: None, }], - prefixes: vec![], + prefixes, archive: ArchiveConfig { enabled: false, ..ArchiveConfig::default() @@ -205,6 +213,26 @@ async fn service_with_passive_peer(temp: &tempfile::TempDir, port: u16) -> Resul BgpService::new(&cfg, event_tx).await } +/// Builds a service with one passive peer and no configured prefixes. +async fn service_with_passive_peer(temp: &tempfile::TempDir, port: u16) -> Result { + service_with_prefixes(temp, port, vec![]).await +} + +/// Builds a service with one passive peer and the clock prefix configured to +/// re-announce every second. +async fn service_with_clock_prefix(temp: &tempfile::TempDir, port: u16) -> Result { + service_with_prefixes( + temp, + port, + vec![PrefixConfig { + network: CLOCK_PREFIX.to_string(), + next_hop: Some("2001:db8::1".to_string()), + dev_attr255_interval_secs: Some(1), + }], + ) + .await +} + /// Connects as the peer side and completes the OPEN/KEEPALIVE exchange. async fn establish_peer_session(port: u16, capabilities: Vec) -> Result { let mut stream = timeout( @@ -308,6 +336,126 @@ async fn runtime_changes_skip_peers_without_the_family() -> Result<()> { Ok(()) } +/// The attribute-255 clock travels on the wire for a configured prefix and is +/// re-announced with a fresh embedded unix time on the configured interval. +#[tokio::test] +async fn clock_attribute_refreshes_on_schedule() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let _bgp = service_with_clock_prefix(&temp, port).await?; + let mut stream = establish_peer_session(port, capabilities()).await?; + + let (flags, first_payload) = + timeout(Duration::from_secs(5), read_development_clock(&mut stream)).await??; + assert_eq!(first_payload.len(), 13, "13-byte clock payload"); + assert!( + first_payload.starts_with(b"BGPKIT\x01"), + "magic and version lead the payload" + ); + assert!( + flags.contains(AttrFlags::OPTIONAL) && flags.contains(AttrFlags::TRANSITIVE), + "originating flags must be OPTIONAL|TRANSITIVE, got {flags:?}" + ); + assert!( + !flags.contains(AttrFlags::PARTIAL), + "an originated attribute must not be marked PARTIAL" + ); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("system clock is after the epoch") + .as_secs(); + let first_unix = clock_unix(&first_payload); + assert!( + first_unix.abs_diff(now) <= 60, + "embedded unix {first_unix} must be within a minute of now ({now})" + ); + + // The refresh loop re-sends the announcement with a newer clock while the + // session stays up. + let later_unix = timeout(Duration::from_secs(5), async { + loop { + let message = read_message(&mut stream).await?; + if let Some((_, payload)) = development_clock(&message, CLOCK_PREFIX) { + let unix = clock_unix(&payload); + if unix > first_unix { + return Ok::<_, anyhow::Error>(unix); + } + } + } + }) + .await??; + assert!(later_unix > first_unix); + Ok(()) +} + +/// Removing and re-adding a configured clock prefix keeps the attribute-255 +/// clock on the announcement the re-add emits. +#[tokio::test] +async fn runtime_readd_keeps_configured_clock() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let bgp = service_with_clock_prefix(&temp, port).await?; + let mut stream = establish_peer_session(port, capabilities()).await?; + let network: IpNet = CLOCK_PREFIX.parse()?; + + // Wait for the establishment announcement, then for a refresh tick. A + // tick only reaches the socket through a registered session handle, so + // the removal below cannot race the session's initial table send (an + // early removal would simply never announce, and withdraw nothing). + let (_, first_payload) = + timeout(Duration::from_secs(5), read_development_clock(&mut stream)).await??; + let first_unix = clock_unix(&first_payload); + timeout(Duration::from_secs(5), async { + loop { + let message = read_message(&mut stream).await?; + if let Some((_, payload)) = development_clock(&message, CLOCK_PREFIX) { + if clock_unix(&payload) > first_unix { + return Ok::<_, anyhow::Error>(()); + } + } + } + }) + .await + .context("the refresh tick did not arrive before the removal")??; + + let removed = bgp.prefix_remove(network, false).await?; + assert!(removed.changed); + timeout( + Duration::from_secs(5), + read_until_withdrawal(&mut stream, CLOCK_PREFIX), + ) + .await + .context("withdrawal for the removed clock prefix did not arrive")??; + + // Removal silences the refresh loop. Drain anything that was already in + // flight, so the next announcement observed is the one re-add emits. + timeout(Duration::from_secs(5), async { + loop { + match timeout(Duration::from_millis(1500), read_message(&mut stream)).await { + Err(_) => return Ok::<_, anyhow::Error>(()), + Ok(Ok(_)) => continue, + Ok(Err(error)) => return Err(error), + } + } + }) + .await + .context("the clock prefix did not go quiet after removal")??; + + let added = bgp.prefix_add(network, None, false).await?; + assert!(added.changed); + assert_eq!(added.peers_notified, vec!["127.0.0.1".to_string()]); + let (flags, payload) = timeout(Duration::from_secs(5), read_development_clock(&mut stream)) + .await + .context("the re-add announcement did not arrive")??; + assert_eq!(payload.len(), 13); + assert!(payload.starts_with(b"BGPKIT\x01")); + assert!( + flags.contains(AttrFlags::OPTIONAL) && flags.contains(AttrFlags::TRANSITIVE), + "the re-added prefix keeps the clock with originating flags" + ); + Ok(()) +} + fn capabilities() -> Vec { let mut bytes = vec![1, 4, 0, 1, 0, 1, 1, 4, 0, 2, 0, 1, 65, 4]; bytes.extend_from_slice(&PEER_AS.to_be_bytes()); @@ -385,6 +533,78 @@ fn has_focl_v6(message: &BgpMessage) -> bool { matches!(message, BgpMessage::Update(update) if update.attributes.get_reachable_nlri().is_some_and(|nlri| nlri.prefixes.iter().any(|prefix| prefix.prefix.to_string() == "2001:db8:feed::/48"))) } +/// The attribute-255 payload attached to an announcement of `prefix`, when +/// present, together with its attribute flags. +fn development_clock(message: &BgpMessage, prefix: &str) -> Option<(AttrFlags, Vec)> { + let BgpMessage::Update(update) = message else { + return None; + }; + let announced = update + .announced_prefixes + .iter() + .any(|network| network.prefix.to_string() == prefix) + || update + .attributes + .get_reachable_nlri() + .is_some_and(|nlri| nlri.prefixes.iter().any(|p| p.prefix.to_string() == prefix)); + if !announced { + return None; + } + update + .attributes + .clone() + .into_attributes_iter() + .find_map(|attribute| match attribute.value { + AttributeValue::Development(payload) => Some((attribute.flag, payload)), + _ => None, + }) +} + +/// True when the message withdraws `prefix` (classic NLRI or MP_UNREACH). +fn withdraws_prefix(message: &BgpMessage, prefix: &str) -> bool { + let BgpMessage::Update(update) = message else { + return false; + }; + update + .withdrawn_prefixes + .iter() + .any(|network| network.prefix.to_string() == prefix) + || update + .attributes + .get_unreachable_nlri() + .is_some_and(|nlri| nlri.prefixes.iter().any(|p| p.prefix.to_string() == prefix)) +} + +/// The low 32 bits of the send time embedded in a clock payload. +fn clock_unix(payload: &[u8]) -> u64 { + u64::from(u32::from_be_bytes([ + payload[9], + payload[10], + payload[11], + payload[12], + ])) +} + +/// Reads until the clock prefix is announced with the development attribute. +async fn read_development_clock(stream: &mut TcpStream) -> Result<(AttrFlags, Vec)> { + loop { + let message = read_message(stream).await?; + if let Some(clock) = development_clock(&message, CLOCK_PREFIX) { + return Ok(clock); + } + } +} + +/// Reads until `prefix` is withdrawn. +async fn read_until_withdrawal(stream: &mut TcpStream, prefix: &str) -> Result<()> { + loop { + let message = read_message(stream).await?; + if withdraws_prefix(&message, prefix) { + return Ok(()); + } + } +} + async fn write_message(stream: &mut TcpStream, message: &BgpMessage) -> Result<()> { let mut bytes = message.encode(AsnLength::Bits32)?.to_vec(); bytes[..16].fill(0xff); From bd0605a59fc4fcf8d22c683a2e5aad6b74b1b31e Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Mon, 28 Sep 2026 19:02:39 -0700 Subject: [PATCH 13/17] docs: cover the collector revision in the CHANGELOG and drop deployment specifics The Unreleased section described only the runtime prefix control and the attribute-255 clock, so the archive and peering work this branch lands had no entries. Add entries for the Phase 1 peering collector, the global passive listener, the Phase 0 dual-stack archive with raw-frame passthrough, the ingestion-clock rotation rule and the archive path validation. The plan and review documents carried the reference deployment's host name, provider, session endpoints and reviewer identity; describe the reference target generically instead. --- CHANGELOG.md | 5 +++++ docs/collector-revision-plan.md | 28 ++++++++++++---------------- docs/review-2026-08-20.md | 7 +++---- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2bfe7f..acb481d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ All notable changes to this project will be documented in this file. ### New features +* **Real peering collector (Phase 1)** - the established session loop no longer discards UPDATEs: raw frames go to the archive and parsed prefixes fill a per-peer Adj-RIB-In that `focl rib in` reads, cleared on session end. OPEN advertises MP-BGP IPv4 and IPv6 unicast plus four-octet AS (AS_TRANS on the wire for a 4-byte local ASN) and, when configured, route refresh; peer capabilities are parsed from the raw frame with negotiated families, ASN4 and route refresh tracked per session, and the remote ASN validated including AS_TRANS resolution. A peer that negotiates no capabilities still establishes plain IPv4 unicast. IPv4 prefixes are announced with classic NLRI and NEXT_HOP, IPv6 through MP_REACH_NLRI, and an invalid non-IPv6 configured next hop is rejected instead of malformed-encoded. +* **Global passive listener** - one bind of `global.listen_addr` serves every inbound connection; a connection is matched against the configured peers before any state change (unmatched ones are dropped with a log), TCP-MD5 is applied to accepted sockets, an inbound connection wins a collision with a simultaneous outbound attempt, and the active loop resumes once it ends. +* **Dual-stack archive with raw-frame passthrough (Phase 0)** - archive record types carry `IpAddr`/`IpNet` peers and prefixes, so both families share the update and RIB paths. An UPDATE is written as the original wire frame inside a `BGP4MP_MESSAGE_AS4` envelope instead of being parsed and re-encoded, preserving wire fidelity and unknown attributes. TABLE_DUMP_V2 groups IPv4 and IPv6 entries per (family, prefix) with snapshot-global sequence numbers and ADD-PATH subtypes when a path id is present. Dependencies move to `bgpkit-parser` 0.20 and `bzip2` 0.6, with a new `ipnet-trie` dependency. * **Runtime prefix control** - `focl prefix add|remove|list` announces or withdraws an originated prefix on the running daemon without restarting it or resetting any session. The effective set is (configured `[[prefixes]]` + runtime additions) minus runtime suppressions: `prefix remove` suppresses a configured prefix (a runtime-only one is dropped), `prefix add` announces it again and clears the suppression, and `prefix list` shows each prefix as `announced`/`suppressed` with a `config`/`runtime` source. Runtime overrides are in-memory only and are never written back to the config file. Address family is inferred from the prefix, `--next-hop` defaults to the configured next hop of the same family, `--dry-run` reports what would be sent without changing state, and `--json` prints the control response. * **`focl reload` applies the config's prefix delta** - reload re-reads the config file, announces prefixes added since the last read, withdraws removed ones, and clears runtime overrides; the response reports the delta and how many overrides were reset. Peer and archive settings still require a restart. * **Attribute-255 clock on announcements** - a `[[prefixes]]` entry with `dev_attr255_interval_secs = N` attaches attribute 255 (reserved for development, RFC 2042) carrying a 13-byte BGPKIT clock payload (magic, version, refresh round, unix seconds) to that prefix's announcements, re-announced every N seconds. A runtime `prefix add` for a configured network keeps its clock, and an interval of 0 is rejected by config validation. @@ -20,6 +23,8 @@ All notable changes to this project will be documented in this file. * A session registers for runtime changes under the same lock as its initial table send, so a mutation racing with establishment cannot leave the new session advertising a stale set. `prefix remove` reports `source: null` for a network the state never knew instead of labelling it `config`. * Socket-level acceptance tests cover the runtime path: `prefix_add`/`prefix_remove` reach an established peer on the wire (announcement, withdrawal, session stays established) and a prefix is not dispatched to a peer that did not negotiate its family. * `focl --json` output now exits non-zero on a failed response; `--json` changes formatting only. +* Archive writers rotate on the ingestion clock only, so a record with a late or zero event timestamp stays in the current segment with its event time preserved in the MRT header, and a rollover with no routes no longer writes an empty RIB snapshot. +* The archive collector id and custom path templates are validated at config load: the id must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, templates reject absolute, backslash, control-character, empty and `..` components, and the rendered path is asserted to stay inside the archive root. ## v0.1.0 - 2025-02-21 diff --git a/docs/collector-revision-plan.md b/docs/collector-revision-plan.md index c69c443..80b05a1 100644 --- a/docs/collector-revision-plan.md +++ b/docs/collector-revision-plan.md @@ -127,22 +127,18 @@ MRT; the archive knows nothing about BMP/BGP sessions. mutation, connection-collision handling, and separate v4/v6 bind configuration; replacing per-peer binds; the `listen` global config becomes real. -6. **Reference interop target: duck (announcer replacement).** The - production reference is `duck`, the Vultr BGP announcer. Note duck runs - **BIRD** (not FRR) today; `/etc/bird/bird.conf` is the reference config: - - AS 400644, router id 149.28.81.209 - - two Vultr sessions: v4 peer 169.254.169.254 and v6 peer - 2001:19f0:ffff::1, both remote AS 64515, both with TCP-MD5 password - - announces 192.100.82.0/24 (next hop 149.28.81.209) and - 2620:aa:a000::/48 (next hop 2001:19f0:6001:30cc:5400:5ff:fe61:25da) - with blackhole backing; `import none; export filter` policy - Phase 1 done means: focl replaces bird on duck for these two - announcements — active sessions to the Vultr peers with MD5, correct - MP-BGP capability negotiation (v4 session advertises v4; v6 session - negotiates MP-BGP v6 and announces via MP_REACH), routes present in - Vultr's looking glass, and MRT updates archived for both families. - Deployment is a separate manual step (routing-infrastructure change, - operator-driven). +6. **Reference interop target: replacing a running announcer.** The + production reference is a single-host announcer running **BIRD** (not + FRR), with one session per address family, both authenticated with + TCP-MD5, each announcing one block with blackhole backing under a + restrictive export policy (`import none`). + Phase 1 done means: focl replaces BIRD on that host for both + announcements — active MD5 sessions to the upstream peers, correct + MP-BGP capability negotiation (the v4 session advertises v4; the v6 + session negotiates MP-BGP v6 and announces via MP_REACH), the prefixes + visible in the upstream provider's looking glass, and MRT updates + archived for both families. Deployment is a separate manual step + (routing-infrastructure change, operator-driven). 7. **Interop expansion.** Extend the GoBGP scripts: v6 session, capability matrix, flap → assert MRT files parse and contain expected elements. Negative tests (review minor 16): malformed UPDATE disposition, Peer diff --git a/docs/review-2026-08-20.md b/docs/review-2026-08-20.md index 94a1adc..e38560d 100644 --- a/docs/review-2026-08-20.md +++ b/docs/review-2026-08-20.md @@ -1,8 +1,7 @@ -Delegated technical review of docs/collector-revision-plan.md (rev 3) and +Technical review of docs/collector-revision-plan.md (rev 3) and docs/examples.md, cross-checked against the focl source tree and the -bgpkit-parser 0.20 checkout. Reviewer: GPT-5.6 Terra (high reasoning), via -Scouty delegation, 2026-08-19. Verdict: **needs-rework**. This file is the -verbatim review; the plan is rev 4 accordingly. +bgpkit-parser 0.20 checkout. 2026-08-19. Verdict: **needs-rework**. This +file is the verbatim review; the plan is rev 4 accordingly. ## Verdict From 3f7a0766e52ba587776fec18ef5b260c6b6373a0 Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Mon, 28 Sep 2026 20:04:00 -0700 Subject: [PATCH 14/17] fix(bgp): passive TCP-MD5, hold-time negotiation, AS4_PATH, refresh replay Address the six review findings on the session code of the collector revision. No finding was declined. * src/bgp/mod.rs:598 (TCP-MD5, passive sessions): the per-peer keys are now installed on the listening socket before the accept loop (raw fd TCP_MD5SIG, via the new `listener_md5_keys`/`install_listener_md5_keys`, which skip disabled peers, peers without a password and non-IP addresses). A peer with a configured password can now complete the handshake at all; the accepted socket still gets the key as before. * src/bgp/mod.rs:729 (hold time, RFC 4271 s4.2/s4.4/s6.1): OPEN advertises the configured hold time unchanged (0 stays 0, no `.max(3)`), the new `negotiate_hold_time` derives the negotiated value from the remote OPEN (0 on either side disables the timers, otherwise the smaller value wins), and the keepalive and hold timers are only armed for a non-zero negotiated value, so a negotiated 0 really disables them. * src/bgp/mod.rs:1624 with build_announce_updates at :1518 (RFC 6793 fallback): `base_announce_attributes` takes the negotiated capabilities and, for a session without 4-octet AS support whose local ASN does not fit in two octets, puts AS_TRANS in AS_PATH and the real ASN in AS4_PATH (attribute 17) instead of letting the encoder truncate the ASN. A 2-octet local ASN still sends a single plain AS_PATH. * src/bgp/mod.rs:863 (route refresh, RFC 2918 s4): a received ROUTE-REFRESH now replays the requested family's Adj-RIB-Out (the session's effective prefix set, filtered to the family and snapshotted under the mutation lock) and then that family's End-of-RIB, through the new `replay_route_refresh`, while the hold-timer reset stays as it was. A refresh for a family the session does not carry, and the RFC 7313 BoRR/EoRR subtypes, are ignored. The End-of-RIB builder moved into `end_of_rib` because three sites now need it. * src/bgp/mod.rs:766 (End-of-RIB, capability-less peer): the EoR loop uses the same family predicate as the announcement path (new `NegotiatedCapabilities::carries`, which accepts classic IPv4 for a peer that negotiated nothing), so such a peer gets its IPv4 End-of-RIB. The IPv4 decisions in `build_announce_updates`, `build_withdraw_updates`, `apply_update_to_rib` and the session handle now share that predicate. * src/bgp/mod.rs:760 vs :816 (duplicate establishment table): the pre-lock table send and the separate End-of-RIB loop are gone. The session now registers and sends its initial table in one critical section under the mutation lock, and the End-of-RIB markers follow that single send, so a peer (and the archive) no longer sees every initial announcement twice, once of them after End-of-RIB. Also re-exports the TCP-MD5 socket helpers as `focl::bgp::{TcpSocketExt, TcpStreamExt}` so the socket-level acceptance test can authenticate its own socket the way the daemon does, and records the six fixes in the CHANGELOG. Tests: unit tests for the listener key list, the hold-time negotiation table, the OPEN advertisement including zero, the AS4_PATH fallback (wire bytes plus a bgpkit-parser round trip), the family predicate and the EoR builders; socket acceptance tests for an MD5-authenticated passive session, the IPv4 refresh replay with its End-of-RIB, a refresh for an unnegotiated family, a capability-less peer that receives its IPv4 table and EoR exactly once, and a configured hold time of 0 seen on the wire. Each new test fails with the corresponding fix reverted. Gates: cargo fmt --all, cargo clippy --all-targets --all-features -- -D warnings and cargo test --all-features all pass. --- CHANGELOG.md | 10 + src/bgp/mod.rs | 488 +++++++++++++++++++++++++++++++-------- tests/acceptance_peer.rs | 311 ++++++++++++++++++++++++- 3 files changed, 708 insertions(+), 101 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index acb481d..9193f00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file. ## Unreleased +### Fixes + +* **TCP-MD5 on the passive listener** - the per-peer keys are installed on the listening socket (Linux `TCP_MD5SIG`) before the accept loop, because the kernel validates the digest on the SYN and `accept()` never returns for a peer whose key is missing; the key is still applied to the accepted socket as well. +* **RFC 4271 hold time** - OPEN advertises the configured hold time unchanged (0 disables the timers instead of being raised to 3), the remote OPEN's hold time is taken into account (0 on either side disables the timers, otherwise the smaller value wins), and the keepalive and hold timers are driven by that negotiated value. +* **RFC 6793 AS4_PATH fallback** - a session that did not negotiate the four-octet AS capability now carries `AS_TRANS` in AS_PATH and the real local ASN in AS4_PATH instead of a truncated 2-octet AS_PATH. +* **RFC 2918 route refresh replay** - a received ROUTE-REFRESH for a negotiated family re-sends that family's Adj-RIB-Out followed by its End-of-RIB (the hold timer reset is unchanged); a refresh for a family the session does not carry is ignored, and the RFC 7313 BoRR/EoRR subtypes are not implemented. +* **End-of-RIB for a capability-less peer** - the IPv4 End-of-RIB decision now agrees with the announcement decision, so a plain RFC 4271 peer that negotiated no capabilities gets its IPv4 marker. +* **One initial table send** - the establishment table is sent exactly once, inside the registration critical section, with the End-of-RIB markers after it; the previous pre-lock send re-sent every copy after the EoR and archived it twice. +* The TCP-MD5 socket helpers are re-exported as `focl::bgp::{TcpSocketExt, TcpStreamExt}`. + ### New features * **Real peering collector (Phase 1)** - the established session loop no longer discards UPDATEs: raw frames go to the archive and parsed prefixes fill a per-peer Adj-RIB-In that `focl rib in` reads, cleared on session end. OPEN advertises MP-BGP IPv4 and IPv6 unicast plus four-octet AS (AS_TRANS on the wire for a 4-byte local ASN) and, when configured, route refresh; peer capabilities are parsed from the raw frame with negotiated families, ASN4 and route refresh tracked per session, and the remote ASN validated including AS_TRANS resolution. A peer that negotiates no capabilities still establishes plain IPv4 unicast. IPv4 prefixes are announced with classic NLRI and NEXT_HOP, IPv6 through MP_REACH_NLRI, and an invalid non-IPv6 configured next hop is rejected instead of malformed-encoded. diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 4aea7ad..e421cd4 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -1,5 +1,6 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::os::unix::io::AsRawFd; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; @@ -8,7 +9,8 @@ use anyhow::{anyhow, Context, Result}; use bgpkit_parser::bgp::parse_bgp_message; use bgpkit_parser::models::{ Afi, AsPath, Asn, AsnLength, AttrFlags, Attribute, AttributeValue, Attributes, BgpMessage, - BgpOpenMessage, BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, Safi, + BgpOpenMessage, BgpRouteRefreshMessage, BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, + Origin, ParamValue, Safi, }; use bytes::Bytes; use ipnet::IpNet; @@ -26,7 +28,10 @@ use crate::config::{FoclConfig, PeerConfig}; use crate::types::{Event, EventEnvelope, PeerState}; mod auth; -use auth::{TcpSocketExt, TcpStreamExt}; +/// TCP-MD5 socket helpers (RFC 2385). Re-exported so library users and the +/// socket-level tests can authenticate a session against `focld` the same way +/// the daemon does. +pub use auth::{TcpSocketExt, TcpStreamExt}; const AS_TRANS: u16 = 23_456; @@ -405,6 +410,22 @@ impl NegotiatedCapabilities { fn plain_ipv4(&self) -> bool { self.families.is_empty() } + + /// Whether the session carries the family for announcements and for + /// End-of-RIB: a capability-less peer still has classic IPv4 (RFC 4271), + /// so every IPv4 decision has to accept [`Self::plain_ipv4`] as well. + fn carries(&self, afi: Afi, safi: Safi) -> bool { + self.supports(afi, safi) || (afi == Afi::Ipv4 && safi == Safi::Unicast && self.plain_ipv4()) + } + + /// AS number width on this session's wire (RFC 6793). + fn asn_length(&self) -> AsnLength { + if self.asn4 { + AsnLength::Bits32 + } else { + AsnLength::Bits16 + } + } } struct BgpServiceInner { @@ -469,7 +490,9 @@ impl BgpService { let service = Self { inner }; service.start_peers(&cfg.peers).await; if cfg.global.listen { - service.start_listener(&cfg.global.listen_addr).await?; + service + .start_listener(&cfg.global.listen_addr, &cfg.peers) + .await?; } service.start_clock_refresh().await; Ok(service) @@ -519,10 +542,15 @@ impl BgpService { tokio::spawn(async move { service.peer_loop(peer_cfg).await }) } - async fn start_listener(&self, listen_addr: &str) -> Result<()> { + async fn start_listener(&self, listen_addr: &str, peers: &[PeerConfig]) -> Result<()> { let listener = TcpListener::bind(listen_addr) .await .with_context(|| format!("failed binding global BGP listener {listen_addr}"))?; + // RFC 2385: the kernel validates the MD5 digest when the SYN arrives, + // so a passive peer's key has to live on the listening socket before + // `accept()` can ever return for that peer. The accepted-connection + // install in `accept_inbound` stays as the per-connection assertion. + install_listener_md5_keys(listener.as_raw_fd(), &listener_md5_keys(peers)); let service = self.clone(); tokio::spawn(async move { loop { @@ -726,11 +754,13 @@ impl BgpService { .await; let local_as = peer.local_as.unwrap_or(self.inner.global_asn); - let hold_time = peer.hold_time_secs.max(3); + // RFC 4271 s4.2: the OPEN carries the configured hold time as-is; 0 is + // a deliberate "timers disabled" setting and must not be raised to a + // minimum here. let open = local_open( self.inner.router_id, local_as, - hold_time, + peer.hold_time_secs, peer.route_refresh, ); write_bgp_message(&mut writer, &open, AsnLength::Bits32).await?; @@ -741,6 +771,9 @@ impl BgpService { }; let negotiated = negotiate_capabilities(&incoming.raw, peer.route_refresh); validate_remote_as(&remote_open, &incoming.raw, peer.remote_as, negotiated.asn4)?; + // RFC 4271 s4.4/s6.1: the hold time that governs this session is 0 when + // either side advertised 0, otherwise the smaller of the two. + let hold_time = negotiate_hold_time(peer.hold_time_secs, remote_open.hold_time); self.set_peer_state(&peer.address, PeerState::OpenConfirm, None, None) .await; @@ -757,55 +790,19 @@ impl BgpService { Some(chrono::Utc::now().timestamp()), ) .await; - self.send_prefix_announcements(peer, &mut writer, &negotiated, local_ip) - .await?; - // RFC 4271 End-of-RIB: an empty UPDATE per family marks the initial - // table transfer complete. Vultr's route servers treat a session - // missing EoR as still converging; send both families' markers. - for eor_family in [Afi::Ipv4, Afi::Ipv6] { - if negotiated.supports(eor_family, Safi::Unicast) { - let eor = if eor_family == Afi::Ipv4 { - BgpMessage::Update(BgpUpdateMessage::default()) - } else { - let mut attrs = Attributes::default(); - attrs.add_attr( - AttributeValue::MpUnreachNlri(Nlri { - afi: Afi::Ipv6, - safi: Safi::Unicast, - next_hop: None, - prefixes: vec![], - labeled_prefixes: None, - link_state_nlris: None, - flowspec_nlris: None, - }) - .into(), - ); - BgpMessage::Update(BgpUpdateMessage { - withdrawn_prefixes: vec![], - attributes: attrs, - announced_prefixes: vec![], - }) - }; - let asn_len = if negotiated.asn4 { - AsnLength::Bits32 - } else { - AsnLength::Bits16 - }; - write_bgp_message(&mut writer, &eor, asn_len).await?; - } - } - - // Register and send the initial table under the mutation lock: a - // concurrent add/remove that lands between the snapshot and the - // registration would otherwise never reach this session, leaving it - // advertising a stale set until the next mutation. + // Register this session and send its initial table in one critical + // section under the mutation lock: a concurrent add/remove landing + // between the snapshot and the registration would otherwise never + // reach this session (stale set until the next mutation), and + // registering before the snapshot would deliver the same change twice. + // The End-of-RIB markers follow that single send, so the initial table + // reaches the peer exactly once. let (ctrl_tx, mut ctrl_rx) = mpsc::channel::(64); { let _guard = self.inner.prefix_ops.lock().await; let handle = SessionHandle { tx: ctrl_tx, - supports_v4: negotiated.plain_ipv4() - || negotiated.supports(Afi::Ipv4, Safi::Unicast), + supports_v4: negotiated.carries(Afi::Ipv4, Safi::Unicast), supports_v6: negotiated.supports(Afi::Ipv6, Safi::Unicast), }; self.inner @@ -815,23 +812,41 @@ impl BgpService { .insert(peer.address.clone(), handle); self.send_prefix_announcements(peer, &mut writer, &negotiated, local_ip) .await?; + // RFC 4271 End-of-RIB: an empty UPDATE per family marks the initial + // table transfer complete. A capability-less RFC 4271 peer still + // gets the IPv4 marker, and a route server missing one treats the + // session as still converging. + for eor_family in [Afi::Ipv4, Afi::Ipv6] { + if negotiated.carries(eor_family, Safi::Unicast) { + write_bgp_message( + &mut writer, + &end_of_rib(eor_family), + negotiated.asn_length(), + ) + .await?; + } + } } - let negotiated_hold = Duration::from_secs(hold_time as u64); - let keepalive_interval = Duration::from_secs((hold_time as u64 / 3).max(1)); - let mut next_keepalive = Instant::now() + keepalive_interval; - let mut hold_deadline = Instant::now() + negotiated_hold; + // RFC 4271 s4.4: a negotiated hold time of 0 disables both the + // keepalive and the hold timer, so they are only armed when non-zero. + let keepalive_interval = + (hold_time != 0).then(|| Duration::from_secs((u64::from(hold_time) / 3).max(1))); + let mut next_keepalive = keepalive_interval.map(|interval| Instant::now() + interval); + let mut hold_deadline = reset_hold_deadline(hold_time); loop { let now = Instant::now(); - if now >= next_keepalive { + if next_keepalive.is_some_and(|deadline| now >= deadline) { write_bgp_message(&mut writer, &BgpMessage::KeepAlive, AsnLength::Bits32).await?; - next_keepalive = now + keepalive_interval; + next_keepalive = keepalive_interval.map(|interval| now + interval); } - if now >= hold_deadline { + if hold_deadline.is_some_and(|deadline| now >= deadline) { return Err(anyhow!("hold timer expired")); } let timeout_dur = std::cmp::min( - next_keepalive.saturating_duration_since(now), + next_keepalive.map_or(Duration::from_secs(1), |next| { + next.saturating_duration_since(now) + }), Duration::from_secs(1), ); // Runtime announce/withdraw commands are applied between reads; the @@ -858,12 +873,21 @@ impl BgpService { &negotiated, ) .await?; - hold_deadline = Instant::now() + negotiated_hold; + hold_deadline = reset_hold_deadline(hold_time); + } + BgpMessage::RouteRefresh(refresh) => { + hold_deadline = reset_hold_deadline(hold_time); + self.replay_route_refresh( + peer, + &mut writer, + &negotiated, + local_ip, + &refresh, + ) + .await?; } - BgpMessage::KeepAlive - | BgpMessage::Open(_) - | BgpMessage::RouteRefresh(_) => { - hold_deadline = Instant::now() + negotiated_hold; + BgpMessage::KeepAlive | BgpMessage::Open(_) => { + hold_deadline = reset_hold_deadline(hold_time); } BgpMessage::Notification(_) => { return Err(anyhow!("received NOTIFICATION from peer")) @@ -909,6 +933,55 @@ impl BgpService { Ok(()) } + /// RFC 2918 s4: answer a ROUTE-REFRESH by re-sending this session's + /// Adj-RIB-Out for the requested family, followed by that family's + /// End-of-RIB. A refresh for a family the session does not carry is + /// ignored; the caller resets the hold timer either way. + async fn replay_route_refresh( + &self, + peer: &PeerConfig, + writer: &mut W, + negotiated: &NegotiatedCapabilities, + local_ip: IpAddr, + refresh: &BgpRouteRefreshMessage, + ) -> Result<()> { + let (Some(afi), Some(safi)) = (refresh.afi(), refresh.safi()) else { + return Ok(()); + }; + // Subtype 1/2 (BoRR/EoRR, RFC 7313) are not implemented, and answering + // them as a normal refresh would send a table the peer did not ask for. + if refresh.subtype != 0 || !negotiated.carries(afi, safi) { + return Ok(()); + } + let local_as = peer.local_as.unwrap_or(self.inner.global_asn); + let updates = { + // Snapshot under the mutation lock, so an incremental change cannot + // interleave with the replay: an earlier mutation is already in the + // snapshot, a later one is dispatched after the replay is written. + let _guard = self.inner.prefix_ops.lock().await; + let prefixes: Vec = self + .inner + .prefix_state + .read() + .await + .effective() + .into_iter() + .filter(|entry| afi_of(&entry.network) == afi) + .collect(); + build_announce_updates( + &prefixes, + self.inner.router_id, + local_ip, + local_as, + negotiated, + ) + }; + self.emit_updates(peer, writer, negotiated, local_ip, local_as, updates) + .await?; + write_bgp_message(writer, &end_of_rib(afi), negotiated.asn_length()).await?; + Ok(()) + } + /// Recomputes how many announcements this session currently carries. async fn refresh_advertised_count( &self, @@ -944,11 +1017,7 @@ impl BgpService { local_as: u32, updates: Vec, ) -> Result<()> { - let asn_len = if negotiated.asn4 { - AsnLength::Bits32 - } else { - AsnLength::Bits16 - }; + let asn_len = negotiated.asn_length(); for update in updates { let raw = write_bgp_message(writer, &update, asn_len).await?; if let Some(archive) = &self.inner.archive { @@ -1008,8 +1077,7 @@ impl BgpService { let rib = ribs.entry(peer.to_string()).or_insert_with(IpnetTrie::new); // Plain IPv4 NLRI is only valid on a session that carries IPv4 // (negotiated v4 MP capability or a capability-less RFC 4271 peer). - let classic_ipv4_ok = - negotiated.plain_ipv4() || negotiated.supports(Afi::Ipv4, Safi::Unicast); + let classic_ipv4_ok = negotiated.carries(Afi::Ipv4, Safi::Unicast); for prefix in &update.withdrawn_prefixes { if classic_ipv4_ok { rib.remove(prefix.prefix); @@ -1414,6 +1482,58 @@ impl BgpService { } } +/// RFC 4271 s4.2/s6.1 hold-time negotiation: a hold time of 0 on either side +/// disables the timers, otherwise the smaller advertised value is the +/// negotiated one. +fn negotiate_hold_time(local: u16, remote: u16) -> u16 { + if local == 0 || remote == 0 { + 0 + } else { + local.min(remote) + } +} + +/// Restarts the hold timer after a received message. `None` when the negotiated +/// hold time is 0, which disables the timer (RFC 4271 s4.4). +fn reset_hold_deadline(hold_time: u16) -> Option { + (hold_time != 0).then(|| Instant::now() + Duration::from_secs(u64::from(hold_time))) +} + +/// RFC 4271 End-of-RIB: an empty UPDATE marks one family's initial or refreshed +/// table as complete. IPv4 uses the classic empty UPDATE, IPv6 the MP_UNREACH +/// form with no NLRI. +fn end_of_rib(family: Afi) -> BgpMessage { + if family == Afi::Ipv4 { + return BgpMessage::Update(BgpUpdateMessage::default()); + } + let mut attrs = Attributes::default(); + attrs.add_attr( + AttributeValue::MpUnreachNlri(Nlri { + afi: family, + safi: Safi::Unicast, + next_hop: None, + prefixes: vec![], + labeled_prefixes: None, + link_state_nlris: None, + flowspec_nlris: None, + }) + .into(), + ); + BgpMessage::Update(BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![], + }) +} + +/// Address family of an originated prefix. +fn afi_of(network: &IpNet) -> Afi { + match network { + IpNet::V4(_) => Afi::Ipv4, + IpNet::V6(_) => Afi::Ipv6, + } +} + fn local_open( router_id: Ipv4Addr, local_as: u32, @@ -1524,13 +1644,12 @@ fn build_announce_updates( ) -> Vec { let now = unix_now(); let mut result = Vec::new(); - let plain_ipv4 = negotiated.plain_ipv4(); for prefix in prefixes .iter() .filter(|prefix| matches!(prefix.network, IpNet::V4(_))) { - if plain_ipv4 || negotiated.supports(Afi::Ipv4, Safi::Unicast) { - let mut attrs = base_announce_attributes(local_as); + if negotiated.carries(Afi::Ipv4, Safi::Unicast) { + let mut attrs = base_announce_attributes(local_as, negotiated); let next_hop = prefix.next_hop.unwrap_or(IpAddr::V4(router_id)); attrs.add_attr(AttributeValue::NextHop(next_hop).into()); attach_dev_attr255(&mut attrs, prefix, now); @@ -1548,7 +1667,7 @@ fn build_announce_updates( if !negotiated.supports(Afi::Ipv6, Safi::Unicast) { continue; } - let mut attrs = base_announce_attributes(local_as); + let mut attrs = base_announce_attributes(local_as, negotiated); // MP_REACH requires an IPv6 next hop. A configured non-v6 next hop is // ignored rather than serializing a malformed NEXT_HOP attribute. let next_hop = prefix @@ -1578,7 +1697,7 @@ fn build_withdraw_updates( negotiated: &NegotiatedCapabilities, ) -> Vec { let mut result = Vec::new(); - let classic_ipv4_ok = negotiated.plain_ipv4() || negotiated.supports(Afi::Ipv4, Safi::Unicast); + let classic_ipv4_ok = negotiated.carries(Afi::Ipv4, Safi::Unicast); let v4: Vec = networks .iter() .filter(|network| matches!(network, IpNet::V4(_))) @@ -1621,21 +1740,38 @@ fn build_withdraw_updates( result } -fn base_announce_attributes(local_as: u32) -> Attributes { +fn base_announce_attributes(local_as: u32, negotiated: &NegotiatedCapabilities) -> Attributes { let mut attrs = Attributes::default(); attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); + // `is_as4: true` selects AS4_PATH (attribute type 17) and the encoder + // always writes it with 4-octet segments. On a session that negotiated + // 4-octet AS support the correct wire form is AS_PATH (type 2) with + // 4-octet segments, so `is_as4` stays false and the session AsnLength + // drives the width. A session without that capability cannot carry a + // 4-octet ASN in AS_PATH (RFC 6793 s4.2), so an unrepresentable local ASN + // goes into AS4_PATH while AS_TRANS takes its place in AS_PATH; a 2-octet + // local ASN needs neither and keeps a plain AS_PATH. + let (as_path, real_asn) = if !negotiated.asn4 && local_as > u32::from(u16::MAX) { + (u32::from(AS_TRANS), Some(local_as)) + } else { + (local_as, None) + }; attrs.add_attr( AttributeValue::AsPath { - path: AsPath::from_sequence([local_as]), - // `is_as4: true` selects AS4_PATH (attribute type 17), which is - // only for the RFC 6793 migration fallback. On a session that - // negotiated 4-octet AS, the correct wire form is AS_PATH (type 2) - // with 4-octet segments: keep this false and let the session - // AsnLength (Bits32 when AS4, Bits16 otherwise) drive the width. + path: AsPath::from_sequence([as_path]), is_as4: false, } .into(), ); + if let Some(real_asn) = real_asn { + attrs.add_attr( + AttributeValue::AsPath { + path: AsPath::from_sequence([real_asn]), + is_as4: true, + } + .into(), + ); + } attrs } @@ -1734,6 +1870,31 @@ fn normalize_socket_addr(raw: &str, default_port: u16) -> Result { Ok(SocketAddr::new(address, default_port)) } +/// Per-peer TCP-MD5 keys for the listening socket: every enabled peer that +/// has a password. A peer whose configured address is not a literal IP cannot +/// be keyed here; the session path reports such an address. +fn listener_md5_keys(peers: &[PeerConfig]) -> Vec<(IpAddr, String)> { + peers + .iter() + .filter(|peer| peer.enabled) + .filter_map(|peer| Some((peer.address.parse::().ok()?, peer.password.clone()?))) + .collect() +} + +/// Installs `keys` on a listening socket (RFC 2385). The port of a TCP-MD5 key +/// is not part of the kernel's lookup (the key is per peer address, and the +/// source port of an inbound connection is ephemeral), so the BGP port is used. +/// A key the kernel refuses is logged rather than fatal: that peer cannot +/// complete the handshake, but the listener still serves the others. +fn install_listener_md5_keys(fd: i32, keys: &[(IpAddr, String)]) { + for (address, password) in keys { + let remote = SocketAddr::new(*address, 179); + if let Err(error) = auth::set_tcp_md5_signature(fd, &remote, password) { + tracing::warn!(peer=%address, error=%error, "failed to install TCP-MD5 key on the BGP listener"); + } + } +} + async fn write_bgp_message( stream: &mut W, message: &BgpMessage, @@ -1795,12 +1956,15 @@ mod tests { #[test] fn announce_updates_use_type2_as_path_with_negotiated_width() { - fn as_path_attr(msg: &BgpMessage, asn_len: AsnLength) -> (u8, Vec) { + /// Every AS_PATH (2) and AS4_PATH (17) attribute on the encoded + /// message, in wire order. + fn as_path_attrs(msg: &BgpMessage, asn_len: AsnLength) -> Vec<(u8, Vec)> { let BgpMessage::Update(u) = msg else { panic!("not an UPDATE") }; let mut buf = bytes::BytesMut::new(); u.attributes.encode_to(asn_len, &mut buf).unwrap(); + let mut attrs = Vec::new(); let mut p = 0; while p < buf.len() { let flags = buf[p]; @@ -1811,11 +1975,12 @@ mod tests { (buf[p + 2] as usize, 3) }; if code == 2 || code == 17 { - return (code, buf[p + hdr..p + hdr + l].to_vec()); + attrs.push((code, buf[p + hdr..p + hdr + l].to_vec())); } p += hdr + l; } - panic!("no AS_PATH attribute found"); + assert!(!attrs.is_empty(), "no AS_PATH attribute found"); + attrs } let prefixes = vec![PrefixEntry { @@ -1838,10 +2003,9 @@ mod tests { ); // RFC 6793: AS4-capable session carries AS_PATH (type 2) with // 4-octet segments, one AS_SEQUENCE {400644} = 0x00061D04. - let (code, val) = as_path_attr(&updates[0], AsnLength::Bits32); assert_eq!( - (code, val.as_slice()), - (2u8, &[2u8, 1, 0x00, 0x06, 0x1D, 0x04][..]) + as_path_attrs(&updates[0], AsnLength::Bits32), + vec![(2u8, vec![2u8, 1, 0x00, 0x06, 0x1D, 0x04])] ); // Plain 16-bit peer (e.g. local AS 65010): type 2 with 2-octet segments. @@ -1857,8 +2021,52 @@ mod tests { 65010, &plain, ); - let (code, val) = as_path_attr(&updates[0], AsnLength::Bits16); - assert_eq!((code, val.as_slice()), (2u8, &[2u8, 1, 0xFD, 0xF2][..])); + assert_eq!( + as_path_attrs(&updates[0], AsnLength::Bits16), + vec![(2u8, vec![2u8, 1, 0xFD, 0xF2])] + ); + + // RFC 6793 s4.2: a session without AS4 support cannot carry a 4-octet + // ASN in AS_PATH, so AS_TRANS (23456) goes there and the real ASN goes + // into AS4_PATH. The old encoding truncated 400644 to its low 16 bits + // (0x1D04 = AS 7428) on the wire. + let updates = build_announce_updates( + &prefixes, + "192.0.2.1".parse().unwrap(), + IpAddr::V4("192.0.2.1".parse().unwrap()), + 400_644, + &plain, + ); + assert_eq!( + as_path_attrs(&updates[0], AsnLength::Bits16), + vec![ + (2u8, vec![2u8, 1, 0x5B, 0xA0]), + (17u8, vec![2u8, 1, 0x00, 0x06, 0x1D, 0x04]), + ] + ); + + // The pair round-trips through bgpkit-parser exactly as it goes out: + // AS_PATH is AS_TRANS and AS4_PATH carries the real local ASN. + let mut raw = updates[0].encode(AsnLength::Bits16).unwrap(); + let parsed = parse_bgp_message(&mut raw, false, &AsnLength::Bits16).unwrap(); + let BgpMessage::Update(parsed) = parsed else { + panic!("not an UPDATE") + }; + let paths: Vec<(bool, String)> = parsed + .attributes + .into_attributes_iter() + .filter_map(|attribute| match attribute.value { + AttributeValue::AsPath { path, is_as4 } => Some((is_as4, path.to_string())), + _ => None, + }) + .collect(); + assert_eq!( + paths, + vec![ + (false, AS_TRANS.to_string()), + (true, 400_644u32.to_string()), + ] + ); } #[test] @@ -1878,6 +2086,106 @@ mod tests { assert!(negotiated.route_refresh); } + #[test] + fn listener_md5_keys_cover_exactly_the_enabled_peers_with_passwords() { + let peers = vec![ + md5_peer("192.0.2.1", true, Some("first")), + md5_peer("192.0.2.2", false, Some("disabled-peer")), + md5_peer("192.0.2.3", true, None), + md5_peer("2001:db8::1", true, Some("v6-peer")), + md5_peer("not-an-address", true, Some("unusable")), + ]; + assert_eq!( + listener_md5_keys(&peers), + vec![ + ("192.0.2.1".parse::().unwrap(), "first".to_string()), + ( + "2001:db8::1".parse::().unwrap(), + "v6-peer".to_string() + ), + ] + ); + assert!(listener_md5_keys(&[]).is_empty()); + } + + fn md5_peer(address: &str, enabled: bool, password: Option<&str>) -> PeerConfig { + PeerConfig { + address: address.to_string(), + remote_as: 65_002, + local_as: None, + hold_time_secs: 90, + connect_retry_secs: 5, + remote_port: 179, + local_address: None, + enabled, + passive: true, + route_refresh: true, + name: None, + password: password.map(str::to_string), + } + } + + #[test] + fn local_open_advertises_the_configured_hold_time_including_zero() { + for advertised in [0u16, 30, 90] { + let BgpMessage::Open(open) = + local_open(Ipv4Addr::new(192, 0, 2, 1), 65_001, advertised, true) + else { + panic!() + }; + assert_eq!( + open.hold_time, advertised, + "the OPEN must advertise the configured hold time unchanged" + ); + } + } + + #[test] + fn negotiated_hold_time_is_zero_if_either_side_disables_it_else_the_minimum() { + assert_eq!(negotiate_hold_time(0, 180), 0); + assert_eq!(negotiate_hold_time(90, 30), 30); + assert_eq!(negotiate_hold_time(90, 0), 0); + assert_eq!(negotiate_hold_time(90, 180), 90); + assert_eq!(negotiate_hold_time(30, 30), 30); + } + + #[test] + fn a_capability_less_peer_still_carries_ipv4_unicast() { + let plain = NegotiatedCapabilities::default(); + assert!(plain.plain_ipv4()); + assert!(plain.carries(Afi::Ipv4, Safi::Unicast)); + assert!(!plain.carries(Afi::Ipv6, Safi::Unicast)); + + let v6_only = NegotiatedCapabilities { + families: HashSet::from([(Afi::Ipv6, Safi::Unicast)]), + ..Default::default() + }; + assert!(!v6_only.carries(Afi::Ipv4, Safi::Unicast)); + assert!(v6_only.carries(Afi::Ipv6, Safi::Unicast)); + } + + #[test] + fn end_of_rib_markers_are_empty_per_family() { + let BgpMessage::Update(v4) = end_of_rib(Afi::Ipv4) else { + panic!("not an UPDATE") + }; + assert!(v4.withdrawn_prefixes.is_empty()); + assert!(v4.announced_prefixes.is_empty()); + assert!(v4.attributes.into_attributes_iter().next().is_none()); + + let BgpMessage::Update(v6) = end_of_rib(Afi::Ipv6) else { + panic!("not an UPDATE") + }; + assert!(v6.withdrawn_prefixes.is_empty()); + assert!(v6.announced_prefixes.is_empty()); + let unreach = v6 + .attributes + .get_unreachable_nlri() + .expect("MP_UNREACH present"); + assert_eq!(unreach.afi, Afi::Ipv6); + assert!(unreach.prefixes.is_empty()); + } + #[test] fn prefix_state_layers_runtime_overrides_over_config() { let config = vec![ diff --git a/tests/acceptance_peer.rs b/tests/acceptance_peer.rs index 51edd1b..ff00e7c 100644 --- a/tests/acceptance_peer.rs +++ b/tests/acceptance_peer.rs @@ -1,30 +1,32 @@ use std::io::{Cursor, Read}; -use std::net::{IpAddr, Ipv4Addr, TcpListener as StdTcpListener}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener as StdTcpListener}; use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result}; use bgpkit_parser::bgp::parse_bgp_message; use bgpkit_parser::models::{ - AsPath, Asn, AsnLength, AttrFlags, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, - BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, + Afi, AsPath, Asn, AsnLength, AttrFlags, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, + BgpRouteRefreshMessage, BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, }; use bgpkit_parser::parse_mrt_record; use bytes::Bytes; use flate2::read::GzDecoder; use focl::archive::types::ArchiveStream; use focl::archive::ArchiveService; -use focl::bgp::{BgpService, PrefixSource, PrefixStatus}; +use focl::bgp::{BgpService, PrefixSource, PrefixStatus, TcpSocketExt}; use focl::config::{ArchiveConfig, FoclConfig, GlobalConfig, PeerConfig, PrefixConfig}; use focl::types::{Event, PeerState}; use ipnet::IpNet; use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::TcpStream; +use tokio::net::{TcpSocket, TcpStream}; use tokio::sync::broadcast; use tokio::time::timeout; const PEER_AS: u32 = 65_002; const FOCL_AS: u32 = 65_001; +/// The TCP-MD5 password of the passive peer in the MD5 acceptance test. +const MD5_PASSWORD: &str = "focl-md5-acceptance"; /// The IPv6 prefix carrying the attribute-255 clock in the clock tests. const CLOCK_PREFIX: &str = "2001:db8:feed::/48"; @@ -166,7 +168,8 @@ async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<() parse_mrt_record(&mut cursor)?; record_count += 1; } - // two outbound configured-prefix UPDATEs plus the two peer UPDATEs, and state changes. + // one outbound UPDATE per configured prefix plus the two peer UPDATEs, and + // state changes. assert!( record_count >= 4, "expected both directions in archived BGP4MP records" @@ -179,6 +182,18 @@ async fn service_with_prefixes( temp: &tempfile::TempDir, port: u16, prefixes: Vec, +) -> Result { + service_with_peer(temp, port, prefixes, None, 30).await +} + +/// Same as [`service_with_prefixes`], with an optional TCP-MD5 password and an +/// explicit hold time on the passive peer. +async fn service_with_peer( + temp: &tempfile::TempDir, + port: u16, + prefixes: Vec, + password: Option<&str>, + hold_time_secs: u16, ) -> Result { let cfg = FoclConfig { global: GlobalConfig { @@ -193,7 +208,7 @@ async fn service_with_prefixes( address: "127.0.0.1".to_string(), remote_as: PEER_AS, local_as: None, - hold_time_secs: 30, + hold_time_secs, connect_retry_secs: 1, remote_port: port, local_address: None, @@ -201,7 +216,7 @@ async fn service_with_prefixes( passive: true, route_refresh: true, name: None, - password: None, + password: password.map(str::to_string), }], prefixes, archive: ArchiveConfig { @@ -235,6 +250,18 @@ async fn service_with_clock_prefix(temp: &tempfile::TempDir, port: u16) -> Resul /// Connects as the peer side and completes the OPEN/KEEPALIVE exchange. async fn establish_peer_session(port: u16, capabilities: Vec) -> Result { + establish_session(port, peer_open_with_capabilities(capabilities)).await +} + +/// Connects as a peer that negotiates no capabilities at all: a plain RFC 4271 +/// IPv4-only speaker, whose OPEN carries no optional parameters. +async fn establish_capability_less_session(port: u16) -> Result { + establish_session(port, peer_open_without_capabilities()).await +} + +/// Connects as the peer side with `open` and completes the OPEN/KEEPALIVE +/// exchange. +async fn establish_session(port: u16, open: BgpMessage) -> Result { let mut stream = timeout( Duration::from_secs(5), TcpStream::connect(("127.0.0.1", port)), @@ -244,7 +271,7 @@ async fn establish_peer_session(port: u16, capabilities: Vec) -> Result Result<()> { Ok(()) } +/// TCP-MD5 (RFC 2385) on a passive session: the kernel validates the digest on +/// the SYN, before `accept()` can return, so the key has to be installed on the +/// listening socket. Without that install a peer with a configured password can +/// never complete the handshake (its connect hangs, the session never starts). +#[cfg(target_os = "linux")] +#[tokio::test] +async fn passive_session_with_md5_completes_the_handshake() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let bgp = service_with_peer( + &temp, + port, + vec![PrefixConfig { + network: "198.51.100.0/24".to_string(), + next_hop: Some("192.0.2.1".to_string()), + dev_attr255_interval_secs: None, + }], + Some(MD5_PASSWORD), + 30, + ) + .await?; + + // The peer side installs the same key on its own socket before connecting, + // exactly like an authenticating router would. Installing a TCP-MD5 key + // needs CAP_NET_ADMIN, like it does for the daemon. + let remote = SocketAddr::from(([127, 0, 0, 1], port)); + let socket = TcpSocket::new_v4()?; + socket + .set_md5_signature(&remote, MD5_PASSWORD) + .context("installing the peer-side TCP-MD5 key (needs CAP_NET_ADMIN)")?; + let mut stream = timeout(Duration::from_secs(5), socket.connect(remote)) + .await + .context("the MD5-keyed peer could not connect: the listener has no key")??; + + assert!(matches!( + read_message(&mut stream).await?, + BgpMessage::Open(_) + )); + write_message(&mut stream, &peer_open()).await?; + assert!(matches!( + read_message(&mut stream).await?, + BgpMessage::KeepAlive + )); + write_message(&mut stream, &BgpMessage::KeepAlive).await?; + + // The authenticated session exchanges routes like any other. + let announcement = read_message(&mut stream).await?; + assert!( + has_focl_v4(&announcement), + "expected the configured table over the MD5 session, got {announcement:?}" + ); + assert!(ipv4_eor(&read_message(&mut stream).await?)); + let peer = bgp + .peer_show("127.0.0.1") + .await + .context("peer stays configured")?; + assert!(matches!(peer.state, PeerState::Established)); + Ok(()) +} + +/// RFC 2918 s4: a ROUTE-REFRESH for a negotiated family replays that family's +/// Adj-RIB-Out and then its End-of-RIB. A refresh for the other family stays +/// silent (see `route_refresh_for_an_unnegotiated_family_is_ignored`). +#[tokio::test] +async fn route_refresh_replays_the_requested_family_then_end_of_rib() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let bgp = service_with_prefixes( + &temp, + port, + vec![ + PrefixConfig { + network: "198.51.100.0/24".to_string(), + next_hop: Some("192.0.2.1".to_string()), + dev_attr255_interval_secs: None, + }, + PrefixConfig { + network: "2001:db8:feed::/48".to_string(), + next_hop: Some("2001:db8::1".to_string()), + dev_attr255_interval_secs: None, + }, + ], + ) + .await?; + let mut stream = establish_peer_session(port, capabilities()).await?; + + // Establishment sends the configured table once per family, then both + // End-of-RIB markers. + let mut v4_seen = false; + let mut v6_seen = false; + let mut v4_eor_seen = false; + let mut v6_eor_seen = false; + timeout(Duration::from_secs(5), async { + while !(v4_eor_seen && v6_eor_seen) { + let message = read_message(&mut stream).await?; + v4_seen |= has_focl_v4(&message); + v6_seen |= has_focl_v6(&message); + v4_eor_seen |= ipv4_eor(&message); + v6_eor_seen |= ipv6_eor(&message); + } + Ok::<_, anyhow::Error>(()) + }) + .await??; + assert!( + v4_seen && v6_seen, + "expected both families in the initial table" + ); + + // Ask for the IPv4 table again: the replay carries the IPv4 prefix, not the + // IPv6 one, and ends with the IPv4 End-of-RIB. + write_message(&mut stream, &route_refresh(1, 1)).await?; + let replay = read_message(&mut stream).await?; + assert!( + has_focl_v4(&replay), + "expected the IPv4 announcement to be replayed, got {replay:?}" + ); + assert!( + !has_focl_v6(&replay), + "an IPv4 refresh must not replay the IPv6 table: {replay:?}" + ); + let trailing_eor = read_message(&mut stream).await?; + assert!( + ipv4_eor(&trailing_eor), + "the replay has to end with the IPv4 End-of-RIB, got {trailing_eor:?}" + ); + + let peer = bgp + .peer_show("127.0.0.1") + .await + .context("the session survives the replay")?; + assert!(matches!(peer.state, PeerState::Established)); + Ok(()) +} + +/// A refresh for a family the session did not negotiate has no Adj-RIB-Out to +/// send and must leave the session silent (RFC 2918 s4). +#[tokio::test] +async fn route_refresh_for_an_unnegotiated_family_is_ignored() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let _bgp = service_with_passive_peer(&temp, port).await?; + let mut stream = establish_peer_session(port, capabilities_v4_only()).await?; + // A v4-only peer with no configured prefixes gets the IPv4 EoR only. + assert!(ipv4_eor(&read_message(&mut stream).await?)); + + write_message(&mut stream, &route_refresh(2, 1)).await?; + assert!( + timeout(Duration::from_millis(250), read_message(&mut stream)) + .await + .is_err(), + "an IPv6 refresh on a v4-only session must be ignored" + ); + Ok(()) +} + +/// RFC 4271: a peer that negotiates no capabilities still has classic IPv4 +/// unicast, so it gets the IPv4 table and the IPv4 End-of-RIB, and only once. +#[tokio::test] +async fn capability_less_peer_receives_the_ipv4_table_and_end_of_rib_once() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let _bgp = service_with_prefixes( + &temp, + port, + vec![PrefixConfig { + network: "198.51.100.0/24".to_string(), + next_hop: Some("192.0.2.1".to_string()), + dev_attr255_interval_secs: None, + }], + ) + .await?; + let mut stream = establish_capability_less_session(port).await?; + + let announcement = read_message(&mut stream).await?; + assert!( + has_focl_v4(&announcement), + "classic NLRI is available without any capability, got {announcement:?}" + ); + let eor = read_message(&mut stream).await?; + assert!( + ipv4_eor(&eor), + "the IPv4 End-of-RIB must follow the table, got {eor:?}" + ); + + // The initial table is sent exactly once, under the registration lock: no + // duplicate announcement after the End-of-RIB, and nothing for a family + // that was not negotiated. + assert!( + timeout(Duration::from_millis(250), read_message(&mut stream)) + .await + .is_err(), + "a capability-less session must be quiet after its single table and EoR" + ); + Ok(()) +} + +/// RFC 4271 s4.2/s4.4: the OPEN advertises the configured hold time — including +/// 0, which disables the timers instead of being raised to a minimum. +#[tokio::test] +async fn open_advertises_the_configured_hold_time_including_zero() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let _bgp = service_with_peer(&temp, port, vec![], None, 0).await?; + + let mut stream = timeout( + Duration::from_secs(5), + TcpStream::connect(("127.0.0.1", port)), + ) + .await??; + let BgpMessage::Open(open) = read_message(&mut stream).await? else { + panic!("the first message from focld must be an OPEN") + }; + assert_eq!( + open.hold_time, 0, + "a configured hold time of 0 means \"no timers\" and must be advertised as-is" + ); + Ok(()) +} + /// The attribute-255 clock travels on the wire for a configured prefix and is /// re-announced with a fresh embedded unix time on the configured interval. #[tokio::test] @@ -489,6 +735,44 @@ fn peer_open() -> BgpMessage { peer_open_with_capabilities(capabilities()) } +/// An OPEN without any optional parameter: a peer that negotiates nothing. +fn peer_open_without_capabilities() -> BgpMessage { + BgpMessage::Open(BgpOpenMessage { + version: 4, + asn: Asn::new_16bit(PEER_AS as u16), + hold_time: 30, + bgp_identifier: Ipv4Addr::new(192, 0, 2, 2), + extended_length: false, + opt_params: vec![], + }) +} + +/// A ROUTE-REFRESH (RFC 2918) for one family. AFI and SAFI are the raw wire +/// integers, so the tests can also ask for a family they did not negotiate. +fn route_refresh(afi: u16, safi: u8) -> BgpMessage { + BgpMessage::RouteRefresh(BgpRouteRefreshMessage { + afi, + subtype: 0, + safi, + data: vec![], + }) +} + +/// The IPv4 End-of-RIB: an UPDATE with no NLRI and no attributes (RFC 4271). +fn ipv4_eor(message: &BgpMessage) -> bool { + matches!(message, BgpMessage::Update(update) + if update.withdrawn_prefixes.is_empty() + && update.announced_prefixes.is_empty() + && update.attributes.clone().into_attributes_iter().next().is_none()) +} + +/// The IPv6 End-of-RIB: MP_UNREACH_NLRI for IPv6 with no prefix. +fn ipv6_eor(message: &BgpMessage) -> bool { + matches!(message, BgpMessage::Update(update) + if update.announced_prefixes.is_empty() + && update.attributes.get_unreachable_nlri().is_some_and(|nlri| nlri.afi == Afi::Ipv6 && nlri.prefixes.is_empty())) +} + fn attrs() -> Attributes { let mut attrs = Attributes::default(); attrs.add_attr(AttributeValue::Origin(Origin::IGP).into()); @@ -622,8 +906,13 @@ async fn read_message(stream: &mut TcpStream) -> Result { timeout(Duration::from_secs(5), stream.read_exact(&mut body)).await??; raw.extend_from_slice(&body); } - let mut bytes = Bytes::from(raw); - Ok(parse_bgp_message(&mut bytes, false, &AsnLength::Bits32)?) + // A session without the four-octet AS capability encodes its AS_PATH with + // 2-octet segments, so fall back to that width like focld's own reader. + let mut wide = Bytes::from(raw.clone()); + let mut narrow = Bytes::from(raw); + parse_bgp_message(&mut wide, false, &AsnLength::Bits32) + .or_else(|_| parse_bgp_message(&mut narrow, false, &AsnLength::Bits16)) + .map_err(Into::into) } #[test] From 0778bd438697d391817ec9fd4df78054c380ee8e Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Mon, 28 Sep 2026 19:59:24 -0700 Subject: [PATCH 15/17] fix(bgp): prefix control review findings (remove, list, reload delta, dry-run, lock, family) Fixes six findings from the Copilot review of the runtime prefix control path. Each finding is cited by its line range in src/bgp/mod.rs at bd0605a. - src/bgp/mod.rs:304-313 PrefixState::remove early-returned when the network had a runtime entry in `added`. For a configured network with a `prefix add --next-hop` override, `prefix remove` dropped the override but never suppressed the config baseline: peers received a withdrawal while prefix_view/prefix list and any later session still treated the network as announced. The override is dropped and a configured network is suppressed in the same call; the return value still reports whether the effective originated set changed. - src/bgp/mod.rs:251-264 PrefixState::view mapped configured entries directly, so `prefix list` printed the configured next hop and source `config` for a network with a runtime override, contradicting effective() (:183-197) and source_of() (:220-228). The row is built from the `added` entry with source Runtime when one exists. - src/bgp/mod.rs:317-334 reset_overrides compared networks only, so a changed configured next hop or a changed/cleared attribute-255 interval updated the internal state without re-announcing, leaving established peers with the old attributes on the wire. The delta now compares the whole entry (network, next hop, interval) and treats an attribute change as an announcement, while a network that disappeared stays a withdrawal. Comment added: a changed interval only takes effect after a restart, because the refresh task set is sampled at startup. - src/bgp/mod.rs:1225-1240 `prefix add --dry-run` computed `changed` as `!is_announced`, while the real mutation also reports a change when the next hop differs (:283-300). `prefix add --next-hop --dry-run` wrongly reported no change and no target peers. The dry run now runs the same `add` on a clone of the state and discards it, so it agrees with the real mutation without mutating or dispatching anything. - src/bgp/mod.rs:1259-1261 prefix_remove read previous_source before acquiring prefix_ops, so a concurrent add/remove/reload could change provenance in between and the reported `source` could be wrong (including the deliberate `source: null` for a network the state never knew). Guarantee now: the mutation lock is acquired before the provenance read, and the provenance read, `changed`, and the session dispatch all happen under that single lock hold, so the reported source describes the same state the mutation applies to. Lock ordering is not observable from a single-threaded unit test; the added test covers the observable provenance behaviour instead. - src/bgp/mod.rs:346-366 parse_prefix_entries parsed next hops without validating them against the prefix family, while the runtime path calls ensure_next_hop_family (:368, used at :1220). An IPv4 prefix with an IPv6 next hop reached classic NEXT_HOP encoding (a 16-octet NEXT_HOP on the wire; RFC 8950 capability 5 is never advertised) and the inverse was silently dropped later. Each configured entry is now validated at parse time with the same helper, and the error names the entry. Tests added in src/bgp/mod.rs: remove_after_a_next_hop_override_suppresses_the_configured_prefix, prefix_list_reports_the_runtime_override_for_a_configured_network, reload_re_announces_changed_attributes_and_withdraws_gone_networks, configured_next_hop_must_match_the_prefix_family, dry_run_add_reports_a_next_hop_change_and_family_targets, prefix_remove_reads_provenance_under_the_mutation_lock. Five of the six fail against the bd0605a code with only the tests applied; the provenance test passes both ways because lock ordering is not observable from a single-threaded test, so that finding is documented here. Gates: cargo fmt --all, cargo clippy --all-targets --all-features -- -D warnings, cargo test --all-features (48 unit, 6 acceptance, 1 archive integration, all pass; exit codes 0/0/0). --- CHANGELOG.md | 1 + src/bgp/mod.rs | 288 +++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 280 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9193f00..41821c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ All notable changes to this project will be documented in this file. * Runtime prefix mutations are serialized with their dispatch, so two concurrent control clients cannot enqueue a withdrawal before the announcement it reverses. * `prefix add` treats a next-hop change as a change (peers keep the old next hop until re-announced), a runtime entry shadows the configured entry for the same network, and the default next hop is taken from the config baseline only. * A session registers for runtime changes under the same lock as its initial table send, so a mutation racing with establishment cannot leave the new session advertising a stale set. `prefix remove` reports `source: null` for a network the state never knew instead of labelling it `config`. +* Review fixes on the runtime prefix control path: `prefix remove` now also suppresses the config baseline of a configured network that carried a runtime override (previously peers got a withdrawal while the state still called the network announced), `prefix list` shows the runtime entry that is actually announced, `reload` re-announces an entry whose next hop or attribute-255 interval changed, `--dry-run` reports a next-hop change like the real mutation, provenance is read under the mutation lock, and a configured next hop that does not match the prefix family is rejected when the config is parsed. * Socket-level acceptance tests cover the runtime path: `prefix_add`/`prefix_remove` reach an established peer on the wire (announcement, withdrawal, session stays established) and a prefix is not dispatched to a peer that did not negotiate its family. * `focl --json` output now exits non-zero on a failed response; `--json` changes formatting only. * Archive writers rotate on the ingestion clock only, so a record with a late or zero event timestamp stays in the current segment with its event time preserved in the MRT header, and a rollover with no routes no longer writes an empty RIB snapshot. diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index e421cd4..45279fe 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -257,7 +257,15 @@ impl PrefixState { let mut rows: Vec = self .config .iter() - .map(|entry| self.view_of(entry, PrefixSource::Config)) + .map(|entry| { + // A runtime entry shadows the configured one for the same + // network, so the row has to describe the entry that is + // actually announced, not the config baseline behind it. + match self.added.get(&entry.network) { + Some(runtime) => self.view_of(runtime, PrefixSource::Runtime), + None => self.view_of(entry, PrefixSource::Config), + } + }) .collect(); for (network, entry) in &self.added { if self.config.iter().any(|e| e.network == *network) { @@ -308,9 +316,11 @@ impl PrefixState { /// suppressed. Returns whether the effective originated set changed. fn remove(&mut self, network: &IpNet) -> bool { let was_announced = self.is_announced(network); - if self.added.remove(network).is_some() { - return was_announced; - } + // Dropping a runtime override alone leaves a configured network + // announced through the config baseline, so a configured network has to + // be suppressed as well; otherwise peers get a withdrawal while the + // state still calls the network announced. + self.added.remove(network); if self.config.iter().any(|e| e.network == *network) { self.suppressed.insert(*network); } @@ -319,6 +329,12 @@ impl PrefixState { /// Replaces the config baseline and drops every runtime override, returning /// the prefixes to announce and to withdraw. + /// + /// The delta compares whole entries, not just networks: a changed configured + /// next hop or a changed/cleared attribute-255 interval updates the internal + /// state but leaves established peers with the old attributes on the wire, so + /// it counts as an announcement. A changed interval only takes effect after + /// a restart, because the refresh task set is sampled at startup. fn reset_overrides(&mut self, config: Vec) -> (Vec, Vec) { let before = self.effective(); self.config = config; @@ -327,7 +343,13 @@ impl PrefixState { let after = self.effective(); let announce = after .iter() - .filter(|entry| !before.iter().any(|old| old.network == entry.network)) + .filter(|entry| { + !before.iter().any(|old| { + old.network == entry.network + && old.next_hop == entry.next_hop + && old.dev_attr255_interval_secs == entry.dev_attr255_interval_secs + }) + }) .cloned() .collect(); let withdraw = before @@ -360,6 +382,18 @@ fn parse_prefix_entries(cfg: &FoclConfig) -> Result> { .map(|nh| nh.parse::()) .transpose() .with_context(|| format!("invalid next-hop address: {:?}", p.next_hop))?; + if let Some(next_hop) = next_hop { + // Same check as the runtime path: classic NEXT_HOP only carries + // the prefix's own family, so a mismatched configured next hop + // would encode a 16-octet v6 NEXT_HOP on a v4 announcement (the + // inverse is dropped later), never reaching the wire as intended. + ensure_next_hop_family(&network, next_hop).with_context(|| { + format!( + "invalid prefix entry {} with next hop {next_hop}", + p.network + ) + })?; + } Ok::<_, anyhow::Error>(PrefixEntry { network, next_hop, @@ -1295,9 +1329,12 @@ impl BgpService { dev_attr255_interval_secs: state.configured_attr255_interval(&network), } }; - // A dry run reports what would happen without touching the state. + // A dry run reports what would happen without touching the state: run + // the same `add` on a snapshot clone and discard it, so a dry run and + // the real mutation agree (including a next-hop change). let changed = if dry_run { - !self.inner.prefix_state.read().await.is_announced(&network) + let mut snapshot = self.inner.prefix_state.read().await.clone(); + snapshot.add(entry.clone()) } else { self.inner.prefix_state.write().await.add(entry.clone()) }; @@ -1324,9 +1361,12 @@ impl BgpService { /// Withdraws a prefix at runtime: a configured prefix is suppressed, a /// runtime-only one is dropped. pub async fn prefix_remove(&self, network: IpNet, dry_run: bool) -> Result { - // Provenance has to be read before the entry is dropped. - let previous_source = self.inner.prefix_state.read().await.source_of(&network); let _guard = self.inner.prefix_ops.lock().await; + // Provenance has to be read before the entry is dropped, and under the + // mutation lock: a concurrent add/remove/reload can change (or drop) it + // in between, and the reported source would not describe the entry the + // withdrawal applies to. + let previous_source = self.inner.prefix_state.read().await.source_of(&network); let changed = if dry_run { self.inner.prefix_state.read().await.is_announced(&network) } else { @@ -2294,6 +2334,40 @@ mod tests { assert_eq!(state.status_of(&entry.network), PrefixStatus::Announced); } + #[test] + fn reload_re_announces_changed_attributes_and_withdraws_gone_networks() { + let network: IpNet = "192.0.2.0/24".parse().unwrap(); + let entry = |next_hop: &str, interval: Option| PrefixEntry { + network, + next_hop: Some(next_hop.parse().unwrap()), + dev_attr255_interval_secs: interval, + }; + let mut state = PrefixState::new(vec![entry("10.0.0.1", Some(1800))]); + + // An unchanged config produces an empty delta. + let (announce, withdraw) = state.reset_overrides(vec![entry("10.0.0.1", Some(1800))]); + assert!(announce.is_empty(), "unchanged config must not re-announce"); + assert!(withdraw.is_empty()); + + // A new configured next hop only reaches the wire on a re-announcement. + let (announce, withdraw) = state.reset_overrides(vec![entry("10.0.0.9", Some(1800))]); + assert_eq!(announce.len(), 1); + assert_eq!(announce[0].next_hop, Some("10.0.0.9".parse().unwrap())); + assert!(announce[0].dev_attr255_interval_secs == Some(1800)); + assert!(withdraw.is_empty()); + + // Clearing the attribute-255 clock changes the wire attributes too. + let (announce, withdraw) = state.reset_overrides(vec![entry("10.0.0.9", None)]); + assert_eq!(announce.len(), 1); + assert_eq!(announce[0].dev_attr255_interval_secs, None); + assert!(withdraw.is_empty()); + + // A network that disappeared stays a withdrawal, not an announcement. + let (announce, withdraw) = state.reset_overrides(vec![]); + assert!(announce.is_empty()); + assert_eq!(withdraw, vec![network]); + } + #[test] fn withdraw_updates_use_withdrawn_nlri_for_v4_and_mp_unreach_for_v6() { let networks: Vec = vec![ @@ -2356,6 +2430,54 @@ mod tests { assert!(ensure_next_hop_family(&v6, "2001:db8::1".parse().unwrap()).is_ok()); } + #[test] + fn configured_next_hop_must_match_the_prefix_family() { + use crate::config::PrefixConfig; + + fn entry_config(network: &str, next_hop: &str) -> FoclConfig { + let mut cfg = test_service_config(); + cfg.prefixes = vec![PrefixConfig { + network: network.to_string(), + next_hop: Some(next_hop.to_string()), + dev_attr255_interval_secs: None, + }]; + cfg + } + + // A v6 next hop on a v4 prefix would reach classic NEXT_HOP encoding. + let error = parse_prefix_entries(&entry_config("192.0.2.0/24", "2001:db8::1")) + .expect_err("a v6 next hop on a v4 prefix must be rejected"); + let message = format!("{error:#}"); + assert!( + message.contains("192.0.2.0/24") && message.contains("2001:db8::1"), + "the error names the entry: {message}" + ); + assert!( + message.contains("does not match the prefix family"), + "{message}" + ); + + // The inverse: a v4 next hop on a v6 prefix is dropped later, so it is + // rejected at parse time too. + let error = parse_prefix_entries(&entry_config("2001:db8::/48", "192.0.2.1")) + .expect_err("a v4 next hop on a v6 prefix must be rejected"); + let message = format!("{error:#}"); + assert!( + message.contains("2001:db8::/48") && message.contains("192.0.2.1"), + "the error names the entry: {message}" + ); + + // Matching pairs still parse. + let entries = parse_prefix_entries(&entry_config("192.0.2.0/24", "192.0.2.1")) + .expect("a matching v4 pair must parse"); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].next_hop, Some("192.0.2.1".parse().unwrap())); + let entries = parse_prefix_entries(&entry_config("2001:db8::/48", "2001:db8::1")) + .expect("a matching v6 pair must parse"); + assert_eq!(entries[0].network.to_string(), "2001:db8::/48"); + assert_eq!(entries[0].next_hop, Some("2001:db8::1".parse().unwrap())); + } + #[test] fn next_hop_change_is_a_change() { let network: IpNet = "198.51.100.0/24".parse().unwrap(); @@ -2415,6 +2537,69 @@ mod tests { assert_eq!(effective[0].next_hop, Some(override_hop)); } + #[test] + fn remove_after_a_next_hop_override_suppresses_the_configured_prefix() { + let network: IpNet = "192.0.2.0/24".parse().unwrap(); + let mut state = PrefixState::new(vec![PrefixEntry { + network, + next_hop: Some("10.0.0.1".parse().unwrap()), + dev_attr255_interval_secs: None, + }]); + + // A runtime override on a configured network. + assert!(state.add(PrefixEntry { + network, + next_hop: Some("10.0.0.9".parse().unwrap()), + dev_attr255_interval_secs: None, + })); + + // Removing it must suppress the config baseline as well: dropping only + // the override leaves the network announced through the config entry. + assert!(state.remove(&network)); + assert!( + state + .effective() + .iter() + .all(|entry| entry.network != network), + "the config baseline must not stay in the effective set" + ); + assert_eq!(state.status_of(&network), PrefixStatus::Suppressed); + assert_eq!(state.source_of(&network), Some(PrefixSource::Config)); + // Removing it again changes nothing. + assert!(!state.remove(&network)); + assert_eq!(state.override_count(), 1); + } + + #[test] + fn prefix_list_reports_the_runtime_override_for_a_configured_network() { + let network: IpNet = "192.0.2.0/24".parse().unwrap(); + let mut state = PrefixState::new(vec![PrefixEntry { + network, + next_hop: Some("10.0.0.1".parse().unwrap()), + dev_attr255_interval_secs: None, + }]); + assert!(state.add(PrefixEntry { + network, + next_hop: Some("10.0.0.9".parse().unwrap()), + dev_attr255_interval_secs: None, + })); + + let rows = state.view(); + assert_eq!( + rows.len(), + 1, + "the override must not add a second row for the same network" + ); + assert_eq!(rows[0].network, network.to_string()); + assert_eq!( + rows[0].next_hop.as_deref(), + Some("10.0.0.9"), + "the row must describe the entry that is announced" + ); + assert_eq!(rows[0].source, PrefixSource::Runtime); + assert_eq!(rows[0].status, PrefixStatus::Announced); + } + #[test] fn default_next_hop_comes_from_the_config_only() { let v4: IpNet = "192.0.2.0/24".parse().unwrap(); @@ -2678,4 +2863,89 @@ enabled = false .contains("does not match the prefix family")); assert!(service.prefix_view().await.is_empty()); } + + #[tokio::test] + async fn dry_run_add_reports_a_next_hop_change_and_family_targets() { + use crate::config::PrefixConfig; + + let network: IpNet = "192.0.2.0/24".parse().unwrap(); + let configured: IpAddr = "192.0.2.1".parse().unwrap(); + let override_hop: IpAddr = "192.0.2.9".parse().unwrap(); + let mut cfg = test_service_config(); + cfg.prefixes.push(PrefixConfig { + network: network.to_string(), + next_hop: Some(configured.to_string()), + dev_attr255_interval_secs: None, + }); + let (event_tx, _) = broadcast::channel::(4); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + + // One dual-stack session and one IPv6-only session: only the peers that + // can carry the network's family may be named as targets. + for (peer, supports_v4, supports_v6) in + [("192.0.2.2", true, true), ("2001:db8::2", false, true)] + { + let (tx, _rx) = mpsc::channel(4); + service.inner.session_ops.write().await.insert( + peer.to_string(), + SessionHandle { + tx, + supports_v4, + supports_v6, + }, + ); + } + + let dry = service + .prefix_add(network, Some(override_hop), true) + .await + .unwrap(); + assert!( + dry.changed, + "a next-hop change is a change in a dry run too" + ); + assert!(dry.dry_run); + assert_eq!(dry.peers_notified, vec!["192.0.2.2".to_string()]); + assert_eq!(dry.status, PrefixStatus::Announced); + + // A new v6 network reaches both sessions. + let v6: IpNet = "2001:db8:1::/48".parse().unwrap(); + let dry_v6 = service.prefix_add(v6, None, true).await.unwrap(); + assert!(dry_v6.changed); + assert_eq!( + dry_v6.peers_notified, + vec!["192.0.2.2".to_string(), "2001:db8::2".to_string()] + ); + + // The dry runs must not have touched the state. + let rows = service.prefix_view().await; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].next_hop.as_deref(), Some("192.0.2.1")); + let effective = service.inner.prefix_state.read().await.effective(); + assert_eq!(effective.len(), 1); + assert_eq!(effective[0].next_hop, Some(configured)); + } + + #[tokio::test] + async fn prefix_remove_reads_provenance_under_the_mutation_lock() { + let cfg = test_service_config(); + let (event_tx, _) = broadcast::channel::(4); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + let network: IpNet = "198.51.100.0/24".parse().unwrap(); + + let added = service.prefix_add(network, None, false).await.unwrap(); + assert_eq!(added.source, Some(PrefixSource::Runtime)); + + // The source has to be read before the entry is dropped, while holding + // `prefix_ops`, so no concurrent mutation can change it in between. + let removed = service.prefix_remove(network, false).await.unwrap(); + assert!(removed.changed); + assert_eq!(removed.source, Some(PrefixSource::Runtime)); + assert_eq!(removed.status, PrefixStatus::Absent); + + // A network the state never knew reports null, from the same locked read. + let again = service.prefix_remove(network, false).await.unwrap(); + assert!(!again.changed); + assert_eq!(again.source, None); + } } From 3d91fa03a7a01c1c0b1b3ac3b99f65ef210e31ef Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Mon, 28 Sep 2026 21:09:58 -0700 Subject: [PATCH 16/17] fix(archive): wire live Adj-RIB-In into snapshots, archive local direction Address the archive findings of the PR-3 review: * The scheduled RIB snapshot is built from the speaker's live Adj-RIB-In through a registered source port instead of a hard-coded empty view, so rib segments are produced again; an explicit snapshot-now still writes a segment for an empty view. * Locally generated messages are archived as BGP4MP_MESSAGE_AS4_LOCAL (RFC 6396 section 4.4.6) instead of an incoming subtype. * A session's exit from Established is archived before the RIB (and the session's local address) is cleared. --- CHANGELOG.md | 6 + src/archive/mod.rs | 263 ++++++++++++++++++++++++++++++++++----- src/archive/snapshot.rs | 46 +++++-- src/bgp/mod.rs | 139 +++++++++++++++++++-- src/bin/focld.rs | 12 +- tests/acceptance_peer.rs | 259 +++++++++++++++++++++++++++++++++++++- 6 files changed, 663 insertions(+), 62 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41821c4..c841181 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,12 @@ All notable changes to this project will be documented in this file. * Archive writers rotate on the ingestion clock only, so a record with a late or zero event timestamp stays in the current segment with its event time preserved in the MRT header, and a rollover with no routes no longer writes an empty RIB snapshot. * The archive collector id and custom path templates are validated at config load: the id must match `^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`, templates reject absolute, backslash, control-character, empty and `..` components, and the rendered path is asserted to stay inside the archive root. +### Bug fixes + +* **RIB snapshots carry the live Adj-RIB-In.** The archive asks the speaker for its current view through a small source port that `focld` registers after both services exist, so `rib.*` segments are produced again on the configured interval: one peer index table entry per peer holding a session (with the BGP identifier from its OPEN) and one `TABLE_DUMP_V2` RIB entry per Adj-RIB-In route, with path attributes rebuilt from ORIGIN, the received AS path and the IPv4 next hop. A view without routes still writes no file, and `archive snapshot-now` serves the same view while writing a segment on the explicit request. +* **An inbound session's exit from Established is archived.** The state transition is recorded before the RIB (and the session's local address with it) is cleared, in both the active and the passive session path, so the `Established -> Active` record is no longer dropped. +* **Locally generated messages use the local BGP4MP subtype.** Our own announcements are archived as `BGP4MP_MESSAGE_AS4_LOCAL` (subtype 7) instead of `BGP4MP_MESSAGE_AS4`, so a consumer does not read them as updates received from the peer. Both directions stay archived; the received path is unchanged. + ## v0.1.0 - 2025-02-21 ### New features diff --git a/src/archive/mod.rs b/src/archive/mod.rs index 2853d2f..6fe08d9 100644 --- a/src/archive/mod.rs +++ b/src/archive/mod.rs @@ -6,8 +6,10 @@ pub mod snapshot; pub mod types; pub mod writer; +use std::future::Future; use std::net::Ipv4Addr; -use std::sync::Arc; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; use std::time::Duration; use anyhow::{Context, Result}; @@ -17,7 +19,8 @@ use tokio::sync::{broadcast, Mutex}; use crate::archive::layout::{aligned_epoch, segment_paths}; use crate::archive::replicator::Replicator; use crate::archive::snapshot::{ - build_table_dump_v2, encode_bgp4mp_raw_as4, encode_bgp4mp_state_change_as4, + build_table_dump_v2, encode_bgp4mp_raw_as4, encode_bgp4mp_raw_as4_local, + encode_bgp4mp_state_change_as4, }; use crate::archive::types::{ ArchiveStatus, ArchiveStream, FinalizedSegment, PeerStateRecordInput, RibSnapshotInput, @@ -27,12 +30,28 @@ use crate::archive::writer::SegmentWriter; use crate::config::{ArchiveConfig, DestinationMode}; use crate::types::{Event, EventEnvelope}; +/// Future returned by [`RibSnapshotSource::snapshot_input`]. A boxed future +/// keeps the source a plain trait object; there is exactly one implementation +/// and it is called once per RIB interval. +pub type SnapshotInputFuture<'a> = + Pin> + Send + 'a>>; + +/// Supplies the live RIB view an archive snapshot is built from. The speaker +/// implements it over the state its sessions already track; the archive owns +/// the snapshot timing, so the source does not need to stamp a usable +/// timestamp (the archive overwrites it) and may leave the collector id +/// unspecified. +pub trait RibSnapshotSource: Send + Sync { + fn snapshot_input(&self) -> SnapshotInputFuture<'_>; +} + pub struct ArchiveService { cfg: ArchiveConfig, collector_bgp_id: Ipv4Addr, updates_writer: Mutex>, ribs_last: Mutex>, last_rib_bucket: Mutex>, + snapshot_source: OnceLock>, replicator: Option>, event_tx: broadcast::Sender, } @@ -69,6 +88,7 @@ impl ArchiveService { updates_writer: Mutex::new(None), ribs_last: Mutex::new(None), last_rib_bucket: Mutex::new(None), + snapshot_source: OnceLock::new(), replicator, event_tx, }); @@ -111,6 +131,14 @@ impl ArchiveService { .collect() } + /// Registers the RIB view source. The daemon calls this once, after both + /// the archive and the speaker exist. + pub fn set_snapshot_source(&self, source: Arc) { + if self.snapshot_source.set(source).is_err() { + tracing::warn!("RIB snapshot source is already registered"); + } + } + pub async fn ingest_update(&self, update: UpdateRecordInput) -> Result<()> { if !self.cfg.enabled { return Ok(()); @@ -119,11 +147,29 @@ impl ArchiveService { // Segment selection is driven exclusively by the ingestion-clock tick. // Event timestamps are preserved in MRT records, never used to reopen buckets. let record = encode_bgp4mp_raw_as4(&update)?; + self.write_update_record(&record).await + } + + /// Archives a message this speaker generated. RFC 6396 section 4.4.6 + /// reserves `BGP4MP_MESSAGE_AS4_LOCAL` for locally generated messages, so + /// a consumer can tell our own announcements from updates received from + /// the peer instead of reading both as received. Both directions stay + /// archived. + pub async fn ingest_local_update(&self, update: UpdateRecordInput) -> Result<()> { + if !self.cfg.enabled { + return Ok(()); + } + + let record = encode_bgp4mp_raw_as4_local(&update)?; + self.write_update_record(&record).await + } + + async fn write_update_record(&self, record: &[u8]) -> Result<()> { let mut writer_guard = self.updates_writer.lock().await; let writer = writer_guard .as_mut() .context("updates writer not initialized")?; - writer.write_record(&record)?; + writer.write_record(record)?; Ok(()) } @@ -192,6 +238,51 @@ impl ArchiveService { Ok(finalized) } + /// Forces a RIB segment from the registered source for an explicit + /// `archive snapshot-now` request. Unlike the scheduled snapshot, an + /// explicit request writes the segment even when the view has no routes. + pub async fn snapshot_current(&self) -> Result { + let now = Utc::now().timestamp(); + let input = self + .snapshot_input_from_source(now) + .await? + .unwrap_or_else(|| RibSnapshotInput { + timestamp: now, + collector_bgp_id: Ipv4Addr::UNSPECIFIED, + view_name: "main".to_string(), + peers: vec![], + routes: vec![], + }); + self.snapshot_now(input).await + } + + /// Writes a RIB segment from the registered source. A view without routes + /// yields no segment: the archive must not publish a RIB file before a + /// valid baseline exists, which also keeps a rollover on an empty view + /// from writing an empty file. + async fn snapshot_from_source(&self, now_ts: i64) -> Result> { + let Some(input) = self.snapshot_input_from_source(now_ts).await? else { + tracing::debug!("skipping RIB snapshot because no snapshot source is registered"); + return Ok(None); + }; + if input.routes.is_empty() { + tracing::debug!("skipping RIB snapshot because no baseline routes exist"); + return Ok(None); + } + Ok(Some(self.snapshot_now(input).await?)) + } + + /// Reads the registered source, if any, and stamps the archive's own + /// ingestion clock on the view. + async fn snapshot_input_from_source(&self, now_ts: i64) -> Result> { + let Some(source) = self.snapshot_source.get() else { + return Ok(None); + }; + let mut input = source.snapshot_input().await?; + input.timestamp = now_ts; + Ok(Some(input)) + } + pub async fn rollover(&self, stream: ArchiveStream) -> Result<()> { if !self.cfg.enabled { return Ok(()); @@ -202,19 +293,7 @@ impl ArchiveService { self.rotate_updates(Utc::now().timestamp()).await?; } ArchiveStream::Ribs => { - let now = Utc::now().timestamp(); - let snapshot = RibSnapshotInput { - timestamp: now, - collector_bgp_id: self.collector_bgp_id, - view_name: "main".to_string(), - peers: vec![], - routes: vec![], - }; - if snapshot.routes.is_empty() { - tracing::debug!("skipping RIB rollover because no baseline routes exist"); - } else { - self.snapshot_now(snapshot).await?; - } + self.snapshot_from_source(Utc::now().timestamp()).await?; } } @@ -287,20 +366,10 @@ impl ArchiveService { let rib_bucket = aligned_epoch(now, self.cfg.ribs_interval_secs); let mut last_rib = self.last_rib_bucket.lock().await; - if last_rib.map(|v| v != rib_bucket).unwrap_or(true) { - let snapshot = RibSnapshotInput { - timestamp: now, - collector_bgp_id: self.collector_bgp_id, - view_name: "main".to_string(), - peers: vec![], - routes: vec![], - }; - if snapshot.routes.is_empty() { - tracing::debug!("skipping RIB snapshot because no baseline routes exist"); - } else { - self.snapshot_now(snapshot).await?; - *last_rib = Some(rib_bucket); - } + if last_rib.map(|v| v != rib_bucket).unwrap_or(true) + && self.snapshot_from_source(now).await?.is_some() + { + *last_rib = Some(rib_bucket); } Ok(()) @@ -394,12 +463,13 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; use anyhow::{Context, Result}; + use bgpkit_parser::models::{MrtMessage, TableDumpV2Message}; use bgpkit_parser::parse_mrt_record; use chrono::Utc; use flate2::read::GzDecoder; use super::*; - use crate::archive::types::UpdateRecordInput; + use crate::archive::types::{SnapshotPeer, SnapshotRoute, UpdateRecordInput}; use crate::config::ArchiveConfig; #[tokio::test] @@ -475,6 +545,137 @@ mod tests { Ok(()) } + #[tokio::test] + async fn rib_rollover_with_a_snapshot_source_writes_a_rib_file() -> Result<()> { + let temp = tempfile::tempdir()?; + let root = temp.path().join("archive"); + let cfg = ArchiveConfig { + enabled: true, + root: root.clone(), + tmp_root: root.join(".tmp"), + ..ArchiveConfig::default() + }; + let service = ArchiveService::new(cfg, Ipv4Addr::new(192, 0, 2, 1)).await?; + service.set_snapshot_source(Arc::new(FakeSnapshotSource { + peers: vec![SnapshotPeer { + peer_bgp_id: Ipv4Addr::new(198, 51, 100, 1), + peer_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + peer_asn: 64_512, + }], + routes: vec![SnapshotRoute { + prefix: "203.0.113.0/24".parse()?, + peer_index: 0, + originated_time: 1_700_000_000, + path_id: None, + path_attributes: vec![], + }], + })); + + service.rollover(ArchiveStream::Ribs).await?; + + let status = service.status().await?; + let path = status + .ribs_last_path + .clone() + .context("a rollover with routes should finalize a RIB segment")?; + assert_eq!(status.ribs_last_record_count, 2); + let mut decoded = Vec::new(); + GzDecoder::new(File::open(&path)?).read_to_end(&mut decoded)?; + let mut cursor = Cursor::new(decoded); + let peer_index = parse_mrt_record(&mut cursor)?; + let rib = parse_mrt_record(&mut cursor)?; + assert!(matches!( + peer_index.message, + MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(_)) + )); + assert!(matches!( + rib.message, + MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(_)) + )); + Ok(()) + } + + #[tokio::test] + async fn tick_with_a_source_but_no_routes_writes_no_rib_file() -> Result<()> { + let temp = tempfile::tempdir()?; + let root = temp.path().join("archive"); + let cfg = ArchiveConfig { + enabled: true, + root: root.clone(), + tmp_root: root.join(".tmp"), + ..ArchiveConfig::default() + }; + let service = ArchiveService::new(cfg, Ipv4Addr::new(192, 0, 2, 1)).await?; + service.set_snapshot_source(Arc::new(FakeSnapshotSource { + peers: vec![SnapshotPeer { + peer_bgp_id: Ipv4Addr::new(198, 51, 100, 1), + peer_ip: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + peer_asn: 64_512, + }], + routes: vec![], + })); + + service.tick().await?; + + let status = service.status().await?; + assert!( + status.ribs_last_path.is_none(), + "a view without routes must not write a RIB file" + ); + assert!(!walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + .any(|entry| { + entry.file_type().is_file() + && entry.file_name().to_string_lossy().starts_with("rib.") + })); + Ok(()) + } + + /// An explicit `archive snapshot-now` request is served from the same + /// source but, unlike the scheduled snapshot, still writes a segment. + #[tokio::test] + async fn explicit_snapshot_writes_a_segment_without_routes() -> Result<()> { + let temp = tempfile::tempdir()?; + let root = temp.path().join("archive"); + let cfg = ArchiveConfig { + enabled: true, + root: root.clone(), + tmp_root: root.join(".tmp"), + ..ArchiveConfig::default() + }; + let service = ArchiveService::new(cfg, Ipv4Addr::new(192, 0, 2, 1)).await?; + service.set_snapshot_source(Arc::new(FakeSnapshotSource { + peers: vec![], + routes: vec![], + })); + + let finalized = service.snapshot_current().await?; + assert!(finalized.final_path.exists()); + assert_eq!(finalized.record_count, 1); + Ok(()) + } + + /// Stands in for the speaker: the archive only sees the source port. + struct FakeSnapshotSource { + peers: Vec, + routes: Vec, + } + + impl RibSnapshotSource for FakeSnapshotSource { + fn snapshot_input(&self) -> SnapshotInputFuture<'_> { + Box::pin(async move { + Ok(RibSnapshotInput { + timestamp: 0, + collector_bgp_id: Ipv4Addr::UNSPECIFIED, + view_name: "main".to_string(), + peers: self.peers.clone(), + routes: self.routes.clone(), + }) + }) + } + } + fn test_update(timestamp: i64) -> UpdateRecordInput { let mut message = vec![0xff; 16]; message.extend_from_slice(&24_u16.to_be_bytes()); diff --git a/src/archive/snapshot.rs b/src/archive/snapshot.rs index 6243867..21eb034 100644 --- a/src/archive/snapshot.rs +++ b/src/archive/snapshot.rs @@ -46,6 +46,18 @@ pub fn encode_bgp4mp_message_as4(input: &UpdateRecordInput) -> Result> { /// embedded BGP UPDATE. The archive always uses this path so malformed yet /// archivable frames retain their exact original bytes. pub fn encode_bgp4mp_raw_as4(input: &UpdateRecordInput) -> Result> { + encode_bgp4mp_raw(input, Bgp4MpType::MessageAs4) +} + +/// The same raw envelope for a message this speaker generated. RFC 6396 +/// section 4.4.6 reserves `BGP4MP_MESSAGE_AS4_LOCAL` (7) for locally +/// generated messages, so a consumer does not read our own announcements as +/// updates received from the remote peer. +pub fn encode_bgp4mp_raw_as4_local(input: &UpdateRecordInput) -> Result> { + encode_bgp4mp_raw(input, Bgp4MpType::MessageAs4Local) +} + +fn encode_bgp4mp_raw(input: &UpdateRecordInput, msg_type: Bgp4MpType) -> Result> { let (address_family, peer_address, local_address) = match (input.peer_ip, input.local_ip) { (IpAddr::V4(peer), IpAddr::V4(local)) => { (1_u16, peer.octets().to_vec(), local.octets().to_vec()) @@ -69,7 +81,7 @@ pub fn encode_bgp4mp_raw_as4(input: &UpdateRecordInput) -> Result> { encode_common_header( input.timestamp as u32, EntryType::BGP4MP, - Bgp4MpType::MessageAs4 as u16, + msg_type as u16, payload, ) } @@ -312,7 +324,7 @@ mod tests { IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)), ); - assert_raw_bgp4mp_round_trip(&input) + assert_raw_bgp4mp_round_trip(&input, Bgp4MpType::MessageAs4) } #[test] @@ -321,7 +333,18 @@ mod tests { IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)), IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2)), ); - assert_raw_bgp4mp_round_trip(&input) + assert_raw_bgp4mp_round_trip(&input, Bgp4MpType::MessageAs4) + } + + /// A locally generated message is archived under the local subtype, so a + /// consumer can tell our own announcements from received updates. + #[test] + fn raw_bgp4mp_local_uses_the_local_subtype() -> Result<()> { + let input = update_input( + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1)), + IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)), + ); + assert_raw_bgp4mp_round_trip(&input, Bgp4MpType::MessageAs4Local) } #[test] @@ -456,18 +479,23 @@ mod tests { } } - fn assert_raw_bgp4mp_round_trip(input: &UpdateRecordInput) -> Result<()> { - let bytes = encode_bgp4mp_raw_as4(input)?; + fn assert_raw_bgp4mp_round_trip(input: &UpdateRecordInput, msg_type: Bgp4MpType) -> Result<()> { + let bytes = match msg_type { + Bgp4MpType::MessageAs4 => encode_bgp4mp_raw_as4(input)?, + Bgp4MpType::MessageAs4Local => encode_bgp4mp_raw_as4_local(input)?, + other => bail!("unexpected BGP4MP subtype in this test: {other:?}"), + }; let parsed = parse_mrt_record(&mut Cursor::new(&bytes))?; assert_eq!(parsed.common_header.entry_type, EntryType::BGP4MP); - assert_eq!( - parsed.common_header.entry_subtype, - Bgp4MpType::MessageAs4 as u16 - ); + assert_eq!(parsed.common_header.entry_subtype, msg_type as u16); match parsed.message { MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(message)) => { assert_eq!(message.peer_ip, input.peer_ip); assert_eq!(message.local_ip, input.local_ip); + assert_eq!( + message.is_local(), + matches!(msg_type, Bgp4MpType::MessageAs4Local) + ); let decoded = message .bgp_message .encode(AsnLength::Bits32) diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index 45279fe..c897195 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -8,9 +8,9 @@ use std::time::Duration; use anyhow::{anyhow, Context, Result}; use bgpkit_parser::bgp::parse_bgp_message; use bgpkit_parser::models::{ - Afi, AsPath, Asn, AsnLength, AttrFlags, Attribute, AttributeValue, Attributes, BgpMessage, - BgpOpenMessage, BgpRouteRefreshMessage, BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, - Origin, ParamValue, Safi, + Afi, AsPath, Asn, AsnLength, AttrFlags, AttrType, Attribute, AttributeValue, Attributes, + BgpMessage, BgpOpenMessage, BgpRouteRefreshMessage, BgpUpdateMessage, NetworkPrefix, Nlri, + OptParam, Origin, ParamValue, Safi, }; use bytes::Bytes; use ipnet::IpNet; @@ -22,8 +22,10 @@ use tokio::sync::{broadcast, mpsc, Mutex, RwLock}; use tokio::task::JoinHandle; use tokio::time::{sleep, timeout, Instant}; -use crate::archive::types::{PeerStateRecordInput, UpdateRecordInput}; -use crate::archive::ArchiveService; +use crate::archive::types::{ + PeerStateRecordInput, RibSnapshotInput, SnapshotPeer, SnapshotRoute, UpdateRecordInput, +}; +use crate::archive::{ArchiveService, RibSnapshotSource, SnapshotInputFuture}; use crate::config::{FoclConfig, PeerConfig}; use crate::types::{Event, EventEnvelope, PeerState}; @@ -62,6 +64,10 @@ struct PeerRuntime { info: PeerInfo, cfg: PeerConfig, task: Option>, + /// The peer's BGP identifier, learned from its OPEN. A TABLE_DUMP_V2 + /// snapshot Peer entry carries it; it is unspecified until a session has + /// presented an OPEN. + remote_bgp_id: Option, } #[derive(Debug, Clone)] @@ -422,7 +428,11 @@ fn ensure_next_hop_family(network: &IpNet, next_hop: IpAddr) -> Result<()> { #[derive(Debug, Clone)] struct AdjRibValue { next_hop: Option, - as_path: Option, + /// The received AS path, kept parsed rather than formatted: a RIB snapshot + /// rebuilds the route's AS_PATH attribute from it. + as_path: Option, + /// The received ORIGIN, when the peer sent one. + origin: Option, last_seen: i64, } @@ -568,6 +578,7 @@ impl BgpService { info, cfg: peer_cfg, task, + remote_bgp_id: None, } } @@ -680,7 +691,9 @@ impl BgpService { let key = peer.address.clone(); let task = tokio::spawn(async move { let result = service.run_session(&peer, stream).await; - service.clear_rib(&peer.address).await; + // Record the exit transition before clearing the RIB: `clear_rib` + // drops the session's local address, and a state change without it + // cannot be archived. match result { Ok(()) => { service @@ -698,6 +711,7 @@ impl BgpService { .await } } + service.clear_rib(&peer.address).await; if !peer.passive { sleep(Duration::from_secs(peer.connect_retry_secs as u64)).await; service.peer_loop(peer).await; @@ -714,7 +728,8 @@ impl BgpService { self.set_peer_state(&peer.address, PeerState::Connect, None, None) .await; let result = self.run_active_session(&peer).await; - self.clear_rib(&peer.address).await; + // Same ordering as the passive path: archive the exit transition + // while the session's local address is still known. match result { Ok(()) => { self.set_peer_state(&peer.address, PeerState::Active, None, None) @@ -730,6 +745,7 @@ impl BgpService { .await; } } + self.clear_rib(&peer.address).await; sleep(Duration::from_secs(peer.connect_retry_secs as u64)).await; } } @@ -808,6 +824,9 @@ impl BgpService { // RFC 4271 s4.4/s6.1: the hold time that governs this session is 0 when // either side advertised 0, otherwise the smaller of the two. let hold_time = negotiate_hold_time(peer.hold_time_secs, remote_open.hold_time); + if let Some(runtime) = self.inner.peers.write().await.get_mut(&peer.address) { + runtime.remote_bgp_id = Some(remote_open.bgp_identifier); + } self.set_peer_state(&peer.address, PeerState::OpenConfirm, None, None) .await; @@ -1041,7 +1060,9 @@ impl BgpService { /// Writes updates to one session and mirrors them into the archive. The /// archive is receive-only for a collector, so our own announcements are - /// recorded here to keep a self-contained lab archive complete. + /// recorded here to keep a self-contained lab archive complete; they are + /// archived in the local direction (RFC 6396 section 4.4.6), so a consumer + /// can still tell them apart from updates received from the peer. async fn emit_updates( &self, peer: &PeerConfig, @@ -1056,7 +1077,7 @@ impl BgpService { let raw = write_bgp_message(writer, &update, asn_len).await?; if let Some(archive) = &self.inner.archive { archive - .ingest_update(UpdateRecordInput { + .ingest_local_update(UpdateRecordInput { timestamp: chrono::Utc::now().timestamp(), peer_ip: peer.address.parse().context("invalid configured peer IP")?, peer_asn: peer.remote_as, @@ -1105,7 +1126,13 @@ impl BgpService { negotiated: &NegotiatedCapabilities, ) { let next_hop = update.attributes.next_hop(); - let as_path = update.attributes.as_path().map(ToString::to_string); + let as_path = update.attributes.as_path().cloned(); + // Absent ORIGIN stays absent: the snapshot must not invent a value for + // an attribute the peer never sent. + let origin = update + .attributes + .has_attr(AttrType::ORIGIN) + .then(|| update.attributes.origin()); let now = chrono::Utc::now().timestamp(); let mut ribs = self.inner.rib_in.write().await; let rib = ribs.entry(peer.to_string()).or_insert_with(IpnetTrie::new); @@ -1124,6 +1151,7 @@ impl BgpService { AdjRibValue { next_hop, as_path: as_path.clone(), + origin, last_seen: now, }, ); @@ -1145,6 +1173,7 @@ impl BgpService { AdjRibValue { next_hop: mp_next_hop, as_path: as_path.clone(), + origin, last_seen: now, }, ); @@ -1520,6 +1549,94 @@ impl BgpService { prefixes.sort(); Ok(prefixes) } + + /// Builds the archive's RIB view: every peer that currently holds a + /// session, with its Adj-RIB-In entries. The trie the session loop already + /// maintains is the source; an Adj-RIB-In value keeps no attribute blob + /// (interning is deferred), so a route's TABLE_DUMP_V2 attributes are + /// rebuilt from ORIGIN, the stored AS path and, for IPv4 prefixes, the + /// next hop. + pub async fn rib_snapshot_input(&self) -> Result { + let local_ips = self.inner.session_local_ips.read().await; + let peers = self.inner.peers.read().await; + let ribs = self.inner.rib_in.read().await; + + // A stable order keeps the peer index table reproducible. + let mut addresses = local_ips.keys().cloned().collect::>(); + addresses.sort(); + + let mut snapshot_peers = Vec::with_capacity(addresses.len()); + let mut routes = Vec::new(); + for address in addresses { + let Some(runtime) = peers.get(&address) else { + continue; + }; + let Ok(peer_ip) = address.parse::() else { + continue; + }; + let peer_index = u16::try_from(snapshot_peers.len()) + .context("snapshot peer count exceeds the TABLE_DUMP_V2 limit")?; + snapshot_peers.push(SnapshotPeer { + peer_bgp_id: runtime.remote_bgp_id.unwrap_or(Ipv4Addr::UNSPECIFIED), + peer_ip, + peer_asn: runtime.info.remote_as, + }); + let Some(rib) = ribs.get(&address) else { + continue; + }; + for (prefix, value) in rib.iter() { + routes.push(SnapshotRoute { + prefix, + peer_index, + originated_time: value.last_seen as u32, + path_id: None, + path_attributes: snapshot_path_attributes(value, prefix)?, + }); + } + } + + Ok(RibSnapshotInput { + timestamp: chrono::Utc::now().timestamp(), + collector_bgp_id: Ipv4Addr::UNSPECIFIED, + view_name: "main".to_string(), + peers: snapshot_peers, + routes, + }) + } +} + +impl RibSnapshotSource for BgpService { + fn snapshot_input(&self) -> SnapshotInputFuture<'_> { + Box::pin(self.rib_snapshot_input()) + } +} + +/// Rebuilds the path attributes a TABLE_DUMP_V2 RIB entry carries from one +/// Adj-RIB-In value: the received ORIGIN and AS path (attribute type 2 with +/// four-octet segments), plus NEXT_HOP for an IPv4 prefix. A table dump has no +/// NLRI inside the attribute blob, so no MP_REACH is emitted for IPv6, and an +/// attribute the peer never sent is left out rather than invented. +fn snapshot_path_attributes(value: &AdjRibValue, prefix: IpNet) -> Result> { + let mut attributes = Attributes::default(); + if let Some(origin) = value.origin { + attributes.add_attr(AttributeValue::Origin(origin).into()); + } + if let Some(as_path) = &value.as_path { + attributes.add_attr( + AttributeValue::AsPath { + path: as_path.clone(), + is_as4: false, + } + .into(), + ); + } + if let (Some(next_hop @ IpAddr::V4(_)), IpNet::V4(_)) = (value.next_hop, prefix) { + attributes.add_attr(AttributeValue::NextHop(next_hop).into()); + } + let encoded = attributes + .encode(AsnLength::Bits32) + .map_err(|error| anyhow!("failed encoding snapshot path attributes: {error}"))?; + Ok(encoded.to_vec()) } /// RFC 4271 s4.2/s6.1 hold-time negotiation: a hold time of 0 on either side diff --git a/src/bin/focld.rs b/src/bin/focld.rs index 3fd0aef..34f1c81 100644 --- a/src/bin/focld.rs +++ b/src/bin/focld.rs @@ -40,6 +40,9 @@ async fn main() -> Result<()> { let archive = ArchiveService::new(cfg.archive.clone(), collector_bgp_id).await?; let events_tx = archive.event_sender(); let bgp = BgpService::new_with_archive(&cfg, events_tx, Some(Arc::clone(&archive))).await?; + // The speaker is the archive's RIB view source: a snapshot reads the live + // Adj-RIB-In from the service that owns it. + archive.set_snapshot_source(Arc::new(bgp.clone())); let socket_path = cfg.global.control_socket.clone(); cleanup_socket(&socket_path)?; @@ -224,14 +227,7 @@ async fn handle_client( ControlResponse::ok(req.id, json!({"ok": true})) } CommandKind::ArchiveSnapshotNow => { - let snapshot = focl::archive::types::RibSnapshotInput { - timestamp: chrono::Utc::now().timestamp(), - collector_bgp_id: std::net::Ipv4Addr::UNSPECIFIED, - view_name: "main".to_string(), - peers: vec![], - routes: vec![], - }; - let result = archive.snapshot_now(snapshot).await?; + let result = archive.snapshot_current().await?; ControlResponse::ok( req.id, json!({ diff --git a/tests/acceptance_peer.rs b/tests/acceptance_peer.rs index ff00e7c..188be76 100644 --- a/tests/acceptance_peer.rs +++ b/tests/acceptance_peer.rs @@ -6,8 +6,9 @@ use std::time::Duration; use anyhow::{Context, Result}; use bgpkit_parser::bgp::parse_bgp_message; use bgpkit_parser::models::{ - Afi, AsPath, Asn, AsnLength, AttrFlags, AttributeValue, Attributes, BgpMessage, BgpOpenMessage, - BgpRouteRefreshMessage, BgpUpdateMessage, NetworkPrefix, Nlri, OptParam, Origin, ParamValue, + Afi, AsPath, Asn, AsnLength, AttrFlags, AttributeValue, Attributes, Bgp4MpEnum, BgpMessage, + BgpOpenMessage, BgpRouteRefreshMessage, BgpState, BgpUpdateMessage, MrtMessage, NetworkPrefix, + Nlri, OptParam, Origin, ParamValue, TableDumpV2Message, TableDumpV2Type, }; use bgpkit_parser::parse_mrt_record; use bytes::Bytes; @@ -164,8 +165,17 @@ async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<() GzDecoder::new(std::fs::File::open(segment)?).read_to_end(&mut decoded)?; let mut cursor = Cursor::new(decoded); let mut record_count = 0; + let mut local_records = 0; + let mut received_records = 0; while (cursor.position() as usize) < cursor.get_ref().len() { - parse_mrt_record(&mut cursor)?; + let record = parse_mrt_record(&mut cursor)?; + if let MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(message)) = &record.message { + if message.is_local() { + local_records += 1; + } else { + received_records += 1; + } + } record_count += 1; } // one outbound UPDATE per configured prefix plus the two peer UPDATEs, and @@ -174,6 +184,249 @@ async fn configured_prefixes_exchange_bidirectionally_and_archive() -> Result<() record_count >= 4, "expected both directions in archived BGP4MP records" ); + // Our own announcements are archived in the local direction (RFC 6396 + // section 4.4.6); the peer's updates keep the received direction. + assert!( + local_records >= 2, + "expected at least two locally generated records, got {local_records}" + ); + assert!( + received_records >= 2, + "expected at least two received records, got {received_records}" + ); + Ok(()) +} + +/// The archive's periodic RIB snapshot is built from the speaker's live +/// Adj-RIB-In: the segment carries a peer index table plus one RIB entry per +/// received route and parses as TABLE_DUMP_V2. +#[tokio::test] +async fn rib_snapshot_carries_the_live_adj_rib_in() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let archive_root = temp.path().join("archive"); + let cfg = FoclConfig { + global: GlobalConfig { + asn: FOCL_AS, + router_id: "192.0.2.1".to_string(), + listen: true, + listen_addr: format!("127.0.0.1:{port}"), + control_socket: temp.path().join("focld.sock"), + log_level: "warn".to_string(), + }, + peers: vec![PeerConfig { + address: "127.0.0.1".to_string(), + remote_as: PEER_AS, + local_as: None, + hold_time_secs: 30, + connect_retry_secs: 1, + remote_port: port, + local_address: None, + enabled: true, + passive: true, + route_refresh: true, + name: None, + password: None, + }], + prefixes: vec![], + archive: ArchiveConfig { + enabled: true, + root: archive_root.clone(), + tmp_root: archive_root.join(".tmp"), + ..ArchiveConfig::default() + }, + }; + let archive = ArchiveService::new(cfg.archive.clone(), Ipv4Addr::new(192, 0, 2, 1)).await?; + let bgp = + BgpService::new_with_archive(&cfg, archive.event_sender(), Some(Arc::clone(&archive))) + .await?; + // The daemon wires the speaker in as the archive's RIB view source. + archive.set_snapshot_source(Arc::new(bgp.clone())); + + let mut stream = establish_peer_session(port, capabilities()).await?; + write_message( + &mut stream, + &announce_v4("192.0.2.0/24", "192.0.2.2".parse()?), + ) + .await?; + write_message( + &mut stream, + &announce_v6("2001:db8::/32", "2001:db8::2".parse()?), + ) + .await?; + timeout(Duration::from_secs(5), async { + loop { + let prefixes = bgp.rib_in("127.0.0.1").await?; + if prefixes.iter().any(|prefix| prefix == "192.0.2.0/24") + && prefixes.iter().any(|prefix| prefix == "2001:db8::/32") + { + return Ok::<_, anyhow::Error>(()); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await??; + + archive.rollover(ArchiveStream::Ribs).await?; + + let segment = walkdir::WalkDir::new(&archive_root) + .into_iter() + .filter_map(Result::ok) + .find_map(|entry| { + let name = entry.file_name().to_string_lossy().to_string(); + (entry.file_type().is_file() && name.starts_with("rib.") && name.ends_with(".gz")) + .then(|| entry.path().to_path_buf()) + }) + .context("a RIB rollover should write a rib segment for the received routes")?; + let mut decoded = Vec::new(); + GzDecoder::new(std::fs::File::open(segment)?).read_to_end(&mut decoded)?; + let mut cursor = Cursor::new(decoded); + + let MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(table)) = + parse_mrt_record(&mut cursor)?.message + else { + panic!("the RIB segment must start with a peer index table"); + }; + assert_eq!(table.id_peer_map.len(), 1, "one session, one peer entry"); + let peer = table.id_peer_map.get(&0).context("peer index 0 is used")?; + assert_eq!(peer.peer_ip, IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))); + assert_eq!(peer.peer_asn.to_u32(), PEER_AS); + assert_eq!(peer.peer_bgp_id, Ipv4Addr::new(192, 0, 2, 2)); + + let MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(v4)) = + parse_mrt_record(&mut cursor)?.message + else { + panic!("expected a RIB AFI entry for the IPv4 route"); + }; + assert_eq!(v4.rib_type, TableDumpV2Type::RibIpv4Unicast); + assert_eq!(v4.prefix.prefix.to_string(), "192.0.2.0/24"); + assert_eq!(v4.rib_entries.len(), 1); + assert_eq!(v4.rib_entries[0].peer_index, 0); + assert_eq!( + v4.rib_entries[0].attributes.next_hop(), + Some("192.0.2.2".parse::()?) + ); + assert_eq!( + v4.rib_entries[0] + .attributes + .as_path() + .map(ToString::to_string), + Some(PEER_AS.to_string()) + ); + + let MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(v6)) = + parse_mrt_record(&mut cursor)?.message + else { + panic!("expected a RIB AFI entry for the IPv6 route"); + }; + assert_eq!(v6.rib_type, TableDumpV2Type::RibIpv6Unicast); + assert_eq!(v6.prefix.prefix.to_string(), "2001:db8::/32"); + assert_eq!(v6.rib_entries.len(), 1); + assert_eq!(v6.rib_entries[0].peer_index, 0); + Ok(()) +} + +/// Ending a session records the exit transition: clearing the RIB drops the +/// session's local address, so the state change has to be archived first or it +/// is lost. +#[tokio::test] +async fn session_end_archives_the_established_to_active_transition() -> Result<()> { + let temp = tempfile::tempdir()?; + let port = StdTcpListener::bind("127.0.0.1:0")?.local_addr()?.port(); + let archive_root = temp.path().join("archive"); + let cfg = FoclConfig { + global: GlobalConfig { + asn: FOCL_AS, + router_id: "192.0.2.1".to_string(), + listen: true, + listen_addr: format!("127.0.0.1:{port}"), + control_socket: temp.path().join("focld.sock"), + log_level: "warn".to_string(), + }, + peers: vec![PeerConfig { + address: "127.0.0.1".to_string(), + remote_as: PEER_AS, + local_as: None, + hold_time_secs: 30, + connect_retry_secs: 1, + remote_port: port, + local_address: None, + enabled: true, + passive: true, + route_refresh: true, + name: None, + password: None, + }], + prefixes: vec![], + archive: ArchiveConfig { + enabled: true, + root: archive_root.clone(), + tmp_root: archive_root.join(".tmp"), + ..ArchiveConfig::default() + }, + }; + let archive = ArchiveService::new(cfg.archive.clone(), Ipv4Addr::new(192, 0, 2, 1)).await?; + let _bgp = + BgpService::new_with_archive(&cfg, archive.event_sender(), Some(Arc::clone(&archive))) + .await?; + + let stream = establish_peer_session(port, capabilities()).await?; + // Establishment archives OpenSent, OpenConfirm and Established. With no + // configured prefixes nothing else is archived while the session is quiet, + // so the record count can only move again when the session ends. + timeout(Duration::from_secs(5), async { + loop { + if archive.status().await?.updates_record_count >= 3 { + return Ok::<_, anyhow::Error>(()); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await + .context("the establishment state changes should be archived")??; + let before = archive.status().await?.updates_record_count; + + drop(stream); + timeout(Duration::from_secs(5), async { + loop { + if archive.status().await?.updates_record_count > before { + return Ok::<_, anyhow::Error>(()); + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await + .context("ending the session should archive a record")??; + + archive.rollover(ArchiveStream::Updates).await?; + + let mut transition = None; + for entry in walkdir::WalkDir::new(&archive_root) { + let entry = entry?; + let name = entry.file_name().to_string_lossy().to_string(); + if !entry.file_type().is_file() || !name.ends_with(".gz") { + continue; + } + let mut decoded = Vec::new(); + GzDecoder::new(std::fs::File::open(entry.path())?).read_to_end(&mut decoded)?; + let mut cursor = Cursor::new(decoded); + while (cursor.position() as usize) < cursor.get_ref().len() { + let record = parse_mrt_record(&mut cursor)?; + if let MrtMessage::Bgp4Mp(Bgp4MpEnum::StateChange(state)) = record.message { + if state.old_state == BgpState::Established && state.new_state == BgpState::Active { + transition = Some(state); + } + } + } + } + + let transition = + transition.context("the Established -> Active transition should be archived")?; + assert_eq!(transition.peer_ip, IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))); + assert_eq!( + transition.local_addr, + IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)) + ); Ok(()) } From 89c55995b519f2badd3c06d92089b8ee5211db93 Mon Sep 17 00:00:00 2001 From: Mingwei Zhang Date: Mon, 28 Sep 2026 21:17:33 -0700 Subject: [PATCH 17/17] fix(bgp,archive): close the remaining PR-3 review findings - A route-refresh replay no longer takes the mutation lock: the session loop is the only drain for its own queue, so a control client blocked on a full queue while holding the lock could never be unblocked, and the lock wait deadlocked the session against its own producer. Ordering is kept by the loop itself: the state read is one view, so a mutation applied before it is inside the replay and a later one is written after it. - The replication path resolves a manifest's relative path before use, so a manifest changed after it was queued cannot redirect the copy: absolute paths, parent components and empty paths are refused, and a local target is asserted to stay inside the destination root. - The attribute-255 ticker skips missed ticks instead of bursting them, so a stall dispatches one refresh per clock round. Each fix is pinned by a regression test that fails when the fix is reverted, and the ticker test drives the skipped-tick behavior on a paused clock. --- CHANGELOG.md | 3 + Cargo.toml | 1 + src/archive/replicator.rs | 125 +++++++++++++++++++++++++++++++++-- src/bgp/mod.rs | 134 +++++++++++++++++++++++++++++++------- 4 files changed, 236 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c841181..baccdde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,9 @@ All notable changes to this project will be documented in this file. * **RIB snapshots carry the live Adj-RIB-In.** The archive asks the speaker for its current view through a small source port that `focld` registers after both services exist, so `rib.*` segments are produced again on the configured interval: one peer index table entry per peer holding a session (with the BGP identifier from its OPEN) and one `TABLE_DUMP_V2` RIB entry per Adj-RIB-In route, with path attributes rebuilt from ORIGIN, the received AS path and the IPv4 next hop. A view without routes still writes no file, and `archive snapshot-now` serves the same view while writing a segment on the explicit request. * **An inbound session's exit from Established is archived.** The state transition is recorded before the RIB (and the session's local address with it) is cleared, in both the active and the passive session path, so the `Established -> Active` record is no longer dropped. * **Locally generated messages use the local BGP4MP subtype.** Our own announcements are archived as `BGP4MP_MESSAGE_AS4_LOCAL` (subtype 7) instead of `BGP4MP_MESSAGE_AS4`, so a consumer does not read them as updates received from the peer. Both directions stay archived; the received path is unchanged. +* **A ROUTE-REFRESH replay no longer waits for the mutation lock.** The replay reads the advertised state directly, because the session loop is the only drain for its own queue: a control client blocked on that full queue while holding the lock could never be unblocked. Ordering is kept by the loop itself - the state read is one view, so a mutation applied before it is inside the replay and a later one is written after it. +* **A queued manifest cannot redirect a copy.** The replication path re-reads the manifest from disk on every attempt, so its relative path is now resolved before use: absolute paths, `..` components and an empty path are refused, and a local target is asserted to stay inside the destination root. +* **Missed clock ticks are skipped.** The attribute-255 ticker no longer bursts: after a stall one refresh per clock round is dispatched instead of one per missed tick, which could fill a session queue without recovering a measurement. ## v0.1.0 - 2025-02-21 diff --git a/Cargo.toml b/Cargo.toml index 4e4b84f..b4f18e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,4 +51,5 @@ zstd = "0.13" [dev-dependencies] tempfile = "3" +tokio = { version = "1", features = ["test-util"] } walkdir = "2" diff --git a/src/archive/replicator.rs b/src/archive/replicator.rs index f635c43..e8d7ea7 100644 --- a/src/archive/replicator.rs +++ b/src/archive/replicator.rs @@ -1,11 +1,11 @@ use std::collections::HashMap; use std::fs; -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use aws_sdk_s3::primitives::ByteStream; use aws_types::region::Region; use tokio::time::sleep; @@ -150,8 +150,15 @@ impl Replicator { .path .as_ref() .context("local destination path missing")?; - let relative_path = PathBuf::from(&manifest.relative_path); + let relative_path = contained_relative_path(manifest)?; let target_segment = base.join(&relative_path); + if !target_segment.starts_with(base) { + bail!( + "manifest path {} escapes the destination root {}", + manifest.relative_path, + base.display() + ); + } let target_manifest = PathBuf::from(format!("{}.json", target_segment.display())); if let Some(parent) = target_segment.parent() { @@ -207,7 +214,8 @@ impl Replicator { let client = aws_sdk_s3::Client::from_conf(s3_conf); - let key = object_key(prefix, &manifest.relative_path); + let relative_path = contained_relative_path(manifest)?; + let key = object_key(prefix, &relative_path.to_string_lossy()); let manifest_key = format!("{}.json", key); let body = ByteStream::from_path(Path::new(&job.segment_path)).await?; @@ -253,3 +261,112 @@ fn object_key(prefix: &str, relative: &str) -> String { let normalized_prefix = prefix.trim_matches('/'); format!("{}/{}", normalized_prefix, relative.trim_start_matches('/')) } + +/// Resolves a manifest's relative path, refusing anything that is not a plain +/// relative path. The queue is re-read from disk on every retry, so a manifest +/// changed after it was queued must not be able to redirect the copy: an +/// absolute path discards the destination root in `Path::join`, and a `..` +/// component climbs out of it. +fn contained_relative_path(manifest: &SegmentManifest) -> Result { + let mut safe = PathBuf::new(); + for component in Path::new(&manifest.relative_path).components() { + match component { + Component::Normal(part) => safe.push(part), + _ => bail!( + "manifest relative path is not a plain relative path: {}", + manifest.relative_path + ), + } + } + if safe.as_os_str().is_empty() { + bail!("manifest relative path is empty"); + } + Ok(safe) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{CompressionKind, LayoutProfile}; + + fn manifest(relative_path: &str) -> SegmentManifest { + SegmentManifest { + collector_id: "test".to_string(), + stream: "updates".to_string(), + start_ts: 0, + end_ts: 1, + record_count: 1, + bytes: 1, + sha256: "0".repeat(64), + compression: CompressionKind::Gzip, + layout_profile: LayoutProfile::RouteViews, + relative_path: relative_path.to_string(), + } + } + + #[test] + fn manifest_paths_must_stay_relative() { + for path in [ + "/etc/passwd", + "../escaped.gz", + "a/../../escaped.gz", + "..", + "", + ] { + assert!( + contained_relative_path(&manifest(path)).is_err(), + "{path} must be refused" + ); + } + assert_eq!( + contained_relative_path(&manifest("route-views2/bgpdata/updates.1700000000.gz")) + .expect("a plain relative path is accepted"), + PathBuf::from("route-views2/bgpdata/updates.1700000000.gz") + ); + } + + /// The retry path re-reads the manifest from disk, so a queued manifest + /// that was changed afterwards must not be able to write outside the + /// replica root. + #[test] + fn copy_to_local_refuses_a_manifest_that_escapes_the_root() -> Result<()> { + let temp = tempfile::tempdir()?; + let replica = temp.path().join("replica"); + let mut cfg = ArchiveConfig::default(); + cfg.destinations[0].path = Some(replica.clone()); + let destination = cfg.destinations[0].clone(); + assert!( + matches!(destination.destination_type, DestinationType::Local), + "the default destination is a local one" + ); + let replicator = Replicator::new( + &cfg, + ReplicationQueue::new(&temp.path().join("queue"))?, + None, + ); + + let segment = temp.path().join("updates.1700000000.gz"); + fs::write(&segment, b"segment")?; + let job = ReplicationJob { + id: 1, + segment_path: segment, + manifest_path: temp.path().join("manifest.json"), + destination_key: destination.destination_key(), + attempts: 1, + max_retries: 3, + }; + + let error = replicator + .copy_to_local(&destination, &job, &manifest("../escaped.gz")) + .expect_err("a path leaving the replica root must be refused"); + assert!( + error.to_string().contains("not a plain relative path"), + "{error}" + ); + assert!( + !temp.path().join("escaped.gz").exists(), + "nothing may be written outside the replica root" + ); + Ok(()) + } +} diff --git a/src/bgp/mod.rs b/src/bgp/mod.rs index c897195..0a7e97b 100644 --- a/src/bgp/mod.rs +++ b/src/bgp/mod.rs @@ -625,7 +625,7 @@ impl BgpService { for interval in intervals { let service = self.clone(); tokio::spawn(async move { - let mut ticker = tokio::time::interval(Duration::from_secs(u64::from(interval))); + let mut ticker = clock_ticker(interval); // The establishment announcement already covers t0. ticker.tick().await; loop { @@ -1007,28 +1007,29 @@ impl BgpService { return Ok(()); } let local_as = peer.local_as.unwrap_or(self.inner.global_asn); - let updates = { - // Snapshot under the mutation lock, so an incremental change cannot - // interleave with the replay: an earlier mutation is already in the - // snapshot, a later one is dispatched after the replay is written. - let _guard = self.inner.prefix_ops.lock().await; - let prefixes: Vec = self - .inner - .prefix_state - .read() - .await - .effective() - .into_iter() - .filter(|entry| afi_of(&entry.network) == afi) - .collect(); - build_announce_updates( - &prefixes, - self.inner.router_id, - local_ip, - local_as, - negotiated, - ) - }; + // The mutation lock is deliberately not taken here. A control client + // holds it across its dispatch, and a dispatch blocked on this + // session's full queue can only be unblocked by this loop draining it, + // so a lock wait here deadlocks the session against its own producer. + // Ordering comes from this loop instead: the state read below is one + // atomic view, a mutation applied before it is inside the replay, and a + // later one is written after it. + let prefixes: Vec = self + .inner + .prefix_state + .read() + .await + .effective() + .into_iter() + .filter(|entry| afi_of(&entry.network) == afi) + .collect(); + let updates = build_announce_updates( + &prefixes, + self.inner.router_id, + local_ip, + local_as, + negotiated, + ); self.emit_updates(peer, writer, negotiated, local_ip, local_as, updates) .await?; write_bgp_message(writer, &end_of_rib(afi), negotiated.asn_length()).await?; @@ -1691,6 +1692,16 @@ fn afi_of(network: &IpNet) -> Afi { } } +/// The refresh ticker for one attribute-255 interval. Missed ticks are skipped +/// rather than burst: after a stall the same clock round would otherwise be +/// dispatched once per missed tick, which can fill a session queue without +/// recovering any measurement. +fn clock_ticker(interval_secs: u32) -> tokio::time::Interval { + let mut ticker = tokio::time::interval(Duration::from_secs(u64::from(interval_secs))); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + ticker +} + fn local_open( router_id: Ipv4Addr, local_as: u32, @@ -3065,4 +3076,81 @@ enabled = false assert!(!again.changed); assert_eq!(again.source, None); } + + /// The session loop must answer a ROUTE-REFRESH while a control client + /// holds the mutation lock: the loop is the only drain for its own queue, + /// so waiting on a lock a blocked producer holds would never resolve. + #[tokio::test] + async fn route_refresh_replay_does_not_wait_for_the_mutation_lock() { + let cfg = test_service_config(); + let (event_tx, _) = broadcast::channel::(4); + let service = BgpService::new(&cfg, event_tx).await.unwrap(); + let network: IpNet = "198.51.100.0/24".parse().unwrap(); + service.prefix_add(network, None, false).await.unwrap(); + + let peer = PeerConfig { + address: "192.0.2.9".to_string(), + remote_as: 65_002, + local_as: None, + hold_time_secs: 30, + connect_retry_secs: 1, + remote_port: 179, + local_address: None, + enabled: true, + passive: true, + route_refresh: true, + name: None, + password: None, + }; + let negotiated = NegotiatedCapabilities { + families: HashSet::from([(Afi::Ipv4, Safi::Unicast)]), + asn4: true, + route_refresh: true, + graceful_restart: false, + }; + let refresh = BgpRouteRefreshMessage { + afi: 1, + subtype: 0, + safi: 1, + data: vec![], + }; + + let guard = service.inner.prefix_ops.lock().await; + let mut out = Vec::new(); + timeout( + Duration::from_secs(5), + service.replay_route_refresh( + &peer, + &mut out, + &negotiated, + "192.0.2.1".parse().unwrap(), + &refresh, + ), + ) + .await + .expect("the replay must not wait for the mutation lock") + .unwrap(); + drop(guard); + + assert!( + !out.is_empty(), + "the replay writes the table and the family's End-of-RIB" + ); + } + + /// A stalled clock task must not replay every missed tick: the same round + /// would be dispatched once per tick and can fill a session queue. + #[tokio::test(start_paused = true)] + async fn clock_ticker_skips_missed_ticks() { + let mut ticker = clock_ticker(30); + ticker.tick().await; + tokio::time::advance(Duration::from_secs(95)).await; + + let mut immediate = 0; + while timeout(Duration::ZERO, ticker.tick()).await.is_ok() { + immediate += 1; + assert!(immediate < 4, "a stall must not burst the missed ticks"); + } + assert_eq!(immediate, 1, "one tick after a stall, not three"); + } }