Compare commits

...
19 Commits
Author SHA1 Message Date
ktims 525a22d100 update cargo
CI / fmt (push) Successful in 32s
CI / clippy (push) Successful in 32s
CI / test (push) Successful in 37s
2026-10-27 15:06:42 -07:00
ktims 2b2fe66785 implement local binding, rfc-based tests, fix deficiencies, add CI 2026-10-27 15:04:50 -07:00
ktims 8962406c57 implement auth, improve session stats 2026-10-23 14:11:16 -07:00
ktims bdf5455a3f Expand unit tests and fix bugs they found
Add unit tests for packet parsing/serialization, interval arithmetic, the
session state machine, validation discards, poll/final, the detection
watchdog, hook scripts, and socket binding.

Fixes:
- BfdAuth parsing subtracted the header from Auth Len twice; Auth Len
  includes the 2-byte header.
- A diagnostic code above 9 panicked the session task; map it to Reserved.
- script_runner panicked on non-UTF-8 script output; decode lossily.
- BfdError::InvalidFieldValue printed field and value swapped.
- BfdInterval now panics on values exceeding u32 microseconds instead of
  silently truncating, and gains checked_mul. Detection time computation
  saturates rather than panicking on remote-supplied multipliers.
2026-10-23 09:52:57 -07:00
ktims 8fbafa455a per-peer stats 2026-10-22 18:14:05 -07:00
ktims ac154066e1 Build a static musl binary into a scratch image
The runtime image contains only the binary and an empty hooks directory, and runs as an unprivileged numeric user. Hook scripts need a shell, so they will not run in this image.
2026-10-22 17:49:12 -07:00
ktims 8321d01ffb Dump the session table on SIGUSR1
Split the receive loop into a select over the control socket and SIGUSR1, and factor the session table formatting into session_report().
2026-10-22 17:49:12 -07:00
ktims eeeef5fb73 Rate-limit logging of unmatched packets
Log the first unmatched packet per source (WARN for an unconfigured source address, INFO for an unknown Your Discriminator) and the repeats at DEBUG until a packet matches again. Removes the duplicate message in rx_packet.
2026-10-22 17:49:12 -07:00
ktims 87e2011c05 Send a control packet immediately on session state change
RFC 5880 6.8.7 says a packet SHOULD be sent between periodic transmissions when its contents would change, so peers see state changes without waiting up to a full interval.
2026-10-22 17:49:12 -07:00
ktims 0c19b955f9 Fix periodic transmit jitter to follow RFC 5880 6.8.7
Jitter was added to a fixed 0.75x clock, so gaps ranged 0.5x-1.0x with a mean of 0.75x of the negotiated interval, below the required 75-100%. Each delay is now drawn independently from 75-100% of the interval (90-100% when DetectMult is 1). Adds statistical and end-to-end sender tests.
2026-10-22 17:49:12 -07:00
ktims 5e5da0c78c Load daemon configuration from file, environment and CLI
Bind addresses and peers are now optional on the command line and merged with the config file. Per-peer timers and detect multiplier are passed through to the session. Multiple bind addresses are accepted by the model but rejected at startup until supported.
2026-10-22 17:49:12 -07:00
ktims ea56afd2f2 Add YAML configuration model and loader
Config is layered: built-in defaults, then the YAML file, then BFD_* environment variables, then CLI flags. Global defaults live under a 'defaults' mapping; per-peer settings are file-only. Includes config.yaml.dist and ScriptHookSink::with_script_dir so the hooks directory is configurable.
2026-10-22 17:48:59 -07:00
ktims 0284ee17b1 clippies 2026-10-22 15:47:16 -07:00
ktims dcbf25ebe0 Add Dockerfile
Multi-stage build producing a slim image with rust-bfdd as the entrypoint. Dependencies are built against stub sources in their own layer so source-only changes do not rebuild them.
2026-10-22 15:44:39 -07:00
ktims 146f8d4c32 Log session table at debug level
The per-packet session dump is too noisy at info.
2026-10-22 15:41:08 -07:00
ktims 4773c9e4f7 Fix protocol conformance issues found in interop testing
Implement the Poll Sequence (initiate on reaching Up when the configured interval is lower than the slow-start one; respond to Poll with Final; terminate on Final) and apply DesiredMinTxInterval changes per RFC 5880 section 6.8.3, keeping the slow rate until the peer has acknowledged. Never set the Demand bit unless demand mode is active, clear the C bit (this implementation shares fate with the control plane), discard packets whose Length exceeds the received payload, and log effective timer changes.
2026-10-22 15:41:08 -07:00
ktims 0bd4f8766a Bind session sockets without panicking
Select a random unused source port in the RFC 5881 range (retrying on EADDRINUSE) instead of unwrapping a pure-random bind. Propagate bind errors out of session start-up, store the local IP on the session instead of unwrapping local_addr(), and log (rather than panic on) receive errors in the rx loop.
2026-10-22 15:41:08 -07:00
ktims c7a6ed16e4 Add command line arguments
Replace the hard-coded addresses with clap arguments: --bind <IP> and one or more --peer <IP>. Peers must match the address family of the bind address. Also updates Cargo.lock.
2026-10-22 15:41:08 -07:00
ktims 0bb1f437ae Declare nix dependency
lib.rs and events.rs already use nix; it was missing from Cargo.toml so the crate did not build.
2026-10-22 15:41:08 -07:00
19 changed files with 5974 additions and 731 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
target
.git
Dockerfile
.dockerignore
+37
View File
@@ -0,0 +1,37 @@
name: CI
on:
push:
branches: [main]
pull_request:
env:
CARGO_TERM_COLOR: always
jobs:
fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@1.94
with:
components: rustfmt
- run: cargo fmt --all -- --check
clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@1.94
with:
components: clippy
- uses: Swatinem/rust-cache@v2
- run: cargo clippy --locked --all-targets -- -D warnings
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@1.94
- uses: Swatinem/rust-cache@v2
- run: cargo test --locked
+21
View File
@@ -0,0 +1,21 @@
repos:
- repo: local
hooks:
- id: cargo-fmt
name: cargo fmt
entry: cargo fmt --all -- --check
language: system
types: [rust]
pass_filenames: false
- id: cargo-clippy
name: cargo clippy
entry: cargo clippy --locked --all-targets -- -D warnings
language: system
types: [rust]
pass_filenames: false
- id: cargo-test
name: cargo test
entry: cargo test --locked
language: system
types: [rust]
pass_filenames: false
Generated
+666 -333
View File
File diff suppressed because it is too large. Load diff
+15
View File
@@ -7,13 +7,28 @@ edition = "2021"
atomic = "0.6.0"
bytemuck = { version = "1.14.1", features = ["derive"] }
byteorder = "1.5.0"
clap = { version = "4", features = ["derive", "env"] }
digest = "0.11.3"
env_logger = "0.11.1"
futures = "0.3.30"
humantime = "2.4.0"
humantime-serde = "1.1.1"
itertools = "0.12.1"
log = "0.4.20"
md-5 = "0.11.0"
nix = { version = "0.31.3", features = ["fs", "net", "socket"] }
nom = "7.1.3"
nom-derive = "0.10.1"
proc-bitfield = "0.3.1"
rand = "0.8.5"
serde = { version = "1.0.229", features = ["derive"] }
serde_bytes = "0.11.19"
serde_yaml_ng = "0.10.0"
sha1 = "0.11.0"
subtle = "2.6"
tokio = { version = "1.35.1", features = ["net", "full"] }
tokio-timer = "0.2.13"
[dev-dependencies]
rstest = "0.28.0"
+28
View File
@@ -0,0 +1,28 @@
FROM rust:1.94-bookworm AS builder
# Statically linked musl build. Override for other architectures, e.g. --build-arg RUST_TARGET=aarch64-unknown-linux-musl
ARG RUST_TARGET=x86_64-unknown-linux-musl
RUN rustup target add ${RUST_TARGET}
WORKDIR /build
# Build dependencies against stub sources so this layer is only invalidated by Cargo.toml/Cargo.lock changes.
COPY Cargo.toml Cargo.lock ./
RUN mkdir -p src/bin \
&& touch src/lib.rs \
&& echo 'fn main() {}' > src/bin/rust-bfdd.rs \
&& cargo build --release --locked --target ${RUST_TARGET} --bin rust-bfdd \
&& rm -rf src
COPY src ./src
# COPY keeps the host mtimes, which may predate the stub build; force cargo to rebuild the crate itself.
RUN touch src/lib.rs src/bin/rust-bfdd.rs \
&& cargo build --release --locked --target ${RUST_TARGET} --bin rust-bfdd \
&& mkdir -p /rootfs/etc/rust-bfd/hooks.d \
&& cp target/${RUST_TARGET}/release/rust-bfdd /rootfs/rust-bfdd
FROM scratch
COPY --from=builder /rootfs/etc /etc
COPY --from=builder /rootfs/rust-bfdd /usr/local/bin/rust-bfdd
# No /etc/passwd in scratch, so use a numeric unprivileged user
USER 10001:10001
EXPOSE 3784/udp
ENTRYPOINT ["/usr/local/bin/rust-bfdd"]
+80
View File
@@ -0,0 +1,80 @@
# rust-bfd configuration. Install as /etc/rust-bfd/config.yaml, or select another file with --config / BFD_CONFIG.
# This file is the only way to configure the daemon.
#
# Values shown below are the built-in defaults unless noted. Unknown keys are an error.
# Directory of executable scripts run, in lexical order, on every session state change.
hooks_dir: /etc/rust-bfd/hooks.d
# Settings inherited by every peer that does not override them. Durations are humantime strings (300ms, 1s, 2m).
# A peer is never allowed a zero interval or a detect_mult of 0.
defaults:
# Minimum interval between transmitted control packets that we would like to use once the session is Up. Sessions
# that are not Up transmit no faster than once per second regardless (RFC 5880 section 6.8.3).
desired_min_tx: 300ms
# Minimum interval between received control packets we can support.
required_min_rx: 300ms
# Detection time multiplier: we declare the session down after this many missed packets.
detect_mult: 3
# Peers to establish sessions with.
#
# `local` is required: the local address the session runs from, which is the source of its control packets and the
# address the daemon listens on for the peer's. It must be of the same address family as `address`. The daemon listens
# on each distinct `local` address (and `interface`, below) once, however many peers use it; peers may use different
# local addresses.
#
# `interface` optionally binds the session's sockets to one interface (SO_BINDTODEVICE). It is required when `local` or
# `address` is an IPv6 link-local address (fe80::/10), which is only meaningful on a given link. The same peer address
# may be configured on several interfaces. The binding is to the interface as it exists at startup: if it is
# recreated, the daemon must be restarted.
peers:
- address: 192.0.2.2
local: 192.0.2.1
# - address: 2001:db8::2
# local: "2001:db8::1"
#
# - address: "fe80::2"
# local: "fe80::1"
# interface: eth1
#
# Per-peer overrides of any `defaults` key:
# - address: 192.0.2.3
# local: 192.0.2.1
# desired_min_tx: 1s
# required_min_rx: 1s
# detect_mult: 5
#
# Authentication (RFC 5880 section 6.7), per peer and off by default. Both ends must be configured identically; a
# peer that does not authenticate as configured is discarded. `key_id` is a number (0-255) that must match the remote's.
# Keys are used verbatim (not hashed or derived), so they must be exactly the length shown. Give them as a string;
# use YAML double-quoted escapes (\x00, \x1b, ...) for bytes that are not printable. Strings are UTF-8, so only bytes
# 0x00-0x7f can be written this way. To use bytes 0x80-0xff, give the key as a list of integers instead, one per
# byte (hex is fine), with the same length requirement:
# key: [0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x80, 0xff]
#
# Keyed MD5: `key` is exactly 16 bytes. `meticulous` (default true) selects Meticulous Keyed MD5, in which every
# packet must carry a newer sequence number; the remote must be set to the same mode.
# - address: 192.0.2.4
# local: 192.0.2.1
# auth:
# type: md5
# key_id: 1
# key: "0123456789abcdef"
# meticulous: true
#
# Keyed SHA1: `key` is exactly 20 bytes. `meticulous` as above.
# - address: 192.0.2.5
# local: 192.0.2.1
# auth:
# type: sha1
# key_id: 1
# key: "0123456789abcdef\x00\x01\x7f\x1b"
#
# Simple password: 1 to 16 bytes, sent in the clear. Provides no protection against an attacker on the path.
# - address: 192.0.2.6
# local: 192.0.2.1
# auth:
# type: password
# key_id: 1
# password: "secret"
+952 -67
View File
File diff suppressed because it is too large. Load diff
+1683 -309
View File
File diff suppressed because it is too large. Load diff
+166
View File
@@ -0,0 +1,166 @@
//! Conformance tests for the single-hop subset of RFC 5880 and RFC 5881.
//!
//! Tests marked `#[ignore = "known RFC violation: ..."]` assert the RFC behaviour and currently fail.
use super::*;
use digest::Digest;
use md5::Md5;
use sha1::Sha1;
mod auth;
mod fsm;
mod transport;
mod tx;
mod violations;
const MD5_KEY: [u8; 16] = *b"0123456789abcdef";
type Events = mpsc::UnboundedReceiver<StateChangeEvent>;
async fn tapped(peer: ResolvedPeer) -> (BfdSession, UdpSocket, Events) {
let (dispatcher, events) = capture_dispatcher().await;
let (tx, rx) = mpsc::channel(32);
let sock = UdpSocket::bind((LOCAL, 0)).await.unwrap();
let tap = UdpSocket::bind((LOCAL, 0)).await.unwrap();
let s = BfdSession::new(
rx,
BfdSessionHandle { tx },
sock,
LOCAL,
tap.local_addr().unwrap(),
peer,
BfdDiscriminator(LOCAL_DISCR),
dispatcher,
);
(s, tap, events)
}
async fn recv_raw(tap: &UdpSocket) -> Vec<u8> {
let mut buf = [0u8; 128];
let (n, _) = time::timeout(Duration::from_secs(2), tap.recv_from(&mut buf))
.await
.expect("no packet transmitted")
.unwrap();
buf[..n].to_vec()
}
fn parse_raw(raw: &[u8]) -> BfdPacket {
BfdPacket::parse(raw).expect("transmitted packet parses").1
}
async fn recv_packet(tap: &UdpSocket) -> BfdPacket {
parse_raw(&recv_raw(tap).await)
}
async fn drain(tap: &UdpSocket) -> Vec<BfdPacket> {
let mut out = Vec::new();
let mut buf = [0u8; 128];
while let Ok(Ok((n, _))) =
time::timeout(Duration::from_millis(40), tap.recv_from(&mut buf)).await
{
out.push(parse_raw(&buf[..n]));
}
out
}
async fn tapped_in(state: BfdState) -> (BfdSession, UdpSocket, Events) {
let (mut s, tap, mut events) = tapped(peer_cfg(300, 300, 3)).await;
let path: &[BfdState] = match state {
BfdState::Down => &[],
BfdState::Init => &[BfdState::Down],
_ => &[BfdState::Down, BfdState::Init],
};
for (i, remote) in path.iter().enumerate() {
let your = if i == 0 { 0 } else { LOCAL_DISCR };
s.receive_control_packet(&pkt(*remote, REMOTE_DISCR, your))
.await;
next_event(&mut events).await;
}
assert_eq!(s.state.session_state(), state);
drain(&tap).await;
(s, tap, events)
}
fn fast(state: BfdState, your: u32) -> BfdPacket {
let mut p = pkt(state, REMOTE_DISCR, your);
p.flags = p.flags.with_detect_mult(255);
p.desired_min_tx = BfdInterval::from_millis(20);
p.required_min_rx = BfdInterval::from_millis(20);
p
}
async fn fast_up() -> (BfdSession, UdpSocket, Events) {
let (mut s, tap, mut events) = tapped(peer_cfg(20, 20, 3)).await;
s.receive_control_packet(&fast(BfdState::Down, 0)).await;
s.receive_control_packet(&fast(BfdState::Init, LOCAL_DISCR))
.await;
next_event(&mut events).await;
next_event(&mut events).await;
assert_eq!(s.state.session_state(), BfdState::Up);
let ended = with_flags(fast(BfdState::Up, LOCAL_DISCR), |f| f.with_final_(true));
s.receive_control_packet(&ended).await;
assert!(!s.state.poll_mode());
drain(&tap).await;
(s, tap, events)
}
async fn drain_commands(s: &mut BfdSession) -> usize {
time::sleep(Duration::from_millis(50)).await;
let mut n = 0;
while let Ok(cmd) = s.rx.try_recv() {
n += matches!(cmd, SessionControlCommand::TxControlPacket { .. }) as usize;
}
n
}
fn key_for(auth: &BfdAuth) -> Vec<u8> {
auth.digest_field().unwrap().to_vec()
}
fn md5_auth(meticulous: bool, key_id: u8, seq: u32) -> BfdAuth {
BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
meticulous,
key_id,
reserved: 0,
seq,
digest: MD5_KEY,
})
}
fn sha1_auth(meticulous: bool, key_id: u8, seq: u32) -> BfdAuth {
BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
meticulous,
key_id,
reserved: 0,
seq,
digest: SHA1_KEY,
})
}
fn password_auth(key_id: u8, password: &[u8]) -> BfdAuth {
BfdAuth::SimplePassword(BfdAuthSimplePassword {
key_id,
password: password.to_vec(),
})
}
fn signed(auth: BfdAuth, state: BfdState, my: u32, your: u32) -> BfdPacket {
let len = 24 + auth.auth_len();
let mut p = with_flags(pkt(state, my, your), |f| {
f.with_auth_present(true).with_length(len)
});
p.auth = Some(auth);
p.sign().unwrap();
p
}
async fn keyed_session(auth: BfdAuth) -> (BfdSession, UdpSocket, Events) {
let (mut s, tap, events) = tapped(peer_cfg(300, 300, 3)).await;
s.state.auth_type.store(auth.auth_type(), ORDERING);
s.auth = Some(auth);
(s, tap, events)
}
async fn accepted(s: &mut BfdSession, p: &BfdPacket) -> bool {
s.receive_control_packet(p).await;
s.state.remote_discr() == p.my_disc
}
+312
View File
@@ -0,0 +1,312 @@
use super::*;
fn digest_with_key<D: Digest>(raw: &[u8], key: &[u8], at: usize) -> Vec<u8> {
let mut keyed = raw.to_vec();
keyed[at..at + key.len()].copy_from_slice(key);
D::digest(&keyed).as_slice().to_vec()
}
// RFC 5880 4.3, 4.4, 6.7.3, 6.7.4: field layout, sequence number handling and digest of a transmitted packet.
async fn check_keyed_tx<D: Digest>(auth: BfdAuth, auth_len: usize, type_byte: u8) {
let key = key_for(&auth);
let (mut s, tap, _events) = keyed_session(auth).await;
s.state.xmit_auth_seq.store(u32::MAX - 1, ORDERING);
let mut seqs = Vec::new();
for _ in 0..4 {
s.transmit_control_packet(false).await;
let raw = recv_raw(&tap).await;
assert_eq!(raw.len(), 24 + auth_len);
assert_eq!(raw[3] as usize, 24 + auth_len);
assert_ne!(raw[1] & 0x04, 0, "A bit");
assert_eq!(raw[24], type_byte);
assert_eq!(raw[25] as usize, auth_len);
assert_eq!(raw[26], 7, "key id");
assert_eq!(raw[27], 0, "reserved");
seqs.push(u32::from_be_bytes(raw[28..32].try_into().unwrap()));
let digest = &raw[32..];
assert_ne!(digest, key, "key must not be sent");
assert_eq!(digest, digest_with_key::<D>(&raw, &key, 32));
}
assert_eq!(
seqs,
[u32::MAX, 0, 1, 2],
"meticulous sequence wraps by one"
);
}
#[tokio::test]
async fn tx_keyed_md5() {
check_keyed_tx::<Md5>(md5_auth(false, 7, 0), 24, 2).await;
}
#[tokio::test]
async fn tx_meticulous_keyed_md5() {
check_keyed_tx::<Md5>(md5_auth(true, 7, 0), 24, 3).await;
}
#[tokio::test]
async fn tx_keyed_sha1() {
check_keyed_tx::<Sha1>(sha1_auth(false, 7, 0), 28, 4).await;
}
#[tokio::test]
async fn tx_meticulous_keyed_sha1() {
check_keyed_tx::<Sha1>(sha1_auth(true, 7, 0), 28, 5).await;
}
// RFC 5880 4.2, 6.7.2
#[tokio::test]
async fn tx_simple_password() {
let (mut s, tap, _events) = keyed_session(password_auth(3, b"secret")).await;
s.transmit_control_packet(false).await;
let raw = recv_raw(&tap).await;
assert_eq!(raw.len(), 24 + 3 + 6);
assert_eq!(raw[3], 33);
assert_ne!(raw[1] & 0x04, 0);
assert_eq!(&raw[24..27], &[1, 9, 3]);
assert_eq!(&raw[27..], b"secret");
}
// RFC 5880 6.8.1: bfd.XmitAuthSeq SHOULD be random at session creation.
#[tokio::test]
async fn initial_xmit_auth_seq_is_random() {
let mut seqs = HashSet::new();
for _ in 0..8 {
let (s, _tap, _events) = keyed_session(sha1_auth(true, 1, 0)).await;
seqs.insert(s.state.xmit_auth_seq.load(ORDERING));
}
assert!(seqs.len() > 1);
}
// RFC 5880 6.7.3 / 6.7.4 receive rules.
#[tokio::test]
async fn rx_valid_keyed_packets_are_accepted() {
for auth in [
md5_auth(false, 1, 5),
md5_auth(true, 1, 5),
sha1_auth(false, 1, 5),
sha1_auth(true, 1, 5),
] {
let (mut s, _tap, _events) = keyed_session(auth.clone()).await;
assert!(
accepted(
&mut s,
&signed(auth.clone(), BfdState::Down, REMOTE_DISCR, 0)
)
.await
);
assert_eq!(s.state.auth_type(), auth.auth_type());
}
}
#[tokio::test]
async fn rx_bad_digest_is_discarded() {
for auth in [md5_auth(false, 1, 5), sha1_auth(true, 1, 5)] {
let (mut s, _tap, _events) = keyed_session(auth.clone()).await;
let mut p = signed(auth.clone(), BfdState::Down, REMOTE_DISCR, 0);
p.desired_min_tx = BfdInterval::from_millis(1);
assert!(!accepted(&mut s, &p).await);
let wrong_key = match auth {
BfdAuth::KeyedMD5(a) => BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
digest: [9; 16],
..a
}),
BfdAuth::KeyedSHA1(a) => BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
digest: [9; 20],
..a
}),
other => other,
};
assert!(!accepted(&mut s, &signed(wrong_key, BfdState::Down, REMOTE_DISCR, 0)).await);
assert_eq!(s.state.session_state(), BfdState::Down);
}
}
#[tokio::test]
async fn rx_unknown_key_id_is_discarded() {
let (mut s, _tap, _events) = keyed_session(sha1_auth(false, 1, 0)).await;
assert!(
!accepted(
&mut s,
&signed(sha1_auth(false, 2, 5), BfdState::Down, REMOTE_DISCR, 0)
)
.await
);
let (mut s, _tap, _events) = keyed_session(password_auth(1, b"pw")).await;
assert!(
!accepted(
&mut s,
&signed(password_auth(2, b"pw"), BfdState::Down, REMOTE_DISCR, 0)
)
.await
);
}
#[tokio::test]
async fn rx_wrong_auth_type_is_discarded() {
let cases = [
(sha1_auth(false, 1, 0), md5_auth(false, 1, 5)),
(md5_auth(false, 1, 0), md5_auth(true, 1, 5)),
(sha1_auth(true, 1, 0), sha1_auth(false, 1, 5)),
(md5_auth(false, 1, 0), password_auth(1, b"pw")),
(password_auth(1, b"pw"), sha1_auth(false, 1, 5)),
];
for (configured, received) in cases {
let (mut s, _tap, _events) = keyed_session(configured.clone()).await;
let p = signed(received.clone(), BfdState::Down, REMOTE_DISCR, 0);
assert!(
!accepted(&mut s, &p).await,
"{:?} vs {:?}",
configured.auth_type(),
received.auth_type()
);
}
}
// RFC 5880 6.8.6: the A bit must agree with whether authentication is in use.
#[tokio::test]
async fn rx_a_bit_must_match_authentication_in_use() {
let (mut s, _tap, _events) = keyed_session(sha1_auth(false, 1, 0)).await;
assert!(!accepted(&mut s, &pkt(BfdState::Down, REMOTE_DISCR, 0)).await);
let (mut s, _tap, _events) = tapped(peer_cfg(300, 300, 3)).await;
let p = signed(sha1_auth(false, 1, 5), BfdState::Down, REMOTE_DISCR, 0);
assert!(!accepted(&mut s, &p).await);
}
#[tokio::test]
async fn rx_simple_password_must_match() {
let (mut s, _tap, _events) = keyed_session(password_auth(1, b"secret")).await;
assert!(
!accepted(
&mut s,
&signed(password_auth(1, b"secreT"), BfdState::Down, REMOTE_DISCR, 0)
)
.await
);
assert!(
!accepted(
&mut s,
&signed(password_auth(1, b"secre"), BfdState::Down, REMOTE_DISCR, 0)
)
.await
);
assert!(
!accepted(
&mut s,
&signed(
password_auth(1, b"secrets"),
BfdState::Down,
REMOTE_DISCR,
0
)
)
.await
);
assert!(
accepted(
&mut s,
&signed(password_auth(1, b"secret"), BfdState::Down, REMOTE_DISCR, 0)
)
.await
);
}
// RFC 5880 6.7.3 / 6.7.4: meticulous requires a strictly increasing sequence, non-meticulous allows repeats.
#[tokio::test]
async fn rx_sequence_replay_rules_depend_on_meticulous() {
for (meticulous, repeat_ok) in [(true, false), (false, true)] {
let (mut s, _tap, _events) = keyed_session(sha1_auth(meticulous, 1, 0)).await;
let first = signed(
sha1_auth(meticulous, 1, 1000),
BfdState::Down,
REMOTE_DISCR,
0,
);
assert!(accepted(&mut s, &first).await);
let repeat = signed(
sha1_auth(meticulous, 1, 1000),
BfdState::Down,
REMOTE_DISCR + 1,
0,
);
assert_eq!(
accepted(&mut s, &repeat).await,
repeat_ok,
"meticulous={meticulous}"
);
let next = signed(
sha1_auth(meticulous, 1, 1001),
BfdState::Down,
REMOTE_DISCR + 2,
0,
);
assert!(accepted(&mut s, &next).await);
let old = signed(
sha1_auth(meticulous, 1, 900),
BfdState::Down,
REMOTE_DISCR + 3,
0,
);
assert!(!accepted(&mut s, &old).await, "old seq");
}
}
// A packet that fails authentication must not move the replay window, otherwise a forged packet could lock out the
// legitimate peer. (Deliberate deviation from the literal order of RFC 5880 6.7.3 / 6.7.4.)
#[tokio::test]
async fn rx_failed_digest_does_not_update_sequence_state() {
for meticulous in [false, true] {
let (mut s, _tap, _events) = keyed_session(sha1_auth(meticulous, 1, 0)).await;
let forge = |seq: u32| {
let mut p = signed(
sha1_auth(meticulous, 1, seq),
BfdState::Down,
REMOTE_DISCR + 100,
0,
);
p.desired_min_tx = BfdInterval::from_millis(1);
p
};
// Unknown state: a forged packet must not initialise the sequence state.
assert!(!accepted(&mut s, &forge(5000)).await);
assert!(!s.state.auth_seq_known());
let first = signed(
sha1_auth(meticulous, 1, 10),
BfdState::Down,
REMOTE_DISCR,
0,
);
assert!(accepted(&mut s, &first).await);
assert_eq!(s.state.rcv_auth_seq.load(ORDERING), 10);
// Known state: a forged in-window packet must not advance it.
assert!(!accepted(&mut s, &forge(12)).await);
assert!(s.state.auth_seq_known());
assert_eq!(s.state.rcv_auth_seq.load(ORDERING), 10);
let next = signed(
sha1_auth(meticulous, 1, 11),
BfdState::Down,
REMOTE_DISCR + 1,
0,
);
assert!(accepted(&mut s, &next).await);
assert_eq!(s.state.rcv_auth_seq.load(ORDERING), 11);
}
}
// RFC 5880 6.7.3 / 6.7.4: Auth Len other than 24 / 28 is discarded (here via the digest, which covers the length).
#[tokio::test]
async fn rx_keyed_auth_len_other_than_24_or_28_is_discarded() {
for auth in [md5_auth(false, 1, 5), sha1_auth(false, 1, 5)] {
let (mut s, _tap, _events) = keyed_session(auth.clone()).await;
let mut raw = signed(auth.clone(), BfdState::Down, REMOTE_DISCR, 0)
.serialize()
.unwrap();
raw[25] += 4;
raw[3] += 4;
raw.extend_from_slice(&[0; 4]);
let p = BfdPacket::parse(&raw).unwrap().1;
assert!(!accepted(&mut s, &p).await, "{:?}", auth.auth_type());
}
}
+180
View File
@@ -0,0 +1,180 @@
use super::*;
use BfdState::{AdminDown, Down, Init, Up};
// RFC 5880 6.8.6 state machine, with Your Discriminator naming this session.
#[tokio::test]
async fn state_machine_table() {
let table = [
(Down, Down, Init),
(Down, Init, Up),
(Down, Up, Down),
(Down, AdminDown, Down),
(Init, Down, Init),
(Init, Init, Up),
(Init, Up, Up),
(Init, AdminDown, Down),
(Up, Down, Down),
(Up, Init, Up),
(Up, Up, Up),
(Up, AdminDown, Down),
];
for (local, remote, expected) in table {
let (mut s, _events) = session_in(local).await;
s.receive_control_packet(&pkt(remote, REMOTE_DISCR, LOCAL_DISCR))
.await;
assert_eq!(
s.state.session_state(),
expected,
"local {local}, received {remote}"
);
let signalled_down = local != Down && remote == AdminDown || (local, remote) == (Up, Down);
let diag = if signalled_down {
BfdDiagnostic::NeighborDown
} else {
BfdDiagnostic::None
};
assert_eq!(
s.state.local_diag(),
diag,
"local {local}, received {remote}"
);
}
}
// RFC 5880 6.8.6: a first packet (Your Discriminator zero) may only be Down or AdminDown.
#[tokio::test]
async fn zero_your_discriminator_requires_down_or_admin_down() {
for state in [Init, Up] {
let (mut s, _events) = session(peer_cfg(300, 300, 3)).await;
s.receive_control_packet(&pkt(state, REMOTE_DISCR, 0)).await;
assert_eq!(s.state.session_state(), Down);
assert_eq!(s.state.remote_discr(), BfdDiscriminator(0));
}
}
// RFC 5880 6.8.4: Detection Time expiry takes an Up session Down with diagnostic 1.
#[tokio::test]
async fn up_timeout_goes_down_with_time_expired() {
let (mut s, mut events) = session_in(Up).await;
s.detection_timeout().await;
assert_eq!(s.state.session_state(), Down);
assert_eq!(s.state.local_diag(), BfdDiagnostic::TimeExpired);
let ev = next_event(&mut events).await;
assert_eq!((ev.from_state, ev.to_state), (Up, Down));
}
#[tokio::test]
async fn init_timeout_goes_down_with_time_expired() {
let (mut s, _events) = session_in(Init).await;
s.detection_timeout().await;
assert_eq!(s.state.session_state(), Down);
assert_eq!(s.state.local_diag(), BfdDiagnostic::TimeExpired);
}
// RFC 5880 6.8.4: the timer is armed by a valid packet in Init or Up, and not in Down.
#[tokio::test]
async fn detection_timer_is_armed_only_in_init_and_up() {
let (mut s, _events) = session(peer_cfg(300, 300, 3)).await;
s.receive_control_packet(&pkt(Down, REMOTE_DISCR, 0)).await;
assert_eq!(s.state.session_state(), Init);
assert!(s.detect_deadline.is_some());
s.receive_control_packet(&pkt(Init, REMOTE_DISCR, LOCAL_DISCR))
.await;
assert_eq!(s.state.session_state(), Up);
assert!(s.detect_deadline.is_some());
s.receive_control_packet(&pkt(Down, REMOTE_DISCR, LOCAL_DISCR))
.await;
assert_eq!(s.state.session_state(), Down);
assert!(s.detect_deadline.is_none());
}
// RFC 5880 6.8.4: the timer only applies while Demand mode is not active on the remote system (6.8.6: D bit set and
// both sessions Up). A remote in Demand mode legitimately stops sending periodic packets.
#[tokio::test]
async fn detection_timer_is_suspended_while_remote_demand_is_active() {
let demand = |state, your| with_flags(pkt(state, REMOTE_DISCR, your), |f| f.with_demand(true));
let (mut s, _events) = session_in(Up).await;
assert!(s.detect_deadline.is_some());
s.receive_control_packet(&demand(Up, LOCAL_DISCR)).await;
assert_eq!(s.state.session_state(), Up);
assert!(s.detect_deadline.is_none());
// Further Polls from a demand-mode peer don't re-arm it.
s.receive_control_packet(&with_flags(demand(Up, LOCAL_DISCR), |f| f.with_poll(true)))
.await;
assert!(s.detect_deadline.is_none());
// Demand mode ends: periodic packets are expected again.
s.receive_control_packet(&pkt(Up, REMOTE_DISCR, LOCAL_DISCR))
.await;
assert!(s.detect_deadline.is_some());
}
// The D bit has no effect unless the remote session is Up and ours is Up too.
#[tokio::test]
async fn detection_timer_stays_armed_when_demand_is_not_active() {
let (mut s, _events) = session_in(Init).await;
s.receive_control_packet(&with_flags(pkt(Init, REMOTE_DISCR, LOCAL_DISCR), |f| {
f.with_demand(true)
}))
.await;
assert_eq!(s.state.session_state(), Up);
// remote state is Init, not Up
assert!(s.detect_deadline.is_some());
}
// RFC 5880 6.8.4: the timer does not fire a second time after the session has gone Down.
#[tokio::test]
async fn detection_timer_is_disarmed_after_firing() {
let (mut s, _events) = session_in(Up).await;
s.detection_timeout().await;
assert!(s.detect_deadline.is_none());
}
// RFC 5880 6.8.4: the watchdog itself fires in Init when no further packets arrive.
#[tokio::test]
async fn init_expires_without_further_packets() {
let (dispatcher, mut events) = capture_dispatcher().await;
let handle = BfdSessionHandle::new(
LOCAL,
peer_cfg(20, 20, 3),
BfdDiscriminator(LOCAL_DISCR),
dispatcher,
)
.await
.unwrap();
let mut p = fast(Down, 0);
p.flags = p.flags.with_detect_mult(5);
handle
.tx
.send(SessionControlCommand::RxPacket(p))
.await
.unwrap();
assert_eq!(next_event(&mut events).await.to_state, Init);
let ev = next_event(&mut events).await;
assert_eq!((ev.from_state, ev.to_state), (Init, Down));
handle.tx.send(SessionControlCommand::Quit).await.unwrap();
}
// RFC 5880 6.8.4: Detection Time is the remote's Detect Mult times the agreed interval.
#[tokio::test]
async fn detection_time_is_remote_mult_times_larger_interval() {
let (mut s, _events) = session(peer_cfg(300, 100, 3)).await;
let mut p = pkt(Down, REMOTE_DISCR, 0);
p.flags = p.flags.with_detect_mult(4);
p.desired_min_tx = BfdInterval::from_millis(250);
s.receive_control_packet(&p).await;
assert_eq!(s.state.detection_time(), BfdInterval::from_millis(1000));
}
// RFC 5880 6.8.2: the transmit interval is the larger of our Desired Min TX and the remote's Required Min RX.
#[tokio::test]
async fn transmit_interval_is_max_of_desired_and_remote_required() {
let (mut s, _events) = session(peer_cfg(300, 100, 3)).await;
let mut p = pkt(Down, REMOTE_DISCR, 0);
p.required_min_rx = BfdInterval::from_secs(3);
s.receive_control_packet(&p).await;
assert_eq!(s.cur_interval, BfdInterval::from_secs(3));
}
+92
View File
@@ -0,0 +1,92 @@
use super::*;
use std::net::Ipv6Addr;
async fn dispatcher() -> EventDispatcherHandle {
capture_dispatcher().await.0
}
async fn ttl_filter_case(local: IpAddr, sender_bind: IpAddr) {
let key = BfddKey {
local,
interface: None,
};
let (d, _handle) = Bfdd::new(
key,
Vec::new(),
DiscriminatorAllocator::default(),
dispatcher().await,
)
.await
.unwrap();
let dest = SocketAddr::new(local, CONTROL_PORT);
let sender = UdpSocket::bind((sender_bind, 0)).await.unwrap();
let mut buf = [0u8; 64];
set_ttl_or_hop_limit(&sender, 64).unwrap();
sender.send_to(&[0u8; 24], dest).await.unwrap();
let got = time::timeout(
Duration::from_millis(300),
d.control_socket.recv_from(&mut buf),
)
.await;
assert!(got.is_err(), "packet with TTL 64 was delivered");
set_ttl_or_hop_limit(&sender, 255).unwrap();
sender.send_to(&[0u8; 24], dest).await.unwrap();
let got = time::timeout(Duration::from_secs(2), d.control_socket.recv_from(&mut buf))
.await
.expect("packet with TTL 255 was not delivered")
.unwrap();
assert_eq!(got.0, 24);
}
// RFC 5881 5: received packets with TTL / Hop Limit other than 255 MUST be discarded.
#[tokio::test]
async fn rx_ttl_other_than_255_is_dropped_v4() {
ttl_filter_case(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 88)), LOCAL).await;
}
#[tokio::test]
async fn rx_hop_limit_other_than_255_is_dropped_v6() {
let lo = IpAddr::V6(Ipv6Addr::LOCALHOST);
if UdpSocket::bind((lo, 0)).await.is_err() {
eprintln!("skipping: no IPv6 loopback");
return;
}
ttl_filter_case(lo, lo).await;
}
// RFC 5881 4: destination port 3784; source port in 49152..=65535 and constant for the life of the session.
#[tokio::test]
async fn tx_uses_port_3784_and_a_stable_source_port_in_range() {
let peer_ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 77));
let listener = UdpSocket::bind((peer_ip, CONTROL_PORT)).await.unwrap();
let peer = ResolvedPeer {
address: peer_ip,
..peer_cfg(300, 300, 3)
};
let handle = BfdSessionHandle::new(
LOCAL,
peer,
BfdDiscriminator(LOCAL_DISCR),
dispatcher().await,
)
.await
.unwrap();
let mut ports = Vec::new();
for _ in 0..3 {
handle.transmit_control_packet(false).await.unwrap();
let mut buf = [0u8; 64];
let (n, from) = time::timeout(Duration::from_secs(2), listener.recv_from(&mut buf))
.await
.expect("nothing sent to the peer")
.unwrap();
assert_eq!(n, 24);
assert_eq!(from.ip(), LOCAL);
ports.push(from.port());
}
assert_eq!(listener.local_addr().unwrap().port(), 3784);
assert!(ports.iter().all(|p| *p >= SOURCE_PORT_FIRST), "{ports:?}");
assert!(ports.windows(2).all(|w| w[0] == w[1]), "{ports:?}");
handle.tx.send(SessionControlCommand::Quit).await.unwrap();
}
+148
View File
@@ -0,0 +1,148 @@
use super::*;
// RFC 5880 6.8.7 and RFC 5881 3 (Active role): the first packet of a session.
#[tokio::test]
async fn first_packet_of_new_session() {
let (mut s, tap, _events) = tapped(peer_cfg(300, 200, 3)).await;
s.transmit_control_packet(false).await;
let raw = recv_raw(&tap).await;
assert_eq!(raw.len(), 24);
let p = parse_raw(&raw);
assert_eq!(p.flags.vers(), 1);
assert_eq!(p.flags.diag(), Ok(BfdDiagnostic::None));
assert_eq!(p.flags.state(), Ok(BfdState::Down));
assert!(!p.flags.poll());
assert!(!p.flags.final_());
assert!(!p.flags.cpi());
assert!(!p.flags.auth_present());
assert!(!p.flags.demand());
assert!(!p.flags.multipoint());
assert_eq!(p.flags.detect_mult(), 3);
assert_eq!(p.flags.length(), 24);
assert_eq!(p.my_disc, BfdDiscriminator(LOCAL_DISCR));
assert_eq!(p.your_disc, BfdDiscriminator(0));
assert_eq!(p.desired_min_tx, BfdInterval::from_secs(1));
assert_eq!(p.required_min_rx, BfdInterval::from_millis(200));
assert_eq!(p.required_min_echo_rx, BfdInterval::from_micros(0));
}
// RFC 5881 3: a system in the Active role sends periodic packets without having heard from the peer.
#[tokio::test]
async fn active_role_transmits_unsolicited() {
let (mut s, _tap, _events) = tapped(peer_cfg(300, 300, 3)).await;
let cmd = time::timeout(Duration::from_millis(1200), s.rx.recv())
.await
.expect("no periodic transmission within the 1s interval");
assert!(matches!(
cmd,
Some(SessionControlCommand::TxControlPacket {
poll_response: false
})
));
}
// RFC 5880 6.8.7: Your Discriminator is bfd.RemoteDiscr.
#[tokio::test]
async fn your_discriminator_reflects_learned_remote_discriminator() {
let (mut s, tap, _events) = tapped(peer_cfg(300, 300, 3)).await;
s.receive_control_packet(&pkt(BfdState::Down, REMOTE_DISCR, 0))
.await;
let p = recv_packet(&tap).await;
assert_eq!(p.flags.state(), Ok(BfdState::Init));
assert_eq!(p.your_disc, BfdDiscriminator(REMOTE_DISCR));
assert_eq!(p.my_disc, BfdDiscriminator(LOCAL_DISCR));
}
// RFC 5880 6.8.7: the Poll and Final bits MUST NOT both be set.
#[tokio::test]
async fn poll_and_final_are_never_both_set() {
let (mut s, tap, _events) = tapped(peer_cfg(300, 300, 3)).await;
s.state.set_poll_mode(true);
s.transmit_control_packet(false).await;
let p = recv_packet(&tap).await;
assert!(p.flags.poll() && !p.flags.final_());
s.transmit_control_packet(true).await;
let p = recv_packet(&tap).await;
assert!(!p.flags.poll() && p.flags.final_());
}
// RFC 5880 6.8.6: a received Poll is answered with exactly one Final packet.
#[tokio::test]
async fn poll_is_answered_with_a_single_final() {
for (local, remote) in [
(BfdState::Down, BfdState::Up),
(BfdState::Init, BfdState::Down),
(BfdState::Up, BfdState::Up),
] {
let (mut s, tap, _events) = tapped_in(local).await;
let poll = with_flags(pkt(remote, REMOTE_DISCR, LOCAL_DISCR), |f| {
f.with_poll(true)
});
s.receive_control_packet(&poll).await;
let sent = drain(&tap).await;
assert_eq!(sent.len(), 1, "{local} / {remote}");
assert!(sent[0].flags.final_() && !sent[0].flags.poll(), "{local}");
assert_eq!(s.state.session_state(), local);
}
}
// RFC 5880 6.8.7: a packet SHOULD be sent immediately when its contents change.
#[tokio::test]
async fn state_change_sends_packet_carrying_the_new_state() {
let (mut s, tap, _events) = tapped_in(BfdState::Init).await;
s.receive_control_packet(&pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR))
.await;
let p = recv_packet(&tap).await;
assert_eq!(p.flags.state(), Ok(BfdState::Up));
s.receive_control_packet(&pkt(BfdState::Down, REMOTE_DISCR, LOCAL_DISCR))
.await;
let p = recv_packet(&tap).await;
assert_eq!(p.flags.state(), Ok(BfdState::Down));
assert_eq!(p.flags.diag(), Ok(BfdDiagnostic::NeighborDown));
}
// RFC 5880 6.8.3: not Up means Desired Min TX Interval of at least one second; Up advertises the configured value.
#[tokio::test]
async fn desired_min_tx_is_at_least_one_second_unless_up() {
let (mut s, tap, _events) = tapped(peer_cfg(100, 100, 3)).await;
s.receive_control_packet(&pkt(BfdState::Down, REMOTE_DISCR, 0))
.await;
let p = recv_packet(&tap).await;
assert_eq!(p.desired_min_tx, BfdInterval::from_secs(1));
s.receive_control_packet(&pkt(BfdState::Init, REMOTE_DISCR, LOCAL_DISCR))
.await;
let p = recv_packet(&tap).await;
assert_eq!(p.flags.state(), Ok(BfdState::Up));
assert_eq!(p.desired_min_tx, BfdInterval::from_millis(100));
s.receive_control_packet(&pkt(BfdState::Down, REMOTE_DISCR, LOCAL_DISCR))
.await;
let p = recv_packet(&tap).await;
assert_eq!(p.desired_min_tx, BfdInterval::from_secs(1));
}
// RFC 5880 6.8.7: periodic transmission stops while the remote is in Demand mode and Up.
#[tokio::test]
async fn periodic_transmission_ceases_in_remote_demand_mode() {
let (mut s, _tap, _events) = fast_up().await;
assert!(drain_commands(&mut s).await > 0, "no periodic tx at 20ms");
let demand = with_flags(fast(BfdState::Up, LOCAL_DISCR), |f| f.with_demand(true));
s.receive_control_packet(&demand).await;
drain_commands(&mut s).await;
time::sleep(Duration::from_millis(150)).await;
assert_eq!(drain_commands(&mut s).await, 0);
}
// RFC 5880 6.8.7: periodic transmission is suspended while the remote's Required Min RX is zero, and resumes after.
#[tokio::test]
async fn periodic_transmission_resumes_when_remote_min_rx_becomes_nonzero() {
let (mut s, _tap, _events) = fast_up().await;
let mut p = fast(BfdState::Up, LOCAL_DISCR);
p.required_min_rx = BfdInterval::from_micros(0);
s.receive_control_packet(&p).await;
drain_commands(&mut s).await;
assert_eq!(drain_commands(&mut s).await, 0);
s.receive_control_packet(&fast(BfdState::Up, LOCAL_DISCR))
.await;
time::sleep(Duration::from_millis(100)).await;
assert!(drain_commands(&mut s).await > 0);
}
+158
View File
@@ -0,0 +1,158 @@
use super::*;
use BfdState::{AdminDown, Down, Init, Up};
async fn timed_out_after_up() -> BfdSession {
let (mut s, _events) = session_in(Up).await;
s.detection_timeout().await;
assert_eq!(s.state.session_state(), Down);
s
}
#[tokio::test]
async fn remote_min_rx_interval_starts_at_one_microsecond() {
let (s, _events) = session(peer_cfg(300, 300, 3)).await;
assert_eq!(
s.state.remote_min_rx_interval(),
BfdInterval::from_micros(1)
);
}
#[tokio::test]
async fn remote_discriminator_is_zeroed_on_detection_timeout() {
let s = timed_out_after_up().await;
assert_eq!(s.state.remote_discr(), BfdDiscriminator(0));
}
#[tokio::test]
async fn remote_min_rx_interval_is_reset_on_detection_timeout() {
let s = timed_out_after_up().await;
assert_eq!(
s.state.remote_min_rx_interval(),
BfdInterval::from_micros(1)
);
}
#[tokio::test]
async fn periodic_transmission_resumes_when_remote_demand_clears() {
let (mut s, _tap, _events) = fast_up().await;
let demand = with_flags(fast(Up, LOCAL_DISCR), |f| f.with_demand(true));
s.receive_control_packet(&demand).await;
drain_commands(&mut s).await;
s.receive_control_packet(&fast(Up, LOCAL_DISCR)).await;
time::sleep(Duration::from_millis(150)).await;
assert!(drain_commands(&mut s).await > 0);
}
#[tokio::test]
async fn no_periodic_transmission_when_remote_min_rx_is_zero() {
let (mut s, _tap, _events) = fast_up().await;
let mut p = fast(Up, LOCAL_DISCR);
p.required_min_rx = BfdInterval::from_micros(0);
s.receive_control_packet(&p).await;
drain_commands(&mut s).await;
time::sleep(Duration::from_millis(150)).await;
assert_eq!(drain_commands(&mut s).await, 0);
}
#[tokio::test]
async fn reduced_interval_sends_immediately_if_already_elapsed() {
let (tx, mut rx) = mpsc::channel(8);
let sender =
BfdPeriodicSenderHandle::new(BfdSessionHandle { tx }, BfdInterval::from_secs(10), 3);
time::sleep(Duration::from_millis(200)).await;
sender
.tx
.send(PeriodicControlCommand::SetMinInterval(
BfdInterval::from_millis(100),
))
.await
.unwrap();
let got = time::timeout(Duration::from_millis(30), rx.recv()).await;
assert!(matches!(
got,
Ok(Some(SessionControlCommand::TxControlPacket { .. }))
));
}
#[tokio::test]
async fn init_times_out_after_a_session_flap() {
let (dispatcher, mut events) = capture_dispatcher().await;
let handle = BfdSessionHandle::new(
LOCAL,
peer_cfg(20, 20, 3),
BfdDiscriminator(LOCAL_DISCR),
dispatcher,
)
.await
.unwrap();
let send = |state, your| {
let mut p = fast(state, your);
p.flags = p.flags.with_detect_mult(5);
handle.tx.send(SessionControlCommand::RxPacket(p))
};
send(Down, 0).await.unwrap();
send(Init, LOCAL_DISCR).await.unwrap();
send(Down, LOCAL_DISCR).await.unwrap();
send(Down, 0).await.unwrap();
for expected in [Init, Up, Down, Init] {
assert_eq!(next_event(&mut events).await.to_state, expected);
}
let ev = time::timeout(Duration::from_secs(1), events.recv())
.await
.expect("Init never timed out")
.unwrap();
assert_eq!((ev.from_state, ev.to_state), (Init, Down));
handle.tx.send(SessionControlCommand::Quit).await.unwrap();
}
#[tokio::test]
async fn timeout_in_down_keeps_neighbor_down_diagnostic() {
let (mut s, _events) = session_in(Up).await;
s.receive_control_packet(&pkt(Down, REMOTE_DISCR, LOCAL_DISCR))
.await;
assert_eq!(s.state.local_diag(), BfdDiagnostic::NeighborDown);
assert!(s.detect_deadline.is_none());
s.detection_timeout().await;
assert_eq!(s.state.local_diag(), BfdDiagnostic::NeighborDown);
}
#[tokio::test]
async fn poll_from_admin_down_remote_is_answered() {
let (mut s, tap, _events) = tapped_in(Down).await;
let poll = with_flags(pkt(AdminDown, REMOTE_DISCR, LOCAL_DISCR), |f| {
f.with_poll(true)
});
s.receive_control_packet(&poll).await;
let sent = drain(&tap).await;
assert_eq!(sent.len(), 1);
assert!(sent[0].flags.final_());
}
#[tokio::test]
async fn simple_password_auth_len_must_match_password_length() {
let pw = b"0123456789abcdef";
let (mut s, _tap, _events) = keyed_session(password_auth(1, pw)).await;
let mut raw = signed(password_auth(1, pw), Down, REMOTE_DISCR, 0)
.serialize()
.unwrap();
raw[3] += 1;
raw[25] += 1;
raw.push(b'X');
let p = BfdPacket::parse(&raw).unwrap().1;
assert!(!accepted(&mut s, &p).await);
}
#[tokio::test]
async fn keyed_auth_reserved_byte_is_ignored_on_receipt() {
let (mut s, _tap, _events) = keyed_session(md5_auth(false, 1, 0)).await;
let mut p = with_flags(pkt(Down, REMOTE_DISCR, 0), |f| {
f.with_auth_present(true).with_length(48)
});
p.auth = Some(md5_auth(false, 1, 5));
let mut raw = p.serialize().unwrap();
raw[27] = 0xab;
let digest = Md5::digest(&raw);
raw[32..48].copy_from_slice(digest.as_slice());
let p = BfdPacket::parse(&raw).unwrap().1;
assert!(accepted(&mut s, &p).await);
}
+588
View File
@@ -0,0 +1,588 @@
//! Daemon configuration: a single YAML file, loaded and validated.
//!
//! [`Config`] is the file's model. [`Config::resolve`] validates it and produces a [`ResolvedConfig`] with all per-peer
//! inheritance applied, which is what the daemon runs from.
use std::{
collections::HashSet,
error::Error,
fmt, fs, io,
net::IpAddr,
path::{Path, PathBuf},
time::Duration,
};
use serde::Deserialize;
use crate::bfd::{BfdAuth, BfdAuthKeyedMD5, BfdAuthKeyedSHA1, BfdAuthSimplePassword, BfdInterval};
pub const DEFAULT_CONFIG_PATH: &str = "/etc/rust-bfd/config.yaml";
pub const DEFAULT_HOOKS_DIR: &str = "/etc/rust-bfd/hooks.d";
fn default_true() -> bool {
true
}
#[derive(Debug)]
pub enum ConfigError {
Io {
path: PathBuf,
source: io::Error,
},
Parse {
path: PathBuf,
source: serde_yaml_ng::Error,
},
Invalid(String),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => {
write!(f, "cannot read config file `{}`: {source}", path.display())
}
Self::Parse { path, source } => {
write!(f, "invalid config file `{}`: {source}", path.display())
}
Self::Invalid(message) => write!(f, "invalid configuration: {message}"),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Parse { source, .. } => Some(source),
Self::Invalid(_) => None,
}
}
}
/// Timer and multiplier settings inherited by every peer that does not override them.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Defaults {
#[serde(with = "humantime_serde")]
pub desired_min_tx: Duration,
#[serde(with = "humantime_serde")]
pub required_min_rx: Duration,
pub detect_mult: u8,
}
impl Default for Defaults {
fn default() -> Self {
Self {
desired_min_tx: Duration::from_millis(300),
required_min_rx: Duration::from_millis(300),
detect_mult: 3,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PasswordAuthConfig {
pub key_id: u8,
#[serde(with = "serde_bytes")]
// The password is a binary string, and MUST be 1 to 16 bytes in length (checked in `Config::resolve`).
pub password: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Md5AuthConfig {
pub key_id: u8,
#[serde(with = "serde_bytes")]
// The key is given verbatim (not derived) and must be exactly 16 bytes
pub key: [u8; 16],
#[serde(default = "default_true")]
pub meticulous: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Sha1AuthConfig {
pub key_id: u8,
#[serde(with = "serde_bytes")]
// The key is given verbatim (not derived) and must be exactly 20 bytes
pub key: [u8; 20],
#[serde(default = "default_true")]
pub meticulous: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields, tag = "type", rename_all = "lowercase")]
pub enum AuthConfig {
Password(PasswordAuthConfig),
Md5(Md5AuthConfig),
Sha1(Sha1AuthConfig),
}
impl From<AuthConfig> for BfdAuth {
fn from(value: AuthConfig) -> Self {
match value {
AuthConfig::Password(ac) => BfdAuth::SimplePassword(BfdAuthSimplePassword {
key_id: ac.key_id,
password: ac.password,
}),
AuthConfig::Md5(ac) => BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
key_id: ac.key_id,
reserved: 0,
meticulous: ac.meticulous,
digest: ac.key,
seq: 0, // set during signing
}),
AuthConfig::Sha1(ac) => BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
key_id: ac.key_id,
reserved: 0,
meticulous: ac.meticulous,
digest: ac.key,
seq: 0, // set during signing
}),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PeerConfig {
pub address: IpAddr,
/// Local address the session runs from: the source of its control packets, and the address the daemon listens
/// on for the peer's. Must be of the same address family as `address`.
pub local: IpAddr,
/// Bind the session's sockets to this interface (`SO_BINDTODEVICE`). Required when `local` or `address` is an
/// IPv6 link-local address.
#[serde(default)]
pub interface: Option<String>,
#[serde(default, with = "humantime_serde")]
pub desired_min_tx: Option<Duration>,
#[serde(default, with = "humantime_serde")]
pub required_min_rx: Option<Duration>,
#[serde(default)]
pub detect_mult: Option<u8>,
#[serde(default)]
pub auth: Option<AuthConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// Directory of executable state-change hook scripts.
pub hooks_dir: PathBuf,
pub defaults: Defaults,
pub peers: Vec<PeerConfig>,
}
impl Default for Config {
fn default() -> Self {
Self {
hooks_dir: PathBuf::from(DEFAULT_HOOKS_DIR),
defaults: Defaults::default(),
peers: Vec::new(),
}
}
}
impl Config {
pub fn from_yaml(yaml: &str) -> Result<Self, serde_yaml_ng::Error> {
// An empty (or comment-only) document is a null value, which means "all defaults".
Ok(serde_yaml_ng::from_str::<Option<Self>>(yaml)?.unwrap_or_default())
}
/// Load the config file. An explicit `path` must exist; with `None`, [`DEFAULT_CONFIG_PATH`] is used if present and
/// built-in defaults otherwise.
pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
let optional = path.is_none();
let path = path.unwrap_or(Path::new(DEFAULT_CONFIG_PATH));
let to_owned = || path.to_owned();
match fs::read_to_string(path) {
Ok(yaml) => Self::from_yaml(&yaml).map_err(|source| ConfigError::Parse {
path: to_owned(),
source,
}),
Err(e) if optional && e.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
Err(source) => Err(ConfigError::Io {
path: to_owned(),
source,
}),
}
}
/// Validate and apply defaults to each peer.
pub fn resolve(self) -> Result<ResolvedConfig, ConfigError> {
let invalid = |message: String| ConfigError::Invalid(message);
let mut seen = HashSet::new();
let peers = self
.peers
.into_iter()
.map(|peer| {
if !seen.insert((peer.local, peer.interface.clone(), peer.address)) {
return Err(invalid(format!(
"duplicate peer {} with local address {}",
peer.address, peer.local
)));
}
if let Some(name) = &peer.interface {
validate_interface_name(name).map_err(|why| {
invalid(format!("peer {} interface {name:?} {why}", peer.address))
})?;
} else if is_link_local_v6(peer.local) || is_link_local_v6(peer.address) {
return Err(invalid(format!(
"peer {} uses an IPv6 link-local address and requires an interface",
peer.address
)));
}
if peer.local.is_ipv4() != peer.address.is_ipv4() {
return Err(invalid(format!(
"peer {} has local address {} of a different address family",
peer.address, peer.local
)));
}
let what = |field: &str| format!("peer {} {field}", peer.address);
if let Some(AuthConfig::Password(p)) = &peer.auth {
if !(1..=16).contains(&p.password.len()) {
return Err(invalid(format!(
"{} must be 1 to 16 bytes",
what("auth password")
)));
}
}
let detect_mult = peer.detect_mult.unwrap_or(self.defaults.detect_mult);
if detect_mult == 0 {
return Err(invalid(format!(
"{} must be at least 1",
what("detect_mult")
)));
}
Ok(ResolvedPeer {
address: peer.address,
local: peer.local,
interface: peer.interface,
desired_min_tx: to_interval(
peer.desired_min_tx.unwrap_or(self.defaults.desired_min_tx),
&what("desired_min_tx"),
)?,
required_min_rx: to_interval(
peer.required_min_rx
.unwrap_or(self.defaults.required_min_rx),
&what("required_min_rx"),
)?,
detect_mult,
auth: peer.auth,
})
})
.collect::<Result<Vec<_>, _>>()?;
// Validate the defaults even when no peer uses them, so that a bad value is not latent.
let d = &self.defaults;
to_interval(d.desired_min_tx, "defaults.desired_min_tx")?;
to_interval(d.required_min_rx, "defaults.required_min_rx")?;
if d.detect_mult == 0 {
return Err(invalid("defaults.detect_mult must be at least 1".into()));
}
Ok(ResolvedConfig {
hooks_dir: self.hooks_dir,
peers,
})
}
}
fn is_link_local_v6(addr: IpAddr) -> bool {
crate::is_ipv6_link_local(&addr)
}
/// Linux limits interface names to IFNAMSIZ - 1 = 15 bytes, and `/` and NUL cannot appear in them.
fn validate_interface_name(name: &str) -> Result<(), &'static str> {
if name.is_empty() {
Err("must not be empty")
} else if name.len() > 15 {
Err("must be at most 15 bytes")
} else if name.contains(['/', '\0']) {
Err("must not contain '/' or NUL")
} else {
Ok(())
}
}
/// Zero is rejected for both intervals: a zero Required Min RX Interval is legal in RFC 5880 (it asks the peer to
/// stop sending periodic packets) but is not supported here.
fn to_interval(value: Duration, what: &str) -> Result<BfdInterval, ConfigError> {
let micros = value.as_micros();
if micros == 0 {
return Err(ConfigError::Invalid(format!(
"{what} must be greater than zero"
)));
}
u32::try_from(micros)
.map(BfdInterval::from_micros)
.map_err(|_| {
ConfigError::Invalid(format!(
"{what} of {} is too large (maximum is {} microseconds)",
humantime::format_duration(value),
u32::MAX
))
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedConfig {
pub hooks_dir: PathBuf,
pub peers: Vec<ResolvedPeer>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPeer {
pub address: IpAddr,
pub local: IpAddr,
pub interface: Option<String>,
pub desired_min_tx: BfdInterval,
pub required_min_rx: BfdInterval,
pub detect_mult: u8,
pub auth: Option<AuthConfig>,
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
enum Expect {
Ok,
Err,
ErrContaining(&'static str),
}
fn check(result: Result<ResolvedConfig, ConfigError>, expect: Expect) {
match expect {
Expect::Ok => assert!(result.is_ok()),
Expect::Err => assert!(result.is_err()),
Expect::ErrContaining(s) => assert!(result.unwrap_err().to_string().contains(s)),
}
}
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
fn peer(address: &str, local: &str) -> PeerConfig {
PeerConfig {
address: ip(address),
local: ip(local),
interface: None,
desired_min_tx: None,
required_min_rx: None,
detect_mult: None,
auth: None,
}
}
const FULL: &str = "
hooks_dir: /tmp/hooks
defaults:
desired_min_tx: 500ms
required_min_rx: 250ms
detect_mult: 5
peers:
- address: 192.0.2.2
local: 192.0.2.1
- address: 192.0.2.3
local: 192.0.2.1
desired_min_tx: 1s
detect_mult: 4
";
#[test]
fn parses_full_config() {
let config = Config::from_yaml(FULL).unwrap();
assert_eq!(config.peers[0].local, ip("192.0.2.1"));
assert_eq!(config.hooks_dir, PathBuf::from("/tmp/hooks"));
assert_eq!(config.defaults.desired_min_tx, Duration::from_millis(500));
assert_eq!(config.peers.len(), 2);
assert_eq!(config.peers[1].desired_min_tx, Some(Duration::from_secs(1)));
assert_eq!(config.peers[0].detect_mult, None);
}
#[rstest]
#[case::empty("")]
#[case::comment_only("# nothing\n")]
fn empty_and_comment_only_documents_are_defaults(#[case] yaml: &str) {
assert_eq!(Config::from_yaml(yaml).unwrap(), Config::default());
}
#[test]
fn partial_defaults_keep_remaining_builtin_values() {
let config = Config::from_yaml("defaults:\n detect_mult: 7\n").unwrap();
assert_eq!(config.defaults.detect_mult, 7);
assert_eq!(config.defaults.desired_min_tx, Duration::from_millis(300));
}
#[test]
fn peers_inherit_defaults_and_override() {
let resolved = Config::from_yaml(FULL).unwrap().resolve().unwrap();
let (a, b) = (&resolved.peers[0], &resolved.peers[1]);
assert_eq!(a.desired_min_tx, BfdInterval::from_millis(500));
assert_eq!(a.required_min_rx, BfdInterval::from_millis(250));
assert_eq!(a.detect_mult, 5);
assert_eq!(b.desired_min_tx, BfdInterval::from_secs(1));
assert_eq!(b.required_min_rx, BfdInterval::from_millis(250));
assert_eq!(b.detect_mult, 4);
}
#[test]
fn peers_may_use_different_local_addresses() {
let config = Config::from_yaml(
"peers:
- {address: 192.0.2.2, local: 192.0.2.1}
- {address: 2001:db8::2, local: '2001:db8::1'}
",
)
.unwrap();
assert_eq!(config.peers[1].local, ip("2001:db8::1"));
}
#[rstest]
#[case::misspelled_top_level_field("bnid: 192.0.2.1")]
#[case::removed_top_level_field("bind: 192.0.2.1")]
#[case::unknown_defaults_field("defaults:\n desired_min_txx: 1s")]
#[case::unknown_peer_field(
"peers:\n - address: 192.0.2.2\n local: 192.0.2.1\n color: red"
)]
#[case::invalid_local_address("peers:\n - address: 192.0.2.2\n local: not-an-ip")]
#[case::invalid_interval("defaults:\n desired_min_tx: soon")]
#[case::peer_without_address("peers:\n - detect_mult: 3")]
#[case::peer_without_local("peers:\n - address: 192.0.2.2")]
fn rejects_unknown_fields_and_bad_values(#[case] yaml: &str) {
assert!(Config::from_yaml(yaml).is_err());
}
#[test]
fn dist_config_is_valid() {
let config = Config::from_yaml(include_str!("../config.yaml.dist")).unwrap();
assert_eq!(config.defaults, Defaults::default());
assert_eq!(config.hooks_dir, PathBuf::from(DEFAULT_HOOKS_DIR));
let resolved = config.resolve().unwrap();
assert_eq!(resolved.peers.len(), 1);
}
#[rstest]
#[case::valid_base(|_: &mut Config| {}, Expect::Ok)]
#[case::duplicate_peer(
|c: &mut Config| c.peers.push(peer("192.0.2.2", "192.0.2.1")),
Expect::ErrContaining("duplicate peer")
)]
#[case::same_peer_from_different_local_addresses(
|c: &mut Config| c.peers.push(peer("192.0.2.2", "192.0.2.9")),
Expect::Ok
)]
#[case::address_family_mismatch(
|c: &mut Config| c.peers[0].local = ip("2001:db8::1"),
Expect::ErrContaining("address family")
)]
#[case::second_peer_in_other_family(
|c: &mut Config| c.peers.push(peer("2001:db8::2", "2001:db8::1")),
Expect::Ok
)]
#[case::zero_peer_detect_mult(|c: &mut Config| c.peers[0].detect_mult = Some(0), Expect::Err)]
#[case::zero_peer_desired_min_tx(
|c: &mut Config| c.peers[0].desired_min_tx = Some(Duration::ZERO),
Expect::Err
)]
#[case::too_large_peer_required_min_rx(
|c: &mut Config| c.peers[0].required_min_rx = Some(Duration::from_secs(5000)),
Expect::ErrContaining("too large")
)]
#[case::zero_default_detect_mult(|c: &mut Config| c.defaults.detect_mult = 0, Expect::Err)]
fn resolve_validation(#[case] mutate: fn(&mut Config), #[case] expect: Expect) {
let mut c =
Config::from_yaml("peers:\n - {address: 192.0.2.2, local: 192.0.2.1}\n").unwrap();
mutate(&mut c);
check(c.resolve(), expect);
}
#[rstest]
#[case::v4_with_interface("192.0.2.2", "192.0.2.1", Some("eth1"), Expect::Ok)]
#[case::link_local_with_interface("fe80::2", "fe80::1", Some("eth1"), Expect::Ok)]
#[case::link_local_without_interface(
"fe80::2",
"fe80::1",
None,
Expect::ErrContaining("requires an interface")
)]
#[case::link_local_peer_global_local("fe80::2", "2001:db8::1", None, Expect::Err)]
#[case::global_peer_link_local_local("2001:db8::2", "fe80::1", None, Expect::Err)]
#[case::global_v6_without_interface("2001:db8::2", "2001:db8::1", None, Expect::Ok)]
#[case::empty_interface_name("192.0.2.2", "192.0.2.1", Some(""), Expect::Err)]
#[case::interface_name_with_slash("192.0.2.2", "192.0.2.1", Some("a/b"), Expect::Err)]
#[case::interface_name_too_long(
"192.0.2.2",
"192.0.2.1",
Some("0123456789abcdef"),
Expect::Err
)]
#[case::interface_name_max_length(
"192.0.2.2",
"192.0.2.1",
Some("0123456789abcde"),
Expect::Ok
)]
fn interface_validation(
#[case] address: &str,
#[case] local: &str,
#[case] interface: Option<&str>,
#[case] expect: Expect,
) {
let mut c = Config::from_yaml("").unwrap();
c.peers.push(PeerConfig {
interface: interface.map(String::from),
..peer(address, local)
});
check(c.resolve(), expect);
}
#[test]
fn same_address_on_two_interfaces_is_two_sessions() {
let mut c = Config::from_yaml("").unwrap();
for iface in ["eth1", "eth2"] {
c.peers.push(PeerConfig {
interface: Some(iface.into()),
..peer("fe80::2", "fe80::1")
});
}
assert!(c.clone().resolve().is_ok());
c.peers[1].interface = Some("eth1".into());
assert!(c.resolve().unwrap_err().to_string().contains("duplicate"));
}
#[rstest]
#[case::empty(b"", Expect::Err)]
#[case::one_byte(b"a", Expect::Ok)]
#[case::sixteen_bytes(&[b'a'; 16], Expect::Ok)]
#[case::seventeen_bytes(&[b'a'; 17], Expect::ErrContaining("1 to 16 bytes"))]
fn password_length_is_limited_to_16_bytes(#[case] password: &[u8], #[case] expect: Expect) {
let mut c = Config::from_yaml("").unwrap();
c.peers.push(PeerConfig {
auth: Some(AuthConfig::Password(PasswordAuthConfig {
key_id: 1,
password: password.to_vec(),
})),
..peer("192.0.2.2", "192.0.2.1")
});
check(c.resolve(), expect);
}
#[test]
fn zero_peers_is_valid() {
let config = Config::from_yaml("").unwrap();
assert!(config.resolve().unwrap().peers.is_empty());
}
#[test]
fn load_requires_explicit_path_to_exist() {
let err = Config::load(Some(Path::new("/nonexistent/rust-bfd.yaml"))).unwrap_err();
assert!(matches!(err, ConfigError::Io { .. }));
}
}
+1
View File
@@ -0,0 +1 @@
+243 -15
View File
@@ -1,14 +1,13 @@
use core::{fmt, str};
use core::fmt;
use std::{
ffi::{OsStr, OsString},
net::IpAddr,
path::PathBuf,
process::ExitStatus,
};
use itertools::Itertools;
use log::{debug, info, warn};
use nix::unistd::{self, eaccess};
use nix::unistd;
use tokio::{
fs, process,
sync::mpsc,
@@ -28,6 +27,7 @@ pub struct StateChangeEvent {
pub remote_discr: BfdDiscriminator,
pub local_ip: IpAddr,
pub remote_ip: IpAddr,
pub interface: Option<String>,
pub from_state: BfdState,
pub to_state: BfdState,
}
@@ -53,11 +53,20 @@ impl EventMessageSink for ScriptHookSink {
}
}
impl Default for ScriptHookSink {
fn default() -> Self {
Self::new()
}
}
impl ScriptHookSink {
pub fn new() -> Self {
Self::with_script_dir("/etc/rust-bfd/hooks.d/")
}
pub fn with_script_dir(script_dir: impl Into<PathBuf>) -> Self {
let (tx_channel, rx_channel) = mpsc::channel(16);
Self {
script_dir: "/etc/rust-bfd/hooks.d/".into(),
script_dir: script_dir.into(),
tx_channel,
rx_channel,
}
@@ -83,17 +92,11 @@ impl ScriptHookSink {
output.status
);
if !output.status.success() {
if output.stdout.len() > 0 {
warn!(
" stdout: \n{}",
str::from_utf8(output.stdout.as_slice()).unwrap()
);
if !output.stdout.is_empty() {
warn!(" stdout: \n{}", String::from_utf8_lossy(&output.stdout));
}
if output.stderr.len() > 0 {
warn!(
" stderr: \n{}",
str::from_utf8(output.stderr.as_slice()).unwrap()
);
if !output.stderr.is_empty() {
warn!(" stderr: \n{}", String::from_utf8_lossy(&output.stderr));
}
}
}
@@ -133,7 +136,7 @@ impl ScriptHookSink {
.map_or(OsString::new(), |file| file.to_owned())
});
if scripts.len() > 0 {
if !scripts.is_empty() {
// Build context
let mut args = Vec::<&OsStr>::new();
let mut env = Vec::<(&OsStr, &OsStr)>::new();
@@ -142,6 +145,7 @@ impl ScriptHookSink {
let local_ip_str = OsString::from(event.local_ip.to_string());
let remote_discr_str = OsString::from(event.remote_discr.to_string());
let local_discr_str = OsString::from(event.local_discr.to_string());
let interface_str = OsString::from(event.interface.as_deref().unwrap_or_default());
args.push(event.to_state.into());
args.push(&remote_ip_str);
@@ -149,6 +153,7 @@ impl ScriptHookSink {
env.push((OsStr::new("BFD_STATE"), event.to_state.into()));
env.push((OsStr::new("BFD_LOCAL_ADDR"), &local_ip_str));
env.push((OsStr::new("BFD_PEER_ADDR"), &remote_ip_str));
env.push((OsStr::new("BFD_INTERFACE"), &interface_str));
env.push((OsStr::new("BFD_LOCAL_DISCRIMINATOR"), &local_discr_str));
env.push((OsStr::new("BFD_PEER_DISCRIMINATOR"), &remote_discr_str));
for script in scripts {
@@ -169,3 +174,226 @@ impl ScriptHookSink {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
use std::{
fs::{self as stdfs, Permissions},
net::{Ipv4Addr, Ipv6Addr},
os::unix::fs::PermissionsExt,
sync::atomic::{AtomicU32, Ordering},
time::Duration,
};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new() -> Self {
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("rust-bfd-hooks-{}-{}", std::process::id(), n));
stdfs::create_dir_all(path.join("hooks")).unwrap();
Self(path)
}
fn hooks(&self) -> PathBuf {
self.0.join("hooks")
}
fn out(&self) -> PathBuf {
self.0.join("out")
}
fn script(&self, name: &str, mode: u32, body: &str) {
let path = self.hooks().join(name);
stdfs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
stdfs::set_permissions(&path, Permissions::from_mode(mode)).unwrap();
}
fn append_script(&self, name: &str, mode: u32, line: &str) {
self.script(
name,
mode,
&format!("echo \"{line}\" >> {}", self.out().display()),
);
}
fn output(&self) -> Vec<String> {
stdfs::read_to_string(self.out())
.map(|s| s.lines().map(str::to_owned).collect())
.unwrap_or_default()
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = stdfs::remove_dir_all(&self.0);
}
}
fn event(local: IpAddr, remote: IpAddr, from: BfdState, to: BfdState) -> EventMessage {
EventMessage::StateChange(StateChangeEvent {
local_discr: BfdDiscriminator(11),
remote_discr: BfdDiscriminator(22),
local_ip: local,
remote_ip: remote,
interface: None,
from_state: from,
to_state: to,
})
}
fn v4_event() -> EventMessage {
event(
Ipv4Addr::new(192, 0, 2, 1).into(),
Ipv4Addr::new(192, 0, 2, 2).into(),
BfdState::Init,
BfdState::Up,
)
}
const ENV_LINE: &str = "$1|$2|$BFD_STATE|$BFD_LAST_STATE|$BFD_LOCAL_ADDR|$BFD_PEER_ADDR|$BFD_LOCAL_DISCRIMINATOR|$BFD_PEER_DISCRIMINATOR";
#[rstest]
#[case::v4(
Ipv4Addr::new(192, 0, 2, 1).into(),
Ipv4Addr::new(192, 0, 2, 2).into(),
BfdState::Init,
BfdState::Up,
"up|192.0.2.2|up|init|192.0.2.1|192.0.2.2|11|22"
)]
#[case::v6(
Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).into(),
Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2).into(),
BfdState::Up,
BfdState::Down,
"down|2001:db8::2|down|up|2001:db8::1|2001:db8::2|11|22"
)]
#[tokio::test]
async fn passes_args_and_environment(
#[case] local: IpAddr,
#[case] remote: IpAddr,
#[case] from: BfdState,
#[case] to: BfdState,
#[case] expected: &str,
) {
let t = TempDir::new();
t.append_script("10-env", 0o755, ENV_LINE);
ScriptHookSink::with_script_dir(t.hooks())
.handle_event(&event(local, remote, from, to))
.await;
assert_eq!(t.output(), [expected]);
}
#[tokio::test]
async fn passes_interface() {
let t = TempDir::new();
t.append_script("10-env", 0o755, "${BFD_INTERFACE-unset}|$BFD_PEER_ADDR");
let sink = ScriptHookSink::with_script_dir(t.hooks());
sink.handle_event(&v4_event()).await;
sink.handle_event(&EventMessage::StateChange(StateChangeEvent {
local_discr: BfdDiscriminator(11),
remote_discr: BfdDiscriminator(22),
local_ip: "fe80::1".parse().unwrap(),
remote_ip: "fe80::2".parse().unwrap(),
interface: Some("eth1".to_owned()),
from_state: BfdState::Init,
to_state: BfdState::Up,
}))
.await;
assert_eq!(t.output(), ["|192.0.2.2", "eth1|fe80::2"]);
}
#[tokio::test]
async fn environment_is_cleared() {
let t = TempDir::new();
std::env::set_var("RUST_BFD_TEST_LEAK", "leaked");
t.append_script(
"10-env",
0o755,
"${RUST_BFD_TEST_LEAK:-unset}|${HOME:-unset}",
);
ScriptHookSink::with_script_dir(t.hooks())
.handle_event(&v4_event())
.await;
assert_eq!(t.output(), ["unset|unset"]);
}
#[tokio::test]
async fn runs_scripts_in_lexicographic_order() {
let t = TempDir::new();
t.append_script("20-b", 0o755, "b");
t.append_script("30-c", 0o755, "c");
t.append_script("10-a", 0o755, "a");
ScriptHookSink::with_script_dir(t.hooks())
.handle_event(&v4_event())
.await;
assert_eq!(t.output(), ["a", "b", "c"]);
}
#[tokio::test]
async fn skips_non_executable_files_and_directories() {
let t = TempDir::new();
t.append_script("10-run", 0o755, "run");
t.append_script("20-noexec", 0o644, "noexec");
let dir = t.hooks().join("30-dir");
stdfs::create_dir(&dir).unwrap();
stdfs::set_permissions(&dir, Permissions::from_mode(0o755)).unwrap();
ScriptHookSink::with_script_dir(t.hooks())
.handle_event(&v4_event())
.await;
assert_eq!(t.output(), ["run"]);
}
#[tokio::test]
async fn failing_script_does_not_stop_later_scripts() {
let t = TempDir::new();
t.script(
"10-fail",
0o755,
"printf '\\377\\376'; printf '\\377' >&2; exit 3",
);
t.append_script("20-ok", 0o755, "ok");
ScriptHookSink::with_script_dir(t.hooks())
.handle_event(&v4_event())
.await;
assert_eq!(t.output(), ["ok"]);
}
#[rstest]
#[case::missing_dir("nope")]
#[case::empty_dir("hooks")]
#[tokio::test]
async fn missing_or_empty_script_dir_is_a_noop(#[case] subdir: &str) {
let t = TempDir::new();
ScriptHookSink::with_script_dir(t.0.join(subdir))
.handle_event(&v4_event())
.await;
assert!(t.output().is_empty());
}
#[tokio::test]
async fn events_sent_over_channel_run_hooks() {
let t = TempDir::new();
t.append_script("10-env", 0o755, ENV_LINE);
let sink = ScriptHookSink::with_script_dir(t.hooks());
let tx = sink.channel();
let handle = Box::new(sink).run();
tx.send(v4_event()).await.unwrap();
tx.send(event(
Ipv4Addr::new(192, 0, 2, 1).into(),
Ipv4Addr::new(192, 0, 2, 2).into(),
BfdState::Up,
BfdState::Down,
))
.await
.unwrap();
for _ in 0..100 {
if t.output().len() >= 2 {
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
handle.abort();
let out = t.output();
assert_eq!(out.len(), 2);
assert!(out[0].starts_with("up|") && out[1].starts_with("down|"));
}
}
+600 -7
View File
@@ -1,19 +1,203 @@
pub mod bfd;
pub mod config;
pub mod control;
pub mod events;
use std::{
ffi::OsString,
fmt::{self, Display},
net::IpAddr,
time::Instant,
io,
net::{IpAddr, SocketAddr, SocketAddrV6},
os::fd::AsRawFd,
sync::atomic::{AtomicU64, Ordering},
time::{Duration, Instant},
};
use log::debug;
use nix::sys::socket::{getsockopt, setsockopt, sockopt};
use nix::{
net::if_::if_nametoindex,
sys::socket::{
bind, getsockopt, setsockopt, socket, sockopt, AddressFamily, SockFlag, SockProtocol,
SockType, SockaddrIn, SockaddrIn6,
},
};
use tokio::net::UdpSocket;
use crate::bfd::*;
/// A snapshot of the packet count and inter-packet interval statistics for one direction of a session.
#[derive(Debug, Clone, Copy, Default)]
pub struct IntervalStats {
count: u64,
min: Option<Duration>,
max: Option<Duration>,
mean: Option<Duration>,
}
impl IntervalStats {
pub fn count(&self) -> u64 {
self.count
}
pub fn min(&self) -> Option<Duration> {
self.min
}
pub fn max(&self) -> Option<Duration> {
self.max
}
pub fn mean(&self) -> Option<Duration> {
self.mean
}
}
impl Display for IntervalStats {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ms = |d: Option<Duration>| {
d.map_or("-".to_string(), |d| {
format!("{:.0}", d.as_secs_f64() * 1000.0)
})
};
write!(
f,
"{} pkts, interval min/avg/max {}/{}/{} ms",
self.count,
ms(self.min),
ms(self.mean),
ms(self.max)
)
}
}
/// An optional `Instant` that can be shared between threads, stored as nanoseconds since its construction.
/// Instants earlier than the construction time are clamped to it.
#[derive(Debug)]
pub struct AtomicInstant {
epoch: Instant,
nanos: AtomicU64,
}
impl AtomicInstant {
const NONE: u64 = u64::MAX;
pub fn new() -> Self {
Self {
epoch: Instant::now(),
nanos: AtomicU64::new(Self::NONE),
}
}
pub fn load(&self) -> Option<Instant> {
match self.nanos.load(Ordering::Relaxed) {
Self::NONE => None,
n => Some(self.epoch + Duration::from_nanos(n)),
}
}
pub fn store(&self, value: Instant) {
self.swap(value);
}
pub fn swap(&self, value: Instant) -> Option<Instant> {
let n = u64::try_from(value.saturating_duration_since(self.epoch).as_nanos())
.unwrap_or(Self::NONE - 1)
.min(Self::NONE - 1);
match self.nanos.swap(n, Ordering::Relaxed) {
Self::NONE => None,
prev => Some(self.epoch + Duration::from_nanos(prev)),
}
}
pub fn clear(&self) {
self.nanos.store(Self::NONE, Ordering::Relaxed);
}
}
impl Default for AtomicInstant {
fn default() -> Self {
Self::new()
}
}
/// Lock-free accumulator for packet counts and inter-packet intervals. Updates are not atomic as a group, so it
/// is intended for a single writer; a concurrent reader may observe a mix of old and new values.
#[derive(Debug)]
pub struct AtomicIntervalStats {
count: AtomicU64,
last: AtomicInstant,
min_nanos: AtomicU64,
max_nanos: AtomicU64,
total_nanos: AtomicU64,
}
impl AtomicIntervalStats {
pub fn new() -> Self {
Self {
count: AtomicU64::new(0),
last: AtomicInstant::new(),
min_nanos: AtomicU64::new(u64::MAX),
max_nanos: AtomicU64::new(0),
total_nanos: AtomicU64::new(0),
}
}
pub fn record(&self, now: Instant) {
self.count.fetch_add(1, Ordering::Relaxed);
if let Some(prev) = self.last.swap(now) {
let nanos =
u64::try_from(now.saturating_duration_since(prev).as_nanos()).unwrap_or(u64::MAX);
self.min_nanos.fetch_min(nanos, Ordering::Relaxed);
self.max_nanos.fetch_max(nanos, Ordering::Relaxed);
self.total_nanos.fetch_add(nanos, Ordering::Relaxed);
}
}
pub fn reset(&self) {
self.count.store(0, Ordering::Relaxed);
self.last.clear();
self.min_nanos.store(u64::MAX, Ordering::Relaxed);
self.max_nanos.store(0, Ordering::Relaxed);
self.total_nanos.store(0, Ordering::Relaxed);
}
pub fn snapshot(&self) -> IntervalStats {
let count = self.count.load(Ordering::Relaxed);
let intervals = count.saturating_sub(1);
if intervals == 0 {
return IntervalStats {
count,
..Default::default()
};
}
let total = self.total_nanos.load(Ordering::Relaxed);
IntervalStats {
count,
min: Some(Duration::from_nanos(self.min_nanos.load(Ordering::Relaxed))),
max: Some(Duration::from_nanos(self.max_nanos.load(Ordering::Relaxed))),
mean: Some(Duration::from_nanos(total / intervals)),
}
}
}
impl Default for AtomicIntervalStats {
fn default() -> Self {
Self::new()
}
}
fn fmt_ago(t: Option<Instant>) -> String {
t.map_or("never".to_string(), |t| {
format!("{}s ago", t.elapsed().as_secs())
})
}
/// A snapshot of a session's authentication state. Sequence numbers are `None` when not applicable or not yet known.
#[derive(Debug, Clone, Copy)]
pub struct AuthStats {
pub auth_type: BfdAuthType,
pub key_id: u8,
pub rcv_seq: Option<u32>,
pub xmit_seq: Option<u32>,
}
impl Display for AuthStats {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let seq = |s: Option<u32>| s.map_or("-".to_string(), |s| s.to_string());
write!(
f,
"{} KeyId:{} RcvSeq:{} XmitSeq:{}",
self.auth_type,
self.key_id,
seq(self.rcv_seq),
seq(self.xmit_seq)
)
}
}
#[derive(Debug)]
pub struct BfdSessionStats {
pub local_ip: IpAddr,
@@ -22,13 +206,24 @@ pub struct BfdSessionStats {
pub remote_discr: BfdDiscriminator,
pub state: BfdState,
pub last_diag: BfdDiagnostic,
pub control_packets_rx: u64,
pub control_packets_tx: u64,
/// Valid (not discarded) packet statistics since the session last entered Up
pub rx: IntervalStats,
/// Every packet received over the life of the session, including discarded ones
pub rx_received: u64,
pub tx: IntervalStats,
pub last_up: Option<Instant>,
pub last_down: Option<Instant>,
pub last_change: Instant,
pub detect_time: BfdInterval,
pub base_interval: BfdInterval,
/// `None` when the session does not use authentication
pub auth: Option<AuthStats>,
}
impl BfdSessionStats {
pub fn with_auth(mut self, auth: Option<AuthStats>) -> Self {
self.auth = auth;
self
}
pub fn with_base_interval(mut self, base_interval: BfdInterval) -> Self {
self.base_interval = base_interval;
self
@@ -39,9 +234,12 @@ impl Display for BfdSessionStats {
writeln!(
f,
"{:<20} {:<9} {:>6} {:>6}",
self.remote_ip, self.state, self.control_packets_rx, self.control_packets_tx
self.remote_ip,
self.state,
self.rx.count(),
self.tx.count()
)?;
write!(
writeln!(
f,
" LocalDiscr:{} RemoteDiscr:{} DetectTime: {} TxTime: {} Diag:{} Last: {}s",
self.local_discr,
@@ -50,10 +248,122 @@ impl Display for BfdSessionStats {
self.base_interval,
self.last_diag,
Instant::now().duration_since(self.last_change).as_secs()
)?;
writeln!(f, " Rx: {}", self.rx)?;
writeln!(f, " Tx: {}", self.tx)?;
match &self.auth {
Some(auth) => writeln!(f, " Auth: {auth}")?,
None => writeln!(f, " Auth: none")?,
}
write!(
f,
" Last Up: {} Last Down: {}",
fmt_ago(self.last_up),
fmt_ago(self.last_down)
)
}
}
pub fn is_ipv6_link_local(addr: &IpAddr) -> bool {
matches!(addr, IpAddr::V6(a) if a.segments()[0] & 0xffc0 == 0xfe80)
}
/// Bind a UDP socket, optionally to a single interface (`SO_BINDTODEVICE`). The device is set before `bind` so that
/// sockets on different interfaces can share an address and port. Must be called from within a Tokio runtime.
pub fn bind_udp(addr: SocketAddr, interface: Option<&str>) -> io::Result<UdpSocket> {
let family = match addr {
SocketAddr::V4(_) => AddressFamily::Inet,
SocketAddr::V6(_) => AddressFamily::Inet6,
};
let fd = socket(
family,
SockType::Datagram,
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
None::<SockProtocol>,
)?;
if let Some(name) = interface {
setsockopt(&fd, sockopt::BindToDevice, &OsString::from(name))?;
}
match addr {
SocketAddr::V4(a) => bind(fd.as_raw_fd(), &SockaddrIn::from(a)),
SocketAddr::V6(a) => bind(fd.as_raw_fd(), &SockaddrIn6::from(a)),
}?;
UdpSocket::from_std(std::net::UdpSocket::from(fd))
}
/// A socket address for `ip`:`port`. An IPv6 link-local address is only meaningful with a scope, so it is scoped to
/// `interface`, which is then required.
pub fn scoped_socket_addr(
ip: IpAddr,
port: u16,
interface: Option<&str>,
) -> io::Result<SocketAddr> {
match (ip, interface) {
(IpAddr::V6(v6), Some(name)) if is_ipv6_link_local(&ip) => {
let scope_id = if_nametoindex(name)?;
Ok(SocketAddr::V6(SocketAddrV6::new(v6, port, 0, scope_id)))
}
(_, None) if is_ipv6_link_local(&ip) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("link-local address {ip} requires an interface"),
)),
_ => Ok(SocketAddr::new(ip, port)),
}
}
/// Have the kernel discard datagrams that arrive with a TTL (IPv4) or Hop Limit (IPv6) other than `hop_limit`.
///
/// `IP_MINTTL` and `IPV6_MINHOPCOUNT` are only enforced for TCP, so this attaches a classic BPF socket filter that
/// reads the field from the network header (`SKF_NET_OFF`). Discards are silent.
pub fn require_hop_limit(sock: &UdpSocket, hop_limit: u8) -> io::Result<()> {
// Offset of the TTL in the IPv4 header, and of the Hop Limit in the IPv6 header
let field_offset = if sock.local_addr()?.is_ipv4() { 8 } else { 7 };
let insn = |code: u32, jt: u8, jf: u8, k: u32| nix::libc::sock_filter {
code: code as u16,
jt,
jf,
k,
};
let mut program = [
// A = the TTL / Hop Limit byte
insn(
nix::libc::BPF_LD | nix::libc::BPF_B | nix::libc::BPF_ABS,
0,
0,
(nix::libc::SKF_NET_OFF + field_offset) as u32,
),
// if A == hop_limit, skip the drop
insn(
nix::libc::BPF_JMP | nix::libc::BPF_JEQ | nix::libc::BPF_K,
1,
0,
hop_limit as u32,
),
insn(nix::libc::BPF_RET | nix::libc::BPF_K, 0, 0, 0),
insn(nix::libc::BPF_RET | nix::libc::BPF_K, 0, 0, u32::MAX),
];
let fprog = nix::libc::sock_fprog {
len: program.len() as u16,
filter: program.as_mut_ptr(),
};
// SAFETY: `fprog` and the program it points to are valid for the duration of the call, and the kernel copies
// the program during it.
let res = unsafe {
nix::libc::setsockopt(
sock.as_raw_fd(),
nix::libc::SOL_SOCKET,
nix::libc::SO_ATTACH_FILTER,
std::ptr::from_ref(&fprog).cast(),
std::mem::size_of::<nix::libc::sock_fprog>() as nix::libc::socklen_t,
)
};
if res == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std::io::Error> {
let addr = sock.local_addr()?;
if addr.is_ipv4() {
@@ -73,3 +383,286 @@ pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std::
panic!("UdpSocket with no address family ?!")
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
fn record_offsets_ms(offsets_ms: &[u64]) -> AtomicIntervalStats {
let stats = AtomicIntervalStats::new();
let t0 = Instant::now();
for &ms in offsets_ms {
stats.record(t0 + Duration::from_millis(ms));
}
stats
}
#[rstest]
#[case::empty(&[], 0, None, None, None)]
#[case::single_packet_has_no_intervals(&[0], 1, None, None, None)]
#[case::min_max_mean(&[0, 100, 400, 500], 4, Some(100), Some(300), Some(166))]
fn interval_stats_summary(
#[case] offsets_ms: &[u64],
#[case] count: u64,
#[case] min_ms: Option<u64>,
#[case] max_ms: Option<u64>,
#[case] mean_ms: Option<u128>,
) {
let s = record_offsets_ms(offsets_ms).snapshot();
assert_eq!(s.count(), count);
assert_eq!(s.min(), min_ms.map(Duration::from_millis));
assert_eq!(s.max(), max_ms.map(Duration::from_millis));
assert_eq!(s.mean().map(|m| m.as_millis()), mean_ms);
}
#[test]
fn interval_stats_reset() {
let stats = AtomicIntervalStats::new();
let t0 = Instant::now();
stats.record(t0);
stats.record(t0 + Duration::from_millis(100));
stats.reset();
let s = stats.snapshot();
assert_eq!(s.count(), 0);
assert_eq!((s.min(), s.max(), s.mean()), (None, None, None));
stats.record(t0 + Duration::from_millis(900));
stats.record(t0 + Duration::from_millis(1000));
assert_eq!(stats.snapshot().max(), Some(Duration::from_millis(100)));
}
#[test]
fn atomic_instant_roundtrip() {
let a = AtomicInstant::new();
assert_eq!(a.load(), None);
let t = Instant::now() + Duration::from_secs(5);
assert_eq!(a.swap(t), None);
assert_eq!(a.load(), Some(t));
a.clear();
assert_eq!(a.load(), None);
}
#[test]
fn atomic_instant_swap_returns_previous() {
let a = AtomicInstant::new();
let t1 = Instant::now() + Duration::from_secs(1);
let t2 = t1 + Duration::from_secs(1);
a.store(t1);
assert_eq!(a.swap(t2), Some(t1));
assert_eq!(a.load(), Some(t2));
}
#[test]
fn atomic_instant_clamps_before_epoch() {
let a = AtomicInstant::new();
let before = Instant::now().checked_sub(Duration::from_secs(1));
let Some(before) = before else { return };
a.store(before);
let loaded = a.load().unwrap();
assert!(loaded >= before);
assert!(loaded <= Instant::now());
}
#[rstest]
#[case::empty(IntervalStats::default(), "0 pkts, interval min/avg/max -/-/- ms")]
#[case::four_packets(
record_offsets_ms(&[0, 100, 400, 500]).snapshot(),
"4 pkts, interval min/avg/max 100/167/300 ms"
)]
fn interval_stats_display(#[case] stats: IntervalStats, #[case] expected: &str) {
assert_eq!(stats.to_string(), expected);
}
fn session_stats(last_up: Option<Instant>, last_down: Option<Instant>) -> BfdSessionStats {
let rx = AtomicIntervalStats::new();
let tx = AtomicIntervalStats::new();
let t0 = Instant::now();
rx.record(t0);
rx.record(t0 + Duration::from_millis(300));
tx.record(t0);
BfdSessionStats {
local_ip: "192.0.2.1".parse().unwrap(),
remote_ip: "192.0.2.2".parse().unwrap(),
local_discr: BfdDiscriminator(10),
remote_discr: BfdDiscriminator(20),
state: BfdState::Up,
last_diag: BfdDiagnostic::TimeExpired,
rx: rx.snapshot(),
rx_received: 2,
tx: tx.snapshot(),
last_up,
last_down,
last_change: Instant::now(),
detect_time: BfdInterval::from_millis(900),
base_interval: BfdInterval::from_secs(1),
auth: None,
}
}
#[test]
fn session_stats_display_never() {
let out = session_stats(None, None).to_string();
let lines: Vec<&str> = out.lines().collect();
assert_eq!(lines.len(), 6);
assert_eq!(
lines[0].split_whitespace().collect::<Vec<_>>(),
["192.0.2.2", "Up", "2", "1"]
);
assert_eq!(
lines[1].trim(),
"LocalDiscr:10 RemoteDiscr:20 DetectTime: 900000us TxTime: 1000000us Diag:TimeExpired Last: 0s"
);
assert_eq!(
lines[2],
" Rx: 2 pkts, interval min/avg/max 300/300/300 ms"
);
assert_eq!(lines[3], " Tx: 1 pkts, interval min/avg/max -/-/- ms");
assert_eq!(lines[4], " Auth: none");
assert_eq!(lines[5], " Last Up: never Last Down: never");
}
#[rstest]
#[case::meticulous_sha1(
AuthStats {
auth_type: BfdAuthType::MetKeyedSHA1,
key_id: 3,
rcv_seq: Some(100),
xmit_seq: Some(7),
},
"\n Auth: meticulous-sha1 KeyId:3 RcvSeq:100 XmitSeq:7\n"
)]
#[case::md5_without_rcv_seq(
AuthStats {
auth_type: BfdAuthType::KeyedMD5,
key_id: 1,
rcv_seq: None,
xmit_seq: Some(7),
},
"\n Auth: md5 KeyId:1 RcvSeq:- XmitSeq:7\n"
)]
fn session_stats_display_auth(#[case] auth: AuthStats, #[case] expected: &str) {
let out = session_stats(None, None).with_auth(Some(auth)).to_string();
assert!(out.contains(expected), "{out}");
}
#[rstest]
#[case::last_up(true, false, "Last Up: 0s ago Last Down: never")]
#[case::last_down(false, true, "Last Up: never Last Down: 0s ago")]
fn session_stats_display_last_up_down(
#[case] up: bool,
#[case] down: bool,
#[case] expected_suffix: &str,
) {
let now = Instant::now();
let out = session_stats(up.then_some(now), down.then_some(now)).to_string();
assert!(out.ends_with(expected_suffix), "{out}");
}
#[test]
fn session_stats_with_base_interval() {
let s = session_stats(None, None).with_base_interval(BfdInterval::from_millis(300));
assert_eq!(s.base_interval, BfdInterval::from_millis(300));
}
#[rstest]
#[tokio::test]
async fn set_ttl_v4(#[values(255, 64)] ttl: u8) {
let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
set_ttl_or_hop_limit(&sock, ttl).unwrap();
assert_eq!(sock.ttl().unwrap(), u32::from(ttl));
}
#[tokio::test]
async fn set_hop_limit_v6() {
let Ok(sock) = UdpSocket::bind("[::1]:0").await else {
return;
};
set_ttl_or_hop_limit(&sock, 255).unwrap();
assert_eq!(getsockopt(&sock, sockopt::Ipv6Ttl).unwrap(), 255);
}
#[rstest]
#[case::v4("127.0.0.1:0")]
#[case::v6("[::1]:0")]
#[tokio::test]
async fn require_hop_limit_accepts_only_255(#[case] bind: &str) {
let Ok(rx) = UdpSocket::bind(bind).await else {
return;
};
require_hop_limit(&rx, 255).unwrap();
let tx = UdpSocket::bind(bind).await.unwrap();
for hop_limit in [1u8, 64, 254, 255] {
set_ttl_or_hop_limit(&tx, hop_limit).unwrap();
tx.send_to(&[hop_limit], rx.local_addr().unwrap())
.await
.unwrap();
}
let mut buf = [0u8; 8];
let n = rx.recv(&mut buf).await.unwrap();
assert_eq!(&buf[..n], [255]);
let more = tokio::time::timeout(Duration::from_millis(100), rx.recv(&mut buf)).await;
assert!(more.is_err(), "received a datagram with hop limit != 255");
}
#[tokio::test]
async fn bind_udp_without_interface() {
let sock = bind_udp("127.0.0.1:0".parse().unwrap(), None).unwrap();
assert!(sock.local_addr().unwrap().port() != 0);
}
#[tokio::test]
async fn bind_udp_to_loopback_interface() {
let sock = bind_udp("127.0.0.1:0".parse().unwrap(), Some("lo")).unwrap();
let addr = sock.local_addr().unwrap();
let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
peer.send_to(b"x", addr).await.unwrap();
let mut buf = [0u8; 1];
let (n, _) = sock.recv_from(&mut buf).await.unwrap();
assert_eq!(n, 1);
}
#[tokio::test]
async fn bind_udp_rejects_unknown_interface() {
assert!(bind_udp("127.0.0.1:0".parse().unwrap(), Some("nosuchif0")).is_err());
}
#[rstest]
#[case::link_local_is_scoped("fe80::1", Some("lo"), "[fe80::1%{lo}]:3784")]
#[case::global_v6_is_unscoped("2001:db8::1", Some("lo"), "[2001:db8::1]:3784")]
#[case::v4_is_unscoped("192.0.2.1", None, "192.0.2.1:3784")]
fn scoped_socket_addr_formats(
#[case] addr: &str,
#[case] interface: Option<&str>,
#[case] expected: &str,
) {
let lo = if_nametoindex("lo").unwrap();
let scoped = scoped_socket_addr(addr.parse().unwrap(), 3784, interface).unwrap();
assert_eq!(
scoped.to_string(),
expected.replace("{lo}", &lo.to_string())
);
}
#[rstest]
#[case::link_local_without_interface(None, Some(io::ErrorKind::InvalidInput))]
#[case::link_local_unknown_interface(Some("nosuchif0"), None)]
fn scoped_socket_addr_rejects(
#[case] interface: Option<&str>,
#[case] kind: Option<io::ErrorKind>,
) {
let err = scoped_socket_addr("fe80::1".parse().unwrap(), 3784, interface).unwrap_err();
if let Some(kind) = kind {
assert_eq!(err.kind(), kind);
}
}
#[rstest]
#[case::fe80("fe80::1", true)]
#[case::febf("febf::1", true)]
#[case::fec0("fec0::1", false)]
#[case::global_v6("2001:db8::1", false)]
#[case::v4_link_local("169.254.0.1", false)]
fn link_local_detection(#[case] addr: &str, #[case] expected: bool) {
assert_eq!(is_ipv6_link_local(&addr.parse().unwrap()), expected);
}
}