From 2b2fe66785fe0ae2f0ab4bdcf7529b07eb3f7e7d Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 27 Oct 2026 14:51:21 -0700 Subject: [PATCH] implement local binding, rfc-based tests, fix deficiencies, add CI --- .gitea/workflows/ci.yaml | 37 + .pre-commit-config.yaml | 21 + Cargo.lock | 223 ++--- Cargo.toml | 7 +- config.yaml.dist | 42 +- src/bfd.rs | 760 +++++++++-------- src/bin/rust-bfdd.rs | 1400 +++++++++++++++++++------------ src/bin/tests/rfc.rs | 166 ++++ src/bin/tests/rfc/auth.rs | 312 +++++++ src/bin/tests/rfc/fsm.rs | 180 ++++ src/bin/tests/rfc/transport.rs | 92 ++ src/bin/tests/rfc/tx.rs | 148 ++++ src/bin/tests/rfc/violations.rs | 158 ++++ src/config.rs | 590 ++++++------- src/control.rs | 1 + src/events.rs | 85 +- src/lib.rs | 345 ++++++-- 17 files changed, 3076 insertions(+), 1491 deletions(-) create mode 100644 .gitea/workflows/ci.yaml create mode 100644 .pre-commit-config.yaml create mode 100644 src/bin/tests/rfc.rs create mode 100644 src/bin/tests/rfc/auth.rs create mode 100644 src/bin/tests/rfc/fsm.rs create mode 100644 src/bin/tests/rfc/transport.rs create mode 100644 src/bin/tests/rfc/tx.rs create mode 100644 src/bin/tests/rfc/violations.rs diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml new file mode 100644 index 0000000..3084676 --- /dev/null +++ b/.gitea/workflows/ci.yaml @@ -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 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..849c531 --- /dev/null +++ b/.pre-commit-config.yaml @@ -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 diff --git a/Cargo.lock b/Cargo.lock index 7048e29..c46483f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -256,7 +256,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ - "thiserror 2.0.21", + "thiserror", ] [[package]] @@ -392,6 +392,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" +[[package]] +name = "futures-timer" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" + [[package]] name = "futures-util" version = "0.3.34" @@ -420,6 +426,12 @@ dependencies = [ "wasi", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "hashbrown" version = "0.17.1" @@ -465,8 +477,6 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown", - "serde", - "serde_core", ] [[package]] @@ -484,15 +494,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - [[package]] name = "itoa" version = "1.0.18" @@ -650,15 +651,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -739,6 +731,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -825,6 +826,41 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "relative-path" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" + +[[package]] +name = "rstest" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b376e512f30a7686a8dbc6aeaace99b3ade1c26c1c63473473a817ade226dafc" +dependencies = [ + "futures-timer", + "futures-util", + "rstest_macros", +] + +[[package]] +name = "rstest_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88512dbfb5b73a0dfa38aef7bc73b5657035fce477b923faf12d332dd83051ea" +dependencies = [ + "cfg-if 1.0.5", + "glob", + "proc-macro-crate", + "proc-macro2", + "quote", + "regex", + "relative-path", + "rustc_version", + "syn 2.0.119", + "unicode-ident", +] + [[package]] name = "rust-bfd" version = "0.1.0" @@ -838,7 +874,7 @@ dependencies = [ "futures 0.3.34", "humantime", "humantime-serde", - "itertools 0.12.1", + "itertools", "log", "md-5", "nix", @@ -846,9 +882,9 @@ dependencies = [ "nom-derive", "proc-bitfield", "rand", + "rstest", "serde", "serde_bytes", - "serde_valid", "serde_yaml_ng", "sha1", "subtle", @@ -856,6 +892,15 @@ dependencies = [ "tokio-timer", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -874,6 +919,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -914,59 +965,6 @@ dependencies = [ "syn 3.0.9", ] -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_valid" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a812672d5d6c94c0fa540e62dc318728410c78f40d60ae6c07afc845616da5f6" -dependencies = [ - "indexmap", - "itertools 0.14.0", - "num-traits", - "regex", - "serde", - "serde_json", - "serde_valid_derive", - "serde_valid_literal", - "thiserror 1.0.69", - "unicode-segmentation", -] - -[[package]] -name = "serde_valid_derive" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "539cd22aaf48cb9a8932c8b7f5d54f51719b2f826564f9da1a9902ee411d753c" -dependencies = [ - "itertools 0.14.0", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.9", -] - -[[package]] -name = "serde_valid_literal" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "433e602b939d2e8e8b47f30f919b27a984183974079de2262ca876c2162657c8" -dependencies = [ - "regex", -] - [[package]] name = "serde_yaml_ng" version = "0.10.0" @@ -1074,33 +1072,13 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - [[package]] name = "thiserror" version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.21", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "thiserror-impl", ] [[package]] @@ -1164,6 +1142,36 @@ dependencies = [ "tokio-executor", ] +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + [[package]] name = "typenum" version = "1.20.1" @@ -1176,12 +1184,6 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" -[[package]] -name = "unicode-segmentation" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" - [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -1215,6 +1217,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -1234,9 +1245,3 @@ dependencies = [ "quote", "syn 2.0.119", ] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index 2c9dd53..ece3f44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,16 +16,19 @@ 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", "socket"] } +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_valid = "3.2.0" + 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" diff --git a/config.yaml.dist b/config.yaml.dist index e7d5ffe..868c807 100644 --- a/config.yaml.dist +++ b/config.yaml.dist @@ -1,18 +1,9 @@ -# rust-bfd configuration. Install as /etc/rust-bfd/config.yaml (or pass --config / set BFD_CONFIG). +# 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. # -# Precedence, lowest to highest: built-in defaults < this file < BFD_* environment < command line. # Values shown below are the built-in defaults unless noted. Unknown keys are an error. -# Local address(es) to bind and use as the source of BFD control packets. Required (here, in BFD_BIND, or via --bind). -# Accepts a single address, a list, or a comma-separated string. The daemon currently supports exactly one address; -# the list form is accepted so configs do not need to change once multiple binds are implemented. -# Env: BFD_BIND="192.0.2.1" (or "192.0.2.1,2001:db8::1") -# CLI: --bind 192.0.2.1 [--bind ...] (replaces the addresses configured here) -bind: 192.0.2.1 -# bind: [192.0.2.1, "2001:db8::1"] - # Directory of executable scripts run, in lexical order, on every session state change. -# Env: BFD_HOOKS_DIR hooks_dir: /etc/rust-bfd/hooks.d # Settings inherited by every peer that does not override them. Durations are humantime strings (300ms, 1s, 2m). @@ -20,22 +11,36 @@ hooks_dir: /etc/rust-bfd/hooks.d 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). - # Env: BFD_DEFAULTS_DESIRED_MIN_TX desired_min_tx: 300ms # Minimum interval between received control packets we can support. - # Env: BFD_DEFAULTS_REQUIRED_MIN_RX required_min_rx: 300ms # Detection time multiplier: we declare the session down after this many missed packets. - # Env: BFD_DEFAULTS_DETECT_MULT detect_mult: 3 -# Peers to establish sessions with. Peers can only be configured here and with --peer (repeatable, addresses only, -# default settings); they cannot be set from the environment. Each peer's address must match the family of at least -# one bind address. +# 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 @@ -51,6 +56,7 @@ peers: # 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 @@ -59,6 +65,7 @@ peers: # # 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 @@ -66,6 +73,7 @@ peers: # # 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 diff --git a/src/bfd.rs b/src/bfd.rs index 1b635c8..ae75025 100644 --- a/src/bfd.rs +++ b/src/bfd.rs @@ -12,7 +12,7 @@ use bytemuck::NoUninit; use byteorder::{BigEndian, WriteBytesExt}; use nom::{ bytes::complete::take, - multi::many_m_n, + combinator::{rest, verify}, number::complete::{be_u32, be_u8}, IResult, }; @@ -73,10 +73,10 @@ impl Display for BfdState { impl From for &OsStr { fn from(val: BfdState) -> Self { match val { - BfdState::AdminDown => OsStr::new("AdminDown"), - BfdState::Init => OsStr::new("Init"), - BfdState::Down => OsStr::new("Down"), - BfdState::Up => OsStr::new("Up"), + BfdState::AdminDown => OsStr::new("admin_down"), + BfdState::Init => OsStr::new("init"), + BfdState::Down => OsStr::new("down"), + BfdState::Up => OsStr::new("up"), } } } @@ -122,6 +122,7 @@ impl Display for BfdDiscriminator { pub struct BfdInterval(u32); impl BfdInterval { + pub const ZERO: Self = Self(0); pub fn from_micros(micros: u32) -> Self { Self(micros) } @@ -228,8 +229,14 @@ pub struct BfdAuthSimplePassword { impl<'a> Parse<&'a [u8]> for BfdAuthSimplePassword { fn parse(i: &'a [u8]) -> IResult<&'a [u8], Self, nom::error::Error<&'a [u8]>> { let (i, key_id) = be_u8(i)?; - let (i, password) = many_m_n(1, 16, be_u8)(i)?; - Ok((i, Self { key_id, password })) + let (i, password) = verify(rest, |p: &[u8]| !p.is_empty())(i)?; + Ok(( + i, + Self { + key_id, + password: password.to_vec(), + }, + )) } } @@ -246,6 +253,8 @@ impl BfdAuthSimplePassword { pub struct BfdAuthKeyedMD5 { pub meticulous: bool, pub key_id: u8, + /// Reserved byte, kept as received because the digest covers it (RFC 5880 4.3 requires ignoring its value) + pub reserved: u8, pub seq: u32, pub digest: [u8; 16], } @@ -253,7 +262,7 @@ pub struct BfdAuthKeyedMD5 { impl BfdAuthKeyedMD5 { fn parse_with(i: &[u8], meticulous: bool) -> IResult<&[u8], Self> { let (i, key_id) = be_u8(i)?; - let (i, _reserved) = be_u8(i)?; + let (i, reserved) = be_u8(i)?; let (i, seq) = be_u32(i)?; let (i, digest) = take(16usize)(i)?; let digest = digest.try_into().expect("took 16 bytes"); @@ -262,6 +271,7 @@ impl BfdAuthKeyedMD5 { Self { meticulous, key_id, + reserved, seq, digest, }, @@ -270,7 +280,7 @@ impl BfdAuthKeyedMD5 { fn serialize(&self, wtr: &mut impl Write) -> Result<(), std::io::Error> { wtr.write_u8(self.key_id)?; - wtr.write_u8(0)?; + wtr.write_u8(self.reserved)?; wtr.write_u32::(self.seq)?; wtr.write_all(&self.digest) } @@ -280,6 +290,8 @@ impl BfdAuthKeyedMD5 { pub struct BfdAuthKeyedSHA1 { pub meticulous: bool, pub key_id: u8, + /// Reserved byte, kept as received because the digest covers it (RFC 5880 4.3 requires ignoring its value) + pub reserved: u8, pub seq: u32, pub digest: [u8; 20], } @@ -287,7 +299,7 @@ pub struct BfdAuthKeyedSHA1 { impl BfdAuthKeyedSHA1 { fn parse_with(i: &[u8], meticulous: bool) -> IResult<&[u8], Self> { let (i, key_id) = be_u8(i)?; - let (i, _reserved) = be_u8(i)?; + let (i, reserved) = be_u8(i)?; let (i, seq) = be_u32(i)?; let (i, digest) = take(20usize)(i)?; let digest = digest.try_into().expect("took 20 bytes"); @@ -296,6 +308,7 @@ impl BfdAuthKeyedSHA1 { Self { meticulous, key_id, + reserved, seq, digest, }, @@ -304,7 +317,7 @@ impl BfdAuthKeyedSHA1 { fn serialize(&self, wtr: &mut impl Write) -> Result<(), std::io::Error> { wtr.write_u8(self.key_id)?; - wtr.write_u8(0)?; + wtr.write_u8(self.reserved)?; wtr.write_u32::(self.seq)?; wtr.write_all(&self.digest) } @@ -504,7 +517,7 @@ impl BfdPacket { } // If the Auth Len field is not equal to the length of the password // selected by the key ID, plus three, the packet MUST be discarded. - // NB: implied by vec comparison + // NB: the parser keeps the whole password field, so this is implied by the comparison // // If the Password field does not match the password selected by the // key ID, the packet MUST be discarded. @@ -559,6 +572,8 @@ impl BfdPacket { mod tests { use super::*; use nom_derive::Parse; + use rstest::rstest; + use std::fmt::Display; use std::time::Duration; // vers=1 diag=0 | state=Up | mult=3 | len=24, then RFC 5880 6.8.7 fields @@ -575,23 +590,43 @@ mod tests { BfdPacket::parse(bytes).expect("parse").1 } - #[test] - fn flags_bit_layout() { - let f = BfdFlags(0) + /// `UP_PACKET` with the A bit set, followed by `section` + fn up_packet_with_auth_section(section: &[u8]) -> Vec { + let mut bytes = UP_PACKET.to_vec(); + bytes[1] |= 0x04; + bytes.extend_from_slice(section); + bytes + } + + /// RFC 5880 4.3: type, len (incl. type and len bytes) = 24, key id, reserved, seq, `digest_len` byte digest + fn md5_section(auth_type: u8, digest_len: usize) -> Vec { + let mut section = vec![auth_type, 24, 1, 0, 0, 0, 0, 1]; + section.extend(std::iter::repeat_n(0, digest_len)); + section + } + + #[rstest] + #[case::vers_diag_state_poll_mult_len( + BfdFlags(0) .with_vers(1) .with_diag(BfdDiagnostic::NeighborDown as u8) .with_state(BfdState::Up as u8) .with_poll(true) .with_detect_mult(3) - .with_length(24); - assert_eq!(f.0, 0x23e0_0318); - let f = BfdFlags(0) + .with_length(24), + 0x23e0_0318 + )] + #[case::single_bit_flags( + BfdFlags(0) .with_final_(true) .with_cpi(true) .with_auth_present(true) .with_demand(true) - .with_multipoint(true); - assert_eq!(f.0, 0x001f_0000); + .with_multipoint(true), + 0x001f_0000 + )] + fn flags_bit_layout(#[case] flags: BfdFlags, #[case] expected: u32) { + assert_eq!(flags.0, expected); } #[test] @@ -654,11 +689,14 @@ mod tests { assert_eq!(q.required_min_echo_rx, p.required_min_echo_rx); } - #[test] - fn parse_rejects_truncated() { - for len in 0..UP_PACKET.len() { - assert!(BfdPacket::parse(&UP_PACKET[..len]).is_err(), "len {len}"); - } + #[rstest] + fn parse_rejects_truncated( + #[values( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 + )] + len: usize, + ) { + assert!(BfdPacket::parse(&UP_PACKET[..len]).is_err()); } #[test] @@ -670,163 +708,119 @@ mod tests { assert_eq!(p.my_disc, BfdDiscriminator(1)); } - #[test] - fn parse_auth_present_requires_auth_section() { - let mut bytes = UP_PACKET; - bytes[1] |= 0x04; + #[rstest] + #[case::a_bit_without_section(up_packet_with_auth_section(&[]))] + #[case::auth_type_none(up_packet_with_auth_section(&md5_section(0, 16)))] + #[case::unassigned_auth_type(up_packet_with_auth_section(&md5_section(6, 16)))] + #[case::truncated_digest(up_packet_with_auth_section(&md5_section(2, 8)))] + fn parse_rejects_bad_auth_sections(#[case] bytes: Vec) { assert!(BfdPacket::parse(&bytes).is_err()); } #[test] fn parse_keyed_md5_auth() { - // RFC 5880 4.3: type, len (incl. type and len bytes) = 24, key id, reserved, seq, 16 byte digest - let mut bytes = UP_PACKET.to_vec(); - bytes[1] |= 0x04; + let mut bytes = up_packet_with_auth_section(&md5_section(2, 16)); bytes[3] = 48; - bytes.extend_from_slice(&[2, 24, 7, 0, 0, 0, 0, 9]); - bytes.extend_from_slice(&[0xaa; 16]); let (rest, p) = BfdPacket::parse(&bytes).expect("parse"); assert!(rest.is_empty()); assert!(p.auth.is_some()); } - #[test] - fn invalid_state_and_diag_values() { - assert!(BfdState::try_from(4u8).is_err()); - assert!(BfdDiagnostic::try_from(10u8).is_err()); - assert!(BfdState::try_from(3u8).is_ok()); + #[rstest] + #[case::state_in_range(3, true)] + #[case::state_out_of_range(4, false)] + fn state_try_from(#[case] value: u8, #[case] valid: bool) { + assert_eq!(BfdState::try_from(value).is_ok(), valid); } #[test] - fn state_display_and_osstr() { - for (s, name) in [ - (BfdState::AdminDown, "AdminDown"), - (BfdState::Down, "Down"), - (BfdState::Init, "Init"), - (BfdState::Up, "Up"), - ] { - assert_eq!(s.to_string(), name); - assert_eq!(<&OsStr>::from(s), OsStr::new(name)); - } + fn invalid_diag_value() { + assert!(BfdDiagnostic::try_from(10u8).is_err()); + } + + #[test] + fn state_default_is_down() { assert_eq!(BfdState::default(), BfdState::Down); } - #[test] - fn diagnostic_display() { - assert_eq!(BfdDiagnostic::None.to_string(), "None"); - assert_eq!(BfdDiagnostic::TimeExpired.to_string(), "TimeExpired"); - assert_eq!(BfdDiagnostic::AdminDown.to_string(), "AdminDown"); + #[rstest] + #[case(BfdState::AdminDown, "admin_down")] + #[case(BfdState::Down, "down")] + #[case(BfdState::Init, "init")] + #[case(BfdState::Up, "up")] + fn state_osstr(#[case] state: BfdState, #[case] env: &str) { + assert_eq!(<&OsStr>::from(state), OsStr::new(env)); + } + + #[rstest] + #[case::state_admin_down(&BfdState::AdminDown, "AdminDown")] + #[case::state_down(&BfdState::Down, "Down")] + #[case::state_init(&BfdState::Init, "Init")] + #[case::state_up(&BfdState::Up, "Up")] + #[case::diag_none(&BfdDiagnostic::None, "None")] + #[case::diag_time_expired(&BfdDiagnostic::TimeExpired, "TimeExpired")] + #[case::diag_admin_down(&BfdDiagnostic::AdminDown, "AdminDown")] + #[case::interval(&BfdInterval::from_millis(300), "300000us")] + #[case::discriminator(&BfdDiscriminator(42), "42")] + fn display_formats(#[case] value: &dyn Display, #[case] expected: &str) { + assert_eq!(value.to_string(), expected); + } + + #[rstest] + #[case::millis_vs_micros(BfdInterval::from_millis(300), BfdInterval::from_micros(300_000))] + #[case::secs_vs_millis(BfdInterval::from_secs(2), BfdInterval::from_millis(2000))] + #[case::secs_f32(BfdInterval::from_secs_f32(0.25), BfdInterval::from_millis(250))] + #[case::max_millis( + BfdInterval::from_millis(4_294_967), + BfdInterval::from_micros(4_294_967_000) + )] + #[case::max_secs(BfdInterval::from_secs(4294), BfdInterval::from_micros(4_294_000_000))] + fn interval_constructors(#[case] actual: BfdInterval, #[case] expected: BfdInterval) { + assert_eq!(actual, expected); + } + + #[rstest] + #[case::millis(Duration::from_millis(300), BfdInterval::from_millis(300))] + #[case::micros(Duration::from_micros(1999), BfdInterval::from_micros(1999))] + #[case::max(Duration::from_micros(u32::MAX as u64), BfdInterval::from_micros(u32::MAX))] + fn interval_duration_conversion(#[case] duration: Duration, #[case] interval: BfdInterval) { + assert_eq!(Duration::from(interval), duration); + assert_eq!(BfdInterval::from(duration), interval); + } + + #[rstest] + #[case::mul(BfdInterval::from_millis(300) * 3, BfdInterval::from_millis(900))] + #[case::reverse_mul(3 * BfdInterval::from_millis(300), BfdInterval::from_millis(900))] + #[case::div(BfdInterval::from_millis(300) / 3, BfdInterval::from_millis(100))] + #[case::int_div_interval(900_000 / BfdInterval::from_millis(300), BfdInterval::from_micros(3))] + fn interval_arithmetic(#[case] actual: BfdInterval, #[case] expected: BfdInterval) { + assert_eq!(actual, expected); } #[test] - fn interval_constructors() { - assert_eq!( - BfdInterval::from_millis(300), - BfdInterval::from_micros(300_000) - ); - assert_eq!(BfdInterval::from_secs(2), BfdInterval::from_millis(2000)); - assert_eq!( - BfdInterval::from_secs_f32(0.25), - BfdInterval::from_millis(250) - ); - } - - #[test] - fn interval_duration_conversion() { - let i = BfdInterval::from_millis(300); - assert_eq!(Duration::from(i), Duration::from_millis(300)); - assert_eq!(BfdInterval::from(Duration::from_millis(300)), i); - assert_eq!( - BfdInterval::from(Duration::from_micros(1999)), - BfdInterval::from_micros(1999) - ); - } - - #[test] - fn interval_arithmetic_and_display() { - let i = BfdInterval::from_millis(300); - assert_eq!(i * 3, BfdInterval::from_millis(900)); - assert_eq!(3 * i, BfdInterval::from_millis(900)); - assert_eq!(i / 3, BfdInterval::from_millis(100)); - assert_eq!(900_000 / i, BfdInterval::from_micros(3)); - assert_eq!(i.to_string(), "300000us"); + fn interval_ordering() { assert!(BfdInterval::from_millis(1) < BfdInterval::from_secs(1)); } - #[test] - fn discriminator_display() { - assert_eq!(BfdDiscriminator(42).to_string(), "42"); - } - - #[test] - fn interval_constructors_accept_the_maximum() { - assert_eq!( - BfdInterval::from_millis(4_294_967), - BfdInterval::from_micros(4_294_967_000) - ); - assert_eq!( - BfdInterval::from_secs(4294), - BfdInterval::from_micros(4_294_000_000) - ); - assert_eq!( - BfdInterval::from(Duration::from_micros(u32::MAX as u64)), - BfdInterval::from_micros(u32::MAX) - ); - } - - #[test] + #[rstest] + #[case::from_millis(|| { BfdInterval::from_millis(4_294_968); })] + #[case::from_secs(|| { BfdInterval::from_secs(4295); })] + #[case::from_secs_f32(|| { BfdInterval::from_secs_f32(4295.0); })] + #[case::from_secs_f32_negative(|| { BfdInterval::from_secs_f32(-1.0); })] + #[case::from_secs_f32_nan(|| { BfdInterval::from_secs_f32(f32::NAN); })] + #[case::from_duration(|| { let _ = BfdInterval::from(Duration::from_micros(u32::MAX as u64 + 1)); })] + #[case::mul(|| { let _ = BfdInterval::from_secs(2000) * 3; })] + #[case::reverse_mul(|| { let _ = 3 * BfdInterval::from_secs(2000); })] #[should_panic(expected = "overflow")] - fn from_millis_overflow_panics() { - BfdInterval::from_millis(4_294_968); + fn interval_overflow_panics(#[case] overflowing: fn()) { + overflowing(); } - #[test] - #[should_panic(expected = "overflow")] - fn from_secs_overflow_panics() { - BfdInterval::from_secs(4295); - } - - #[test] - #[should_panic(expected = "overflow")] - fn from_secs_f32_overflow_panics() { - BfdInterval::from_secs_f32(4295.0); - } - - #[test] - #[should_panic(expected = "overflow")] - fn from_secs_f32_negative_panics() { - BfdInterval::from_secs_f32(-1.0); - } - - #[test] - #[should_panic(expected = "overflow")] - fn from_secs_f32_nan_panics() { - BfdInterval::from_secs_f32(f32::NAN); - } - - #[test] - #[should_panic(expected = "overflow")] - fn from_duration_overflow_panics() { - let _ = BfdInterval::from(Duration::from_micros(u32::MAX as u64 + 1)); - } - - #[test] - #[should_panic(expected = "overflow")] - fn mul_overflow_panics() { - let _ = BfdInterval::from_secs(2000) * 3; - } - - #[test] - #[should_panic(expected = "overflow")] - fn reverse_mul_overflow_panics() { - let _ = 3 * BfdInterval::from_secs(2000); - } - - #[test] - fn checked_mul() { - let i = BfdInterval::from_secs(1000); - assert_eq!(i.checked_mul(4), Some(BfdInterval::from_secs(4000))); - assert_eq!(i.checked_mul(5), None); + #[rstest] + #[case(4, Some(BfdInterval::from_secs(4000)))] + #[case(5, None)] + fn checked_mul(#[case] factor: u32, #[case] expected: Option) { + assert_eq!(BfdInterval::from_secs(1000).checked_mul(factor), expected); } const MD5_KEY: [u8; 16] = *b"0123456789abcdef"; @@ -840,10 +834,16 @@ mod tests { bytes.iter().map(|b| format!("{b:02x}")).collect() } + fn flip(mut key: [u8; N], index: usize) -> [u8; N] { + key[index] ^= 1; + key + } + fn md5_auth(meticulous: bool, key_id: u8, seq: u32, key: [u8; 16]) -> BfdAuth { BfdAuth::KeyedMD5(BfdAuthKeyedMD5 { meticulous, key_id, + reserved: 0, seq, digest: key, }) @@ -853,6 +853,7 @@ mod tests { BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 { meticulous, key_id, + reserved: 0, seq, digest: key, }) @@ -890,261 +891,248 @@ mod tests { parse(&p.serialize().unwrap()) } - #[test] - fn auth_accessors() { - let md5 = md5_auth(true, 7, 9, MD5_KEY); - assert_eq!(md5.auth_type(), BfdAuthType::MetKeyedMD5); - assert_eq!(md5.auth_len(), 24); + #[rstest] + #[case::md5_meticulous( + md5_auth(true, 7, 9, MD5_KEY), + BfdAuthType::MetKeyedMD5, + 24, + Some(9), + 7, + true, + true + )] + #[case::md5( + md5_auth(false, 0, 0, MD5_KEY), + BfdAuthType::KeyedMD5, + 24, + Some(0), + 0, + false, + true + )] + #[case::sha1_meticulous( + sha1_auth(true, 1, 2, SHA1_KEY), + BfdAuthType::MetKeyedSHA1, + 28, + Some(2), + 1, + true, + true + )] + #[case::sha1( + sha1_auth(false, 0, 0, SHA1_KEY), + BfdAuthType::KeyedSHA1, + 28, + Some(0), + 0, + false, + true + )] + #[case::simple_password( + password_auth(3, b"secret"), + BfdAuthType::SimplePassword, + 9, + None, + 3, + false, + false + )] + fn auth_accessors( + #[case] auth: BfdAuth, + #[case] auth_type: BfdAuthType, + #[case] auth_len: u8, + #[case] seq: Option, + #[case] key_id: u8, + #[case] meticulous: bool, + #[case] has_digest: bool, + ) { + assert_eq!(auth.auth_type(), auth_type); + assert_eq!(auth.auth_len(), auth_len); assert_eq!( - (md5.seq(), md5.key_id(), md5.meticulous()), - (Some(9), 7, true) + (auth.seq(), auth.key_id(), auth.meticulous()), + (seq, key_id, meticulous) ); + assert_eq!(auth.digest_field().is_some(), has_digest); + } + + #[rstest] + #[case::md5(md5_auth(true, 1, 0, MD5_KEY), Some(42))] + #[case::sha1(sha1_auth(true, 1, 0, SHA1_KEY), Some(42))] + #[case::simple_password(password_auth(1, b"pw"), None)] + fn set_seq_only_affects_keyed(#[case] mut auth: BfdAuth, #[case] expected: Option) { + auth.set_seq(42); + assert_eq!(auth.seq(), expected); + } + + #[rstest] + #[case::md5(md5_auth(false, 7, 0xdead_beef, MD5_KEY))] + #[case::md5_meticulous(md5_auth(true, 7, 1, MD5_KEY))] + #[case::sha1(sha1_auth(false, 255, u32::MAX, SHA1_KEY))] + #[case::sha1_meticulous(sha1_auth(true, 0, 0, SHA1_KEY))] + fn keyed_auth_wire_roundtrip(#[case] auth: BfdAuth) { + let p = auth_packet(Some(auth.clone())); + let bytes = p.serialize().unwrap(); + assert_eq!(bytes.len(), 24 + auth.auth_len() as usize); + assert_eq!(bytes[3] as usize, bytes.len()); + assert_eq!(bytes[24], u8::from(auth.auth_type())); + assert_eq!(bytes[25], auth.auth_len()); + assert_eq!(parse(&bytes).auth, Some(auth)); + } + + #[rstest] + #[case::one_byte(&b"a"[..])] + #[case::word(&b"secret"[..])] + #[case::sixteen_bytes(&b"0123456789abcdef"[..])] + fn password_auth_wire_roundtrip(#[case] pw: &[u8]) { + let auth = password_auth(5, pw); + let p = auth_packet(Some(auth.clone())); + let bytes = p.serialize().unwrap(); + assert_eq!(bytes.len(), 24 + 3 + pw.len()); + assert_eq!(bytes[24..27], [1, 3 + pw.len() as u8, 5]); + assert_eq!(&bytes[27..], pw); + assert_eq!(parse(&bytes).auth, Some(auth)); + } + + #[rstest] + #[case::md5_meticulous(md5_auth(true, 7, 9, MD5_KEY), MD5_MET_DIGEST)] + #[case::md5_non_meticulous(md5_auth(false, 7, 9, MD5_KEY), MD5_NONMET_DIGEST)] + #[case::sha1_meticulous(sha1_auth(true, 7, 9, SHA1_KEY), SHA1_MET_DIGEST)] + fn sign_matches_known_digest(#[case] auth: BfdAuth, #[case] expected: &str) { + let auth_len = auth.auth_len(); + let mut p = auth_packet(Some(auth)); assert_eq!( - md5_auth(false, 0, 0, MD5_KEY).auth_type(), - BfdAuthType::KeyedMD5 + p.serialize().unwrap()[..4], + [0x20, 0xc4, 0x03, 24 + auth_len] ); - - let sha1 = sha1_auth(true, 1, 2, SHA1_KEY); - assert_eq!(sha1.auth_type(), BfdAuthType::MetKeyedSHA1); - assert_eq!(sha1.auth_len(), 28); - assert_eq!( - sha1_auth(false, 0, 0, SHA1_KEY).auth_type(), - BfdAuthType::KeyedSHA1 - ); - - let pw = password_auth(3, b"secret"); - assert_eq!(pw.auth_type(), BfdAuthType::SimplePassword); - assert_eq!(pw.auth_len(), 9); - assert_eq!((pw.seq(), pw.key_id(), pw.meticulous()), (None, 3, false)); - assert!(pw.digest_field().is_none()); - } - - #[test] - fn set_seq_only_affects_keyed() { - let mut md5 = md5_auth(true, 1, 0, MD5_KEY); - md5.set_seq(42); - assert_eq!(md5.seq(), Some(42)); - let mut sha1 = sha1_auth(true, 1, 0, SHA1_KEY); - sha1.set_seq(43); - assert_eq!(sha1.seq(), Some(43)); - let mut pw = password_auth(1, b"pw"); - pw.set_seq(44); - assert_eq!(pw.seq(), None); - } - - #[test] - fn keyed_auth_wire_roundtrip() { - for auth in [ - md5_auth(false, 7, 0xdead_beef, MD5_KEY), - md5_auth(true, 7, 1, MD5_KEY), - sha1_auth(false, 255, u32::MAX, SHA1_KEY), - sha1_auth(true, 0, 0, SHA1_KEY), - ] { - let p = auth_packet(Some(auth.clone())); - let bytes = p.serialize().unwrap(); - assert_eq!(bytes.len(), 24 + auth.auth_len() as usize); - assert_eq!(bytes[3] as usize, bytes.len()); - assert_eq!(bytes[24], u8::from(auth.auth_type())); - assert_eq!(bytes[25], auth.auth_len()); - assert_eq!(parse(&bytes).auth, Some(auth)); - } - } - - #[test] - fn password_auth_wire_roundtrip() { - for pw in [&b"a"[..], b"secret", b"0123456789abcdef"] { - let auth = password_auth(5, pw); - let p = auth_packet(Some(auth.clone())); - let bytes = p.serialize().unwrap(); - assert_eq!(bytes.len(), 24 + 3 + pw.len()); - assert_eq!(bytes[24..27], [1, 3 + pw.len() as u8, 5]); - assert_eq!(&bytes[27..], pw); - assert_eq!(parse(&bytes).auth, Some(auth)); - } - } - - #[test] - fn parse_rejects_bad_auth_sections() { - let mut base = UP_PACKET.to_vec(); - base[1] |= 0x04; - // Auth Type 0 (None) and an unassigned type are not valid with the A bit set - for auth_type in [0u8, 6] { - let mut bytes = base.clone(); - bytes.extend_from_slice(&[auth_type, 24, 1, 0, 0, 0, 0, 1]); - bytes.extend_from_slice(&[0; 16]); - assert!(BfdPacket::parse(&bytes).is_err(), "type {auth_type}"); - } - // Truncated digest - let mut bytes = base.clone(); - bytes.extend_from_slice(&[2, 24, 1, 0, 0, 0, 0, 1]); - bytes.extend_from_slice(&[0; 8]); - assert!(BfdPacket::parse(&bytes).is_err()); - } - - #[test] - fn sign_matches_known_md5_digest() { - let mut p = auth_packet(Some(md5_auth(true, 7, 9, MD5_KEY))); - assert_eq!(p.serialize().unwrap()[..4], [0x20, 0xc4, 0x03, 0x30]); p.sign().unwrap(); let digest = p.auth.as_ref().unwrap().digest_field().unwrap(); - assert_eq!(hex(digest), MD5_MET_DIGEST); + assert_eq!(hex(digest), expected); + } + + #[rstest] + #[case::md5(md5_auth(true, 7, 9, MD5_KEY), &MD5_KEY[..])] + #[case::sha1(sha1_auth(true, 7, 9, SHA1_KEY), &SHA1_KEY[..])] + fn sign_does_not_leak_key(#[case] auth: BfdAuth, #[case] key: &[u8]) { + let bytes = over_the_wire(auth).serialize().unwrap(); + assert!(!bytes.windows(key.len()).any(|w| w == key)); } #[test] - fn sign_matches_known_sha1_digest() { - let mut p = auth_packet(Some(sha1_auth(true, 7, 9, SHA1_KEY))); - p.sign().unwrap(); - let digest = p.auth.as_ref().unwrap().digest_field().unwrap(); - assert_eq!(hex(digest), SHA1_MET_DIGEST); - } - - #[test] - fn meticulous_flag_changes_digest() { - let mut p = auth_packet(Some(md5_auth(false, 7, 9, MD5_KEY))); - p.sign().unwrap(); - let digest = p.auth.as_ref().unwrap().digest_field().unwrap(); - assert_eq!(hex(digest), MD5_NONMET_DIGEST); - } - - #[test] - fn sign_does_not_leak_key() { - for (auth, key) in [ - (md5_auth(true, 7, 9, MD5_KEY), &MD5_KEY[..]), - (sha1_auth(true, 7, 9, SHA1_KEY), &SHA1_KEY[..]), - ] { - let bytes = over_the_wire(auth).serialize().unwrap(); - assert!(!bytes.windows(key.len()).any(|w| w == key)); - } - } - - #[test] - fn sign_is_a_noop_without_keyed_auth() { - let mut none = auth_packet(None); - none.sign().unwrap(); + fn auth_packet_without_auth_matches_up_packet() { assert_eq!( - none.serialize().unwrap(), + auth_packet(None).serialize().unwrap(), parse(&UP_PACKET).serialize().unwrap() ); - - let mut pw = auth_packet(Some(password_auth(1, b"secret"))); - let before = pw.serialize().unwrap(); - pw.sign().unwrap(); - assert_eq!(pw.serialize().unwrap(), before); } - #[test] - fn verify_accepts_valid_keyed_packets() { - for (sent, expected) in [ - (md5_auth(true, 7, 9, MD5_KEY), md5_auth(true, 7, 0, MD5_KEY)), - ( - md5_auth(false, 7, 9, MD5_KEY), - md5_auth(false, 7, 0, MD5_KEY), - ), - ( - sha1_auth(true, 7, 9, SHA1_KEY), - sha1_auth(true, 7, 0, SHA1_KEY), - ), - ( - sha1_auth(false, 7, 9, SHA1_KEY), - sha1_auth(false, 7, 0, SHA1_KEY), - ), - ] { - assert!(over_the_wire(sent).verify(&expected).unwrap()); - } + #[rstest] + #[case::no_auth(auth_packet(None))] + #[case::simple_password(auth_packet(Some(password_auth(1, b"secret"))))] + fn sign_is_a_noop_without_keyed_auth(#[case] mut p: BfdPacket) { + let before = p.serialize().unwrap(); + p.sign().unwrap(); + assert_eq!(p.serialize().unwrap(), before); } - #[test] - fn verify_does_not_depend_on_expected_seq() { - let p = over_the_wire(md5_auth(true, 7, 9, MD5_KEY)); - assert!(p.verify(&md5_auth(true, 7, 12345, MD5_KEY)).unwrap()); + #[rstest] + #[case::md5_met(md5_auth(true, 7, 9, MD5_KEY), md5_auth(true, 7, 0, MD5_KEY), true)] + #[case::md5_non_met(md5_auth(false, 7, 9, MD5_KEY), md5_auth(false, 7, 0, MD5_KEY), true)] + #[case::sha1_met(sha1_auth(true, 7, 9, SHA1_KEY), sha1_auth(true, 7, 0, SHA1_KEY), true)] + #[case::sha1_non_met( + sha1_auth(false, 7, 9, SHA1_KEY), + sha1_auth(false, 7, 0, SHA1_KEY), + true + )] + #[case::ignores_expected_seq( + md5_auth(true, 7, 9, MD5_KEY), + md5_auth(true, 7, 12345, MD5_KEY), + true + )] + #[case::md5_wrong_key( + md5_auth(true, 7, 9, MD5_KEY), + md5_auth(true, 7, 0, flip(MD5_KEY, 15)), + false + )] + #[case::sha1_wrong_key( + sha1_auth(true, 7, 9, SHA1_KEY), + sha1_auth(true, 7, 0, flip(SHA1_KEY, 0)), + false + )] + #[case::md5_wrong_key_id(md5_auth(true, 7, 9, MD5_KEY), md5_auth(true, 8, 0, MD5_KEY), false)] + #[case::sha1_wrong_key_id( + sha1_auth(true, 7, 9, SHA1_KEY), + sha1_auth(true, 8, 0, SHA1_KEY), + false + )] + #[case::md5_meticulous_mismatch( + md5_auth(true, 7, 9, MD5_KEY), + md5_auth(false, 7, 0, MD5_KEY), + false + )] + #[case::sha1_meticulous_mismatch( + sha1_auth(false, 7, 9, SHA1_KEY), + sha1_auth(true, 7, 0, SHA1_KEY), + false + )] + #[case::md5_expected_sha1( + md5_auth(true, 7, 9, MD5_KEY), + sha1_auth(true, 7, 0, SHA1_KEY), + false + )] + #[case::md5_expected_password( + md5_auth(true, 7, 9, MD5_KEY), + password_auth(7, b"secret"), + false + )] + #[case::sha1_expected_md5( + sha1_auth(true, 7, 9, SHA1_KEY), + md5_auth(true, 7, 0, MD5_KEY), + false + )] + #[case::password_expected_md5( + password_auth(7, b"secret"), + md5_auth(true, 7, 0, MD5_KEY), + false + )] + #[case::password_match(password_auth(5, b"secret"), password_auth(5, b"secret"), true)] + #[case::password_wrong_case(password_auth(5, b"secret"), password_auth(5, b"secreT"), false)] + #[case::password_longer(password_auth(5, b"secret"), password_auth(5, b"secrets"), false)] + #[case::password_shorter(password_auth(5, b"secret"), password_auth(5, b"secre"), false)] + #[case::password_wrong_key_id(password_auth(5, b"secret"), password_auth(6, b"secret"), false)] + fn verify_over_the_wire( + #[case] sent: BfdAuth, + #[case] expected: BfdAuth, + #[case] accepted: bool, + ) { + assert_eq!(over_the_wire(sent).verify(&expected).unwrap(), accepted); } - #[test] - fn verify_rejects_wrong_key() { - let mut other = MD5_KEY; - other[15] ^= 1; - let p = over_the_wire(md5_auth(true, 7, 9, MD5_KEY)); - assert!(!p.verify(&md5_auth(true, 7, 0, other)).unwrap()); - - let mut other = SHA1_KEY; - other[0] ^= 1; - let p = over_the_wire(sha1_auth(true, 7, 9, SHA1_KEY)); - assert!(!p.verify(&sha1_auth(true, 7, 0, other)).unwrap()); - } - - #[test] - fn verify_rejects_wrong_key_id() { - let p = over_the_wire(md5_auth(true, 7, 9, MD5_KEY)); - assert!(!p.verify(&md5_auth(true, 8, 0, MD5_KEY)).unwrap()); - let p = over_the_wire(sha1_auth(true, 7, 9, SHA1_KEY)); - assert!(!p.verify(&sha1_auth(true, 8, 0, SHA1_KEY)).unwrap()); - } - - #[test] - fn verify_rejects_meticulous_mismatch() { - let p = over_the_wire(md5_auth(true, 7, 9, MD5_KEY)); - assert!(!p.verify(&md5_auth(false, 7, 0, MD5_KEY)).unwrap()); - let p = over_the_wire(sha1_auth(false, 7, 9, SHA1_KEY)); - assert!(!p.verify(&sha1_auth(true, 7, 0, SHA1_KEY)).unwrap()); - } - - #[test] - fn verify_rejects_auth_type_mismatch() { - let md5 = over_the_wire(md5_auth(true, 7, 9, MD5_KEY)); - assert!(!md5.verify(&sha1_auth(true, 7, 0, SHA1_KEY)).unwrap()); - assert!(!md5.verify(&password_auth(7, b"secret")).unwrap()); - let sha1 = over_the_wire(sha1_auth(true, 7, 9, SHA1_KEY)); - assert!(!sha1.verify(&md5_auth(true, 7, 0, MD5_KEY)).unwrap()); - let pw = over_the_wire(password_auth(7, b"secret")); - assert!(!pw.verify(&md5_auth(true, 7, 0, MD5_KEY)).unwrap()); - } - - #[test] - fn verify_rejects_tampered_packet() { - let sent = over_the_wire(md5_auth(true, 7, 9, MD5_KEY)); - let expected = md5_auth(true, 7, 0, MD5_KEY); - assert!(sent.verify(&expected).unwrap()); - - let mut p = sent.clone(); - p.my_disc = BfdDiscriminator(99); - assert!(!p.verify(&expected).unwrap()); - - let mut p = sent.clone(); - p.flags = p.flags.with_state(BfdState::Down as u8); - assert!(!p.verify(&expected).unwrap()); - - let mut p = sent.clone(); - p.desired_min_tx = BfdInterval::from_micros(1); - assert!(!p.verify(&expected).unwrap()); - - let mut p = sent.clone(); - p.auth.as_mut().unwrap().set_seq(10); - assert!(!p.verify(&expected).unwrap()); - - let mut p = sent; + #[rstest] + #[case::my_disc(|p: &mut BfdPacket| p.my_disc = BfdDiscriminator(99))] + #[case::state(|p: &mut BfdPacket| p.flags = p.flags.with_state(BfdState::Down as u8))] + #[case::desired_min_tx(|p: &mut BfdPacket| p.desired_min_tx = BfdInterval::from_micros(1))] + #[case::seq(|p: &mut BfdPacket| p.auth.as_mut().unwrap().set_seq(10))] + #[case::digest(|p: &mut BfdPacket| { if let Some(BfdAuth::KeyedMD5(d)) = p.auth.as_mut() { d.digest[0] ^= 1; } + })] + fn verify_rejects_tampered_packet(#[case] tamper: fn(&mut BfdPacket)) { + let mut p = over_the_wire(md5_auth(true, 7, 9, MD5_KEY)); + let expected = md5_auth(true, 7, 0, MD5_KEY); + assert!(p.verify(&expected).unwrap()); + tamper(&mut p); assert!(!p.verify(&expected).unwrap()); } - #[test] - fn verify_rejects_missing_auth() { - let expected = md5_auth(true, 7, 0, MD5_KEY); - assert!(!auth_packet(None).verify(&expected).unwrap()); - // A bit set but no section + #[rstest] + #[case::no_auth(auth_packet(None))] + #[case::a_bit_without_section({ let mut p = auth_packet(None); p.flags = p.flags.with_auth_present(true); - assert!(!p.verify(&expected).unwrap()); - } - - #[test] - fn verify_simple_password() { - let p = over_the_wire(password_auth(5, b"secret")); - assert!(p.verify(&password_auth(5, b"secret")).unwrap()); - assert!(!p.verify(&password_auth(5, b"secreT")).unwrap()); - assert!(!p.verify(&password_auth(5, b"secrets")).unwrap()); - assert!(!p.verify(&password_auth(5, b"secre")).unwrap()); - assert!(!p.verify(&password_auth(6, b"secret")).unwrap()); + p + })] + fn verify_rejects_missing_auth(#[case] p: BfdPacket) { + assert!(!p.verify(&md5_auth(true, 7, 0, MD5_KEY)).unwrap()); } } diff --git a/src/bin/rust-bfdd.rs b/src/bin/rust-bfdd.rs index 808ad8a..e81efb4 100644 --- a/src/bin/rust-bfdd.rs +++ b/src/bin/rust-bfdd.rs @@ -4,17 +4,20 @@ use rust_bfd::config::{Config, ConfigError, ResolvedConfig, ResolvedPeer}; use rust_bfd::events::{EventMessageSink, ScriptHookSink, StateChangeEvent}; use rust_bfd::{bfd::*, events::EventMessage}; use rust_bfd::{ - set_ttl_or_hop_limit, AtomicInstant, AtomicIntervalStats, AuthStats, BfdSessionStats, + bind_udp, require_hop_limit, scoped_socket_addr, set_ttl_or_hop_limit, AtomicInstant, + AtomicIntervalStats, AuthStats, BfdSessionStats, }; use std::{ - collections::{HashMap, HashSet}, + collections::{BTreeMap, HashMap, HashSet}, error::Error, fmt::Display, io::ErrorKind, - mem::swap, net::{IpAddr, SocketAddr}, path::PathBuf, - sync::{atomic::Ordering, Arc}, + sync::{ + atomic::{AtomicU32, AtomicU64, Ordering}, + Arc, + }, time::{Duration, Instant}, }; @@ -38,6 +41,8 @@ use atomic::Atomic; const CONTROL_PORT: u16 = 3784; const ECHO_PORT: u16 = 3785; +// RFC 5881 section 5 +const REQUIRED_HOP_LIMIT: u8 = 255; #[derive(Parser, Debug)] #[command(version, about = "BFD (RFC 5880) daemon")] @@ -45,27 +50,23 @@ struct Args { /// YAML configuration file [default: /etc/rust-bfd/config.yaml, ignored if absent] #[arg(short, long, value_name = "FILE", env = "BFD_CONFIG")] config: Option, - - /// Local IP address to bind to and use as the source of BFD control packets (repeatable). Replaces any bind - /// addresses from the config file or environment. - #[arg(short, long, value_name = "IP")] - bind: Vec, - - /// Peer IP address to establish a session with, using the default timers (repeatable). Added to the peers from - /// the config file. - #[arg(short, long = "peer", value_name = "IP")] - peers: Vec, } -// RFC 5881 section 4: the source port MUST be in the range 49152 to 65535. -const SOURCE_PORT_RANGE: std::ops::RangeInclusive = 49152..=65535; -const SOURCE_PORT_BIND_ATTEMPTS: usize = 32; +// RFC 5881 section 4: the source port MUST be in the range 49152 to 65535, and SHOULD be unique among all BFD sessions +// on the system. Ports are handed out from a process-wide counter, skipping any that are already in use. +const SOURCE_PORT_FIRST: u16 = 49152; +const SOURCE_PORT_COUNT: u32 = 65536 - SOURCE_PORT_FIRST as u32; +static NEXT_SOURCE_PORT: AtomicU32 = AtomicU32::new(0); -/// Bind a UDP socket on a random unused port in the RFC 5881 source port range, with TTL/hop limit 255. -async fn bind_control_socket(local_addr: IpAddr) -> io::Result { - for _ in 0..SOURCE_PORT_BIND_ATTEMPTS { - let port = rand::thread_rng().gen_range(SOURCE_PORT_RANGE); - match UdpSocket::bind(SocketAddr::new(local_addr, port)).await { +fn next_source_port() -> u16 { + SOURCE_PORT_FIRST + (NEXT_SOURCE_PORT.fetch_add(1, ORDERING) % SOURCE_PORT_COUNT) as u16 +} + +/// Bind a UDP socket on the next unused port in the RFC 5881 source port range, with TTL/hop limit 255. +async fn bind_control_socket(local_addr: IpAddr, interface: Option<&str>) -> io::Result { + for _ in 0..SOURCE_PORT_COUNT { + let port = next_source_port(); + match bind_udp(scoped_socket_addr(local_addr, port, interface)?, interface) { Ok(sock) => { set_ttl_or_hop_limit(&sock, 255)?; return Ok(sock); @@ -76,9 +77,7 @@ async fn bind_control_socket(local_addr: IpAddr) -> io::Result { } Err(io::Error::new( ErrorKind::AddrInUse, - format!( - "no free source port found for {local_addr} after {SOURCE_PORT_BIND_ATTEMPTS} attempts" - ), + format!("no free source port found for {local_addr}"), )) } @@ -115,26 +114,29 @@ struct BfdSessionState { control_sock: Arc, // immutable local_ip: IpAddr, // immutable and Copy peer_addr: IpAddr, // immutable and Copy - session_state: Atomic, // mutable by any thread - remote_session_state: Atomic, // mutable by rx thread - local_discr: BfdDiscriminator, // immutable and Copy - remote_discr: Atomic, // mutable by rx thread - local_diag: Atomic, // mutable by any thread - desired_min_tx_interval: Atomic, // mutable by any thread + interface: Option, // immutable + peer_dest: SocketAddr, // immutable and Copy; peer_addr:CONTROL_PORT with any scope + session_state: Atomic, // mutable by any thread + remote_session_state: Atomic, // mutable by rx thread + local_discr: BfdDiscriminator, // immutable and Copy + remote_discr: Atomic, // mutable by rx thread + local_diag: Atomic, // mutable by any thread + desired_min_tx_interval: Atomic, // mutable by any thread required_min_rx_interval: Atomic, // mutable by any thread - remote_min_rx_interval: Atomic, // mutable by rx thread - demand_mode: Atomic, // mutable by rx thread - remote_demand_mode: Atomic, // mutable by rx thread - detect_mult: Atomic, // mutable by control thread - rcv_auth_seq: Mutex, // must guard validation against parallel reception - xmit_auth_seq: Mutex, // must guard against OOO parallel transmission e.g. in rx task + remote_min_rx_interval: Atomic, // mutable by rx thread + demand_mode: Atomic, // mutable by rx thread + remote_demand_mode: Atomic, // mutable by rx thread + detect_mult: Atomic, // mutable by control thread + rcv_auth_seq: Atomic, // only accessed from the session task + xmit_auth_seq: Atomic, // only accessed from the session task auth_seq_known: Atomic, // mutable by rx thread? auth_type: Atomic, // immutable after construction detection_time: Atomic, // mutable by rx thread poll_mode: Atomic, // mutable by rx thread - rx_stats: AtomicIntervalStats, // reset each time the session enters Up + rx_stats: AtomicIntervalStats, // valid packets only; reset each time the session enters Up + rx_received: AtomicU64, // every packet received, including those discarded tx_stats: AtomicIntervalStats, // reset each time the session enters Up last_up: AtomicInstant, last_down: AtomicInstant, @@ -144,6 +146,7 @@ struct BfdSessionState { // TODO: hide the internal data structure behind a trait impl BfdSessionState { + #[allow(dead_code)] fn control_sock(&self) -> Arc { self.control_sock.clone() } @@ -153,6 +156,9 @@ impl BfdSessionState { fn peer_addr(&self) -> IpAddr { self.peer_addr } + fn interface(&self) -> Option<&str> { + self.interface.as_deref() + } fn session_state(&self) -> BfdState { self.session_state.load(ORDERING) @@ -179,6 +185,7 @@ impl BfdSessionState { fn demand_mode(&self) -> bool { self.demand_mode.load(ORDERING) } + #[allow(dead_code)] fn set_demand_mode(&self, value: bool) { self.demand_mode.store(value, ORDERING) } @@ -212,6 +219,7 @@ impl BfdSessionState { fn detect_mult(&self) -> u8 { self.detect_mult.load(ORDERING) } + #[allow(dead_code)] fn set_detect_mult(&self, value: u8) { self.detect_mult.store(value, ORDERING) } @@ -230,6 +238,7 @@ impl BfdSessionState { fn required_min_rx_interval(&self) -> BfdInterval { self.required_min_rx_interval.load(ORDERING) } + #[allow(dead_code)] fn set_required_min_rx_interval(&self, value: BfdInterval) { self.required_min_rx_interval.store(value, ORDERING) } @@ -239,7 +248,10 @@ impl BfdSessionState { fn set_detection_time(&self, value: BfdInterval) { self.detection_time.store(value, ORDERING) } - fn record_rx(&self) { + fn record_received(&self) { + self.rx_received.fetch_add(1, Ordering::Relaxed); + } + fn record_valid_rx(&self) { self.rx_stats.record(Instant::now()); } fn record_tx(&self) { @@ -264,17 +276,14 @@ impl BfdSessionState { } } -enum WatchdogReset { - ReceivedPacket, - Terminate, -} - struct BfdSession { state: BfdSessionState, periodic: BfdPeriodicSenderHandle, rx: mpsc::Receiver, - tx: mpsc::Sender, - rx_watchdog: Option>, + // When the Detection Time expires; armed by each valid packet received in Init or Up, otherwise None + detect_deadline: Option, + // When the last packet that was not discarded arrived; used to expire bfd.AuthSeqKnown + last_valid_rx: Option, cur_interval: BfdInterval, // Configured DesiredMinTxInterval; advertised only once Up (RFC 5880 6.8.3 requires >= 1s otherwise) configured_desired_min_tx: BfdInterval, @@ -282,6 +291,8 @@ struct BfdSession { effective_desired_min_tx: BfdInterval, event_dispatcher: EventDispatcherHandle, auth: Option, + // Whether the periodic sender has been told to run; cleared while bfd.RemoteMinRxInterval is zero + periodic_running: bool, } impl From<&BfdSessionState> for BfdSessionStats { @@ -294,6 +305,7 @@ impl From<&BfdSessionState> for BfdSessionStats { state: state.session_state(), last_diag: state.last_remote_diag(), rx: state.rx_stats.snapshot(), + rx_received: state.rx_received.load(Ordering::Relaxed), tx: state.tx_stats.snapshot(), last_up: state.last_up.load(), last_down: state.last_down.load(), @@ -304,6 +316,7 @@ impl From<&BfdSessionState> for BfdSessionStats { } } } +#[allow(dead_code)] enum PeriodicControlCommand { Stop, Start, @@ -312,6 +325,7 @@ enum PeriodicControlCommand { SendPollResponse, } +#[allow(dead_code)] enum SessionControlCommand { RxPacket(BfdPacket), TxControlPacket { @@ -320,7 +334,6 @@ enum SessionControlCommand { GetSessionStats { respond_to: oneshot::Sender, }, - ReceiveTimeout, Quit, } @@ -336,7 +349,8 @@ impl BfdSessionHandle { local_discr: BfdDiscriminator, event_dispatcher: EventDispatcherHandle, ) -> io::Result { - let control_sock = bind_control_socket(local_addr).await?; + let peer_dest = scoped_socket_addr(peer.address, CONTROL_PORT, peer.interface.as_deref())?; + let control_sock = bind_control_socket(local_addr, peer.interface.as_deref()).await?; let (tx, rx) = mpsc::channel(32); let new_self = Self { tx }; @@ -346,6 +360,7 @@ impl BfdSessionHandle { new_self.clone(), control_sock, local_addr, + peer_dest, peer, local_discr, event_dispatcher, @@ -397,8 +412,9 @@ struct BfdPeriodicSender { fn jittered_delay(interval: time::Duration, detect_mult: u8) -> time::Duration { // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.7 - let min_percent = if detect_mult == 1 { 90 } else { 75 }; - rand::thread_rng().gen_range(interval * min_percent / 100..=interval) + let min_percent = 75; + let max_percent = if detect_mult == 1 { 90 } else { 100 }; + rand::thread_rng().gen_range(interval * min_percent / 100..=interval * max_percent / 100) } impl BfdPeriodicSender { @@ -421,21 +437,23 @@ impl BfdPeriodicSender { } async fn run(&mut self) { let mut running = true; - let mut next_tx = time::Instant::now() + self.next_delay(); + let mut last_tx = time::Instant::now(); + let mut next_tx = last_tx + self.next_delay(); loop { tokio::select! { _ = time::sleep_until(next_tx), if running => { self.bfd.transmit_control_packet(false).await.unwrap(); - next_tx = time::Instant::now() + self.next_delay(); + last_tx = time::Instant::now(); + next_tx = last_tx + self.next_delay(); }, Some(cmd) = self.rx.recv() => { match cmd { PeriodicControlCommand::Quit => { debug!("Closing periodic packet sender"); return}, PeriodicControlCommand::Stop => { debug!("Stopping periodic packets"); - running= false} - , + running= false + }, PeriodicControlCommand::Start => { debug!("Starting periodic packets"); running = true; @@ -444,7 +462,7 @@ impl BfdPeriodicSender { PeriodicControlCommand::SetMinInterval(i) => { self.cur_interval = i; debug!("Updating transmit interval to {}ms", Duration::from(i).as_millis()); - next_tx = time::Instant::now() + self.next_delay(); + next_tx = last_tx + self.next_delay(); }, PeriodicControlCommand::SendPollResponse => { debug!("Sending poll response"); @@ -458,11 +476,13 @@ impl BfdPeriodicSender { } impl BfdSession { + #[allow(clippy::too_many_arguments)] fn new( rx: mpsc::Receiver, handle: BfdSessionHandle, control_sock: UdpSocket, local_addr: IpAddr, + peer_dest: SocketAddr, peer: ResolvedPeer, local_discr: BfdDiscriminator, event_dispatcher: EventDispatcherHandle, @@ -487,18 +507,21 @@ impl BfdSession { // Incoming packets will come over the channel from the mux, since they don't send to the reciprocal port Self { rx, - tx: handle.tx, periodic, - rx_watchdog: None, + detect_deadline: None, + last_valid_rx: None, cur_interval: BfdInterval::from_secs(1), configured_desired_min_tx, effective_desired_min_tx: slow_desired_min_tx, event_dispatcher, auth, + periodic_running: true, state: BfdSessionState { control_sock: Arc::new(control_sock), local_ip: local_addr, peer_addr: peer.address, + interface: peer.interface.clone(), + peer_dest, session_state: Atomic::new(BfdState::default()), remote_session_state: Atomic::new(BfdState::default()), local_discr, @@ -506,18 +529,19 @@ impl BfdSession { local_diag: Atomic::new(BfdDiagnostic::None), desired_min_tx_interval: Atomic::new(slow_desired_min_tx), required_min_rx_interval: Atomic::new(peer.required_min_rx), - remote_min_rx_interval: Atomic::new(BfdInterval::from_millis(300)), + remote_min_rx_interval: Atomic::new(BfdInterval::from_micros(1)), demand_mode: Atomic::new(false), remote_demand_mode: Atomic::new(false), detect_mult: Atomic::new(peer.detect_mult), - rcv_auth_seq: Mutex::new(0), - xmit_auth_seq: Mutex::new(rng.gen()), + rcv_auth_seq: Atomic::new(0), + xmit_auth_seq: Atomic::new(rng.gen()), auth_seq_known: Atomic::new(false), auth_type: Atomic::new(auth_type), detection_time: Atomic::new(BfdInterval::from_secs(0)), poll_mode: Atomic::new(false), rx_stats: AtomicIntervalStats::new(), + rx_received: AtomicU64::new(0), tx_stats: AtomicIntervalStats::new(), last_up: AtomicInstant::new(), last_down: AtomicInstant::new(), @@ -537,6 +561,7 @@ impl BfdSession { remote_discr: self.state.remote_discr(), local_ip: self.state.local_ip(), remote_ip: self.state.peer_addr(), + interface: self.state.interface().map(str::to_owned), from_state: self.state.session_state(), to_state: new_state, })) @@ -551,9 +576,6 @@ impl BfdSession { match (self.state.session_state(), new_state) { (BfdState::Up, BfdState::AdminDown | BfdState::Down | BfdState::Init) => { self.state.mark_down(); - if let Some(watchdog) = self.rx_watchdog.as_mut() { - watchdog.send(WatchdogReset::Terminate).await.unwrap(); - }; // When bfd.SessionState is not Up, the system MUST set bfd.DesiredMinTxInterval to a value of not // less than one second (1,000,000 microseconds). This is intended to ensure that the bandwidth // consumed by BFD sessions that are not Up is negligible, particularly in the case where a neighbor @@ -568,15 +590,14 @@ impl BfdSession { } (BfdState::AdminDown | BfdState::Down | BfdState::Init, BfdState::Up) => { self.state.mark_up(); - self.start_watchdog().await; self.state.set_local_diag(BfdDiagnostic::None); // This doesn't seem to be required by the spec but seems sensible and at least FRR does it. - // Advertise the configured interval now, but per section 6.8.3 keep transmitting at the old (slower) - // rate until a Poll Sequence confirms the peer has seen the change. + // Section 6.8.3: a decrease in bfd.DesiredMinTxInterval takes effect immediately; only an + // increase must wait for the Poll Sequence to complete. Since we never hold the + // configured value below the slow rate while Down, this is always a decrease or no change. self.state .set_desired_min_tx_interval(self.configured_desired_min_tx); if self.configured_desired_min_tx < self.effective_desired_min_tx { self.state.set_poll_mode(true); - } else { self.set_effective_desired_min_tx(self.configured_desired_min_tx); self.update_transmit_interval().await; } @@ -590,19 +611,12 @@ impl BfdSession { self.transmit_control_packet(false).await; } - async fn auth_stats(&self) -> Option { + fn auth_stats(&self) -> Option { let auth = self.auth.as_ref()?; let uses_seq = !matches!(auth, BfdAuth::SimplePassword(_)); - let rcv_seq = if uses_seq && self.state.auth_seq_known() { - Some(*self.state.rcv_auth_seq.lock().await) - } else { - None - }; - let xmit_seq = if uses_seq { - Some(*self.state.xmit_auth_seq.lock().await) - } else { - None - }; + let rcv_seq = (uses_seq && self.state.auth_seq_known()) + .then(|| self.state.rcv_auth_seq.load(ORDERING)); + let xmit_seq = uses_seq.then(|| self.state.xmit_auth_seq.load(ORDERING)); Some(AuthStats { auth_type: self.state.auth_type(), key_id: auth.key_id(), @@ -612,16 +626,32 @@ impl BfdSession { } async fn run(&mut self) { - while let Some(cmd) = self.rx.recv().await { - let mut missed_detect_times = 0; + loop { + let deadline = self.detect_deadline; + // Wait for a command or the deadline to expire; always check the command first if we have both. + // + // Deadline is updated in `receive_control_packet` + let cmd = tokio::select! { + biased; + cmd = self.rx.recv() => cmd, + _ = async { + match deadline { + Some(d) => time::sleep_until(d).await, + None => future::pending().await, + } + } => { + self.detection_timeout().await; + continue; + } + }; + let Some(cmd) = cmd else { break }; match cmd { SessionControlCommand::Quit => return, SessionControlCommand::RxPacket(packet) => { - missed_detect_times = 0; self.receive_control_packet(&packet).await; } SessionControlCommand::GetSessionStats { respond_to } => { - let auth = self.auth_stats().await; + let auth = self.auth_stats(); let stats = BfdSessionStats::from(&self.state) .with_base_interval(self.cur_interval) .with_auth(auth); @@ -630,19 +660,39 @@ impl BfdSession { SessionControlCommand::TxControlPacket { poll_response } => { self.transmit_control_packet(poll_response).await } - SessionControlCommand::ReceiveTimeout => { - self.state.set_local_diag(BfdDiagnostic::TimeExpired); - missed_detect_times += 1; - self.transition(BfdState::Down).await; - } - } - if missed_detect_times == 2 { - self.state.set_auth_seq_known(false); } } println!("Session command channel closed"); } + // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.4 + async fn detection_timeout(&mut self) { + self.detect_deadline = None; + if !matches!(self.state.session_state(), BfdState::Init | BfdState::Up) { + return; + } + info!( + "Peer {} timed out after {}", + self.state.peer_addr(), + self.state.detection_time() + ); + self.state.set_local_diag(BfdDiagnostic::TimeExpired); + self.state.set_remote_discr(BfdDiscriminator(0)); + // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.18 + self.state + .set_remote_min_rx_interval(BfdInterval::from_micros(1)); + self.update_transmit_interval().await; + if !self.periodic_running { + self.periodic + .tx + .send(PeriodicControlCommand::Start) + .await + .unwrap(); + self.periodic_running = true; + } + self.transition(BfdState::Down).await; + } + async fn transmit_control_packet(&mut self, poll_response: bool) { let mut packet = BfdPacket { flags: BfdFlags(0) @@ -668,16 +718,15 @@ impl BfdSession { auth: self.auth.clone(), // put configured method and key into packet }; let socket = self.state.control_sock.clone(); - let dest = self.state.peer_addr; + let dest = self.state.peer_dest; - // Held until the packet is sent so sequence numbers hit the wire in order - let mut xmit_seq = match packet.auth { - Some(_) => Some(self.state.xmit_auth_seq.lock().await), - None => None, - }; - if let (Some(auth), Some(seq)) = (&mut packet.auth, xmit_seq.as_mut()) { - **seq = seq.wrapping_add(1); - auth.set_seq(**seq); + if let Some(auth) = &mut packet.auth { + let seq = self + .state + .xmit_auth_seq + .fetch_add(1, ORDERING) + .wrapping_add(1); + auth.set_seq(seq); } packet.sign().unwrap(); @@ -685,77 +734,16 @@ impl BfdSession { debug!("tx packet: {:?}", packet); if let Err(e) = socket - .send_to( - packet.serialize().unwrap().as_ref(), - SocketAddr::new(dest, CONTROL_PORT), - ) + .send_to(packet.serialize().unwrap().as_ref(), dest) .await { - warn!( - "Error sending packet to {:?}:{} ({:?})", - dest, CONTROL_PORT, e - ); - } - } - - async fn start_watchdog(&mut self) { - let (tx, mut rx) = mpsc::channel(1); - let cmd_tx = self.tx.clone(); - let duration = self.state.detection_time().into(); - let peer_ip = self.state.peer_addr(); - - tokio::spawn(async move { - let mut running = true; - while running { - match tokio::time::timeout(duration, async { rx.recv().await }).await { - Ok(Some(WatchdogReset::ReceivedPacket)) => { - debug!("Packet received, watchdog ok") - } - Ok(Some(WatchdogReset::Terminate)) | Ok(None) => { - debug!("Watchdog terminating"); - running = false - } - Err(_) => { - info!( - "Peer {} timed out after {}ms", - peer_ip, - duration.as_millis() - ); - cmd_tx - .send(SessionControlCommand::ReceiveTimeout) - .await - .unwrap() - } - } - } - }); - let mut temporary = Some(tx); - swap(&mut temporary, &mut self.rx_watchdog); - if let Some(old_watchdog) = temporary.as_mut() { - debug!( - "Updating old watchdog with new detection time ({}ms)", - duration.as_millis() - ); - old_watchdog - .send(WatchdogReset::Terminate) - .await - .unwrap_or(()) + warn!("Error sending packet to {} ({:?})", dest, e); } } // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.6 async fn receive_control_packet(&mut self, p: &BfdPacket) { - // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.4 - // - // If Demand mode is not active, and a period of time equal to the - // Detection Time passes without receiving a BFD Control packet from the - // remote system, and bfd.SessionState is Init or Up, the session has - // gone down -- the local system MUST set bfd.SessionState to Down and - // bfd.LocalDiag to 1 (Control Detection Time Expired). - if let Some(watchdog) = self.rx_watchdog.as_ref() { - let _ = watchdog.send(WatchdogReset::ReceivedPacket).await; - } - self.state.record_rx(); + self.state.record_received(); let received_state = match p.flags.state() { Err(_) => { warn!("Invalid state, discarding"); @@ -830,30 +818,33 @@ impl BfdSession { // authentication type in use (bfd.AuthType). This may cause the packet to be discarded. if let Some(expected) = self.auth.as_ref().filter(|_| p.flags.auth_present()) { let received_seq = p.auth.as_ref().and_then(BfdAuth::seq); - let mut rcv_auth_seq = self.state.rcv_auth_seq.lock().await; + + // bfd.AuthSeqKnown MUST be set to zero after no packets have been received on this session for at least + // twice the Detection Time (RFC 5880 6.8.1). Discarded packets don't count as received. + if self.state.auth_seq_known() { + let expiry = Duration::from(self.state.detection_time()) * 2; + if self.last_valid_rx.is_none_or(|t| t.elapsed() >= expiry) { + debug!( + "Peer {} authentication sequence expired", + self.state.peer_addr() + ); + self.state.set_auth_seq_known(false); + } + } if let Some(seq) = received_seq { // If bfd.AuthSeqKnown is 1, examine the Sequence Number field. [...] if the sequence number lies // outside of the valid range the received packet MUST be discarded. if self.state.auth_seq_known() { - if !seq_in_window( - *rcv_auth_seq, - seq, - p.flags.detect_mult(), - expected.meticulous(), - ) { + let last = self.state.rcv_auth_seq.load(ORDERING); + if !seq_in_window(last, seq, p.flags.detect_mult(), expected.meticulous()) { warn!( "Got packet with out of window sequence number {} (last {}), discarding", - seq, *rcv_auth_seq + seq, last ); return; } - } else { - // Otherwise (bfd.AuthSeqKnown is 0), set bfd.AuthSeqKnown to 1. - self.state.set_auth_seq_known(true); } - // bfd.RcvAuthSeq is set to the Sequence Number field. - *rcv_auth_seq = seq; } match p.verify(expected) { @@ -870,6 +861,14 @@ impl BfdSession { return; } } + + // Deviation from the literal order in RFC 5880 6.7.3/6.7.4: bfd.AuthSeqKnown and bfd.RcvAuthSeq are only + // updated once the digest has verified, so a forged packet cannot move the replay window (as in BIRD, + // FRR and VPP). + if let Some(seq) = received_seq { + self.state.set_auth_seq_known(true); + self.state.rcv_auth_seq.store(seq, ORDERING); + } } // Set bfd.RemoteDiscr to the value of My Discriminator. @@ -885,7 +884,7 @@ impl BfdSession { .set_last_remote_diag(p.flags.diag().unwrap_or(BfdDiagnostic::Reserved)); // If the Required Min Echo RX Interval field is zero, the transmission of Echo packets, if any, MUST cease. - if p.required_min_echo_rx == BfdInterval::from_secs(0) { + if p.required_min_echo_rx == BfdInterval::ZERO { // TODO: implement echo thread } // If a Poll Sequence is being transmitted by the local system and the Final (F) bit in the received packet is @@ -907,6 +906,7 @@ impl BfdSession { return; } + // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.6 // If received state is AdminDown if received_state == BfdState::AdminDown { // If bfd.SessionState is not Down @@ -948,32 +948,59 @@ impl BfdSession { } BfdState::AdminDown => unreachable!("unexpected AdminDown"), // AdminDown is discarded earlier } - - // Check to see if Demand mode should become active or not (see section 6.6). - // - we don't use demand mode - - // If bfd.RemoteDemandMode is 1, bfd.SessionState is Up, and bfd.RemoteSessionState is Up, Demand mode is - // active on the remote system and - if self.state.remote_demand_mode() - && self.state.session_state() == BfdState::Up - && self.state.remote_session_state() == BfdState::Up - { - // the local system MUST cease the periodic transmission of BFD Control packets (see section 6.8.7). - self.periodic - .tx - .send(PeriodicControlCommand::Stop) - .await - .unwrap(); - } - - // If the Poll (P) bit is set, send a BFD Control packet to the remote system with the Poll (P) bit clear, - // and the Final (F) bit set (see section 6.8.7). - if p.flags.poll() { - self.transmit_control_packet(true).await; - } - // If the packet was not discarded, it has been received for purposes of the Detection Time expiration rules - // in section 6.8.4. } + + // Check to see if Demand mode should become active or not (see section 6.6). + // - we don't use demand mode + + // If bfd.RemoteDemandMode is 1, bfd.SessionState is Up, and bfd.RemoteSessionState is Up, Demand mode is + // active on the remote system and the local system MUST cease the periodic transmission of BFD Control + // packets (see section 6.8.7). + // + // If bfd.RemoteDemandMode is 0, or bfd.SessionState is not Up, or bfd.RemoteSessionState is not Up, Demand + // mode is not active on the remote system and the local system MUST send periodic BFD Control packets (see + // section 6.8.7). + // + // 6.8.7 additionally: a system MUST NOT periodically transmit BFD Control packets if + // bfd.RemoteMinRxInterval is zero. + let remote_demand_active = self.state.remote_demand_mode() + && self.state.session_state() == BfdState::Up + && self.state.remote_session_state() == BfdState::Up; + let periodic = + !remote_demand_active && self.state.remote_min_rx_interval() != BfdInterval::ZERO; + if periodic != self.periodic_running { + debug!( + "Peer {} periodic transmission running: {}", + self.state.peer_addr(), + periodic + ); + let cmd = if periodic { + PeriodicControlCommand::Start + } else { + PeriodicControlCommand::Stop + }; + self.periodic.tx.send(cmd).await.unwrap(); + self.periodic_running = periodic; + } + + // If the Poll (P) bit is set, send a BFD Control packet to the remote system with the Poll (P) bit clear, + // and the Final (F) bit set (see section 6.8.7). + if p.flags.poll() { + self.transmit_control_packet(true).await; + } + + // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.4 + // + // If Demand mode is not active, and a period of time equal to the Detection Time passes without receiving a + // BFD Control packet from the remote system, and bfd.SessionState is Init or Up, the session has gone down -- + // the local system MUST set bfd.SessionState to Down and bfd.LocalDiag to 1 (Control Detection Time Expired). + // + // If the packet was not discarded, it has been received for purposes of the Detection Time expiration rules. + self.state.record_valid_rx(); + self.last_valid_rx = Some(Instant::now()); + self.detect_deadline = (!remote_demand_active + && matches!(self.state.session_state(), BfdState::Init | BfdState::Up)) + .then(|| time::Instant::now() + Duration::from(self.state.detection_time())); } fn set_effective_desired_min_tx(&mut self, value: BfdInterval) { @@ -1040,7 +1067,6 @@ impl BfdSession { old, self.state.detection_time() ); - self.start_watchdog().await } } } @@ -1054,6 +1080,7 @@ enum EventDispatcherCommand { struct EventDispatcher { event_sinks: Vec>, event_sink_handles: Vec>, + #[allow(dead_code)] tx: mpsc::Sender, rx: mpsc::Receiver, // TODO: there must be a better way to do this } @@ -1126,75 +1153,165 @@ impl EventDispatcherHandle { } } +/// Vends local discriminators that are unique across every `Bfdd` sharing the allocator (RFC 5880 section 6.8.1). +#[derive(Clone, Default)] +struct DiscriminatorAllocator { + issued: Arc>>, +} + +impl DiscriminatorAllocator { + fn allocate(&self) -> BfdDiscriminator { + let mut issued = self.issued.lock().unwrap(); + let mut rng = rand::thread_rng(); + loop { + let discr = BfdDiscriminator(rng.gen()); + if discr.0 != 0 && issued.insert(discr) { + return discr; + } + } + } +} + +/// What one `Bfdd` listens on: a local address, optionally on a single interface. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +struct BfddKey { + local: IpAddr, + interface: Option, +} + +impl Display for BfddKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.interface { + Some(interface) => write!(f, "{}%{}", self.local, interface), + None => write!(f, "{}", self.local), + } + } +} + +/// Group `peers` by local address and interface: the set of instances to run, in key order. +fn peers_by_local(peers: Vec) -> BTreeMap> { + let mut groups: BTreeMap> = BTreeMap::new(); + for peer in peers { + let key = BfddKey { + local: peer.local, + interface: peer.interface.clone(), + }; + groups.entry(key).or_default().push(peer); + } + groups +} + +/// Commands accepted by a running `Bfdd`. +enum BfddCommand { + GetSessions { + respond_to: oneshot::Sender>, + }, +} + +#[derive(Clone)] +struct BfddHandle { + key: BfddKey, + tx: mpsc::Sender, +} + +impl BfddHandle { + /// Stats for every session of the instance, sorted by remote address. `None` if the instance has stopped. + async fn get_sessions(&self) -> Option> { + let (send, recv) = oneshot::channel(); + self.tx + .send(BfddCommand::GetSessions { respond_to: send }) + .await + .ok()?; + recv.await.ok() + } +} + +/// Indented, one block per session, each line preceded by a newline. +fn format_session_report(stats: &[BfdSessionStats]) -> String { + stats + .iter() + .flat_map(|s| { + s.to_string() + .lines() + .map(|l| format!("\n {l}")) + .collect::>() + }) + .collect() +} + +/// Runs the sessions of one local address and interface, over a single control socket. struct Bfdd { - local: SocketAddr, + key: BfddKey, peers: Vec, - sessions_by_ip: HashMap<(IpAddr, IpAddr), BfdDiscriminator>, + sessions_by_ip: HashMap, sessions_by_discr: HashMap, // Sources we have already warned about unmatched packets from; cleared per source once a packet matches again unmatched_sources: std::sync::Mutex>, control_socket: Arc, + commands: mpsc::Receiver, + discriminators: DiscriminatorAllocator, event_dispatcher: EventDispatcherHandle, } impl Bfdd { - async fn new(config: ResolvedConfig) -> Result> { - let local = match config.bind.as_slice() { - [addr] => SocketAddr::new(*addr, CONTROL_PORT), - addrs => { - return Err(format!( - "{} bind addresses configured, but only one is currently supported", - addrs.len() - ) - .into()) - } + async fn new( + key: BfddKey, + peers: Vec, + discriminators: DiscriminatorAllocator, + event_dispatcher: EventDispatcherHandle, + ) -> io::Result<(Self, BfddHandle)> { + // TODO: Bind only the sockets we need for the configuration, including multihop. + let interface = key.interface.as_deref(); + let bind = scoped_socket_addr(key.local, CONTROL_PORT, interface)?; + info!("Binding on {}", key); + let control_socket = Arc::new(bind_udp(bind, interface)?); + // If BFD authentication is not in use on a session, all BFD Control packets for the session MUST be sent + // with a Time to Live (TTL) or Hop Limit value of 255. + set_ttl_or_hop_limit(&control_socket, REQUIRED_HOP_LIMIT)?; + // All received BFD Control packets that are demultiplexed to the session MUST be discarded if the received + // TTL or Hop Limit is not equal to 255. The kernel does so for the whole socket, which is equivalent. + // https://datatracker.ietf.org/doc/html/rfc5881#section-5 + require_hop_limit(&control_socket, REQUIRED_HOP_LIMIT)?; + let _echo_socket = bind_udp( + scoped_socket_addr(key.local, ECHO_PORT, interface)?, + interface, + )?; + + let (tx, commands) = mpsc::channel(8); + let handle = BfddHandle { + key: key.clone(), + tx, }; - let peers = config.peers; - let sessions_by_ip = HashMap::new(); - let sessions_by_discr = HashMap::new(); - // TODO: Bind only the sockets we need for the configuration, including multihop and run them in different tasks. - info!("Binding on {:?}", local); - let control_socket = Arc::new(UdpSocket::bind(local).await?); - // If BFD authentication is not in use on a session, all BFD Control packets for the session MUST be sent with a - // Time to Live (TTL) or Hop Limit value of 255. - set_ttl_or_hop_limit(&control_socket, 255)?; - let _echo_socket = Arc::new(UdpSocket::bind(SocketAddr::new(local.ip(), ECHO_PORT)).await?); - - let event_dispatcher = EventDispatcherHandle::new().await; - event_dispatcher - .add_sink(Box::new(ScriptHookSink::with_script_dir(config.hooks_dir))) - .await; - - Ok(Self { - local, - peers, - sessions_by_ip, - sessions_by_discr, - unmatched_sources: std::sync::Mutex::new(HashSet::new()), - control_socket, - event_dispatcher, - }) + Ok(( + Self { + key, + peers, + sessions_by_ip: HashMap::new(), + sessions_by_discr: HashMap::new(), + unmatched_sources: std::sync::Mutex::new(HashSet::new()), + control_socket, + commands, + discriminators, + event_dispatcher, + }, + handle, + )) } async fn start_peers(&mut self) -> io::Result<()> { - let mut rng = rand::thread_rng(); for peer in &self.peers { - let mut local_discr = BfdDiscriminator(0); - while local_discr.0 == 0 || self.sessions_by_discr.contains_key(&local_discr) { - local_discr = BfdDiscriminator(rng.gen()); - } + let local_discr = self.discriminators.allocate(); let session = BfdSessionHandle::new( - self.local.ip(), + self.key.local, peer.clone(), local_discr, self.event_dispatcher.clone(), ) .await?; - self.sessions_by_ip - .insert((self.local.ip(), peer.address), local_discr); + self.sessions_by_ip.insert(peer.address, local_discr); self.sessions_by_discr.insert(local_discr, session); } Ok(()) @@ -1214,7 +1331,7 @@ impl Bfdd { // source address field can change or the interface over which the packets are received can change, but // the packets will still be associated with the proper session). let our_disc = if packet.your_disc == BfdDiscriminator(0) { - if let Some(discr) = self.sessions_by_ip.get(&(self.local.ip(), addr.ip())) { + if let Some(discr) = self.sessions_by_ip.get(&addr.ip()) { // A restarted peer starts over with Your Discriminator of zero. We deliberately keep the existing // session: the RFC 5880 section 6.8.6 state machine takes it Down (diag: Neighbor signaled session // down) and bfd.RemoteDiscr is relearned from the new My Discriminator. @@ -1267,7 +1384,7 @@ impl Bfdd { .unwrap(); } } - async fn session_report(&self) -> String { + async fn session_stats(&self) -> Vec { let mut stats = future::join_all( self.sessions_by_discr .values() @@ -1276,14 +1393,17 @@ impl Bfdd { .await; stats.sort_by_key(|s| s.remote_ip); stats - .iter() - .flat_map(|s| { - s.to_string() - .lines() - .map(|l| format!("\n {l}")) - .collect::>() - }) - .collect() + } + async fn session_report(&self) -> String { + format_session_report(&self.session_stats().await) + } + async fn handle_command(&self, command: BfddCommand) { + match command { + BfddCommand::GetSessions { respond_to } => { + // The requester may have given up waiting; that's not an error here. + let _ = respond_to.send(self.session_stats().await); + } + } } async fn handle_datagram(&self, data: &[u8], addr: SocketAddr) { let Ok((_leftover, packet)) = BfdPacket::parse(data) else { @@ -1300,42 +1420,54 @@ impl Bfdd { self.rx_packet(addr, packet).await } async fn run(mut self) -> io::Result<()> { - info!("rust-bfd starting up"); self.start_peers().await?; - info!("configured sessions:{}", self.session_report().await); + info!( + "configured sessions on {}:{}", + self.key, + self.session_report().await + ); - let mut sigusr1 = signal(SignalKind::user_defined1())?; let mut buf = [0; 1024]; loop { - // TODO: All received BFD Control packets that are demultiplexed to the session MUST be discarded if - // the received TTL or Hop Limit is not equal to 255. Need raw sockets for this. - // // TODO: Maybe it is okay to receive in the session-specific socket instead of this global one? But // the RFC mentions that we must demux based on discriminator only. tokio::select! { - result = self.control_socket.recv_from(&mut buf) => match result { - Ok((len, addr)) => { - self.handle_datagram(&buf[..len], addr).await; - if log_enabled!(log::Level::Debug) { - debug!("configured sessions:{}", self.session_report().await); + result = self.control_socket.recv_from(&mut buf) => { + match result { + Ok((len, source)) => { + self.handle_datagram(&buf[..len], source).await; + if log_enabled!(log::Level::Debug) { + debug!( + "configured sessions on {}:{}", + self.key, + self.session_report().await + ); + } } + Err(e) => warn!("Error receiving from socket on {}: {e:?}", self.key), } - Err(e) => warn!("Error receiving from socket {e:?}"), }, - _ = sigusr1.recv() => { - info!("SIGUSR1 received"); - info!("configured sessions:{}", self.session_report().await); - } + Some(command) = self.commands.recv() => self.handle_command(command).await, } } } } +async fn log_session_reports(handles: &[BfddHandle]) { + for handle in handles { + match handle.get_sessions().await { + Some(stats) => info!( + "configured sessions on {}:{}", + handle.key, + format_session_report(&stats) + ), + None => warn!("Instance on {} is not running", handle.key), + } + } +} + fn load_config(args: Args) -> Result { - let mut config = Config::load(args.config.as_deref())?; - config.apply_env(|name| std::env::var(name).ok())?; - config.apply_cli(args.bind, args.peers); - config.resolve() + Config::load(args.config.as_deref())?.resolve() } #[tokio::main] @@ -1351,9 +1483,37 @@ async fn main() -> io::Result<()> { warn!("No peers configured"); } - match Bfdd::new(config).await { - Ok(bfdd) => bfdd.run().await, - Err(e) => Err(std::io::Error::other(e.to_string())), + info!("rust-bfd starting up"); + let discriminators = DiscriminatorAllocator::default(); + let event_dispatcher = EventDispatcherHandle::new().await; + event_dispatcher + .add_sink(Box::new(ScriptHookSink::with_script_dir(config.hooks_dir))) + .await; + + let mut sigusr1 = signal(SignalKind::user_defined1())?; + let mut instances = tokio::task::JoinSet::new(); + let mut handles = Vec::new(); + for (key, peers) in peers_by_local(config.peers) { + let (bfdd, handle) = + Bfdd::new(key, peers, discriminators.clone(), event_dispatcher.clone()).await?; + handles.push(handle); + instances.spawn(bfdd.run()); + } + loop { + tokio::select! { + // Instances only return on error; stop everything as soon as one does. + result = instances.join_next() => { + return match result { + Some(Ok(result)) => result, + Some(Err(e)) => Err(io::Error::other(e)), + None => Ok(()), + }; + } + _ = sigusr1.recv() => { + info!("SIGUSR1 received"); + log_session_reports(&handles).await; + } + } } } @@ -1361,72 +1521,73 @@ async fn main() -> io::Result<()> { mod tests { use super::*; - #[test] - fn seq_window_non_meticulous_bounds() { - // RFC 5880 6.7.3: [RcvAuthSeq, RcvAuthSeq + 3*DetectMult] - assert!(seq_in_window(100, 100, 3, false)); - assert!(seq_in_window(100, 101, 3, false)); - assert!(seq_in_window(100, 109, 3, false)); - assert!(!seq_in_window(100, 110, 3, false)); - assert!(!seq_in_window(100, 99, 3, false)); + use rstest::rstest; + + // RFC 5880 6.7.3: [RcvAuthSeq, RcvAuthSeq + 3*DetectMult]; 6.7.4 (meticulous): [RcvAuthSeq + 1, ...] + #[rstest] + #[case::non_meticulous_equal(100, 100, 3, false, true)] + #[case::non_meticulous_next(100, 101, 3, false, true)] + #[case::non_meticulous_upper_edge(100, 109, 3, false, true)] + #[case::non_meticulous_above_window(100, 110, 3, false, false)] + #[case::non_meticulous_behind(100, 99, 3, false, false)] + #[case::meticulous_equal(100, 100, 3, true, false)] + #[case::meticulous_next(100, 101, 3, true, true)] + #[case::meticulous_upper_edge(100, 109, 3, true, true)] + #[case::meticulous_above_window(100, 110, 3, true, false)] + #[case::meticulous_behind(100, 99, 3, true, false)] + #[case::mult_1_upper_edge(0, 3, 1, false, true)] + #[case::mult_1_above_window(0, 4, 1, false, false)] + #[case::mult_255_upper_edge(0, 255 * 3, 255, false, true)] + #[case::mult_255_above_window(0, 255 * 3 + 1, 255, false, false)] + #[case::wrap_non_meticulous_equal(u32::MAX, u32::MAX, 3, false, true)] + #[case::wrap_meticulous_equal(u32::MAX, u32::MAX, 3, true, false)] + #[case::wrap_meticulous_next(u32::MAX, 0, 3, true, true)] + #[case::wrap_meticulous_upper_edge(u32::MAX - 2, 6, 3, true, true)] + #[case::wrap_meticulous_above_window(u32::MAX - 2, 7, 3, true, false)] + #[case::wrap_meticulous_behind(u32::MAX - 2, u32::MAX - 3, 3, true, false)] + #[case::wrap_meticulous_max_behind_small(5, u32::MAX, 3, true, false)] + fn seq_window_bounds( + #[case] rcv: u32, + #[case] seq: u32, + #[case] detect_mult: u8, + #[case] meticulous: bool, + #[case] expected: bool, + ) { + assert_eq!(seq_in_window(rcv, seq, detect_mult, meticulous), expected); } - #[test] - fn seq_window_meticulous_bounds() { - // RFC 5880 6.7.4: [RcvAuthSeq + 1, RcvAuthSeq + 3*DetectMult] - assert!(!seq_in_window(100, 100, 3, true)); - assert!(seq_in_window(100, 101, 3, true)); - assert!(seq_in_window(100, 109, 3, true)); - assert!(!seq_in_window(100, 110, 3, true)); - assert!(!seq_in_window(100, 99, 3, true)); - } - - #[test] - fn seq_window_scales_with_detect_mult() { - assert!(seq_in_window(0, 3, 1, false)); - assert!(!seq_in_window(0, 4, 1, false)); - assert!(seq_in_window(0, 255 * 3, 255, false)); - assert!(!seq_in_window(0, 255 * 3 + 1, 255, false)); - } - - #[test] - fn seq_window_wraps_at_u32_max() { - assert!(seq_in_window(u32::MAX, u32::MAX, 3, false)); - assert!(!seq_in_window(u32::MAX, u32::MAX, 3, true)); - assert!(seq_in_window(u32::MAX, 0, 3, true)); - assert!(seq_in_window(u32::MAX - 2, 6, 3, true)); - assert!(!seq_in_window(u32::MAX - 2, 7, 3, true)); - assert!(!seq_in_window(u32::MAX - 2, u32::MAX - 3, 3, true)); - assert!(!seq_in_window(5, u32::MAX, 3, true)); - } - - #[test] - fn jitter_is_uniform_over_rfc_range() { - // RFC 5880 6.8.7: each interval is reduced by a random 0-25% (0-10% when DetectMult is 1), so delays are - // spread over [floor, interval] with a mean at the midpoint, not clustered at either end. + #[rstest] + #[case::mult_3(3, 225.0, 300.0)] + #[case::mult_1(1, 225.0, 270.0)] + fn jitter_is_uniform_over_rfc_range( + #[case] mult: u8, + #[case] floor_ms: f64, + #[case] ceil_ms: f64, + ) { + // RFC 5880 6.8.7: each interval is reduced by a random 0-25% (10-25% when DetectMult is 1), so delays are + // spread over [floor, ceiling] with a mean at the midpoint, not clustered at either end. let interval = time::Duration::from_millis(300); const SAMPLES: u32 = 20_000; - for (mult, floor_ms, mean_ms) in [(3u8, 225.0, 262.5), (1, 270.0, 285.0)] { - let delays: Vec = (0..SAMPLES) - .map(|_| jittered_delay(interval, mult).as_secs_f64() * 1000.0) - .collect(); - let mean = delays.iter().sum::() / f64::from(SAMPLES); - let min = delays.iter().copied().fold(f64::MAX, f64::min); - let max = delays.iter().copied().fold(f64::MIN, f64::max); - let width = 300.0 - floor_ms; - assert!( - (mean - mean_ms).abs() < 1.0, - "mult {mult}: mean {mean}ms, expected {mean_ms}ms" - ); - assert!( - min < floor_ms + width * 0.02, - "mult {mult}: never approached the floor (min {min}ms)" - ); - assert!( - max > 300.0 - width * 0.02, - "mult {mult}: never approached the interval (max {max}ms)" - ); - } + let mean_ms = (floor_ms + ceil_ms) / 2.0; + let delays: Vec = (0..SAMPLES) + .map(|_| jittered_delay(interval, mult).as_secs_f64() * 1000.0) + .collect(); + let mean = delays.iter().sum::() / f64::from(SAMPLES); + let min = delays.iter().copied().fold(f64::MAX, f64::min); + let max = delays.iter().copied().fold(f64::MIN, f64::max); + let width = ceil_ms - floor_ms; + assert!( + (mean - mean_ms).abs() < 1.0, + "mult {mult}: mean {mean}ms, expected {mean_ms}ms" + ); + assert!( + min >= floor_ms && min < floor_ms + width * 0.02, + "mult {mult}: min {min}ms not at the floor {floor_ms}ms" + ); + assert!( + max <= ceil_ms && max > ceil_ms - width * 0.02, + "mult {mult}: max {max}ms not at the ceiling {ceil_ms}ms" + ); } #[tokio::test] @@ -1458,37 +1619,37 @@ mod tests { } } - #[test] - fn jitter_within_rfc_bounds() { + #[rstest] + #[case::mult_3(3, 225, 300)] + #[case::mult_1(1, 225, 270)] + fn jitter_within_rfc_bounds(#[case] mult: u8, #[case] floor_ms: u64, #[case] ceil_ms: u64) { let interval = time::Duration::from_millis(300); - for (mult, floor_ms) in [(3, 225), (1, 270)] { - for _ in 0..1000 { - let d = jittered_delay(interval, mult); - assert!( - d >= time::Duration::from_millis(floor_ms), - "{d:?} below floor for mult {mult}" - ); - assert!(d <= interval, "{d:?} above interval"); - } + for _ in 0..1000 { + let d = jittered_delay(interval, mult); + assert!( + d >= time::Duration::from_millis(floor_ms), + "{d:?} below floor for mult {mult}" + ); + assert!( + d <= time::Duration::from_millis(ceil_ms), + "{d:?} above ceiling for mult {mult}" + ); } } #[test] - fn repeated_bind_and_peer_flags() { - let args = Args::try_parse_from([ - "rust-bfdd", - "-b", - "192.0.2.1", - "--bind", - "2001:db8::1", - "-p", - "192.0.2.2", - "--peer", - "2001:db8::2", - ]) - .unwrap(); - assert_eq!(args.bind.len(), 2); - assert_eq!(args.peers.len(), 2); + fn config_file_is_selectable() { + let args = Args::try_parse_from(["rust-bfdd", "-c", "/tmp/x.yaml"]).unwrap(); + assert_eq!(args.config, Some(PathBuf::from("/tmp/x.yaml"))); + } + + #[rstest] + #[case::short_peer("-p")] + #[case::long_peer("--peer")] + #[case::short_bind("-b")] + #[case::long_bind("--bind")] + fn other_flags_are_rejected(#[case] flag: &str) { + assert!(Args::try_parse_from(["rust-bfdd", flag, "192.0.2.1"]).is_err()); } use std::net::Ipv4Addr; @@ -1533,6 +1694,8 @@ mod tests { fn peer_cfg(desired_ms: u32, required_ms: u32, detect_mult: u8) -> ResolvedPeer { ResolvedPeer { address: PEER, + local: LOCAL, + interface: None, desired_min_tx: BfdInterval::from_millis(desired_ms), required_min_rx: BfdInterval::from_millis(required_ms), detect_mult, @@ -1560,6 +1723,13 @@ mod tests { p.flags = f(p.flags); p } + fn key() -> BfddKey { + BfddKey { + local: LOCAL, + interface: None, + } + } + async fn session( peer: ResolvedPeer, ) -> (BfdSession, mpsc::UnboundedReceiver) { @@ -1571,6 +1741,7 @@ mod tests { BfdSessionHandle { tx }, sock, LOCAL, + SocketAddr::new(peer.address, CONTROL_PORT), peer, BfdDiscriminator(LOCAL_DISCR), dispatcher, @@ -1661,13 +1832,14 @@ mod tests { assert_eq!((ev.from_state, ev.to_state), (BfdState::Init, BfdState::Up)); assert!(s.state.last_up.load().is_some()); assert_eq!(s.state.local_diag(), BfdDiagnostic::None); - // Advertise the fast interval now, but keep transmitting slowly until the poll sequence completes + // 6.8.3: the decrease takes effect immediately and a Poll Sequence confirms it with the peer assert_eq!( s.state.desired_min_tx_interval(), BfdInterval::from_millis(300) ); assert!(s.state.poll_mode()); - assert_eq!(s.cur_interval, BfdInterval::from_secs(1)); + assert_eq!(s.effective_desired_min_tx, BfdInterval::from_millis(300)); + assert_eq!(s.cur_interval, BfdInterval::from_millis(300)); let fin = with_flags(pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR), |f| { f.with_final_(true) @@ -1701,48 +1873,61 @@ mod tests { assert_eq!((ev.from_state, ev.to_state), (BfdState::Down, BfdState::Up)); } + #[rstest] + #[case::remote_up(BfdState::Up)] + #[case::remote_admin_down(BfdState::AdminDown)] #[tokio::test] - async fn down_ignores_remote_up_and_admin_down() { + async fn down_ignores_remote_state(#[case] remote: BfdState) { let (mut s, mut events) = session(peer_cfg(300, 300, 3)).await; - s.receive_control_packet(&pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR)) - .await; - assert_eq!(s.state.session_state(), BfdState::Down); - s.receive_control_packet(&pkt(BfdState::AdminDown, REMOTE_DISCR, LOCAL_DISCR)) + s.receive_control_packet(&pkt(remote, REMOTE_DISCR, LOCAL_DISCR)) .await; assert_eq!(s.state.session_state(), BfdState::Down); assert_no_event(&mut events).await; } + #[rstest] + #[case::remote_down_stays_init(BfdState::Down, BfdState::Init, None, None)] + #[case::remote_up_goes_up(BfdState::Up, BfdState::Up, None, Some(BfdState::Up))] + #[case::remote_admin_down_goes_down( + BfdState::AdminDown, + BfdState::Down, + Some(BfdDiagnostic::NeighborDown), + Some(BfdState::Down) + )] #[tokio::test] - async fn init_transitions() { + async fn init_transitions( + #[case] remote: BfdState, + #[case] expected: BfdState, + #[case] diag: Option, + #[case] event_to: Option, + ) { let (mut s, mut events) = session_in(BfdState::Init).await; - s.receive_control_packet(&pkt(BfdState::Down, REMOTE_DISCR, LOCAL_DISCR)) + s.receive_control_packet(&pkt(remote, REMOTE_DISCR, LOCAL_DISCR)) .await; - assert_eq!(s.state.session_state(), BfdState::Init); - assert_no_event(&mut events).await; - s.receive_control_packet(&pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR)) - .await; - assert_eq!(s.state.session_state(), BfdState::Up); - - let (mut s, mut events) = session_in(BfdState::Init).await; - s.receive_control_packet(&pkt(BfdState::AdminDown, REMOTE_DISCR, LOCAL_DISCR)) - .await; - assert_eq!(s.state.session_state(), BfdState::Down); - assert_eq!(s.state.local_diag(), BfdDiagnostic::NeighborDown); - let ev = next_event(&mut events).await; - assert_eq!( - (ev.from_state, ev.to_state), - (BfdState::Init, BfdState::Down) - ); + assert_eq!(s.state.session_state(), expected); + if let Some(diag) = diag { + assert_eq!(s.state.local_diag(), diag); + } + match event_to { + Some(to) => { + let ev = next_event(&mut events).await; + assert_eq!((ev.from_state, ev.to_state), (BfdState::Init, to)); + } + None => assert_no_event(&mut events).await, + } } + + #[rstest] + #[case::remote_down(BfdState::Down)] + #[case::remote_admin_down(BfdState::AdminDown)] #[tokio::test] - async fn up_goes_down_when_remote_goes_down() { + async fn up_goes_down_when_remote_leaves_up(#[case] remote: BfdState) { let (mut s, mut events) = session_in(BfdState::Up).await; s.receive_control_packet(&pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR)) .await; assert_no_event(&mut events).await; - s.receive_control_packet(&pkt(BfdState::Down, REMOTE_DISCR, LOCAL_DISCR)) + s.receive_control_packet(&pkt(remote, REMOTE_DISCR, LOCAL_DISCR)) .await; assert_eq!(s.state.session_state(), BfdState::Down); assert_eq!(s.state.local_diag(), BfdDiagnostic::NeighborDown); @@ -1755,16 +1940,6 @@ mod tests { assert!(!s.state.poll_mode()); } - #[tokio::test] - async fn up_goes_down_on_remote_admin_down() { - let (mut s, mut events) = session_in(BfdState::Up).await; - s.receive_control_packet(&pkt(BfdState::AdminDown, REMOTE_DISCR, LOCAL_DISCR)) - .await; - assert_eq!(s.state.session_state(), BfdState::Down); - assert_eq!(s.state.local_diag(), BfdDiagnostic::NeighborDown); - assert_eq!(next_event(&mut events).await.to_state, BfdState::Down); - } - #[tokio::test] async fn restarted_peer_relearns_discriminator() { let (mut s, mut events) = session_in(BfdState::Up).await; @@ -1785,64 +1960,138 @@ mod tests { s.receive_control_packet(&pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR)) .await; assert_eq!(s.state.session_state(), BfdState::Up); - // The Up transition resets the counters, then sends one packet announcing the new state - assert_eq!(s.state.rx_stats.snapshot().count(), 0); + // The Up transition resets the counters; the packet that caused it is then counted as valid + assert_eq!(s.state.rx_stats.snapshot().count(), 1); assert_eq!(s.state.tx_stats.snapshot().count(), 1); s.receive_control_packet(&pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR)) .await; - assert_eq!(s.state.rx_stats.snapshot().count(), 1); + assert_eq!(s.state.rx_stats.snapshot().count(), 2); } #[tokio::test] - async fn invalid_packets_are_discarded() { - type Mutation = fn(BfdPacket) -> BfdPacket; - let cases: [(&str, Mutation); 8] = [ - ("version", |p| with_flags(p, |f| f.with_vers(2))), - ("short length", |p| with_flags(p, |f| f.with_length(23))), - ("zero detect mult", |p| { - with_flags(p, |f| f.with_detect_mult(0)) - }), - ("multipoint", |p| with_flags(p, |f| f.with_multipoint(true))), - ("zero my discr", |mut p| { - p.my_disc = BfdDiscriminator(0); - p - }), - ("wrong your discr", |mut p| { - p.your_disc = BfdDiscriminator(LOCAL_DISCR + 1); - p - }), - ("zero your discr, not down", |mut p| { - p.your_disc = BfdDiscriminator(0); - p.flags = p.flags.with_state(BfdState::Up as u8); - p - }), - ("auth without auth in use", |p| { - with_flags(p, |f| f.with_auth_present(true).with_length(26)) - }), - ]; - for (name, mutate) in cases { - let (mut s, mut events) = session(peer_cfg(300, 300, 3)).await; - s.receive_control_packet(&mutate(pkt(BfdState::Down, REMOTE_DISCR, 0))) - .await; - assert_eq!(s.state.session_state(), BfdState::Down, "{name}"); - assert_eq!(s.state.remote_discr(), BfdDiscriminator(0), "{name}"); - assert_eq!( - s.state.remote_min_rx_interval(), - BfdInterval::from_millis(300), - "{name}" - ); - assert_no_event(&mut events).await; - } + async fn discarded_packets_are_received_but_not_valid() { + let (mut s, _events) = session_in(BfdState::Up).await; + let before = s.state.rx_stats.snapshot().count(); + let received = s.state.rx_received.load(Ordering::Relaxed); + s.receive_control_packet(&pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR)) + .await; + let mut bad = pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR); + bad.flags = bad.flags.with_detect_mult(0); + s.receive_control_packet(&bad).await; + assert_eq!(s.state.rx_stats.snapshot().count(), before + 1); + assert_eq!(s.state.rx_received.load(Ordering::Relaxed), received + 2); } + #[rstest] + #[case::version(|p| with_flags(p, |f| f.with_vers(2)))] + #[case::short_length(|p| with_flags(p, |f| f.with_length(23)))] + #[case::zero_detect_mult(|p| with_flags(p, |f| f.with_detect_mult(0)))] + #[case::multipoint(|p| with_flags(p, |f| f.with_multipoint(true)))] + #[case::zero_my_discr(|mut p: BfdPacket| { + p.my_disc = BfdDiscriminator(0); + p + })] + #[case::wrong_your_discr(|mut p: BfdPacket| { + p.your_disc = BfdDiscriminator(LOCAL_DISCR + 1); + p + })] + #[case::zero_your_discr_not_down(|mut p: BfdPacket| { + p.your_disc = BfdDiscriminator(0); + p.flags = p.flags.with_state(BfdState::Up as u8); + p + })] + #[case::auth_without_auth_in_use(|p| { + with_flags(p, |f| f.with_auth_present(true).with_length(26)) + })] + #[case::auth_length_below_minimum(|p| { + with_flags(p, |f| f.with_auth_present(true).with_length(25)) + })] #[tokio::test] - async fn auth_length_minimum_is_26() { - let (mut s, _events) = session(peer_cfg(300, 300, 3)).await; - let p = with_flags(pkt(BfdState::Down, REMOTE_DISCR, 0), |f| { - f.with_auth_present(true).with_length(25) - }); - s.receive_control_packet(&p).await; + async fn invalid_packets_are_discarded(#[case] mutate: fn(BfdPacket) -> BfdPacket) { + let (mut s, mut events) = session(peer_cfg(300, 300, 3)).await; + s.receive_control_packet(&mutate(pkt(BfdState::Down, REMOTE_DISCR, 0))) + .await; + assert_eq!(s.state.session_state(), BfdState::Down); assert_eq!(s.state.remote_discr(), BfdDiscriminator(0)); + assert_eq!( + s.state.remote_min_rx_interval(), + BfdInterval::from_micros(1) + ); + assert_no_event(&mut events).await; + } + + const SHA1_KEY: [u8; 20] = *b"0123456789abcdefghij"; + + async fn sha1_session() -> (BfdSession, mpsc::UnboundedReceiver) { + let (mut s, events) = session(peer_cfg(300, 300, 3)).await; + s.auth = Some(BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 { + meticulous: false, + key_id: 1, + reserved: 0, + seq: 0, + digest: SHA1_KEY, + })); + s.state.auth_type.store(BfdAuthType::KeyedSHA1, ORDERING); + (s, events) + } + + fn sha1_pkt(my: u32, seq: u32) -> BfdPacket { + let mut p = with_flags(pkt(BfdState::Down, my, 0), |f| { + f.with_auth_present(true).with_length(24 + 28) + }); + p.auth = Some(BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 { + meticulous: false, + key_id: 1, + reserved: 0, + seq, + digest: SHA1_KEY, + })); + p.sign().unwrap(); + p + } + + #[rstest] + #[case::expires_after_twice_detection_time(1900, true)] + #[case::holds_within_twice_detection_time(1700, false)] + #[tokio::test] + async fn out_of_window_sequence_is_discarded_until_it_expires( + #[case] idle_ms: u64, + #[case] accepted: bool, + ) { + let (mut s, _events) = sha1_session().await; + s.receive_control_packet(&sha1_pkt(REMOTE_DISCR, 1000)) + .await; + assert_eq!(s.state.remote_discr(), BfdDiscriminator(REMOTE_DISCR)); + assert!(s.state.auth_seq_known()); + + s.receive_control_packet(&sha1_pkt(REMOTE_DISCR + 1, 5000)) + .await; + assert_eq!(s.state.remote_discr(), BfdDiscriminator(REMOTE_DISCR)); + assert_eq!(s.state.rcv_auth_seq.load(ORDERING), 1000); + + // Detection time is 3 * 300ms; nothing valid for more than twice that + s.last_valid_rx = Some(Instant::now() - Duration::from_millis(idle_ms)); + s.receive_control_packet(&sha1_pkt(REMOTE_DISCR + 1, 5000)) + .await; + let (discr, seq) = if accepted { + (REMOTE_DISCR + 1, 5000) + } else { + (REMOTE_DISCR, 1000) + }; + assert_eq!(s.state.remote_discr(), BfdDiscriminator(discr)); + assert_eq!(s.state.rcv_auth_seq.load(ORDERING), seq); + } + + #[tokio::test] + async fn discarded_packets_do_not_arm_the_detection_timer() { + let (mut s, _events) = sha1_session().await; + let mut bad = sha1_pkt(REMOTE_DISCR, 1000); + if let Some(BfdAuth::KeyedSHA1(a)) = bad.auth.as_mut() { + a.digest[0] ^= 0xff; + } + s.receive_control_packet(&bad).await; + assert!(s.detect_deadline.is_none()); + assert!(s.last_valid_rx.is_none()); } #[tokio::test] @@ -1902,27 +2151,26 @@ mod tests { assert_eq!(s.cur_interval, BfdInterval::from_secs(1)); } + #[rstest] + #[case::saturates_on_remote_overflow(300, 255, &[(u32::MAX, u32::MAX)])] + #[case::uses_remote_mult_and_larger_interval(500, 5, &[(400_000, 2_500_000), (800_000, 4_000_000)])] #[tokio::test] - async fn detection_time_saturates_on_remote_overflow() { - let (mut s, _events) = session(peer_cfg(300, 300, 3)).await; + async fn detection_time( + #[case] required_min_rx_ms: u32, + #[case] remote_mult: u8, + #[case] steps: &[(u32, u32)], + ) { + let (mut s, _events) = session(peer_cfg(300, required_min_rx_ms, 3)).await; let mut p = pkt(BfdState::Down, REMOTE_DISCR, 0); - p.flags = p.flags.with_detect_mult(255); - p.desired_min_tx = BfdInterval::from_micros(u32::MAX); - s.receive_control_packet(&p).await; - assert_eq!(s.state.detection_time(), BfdInterval::from_micros(u32::MAX)); - } - - #[tokio::test] - async fn detection_time_uses_remote_mult_and_larger_interval() { - let (mut s, _events) = session(peer_cfg(300, 500, 3)).await; - let mut p = pkt(BfdState::Down, REMOTE_DISCR, 0); - p.flags = p.flags.with_detect_mult(5); - p.desired_min_tx = BfdInterval::from_millis(400); - s.receive_control_packet(&p).await; - assert_eq!(s.state.detection_time(), BfdInterval::from_millis(2500)); - p.desired_min_tx = BfdInterval::from_millis(800); - s.receive_control_packet(&p).await; - assert_eq!(s.state.detection_time(), BfdInterval::from_millis(4000)); + p.flags = p.flags.with_detect_mult(remote_mult); + for &(remote_desired_us, expected_us) in steps { + p.desired_min_tx = BfdInterval::from_micros(remote_desired_us); + s.receive_control_packet(&p).await; + assert_eq!( + s.state.detection_time(), + BfdInterval::from_micros(expected_us) + ); + } } #[tokio::test] async fn watchdog_expires_only_without_packets() { @@ -1974,11 +2222,11 @@ mod tests { #[tokio::test] async fn control_socket_uses_source_port_range_and_ttl_255() { - let a = bind_control_socket(LOCAL).await.unwrap(); - let b = bind_control_socket(LOCAL).await.unwrap(); + let a = bind_control_socket(LOCAL, None).await.unwrap(); + let b = bind_control_socket(LOCAL, None).await.unwrap(); for s in [&a, &b] { let addr = s.local_addr().unwrap(); - assert!(SOURCE_PORT_RANGE.contains(&addr.port()), "{addr}"); + assert!(addr.port() >= SOURCE_PORT_FIRST, "{addr}"); assert_eq!(addr.ip(), LOCAL); assert_eq!(s.ttl().unwrap(), 255); } @@ -1988,9 +2236,40 @@ mod tests { ); } + #[tokio::test] + async fn control_socket_ports_are_unique_across_local_addresses() { + let mut ports = HashSet::new(); + let mut socks = Vec::new(); + for local in [LOCAL, OTHER, LOCAL, OTHER] { + let s = bind_control_socket(local, None).await.unwrap(); + assert!(ports.insert(s.local_addr().unwrap().port())); + socks.push(s); + } + } + + #[tokio::test] + async fn control_socket_skips_ports_in_use() { + let start = NEXT_SOURCE_PORT.load(ORDERING); + let mut squatters = Vec::new(); + for n in start..start + 4 { + let port = SOURCE_PORT_FIRST + (n % SOURCE_PORT_COUNT) as u16; + if let Ok(s) = UdpSocket::bind((LOCAL, port)).await { + squatters.push(s); + } + } + let taken: HashSet = squatters + .iter() + .map(|s| s.local_addr().unwrap().port()) + .collect(); + for _ in 0..4 { + let s = bind_control_socket(LOCAL, None).await.unwrap(); + assert!(!taken.contains(&s.local_addr().unwrap().port())); + } + } + #[tokio::test] async fn control_socket_bind_error_is_propagated() { - let err = bind_control_socket(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1))) + let err = bind_control_socket(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1)), None) .await .unwrap_err(); assert_ne!(err.kind(), ErrorKind::AddrInUse); @@ -1999,40 +2278,90 @@ mod tests { const OTHER: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 3)); async fn bfdd() -> (Bfdd, mpsc::Receiver) { + let (d, _handle, rx) = bfdd_with_handle().await; + (d, rx) + } + + async fn bfdd_with_handle() -> (Bfdd, BfddHandle, mpsc::Receiver) { let (tx, rx) = mpsc::channel(8); + let (cmd_tx, commands) = mpsc::channel(8); let discr = BfdDiscriminator(LOCAL_DISCR); let d = Bfdd { - local: SocketAddr::new(LOCAL, CONTROL_PORT), + key: key(), peers: vec![peer_cfg(300, 300, 3)], - sessions_by_ip: HashMap::from([((LOCAL, PEER), discr)]), + sessions_by_ip: HashMap::from([(PEER, discr)]), sessions_by_discr: HashMap::from([(discr, BfdSessionHandle { tx })]), unmatched_sources: std::sync::Mutex::new(HashSet::new()), control_socket: Arc::new(UdpSocket::bind((LOCAL, 0)).await.unwrap()), + commands, + discriminators: DiscriminatorAllocator::default(), event_dispatcher: EventDispatcherHandle::new().await, }; - (d, rx) + ( + d, + BfddHandle { + key: key(), + tx: cmd_tx, + }, + rx, + ) + } + + #[tokio::test] + async fn get_sessions_returns_stats_sorted_by_remote() { + let (dispatcher, _events) = capture_dispatcher().await; + let (mut d, handle, _rx) = bfdd_with_handle().await; + d.sessions_by_discr.clear(); + // Inserted highest address first; the result must be ordered by address regardless + for (discr, remote) in [(1, OTHER), (2, PEER)] { + let mut peer = peer_cfg(300, 300, 3); + peer.address = remote; + let session = + BfdSessionHandle::new(LOCAL, peer, BfdDiscriminator(discr), dispatcher.clone()) + .await + .unwrap(); + d.sessions_by_discr.insert(BfdDiscriminator(discr), session); + } + let server = tokio::spawn(async move { + let command = d.commands.recv().await.unwrap(); + d.handle_command(command).await; + }); + + let stats = handle.get_sessions().await.unwrap(); + assert_eq!( + stats.iter().map(|s| s.remote_ip).collect::>(), + [PEER, OTHER] + ); + server.await.unwrap(); + } + + #[tokio::test] + async fn get_sessions_is_none_once_instance_is_gone() { + let (d, handle, _rx) = bfdd_with_handle().await; + drop(d); + assert!(handle.get_sessions().await.is_none()); } fn from(ip: IpAddr) -> SocketAddr { SocketAddr::new(ip, 49152) } + #[rstest] + #[case::zero_discr_known_source(BfdState::Down, 0, PEER, true)] + #[case::zero_discr_unknown_source(BfdState::Down, 0, OTHER, false)] + #[case::discr_known_source(BfdState::Up, LOCAL_DISCR, PEER, true)] + #[case::discr_ignores_source_address(BfdState::Up, LOCAL_DISCR, OTHER, true)] + #[case::unknown_discr(BfdState::Up, LOCAL_DISCR + 1, PEER, false)] #[tokio::test] - async fn demux_by_source_when_your_discr_is_zero() { + async fn demux_session_for_packet( + #[case] state: BfdState, + #[case] your_discr: u32, + #[case] source: IpAddr, + #[case] found: bool, + ) { let (d, _rx) = bfdd().await; - let p = pkt(BfdState::Down, REMOTE_DISCR, 0); - assert!(d.session_for_packet(&from(PEER), &p).is_some()); - assert!(d.session_for_packet(&from(OTHER), &p).is_none()); - } - - #[tokio::test] - async fn demux_by_discriminator_ignores_source_address() { - let (d, _rx) = bfdd().await; - let p = pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR); - assert!(d.session_for_packet(&from(PEER), &p).is_some()); - assert!(d.session_for_packet(&from(OTHER), &p).is_some()); - let p = pkt(BfdState::Up, REMOTE_DISCR, LOCAL_DISCR + 1); - assert!(d.session_for_packet(&from(PEER), &p).is_none()); + let p = pkt(state, REMOTE_DISCR, your_discr); + assert_eq!(d.session_for_packet(&from(source), &p).is_some(), found); } #[tokio::test] @@ -2059,30 +2388,73 @@ mod tests { } } + fn down_packet_bytes() -> Vec { + pkt(BfdState::Down, REMOTE_DISCR, 0).serialize().unwrap() + } + + #[rstest] + #[case::truncated(down_packet_bytes()[..23].to_vec(), PEER)] + #[case::empty(vec![], PEER)] + #[case::garbage(vec![0xff; 7], PEER)] + #[case::length_field_exceeds_datagram( + with_flags(pkt(BfdState::Down, REMOTE_DISCR, 0), |f| f.with_length(48)).serialize().unwrap(), + PEER + )] + #[case::unknown_source(down_packet_bytes(), OTHER)] #[tokio::test] - async fn bad_datagrams_are_dropped() { + async fn bad_datagrams_are_dropped(#[case] bytes: Vec, #[case] source: IpAddr) { let (d, mut rx) = bfdd().await; - let good = pkt(BfdState::Down, REMOTE_DISCR, 0).serialize().unwrap(); - d.handle_datagram(&good[..23], from(PEER)).await; - d.handle_datagram(&[], from(PEER)).await; - d.handle_datagram(&[0xff; 7], from(PEER)).await; - let long = with_flags(pkt(BfdState::Down, REMOTE_DISCR, 0), |f| f.with_length(48)); - d.handle_datagram(&long.serialize().unwrap(), from(PEER)) - .await; - let unknown = pkt(BfdState::Down, REMOTE_DISCR, 0); - d.handle_datagram(&unknown.serialize().unwrap(), from(OTHER)) - .await; + d.handle_datagram(&bytes, from(source)).await; assert!(rx.try_recv().is_err()); } - #[tokio::test] - async fn bfdd_rejects_multiple_bind_addresses() { - let cfg = ResolvedConfig { - bind: vec![LOCAL, PEER], - hooks_dir: PathBuf::from("/nonexistent"), - peers: vec![], - }; - let err = Bfdd::new(cfg).await.err().expect("should fail"); - assert!(err.to_string().contains("only one"), "{err}"); + #[test] + fn peers_are_grouped_by_local_address() { + let v6: IpAddr = "2001:db8::1".parse().unwrap(); + let peer6: IpAddr = "2001:db8::2".parse().unwrap(); + let mut p6 = peer_cfg(300, 300, 3); + p6.address = peer6; + p6.local = v6; + let mut p4b = peer_cfg(300, 300, 3); + p4b.address = OTHER; + + let groups = peers_by_local(vec![p6, peer_cfg(300, 300, 3), p4b]); + let summary: Vec<_> = groups + .iter() + .map(|(key, peers)| { + ( + key.local, + peers.iter().map(|p| p.address).collect::>(), + ) + }) + .collect(); + assert_eq!(summary, [(LOCAL, vec![PEER, OTHER]), (v6, vec![peer6])]); + assert!(peers_by_local(vec![]).is_empty()); } + + #[test] + fn peers_are_grouped_by_interface_too() { + let on = |iface: Option<&str>| ResolvedPeer { + interface: iface.map(String::from), + ..peer_cfg(300, 300, 3) + }; + let groups = peers_by_local(vec![on(Some("eth2")), on(None), on(Some("eth1")), on(None)]); + let keys: Vec<_> = groups.keys().map(ToString::to_string).collect(); + assert_eq!(keys, ["127.0.0.1", "127.0.0.1%eth1", "127.0.0.1%eth2"]); + assert_eq!(groups.values().map(Vec::len).collect::>(), [2, 1, 1]); + } + + #[test] + fn discriminators_are_unique_and_non_zero_across_clones() { + let a = DiscriminatorAllocator::default(); + let b = a.clone(); + let issued: HashSet<_> = (0..1000) + .map(|i| if i % 2 == 0 { &a } else { &b }.allocate()) + .collect(); + assert_eq!(issued.len(), 1000); + assert!(!issued.contains(&BfdDiscriminator(0))); + assert_eq!(a.issued.lock().unwrap().len(), 1000); + } + + mod rfc; } diff --git a/src/bin/tests/rfc.rs b/src/bin/tests/rfc.rs new file mode 100644 index 0000000..b0f2761 --- /dev/null +++ b/src/bin/tests/rfc.rs @@ -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; + +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 { + 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 { + 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 { + 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 +} diff --git a/src/bin/tests/rfc/auth.rs b/src/bin/tests/rfc/auth.rs new file mode 100644 index 0000000..96d49e6 --- /dev/null +++ b/src/bin/tests/rfc/auth.rs @@ -0,0 +1,312 @@ +use super::*; + +fn digest_with_key(raw: &[u8], key: &[u8], at: usize) -> Vec { + 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(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::(&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_auth(false, 7, 0), 24, 2).await; +} + +#[tokio::test] +async fn tx_meticulous_keyed_md5() { + check_keyed_tx::(md5_auth(true, 7, 0), 24, 3).await; +} + +#[tokio::test] +async fn tx_keyed_sha1() { + check_keyed_tx::(sha1_auth(false, 7, 0), 28, 4).await; +} + +#[tokio::test] +async fn tx_meticulous_keyed_sha1() { + check_keyed_tx::(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()); + } +} diff --git a/src/bin/tests/rfc/fsm.rs b/src/bin/tests/rfc/fsm.rs new file mode 100644 index 0000000..1698245 --- /dev/null +++ b/src/bin/tests/rfc/fsm.rs @@ -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)); +} diff --git a/src/bin/tests/rfc/transport.rs b/src/bin/tests/rfc/transport.rs new file mode 100644 index 0000000..394c747 --- /dev/null +++ b/src/bin/tests/rfc/transport.rs @@ -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(); +} diff --git a/src/bin/tests/rfc/tx.rs b/src/bin/tests/rfc/tx.rs new file mode 100644 index 0000000..ca9357b --- /dev/null +++ b/src/bin/tests/rfc/tx.rs @@ -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); +} diff --git a/src/bin/tests/rfc/violations.rs b/src/bin/tests/rfc/violations.rs new file mode 100644 index 0000000..584df4c --- /dev/null +++ b/src/bin/tests/rfc/violations.rs @@ -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); +} diff --git a/src/config.rs b/src/config.rs index d4074e9..238e6aa 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,11 +1,7 @@ -//! Daemon configuration: YAML model, layered loading and validation. +//! Daemon configuration: a single YAML file, loaded and validated. //! -//! Layers, lowest to highest precedence: built-in defaults, the YAML file, `BFD_*` environment variables (global -//! settings only), command line (`--bind` replaces, `--peer` adds). Per-peer settings can only come from the file; peers -//! given on the command line use the global defaults. -//! -//! [`Config`] is the editable, serialisable model. [`Config::resolve`] validates it and produces a [`ResolvedConfig`] -//! with all per-peer inheritance applied, which is what the daemon runs from. +//! [`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, @@ -16,20 +12,13 @@ use std::{ time::Duration, }; -use serde::{de, Deserialize, Deserializer, Serialize}; -use serde_valid::Validate; +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"; -pub const ENV_BIND: &str = "BFD_BIND"; -pub const ENV_HOOKS_DIR: &str = "BFD_HOOKS_DIR"; -pub const ENV_DEFAULTS_DESIRED_MIN_TX: &str = "BFD_DEFAULTS_DESIRED_MIN_TX"; -pub const ENV_DEFAULTS_REQUIRED_MIN_RX: &str = "BFD_DEFAULTS_REQUIRED_MIN_RX"; -pub const ENV_DEFAULTS_DETECT_MULT: &str = "BFD_DEFAULTS_DETECT_MULT"; - fn default_true() -> bool { true } @@ -44,10 +33,6 @@ pub enum ConfigError { path: PathBuf, source: serde_yaml_ng::Error, }, - Env { - var: &'static str, - message: String, - }, Invalid(String), } @@ -60,9 +45,6 @@ impl fmt::Display for ConfigError { Self::Parse { path, source } => { write!(f, "invalid config file `{}`: {source}", path.display()) } - Self::Env { var, message } => { - write!(f, "invalid environment variable {var}: {message}") - } Self::Invalid(message) => write!(f, "invalid configuration: {message}"), } } @@ -73,13 +55,13 @@ impl Error for ConfigError { match self { Self::Io { source, .. } => Some(source), Self::Parse { source, .. } => Some(source), - Self::Env { .. } | Self::Invalid(_) => None, + Self::Invalid(_) => None, } } } /// Timer and multiplier settings inherited by every peer that does not override them. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Defaults { #[serde(with = "humantime_serde")] @@ -99,19 +81,16 @@ impl Default for Defaults { } } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Validate)] +#[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. - #[validate(min_items = 1)] - #[validate(max_items = 16)] + // The password is a binary string, and MUST be 1 to 16 bytes in length (checked in `Config::resolve`). pub password: Vec, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Validate)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct Md5AuthConfig { pub key_id: u8, @@ -122,7 +101,7 @@ pub struct Md5AuthConfig { pub meticulous: bool, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Validate)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct Sha1AuthConfig { pub key_id: u8, @@ -133,7 +112,7 @@ pub struct Sha1AuthConfig { pub meticulous: bool, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields, tag = "type", rename_all = "lowercase")] pub enum AuthConfig { Password(PasswordAuthConfig), @@ -150,12 +129,14 @@ impl From for BfdAuth { }), 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 @@ -164,47 +145,30 @@ impl From for BfdAuth { } } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields)] pub struct PeerConfig { pub address: IpAddr, - #[serde( - default, - skip_serializing_if = "Option::is_none", - with = "humantime_serde" - )] + /// 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, + #[serde(default, with = "humantime_serde")] pub desired_min_tx: Option, - #[serde( - default, - skip_serializing_if = "Option::is_none", - with = "humantime_serde" - )] + #[serde(default, with = "humantime_serde")] pub required_min_rx: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default)] pub detect_mult: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default)] pub auth: Option, } -impl PeerConfig { - pub fn new(address: IpAddr) -> Self { - Self { - address, - desired_min_tx: None, - required_min_rx: None, - detect_mult: None, - auth: None, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Config { - /// Local addresses to bind. Accepts a single address, a list, or a comma-separated string. The daemon currently - /// supports exactly one. - #[serde(deserialize_with = "deserialize_bind")] - pub bind: Vec, /// Directory of executable state-change hook scripts. pub hooks_dir: PathBuf, pub defaults: Defaults, @@ -214,7 +178,6 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { - bind: Vec::new(), hooks_dir: PathBuf::from(DEFAULT_HOOKS_DIR), defaults: Defaults::default(), peers: Vec::new(), @@ -222,106 +185,28 @@ impl Default for Config { } } -fn parse_bind_list(s: &str) -> Result, String> { - s.split(|c: char| c == ',' || c.is_whitespace()) - .map(str::trim) - .filter(|item| !item.is_empty()) - .map(|item| { - item.parse() - .map_err(|e| format!("invalid bind address `{item}`: {e}")) - }) - .collect() -} - -fn deserialize_bind<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { - #[derive(Deserialize)] - #[serde(untagged)] - enum OneOrMany { - One(String), - Many(Vec), - } - match OneOrMany::deserialize(deserializer)? { - OneOrMany::One(s) => parse_bind_list(&s).map_err(de::Error::custom), - OneOrMany::Many(items) => items - .iter() - .map(|s| parse_bind_list(s).map_err(de::Error::custom)) - .try_fold(Vec::new(), |mut acc, addrs| { - acc.extend(addrs?); - Ok(acc) - }), - } -} - impl Config { pub fn from_yaml(yaml: &str) -> Result { // An empty (or comment-only) document is a null value, which means "all defaults". Ok(serde_yaml_ng::from_str::>(yaml)?.unwrap_or_default()) } - fn from_file(path: &Path) -> Result { - let yaml = fs::read_to_string(path).map_err(|source| ConfigError::Io { - path: path.to_owned(), - source, - })?; - Self::from_yaml(&yaml).map_err(|source| ConfigError::Parse { - path: path.to_owned(), - source, - }) - } - /// 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 { - match path { - Some(path) => Self::from_file(path), - None => match Self::from_file(Path::new(DEFAULT_CONFIG_PATH)) { - Err(ConfigError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => { - Ok(Self::default()) - } - other => other, - }, - } - } - - /// Override global settings from `BFD_*` variables supplied by `var`. Unset and empty variables are ignored. - pub fn apply_env(&mut self, var: impl Fn(&str) -> Option) -> Result<(), ConfigError> { - let get = |name: &str| var(name).filter(|v| !v.trim().is_empty()); - let env_err = |var: &'static str, message: String| ConfigError::Env { var, message }; - let parse_duration = |name: &'static str, value: String| { - humantime::parse_duration(value.trim()).map_err(|e| env_err(name, e.to_string())) - }; - - if let Some(v) = get(ENV_BIND) { - self.bind = parse_bind_list(&v).map_err(|m| env_err(ENV_BIND, m))?; - } - if let Some(v) = get(ENV_HOOKS_DIR) { - self.hooks_dir = PathBuf::from(v); - } - if let Some(v) = get(ENV_DEFAULTS_DESIRED_MIN_TX) { - self.defaults.desired_min_tx = parse_duration(ENV_DEFAULTS_DESIRED_MIN_TX, v)?; - } - if let Some(v) = get(ENV_DEFAULTS_REQUIRED_MIN_RX) { - self.defaults.required_min_rx = parse_duration(ENV_DEFAULTS_REQUIRED_MIN_RX, v)?; - } - if let Some(v) = get(ENV_DEFAULTS_DETECT_MULT) { - self.defaults.detect_mult = v - .trim() - .parse() - .map_err(|e| env_err(ENV_DEFAULTS_DETECT_MULT, format!("{e}")))?; - } - Ok(()) - } - - /// Apply command line settings: a non-empty `bind` replaces the configured addresses, `peers` are added (with - /// default settings) unless a peer with that address is already configured. - pub fn apply_cli(&mut self, bind: Vec, peers: impl IntoIterator) { - if !bind.is_empty() { - self.bind = bind; - } - for address in peers { - if !self.peers.iter().any(|p| p.address == address) { - self.peers.push(PeerConfig::new(address)); - } + 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, + }), } } @@ -329,35 +214,42 @@ impl Config { pub fn resolve(self) -> Result { let invalid = |message: String| ConfigError::Invalid(message); - if self.bind.is_empty() { - return Err(invalid( - "no bind address configured (`bind`, BFD_BIND or --bind)".into(), - )); - } - let mut seen = HashSet::new(); - if let Some(dup) = self.bind.iter().find(|addr| !seen.insert(**addr)) { - return Err(invalid(format!("duplicate bind address {dup}"))); - } - let mut seen = HashSet::new(); let peers = self .peers .into_iter() .map(|peer| { - if !seen.insert(peer.address) { - return Err(invalid(format!("duplicate peer {}", peer.address))); - } - if !self - .bind - .iter() - .any(|b| b.is_ipv4() == peer.address.is_ipv4()) - { + if !seen.insert((peer.local, peer.interface.clone(), peer.address)) { return Err(invalid(format!( - "peer {} has no bind address of the same address family", + "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!( @@ -367,6 +259,8 @@ impl Config { } 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"), @@ -391,13 +285,29 @@ impl Config { } Ok(ResolvedConfig { - bind: self.bind.clone(), - hooks_dir: self.hooks_dir.clone(), + 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 { @@ -420,7 +330,6 @@ fn to_interval(value: Duration, what: &str) -> Result #[derive(Debug, Clone, PartialEq, Eq)] pub struct ResolvedConfig { - pub bind: Vec, pub hooks_dir: PathBuf, pub peers: Vec, } @@ -428,6 +337,8 @@ pub struct ResolvedConfig { #[derive(Debug, Clone, PartialEq, Eq)] pub struct ResolvedPeer { pub address: IpAddr, + pub local: IpAddr, + pub interface: Option, pub desired_min_tx: BfdInterval, pub required_min_rx: BfdInterval, pub detect_mult: u8, @@ -436,24 +347,40 @@ pub struct ResolvedPeer { #[cfg(test)] mod tests { - use std::collections::HashMap; - use super::*; + use rstest::rstest; + + enum Expect { + Ok, + Err, + ErrContaining(&'static str), + } + + fn check(result: Result, 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 env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { - let map: HashMap = pairs - .iter() - .map(|(k, v)| (k.to_string(), v.to_string())) - .collect(); - move |k| map.get(k).cloned() + 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 = " -bind: 192.0.2.1 hooks_dir: /tmp/hooks defaults: desired_min_tx: 500ms @@ -461,7 +388,9 @@ defaults: 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 "; @@ -469,7 +398,7 @@ peers: #[test] fn parses_full_config() { let config = Config::from_yaml(FULL).unwrap(); - assert_eq!(config.bind, vec![ip("192.0.2.1")]); + 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); @@ -477,10 +406,11 @@ peers: assert_eq!(config.peers[0].detect_mult, None); } - #[test] - fn empty_and_comment_only_documents_are_defaults() { - assert_eq!(Config::from_yaml("").unwrap(), Config::default()); - assert_eq!(Config::from_yaml("# nothing\n").unwrap(), Config::default()); + #[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] @@ -503,73 +433,30 @@ peers: } #[test] - fn bind_accepts_scalar_list_and_comma_string() { - for yaml in [ - "bind: 192.0.2.1", - "bind: [192.0.2.1]", - "bind: \"192.0.2.1\"", - ] { - assert_eq!(Config::from_yaml(yaml).unwrap().bind, vec![ip("192.0.2.1")]); - } - let multi = Config::from_yaml("bind: \"192.0.2.1, 2001:db8::1\"").unwrap(); - assert_eq!(multi.bind, vec![ip("192.0.2.1"), ip("2001:db8::1")]); - let list = Config::from_yaml("bind: [192.0.2.1, \"2001:db8::1\"]").unwrap(); - assert_eq!(list.bind, multi.bind); + 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")); } - #[test] - fn rejects_unknown_fields_and_bad_values() { - assert!(Config::from_yaml("bnid: 192.0.2.1").is_err()); - assert!(Config::from_yaml("defaults:\n desired_min_txx: 1s").is_err()); - assert!(Config::from_yaml("peers:\n - address: 192.0.2.2\n color: red").is_err()); - assert!(Config::from_yaml("bind: not-an-ip").is_err()); - assert!(Config::from_yaml("defaults:\n desired_min_tx: soon").is_err()); - assert!(Config::from_yaml("peers:\n - detect_mult: 3").is_err()); - } - - #[test] - fn yaml_roundtrip() { - let config = Config::from_yaml(FULL).unwrap(); - let again = Config::from_yaml(&serde_yaml_ng::to_string(&config).unwrap()).unwrap(); - assert_eq!(config, again); - } - - #[test] - fn env_overrides_globals() { - let mut config = Config::from_yaml(FULL).unwrap(); - config - .apply_env(env(&[ - (ENV_BIND, "192.0.2.9"), - (ENV_HOOKS_DIR, "/other"), - (ENV_DEFAULTS_DESIRED_MIN_TX, "2s"), - (ENV_DEFAULTS_REQUIRED_MIN_RX, "100ms"), - (ENV_DEFAULTS_DETECT_MULT, "9"), - ])) - .unwrap(); - assert_eq!(config.bind, vec![ip("192.0.2.9")]); - assert_eq!(config.hooks_dir, PathBuf::from("/other")); - assert_eq!(config.defaults.desired_min_tx, Duration::from_secs(2)); - assert_eq!(config.defaults.required_min_rx, Duration::from_millis(100)); - assert_eq!(config.defaults.detect_mult, 9); - // Peers are untouched, and an explicit per-peer value still beats an overridden default. - assert_eq!(config.peers, Config::from_yaml(FULL).unwrap().peers); - } - - #[test] - fn env_bind_accepts_multiple_addresses() { - for value in [ - "192.0.2.1,2001:db8::1", - "192.0.2.1, 2001:db8::1", - "192.0.2.1 2001:db8::1", - ] { - let mut config = Config::default(); - config.apply_env(env(&[(ENV_BIND, value)])).unwrap(); - assert_eq!( - config.bind, - vec![ip("192.0.2.1"), ip("2001:db8::1")], - "{value}" - ); - } + #[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] @@ -581,110 +468,115 @@ peers: assert_eq!(resolved.peers.len(), 1); } - #[test] - fn env_ignores_empty_and_unrelated_variables() { - let mut config = Config::from_yaml(FULL).unwrap(); - config - .apply_env(env(&[ - (ENV_BIND, ""), - (ENV_DEFAULTS_DETECT_MULT, " "), - ("BFD_PEERS", "192.0.2.99"), - ("BFD_PEER", "192.0.2.98"), - ("BFD_ADDR", "192.0.2.97"), - ])) - .unwrap(); - assert_eq!(config, Config::from_yaml(FULL).unwrap()); + #[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 env_errors_name_the_variable() { - for (var, value) in [ - (ENV_BIND, "nope"), - (ENV_DEFAULTS_DESIRED_MIN_TX, "fast"), - (ENV_DEFAULTS_DETECT_MULT, "-1"), - (ENV_DEFAULTS_DETECT_MULT, "300"), - ] { - let err = Config::default() - .apply_env(env(&[(var, value)])) - .unwrap_err(); - assert!(err.to_string().contains(var), "{err}"); + 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")); } - #[test] - fn cli_bind_replaces_and_peers_merge() { - let mut config = Config::from_yaml(FULL).unwrap(); - config.apply_cli( - vec![ip("192.0.2.7"), ip("2001:db8::7")], - [ip("192.0.2.3"), ip("192.0.2.4"), ip("192.0.2.4")], - ); - assert_eq!(config.bind, vec![ip("192.0.2.7"), ip("2001:db8::7")]); - let addrs: Vec<_> = config.peers.iter().map(|p| p.address).collect(); - assert_eq!( - addrs, - vec![ip("192.0.2.2"), ip("192.0.2.3"), ip("192.0.2.4")] - ); - // The file's settings for an existing peer win over the bare CLI entry. - assert_eq!(config.peers[1].detect_mult, Some(4)); - - let mut config = Config::from_yaml(FULL).unwrap(); - config.apply_cli(Vec::new(), []); - assert_eq!(config.bind, vec![ip("192.0.2.1")]); - } - - #[test] - fn resolve_validation() { - let base = - || Config::from_yaml("bind: 192.0.2.1\npeers:\n - address: 192.0.2.2\n").unwrap(); - assert!(base().resolve().is_ok()); - - let mut c = base(); - c.bind.clear(); - assert!(c.resolve().is_err()); - - let mut c = base(); - c.bind.push(ip("192.0.2.1")); - assert!(c.resolve().is_err()); - - let mut c = base(); - c.peers.push(PeerConfig::new(ip("192.0.2.2"))); - assert!(c - .resolve() - .unwrap_err() - .to_string() - .contains("duplicate peer")); - - let mut c = base(); - c.peers.push(PeerConfig::new(ip("2001:db8::2"))); - assert!(c - .clone() - .resolve() - .unwrap_err() - .to_string() - .contains("address family")); - c.bind.push(ip("2001:db8::1")); - assert!(c.resolve().is_ok()); - - let mut c = base(); - c.peers[0].detect_mult = Some(0); - assert!(c.resolve().is_err()); - - let mut c = base(); - c.peers[0].desired_min_tx = Some(Duration::ZERO); - assert!(c.resolve().is_err()); - - let mut c = base(); - c.peers[0].required_min_rx = Some(Duration::from_secs(5000)); - assert!(c.resolve().unwrap_err().to_string().contains("too large")); - - let mut c = base(); - c.defaults.detect_mult = 0; - assert!(c.resolve().is_err()); + #[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("bind: 192.0.2.1").unwrap(); + let config = Config::from_yaml("").unwrap(); assert!(config.resolve().unwrap().peers.is_empty()); } diff --git a/src/control.rs b/src/control.rs index e69de29..8b13789 100644 --- a/src/control.rs +++ b/src/control.rs @@ -0,0 +1 @@ + diff --git a/src/events.rs b/src/events.rs index 78c340c..bc61a98 100644 --- a/src/events.rs +++ b/src/events.rs @@ -27,6 +27,7 @@ pub struct StateChangeEvent { pub remote_discr: BfdDiscriminator, pub local_ip: IpAddr, pub remote_ip: IpAddr, + pub interface: Option, pub from_state: BfdState, pub to_state: BfdState, } @@ -144,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); @@ -151,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 { @@ -175,11 +178,11 @@ 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, - path::Path, sync::atomic::{AtomicU32, Ordering}, time::Duration, }; @@ -231,6 +234,7 @@ mod tests { remote_discr: BfdDiscriminator(22), local_ip: local, remote_ip: remote, + interface: None, from_state: from, to_state: to, }) @@ -247,36 +251,54 @@ mod tests { 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() { + 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(&v4_event()) + .handle_event(&event(local, remote, from, to)) .await; - assert_eq!( - t.output(), - ["Up|192.0.2.2|Up|Init|192.0.2.1|192.0.2.2|11|22"] - ); + assert_eq!(t.output(), [expected]); } #[tokio::test] - async fn passes_ipv6_addresses() { + async fn passes_interface() { let t = TempDir::new(); - t.append_script("10-env", 0o755, ENV_LINE); - let ev = event( - 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, - ); - ScriptHookSink::with_script_dir(t.hooks()) - .handle_event(&ev) - .await; - assert_eq!( - t.output(), - ["Down|2001:db8::2|Down|Up|2001:db8::1|2001:db8::2|11|22"] - ); + 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] @@ -335,20 +357,13 @@ mod tests { assert_eq!(t.output(), ["ok"]); } + #[rstest] + #[case::missing_dir("nope")] + #[case::empty_dir("hooks")] #[tokio::test] - async fn missing_script_dir_is_not_fatal() { + async fn missing_or_empty_script_dir_is_a_noop(#[case] subdir: &str) { let t = TempDir::new(); - let missing: &Path = &t.0.join("nope"); - ScriptHookSink::with_script_dir(missing) - .handle_event(&v4_event()) - .await; - assert!(t.output().is_empty()); - } - - #[tokio::test] - async fn empty_script_dir_is_a_noop() { - let t = TempDir::new(); - ScriptHookSink::with_script_dir(t.hooks()) + ScriptHookSink::with_script_dir(t.0.join(subdir)) .handle_event(&v4_event()) .await; assert!(t.output().is_empty()); @@ -379,6 +394,6 @@ mod tests { handle.abort(); let out = t.output(); assert_eq!(out.len(), 2); - assert!(out[0].starts_with("Up|") && out[1].starts_with("Down|")); + assert!(out[0].starts_with("up|") && out[1].starts_with("down|")); } } diff --git a/src/lib.rs b/src/lib.rs index 0e70845..3c1e172 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,14 +4,23 @@ pub mod control; pub mod events; use std::{ + ffi::OsString, fmt::{self, Display}, - net::IpAddr, + 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::*; @@ -197,8 +206,10 @@ pub struct BfdSessionStats { pub remote_discr: BfdDiscriminator, pub state: BfdState, pub last_diag: BfdDiagnostic, - /// Packet statistics since the session last entered Up + /// 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, pub last_down: Option, @@ -253,6 +264,106 @@ impl Display for BfdSessionStats { } } +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 { + 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::, + )?; + 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 { + 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::() 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() { @@ -276,35 +387,33 @@ pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std:: #[cfg(test)] mod tests { use super::*; + use rstest::rstest; - #[test] - fn interval_stats_empty() { - let s = AtomicIntervalStats::new().snapshot(); - assert_eq!(s.count(), 0); - assert_eq!((s.min(), s.max(), s.mean()), (None, None, None)); - } - - #[test] - fn interval_stats_single_packet_has_no_intervals() { - let stats = AtomicIntervalStats::new(); - stats.record(Instant::now()); - let s = stats.snapshot(); - assert_eq!(s.count(), 1); - assert_eq!((s.min(), s.max(), s.mean()), (None, None, None)); - } - - #[test] - fn interval_stats_min_max_mean() { + fn record_offsets_ms(offsets_ms: &[u64]) -> AtomicIntervalStats { let stats = AtomicIntervalStats::new(); let t0 = Instant::now(); - for ms in [0, 100, 400, 500] { + for &ms in offsets_ms { stats.record(t0 + Duration::from_millis(ms)); } - let s = stats.snapshot(); - assert_eq!(s.count(), 4); - assert_eq!(s.min(), Some(Duration::from_millis(100))); - assert_eq!(s.max(), Some(Duration::from_millis(300))); - assert_eq!(s.mean().unwrap().as_millis(), 166); + 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, + #[case] max_ms: Option, + #[case] mean_ms: Option, + ) { + 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] @@ -354,21 +463,14 @@ mod tests { assert!(loaded <= Instant::now()); } - #[test] - fn interval_stats_display() { - assert_eq!( - IntervalStats::default().to_string(), - "0 pkts, interval min/avg/max -/-/- ms" - ); - let stats = AtomicIntervalStats::new(); - let t0 = Instant::now(); - for ms in [0, 100, 400, 500] { - stats.record(t0 + Duration::from_millis(ms)); - } - assert_eq!( - stats.snapshot().to_string(), - "4 pkts, interval min/avg/max 100/167/300 ms" - ); + #[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, last_down: Option) -> BfdSessionStats { @@ -386,6 +488,7 @@ mod tests { state: BfdState::Up, last_diag: BfdDiagnostic::TimeExpired, rx: rx.snapshot(), + rx_received: 2, tx: tx.snapshot(), last_up, last_down, @@ -418,41 +521,41 @@ mod tests { assert_eq!(lines[5], " Last Up: never Last Down: never"); } - #[test] - fn session_stats_display_auth() { - let out = session_stats(None, None) - .with_auth(Some(AuthStats { - auth_type: BfdAuthType::MetKeyedSHA1, - key_id: 3, - rcv_seq: Some(100), - xmit_seq: Some(7), - })) - .to_string(); - assert!( - out.contains("\n Auth: meticulous-sha1 KeyId:3 RcvSeq:100 XmitSeq:7\n"), - "{out}" - ); - let out = session_stats(None, None) - .with_auth(Some(AuthStats { - auth_type: BfdAuthType::KeyedMD5, - key_id: 1, - rcv_seq: None, - xmit_seq: Some(7), - })) - .to_string(); - assert!( - out.contains("\n Auth: md5 KeyId:1 RcvSeq:- XmitSeq:7\n"), - "{out}" - ); + #[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}"); } - #[test] - fn session_stats_display_last_up_down() { + #[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(Some(now), None).to_string(); - assert!(out.ends_with("Last Up: 0s ago Last Down: never"), "{out}"); - let out = session_stats(None, Some(now)).to_string(); - assert!(out.ends_with("Last Up: never Last Down: 0s ago"), "{out}"); + let out = session_stats(up.then_some(now), down.then_some(now)).to_string(); + assert!(out.ends_with(expected_suffix), "{out}"); } #[test] @@ -461,13 +564,12 @@ mod tests { assert_eq!(s.base_interval, BfdInterval::from_millis(300)); } + #[rstest] #[tokio::test] - async fn set_ttl_v4() { + 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, 255).unwrap(); - assert_eq!(sock.ttl().unwrap(), 255); - set_ttl_or_hop_limit(&sock, 64).unwrap(); - assert_eq!(sock.ttl().unwrap(), 64); + set_ttl_or_hop_limit(&sock, ttl).unwrap(); + assert_eq!(sock.ttl().unwrap(), u32::from(ttl)); } #[tokio::test] @@ -478,4 +580,89 @@ mod tests { 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, + ) { + 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); + } }