implement local binding, rfc-based tests, fix deficiencies, add CI
This commit is contained in:
1 parent
8962406c57
commit
2b2fe66785
17 files changed
+2977
-1392
No files matched your search
@@ -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
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
repos:
|
||||||
|
- repo: local
|
||||||
|
hooks:
|
||||||
|
- id: cargo-fmt
|
||||||
|
name: cargo fmt
|
||||||
|
entry: cargo fmt --all -- --check
|
||||||
|
language: system
|
||||||
|
types: [rust]
|
||||||
|
pass_filenames: false
|
||||||
|
- id: cargo-clippy
|
||||||
|
name: cargo clippy
|
||||||
|
entry: cargo clippy --locked --all-targets -- -D warnings
|
||||||
|
language: system
|
||||||
|
types: [rust]
|
||||||
|
pass_filenames: false
|
||||||
|
- id: cargo-test
|
||||||
|
name: cargo test
|
||||||
|
entry: cargo test --locked
|
||||||
|
language: system
|
||||||
|
types: [rust]
|
||||||
|
pass_filenames: false
|
||||||
Generated
+114
-109
@@ -256,7 +256,7 @@ version = "1.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0"
|
checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror 2.0.21",
|
"thiserror",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -392,6 +392,12 @@ version = "0.3.34"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-timer"
|
||||||
|
version = "3.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures-util"
|
name = "futures-util"
|
||||||
version = "0.3.34"
|
version = "0.3.34"
|
||||||
@@ -420,6 +426,12 @@ dependencies = [
|
|||||||
"wasi",
|
"wasi",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "glob"
|
||||||
|
version = "0.3.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.17.1"
|
version = "0.17.1"
|
||||||
@@ -465,8 +477,6 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"equivalent",
|
"equivalent",
|
||||||
"hashbrown",
|
"hashbrown",
|
||||||
"serde",
|
|
||||||
"serde_core",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -484,15 +494,6 @@ dependencies = [
|
|||||||
"either",
|
"either",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "itertools"
|
|
||||||
version = "0.14.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
|
|
||||||
dependencies = [
|
|
||||||
"either",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itoa"
|
name = "itoa"
|
||||||
version = "1.0.18"
|
version = "1.0.18"
|
||||||
@@ -650,15 +651,6 @@ dependencies = [
|
|||||||
"syn 1.0.109",
|
"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]]
|
[[package]]
|
||||||
name = "once_cell_polyfill"
|
name = "once_cell_polyfill"
|
||||||
version = "1.70.2"
|
version = "1.70.2"
|
||||||
@@ -739,6 +731,15 @@ dependencies = [
|
|||||||
"syn 2.0.119",
|
"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]]
|
[[package]]
|
||||||
name = "proc-macro2"
|
name = "proc-macro2"
|
||||||
version = "1.0.107"
|
version = "1.0.107"
|
||||||
@@ -825,6 +826,41 @@ version = "0.8.11"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
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]]
|
[[package]]
|
||||||
name = "rust-bfd"
|
name = "rust-bfd"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -838,7 +874,7 @@ dependencies = [
|
|||||||
"futures 0.3.34",
|
"futures 0.3.34",
|
||||||
"humantime",
|
"humantime",
|
||||||
"humantime-serde",
|
"humantime-serde",
|
||||||
"itertools 0.12.1",
|
"itertools",
|
||||||
"log",
|
"log",
|
||||||
"md-5",
|
"md-5",
|
||||||
"nix",
|
"nix",
|
||||||
@@ -846,9 +882,9 @@ dependencies = [
|
|||||||
"nom-derive",
|
"nom-derive",
|
||||||
"proc-bitfield",
|
"proc-bitfield",
|
||||||
"rand",
|
"rand",
|
||||||
|
"rstest",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_bytes",
|
"serde_bytes",
|
||||||
"serde_valid",
|
|
||||||
"serde_yaml_ng",
|
"serde_yaml_ng",
|
||||||
"sha1",
|
"sha1",
|
||||||
"subtle",
|
"subtle",
|
||||||
@@ -856,6 +892,15 @@ dependencies = [
|
|||||||
"tokio-timer",
|
"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]]
|
[[package]]
|
||||||
name = "rustversion"
|
name = "rustversion"
|
||||||
version = "1.0.23"
|
version = "1.0.23"
|
||||||
@@ -874,6 +919,12 @@ version = "1.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "semver"
|
||||||
|
version = "1.0.28"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.229"
|
version = "1.0.229"
|
||||||
@@ -914,59 +965,6 @@ dependencies = [
|
|||||||
"syn 3.0.9",
|
"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]]
|
[[package]]
|
||||||
name = "serde_yaml_ng"
|
name = "serde_yaml_ng"
|
||||||
version = "0.10.0"
|
version = "0.10.0"
|
||||||
@@ -1074,33 +1072,13 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"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]]
|
[[package]]
|
||||||
name = "thiserror"
|
name = "thiserror"
|
||||||
version = "2.0.21"
|
version = "2.0.21"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror-impl 2.0.21",
|
"thiserror-impl",
|
||||||
]
|
|
||||||
|
|
||||||
[[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",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1164,6 +1142,36 @@ dependencies = [
|
|||||||
"tokio-executor",
|
"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]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
@@ -1176,12 +1184,6 @@ version = "1.0.27"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "unicode-segmentation"
|
|
||||||
version = "1.13.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unsafe-libyaml"
|
name = "unsafe-libyaml"
|
||||||
version = "0.2.11"
|
version = "0.2.11"
|
||||||
@@ -1215,6 +1217,15 @@ dependencies = [
|
|||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winnow"
|
||||||
|
version = "1.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zerocopy"
|
name = "zerocopy"
|
||||||
version = "0.8.63"
|
version = "0.8.63"
|
||||||
@@ -1234,9 +1245,3 @@ dependencies = [
|
|||||||
"quote",
|
"quote",
|
||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "zmij"
|
|
||||||
version = "1.0.23"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
|
||||||
+5
-2
@@ -16,16 +16,19 @@ humantime-serde = "1.1.1"
|
|||||||
itertools = "0.12.1"
|
itertools = "0.12.1"
|
||||||
log = "0.4.20"
|
log = "0.4.20"
|
||||||
md-5 = "0.11.0"
|
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 = "7.1.3"
|
||||||
nom-derive = "0.10.1"
|
nom-derive = "0.10.1"
|
||||||
proc-bitfield = "0.3.1"
|
proc-bitfield = "0.3.1"
|
||||||
rand = "0.8.5"
|
rand = "0.8.5"
|
||||||
serde = { version = "1.0.229", features = ["derive"] }
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
serde_bytes = "0.11.19"
|
serde_bytes = "0.11.19"
|
||||||
serde_valid = "3.2.0"
|
|
||||||
serde_yaml_ng = "0.10.0"
|
serde_yaml_ng = "0.10.0"
|
||||||
sha1 = "0.11.0"
|
sha1 = "0.11.0"
|
||||||
subtle = "2.6"
|
subtle = "2.6"
|
||||||
tokio = { version = "1.35.1", features = ["net", "full"] }
|
tokio = { version = "1.35.1", features = ["net", "full"] }
|
||||||
tokio-timer = "0.2.13"
|
tokio-timer = "0.2.13"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
rstest = "0.28.0"
|
||||||
+25
-17
@@ -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.
|
# 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.
|
# Directory of executable scripts run, in lexical order, on every session state change.
|
||||||
# Env: BFD_HOOKS_DIR
|
|
||||||
hooks_dir: /etc/rust-bfd/hooks.d
|
hooks_dir: /etc/rust-bfd/hooks.d
|
||||||
|
|
||||||
# Settings inherited by every peer that does not override them. Durations are humantime strings (300ms, 1s, 2m).
|
# 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:
|
defaults:
|
||||||
# Minimum interval between transmitted control packets that we would like to use once the session is Up. Sessions
|
# 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).
|
# 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
|
desired_min_tx: 300ms
|
||||||
# Minimum interval between received control packets we can support.
|
# Minimum interval between received control packets we can support.
|
||||||
# Env: BFD_DEFAULTS_REQUIRED_MIN_RX
|
|
||||||
required_min_rx: 300ms
|
required_min_rx: 300ms
|
||||||
# Detection time multiplier: we declare the session down after this many missed packets.
|
# Detection time multiplier: we declare the session down after this many missed packets.
|
||||||
# Env: BFD_DEFAULTS_DETECT_MULT
|
|
||||||
detect_mult: 3
|
detect_mult: 3
|
||||||
|
|
||||||
# Peers to establish sessions with. Peers can only be configured here and with --peer (repeatable, addresses only,
|
# Peers to establish sessions with.
|
||||||
# default settings); they cannot be set from the environment. Each peer's address must match the family of at least
|
#
|
||||||
# one bind address.
|
# `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:
|
peers:
|
||||||
- address: 192.0.2.2
|
- 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:
|
# Per-peer overrides of any `defaults` key:
|
||||||
# - address: 192.0.2.3
|
# - address: 192.0.2.3
|
||||||
|
# local: 192.0.2.1
|
||||||
# desired_min_tx: 1s
|
# desired_min_tx: 1s
|
||||||
# required_min_rx: 1s
|
# required_min_rx: 1s
|
||||||
# detect_mult: 5
|
# 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
|
# 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.
|
# packet must carry a newer sequence number; the remote must be set to the same mode.
|
||||||
# - address: 192.0.2.4
|
# - address: 192.0.2.4
|
||||||
|
# local: 192.0.2.1
|
||||||
# auth:
|
# auth:
|
||||||
# type: md5
|
# type: md5
|
||||||
# key_id: 1
|
# key_id: 1
|
||||||
@@ -59,6 +65,7 @@ peers:
|
|||||||
#
|
#
|
||||||
# Keyed SHA1: `key` is exactly 20 bytes. `meticulous` as above.
|
# Keyed SHA1: `key` is exactly 20 bytes. `meticulous` as above.
|
||||||
# - address: 192.0.2.5
|
# - address: 192.0.2.5
|
||||||
|
# local: 192.0.2.1
|
||||||
# auth:
|
# auth:
|
||||||
# type: sha1
|
# type: sha1
|
||||||
# key_id: 1
|
# 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.
|
# Simple password: 1 to 16 bytes, sent in the clear. Provides no protection against an attacker on the path.
|
||||||
# - address: 192.0.2.6
|
# - address: 192.0.2.6
|
||||||
|
# local: 192.0.2.1
|
||||||
# auth:
|
# auth:
|
||||||
# type: password
|
# type: password
|
||||||
# key_id: 1
|
# key_id: 1
|
||||||
|
|||||||
+349
-361
@@ -12,7 +12,7 @@ use bytemuck::NoUninit;
|
|||||||
use byteorder::{BigEndian, WriteBytesExt};
|
use byteorder::{BigEndian, WriteBytesExt};
|
||||||
use nom::{
|
use nom::{
|
||||||
bytes::complete::take,
|
bytes::complete::take,
|
||||||
multi::many_m_n,
|
combinator::{rest, verify},
|
||||||
number::complete::{be_u32, be_u8},
|
number::complete::{be_u32, be_u8},
|
||||||
IResult,
|
IResult,
|
||||||
};
|
};
|
||||||
@@ -73,10 +73,10 @@ impl Display for BfdState {
|
|||||||
impl From<BfdState> for &OsStr {
|
impl From<BfdState> for &OsStr {
|
||||||
fn from(val: BfdState) -> Self {
|
fn from(val: BfdState) -> Self {
|
||||||
match val {
|
match val {
|
||||||
BfdState::AdminDown => OsStr::new("AdminDown"),
|
BfdState::AdminDown => OsStr::new("admin_down"),
|
||||||
BfdState::Init => OsStr::new("Init"),
|
BfdState::Init => OsStr::new("init"),
|
||||||
BfdState::Down => OsStr::new("Down"),
|
BfdState::Down => OsStr::new("down"),
|
||||||
BfdState::Up => OsStr::new("Up"),
|
BfdState::Up => OsStr::new("up"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -122,6 +122,7 @@ impl Display for BfdDiscriminator {
|
|||||||
pub struct BfdInterval(u32);
|
pub struct BfdInterval(u32);
|
||||||
|
|
||||||
impl BfdInterval {
|
impl BfdInterval {
|
||||||
|
pub const ZERO: Self = Self(0);
|
||||||
pub fn from_micros(micros: u32) -> Self {
|
pub fn from_micros(micros: u32) -> Self {
|
||||||
Self(micros)
|
Self(micros)
|
||||||
}
|
}
|
||||||
@@ -228,8 +229,14 @@ pub struct BfdAuthSimplePassword {
|
|||||||
impl<'a> Parse<&'a [u8]> for BfdAuthSimplePassword {
|
impl<'a> Parse<&'a [u8]> for BfdAuthSimplePassword {
|
||||||
fn parse(i: &'a [u8]) -> IResult<&'a [u8], Self, nom::error::Error<&'a [u8]>> {
|
fn parse(i: &'a [u8]) -> IResult<&'a [u8], Self, nom::error::Error<&'a [u8]>> {
|
||||||
let (i, key_id) = be_u8(i)?;
|
let (i, key_id) = be_u8(i)?;
|
||||||
let (i, password) = many_m_n(1, 16, be_u8)(i)?;
|
let (i, password) = verify(rest, |p: &[u8]| !p.is_empty())(i)?;
|
||||||
Ok((i, Self { key_id, password }))
|
Ok((
|
||||||
|
i,
|
||||||
|
Self {
|
||||||
|
key_id,
|
||||||
|
password: password.to_vec(),
|
||||||
|
},
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,6 +253,8 @@ impl BfdAuthSimplePassword {
|
|||||||
pub struct BfdAuthKeyedMD5 {
|
pub struct BfdAuthKeyedMD5 {
|
||||||
pub meticulous: bool,
|
pub meticulous: bool,
|
||||||
pub key_id: u8,
|
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 seq: u32,
|
||||||
pub digest: [u8; 16],
|
pub digest: [u8; 16],
|
||||||
}
|
}
|
||||||
@@ -253,7 +262,7 @@ pub struct BfdAuthKeyedMD5 {
|
|||||||
impl BfdAuthKeyedMD5 {
|
impl BfdAuthKeyedMD5 {
|
||||||
fn parse_with(i: &[u8], meticulous: bool) -> IResult<&[u8], Self> {
|
fn parse_with(i: &[u8], meticulous: bool) -> IResult<&[u8], Self> {
|
||||||
let (i, key_id) = be_u8(i)?;
|
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, seq) = be_u32(i)?;
|
||||||
let (i, digest) = take(16usize)(i)?;
|
let (i, digest) = take(16usize)(i)?;
|
||||||
let digest = digest.try_into().expect("took 16 bytes");
|
let digest = digest.try_into().expect("took 16 bytes");
|
||||||
@@ -262,6 +271,7 @@ impl BfdAuthKeyedMD5 {
|
|||||||
Self {
|
Self {
|
||||||
meticulous,
|
meticulous,
|
||||||
key_id,
|
key_id,
|
||||||
|
reserved,
|
||||||
seq,
|
seq,
|
||||||
digest,
|
digest,
|
||||||
},
|
},
|
||||||
@@ -270,7 +280,7 @@ impl BfdAuthKeyedMD5 {
|
|||||||
|
|
||||||
fn serialize(&self, wtr: &mut impl Write) -> Result<(), std::io::Error> {
|
fn serialize(&self, wtr: &mut impl Write) -> Result<(), std::io::Error> {
|
||||||
wtr.write_u8(self.key_id)?;
|
wtr.write_u8(self.key_id)?;
|
||||||
wtr.write_u8(0)?;
|
wtr.write_u8(self.reserved)?;
|
||||||
wtr.write_u32::<BigEndian>(self.seq)?;
|
wtr.write_u32::<BigEndian>(self.seq)?;
|
||||||
wtr.write_all(&self.digest)
|
wtr.write_all(&self.digest)
|
||||||
}
|
}
|
||||||
@@ -280,6 +290,8 @@ impl BfdAuthKeyedMD5 {
|
|||||||
pub struct BfdAuthKeyedSHA1 {
|
pub struct BfdAuthKeyedSHA1 {
|
||||||
pub meticulous: bool,
|
pub meticulous: bool,
|
||||||
pub key_id: u8,
|
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 seq: u32,
|
||||||
pub digest: [u8; 20],
|
pub digest: [u8; 20],
|
||||||
}
|
}
|
||||||
@@ -287,7 +299,7 @@ pub struct BfdAuthKeyedSHA1 {
|
|||||||
impl BfdAuthKeyedSHA1 {
|
impl BfdAuthKeyedSHA1 {
|
||||||
fn parse_with(i: &[u8], meticulous: bool) -> IResult<&[u8], Self> {
|
fn parse_with(i: &[u8], meticulous: bool) -> IResult<&[u8], Self> {
|
||||||
let (i, key_id) = be_u8(i)?;
|
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, seq) = be_u32(i)?;
|
||||||
let (i, digest) = take(20usize)(i)?;
|
let (i, digest) = take(20usize)(i)?;
|
||||||
let digest = digest.try_into().expect("took 20 bytes");
|
let digest = digest.try_into().expect("took 20 bytes");
|
||||||
@@ -296,6 +308,7 @@ impl BfdAuthKeyedSHA1 {
|
|||||||
Self {
|
Self {
|
||||||
meticulous,
|
meticulous,
|
||||||
key_id,
|
key_id,
|
||||||
|
reserved,
|
||||||
seq,
|
seq,
|
||||||
digest,
|
digest,
|
||||||
},
|
},
|
||||||
@@ -304,7 +317,7 @@ impl BfdAuthKeyedSHA1 {
|
|||||||
|
|
||||||
fn serialize(&self, wtr: &mut impl Write) -> Result<(), std::io::Error> {
|
fn serialize(&self, wtr: &mut impl Write) -> Result<(), std::io::Error> {
|
||||||
wtr.write_u8(self.key_id)?;
|
wtr.write_u8(self.key_id)?;
|
||||||
wtr.write_u8(0)?;
|
wtr.write_u8(self.reserved)?;
|
||||||
wtr.write_u32::<BigEndian>(self.seq)?;
|
wtr.write_u32::<BigEndian>(self.seq)?;
|
||||||
wtr.write_all(&self.digest)
|
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
|
// 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.
|
// 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
|
// If the Password field does not match the password selected by the
|
||||||
// key ID, the packet MUST be discarded.
|
// key ID, the packet MUST be discarded.
|
||||||
@@ -559,6 +572,8 @@ impl BfdPacket {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use nom_derive::Parse;
|
use nom_derive::Parse;
|
||||||
|
use rstest::rstest;
|
||||||
|
use std::fmt::Display;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
// vers=1 diag=0 | state=Up | mult=3 | len=24, then RFC 5880 6.8.7 fields
|
// 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
|
BfdPacket::parse(bytes).expect("parse").1
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
/// `UP_PACKET` with the A bit set, followed by `section`
|
||||||
fn flags_bit_layout() {
|
fn up_packet_with_auth_section(section: &[u8]) -> Vec<u8> {
|
||||||
let f = BfdFlags(0)
|
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<u8> {
|
||||||
|
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_vers(1)
|
||||||
.with_diag(BfdDiagnostic::NeighborDown as u8)
|
.with_diag(BfdDiagnostic::NeighborDown as u8)
|
||||||
.with_state(BfdState::Up as u8)
|
.with_state(BfdState::Up as u8)
|
||||||
.with_poll(true)
|
.with_poll(true)
|
||||||
.with_detect_mult(3)
|
.with_detect_mult(3)
|
||||||
.with_length(24);
|
.with_length(24),
|
||||||
assert_eq!(f.0, 0x23e0_0318);
|
0x23e0_0318
|
||||||
let f = BfdFlags(0)
|
)]
|
||||||
|
#[case::single_bit_flags(
|
||||||
|
BfdFlags(0)
|
||||||
.with_final_(true)
|
.with_final_(true)
|
||||||
.with_cpi(true)
|
.with_cpi(true)
|
||||||
.with_auth_present(true)
|
.with_auth_present(true)
|
||||||
.with_demand(true)
|
.with_demand(true)
|
||||||
.with_multipoint(true);
|
.with_multipoint(true),
|
||||||
assert_eq!(f.0, 0x001f_0000);
|
0x001f_0000
|
||||||
|
)]
|
||||||
|
fn flags_bit_layout(#[case] flags: BfdFlags, #[case] expected: u32) {
|
||||||
|
assert_eq!(flags.0, expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -654,11 +689,14 @@ mod tests {
|
|||||||
assert_eq!(q.required_min_echo_rx, p.required_min_echo_rx);
|
assert_eq!(q.required_min_echo_rx, p.required_min_echo_rx);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn parse_rejects_truncated() {
|
fn parse_rejects_truncated(
|
||||||
for len in 0..UP_PACKET.len() {
|
#[values(
|
||||||
assert!(BfdPacket::parse(&UP_PACKET[..len]).is_err(), "len {len}");
|
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]
|
#[test]
|
||||||
@@ -670,163 +708,119 @@ mod tests {
|
|||||||
assert_eq!(p.my_disc, BfdDiscriminator(1));
|
assert_eq!(p.my_disc, BfdDiscriminator(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn parse_auth_present_requires_auth_section() {
|
#[case::a_bit_without_section(up_packet_with_auth_section(&[]))]
|
||||||
let mut bytes = UP_PACKET;
|
#[case::auth_type_none(up_packet_with_auth_section(&md5_section(0, 16)))]
|
||||||
bytes[1] |= 0x04;
|
#[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<u8>) {
|
||||||
assert!(BfdPacket::parse(&bytes).is_err());
|
assert!(BfdPacket::parse(&bytes).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parse_keyed_md5_auth() {
|
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_with_auth_section(&md5_section(2, 16));
|
||||||
let mut bytes = UP_PACKET.to_vec();
|
|
||||||
bytes[1] |= 0x04;
|
|
||||||
bytes[3] = 48;
|
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");
|
let (rest, p) = BfdPacket::parse(&bytes).expect("parse");
|
||||||
assert!(rest.is_empty());
|
assert!(rest.is_empty());
|
||||||
assert!(p.auth.is_some());
|
assert!(p.auth.is_some());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn invalid_state_and_diag_values() {
|
#[case::state_in_range(3, true)]
|
||||||
assert!(BfdState::try_from(4u8).is_err());
|
#[case::state_out_of_range(4, false)]
|
||||||
assert!(BfdDiagnostic::try_from(10u8).is_err());
|
fn state_try_from(#[case] value: u8, #[case] valid: bool) {
|
||||||
assert!(BfdState::try_from(3u8).is_ok());
|
assert_eq!(BfdState::try_from(value).is_ok(), valid);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn state_display_and_osstr() {
|
fn invalid_diag_value() {
|
||||||
for (s, name) in [
|
assert!(BfdDiagnostic::try_from(10u8).is_err());
|
||||||
(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));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn state_default_is_down() {
|
||||||
assert_eq!(BfdState::default(), BfdState::Down);
|
assert_eq!(BfdState::default(), BfdState::Down);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn diagnostic_display() {
|
#[case(BfdState::AdminDown, "admin_down")]
|
||||||
assert_eq!(BfdDiagnostic::None.to_string(), "None");
|
#[case(BfdState::Down, "down")]
|
||||||
assert_eq!(BfdDiagnostic::TimeExpired.to_string(), "TimeExpired");
|
#[case(BfdState::Init, "init")]
|
||||||
assert_eq!(BfdDiagnostic::AdminDown.to_string(), "AdminDown");
|
#[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]
|
#[test]
|
||||||
fn interval_constructors() {
|
fn interval_ordering() {
|
||||||
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");
|
|
||||||
assert!(BfdInterval::from_millis(1) < BfdInterval::from_secs(1));
|
assert!(BfdInterval::from_millis(1) < BfdInterval::from_secs(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn discriminator_display() {
|
#[case::from_millis(|| { BfdInterval::from_millis(4_294_968); })]
|
||||||
assert_eq!(BfdDiscriminator(42).to_string(), "42");
|
#[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); })]
|
||||||
#[test]
|
#[case::from_secs_f32_nan(|| { BfdInterval::from_secs_f32(f32::NAN); })]
|
||||||
fn interval_constructors_accept_the_maximum() {
|
#[case::from_duration(|| { let _ = BfdInterval::from(Duration::from_micros(u32::MAX as u64 + 1)); })]
|
||||||
assert_eq!(
|
#[case::mul(|| { let _ = BfdInterval::from_secs(2000) * 3; })]
|
||||||
BfdInterval::from_millis(4_294_967),
|
#[case::reverse_mul(|| { let _ = 3 * BfdInterval::from_secs(2000); })]
|
||||||
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]
|
|
||||||
#[should_panic(expected = "overflow")]
|
#[should_panic(expected = "overflow")]
|
||||||
fn from_millis_overflow_panics() {
|
fn interval_overflow_panics(#[case] overflowing: fn()) {
|
||||||
BfdInterval::from_millis(4_294_968);
|
overflowing();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
#[should_panic(expected = "overflow")]
|
#[case(4, Some(BfdInterval::from_secs(4000)))]
|
||||||
fn from_secs_overflow_panics() {
|
#[case(5, None)]
|
||||||
BfdInterval::from_secs(4295);
|
fn checked_mul(#[case] factor: u32, #[case] expected: Option<BfdInterval>) {
|
||||||
}
|
assert_eq!(BfdInterval::from_secs(1000).checked_mul(factor), expected);
|
||||||
|
|
||||||
#[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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MD5_KEY: [u8; 16] = *b"0123456789abcdef";
|
const MD5_KEY: [u8; 16] = *b"0123456789abcdef";
|
||||||
@@ -840,10 +834,16 @@ mod tests {
|
|||||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn flip<const N: usize>(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 {
|
fn md5_auth(meticulous: bool, key_id: u8, seq: u32, key: [u8; 16]) -> BfdAuth {
|
||||||
BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
|
BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
|
||||||
meticulous,
|
meticulous,
|
||||||
key_id,
|
key_id,
|
||||||
|
reserved: 0,
|
||||||
seq,
|
seq,
|
||||||
digest: key,
|
digest: key,
|
||||||
})
|
})
|
||||||
@@ -853,6 +853,7 @@ mod tests {
|
|||||||
BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
|
BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
|
||||||
meticulous,
|
meticulous,
|
||||||
key_id,
|
key_id,
|
||||||
|
reserved: 0,
|
||||||
seq,
|
seq,
|
||||||
digest: key,
|
digest: key,
|
||||||
})
|
})
|
||||||
@@ -890,56 +891,85 @@ mod tests {
|
|||||||
parse(&p.serialize().unwrap())
|
parse(&p.serialize().unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn auth_accessors() {
|
#[case::md5_meticulous(
|
||||||
let md5 = md5_auth(true, 7, 9, MD5_KEY);
|
md5_auth(true, 7, 9, MD5_KEY),
|
||||||
assert_eq!(md5.auth_type(), BfdAuthType::MetKeyedMD5);
|
BfdAuthType::MetKeyedMD5,
|
||||||
assert_eq!(md5.auth_len(), 24);
|
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<u32>,
|
||||||
|
#[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!(
|
assert_eq!(
|
||||||
(md5.seq(), md5.key_id(), md5.meticulous()),
|
(auth.seq(), auth.key_id(), auth.meticulous()),
|
||||||
(Some(9), 7, true)
|
(seq, key_id, meticulous)
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(auth.digest_field().is_some(), has_digest);
|
||||||
md5_auth(false, 0, 0, MD5_KEY).auth_type(),
|
|
||||||
BfdAuthType::KeyedMD5
|
|
||||||
);
|
|
||||||
|
|
||||||
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]
|
#[rstest]
|
||||||
fn set_seq_only_affects_keyed() {
|
#[case::md5(md5_auth(true, 1, 0, MD5_KEY), Some(42))]
|
||||||
let mut md5 = md5_auth(true, 1, 0, MD5_KEY);
|
#[case::sha1(sha1_auth(true, 1, 0, SHA1_KEY), Some(42))]
|
||||||
md5.set_seq(42);
|
#[case::simple_password(password_auth(1, b"pw"), None)]
|
||||||
assert_eq!(md5.seq(), Some(42));
|
fn set_seq_only_affects_keyed(#[case] mut auth: BfdAuth, #[case] expected: Option<u32>) {
|
||||||
let mut sha1 = sha1_auth(true, 1, 0, SHA1_KEY);
|
auth.set_seq(42);
|
||||||
sha1.set_seq(43);
|
assert_eq!(auth.seq(), expected);
|
||||||
assert_eq!(sha1.seq(), Some(43));
|
|
||||||
let mut pw = password_auth(1, b"pw");
|
|
||||||
pw.set_seq(44);
|
|
||||||
assert_eq!(pw.seq(), None);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn keyed_auth_wire_roundtrip() {
|
#[case::md5(md5_auth(false, 7, 0xdead_beef, MD5_KEY))]
|
||||||
for auth in [
|
#[case::md5_meticulous(md5_auth(true, 7, 1, MD5_KEY))]
|
||||||
md5_auth(false, 7, 0xdead_beef, MD5_KEY),
|
#[case::sha1(sha1_auth(false, 255, u32::MAX, SHA1_KEY))]
|
||||||
md5_auth(true, 7, 1, MD5_KEY),
|
#[case::sha1_meticulous(sha1_auth(true, 0, 0, SHA1_KEY))]
|
||||||
sha1_auth(false, 255, u32::MAX, SHA1_KEY),
|
fn keyed_auth_wire_roundtrip(#[case] auth: BfdAuth) {
|
||||||
sha1_auth(true, 0, 0, SHA1_KEY),
|
|
||||||
] {
|
|
||||||
let p = auth_packet(Some(auth.clone()));
|
let p = auth_packet(Some(auth.clone()));
|
||||||
let bytes = p.serialize().unwrap();
|
let bytes = p.serialize().unwrap();
|
||||||
assert_eq!(bytes.len(), 24 + auth.auth_len() as usize);
|
assert_eq!(bytes.len(), 24 + auth.auth_len() as usize);
|
||||||
@@ -948,11 +978,12 @@ mod tests {
|
|||||||
assert_eq!(bytes[25], auth.auth_len());
|
assert_eq!(bytes[25], auth.auth_len());
|
||||||
assert_eq!(parse(&bytes).auth, Some(auth));
|
assert_eq!(parse(&bytes).auth, Some(auth));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn password_auth_wire_roundtrip() {
|
#[case::one_byte(&b"a"[..])]
|
||||||
for pw in [&b"a"[..], b"secret", b"0123456789abcdef"] {
|
#[case::word(&b"secret"[..])]
|
||||||
|
#[case::sixteen_bytes(&b"0123456789abcdef"[..])]
|
||||||
|
fn password_auth_wire_roundtrip(#[case] pw: &[u8]) {
|
||||||
let auth = password_auth(5, pw);
|
let auth = password_auth(5, pw);
|
||||||
let p = auth_packet(Some(auth.clone()));
|
let p = auth_packet(Some(auth.clone()));
|
||||||
let bytes = p.serialize().unwrap();
|
let bytes = p.serialize().unwrap();
|
||||||
@@ -961,190 +992,147 @@ mod tests {
|
|||||||
assert_eq!(&bytes[27..], pw);
|
assert_eq!(&bytes[27..], pw);
|
||||||
assert_eq!(parse(&bytes).auth, Some(auth));
|
assert_eq!(parse(&bytes).auth, Some(auth));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn parse_rejects_bad_auth_sections() {
|
#[case::md5_meticulous(md5_auth(true, 7, 9, MD5_KEY), MD5_MET_DIGEST)]
|
||||||
let mut base = UP_PACKET.to_vec();
|
#[case::md5_non_meticulous(md5_auth(false, 7, 9, MD5_KEY), MD5_NONMET_DIGEST)]
|
||||||
base[1] |= 0x04;
|
#[case::sha1_meticulous(sha1_auth(true, 7, 9, SHA1_KEY), SHA1_MET_DIGEST)]
|
||||||
// Auth Type 0 (None) and an unassigned type are not valid with the A bit set
|
fn sign_matches_known_digest(#[case] auth: BfdAuth, #[case] expected: &str) {
|
||||||
for auth_type in [0u8, 6] {
|
let auth_len = auth.auth_len();
|
||||||
let mut bytes = base.clone();
|
let mut p = auth_packet(Some(auth));
|
||||||
bytes.extend_from_slice(&[auth_type, 24, 1, 0, 0, 0, 0, 1]);
|
assert_eq!(
|
||||||
bytes.extend_from_slice(&[0; 16]);
|
p.serialize().unwrap()[..4],
|
||||||
assert!(BfdPacket::parse(&bytes).is_err(), "type {auth_type}");
|
[0x20, 0xc4, 0x03, 24 + auth_len]
|
||||||
}
|
);
|
||||||
// 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();
|
p.sign().unwrap();
|
||||||
let digest = p.auth.as_ref().unwrap().digest_field().unwrap();
|
let digest = p.auth.as_ref().unwrap().digest_field().unwrap();
|
||||||
assert_eq!(hex(digest), MD5_MET_DIGEST);
|
assert_eq!(hex(digest), expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn sign_matches_known_sha1_digest() {
|
#[case::md5(md5_auth(true, 7, 9, MD5_KEY), &MD5_KEY[..])]
|
||||||
let mut p = auth_packet(Some(sha1_auth(true, 7, 9, SHA1_KEY)));
|
#[case::sha1(sha1_auth(true, 7, 9, SHA1_KEY), &SHA1_KEY[..])]
|
||||||
p.sign().unwrap();
|
fn sign_does_not_leak_key(#[case] auth: BfdAuth, #[case] key: &[u8]) {
|
||||||
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();
|
let bytes = over_the_wire(auth).serialize().unwrap();
|
||||||
assert!(!bytes.windows(key.len()).any(|w| w == key));
|
assert!(!bytes.windows(key.len()).any(|w| w == key));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn sign_is_a_noop_without_keyed_auth() {
|
fn auth_packet_without_auth_matches_up_packet() {
|
||||||
let mut none = auth_packet(None);
|
|
||||||
none.sign().unwrap();
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
none.serialize().unwrap(),
|
auth_packet(None).serialize().unwrap(),
|
||||||
parse(&UP_PACKET).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]
|
#[rstest]
|
||||||
fn verify_accepts_valid_keyed_packets() {
|
#[case::no_auth(auth_packet(None))]
|
||||||
for (sent, expected) in [
|
#[case::simple_password(auth_packet(Some(password_auth(1, b"secret"))))]
|
||||||
(md5_auth(true, 7, 9, MD5_KEY), md5_auth(true, 7, 0, MD5_KEY)),
|
fn sign_is_a_noop_without_keyed_auth(#[case] mut p: BfdPacket) {
|
||||||
(
|
let before = p.serialize().unwrap();
|
||||||
md5_auth(false, 7, 9, MD5_KEY),
|
p.sign().unwrap();
|
||||||
md5_auth(false, 7, 0, MD5_KEY),
|
assert_eq!(p.serialize().unwrap(), before);
|
||||||
),
|
}
|
||||||
(
|
|
||||||
sha1_auth(true, 7, 9, SHA1_KEY),
|
#[rstest]
|
||||||
sha1_auth(true, 7, 0, SHA1_KEY),
|
#[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, 9, SHA1_KEY),
|
||||||
sha1_auth(false, 7, 0, SHA1_KEY),
|
sha1_auth(false, 7, 0, SHA1_KEY),
|
||||||
),
|
true
|
||||||
] {
|
)]
|
||||||
assert!(over_the_wire(sent).verify(&expected).unwrap());
|
#[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]
|
#[rstest]
|
||||||
fn verify_does_not_depend_on_expected_seq() {
|
#[case::my_disc(|p: &mut BfdPacket| p.my_disc = BfdDiscriminator(99))]
|
||||||
let p = over_the_wire(md5_auth(true, 7, 9, MD5_KEY));
|
#[case::state(|p: &mut BfdPacket| p.flags = p.flags.with_state(BfdState::Down as u8))]
|
||||||
assert!(p.verify(&md5_auth(true, 7, 12345, MD5_KEY)).unwrap());
|
#[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| {
|
||||||
#[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;
|
|
||||||
if let Some(BfdAuth::KeyedMD5(d)) = p.auth.as_mut() {
|
if let Some(BfdAuth::KeyedMD5(d)) = p.auth.as_mut() {
|
||||||
d.digest[0] ^= 1;
|
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());
|
assert!(!p.verify(&expected).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn verify_rejects_missing_auth() {
|
#[case::no_auth(auth_packet(None))]
|
||||||
let expected = md5_auth(true, 7, 0, MD5_KEY);
|
#[case::a_bit_without_section({
|
||||||
assert!(!auth_packet(None).verify(&expected).unwrap());
|
|
||||||
// A bit set but no section
|
|
||||||
let mut p = auth_packet(None);
|
let mut p = auth_packet(None);
|
||||||
p.flags = p.flags.with_auth_present(true);
|
p.flags = p.flags.with_auth_present(true);
|
||||||
assert!(!p.verify(&expected).unwrap());
|
p
|
||||||
}
|
})]
|
||||||
|
fn verify_rejects_missing_auth(#[case] p: BfdPacket) {
|
||||||
#[test]
|
assert!(!p.verify(&md5_auth(true, 7, 0, MD5_KEY)).unwrap());
|
||||||
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());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+819
-447
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,166 @@
|
|||||||
|
//! Conformance tests for the single-hop subset of RFC 5880 and RFC 5881.
|
||||||
|
//!
|
||||||
|
//! Tests marked `#[ignore = "known RFC violation: ..."]` assert the RFC behaviour and currently fail.
|
||||||
|
use super::*;
|
||||||
|
use digest::Digest;
|
||||||
|
use md5::Md5;
|
||||||
|
use sha1::Sha1;
|
||||||
|
|
||||||
|
mod auth;
|
||||||
|
mod fsm;
|
||||||
|
mod transport;
|
||||||
|
mod tx;
|
||||||
|
mod violations;
|
||||||
|
|
||||||
|
const MD5_KEY: [u8; 16] = *b"0123456789abcdef";
|
||||||
|
|
||||||
|
type Events = mpsc::UnboundedReceiver<StateChangeEvent>;
|
||||||
|
|
||||||
|
async fn tapped(peer: ResolvedPeer) -> (BfdSession, UdpSocket, Events) {
|
||||||
|
let (dispatcher, events) = capture_dispatcher().await;
|
||||||
|
let (tx, rx) = mpsc::channel(32);
|
||||||
|
let sock = UdpSocket::bind((LOCAL, 0)).await.unwrap();
|
||||||
|
let tap = UdpSocket::bind((LOCAL, 0)).await.unwrap();
|
||||||
|
let s = BfdSession::new(
|
||||||
|
rx,
|
||||||
|
BfdSessionHandle { tx },
|
||||||
|
sock,
|
||||||
|
LOCAL,
|
||||||
|
tap.local_addr().unwrap(),
|
||||||
|
peer,
|
||||||
|
BfdDiscriminator(LOCAL_DISCR),
|
||||||
|
dispatcher,
|
||||||
|
);
|
||||||
|
(s, tap, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn recv_raw(tap: &UdpSocket) -> Vec<u8> {
|
||||||
|
let mut buf = [0u8; 128];
|
||||||
|
let (n, _) = time::timeout(Duration::from_secs(2), tap.recv_from(&mut buf))
|
||||||
|
.await
|
||||||
|
.expect("no packet transmitted")
|
||||||
|
.unwrap();
|
||||||
|
buf[..n].to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_raw(raw: &[u8]) -> BfdPacket {
|
||||||
|
BfdPacket::parse(raw).expect("transmitted packet parses").1
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn recv_packet(tap: &UdpSocket) -> BfdPacket {
|
||||||
|
parse_raw(&recv_raw(tap).await)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn drain(tap: &UdpSocket) -> Vec<BfdPacket> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut buf = [0u8; 128];
|
||||||
|
while let Ok(Ok((n, _))) =
|
||||||
|
time::timeout(Duration::from_millis(40), tap.recv_from(&mut buf)).await
|
||||||
|
{
|
||||||
|
out.push(parse_raw(&buf[..n]));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn tapped_in(state: BfdState) -> (BfdSession, UdpSocket, Events) {
|
||||||
|
let (mut s, tap, mut events) = tapped(peer_cfg(300, 300, 3)).await;
|
||||||
|
let path: &[BfdState] = match state {
|
||||||
|
BfdState::Down => &[],
|
||||||
|
BfdState::Init => &[BfdState::Down],
|
||||||
|
_ => &[BfdState::Down, BfdState::Init],
|
||||||
|
};
|
||||||
|
for (i, remote) in path.iter().enumerate() {
|
||||||
|
let your = if i == 0 { 0 } else { LOCAL_DISCR };
|
||||||
|
s.receive_control_packet(&pkt(*remote, REMOTE_DISCR, your))
|
||||||
|
.await;
|
||||||
|
next_event(&mut events).await;
|
||||||
|
}
|
||||||
|
assert_eq!(s.state.session_state(), state);
|
||||||
|
drain(&tap).await;
|
||||||
|
(s, tap, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fast(state: BfdState, your: u32) -> BfdPacket {
|
||||||
|
let mut p = pkt(state, REMOTE_DISCR, your);
|
||||||
|
p.flags = p.flags.with_detect_mult(255);
|
||||||
|
p.desired_min_tx = BfdInterval::from_millis(20);
|
||||||
|
p.required_min_rx = BfdInterval::from_millis(20);
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fast_up() -> (BfdSession, UdpSocket, Events) {
|
||||||
|
let (mut s, tap, mut events) = tapped(peer_cfg(20, 20, 3)).await;
|
||||||
|
s.receive_control_packet(&fast(BfdState::Down, 0)).await;
|
||||||
|
s.receive_control_packet(&fast(BfdState::Init, LOCAL_DISCR))
|
||||||
|
.await;
|
||||||
|
next_event(&mut events).await;
|
||||||
|
next_event(&mut events).await;
|
||||||
|
assert_eq!(s.state.session_state(), BfdState::Up);
|
||||||
|
let ended = with_flags(fast(BfdState::Up, LOCAL_DISCR), |f| f.with_final_(true));
|
||||||
|
s.receive_control_packet(&ended).await;
|
||||||
|
assert!(!s.state.poll_mode());
|
||||||
|
drain(&tap).await;
|
||||||
|
(s, tap, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn drain_commands(s: &mut BfdSession) -> usize {
|
||||||
|
time::sleep(Duration::from_millis(50)).await;
|
||||||
|
let mut n = 0;
|
||||||
|
while let Ok(cmd) = s.rx.try_recv() {
|
||||||
|
n += matches!(cmd, SessionControlCommand::TxControlPacket { .. }) as usize;
|
||||||
|
}
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_for(auth: &BfdAuth) -> Vec<u8> {
|
||||||
|
auth.digest_field().unwrap().to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn md5_auth(meticulous: bool, key_id: u8, seq: u32) -> BfdAuth {
|
||||||
|
BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
|
||||||
|
meticulous,
|
||||||
|
key_id,
|
||||||
|
reserved: 0,
|
||||||
|
seq,
|
||||||
|
digest: MD5_KEY,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha1_auth(meticulous: bool, key_id: u8, seq: u32) -> BfdAuth {
|
||||||
|
BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
|
||||||
|
meticulous,
|
||||||
|
key_id,
|
||||||
|
reserved: 0,
|
||||||
|
seq,
|
||||||
|
digest: SHA1_KEY,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn password_auth(key_id: u8, password: &[u8]) -> BfdAuth {
|
||||||
|
BfdAuth::SimplePassword(BfdAuthSimplePassword {
|
||||||
|
key_id,
|
||||||
|
password: password.to_vec(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signed(auth: BfdAuth, state: BfdState, my: u32, your: u32) -> BfdPacket {
|
||||||
|
let len = 24 + auth.auth_len();
|
||||||
|
let mut p = with_flags(pkt(state, my, your), |f| {
|
||||||
|
f.with_auth_present(true).with_length(len)
|
||||||
|
});
|
||||||
|
p.auth = Some(auth);
|
||||||
|
p.sign().unwrap();
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn keyed_session(auth: BfdAuth) -> (BfdSession, UdpSocket, Events) {
|
||||||
|
let (mut s, tap, events) = tapped(peer_cfg(300, 300, 3)).await;
|
||||||
|
s.state.auth_type.store(auth.auth_type(), ORDERING);
|
||||||
|
s.auth = Some(auth);
|
||||||
|
(s, tap, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn accepted(s: &mut BfdSession, p: &BfdPacket) -> bool {
|
||||||
|
s.receive_control_packet(p).await;
|
||||||
|
s.state.remote_discr() == p.my_disc
|
||||||
|
}
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn digest_with_key<D: Digest>(raw: &[u8], key: &[u8], at: usize) -> Vec<u8> {
|
||||||
|
let mut keyed = raw.to_vec();
|
||||||
|
keyed[at..at + key.len()].copy_from_slice(key);
|
||||||
|
D::digest(&keyed).as_slice().to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5880 4.3, 4.4, 6.7.3, 6.7.4: field layout, sequence number handling and digest of a transmitted packet.
|
||||||
|
async fn check_keyed_tx<D: Digest>(auth: BfdAuth, auth_len: usize, type_byte: u8) {
|
||||||
|
let key = key_for(&auth);
|
||||||
|
let (mut s, tap, _events) = keyed_session(auth).await;
|
||||||
|
s.state.xmit_auth_seq.store(u32::MAX - 1, ORDERING);
|
||||||
|
let mut seqs = Vec::new();
|
||||||
|
for _ in 0..4 {
|
||||||
|
s.transmit_control_packet(false).await;
|
||||||
|
let raw = recv_raw(&tap).await;
|
||||||
|
assert_eq!(raw.len(), 24 + auth_len);
|
||||||
|
assert_eq!(raw[3] as usize, 24 + auth_len);
|
||||||
|
assert_ne!(raw[1] & 0x04, 0, "A bit");
|
||||||
|
assert_eq!(raw[24], type_byte);
|
||||||
|
assert_eq!(raw[25] as usize, auth_len);
|
||||||
|
assert_eq!(raw[26], 7, "key id");
|
||||||
|
assert_eq!(raw[27], 0, "reserved");
|
||||||
|
seqs.push(u32::from_be_bytes(raw[28..32].try_into().unwrap()));
|
||||||
|
let digest = &raw[32..];
|
||||||
|
assert_ne!(digest, key, "key must not be sent");
|
||||||
|
assert_eq!(digest, digest_with_key::<D>(&raw, &key, 32));
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
seqs,
|
||||||
|
[u32::MAX, 0, 1, 2],
|
||||||
|
"meticulous sequence wraps by one"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tx_keyed_md5() {
|
||||||
|
check_keyed_tx::<Md5>(md5_auth(false, 7, 0), 24, 2).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tx_meticulous_keyed_md5() {
|
||||||
|
check_keyed_tx::<Md5>(md5_auth(true, 7, 0), 24, 3).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tx_keyed_sha1() {
|
||||||
|
check_keyed_tx::<Sha1>(sha1_auth(false, 7, 0), 28, 4).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tx_meticulous_keyed_sha1() {
|
||||||
|
check_keyed_tx::<Sha1>(sha1_auth(true, 7, 0), 28, 5).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5880 4.2, 6.7.2
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tx_simple_password() {
|
||||||
|
let (mut s, tap, _events) = keyed_session(password_auth(3, b"secret")).await;
|
||||||
|
s.transmit_control_packet(false).await;
|
||||||
|
let raw = recv_raw(&tap).await;
|
||||||
|
assert_eq!(raw.len(), 24 + 3 + 6);
|
||||||
|
assert_eq!(raw[3], 33);
|
||||||
|
assert_ne!(raw[1] & 0x04, 0);
|
||||||
|
assert_eq!(&raw[24..27], &[1, 9, 3]);
|
||||||
|
assert_eq!(&raw[27..], b"secret");
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5880 6.8.1: bfd.XmitAuthSeq SHOULD be random at session creation.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn initial_xmit_auth_seq_is_random() {
|
||||||
|
let mut seqs = HashSet::new();
|
||||||
|
for _ in 0..8 {
|
||||||
|
let (s, _tap, _events) = keyed_session(sha1_auth(true, 1, 0)).await;
|
||||||
|
seqs.insert(s.state.xmit_auth_seq.load(ORDERING));
|
||||||
|
}
|
||||||
|
assert!(seqs.len() > 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5880 6.7.3 / 6.7.4 receive rules.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_valid_keyed_packets_are_accepted() {
|
||||||
|
for auth in [
|
||||||
|
md5_auth(false, 1, 5),
|
||||||
|
md5_auth(true, 1, 5),
|
||||||
|
sha1_auth(false, 1, 5),
|
||||||
|
sha1_auth(true, 1, 5),
|
||||||
|
] {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(auth.clone()).await;
|
||||||
|
assert!(
|
||||||
|
accepted(
|
||||||
|
&mut s,
|
||||||
|
&signed(auth.clone(), BfdState::Down, REMOTE_DISCR, 0)
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
);
|
||||||
|
assert_eq!(s.state.auth_type(), auth.auth_type());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_bad_digest_is_discarded() {
|
||||||
|
for auth in [md5_auth(false, 1, 5), sha1_auth(true, 1, 5)] {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(auth.clone()).await;
|
||||||
|
let mut p = signed(auth.clone(), BfdState::Down, REMOTE_DISCR, 0);
|
||||||
|
p.desired_min_tx = BfdInterval::from_millis(1);
|
||||||
|
assert!(!accepted(&mut s, &p).await);
|
||||||
|
let wrong_key = match auth {
|
||||||
|
BfdAuth::KeyedMD5(a) => BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
|
||||||
|
digest: [9; 16],
|
||||||
|
..a
|
||||||
|
}),
|
||||||
|
BfdAuth::KeyedSHA1(a) => BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
|
||||||
|
digest: [9; 20],
|
||||||
|
..a
|
||||||
|
}),
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
|
assert!(!accepted(&mut s, &signed(wrong_key, BfdState::Down, REMOTE_DISCR, 0)).await);
|
||||||
|
assert_eq!(s.state.session_state(), BfdState::Down);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_unknown_key_id_is_discarded() {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(sha1_auth(false, 1, 0)).await;
|
||||||
|
assert!(
|
||||||
|
!accepted(
|
||||||
|
&mut s,
|
||||||
|
&signed(sha1_auth(false, 2, 5), BfdState::Down, REMOTE_DISCR, 0)
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
);
|
||||||
|
let (mut s, _tap, _events) = keyed_session(password_auth(1, b"pw")).await;
|
||||||
|
assert!(
|
||||||
|
!accepted(
|
||||||
|
&mut s,
|
||||||
|
&signed(password_auth(2, b"pw"), BfdState::Down, REMOTE_DISCR, 0)
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_wrong_auth_type_is_discarded() {
|
||||||
|
let cases = [
|
||||||
|
(sha1_auth(false, 1, 0), md5_auth(false, 1, 5)),
|
||||||
|
(md5_auth(false, 1, 0), md5_auth(true, 1, 5)),
|
||||||
|
(sha1_auth(true, 1, 0), sha1_auth(false, 1, 5)),
|
||||||
|
(md5_auth(false, 1, 0), password_auth(1, b"pw")),
|
||||||
|
(password_auth(1, b"pw"), sha1_auth(false, 1, 5)),
|
||||||
|
];
|
||||||
|
for (configured, received) in cases {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(configured.clone()).await;
|
||||||
|
let p = signed(received.clone(), BfdState::Down, REMOTE_DISCR, 0);
|
||||||
|
assert!(
|
||||||
|
!accepted(&mut s, &p).await,
|
||||||
|
"{:?} vs {:?}",
|
||||||
|
configured.auth_type(),
|
||||||
|
received.auth_type()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5880 6.8.6: the A bit must agree with whether authentication is in use.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_a_bit_must_match_authentication_in_use() {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(sha1_auth(false, 1, 0)).await;
|
||||||
|
assert!(!accepted(&mut s, &pkt(BfdState::Down, REMOTE_DISCR, 0)).await);
|
||||||
|
let (mut s, _tap, _events) = tapped(peer_cfg(300, 300, 3)).await;
|
||||||
|
let p = signed(sha1_auth(false, 1, 5), BfdState::Down, REMOTE_DISCR, 0);
|
||||||
|
assert!(!accepted(&mut s, &p).await);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_simple_password_must_match() {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(password_auth(1, b"secret")).await;
|
||||||
|
assert!(
|
||||||
|
!accepted(
|
||||||
|
&mut s,
|
||||||
|
&signed(password_auth(1, b"secreT"), BfdState::Down, REMOTE_DISCR, 0)
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!accepted(
|
||||||
|
&mut s,
|
||||||
|
&signed(password_auth(1, b"secre"), BfdState::Down, REMOTE_DISCR, 0)
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!accepted(
|
||||||
|
&mut s,
|
||||||
|
&signed(
|
||||||
|
password_auth(1, b"secrets"),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR,
|
||||||
|
0
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
accepted(
|
||||||
|
&mut s,
|
||||||
|
&signed(password_auth(1, b"secret"), BfdState::Down, REMOTE_DISCR, 0)
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5880 6.7.3 / 6.7.4: meticulous requires a strictly increasing sequence, non-meticulous allows repeats.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_sequence_replay_rules_depend_on_meticulous() {
|
||||||
|
for (meticulous, repeat_ok) in [(true, false), (false, true)] {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(sha1_auth(meticulous, 1, 0)).await;
|
||||||
|
let first = signed(
|
||||||
|
sha1_auth(meticulous, 1, 1000),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert!(accepted(&mut s, &first).await);
|
||||||
|
let repeat = signed(
|
||||||
|
sha1_auth(meticulous, 1, 1000),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR + 1,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
accepted(&mut s, &repeat).await,
|
||||||
|
repeat_ok,
|
||||||
|
"meticulous={meticulous}"
|
||||||
|
);
|
||||||
|
let next = signed(
|
||||||
|
sha1_auth(meticulous, 1, 1001),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR + 2,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert!(accepted(&mut s, &next).await);
|
||||||
|
let old = signed(
|
||||||
|
sha1_auth(meticulous, 1, 900),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR + 3,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert!(!accepted(&mut s, &old).await, "old seq");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A packet that fails authentication must not move the replay window, otherwise a forged packet could lock out the
|
||||||
|
// legitimate peer. (Deliberate deviation from the literal order of RFC 5880 6.7.3 / 6.7.4.)
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_failed_digest_does_not_update_sequence_state() {
|
||||||
|
for meticulous in [false, true] {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(sha1_auth(meticulous, 1, 0)).await;
|
||||||
|
let forge = |seq: u32| {
|
||||||
|
let mut p = signed(
|
||||||
|
sha1_auth(meticulous, 1, seq),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR + 100,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
p.desired_min_tx = BfdInterval::from_millis(1);
|
||||||
|
p
|
||||||
|
};
|
||||||
|
|
||||||
|
// Unknown state: a forged packet must not initialise the sequence state.
|
||||||
|
assert!(!accepted(&mut s, &forge(5000)).await);
|
||||||
|
assert!(!s.state.auth_seq_known());
|
||||||
|
let first = signed(
|
||||||
|
sha1_auth(meticulous, 1, 10),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert!(accepted(&mut s, &first).await);
|
||||||
|
assert_eq!(s.state.rcv_auth_seq.load(ORDERING), 10);
|
||||||
|
|
||||||
|
// Known state: a forged in-window packet must not advance it.
|
||||||
|
assert!(!accepted(&mut s, &forge(12)).await);
|
||||||
|
assert!(s.state.auth_seq_known());
|
||||||
|
assert_eq!(s.state.rcv_auth_seq.load(ORDERING), 10);
|
||||||
|
let next = signed(
|
||||||
|
sha1_auth(meticulous, 1, 11),
|
||||||
|
BfdState::Down,
|
||||||
|
REMOTE_DISCR + 1,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
assert!(accepted(&mut s, &next).await);
|
||||||
|
assert_eq!(s.state.rcv_auth_seq.load(ORDERING), 11);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 5880 6.7.3 / 6.7.4: Auth Len other than 24 / 28 is discarded (here via the digest, which covers the length).
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rx_keyed_auth_len_other_than_24_or_28_is_discarded() {
|
||||||
|
for auth in [md5_auth(false, 1, 5), sha1_auth(false, 1, 5)] {
|
||||||
|
let (mut s, _tap, _events) = keyed_session(auth.clone()).await;
|
||||||
|
let mut raw = signed(auth.clone(), BfdState::Down, REMOTE_DISCR, 0)
|
||||||
|
.serialize()
|
||||||
|
.unwrap();
|
||||||
|
raw[25] += 4;
|
||||||
|
raw[3] += 4;
|
||||||
|
raw.extend_from_slice(&[0; 4]);
|
||||||
|
let p = BfdPacket::parse(&raw).unwrap().1;
|
||||||
|
assert!(!accepted(&mut s, &p).await, "{:?}", auth.auth_type());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
+240
-348
@@ -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
|
//! [`Config`] is the file's model. [`Config::resolve`] validates it and produces a [`ResolvedConfig`] with all per-peer
|
||||||
//! settings only), command line (`--bind` replaces, `--peer` adds). Per-peer settings can only come from the file; peers
|
//! inheritance applied, which is what the daemon runs from.
|
||||||
//! 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.
|
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashSet,
|
collections::HashSet,
|
||||||
@@ -16,20 +12,13 @@ use std::{
|
|||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use serde::{de, Deserialize, Deserializer, Serialize};
|
use serde::Deserialize;
|
||||||
use serde_valid::Validate;
|
|
||||||
|
|
||||||
use crate::bfd::{BfdAuth, BfdAuthKeyedMD5, BfdAuthKeyedSHA1, BfdAuthSimplePassword, BfdInterval};
|
use crate::bfd::{BfdAuth, BfdAuthKeyedMD5, BfdAuthKeyedSHA1, BfdAuthSimplePassword, BfdInterval};
|
||||||
|
|
||||||
pub const DEFAULT_CONFIG_PATH: &str = "/etc/rust-bfd/config.yaml";
|
pub const DEFAULT_CONFIG_PATH: &str = "/etc/rust-bfd/config.yaml";
|
||||||
pub const DEFAULT_HOOKS_DIR: &str = "/etc/rust-bfd/hooks.d";
|
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 {
|
fn default_true() -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
@@ -44,10 +33,6 @@ pub enum ConfigError {
|
|||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
source: serde_yaml_ng::Error,
|
source: serde_yaml_ng::Error,
|
||||||
},
|
},
|
||||||
Env {
|
|
||||||
var: &'static str,
|
|
||||||
message: String,
|
|
||||||
},
|
|
||||||
Invalid(String),
|
Invalid(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,9 +45,6 @@ impl fmt::Display for ConfigError {
|
|||||||
Self::Parse { path, source } => {
|
Self::Parse { path, source } => {
|
||||||
write!(f, "invalid config file `{}`: {source}", path.display())
|
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}"),
|
Self::Invalid(message) => write!(f, "invalid configuration: {message}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,13 +55,13 @@ impl Error for ConfigError {
|
|||||||
match self {
|
match self {
|
||||||
Self::Io { source, .. } => Some(source),
|
Self::Io { source, .. } => Some(source),
|
||||||
Self::Parse { 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.
|
/// 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)]
|
#[serde(default, deny_unknown_fields)]
|
||||||
pub struct Defaults {
|
pub struct Defaults {
|
||||||
#[serde(with = "humantime_serde")]
|
#[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)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct PasswordAuthConfig {
|
pub struct PasswordAuthConfig {
|
||||||
pub key_id: u8,
|
pub key_id: u8,
|
||||||
#[serde(with = "serde_bytes")]
|
#[serde(with = "serde_bytes")]
|
||||||
// The password is a binary string, and MUST be 1 to 16 bytes in
|
// The password is a binary string, and MUST be 1 to 16 bytes in length (checked in `Config::resolve`).
|
||||||
// length.
|
|
||||||
#[validate(min_items = 1)]
|
|
||||||
#[validate(max_items = 16)]
|
|
||||||
pub password: Vec<u8>,
|
pub password: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Validate)]
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Md5AuthConfig {
|
pub struct Md5AuthConfig {
|
||||||
pub key_id: u8,
|
pub key_id: u8,
|
||||||
@@ -122,7 +101,7 @@ pub struct Md5AuthConfig {
|
|||||||
pub meticulous: bool,
|
pub meticulous: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Validate)]
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct Sha1AuthConfig {
|
pub struct Sha1AuthConfig {
|
||||||
pub key_id: u8,
|
pub key_id: u8,
|
||||||
@@ -133,7 +112,7 @@ pub struct Sha1AuthConfig {
|
|||||||
pub meticulous: bool,
|
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")]
|
#[serde(deny_unknown_fields, tag = "type", rename_all = "lowercase")]
|
||||||
pub enum AuthConfig {
|
pub enum AuthConfig {
|
||||||
Password(PasswordAuthConfig),
|
Password(PasswordAuthConfig),
|
||||||
@@ -150,12 +129,14 @@ impl From<AuthConfig> for BfdAuth {
|
|||||||
}),
|
}),
|
||||||
AuthConfig::Md5(ac) => BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
|
AuthConfig::Md5(ac) => BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
|
||||||
key_id: ac.key_id,
|
key_id: ac.key_id,
|
||||||
|
reserved: 0,
|
||||||
meticulous: ac.meticulous,
|
meticulous: ac.meticulous,
|
||||||
digest: ac.key,
|
digest: ac.key,
|
||||||
seq: 0, // set during signing
|
seq: 0, // set during signing
|
||||||
}),
|
}),
|
||||||
AuthConfig::Sha1(ac) => BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
|
AuthConfig::Sha1(ac) => BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
|
||||||
key_id: ac.key_id,
|
key_id: ac.key_id,
|
||||||
|
reserved: 0,
|
||||||
meticulous: ac.meticulous,
|
meticulous: ac.meticulous,
|
||||||
digest: ac.key,
|
digest: ac.key,
|
||||||
seq: 0, // set during signing
|
seq: 0, // set during signing
|
||||||
@@ -164,47 +145,30 @@ impl From<AuthConfig> for BfdAuth {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
#[serde(deny_unknown_fields)]
|
#[serde(deny_unknown_fields)]
|
||||||
pub struct PeerConfig {
|
pub struct PeerConfig {
|
||||||
pub address: IpAddr,
|
pub address: IpAddr,
|
||||||
#[serde(
|
/// Local address the session runs from: the source of its control packets, and the address the daemon listens
|
||||||
default,
|
/// on for the peer's. Must be of the same address family as `address`.
|
||||||
skip_serializing_if = "Option::is_none",
|
pub local: IpAddr,
|
||||||
with = "humantime_serde"
|
/// Bind the session's sockets to this interface (`SO_BINDTODEVICE`). Required when `local` or `address` is an
|
||||||
)]
|
/// IPv6 link-local address.
|
||||||
|
#[serde(default)]
|
||||||
|
pub interface: Option<String>,
|
||||||
|
#[serde(default, with = "humantime_serde")]
|
||||||
pub desired_min_tx: Option<Duration>,
|
pub desired_min_tx: Option<Duration>,
|
||||||
#[serde(
|
#[serde(default, with = "humantime_serde")]
|
||||||
default,
|
|
||||||
skip_serializing_if = "Option::is_none",
|
|
||||||
with = "humantime_serde"
|
|
||||||
)]
|
|
||||||
pub required_min_rx: Option<Duration>,
|
pub required_min_rx: Option<Duration>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default)]
|
||||||
pub detect_mult: Option<u8>,
|
pub detect_mult: Option<u8>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default)]
|
||||||
pub auth: Option<AuthConfig>,
|
pub auth: Option<AuthConfig>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PeerConfig {
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
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)]
|
|
||||||
#[serde(default, deny_unknown_fields)]
|
#[serde(default, deny_unknown_fields)]
|
||||||
pub struct Config {
|
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<IpAddr>,
|
|
||||||
/// Directory of executable state-change hook scripts.
|
/// Directory of executable state-change hook scripts.
|
||||||
pub hooks_dir: PathBuf,
|
pub hooks_dir: PathBuf,
|
||||||
pub defaults: Defaults,
|
pub defaults: Defaults,
|
||||||
@@ -214,7 +178,6 @@ pub struct Config {
|
|||||||
impl Default for Config {
|
impl Default for Config {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
bind: Vec::new(),
|
|
||||||
hooks_dir: PathBuf::from(DEFAULT_HOOKS_DIR),
|
hooks_dir: PathBuf::from(DEFAULT_HOOKS_DIR),
|
||||||
defaults: Defaults::default(),
|
defaults: Defaults::default(),
|
||||||
peers: Vec::new(),
|
peers: Vec::new(),
|
||||||
@@ -222,106 +185,28 @@ impl Default for Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_bind_list(s: &str) -> Result<Vec<IpAddr>, 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<Vec<IpAddr>, D::Error> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(untagged)]
|
|
||||||
enum OneOrMany {
|
|
||||||
One(String),
|
|
||||||
Many(Vec<String>),
|
|
||||||
}
|
|
||||||
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 {
|
impl Config {
|
||||||
pub fn from_yaml(yaml: &str) -> Result<Self, serde_yaml_ng::Error> {
|
pub fn from_yaml(yaml: &str) -> Result<Self, serde_yaml_ng::Error> {
|
||||||
// An empty (or comment-only) document is a null value, which means "all defaults".
|
// An empty (or comment-only) document is a null value, which means "all defaults".
|
||||||
Ok(serde_yaml_ng::from_str::<Option<Self>>(yaml)?.unwrap_or_default())
|
Ok(serde_yaml_ng::from_str::<Option<Self>>(yaml)?.unwrap_or_default())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_file(path: &Path) -> Result<Self, ConfigError> {
|
|
||||||
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
|
/// Load the config file. An explicit `path` must exist; with `None`, [`DEFAULT_CONFIG_PATH`] is used if present and
|
||||||
/// built-in defaults otherwise.
|
/// built-in defaults otherwise.
|
||||||
pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
|
pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
|
||||||
match path {
|
let optional = path.is_none();
|
||||||
Some(path) => Self::from_file(path),
|
let path = path.unwrap_or(Path::new(DEFAULT_CONFIG_PATH));
|
||||||
None => match Self::from_file(Path::new(DEFAULT_CONFIG_PATH)) {
|
let to_owned = || path.to_owned();
|
||||||
Err(ConfigError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
|
match fs::read_to_string(path) {
|
||||||
Ok(Self::default())
|
Ok(yaml) => Self::from_yaml(&yaml).map_err(|source| ConfigError::Parse {
|
||||||
}
|
path: to_owned(),
|
||||||
other => other,
|
source,
|
||||||
},
|
}),
|
||||||
}
|
Err(e) if optional && e.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
|
||||||
}
|
Err(source) => Err(ConfigError::Io {
|
||||||
|
path: to_owned(),
|
||||||
/// Override global settings from `BFD_*` variables supplied by `var`. Unset and empty variables are ignored.
|
source,
|
||||||
pub fn apply_env(&mut self, var: impl Fn(&str) -> Option<String>) -> 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<IpAddr>, peers: impl IntoIterator<Item = IpAddr>) {
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,35 +214,42 @@ impl Config {
|
|||||||
pub fn resolve(self) -> Result<ResolvedConfig, ConfigError> {
|
pub fn resolve(self) -> Result<ResolvedConfig, ConfigError> {
|
||||||
let invalid = |message: String| ConfigError::Invalid(message);
|
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 mut seen = HashSet::new();
|
||||||
let peers = self
|
let peers = self
|
||||||
.peers
|
.peers
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|peer| {
|
.map(|peer| {
|
||||||
if !seen.insert(peer.address) {
|
if !seen.insert((peer.local, peer.interface.clone(), peer.address)) {
|
||||||
return Err(invalid(format!("duplicate peer {}", peer.address)));
|
|
||||||
}
|
|
||||||
if !self
|
|
||||||
.bind
|
|
||||||
.iter()
|
|
||||||
.any(|b| b.is_ipv4() == peer.address.is_ipv4())
|
|
||||||
{
|
|
||||||
return Err(invalid(format!(
|
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
|
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);
|
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);
|
let detect_mult = peer.detect_mult.unwrap_or(self.defaults.detect_mult);
|
||||||
if detect_mult == 0 {
|
if detect_mult == 0 {
|
||||||
return Err(invalid(format!(
|
return Err(invalid(format!(
|
||||||
@@ -367,6 +259,8 @@ impl Config {
|
|||||||
}
|
}
|
||||||
Ok(ResolvedPeer {
|
Ok(ResolvedPeer {
|
||||||
address: peer.address,
|
address: peer.address,
|
||||||
|
local: peer.local,
|
||||||
|
interface: peer.interface,
|
||||||
desired_min_tx: to_interval(
|
desired_min_tx: to_interval(
|
||||||
peer.desired_min_tx.unwrap_or(self.defaults.desired_min_tx),
|
peer.desired_min_tx.unwrap_or(self.defaults.desired_min_tx),
|
||||||
&what("desired_min_tx"),
|
&what("desired_min_tx"),
|
||||||
@@ -391,13 +285,29 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(ResolvedConfig {
|
Ok(ResolvedConfig {
|
||||||
bind: self.bind.clone(),
|
hooks_dir: self.hooks_dir,
|
||||||
hooks_dir: self.hooks_dir.clone(),
|
|
||||||
peers,
|
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
|
/// 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.
|
/// stop sending periodic packets) but is not supported here.
|
||||||
fn to_interval(value: Duration, what: &str) -> Result<BfdInterval, ConfigError> {
|
fn to_interval(value: Duration, what: &str) -> Result<BfdInterval, ConfigError> {
|
||||||
@@ -420,7 +330,6 @@ fn to_interval(value: Duration, what: &str) -> Result<BfdInterval, ConfigError>
|
|||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ResolvedConfig {
|
pub struct ResolvedConfig {
|
||||||
pub bind: Vec<IpAddr>,
|
|
||||||
pub hooks_dir: PathBuf,
|
pub hooks_dir: PathBuf,
|
||||||
pub peers: Vec<ResolvedPeer>,
|
pub peers: Vec<ResolvedPeer>,
|
||||||
}
|
}
|
||||||
@@ -428,6 +337,8 @@ pub struct ResolvedConfig {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ResolvedPeer {
|
pub struct ResolvedPeer {
|
||||||
pub address: IpAddr,
|
pub address: IpAddr,
|
||||||
|
pub local: IpAddr,
|
||||||
|
pub interface: Option<String>,
|
||||||
pub desired_min_tx: BfdInterval,
|
pub desired_min_tx: BfdInterval,
|
||||||
pub required_min_rx: BfdInterval,
|
pub required_min_rx: BfdInterval,
|
||||||
pub detect_mult: u8,
|
pub detect_mult: u8,
|
||||||
@@ -436,24 +347,40 @@ pub struct ResolvedPeer {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use rstest::rstest;
|
||||||
|
|
||||||
|
enum Expect {
|
||||||
|
Ok,
|
||||||
|
Err,
|
||||||
|
ErrContaining(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(result: Result<ResolvedConfig, ConfigError>, expect: Expect) {
|
||||||
|
match expect {
|
||||||
|
Expect::Ok => assert!(result.is_ok()),
|
||||||
|
Expect::Err => assert!(result.is_err()),
|
||||||
|
Expect::ErrContaining(s) => assert!(result.unwrap_err().to_string().contains(s)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn ip(s: &str) -> IpAddr {
|
fn ip(s: &str) -> IpAddr {
|
||||||
s.parse().unwrap()
|
s.parse().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
|
fn peer(address: &str, local: &str) -> PeerConfig {
|
||||||
let map: HashMap<String, String> = pairs
|
PeerConfig {
|
||||||
.iter()
|
address: ip(address),
|
||||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
local: ip(local),
|
||||||
.collect();
|
interface: None,
|
||||||
move |k| map.get(k).cloned()
|
desired_min_tx: None,
|
||||||
|
required_min_rx: None,
|
||||||
|
detect_mult: None,
|
||||||
|
auth: None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const FULL: &str = "
|
const FULL: &str = "
|
||||||
bind: 192.0.2.1
|
|
||||||
hooks_dir: /tmp/hooks
|
hooks_dir: /tmp/hooks
|
||||||
defaults:
|
defaults:
|
||||||
desired_min_tx: 500ms
|
desired_min_tx: 500ms
|
||||||
@@ -461,7 +388,9 @@ defaults:
|
|||||||
detect_mult: 5
|
detect_mult: 5
|
||||||
peers:
|
peers:
|
||||||
- address: 192.0.2.2
|
- address: 192.0.2.2
|
||||||
|
local: 192.0.2.1
|
||||||
- address: 192.0.2.3
|
- address: 192.0.2.3
|
||||||
|
local: 192.0.2.1
|
||||||
desired_min_tx: 1s
|
desired_min_tx: 1s
|
||||||
detect_mult: 4
|
detect_mult: 4
|
||||||
";
|
";
|
||||||
@@ -469,7 +398,7 @@ peers:
|
|||||||
#[test]
|
#[test]
|
||||||
fn parses_full_config() {
|
fn parses_full_config() {
|
||||||
let config = Config::from_yaml(FULL).unwrap();
|
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.hooks_dir, PathBuf::from("/tmp/hooks"));
|
||||||
assert_eq!(config.defaults.desired_min_tx, Duration::from_millis(500));
|
assert_eq!(config.defaults.desired_min_tx, Duration::from_millis(500));
|
||||||
assert_eq!(config.peers.len(), 2);
|
assert_eq!(config.peers.len(), 2);
|
||||||
@@ -477,10 +406,11 @@ peers:
|
|||||||
assert_eq!(config.peers[0].detect_mult, None);
|
assert_eq!(config.peers[0].detect_mult, None);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn empty_and_comment_only_documents_are_defaults() {
|
#[case::empty("")]
|
||||||
assert_eq!(Config::from_yaml("").unwrap(), Config::default());
|
#[case::comment_only("# nothing\n")]
|
||||||
assert_eq!(Config::from_yaml("# nothing\n").unwrap(), Config::default());
|
fn empty_and_comment_only_documents_are_defaults(#[case] yaml: &str) {
|
||||||
|
assert_eq!(Config::from_yaml(yaml).unwrap(), Config::default());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -503,73 +433,30 @@ peers:
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bind_accepts_scalar_list_and_comma_string() {
|
fn peers_may_use_different_local_addresses() {
|
||||||
for yaml in [
|
let config = Config::from_yaml(
|
||||||
"bind: 192.0.2.1",
|
"peers:
|
||||||
"bind: [192.0.2.1]",
|
- {address: 192.0.2.2, local: 192.0.2.1}
|
||||||
"bind: \"192.0.2.1\"",
|
- {address: 2001:db8::2, local: '2001:db8::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);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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();
|
.unwrap();
|
||||||
assert_eq!(config.bind, vec![ip("192.0.2.9")]);
|
assert_eq!(config.peers[1].local, ip("2001:db8::1"));
|
||||||
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]
|
#[rstest]
|
||||||
fn env_bind_accepts_multiple_addresses() {
|
#[case::misspelled_top_level_field("bnid: 192.0.2.1")]
|
||||||
for value in [
|
#[case::removed_top_level_field("bind: 192.0.2.1")]
|
||||||
"192.0.2.1,2001:db8::1",
|
#[case::unknown_defaults_field("defaults:\n desired_min_txx: 1s")]
|
||||||
"192.0.2.1, 2001:db8::1",
|
#[case::unknown_peer_field(
|
||||||
"192.0.2.1 2001:db8::1",
|
"peers:\n - address: 192.0.2.2\n local: 192.0.2.1\n color: red"
|
||||||
] {
|
)]
|
||||||
let mut config = Config::default();
|
#[case::invalid_local_address("peers:\n - address: 192.0.2.2\n local: not-an-ip")]
|
||||||
config.apply_env(env(&[(ENV_BIND, value)])).unwrap();
|
#[case::invalid_interval("defaults:\n desired_min_tx: soon")]
|
||||||
assert_eq!(
|
#[case::peer_without_address("peers:\n - detect_mult: 3")]
|
||||||
config.bind,
|
#[case::peer_without_local("peers:\n - address: 192.0.2.2")]
|
||||||
vec![ip("192.0.2.1"), ip("2001:db8::1")],
|
fn rejects_unknown_fields_and_bad_values(#[case] yaml: &str) {
|
||||||
"{value}"
|
assert!(Config::from_yaml(yaml).is_err());
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -581,110 +468,115 @@ peers:
|
|||||||
assert_eq!(resolved.peers.len(), 1);
|
assert_eq!(resolved.peers.len(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn env_ignores_empty_and_unrelated_variables() {
|
#[case::valid_base(|_: &mut Config| {}, Expect::Ok)]
|
||||||
let mut config = Config::from_yaml(FULL).unwrap();
|
#[case::duplicate_peer(
|
||||||
config
|
|c: &mut Config| c.peers.push(peer("192.0.2.2", "192.0.2.1")),
|
||||||
.apply_env(env(&[
|
Expect::ErrContaining("duplicate peer")
|
||||||
(ENV_BIND, ""),
|
)]
|
||||||
(ENV_DEFAULTS_DETECT_MULT, " "),
|
#[case::same_peer_from_different_local_addresses(
|
||||||
("BFD_PEERS", "192.0.2.99"),
|
|c: &mut Config| c.peers.push(peer("192.0.2.2", "192.0.2.9")),
|
||||||
("BFD_PEER", "192.0.2.98"),
|
Expect::Ok
|
||||||
("BFD_ADDR", "192.0.2.97"),
|
)]
|
||||||
]))
|
#[case::address_family_mismatch(
|
||||||
.unwrap();
|
|c: &mut Config| c.peers[0].local = ip("2001:db8::1"),
|
||||||
assert_eq!(config, Config::from_yaml(FULL).unwrap());
|
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]
|
#[test]
|
||||||
fn env_errors_name_the_variable() {
|
fn same_address_on_two_interfaces_is_two_sessions() {
|
||||||
for (var, value) in [
|
let mut c = Config::from_yaml("").unwrap();
|
||||||
(ENV_BIND, "nope"),
|
for iface in ["eth1", "eth2"] {
|
||||||
(ENV_DEFAULTS_DESIRED_MIN_TX, "fast"),
|
c.peers.push(PeerConfig {
|
||||||
(ENV_DEFAULTS_DETECT_MULT, "-1"),
|
interface: Some(iface.into()),
|
||||||
(ENV_DEFAULTS_DETECT_MULT, "300"),
|
..peer("fe80::2", "fe80::1")
|
||||||
] {
|
});
|
||||||
let err = Config::default()
|
|
||||||
.apply_env(env(&[(var, value)]))
|
|
||||||
.unwrap_err();
|
|
||||||
assert!(err.to_string().contains(var), "{err}");
|
|
||||||
}
|
}
|
||||||
|
assert!(c.clone().resolve().is_ok());
|
||||||
|
c.peers[1].interface = Some("eth1".into());
|
||||||
|
assert!(c.resolve().unwrap_err().to_string().contains("duplicate"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn cli_bind_replaces_and_peers_merge() {
|
#[case::empty(b"", Expect::Err)]
|
||||||
let mut config = Config::from_yaml(FULL).unwrap();
|
#[case::one_byte(b"a", Expect::Ok)]
|
||||||
config.apply_cli(
|
#[case::sixteen_bytes(&[b'a'; 16], Expect::Ok)]
|
||||||
vec![ip("192.0.2.7"), ip("2001:db8::7")],
|
#[case::seventeen_bytes(&[b'a'; 17], Expect::ErrContaining("1 to 16 bytes"))]
|
||||||
[ip("192.0.2.3"), ip("192.0.2.4"), ip("192.0.2.4")],
|
fn password_length_is_limited_to_16_bytes(#[case] password: &[u8], #[case] expect: Expect) {
|
||||||
);
|
let mut c = Config::from_yaml("").unwrap();
|
||||||
assert_eq!(config.bind, vec![ip("192.0.2.7"), ip("2001:db8::7")]);
|
c.peers.push(PeerConfig {
|
||||||
let addrs: Vec<_> = config.peers.iter().map(|p| p.address).collect();
|
auth: Some(AuthConfig::Password(PasswordAuthConfig {
|
||||||
assert_eq!(
|
key_id: 1,
|
||||||
addrs,
|
password: password.to_vec(),
|
||||||
vec![ip("192.0.2.2"), ip("192.0.2.3"), ip("192.0.2.4")]
|
})),
|
||||||
);
|
..peer("192.0.2.2", "192.0.2.1")
|
||||||
// The file's settings for an existing peer win over the bare CLI entry.
|
});
|
||||||
assert_eq!(config.peers[1].detect_mult, Some(4));
|
check(c.resolve(), expect);
|
||||||
|
|
||||||
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());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn zero_peers_is_valid() {
|
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());
|
assert!(config.resolve().unwrap().peers.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
+53
-38
@@ -27,6 +27,7 @@ pub struct StateChangeEvent {
|
|||||||
pub remote_discr: BfdDiscriminator,
|
pub remote_discr: BfdDiscriminator,
|
||||||
pub local_ip: IpAddr,
|
pub local_ip: IpAddr,
|
||||||
pub remote_ip: IpAddr,
|
pub remote_ip: IpAddr,
|
||||||
|
pub interface: Option<String>,
|
||||||
pub from_state: BfdState,
|
pub from_state: BfdState,
|
||||||
pub to_state: BfdState,
|
pub to_state: BfdState,
|
||||||
}
|
}
|
||||||
@@ -144,6 +145,7 @@ impl ScriptHookSink {
|
|||||||
let local_ip_str = OsString::from(event.local_ip.to_string());
|
let local_ip_str = OsString::from(event.local_ip.to_string());
|
||||||
let remote_discr_str = OsString::from(event.remote_discr.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 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(event.to_state.into());
|
||||||
args.push(&remote_ip_str);
|
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_STATE"), event.to_state.into()));
|
||||||
env.push((OsStr::new("BFD_LOCAL_ADDR"), &local_ip_str));
|
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_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_LOCAL_DISCRIMINATOR"), &local_discr_str));
|
||||||
env.push((OsStr::new("BFD_PEER_DISCRIMINATOR"), &remote_discr_str));
|
env.push((OsStr::new("BFD_PEER_DISCRIMINATOR"), &remote_discr_str));
|
||||||
for script in scripts {
|
for script in scripts {
|
||||||
@@ -175,11 +178,11 @@ impl ScriptHookSink {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use rstest::rstest;
|
||||||
use std::{
|
use std::{
|
||||||
fs::{self as stdfs, Permissions},
|
fs::{self as stdfs, Permissions},
|
||||||
net::{Ipv4Addr, Ipv6Addr},
|
net::{Ipv4Addr, Ipv6Addr},
|
||||||
os::unix::fs::PermissionsExt,
|
os::unix::fs::PermissionsExt,
|
||||||
path::Path,
|
|
||||||
sync::atomic::{AtomicU32, Ordering},
|
sync::atomic::{AtomicU32, Ordering},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
@@ -231,6 +234,7 @@ mod tests {
|
|||||||
remote_discr: BfdDiscriminator(22),
|
remote_discr: BfdDiscriminator(22),
|
||||||
local_ip: local,
|
local_ip: local,
|
||||||
remote_ip: remote,
|
remote_ip: remote,
|
||||||
|
interface: None,
|
||||||
from_state: from,
|
from_state: from,
|
||||||
to_state: to,
|
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";
|
const ENV_LINE: &str = "$1|$2|$BFD_STATE|$BFD_LAST_STATE|$BFD_LOCAL_ADDR|$BFD_PEER_ADDR|$BFD_LOCAL_DISCRIMINATOR|$BFD_PEER_DISCRIMINATOR";
|
||||||
|
|
||||||
#[tokio::test]
|
#[rstest]
|
||||||
async fn passes_args_and_environment() {
|
#[case::v4(
|
||||||
let t = TempDir::new();
|
Ipv4Addr::new(192, 0, 2, 1).into(),
|
||||||
t.append_script("10-env", 0o755, ENV_LINE);
|
Ipv4Addr::new(192, 0, 2, 2).into(),
|
||||||
ScriptHookSink::with_script_dir(t.hooks())
|
BfdState::Init,
|
||||||
.handle_event(&v4_event())
|
BfdState::Up,
|
||||||
.await;
|
"up|192.0.2.2|up|init|192.0.2.1|192.0.2.2|11|22"
|
||||||
assert_eq!(
|
)]
|
||||||
t.output(),
|
#[case::v6(
|
||||||
["Up|192.0.2.2|Up|Init|192.0.2.1|192.0.2.2|11|22"]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn passes_ipv6_addresses() {
|
|
||||||
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, 1).into(),
|
||||||
Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2).into(),
|
Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2).into(),
|
||||||
BfdState::Up,
|
BfdState::Up,
|
||||||
BfdState::Down,
|
BfdState::Down,
|
||||||
);
|
"down|2001:db8::2|down|up|2001:db8::1|2001:db8::2|11|22"
|
||||||
|
)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn passes_args_and_environment(
|
||||||
|
#[case] local: IpAddr,
|
||||||
|
#[case] remote: IpAddr,
|
||||||
|
#[case] from: BfdState,
|
||||||
|
#[case] to: BfdState,
|
||||||
|
#[case] expected: &str,
|
||||||
|
) {
|
||||||
|
let t = TempDir::new();
|
||||||
|
t.append_script("10-env", 0o755, ENV_LINE);
|
||||||
ScriptHookSink::with_script_dir(t.hooks())
|
ScriptHookSink::with_script_dir(t.hooks())
|
||||||
.handle_event(&ev)
|
.handle_event(&event(local, remote, from, to))
|
||||||
.await;
|
.await;
|
||||||
assert_eq!(
|
assert_eq!(t.output(), [expected]);
|
||||||
t.output(),
|
}
|
||||||
["Down|2001:db8::2|Down|Up|2001:db8::1|2001:db8::2|11|22"]
|
|
||||||
);
|
#[tokio::test]
|
||||||
|
async fn passes_interface() {
|
||||||
|
let t = TempDir::new();
|
||||||
|
t.append_script("10-env", 0o755, "${BFD_INTERFACE-unset}|$BFD_PEER_ADDR");
|
||||||
|
let sink = ScriptHookSink::with_script_dir(t.hooks());
|
||||||
|
sink.handle_event(&v4_event()).await;
|
||||||
|
sink.handle_event(&EventMessage::StateChange(StateChangeEvent {
|
||||||
|
local_discr: BfdDiscriminator(11),
|
||||||
|
remote_discr: BfdDiscriminator(22),
|
||||||
|
local_ip: "fe80::1".parse().unwrap(),
|
||||||
|
remote_ip: "fe80::2".parse().unwrap(),
|
||||||
|
interface: Some("eth1".to_owned()),
|
||||||
|
from_state: BfdState::Init,
|
||||||
|
to_state: BfdState::Up,
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
assert_eq!(t.output(), ["|192.0.2.2", "eth1|fe80::2"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -335,20 +357,13 @@ mod tests {
|
|||||||
assert_eq!(t.output(), ["ok"]);
|
assert_eq!(t.output(), ["ok"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[case::missing_dir("nope")]
|
||||||
|
#[case::empty_dir("hooks")]
|
||||||
#[tokio::test]
|
#[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 t = TempDir::new();
|
||||||
let missing: &Path = &t.0.join("nope");
|
ScriptHookSink::with_script_dir(t.0.join(subdir))
|
||||||
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())
|
|
||||||
.handle_event(&v4_event())
|
.handle_event(&v4_event())
|
||||||
.await;
|
.await;
|
||||||
assert!(t.output().is_empty());
|
assert!(t.output().is_empty());
|
||||||
@@ -379,6 +394,6 @@ mod tests {
|
|||||||
handle.abort();
|
handle.abort();
|
||||||
let out = t.output();
|
let out = t.output();
|
||||||
assert_eq!(out.len(), 2);
|
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|"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+257
-70
@@ -4,14 +4,23 @@ pub mod control;
|
|||||||
pub mod events;
|
pub mod events;
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
|
ffi::OsString,
|
||||||
fmt::{self, Display},
|
fmt::{self, Display},
|
||||||
net::IpAddr,
|
io,
|
||||||
|
net::{IpAddr, SocketAddr, SocketAddrV6},
|
||||||
|
os::fd::AsRawFd,
|
||||||
sync::atomic::{AtomicU64, Ordering},
|
sync::atomic::{AtomicU64, Ordering},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
use log::debug;
|
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 tokio::net::UdpSocket;
|
||||||
|
|
||||||
use crate::bfd::*;
|
use crate::bfd::*;
|
||||||
@@ -197,8 +206,10 @@ pub struct BfdSessionStats {
|
|||||||
pub remote_discr: BfdDiscriminator,
|
pub remote_discr: BfdDiscriminator,
|
||||||
pub state: BfdState,
|
pub state: BfdState,
|
||||||
pub last_diag: BfdDiagnostic,
|
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,
|
pub rx: IntervalStats,
|
||||||
|
/// Every packet received over the life of the session, including discarded ones
|
||||||
|
pub rx_received: u64,
|
||||||
pub tx: IntervalStats,
|
pub tx: IntervalStats,
|
||||||
pub last_up: Option<Instant>,
|
pub last_up: Option<Instant>,
|
||||||
pub last_down: Option<Instant>,
|
pub last_down: Option<Instant>,
|
||||||
@@ -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<UdpSocket> {
|
||||||
|
let family = match addr {
|
||||||
|
SocketAddr::V4(_) => AddressFamily::Inet,
|
||||||
|
SocketAddr::V6(_) => AddressFamily::Inet6,
|
||||||
|
};
|
||||||
|
let fd = socket(
|
||||||
|
family,
|
||||||
|
SockType::Datagram,
|
||||||
|
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
|
||||||
|
None::<SockProtocol>,
|
||||||
|
)?;
|
||||||
|
if let Some(name) = interface {
|
||||||
|
setsockopt(&fd, sockopt::BindToDevice, &OsString::from(name))?;
|
||||||
|
}
|
||||||
|
match addr {
|
||||||
|
SocketAddr::V4(a) => bind(fd.as_raw_fd(), &SockaddrIn::from(a)),
|
||||||
|
SocketAddr::V6(a) => bind(fd.as_raw_fd(), &SockaddrIn6::from(a)),
|
||||||
|
}?;
|
||||||
|
UdpSocket::from_std(std::net::UdpSocket::from(fd))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A socket address for `ip`:`port`. An IPv6 link-local address is only meaningful with a scope, so it is scoped to
|
||||||
|
/// `interface`, which is then required.
|
||||||
|
pub fn scoped_socket_addr(
|
||||||
|
ip: IpAddr,
|
||||||
|
port: u16,
|
||||||
|
interface: Option<&str>,
|
||||||
|
) -> io::Result<SocketAddr> {
|
||||||
|
match (ip, interface) {
|
||||||
|
(IpAddr::V6(v6), Some(name)) if is_ipv6_link_local(&ip) => {
|
||||||
|
let scope_id = if_nametoindex(name)?;
|
||||||
|
Ok(SocketAddr::V6(SocketAddrV6::new(v6, port, 0, scope_id)))
|
||||||
|
}
|
||||||
|
(_, None) if is_ipv6_link_local(&ip) => Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
format!("link-local address {ip} requires an interface"),
|
||||||
|
)),
|
||||||
|
_ => Ok(SocketAddr::new(ip, port)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Have the kernel discard datagrams that arrive with a TTL (IPv4) or Hop Limit (IPv6) other than `hop_limit`.
|
||||||
|
///
|
||||||
|
/// `IP_MINTTL` and `IPV6_MINHOPCOUNT` are only enforced for TCP, so this attaches a classic BPF socket filter that
|
||||||
|
/// reads the field from the network header (`SKF_NET_OFF`). Discards are silent.
|
||||||
|
pub fn require_hop_limit(sock: &UdpSocket, hop_limit: u8) -> io::Result<()> {
|
||||||
|
// Offset of the TTL in the IPv4 header, and of the Hop Limit in the IPv6 header
|
||||||
|
let field_offset = if sock.local_addr()?.is_ipv4() { 8 } else { 7 };
|
||||||
|
let insn = |code: u32, jt: u8, jf: u8, k: u32| nix::libc::sock_filter {
|
||||||
|
code: code as u16,
|
||||||
|
jt,
|
||||||
|
jf,
|
||||||
|
k,
|
||||||
|
};
|
||||||
|
let mut program = [
|
||||||
|
// A = the TTL / Hop Limit byte
|
||||||
|
insn(
|
||||||
|
nix::libc::BPF_LD | nix::libc::BPF_B | nix::libc::BPF_ABS,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
(nix::libc::SKF_NET_OFF + field_offset) as u32,
|
||||||
|
),
|
||||||
|
// if A == hop_limit, skip the drop
|
||||||
|
insn(
|
||||||
|
nix::libc::BPF_JMP | nix::libc::BPF_JEQ | nix::libc::BPF_K,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
hop_limit as u32,
|
||||||
|
),
|
||||||
|
insn(nix::libc::BPF_RET | nix::libc::BPF_K, 0, 0, 0),
|
||||||
|
insn(nix::libc::BPF_RET | nix::libc::BPF_K, 0, 0, u32::MAX),
|
||||||
|
];
|
||||||
|
let fprog = nix::libc::sock_fprog {
|
||||||
|
len: program.len() as u16,
|
||||||
|
filter: program.as_mut_ptr(),
|
||||||
|
};
|
||||||
|
// SAFETY: `fprog` and the program it points to are valid for the duration of the call, and the kernel copies
|
||||||
|
// the program during it.
|
||||||
|
let res = unsafe {
|
||||||
|
nix::libc::setsockopt(
|
||||||
|
sock.as_raw_fd(),
|
||||||
|
nix::libc::SOL_SOCKET,
|
||||||
|
nix::libc::SO_ATTACH_FILTER,
|
||||||
|
std::ptr::from_ref(&fprog).cast(),
|
||||||
|
std::mem::size_of::<nix::libc::sock_fprog>() as nix::libc::socklen_t,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if res == 0 {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(io::Error::last_os_error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std::io::Error> {
|
pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std::io::Error> {
|
||||||
let addr = sock.local_addr()?;
|
let addr = sock.local_addr()?;
|
||||||
if addr.is_ipv4() {
|
if addr.is_ipv4() {
|
||||||
@@ -276,35 +387,33 @@ pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std::
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use rstest::rstest;
|
||||||
|
|
||||||
#[test]
|
fn record_offsets_ms(offsets_ms: &[u64]) -> AtomicIntervalStats {
|
||||||
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() {
|
|
||||||
let stats = AtomicIntervalStats::new();
|
let stats = AtomicIntervalStats::new();
|
||||||
let t0 = Instant::now();
|
let t0 = Instant::now();
|
||||||
for ms in [0, 100, 400, 500] {
|
for &ms in offsets_ms {
|
||||||
stats.record(t0 + Duration::from_millis(ms));
|
stats.record(t0 + Duration::from_millis(ms));
|
||||||
}
|
}
|
||||||
let s = stats.snapshot();
|
stats
|
||||||
assert_eq!(s.count(), 4);
|
}
|
||||||
assert_eq!(s.min(), Some(Duration::from_millis(100)));
|
|
||||||
assert_eq!(s.max(), Some(Duration::from_millis(300)));
|
#[rstest]
|
||||||
assert_eq!(s.mean().unwrap().as_millis(), 166);
|
#[case::empty(&[], 0, None, None, None)]
|
||||||
|
#[case::single_packet_has_no_intervals(&[0], 1, None, None, None)]
|
||||||
|
#[case::min_max_mean(&[0, 100, 400, 500], 4, Some(100), Some(300), Some(166))]
|
||||||
|
fn interval_stats_summary(
|
||||||
|
#[case] offsets_ms: &[u64],
|
||||||
|
#[case] count: u64,
|
||||||
|
#[case] min_ms: Option<u64>,
|
||||||
|
#[case] max_ms: Option<u64>,
|
||||||
|
#[case] mean_ms: Option<u128>,
|
||||||
|
) {
|
||||||
|
let s = record_offsets_ms(offsets_ms).snapshot();
|
||||||
|
assert_eq!(s.count(), count);
|
||||||
|
assert_eq!(s.min(), min_ms.map(Duration::from_millis));
|
||||||
|
assert_eq!(s.max(), max_ms.map(Duration::from_millis));
|
||||||
|
assert_eq!(s.mean().map(|m| m.as_millis()), mean_ms);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -354,21 +463,14 @@ mod tests {
|
|||||||
assert!(loaded <= Instant::now());
|
assert!(loaded <= Instant::now());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn interval_stats_display() {
|
#[case::empty(IntervalStats::default(), "0 pkts, interval min/avg/max -/-/- ms")]
|
||||||
assert_eq!(
|
#[case::four_packets(
|
||||||
IntervalStats::default().to_string(),
|
record_offsets_ms(&[0, 100, 400, 500]).snapshot(),
|
||||||
"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"
|
"4 pkts, interval min/avg/max 100/167/300 ms"
|
||||||
);
|
)]
|
||||||
|
fn interval_stats_display(#[case] stats: IntervalStats, #[case] expected: &str) {
|
||||||
|
assert_eq!(stats.to_string(), expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn session_stats(last_up: Option<Instant>, last_down: Option<Instant>) -> BfdSessionStats {
|
fn session_stats(last_up: Option<Instant>, last_down: Option<Instant>) -> BfdSessionStats {
|
||||||
@@ -386,6 +488,7 @@ mod tests {
|
|||||||
state: BfdState::Up,
|
state: BfdState::Up,
|
||||||
last_diag: BfdDiagnostic::TimeExpired,
|
last_diag: BfdDiagnostic::TimeExpired,
|
||||||
rx: rx.snapshot(),
|
rx: rx.snapshot(),
|
||||||
|
rx_received: 2,
|
||||||
tx: tx.snapshot(),
|
tx: tx.snapshot(),
|
||||||
last_up,
|
last_up,
|
||||||
last_down,
|
last_down,
|
||||||
@@ -418,41 +521,41 @@ mod tests {
|
|||||||
assert_eq!(lines[5], " Last Up: never Last Down: never");
|
assert_eq!(lines[5], " Last Up: never Last Down: never");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn session_stats_display_auth() {
|
#[case::meticulous_sha1(
|
||||||
let out = session_stats(None, None)
|
AuthStats {
|
||||||
.with_auth(Some(AuthStats {
|
|
||||||
auth_type: BfdAuthType::MetKeyedSHA1,
|
auth_type: BfdAuthType::MetKeyedSHA1,
|
||||||
key_id: 3,
|
key_id: 3,
|
||||||
rcv_seq: Some(100),
|
rcv_seq: Some(100),
|
||||||
xmit_seq: Some(7),
|
xmit_seq: Some(7),
|
||||||
}))
|
},
|
||||||
.to_string();
|
"\n Auth: meticulous-sha1 KeyId:3 RcvSeq:100 XmitSeq:7\n"
|
||||||
assert!(
|
)]
|
||||||
out.contains("\n Auth: meticulous-sha1 KeyId:3 RcvSeq:100 XmitSeq:7\n"),
|
#[case::md5_without_rcv_seq(
|
||||||
"{out}"
|
AuthStats {
|
||||||
);
|
|
||||||
let out = session_stats(None, None)
|
|
||||||
.with_auth(Some(AuthStats {
|
|
||||||
auth_type: BfdAuthType::KeyedMD5,
|
auth_type: BfdAuthType::KeyedMD5,
|
||||||
key_id: 1,
|
key_id: 1,
|
||||||
rcv_seq: None,
|
rcv_seq: None,
|
||||||
xmit_seq: Some(7),
|
xmit_seq: Some(7),
|
||||||
}))
|
},
|
||||||
.to_string();
|
"\n Auth: md5 KeyId:1 RcvSeq:- XmitSeq:7\n"
|
||||||
assert!(
|
)]
|
||||||
out.contains("\n Auth: md5 KeyId:1 RcvSeq:- XmitSeq:7\n"),
|
fn session_stats_display_auth(#[case] auth: AuthStats, #[case] expected: &str) {
|
||||||
"{out}"
|
let out = session_stats(None, None).with_auth(Some(auth)).to_string();
|
||||||
);
|
assert!(out.contains(expected), "{out}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[rstest]
|
||||||
fn session_stats_display_last_up_down() {
|
#[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 now = Instant::now();
|
||||||
let out = session_stats(Some(now), None).to_string();
|
let out = session_stats(up.then_some(now), down.then_some(now)).to_string();
|
||||||
assert!(out.ends_with("Last Up: 0s ago Last Down: never"), "{out}");
|
assert!(out.ends_with(expected_suffix), "{out}");
|
||||||
let out = session_stats(None, Some(now)).to_string();
|
|
||||||
assert!(out.ends_with("Last Up: never Last Down: 0s ago"), "{out}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -461,13 +564,12 @@ mod tests {
|
|||||||
assert_eq!(s.base_interval, BfdInterval::from_millis(300));
|
assert_eq!(s.base_interval, BfdInterval::from_millis(300));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
#[tokio::test]
|
#[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();
|
let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||||
set_ttl_or_hop_limit(&sock, 255).unwrap();
|
set_ttl_or_hop_limit(&sock, ttl).unwrap();
|
||||||
assert_eq!(sock.ttl().unwrap(), 255);
|
assert_eq!(sock.ttl().unwrap(), u32::from(ttl));
|
||||||
set_ttl_or_hop_limit(&sock, 64).unwrap();
|
|
||||||
assert_eq!(sock.ttl().unwrap(), 64);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -478,4 +580,89 @@ mod tests {
|
|||||||
set_ttl_or_hop_limit(&sock, 255).unwrap();
|
set_ttl_or_hop_limit(&sock, 255).unwrap();
|
||||||
assert_eq!(getsockopt(&sock, sockopt::Ipv6Ttl).unwrap(), 255);
|
assert_eq!(getsockopt(&sock, sockopt::Ipv6Ttl).unwrap(), 255);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[case::v4("127.0.0.1:0")]
|
||||||
|
#[case::v6("[::1]:0")]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn require_hop_limit_accepts_only_255(#[case] bind: &str) {
|
||||||
|
let Ok(rx) = UdpSocket::bind(bind).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
require_hop_limit(&rx, 255).unwrap();
|
||||||
|
let tx = UdpSocket::bind(bind).await.unwrap();
|
||||||
|
for hop_limit in [1u8, 64, 254, 255] {
|
||||||
|
set_ttl_or_hop_limit(&tx, hop_limit).unwrap();
|
||||||
|
tx.send_to(&[hop_limit], rx.local_addr().unwrap())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let mut buf = [0u8; 8];
|
||||||
|
let n = rx.recv(&mut buf).await.unwrap();
|
||||||
|
assert_eq!(&buf[..n], [255]);
|
||||||
|
let more = tokio::time::timeout(Duration::from_millis(100), rx.recv(&mut buf)).await;
|
||||||
|
assert!(more.is_err(), "received a datagram with hop limit != 255");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bind_udp_without_interface() {
|
||||||
|
let sock = bind_udp("127.0.0.1:0".parse().unwrap(), None).unwrap();
|
||||||
|
assert!(sock.local_addr().unwrap().port() != 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bind_udp_to_loopback_interface() {
|
||||||
|
let sock = bind_udp("127.0.0.1:0".parse().unwrap(), Some("lo")).unwrap();
|
||||||
|
let addr = sock.local_addr().unwrap();
|
||||||
|
let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
peer.send_to(b"x", addr).await.unwrap();
|
||||||
|
let mut buf = [0u8; 1];
|
||||||
|
let (n, _) = sock.recv_from(&mut buf).await.unwrap();
|
||||||
|
assert_eq!(n, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bind_udp_rejects_unknown_interface() {
|
||||||
|
assert!(bind_udp("127.0.0.1:0".parse().unwrap(), Some("nosuchif0")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[case::link_local_is_scoped("fe80::1", Some("lo"), "[fe80::1%{lo}]:3784")]
|
||||||
|
#[case::global_v6_is_unscoped("2001:db8::1", Some("lo"), "[2001:db8::1]:3784")]
|
||||||
|
#[case::v4_is_unscoped("192.0.2.1", None, "192.0.2.1:3784")]
|
||||||
|
fn scoped_socket_addr_formats(
|
||||||
|
#[case] addr: &str,
|
||||||
|
#[case] interface: Option<&str>,
|
||||||
|
#[case] expected: &str,
|
||||||
|
) {
|
||||||
|
let lo = if_nametoindex("lo").unwrap();
|
||||||
|
let scoped = scoped_socket_addr(addr.parse().unwrap(), 3784, interface).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
scoped.to_string(),
|
||||||
|
expected.replace("{lo}", &lo.to_string())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[case::link_local_without_interface(None, Some(io::ErrorKind::InvalidInput))]
|
||||||
|
#[case::link_local_unknown_interface(Some("nosuchif0"), None)]
|
||||||
|
fn scoped_socket_addr_rejects(
|
||||||
|
#[case] interface: Option<&str>,
|
||||||
|
#[case] kind: Option<io::ErrorKind>,
|
||||||
|
) {
|
||||||
|
let err = scoped_socket_addr("fe80::1".parse().unwrap(), 3784, interface).unwrap_err();
|
||||||
|
if let Some(kind) = kind {
|
||||||
|
assert_eq!(err.kind(), kind);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest]
|
||||||
|
#[case::fe80("fe80::1", true)]
|
||||||
|
#[case::febf("febf::1", true)]
|
||||||
|
#[case::fec0("fec0::1", false)]
|
||||||
|
#[case::global_v6("2001:db8::1", false)]
|
||||||
|
#[case::v4_link_local("169.254.0.1", false)]
|
||||||
|
fn link_local_detection(#[case] addr: &str, #[case] expected: bool) {
|
||||||
|
assert_eq!(is_ipv6_link_local(&addr.parse().unwrap()), expected);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user