Compare commits
5
Commits
ac154066e1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
525a22d100 | ||
|
|
2b2fe66785 | ||
|
|
8962406c57 | ||
|
|
bdf5455a3f | ||
|
|
8fbafa455a |
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
+214
-2
@@ -88,6 +88,15 @@ version = "2.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
@@ -184,6 +193,21 @@ version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.7.2"
|
||||
@@ -195,6 +219,15 @@ dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "defmt"
|
||||
version = "1.2.0"
|
||||
@@ -226,6 +259,17 @@ dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.19.0"
|
||||
@@ -348,6 +392,12 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
||||
|
||||
[[package]]
|
||||
name = "futures-timer"
|
||||
version = "3.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
|
||||
|
||||
[[package]]
|
||||
name = "futures-util"
|
||||
version = "0.3.34"
|
||||
@@ -376,6 +426,12 @@ dependencies = [
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
@@ -404,6 +460,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.14.2"
|
||||
@@ -499,6 +564,16 @@ version = "0.4.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
|
||||
dependencies = [
|
||||
"cfg-if 1.0.5",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
@@ -656,6 +731,15 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro-crate"
|
||||
version = "3.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
|
||||
dependencies = [
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
@@ -742,6 +826,41 @@ version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "relative-path"
|
||||
version = "1.9.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"
|
||||
|
||||
[[package]]
|
||||
name = "rstest"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b376e512f30a7686a8dbc6aeaace99b3ade1c26c1c63473473a817ade226dafc"
|
||||
dependencies = [
|
||||
"futures-timer",
|
||||
"futures-util",
|
||||
"rstest_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rstest_macros"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88512dbfb5b73a0dfa38aef7bc73b5657035fce477b923faf12d332dd83051ea"
|
||||
dependencies = [
|
||||
"cfg-if 1.0.5",
|
||||
"glob",
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"relative-path",
|
||||
"rustc_version",
|
||||
"syn 2.0.119",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rust-bfd"
|
||||
version = "0.1.0"
|
||||
@@ -750,23 +869,38 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"byteorder",
|
||||
"clap",
|
||||
"digest",
|
||||
"env_logger",
|
||||
"futures 0.3.34",
|
||||
"humantime",
|
||||
"humantime-serde",
|
||||
"itertools",
|
||||
"log",
|
||||
"md-5",
|
||||
"nix",
|
||||
"nom",
|
||||
"nom-derive",
|
||||
"proc-bitfield",
|
||||
"rand",
|
||||
"rstest",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_yaml_ng",
|
||||
"sha1",
|
||||
"subtle",
|
||||
"tokio",
|
||||
"tokio-timer",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.23"
|
||||
@@ -785,6 +919,12 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
@@ -795,6 +935,16 @@ dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_bytes"
|
||||
version = "0.11.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.229"
|
||||
@@ -828,6 +978,17 @@ dependencies = [
|
||||
"unsafe-libyaml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
||||
dependencies = [
|
||||
"cfg-if 1.0.5",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
@@ -846,9 +1007,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.3"
|
||||
version = "1.16.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"
|
||||
checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
@@ -872,6 +1033,12 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.109"
|
||||
@@ -975,6 +1142,42 @@ dependencies = [
|
||||
"tokio-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.1.2+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.25.17+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"toml_datetime",
|
||||
"toml_parser",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.1.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.27"
|
||||
@@ -1014,6 +1217,15 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.63"
|
||||
|
||||
+10
-1
@@ -8,18 +8,27 @@ atomic = "0.6.0"
|
||||
bytemuck = { version = "1.14.1", features = ["derive"] }
|
||||
byteorder = "1.5.0"
|
||||
clap = { version = "4", features = ["derive", "env"] }
|
||||
digest = "0.11.3"
|
||||
env_logger = "0.11.1"
|
||||
futures = "0.3.30"
|
||||
humantime = "2.4.0"
|
||||
humantime-serde = "1.1.1"
|
||||
itertools = "0.12.1"
|
||||
log = "0.4.20"
|
||||
nix = { version = "0.31.3", features = ["fs", "socket"] }
|
||||
md-5 = "0.11.0"
|
||||
nix = { version = "0.31.3", features = ["fs", "net", "socket"] }
|
||||
nom = "7.1.3"
|
||||
nom-derive = "0.10.1"
|
||||
proc-bitfield = "0.3.1"
|
||||
rand = "0.8.5"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_bytes = "0.11.19"
|
||||
|
||||
serde_yaml_ng = "0.10.0"
|
||||
sha1 = "0.11.0"
|
||||
subtle = "2.6"
|
||||
tokio = { version = "1.35.1", features = ["net", "full"] }
|
||||
tokio-timer = "0.2.13"
|
||||
|
||||
[dev-dependencies]
|
||||
rstest = "0.28.0"
|
||||
+56
-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.
|
||||
|
||||
# Local address(es) to bind and use as the source of BFD control packets. Required (here, in BFD_BIND, or via --bind).
|
||||
# Accepts a single address, a list, or a comma-separated string. The daemon currently supports exactly one address;
|
||||
# the list form is accepted so configs do not need to change once multiple binds are implemented.
|
||||
# Env: BFD_BIND="192.0.2.1" (or "192.0.2.1,2001:db8::1")
|
||||
# CLI: --bind 192.0.2.1 [--bind ...] (replaces the addresses configured here)
|
||||
bind: 192.0.2.1
|
||||
# bind: [192.0.2.1, "2001:db8::1"]
|
||||
|
||||
# Directory of executable scripts run, in lexical order, on every session state change.
|
||||
# Env: BFD_HOOKS_DIR
|
||||
hooks_dir: /etc/rust-bfd/hooks.d
|
||||
|
||||
# Settings inherited by every peer that does not override them. Durations are humantime strings (300ms, 1s, 2m).
|
||||
@@ -20,22 +11,70 @@ hooks_dir: /etc/rust-bfd/hooks.d
|
||||
defaults:
|
||||
# Minimum interval between transmitted control packets that we would like to use once the session is Up. Sessions
|
||||
# that are not Up transmit no faster than once per second regardless (RFC 5880 section 6.8.3).
|
||||
# Env: BFD_DEFAULTS_DESIRED_MIN_TX
|
||||
desired_min_tx: 300ms
|
||||
# Minimum interval between received control packets we can support.
|
||||
# Env: BFD_DEFAULTS_REQUIRED_MIN_RX
|
||||
required_min_rx: 300ms
|
||||
# Detection time multiplier: we declare the session down after this many missed packets.
|
||||
# Env: BFD_DEFAULTS_DETECT_MULT
|
||||
detect_mult: 3
|
||||
|
||||
# Peers to establish sessions with. Peers can only be configured here and with --peer (repeatable, addresses only,
|
||||
# default settings); they cannot be set from the environment. Each peer's address must match the family of at least
|
||||
# one bind address.
|
||||
# Peers to establish sessions with.
|
||||
#
|
||||
# `local` is required: the local address the session runs from, which is the source of its control packets and the
|
||||
# address the daemon listens on for the peer's. It must be of the same address family as `address`. The daemon listens
|
||||
# on each distinct `local` address (and `interface`, below) once, however many peers use it; peers may use different
|
||||
# local addresses.
|
||||
#
|
||||
# `interface` optionally binds the session's sockets to one interface (SO_BINDTODEVICE). It is required when `local` or
|
||||
# `address` is an IPv6 link-local address (fe80::/10), which is only meaningful on a given link. The same peer address
|
||||
# may be configured on several interfaces. The binding is to the interface as it exists at startup: if it is
|
||||
# recreated, the daemon must be restarted.
|
||||
peers:
|
||||
- address: 192.0.2.2
|
||||
local: 192.0.2.1
|
||||
# - address: 2001:db8::2
|
||||
# local: "2001:db8::1"
|
||||
#
|
||||
# - address: "fe80::2"
|
||||
# local: "fe80::1"
|
||||
# interface: eth1
|
||||
#
|
||||
# Per-peer overrides of any `defaults` key:
|
||||
# - address: 192.0.2.3
|
||||
# local: 192.0.2.1
|
||||
# desired_min_tx: 1s
|
||||
# required_min_rx: 1s
|
||||
# detect_mult: 5
|
||||
#
|
||||
# Authentication (RFC 5880 section 6.7), per peer and off by default. Both ends must be configured identically; a
|
||||
# peer that does not authenticate as configured is discarded. `key_id` is a number (0-255) that must match the remote's.
|
||||
# Keys are used verbatim (not hashed or derived), so they must be exactly the length shown. Give them as a string;
|
||||
# use YAML double-quoted escapes (\x00, \x1b, ...) for bytes that are not printable. Strings are UTF-8, so only bytes
|
||||
# 0x00-0x7f can be written this way. To use bytes 0x80-0xff, give the key as a list of integers instead, one per
|
||||
# byte (hex is fine), with the same length requirement:
|
||||
# key: [0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x80, 0xff]
|
||||
#
|
||||
# Keyed MD5: `key` is exactly 16 bytes. `meticulous` (default true) selects Meticulous Keyed MD5, in which every
|
||||
# packet must carry a newer sequence number; the remote must be set to the same mode.
|
||||
# - address: 192.0.2.4
|
||||
# local: 192.0.2.1
|
||||
# auth:
|
||||
# type: md5
|
||||
# key_id: 1
|
||||
# key: "0123456789abcdef"
|
||||
# meticulous: true
|
||||
#
|
||||
# Keyed SHA1: `key` is exactly 20 bytes. `meticulous` as above.
|
||||
# - address: 192.0.2.5
|
||||
# local: 192.0.2.1
|
||||
# auth:
|
||||
# type: sha1
|
||||
# key_id: 1
|
||||
# key: "0123456789abcdef\x00\x01\x7f\x1b"
|
||||
#
|
||||
# Simple password: 1 to 16 bytes, sent in the clear. Provides no protection against an attacker on the path.
|
||||
# - address: 192.0.2.6
|
||||
# local: 192.0.2.1
|
||||
# auth:
|
||||
# type: password
|
||||
# key_id: 1
|
||||
# password: "secret"
|
||||
+943
-64
File diff suppressed because it is too large.
Load diff
+1462
-316
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);
|
||||
}
|
||||
+314
-346
@@ -1,11 +1,7 @@
|
||||
//! Daemon configuration: YAML model, layered loading and validation.
|
||||
//! Daemon configuration: a single YAML file, loaded and validated.
|
||||
//!
|
||||
//! Layers, lowest to highest precedence: built-in defaults, the YAML file, `BFD_*` environment variables (global
|
||||
//! settings only), command line (`--bind` replaces, `--peer` adds). Per-peer settings can only come from the file; peers
|
||||
//! given on the command line use the global defaults.
|
||||
//!
|
||||
//! [`Config`] is the editable, serialisable model. [`Config::resolve`] validates it and produces a [`ResolvedConfig`]
|
||||
//! with all per-peer inheritance applied, which is what the daemon runs from.
|
||||
//! [`Config`] is the file's model. [`Config::resolve`] validates it and produces a [`ResolvedConfig`] with all per-peer
|
||||
//! inheritance applied, which is what the daemon runs from.
|
||||
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
@@ -16,18 +12,16 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use serde::{de, Deserialize, Deserializer, Serialize};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::bfd::BfdInterval;
|
||||
use crate::bfd::{BfdAuth, BfdAuthKeyedMD5, BfdAuthKeyedSHA1, BfdAuthSimplePassword, BfdInterval};
|
||||
|
||||
pub const DEFAULT_CONFIG_PATH: &str = "/etc/rust-bfd/config.yaml";
|
||||
pub const DEFAULT_HOOKS_DIR: &str = "/etc/rust-bfd/hooks.d";
|
||||
|
||||
pub const ENV_BIND: &str = "BFD_BIND";
|
||||
pub const ENV_HOOKS_DIR: &str = "BFD_HOOKS_DIR";
|
||||
pub const ENV_DEFAULTS_DESIRED_MIN_TX: &str = "BFD_DEFAULTS_DESIRED_MIN_TX";
|
||||
pub const ENV_DEFAULTS_REQUIRED_MIN_RX: &str = "BFD_DEFAULTS_REQUIRED_MIN_RX";
|
||||
pub const ENV_DEFAULTS_DETECT_MULT: &str = "BFD_DEFAULTS_DETECT_MULT";
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigError {
|
||||
@@ -39,10 +33,6 @@ pub enum ConfigError {
|
||||
path: PathBuf,
|
||||
source: serde_yaml_ng::Error,
|
||||
},
|
||||
Env {
|
||||
var: &'static str,
|
||||
message: String,
|
||||
},
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
@@ -55,9 +45,6 @@ impl fmt::Display for ConfigError {
|
||||
Self::Parse { path, source } => {
|
||||
write!(f, "invalid config file `{}`: {source}", path.display())
|
||||
}
|
||||
Self::Env { var, message } => {
|
||||
write!(f, "invalid environment variable {var}: {message}")
|
||||
}
|
||||
Self::Invalid(message) => write!(f, "invalid configuration: {message}"),
|
||||
}
|
||||
}
|
||||
@@ -68,13 +55,13 @@ impl Error for ConfigError {
|
||||
match self {
|
||||
Self::Io { source, .. } => Some(source),
|
||||
Self::Parse { source, .. } => Some(source),
|
||||
Self::Env { .. } | Self::Invalid(_) => None,
|
||||
Self::Invalid(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timer and multiplier settings inherited by every peer that does not override them.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Defaults {
|
||||
#[serde(with = "humantime_serde")]
|
||||
@@ -94,44 +81,94 @@ impl Default for Defaults {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PeerConfig {
|
||||
pub address: IpAddr,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "humantime_serde"
|
||||
)]
|
||||
pub desired_min_tx: Option<Duration>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "humantime_serde"
|
||||
)]
|
||||
pub required_min_rx: Option<Duration>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub detect_mult: Option<u8>,
|
||||
pub struct PasswordAuthConfig {
|
||||
pub key_id: u8,
|
||||
#[serde(with = "serde_bytes")]
|
||||
// The password is a binary string, and MUST be 1 to 16 bytes in length (checked in `Config::resolve`).
|
||||
pub password: Vec<u8>,
|
||||
}
|
||||
|
||||
impl PeerConfig {
|
||||
pub fn new(address: IpAddr) -> Self {
|
||||
Self {
|
||||
address,
|
||||
desired_min_tx: None,
|
||||
required_min_rx: None,
|
||||
detect_mult: None,
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Md5AuthConfig {
|
||||
pub key_id: u8,
|
||||
#[serde(with = "serde_bytes")]
|
||||
// The key is given verbatim (not derived) and must be exactly 16 bytes
|
||||
pub key: [u8; 16],
|
||||
#[serde(default = "default_true")]
|
||||
pub meticulous: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Sha1AuthConfig {
|
||||
pub key_id: u8,
|
||||
#[serde(with = "serde_bytes")]
|
||||
// The key is given verbatim (not derived) and must be exactly 20 bytes
|
||||
pub key: [u8; 20],
|
||||
#[serde(default = "default_true")]
|
||||
pub meticulous: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields, tag = "type", rename_all = "lowercase")]
|
||||
pub enum AuthConfig {
|
||||
Password(PasswordAuthConfig),
|
||||
Md5(Md5AuthConfig),
|
||||
Sha1(Sha1AuthConfig),
|
||||
}
|
||||
|
||||
impl From<AuthConfig> for BfdAuth {
|
||||
fn from(value: AuthConfig) -> Self {
|
||||
match value {
|
||||
AuthConfig::Password(ac) => BfdAuth::SimplePassword(BfdAuthSimplePassword {
|
||||
key_id: ac.key_id,
|
||||
password: ac.password,
|
||||
}),
|
||||
AuthConfig::Md5(ac) => BfdAuth::KeyedMD5(BfdAuthKeyedMD5 {
|
||||
key_id: ac.key_id,
|
||||
reserved: 0,
|
||||
meticulous: ac.meticulous,
|
||||
digest: ac.key,
|
||||
seq: 0, // set during signing
|
||||
}),
|
||||
AuthConfig::Sha1(ac) => BfdAuth::KeyedSHA1(BfdAuthKeyedSHA1 {
|
||||
key_id: ac.key_id,
|
||||
reserved: 0,
|
||||
meticulous: ac.meticulous,
|
||||
digest: ac.key,
|
||||
seq: 0, // set during signing
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PeerConfig {
|
||||
pub address: IpAddr,
|
||||
/// Local address the session runs from: the source of its control packets, and the address the daemon listens
|
||||
/// on for the peer's. Must be of the same address family as `address`.
|
||||
pub local: IpAddr,
|
||||
/// Bind the session's sockets to this interface (`SO_BINDTODEVICE`). Required when `local` or `address` is an
|
||||
/// IPv6 link-local address.
|
||||
#[serde(default)]
|
||||
pub interface: Option<String>,
|
||||
#[serde(default, with = "humantime_serde")]
|
||||
pub desired_min_tx: Option<Duration>,
|
||||
#[serde(default, with = "humantime_serde")]
|
||||
pub required_min_rx: Option<Duration>,
|
||||
#[serde(default)]
|
||||
pub detect_mult: Option<u8>,
|
||||
#[serde(default)]
|
||||
pub auth: Option<AuthConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// 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.
|
||||
pub hooks_dir: PathBuf,
|
||||
pub defaults: Defaults,
|
||||
@@ -141,7 +178,6 @@ pub struct Config {
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bind: Vec::new(),
|
||||
hooks_dir: PathBuf::from(DEFAULT_HOOKS_DIR),
|
||||
defaults: Defaults::default(),
|
||||
peers: Vec::new(),
|
||||
@@ -149,142 +185,71 @@ 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 {
|
||||
pub fn from_yaml(yaml: &str) -> Result<Self, serde_yaml_ng::Error> {
|
||||
// An empty (or comment-only) document is a null value, which means "all defaults".
|
||||
Ok(serde_yaml_ng::from_str::<Option<Self>>(yaml)?.unwrap_or_default())
|
||||
}
|
||||
|
||||
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
|
||||
/// built-in defaults otherwise.
|
||||
pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
|
||||
match path {
|
||||
Some(path) => Self::from_file(path),
|
||||
None => match Self::from_file(Path::new(DEFAULT_CONFIG_PATH)) {
|
||||
Err(ConfigError::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
|
||||
Ok(Self::default())
|
||||
}
|
||||
other => other,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Override global settings from `BFD_*` variables supplied by `var`. Unset and empty variables are ignored.
|
||||
pub fn apply_env(&mut self, var: impl Fn(&str) -> Option<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));
|
||||
}
|
||||
let optional = path.is_none();
|
||||
let path = path.unwrap_or(Path::new(DEFAULT_CONFIG_PATH));
|
||||
let to_owned = || path.to_owned();
|
||||
match fs::read_to_string(path) {
|
||||
Ok(yaml) => Self::from_yaml(&yaml).map_err(|source| ConfigError::Parse {
|
||||
path: to_owned(),
|
||||
source,
|
||||
}),
|
||||
Err(e) if optional && e.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
|
||||
Err(source) => Err(ConfigError::Io {
|
||||
path: to_owned(),
|
||||
source,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate and apply defaults to each peer.
|
||||
pub fn resolve(&self) -> Result<ResolvedConfig, ConfigError> {
|
||||
pub fn resolve(self) -> Result<ResolvedConfig, ConfigError> {
|
||||
let invalid = |message: String| ConfigError::Invalid(message);
|
||||
|
||||
if self.bind.is_empty() {
|
||||
return Err(invalid(
|
||||
"no bind address configured (`bind`, BFD_BIND or --bind)".into(),
|
||||
));
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
if let Some(dup) = self.bind.iter().find(|addr| !seen.insert(**addr)) {
|
||||
return Err(invalid(format!("duplicate bind address {dup}")));
|
||||
}
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
let peers = self
|
||||
.peers
|
||||
.iter()
|
||||
.into_iter()
|
||||
.map(|peer| {
|
||||
if !seen.insert(peer.address) {
|
||||
return Err(invalid(format!("duplicate peer {}", peer.address)));
|
||||
}
|
||||
if !self
|
||||
.bind
|
||||
.iter()
|
||||
.any(|b| b.is_ipv4() == peer.address.is_ipv4())
|
||||
{
|
||||
if !seen.insert((peer.local, peer.interface.clone(), peer.address)) {
|
||||
return Err(invalid(format!(
|
||||
"peer {} has no bind address of the same address family",
|
||||
"duplicate peer {} with local address {}",
|
||||
peer.address, peer.local
|
||||
)));
|
||||
}
|
||||
if let Some(name) = &peer.interface {
|
||||
validate_interface_name(name).map_err(|why| {
|
||||
invalid(format!("peer {} interface {name:?} {why}", peer.address))
|
||||
})?;
|
||||
} else if is_link_local_v6(peer.local) || is_link_local_v6(peer.address) {
|
||||
return Err(invalid(format!(
|
||||
"peer {} uses an IPv6 link-local address and requires an interface",
|
||||
peer.address
|
||||
)));
|
||||
}
|
||||
if peer.local.is_ipv4() != peer.address.is_ipv4() {
|
||||
return Err(invalid(format!(
|
||||
"peer {} has local address {} of a different address family",
|
||||
peer.address, peer.local
|
||||
)));
|
||||
}
|
||||
let what = |field: &str| format!("peer {} {field}", peer.address);
|
||||
if let Some(AuthConfig::Password(p)) = &peer.auth {
|
||||
if !(1..=16).contains(&p.password.len()) {
|
||||
return Err(invalid(format!(
|
||||
"{} must be 1 to 16 bytes",
|
||||
what("auth password")
|
||||
)));
|
||||
}
|
||||
}
|
||||
let detect_mult = peer.detect_mult.unwrap_or(self.defaults.detect_mult);
|
||||
if detect_mult == 0 {
|
||||
return Err(invalid(format!(
|
||||
@@ -294,6 +259,8 @@ impl Config {
|
||||
}
|
||||
Ok(ResolvedPeer {
|
||||
address: peer.address,
|
||||
local: peer.local,
|
||||
interface: peer.interface,
|
||||
desired_min_tx: to_interval(
|
||||
peer.desired_min_tx.unwrap_or(self.defaults.desired_min_tx),
|
||||
&what("desired_min_tx"),
|
||||
@@ -304,6 +271,7 @@ impl Config {
|
||||
&what("required_min_rx"),
|
||||
)?,
|
||||
detect_mult,
|
||||
auth: peer.auth,
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
@@ -317,13 +285,29 @@ impl Config {
|
||||
}
|
||||
|
||||
Ok(ResolvedConfig {
|
||||
bind: self.bind.clone(),
|
||||
hooks_dir: self.hooks_dir.clone(),
|
||||
hooks_dir: self.hooks_dir,
|
||||
peers,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn is_link_local_v6(addr: IpAddr) -> bool {
|
||||
crate::is_ipv6_link_local(&addr)
|
||||
}
|
||||
|
||||
/// Linux limits interface names to IFNAMSIZ - 1 = 15 bytes, and `/` and NUL cannot appear in them.
|
||||
fn validate_interface_name(name: &str) -> Result<(), &'static str> {
|
||||
if name.is_empty() {
|
||||
Err("must not be empty")
|
||||
} else if name.len() > 15 {
|
||||
Err("must be at most 15 bytes")
|
||||
} else if name.contains(['/', '\0']) {
|
||||
Err("must not contain '/' or NUL")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero is rejected for both intervals: a zero Required Min RX Interval is legal in RFC 5880 (it asks the peer to
|
||||
/// stop sending periodic packets) but is not supported here.
|
||||
fn to_interval(value: Duration, what: &str) -> Result<BfdInterval, ConfigError> {
|
||||
@@ -346,39 +330,57 @@ fn to_interval(value: Duration, what: &str) -> Result<BfdInterval, ConfigError>
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedConfig {
|
||||
pub bind: Vec<IpAddr>,
|
||||
pub hooks_dir: PathBuf,
|
||||
pub peers: Vec<ResolvedPeer>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedPeer {
|
||||
pub address: IpAddr,
|
||||
pub local: IpAddr,
|
||||
pub interface: Option<String>,
|
||||
pub desired_min_tx: BfdInterval,
|
||||
pub required_min_rx: BfdInterval,
|
||||
pub detect_mult: u8,
|
||||
pub auth: Option<AuthConfig>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use rstest::rstest;
|
||||
|
||||
enum Expect {
|
||||
Ok,
|
||||
Err,
|
||||
ErrContaining(&'static str),
|
||||
}
|
||||
|
||||
fn check(result: Result<ResolvedConfig, ConfigError>, expect: Expect) {
|
||||
match expect {
|
||||
Expect::Ok => assert!(result.is_ok()),
|
||||
Expect::Err => assert!(result.is_err()),
|
||||
Expect::ErrContaining(s) => assert!(result.unwrap_err().to_string().contains(s)),
|
||||
}
|
||||
}
|
||||
|
||||
fn ip(s: &str) -> IpAddr {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
|
||||
let map: HashMap<String, String> = pairs
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||
.collect();
|
||||
move |k| map.get(k).cloned()
|
||||
fn peer(address: &str, local: &str) -> PeerConfig {
|
||||
PeerConfig {
|
||||
address: ip(address),
|
||||
local: ip(local),
|
||||
interface: None,
|
||||
desired_min_tx: None,
|
||||
required_min_rx: None,
|
||||
detect_mult: None,
|
||||
auth: None,
|
||||
}
|
||||
}
|
||||
|
||||
const FULL: &str = "
|
||||
bind: 192.0.2.1
|
||||
hooks_dir: /tmp/hooks
|
||||
defaults:
|
||||
desired_min_tx: 500ms
|
||||
@@ -386,7 +388,9 @@ defaults:
|
||||
detect_mult: 5
|
||||
peers:
|
||||
- address: 192.0.2.2
|
||||
local: 192.0.2.1
|
||||
- address: 192.0.2.3
|
||||
local: 192.0.2.1
|
||||
desired_min_tx: 1s
|
||||
detect_mult: 4
|
||||
";
|
||||
@@ -394,7 +398,7 @@ peers:
|
||||
#[test]
|
||||
fn parses_full_config() {
|
||||
let config = Config::from_yaml(FULL).unwrap();
|
||||
assert_eq!(config.bind, vec![ip("192.0.2.1")]);
|
||||
assert_eq!(config.peers[0].local, ip("192.0.2.1"));
|
||||
assert_eq!(config.hooks_dir, PathBuf::from("/tmp/hooks"));
|
||||
assert_eq!(config.defaults.desired_min_tx, Duration::from_millis(500));
|
||||
assert_eq!(config.peers.len(), 2);
|
||||
@@ -402,10 +406,11 @@ peers:
|
||||
assert_eq!(config.peers[0].detect_mult, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_comment_only_documents_are_defaults() {
|
||||
assert_eq!(Config::from_yaml("").unwrap(), Config::default());
|
||||
assert_eq!(Config::from_yaml("# nothing\n").unwrap(), Config::default());
|
||||
#[rstest]
|
||||
#[case::empty("")]
|
||||
#[case::comment_only("# nothing\n")]
|
||||
fn empty_and_comment_only_documents_are_defaults(#[case] yaml: &str) {
|
||||
assert_eq!(Config::from_yaml(yaml).unwrap(), Config::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -418,7 +423,7 @@ peers:
|
||||
#[test]
|
||||
fn peers_inherit_defaults_and_override() {
|
||||
let resolved = Config::from_yaml(FULL).unwrap().resolve().unwrap();
|
||||
let (a, b) = (resolved.peers[0], resolved.peers[1]);
|
||||
let (a, b) = (&resolved.peers[0], &resolved.peers[1]);
|
||||
assert_eq!(a.desired_min_tx, BfdInterval::from_millis(500));
|
||||
assert_eq!(a.required_min_rx, BfdInterval::from_millis(250));
|
||||
assert_eq!(a.detect_mult, 5);
|
||||
@@ -428,187 +433,150 @@ peers:
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bind_accepts_scalar_list_and_comma_string() {
|
||||
for yaml in [
|
||||
"bind: 192.0.2.1",
|
||||
"bind: [192.0.2.1]",
|
||||
"bind: \"192.0.2.1\"",
|
||||
] {
|
||||
assert_eq!(Config::from_yaml(yaml).unwrap().bind, vec![ip("192.0.2.1")]);
|
||||
}
|
||||
let multi = Config::from_yaml("bind: \"192.0.2.1, 2001:db8::1\"").unwrap();
|
||||
assert_eq!(multi.bind, vec![ip("192.0.2.1"), ip("2001:db8::1")]);
|
||||
let list = Config::from_yaml("bind: [192.0.2.1, \"2001:db8::1\"]").unwrap();
|
||||
assert_eq!(list.bind, multi.bind);
|
||||
fn peers_may_use_different_local_addresses() {
|
||||
let config = Config::from_yaml(
|
||||
"peers:
|
||||
- {address: 192.0.2.2, local: 192.0.2.1}
|
||||
- {address: 2001:db8::2, local: '2001:db8::1'}
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(config.peers[1].local, ip("2001:db8::1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unknown_fields_and_bad_values() {
|
||||
assert!(Config::from_yaml("bnid: 192.0.2.1").is_err());
|
||||
assert!(Config::from_yaml("defaults:\n desired_min_txx: 1s").is_err());
|
||||
assert!(Config::from_yaml("peers:\n - address: 192.0.2.2\n color: red").is_err());
|
||||
assert!(Config::from_yaml("bind: not-an-ip").is_err());
|
||||
assert!(Config::from_yaml("defaults:\n desired_min_tx: soon").is_err());
|
||||
assert!(Config::from_yaml("peers:\n - detect_mult: 3").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaml_roundtrip() {
|
||||
let config = Config::from_yaml(FULL).unwrap();
|
||||
let again = Config::from_yaml(&serde_yaml_ng::to_string(&config).unwrap()).unwrap();
|
||||
assert_eq!(config, again);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_overrides_globals() {
|
||||
let mut config = Config::from_yaml(FULL).unwrap();
|
||||
config
|
||||
.apply_env(env(&[
|
||||
(ENV_BIND, "192.0.2.9"),
|
||||
(ENV_HOOKS_DIR, "/other"),
|
||||
(ENV_DEFAULTS_DESIRED_MIN_TX, "2s"),
|
||||
(ENV_DEFAULTS_REQUIRED_MIN_RX, "100ms"),
|
||||
(ENV_DEFAULTS_DETECT_MULT, "9"),
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(config.bind, vec![ip("192.0.2.9")]);
|
||||
assert_eq!(config.hooks_dir, PathBuf::from("/other"));
|
||||
assert_eq!(config.defaults.desired_min_tx, Duration::from_secs(2));
|
||||
assert_eq!(config.defaults.required_min_rx, Duration::from_millis(100));
|
||||
assert_eq!(config.defaults.detect_mult, 9);
|
||||
// Peers are untouched, and an explicit per-peer value still beats an overridden default.
|
||||
assert_eq!(config.peers, Config::from_yaml(FULL).unwrap().peers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_bind_accepts_multiple_addresses() {
|
||||
for value in [
|
||||
"192.0.2.1,2001:db8::1",
|
||||
"192.0.2.1, 2001:db8::1",
|
||||
"192.0.2.1 2001:db8::1",
|
||||
] {
|
||||
let mut config = Config::default();
|
||||
config.apply_env(env(&[(ENV_BIND, value)])).unwrap();
|
||||
assert_eq!(
|
||||
config.bind,
|
||||
vec![ip("192.0.2.1"), ip("2001:db8::1")],
|
||||
"{value}"
|
||||
);
|
||||
}
|
||||
#[rstest]
|
||||
#[case::misspelled_top_level_field("bnid: 192.0.2.1")]
|
||||
#[case::removed_top_level_field("bind: 192.0.2.1")]
|
||||
#[case::unknown_defaults_field("defaults:\n desired_min_txx: 1s")]
|
||||
#[case::unknown_peer_field(
|
||||
"peers:\n - address: 192.0.2.2\n local: 192.0.2.1\n color: red"
|
||||
)]
|
||||
#[case::invalid_local_address("peers:\n - address: 192.0.2.2\n local: not-an-ip")]
|
||||
#[case::invalid_interval("defaults:\n desired_min_tx: soon")]
|
||||
#[case::peer_without_address("peers:\n - detect_mult: 3")]
|
||||
#[case::peer_without_local("peers:\n - address: 192.0.2.2")]
|
||||
fn rejects_unknown_fields_and_bad_values(#[case] yaml: &str) {
|
||||
assert!(Config::from_yaml(yaml).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dist_config_is_valid() {
|
||||
let config = Config::from_yaml(include_str!("../config.yaml.dist")).unwrap();
|
||||
let resolved = config.resolve().unwrap();
|
||||
assert_eq!(resolved.peers.len(), 1);
|
||||
assert_eq!(config.defaults, Defaults::default());
|
||||
assert_eq!(config.hooks_dir, PathBuf::from(DEFAULT_HOOKS_DIR));
|
||||
let resolved = config.resolve().unwrap();
|
||||
assert_eq!(resolved.peers.len(), 1);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::valid_base(|_: &mut Config| {}, Expect::Ok)]
|
||||
#[case::duplicate_peer(
|
||||
|c: &mut Config| c.peers.push(peer("192.0.2.2", "192.0.2.1")),
|
||||
Expect::ErrContaining("duplicate peer")
|
||||
)]
|
||||
#[case::same_peer_from_different_local_addresses(
|
||||
|c: &mut Config| c.peers.push(peer("192.0.2.2", "192.0.2.9")),
|
||||
Expect::Ok
|
||||
)]
|
||||
#[case::address_family_mismatch(
|
||||
|c: &mut Config| c.peers[0].local = ip("2001:db8::1"),
|
||||
Expect::ErrContaining("address family")
|
||||
)]
|
||||
#[case::second_peer_in_other_family(
|
||||
|c: &mut Config| c.peers.push(peer("2001:db8::2", "2001:db8::1")),
|
||||
Expect::Ok
|
||||
)]
|
||||
#[case::zero_peer_detect_mult(|c: &mut Config| c.peers[0].detect_mult = Some(0), Expect::Err)]
|
||||
#[case::zero_peer_desired_min_tx(
|
||||
|c: &mut Config| c.peers[0].desired_min_tx = Some(Duration::ZERO),
|
||||
Expect::Err
|
||||
)]
|
||||
#[case::too_large_peer_required_min_rx(
|
||||
|c: &mut Config| c.peers[0].required_min_rx = Some(Duration::from_secs(5000)),
|
||||
Expect::ErrContaining("too large")
|
||||
)]
|
||||
#[case::zero_default_detect_mult(|c: &mut Config| c.defaults.detect_mult = 0, Expect::Err)]
|
||||
fn resolve_validation(#[case] mutate: fn(&mut Config), #[case] expect: Expect) {
|
||||
let mut c =
|
||||
Config::from_yaml("peers:\n - {address: 192.0.2.2, local: 192.0.2.1}\n").unwrap();
|
||||
mutate(&mut c);
|
||||
check(c.resolve(), expect);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::v4_with_interface("192.0.2.2", "192.0.2.1", Some("eth1"), Expect::Ok)]
|
||||
#[case::link_local_with_interface("fe80::2", "fe80::1", Some("eth1"), Expect::Ok)]
|
||||
#[case::link_local_without_interface(
|
||||
"fe80::2",
|
||||
"fe80::1",
|
||||
None,
|
||||
Expect::ErrContaining("requires an interface")
|
||||
)]
|
||||
#[case::link_local_peer_global_local("fe80::2", "2001:db8::1", None, Expect::Err)]
|
||||
#[case::global_peer_link_local_local("2001:db8::2", "fe80::1", None, Expect::Err)]
|
||||
#[case::global_v6_without_interface("2001:db8::2", "2001:db8::1", None, Expect::Ok)]
|
||||
#[case::empty_interface_name("192.0.2.2", "192.0.2.1", Some(""), Expect::Err)]
|
||||
#[case::interface_name_with_slash("192.0.2.2", "192.0.2.1", Some("a/b"), Expect::Err)]
|
||||
#[case::interface_name_too_long(
|
||||
"192.0.2.2",
|
||||
"192.0.2.1",
|
||||
Some("0123456789abcdef"),
|
||||
Expect::Err
|
||||
)]
|
||||
#[case::interface_name_max_length(
|
||||
"192.0.2.2",
|
||||
"192.0.2.1",
|
||||
Some("0123456789abcde"),
|
||||
Expect::Ok
|
||||
)]
|
||||
fn interface_validation(
|
||||
#[case] address: &str,
|
||||
#[case] local: &str,
|
||||
#[case] interface: Option<&str>,
|
||||
#[case] expect: Expect,
|
||||
) {
|
||||
let mut c = Config::from_yaml("").unwrap();
|
||||
c.peers.push(PeerConfig {
|
||||
interface: interface.map(String::from),
|
||||
..peer(address, local)
|
||||
});
|
||||
check(c.resolve(), expect);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_ignores_empty_and_unrelated_variables() {
|
||||
let mut config = Config::from_yaml(FULL).unwrap();
|
||||
config
|
||||
.apply_env(env(&[
|
||||
(ENV_BIND, ""),
|
||||
(ENV_DEFAULTS_DETECT_MULT, " "),
|
||||
("BFD_PEERS", "192.0.2.99"),
|
||||
("BFD_PEER", "192.0.2.98"),
|
||||
("BFD_ADDR", "192.0.2.97"),
|
||||
]))
|
||||
.unwrap();
|
||||
assert_eq!(config, Config::from_yaml(FULL).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_errors_name_the_variable() {
|
||||
for (var, value) in [
|
||||
(ENV_BIND, "nope"),
|
||||
(ENV_DEFAULTS_DESIRED_MIN_TX, "fast"),
|
||||
(ENV_DEFAULTS_DETECT_MULT, "-1"),
|
||||
(ENV_DEFAULTS_DETECT_MULT, "300"),
|
||||
] {
|
||||
let err = Config::default()
|
||||
.apply_env(env(&[(var, value)]))
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains(var), "{err}");
|
||||
fn same_address_on_two_interfaces_is_two_sessions() {
|
||||
let mut c = Config::from_yaml("").unwrap();
|
||||
for iface in ["eth1", "eth2"] {
|
||||
c.peers.push(PeerConfig {
|
||||
interface: Some(iface.into()),
|
||||
..peer("fe80::2", "fe80::1")
|
||||
});
|
||||
}
|
||||
assert!(c.clone().resolve().is_ok());
|
||||
c.peers[1].interface = Some("eth1".into());
|
||||
assert!(c.resolve().unwrap_err().to_string().contains("duplicate"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_bind_replaces_and_peers_merge() {
|
||||
let mut config = Config::from_yaml(FULL).unwrap();
|
||||
config.apply_cli(
|
||||
vec![ip("192.0.2.7"), ip("2001:db8::7")],
|
||||
[ip("192.0.2.3"), ip("192.0.2.4"), ip("192.0.2.4")],
|
||||
);
|
||||
assert_eq!(config.bind, vec![ip("192.0.2.7"), ip("2001:db8::7")]);
|
||||
let addrs: Vec<_> = config.peers.iter().map(|p| p.address).collect();
|
||||
assert_eq!(
|
||||
addrs,
|
||||
vec![ip("192.0.2.2"), ip("192.0.2.3"), ip("192.0.2.4")]
|
||||
);
|
||||
// The file's settings for an existing peer win over the bare CLI entry.
|
||||
assert_eq!(config.peers[1].detect_mult, Some(4));
|
||||
|
||||
let mut config = Config::from_yaml(FULL).unwrap();
|
||||
config.apply_cli(Vec::new(), []);
|
||||
assert_eq!(config.bind, vec![ip("192.0.2.1")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_validation() {
|
||||
let base =
|
||||
|| Config::from_yaml("bind: 192.0.2.1\npeers:\n - address: 192.0.2.2\n").unwrap();
|
||||
assert!(base().resolve().is_ok());
|
||||
|
||||
let mut c = base();
|
||||
c.bind.clear();
|
||||
assert!(c.resolve().is_err());
|
||||
|
||||
let mut c = base();
|
||||
c.bind.push(ip("192.0.2.1"));
|
||||
assert!(c.resolve().is_err());
|
||||
|
||||
let mut c = base();
|
||||
c.peers.push(PeerConfig::new(ip("192.0.2.2")));
|
||||
assert!(c
|
||||
.resolve()
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("duplicate peer"));
|
||||
|
||||
let mut c = base();
|
||||
c.peers.push(PeerConfig::new(ip("2001:db8::2")));
|
||||
assert!(c
|
||||
.resolve()
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("address family"));
|
||||
c.bind.push(ip("2001:db8::1"));
|
||||
assert!(c.resolve().is_ok());
|
||||
|
||||
let mut c = base();
|
||||
c.peers[0].detect_mult = Some(0);
|
||||
assert!(c.resolve().is_err());
|
||||
|
||||
let mut c = base();
|
||||
c.peers[0].desired_min_tx = Some(Duration::ZERO);
|
||||
assert!(c.resolve().is_err());
|
||||
|
||||
let mut c = base();
|
||||
c.peers[0].required_min_rx = Some(Duration::from_secs(5000));
|
||||
assert!(c.resolve().unwrap_err().to_string().contains("too large"));
|
||||
|
||||
let mut c = base();
|
||||
c.defaults.detect_mult = 0;
|
||||
assert!(c.resolve().is_err());
|
||||
#[rstest]
|
||||
#[case::empty(b"", Expect::Err)]
|
||||
#[case::one_byte(b"a", Expect::Ok)]
|
||||
#[case::sixteen_bytes(&[b'a'; 16], Expect::Ok)]
|
||||
#[case::seventeen_bytes(&[b'a'; 17], Expect::ErrContaining("1 to 16 bytes"))]
|
||||
fn password_length_is_limited_to_16_bytes(#[case] password: &[u8], #[case] expect: Expect) {
|
||||
let mut c = Config::from_yaml("").unwrap();
|
||||
c.peers.push(PeerConfig {
|
||||
auth: Some(AuthConfig::Password(PasswordAuthConfig {
|
||||
key_id: 1,
|
||||
password: password.to_vec(),
|
||||
})),
|
||||
..peer("192.0.2.2", "192.0.2.1")
|
||||
});
|
||||
check(c.resolve(), expect);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_peers_is_valid() {
|
||||
let config = Config::from_yaml("bind: 192.0.2.1").unwrap();
|
||||
let config = Config::from_yaml("").unwrap();
|
||||
assert!(config.resolve().unwrap().peers.is_empty());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
+229
-9
@@ -1,4 +1,4 @@
|
||||
use core::{fmt, str};
|
||||
use core::fmt;
|
||||
use std::{
|
||||
ffi::{OsStr, OsString},
|
||||
net::IpAddr,
|
||||
@@ -27,6 +27,7 @@ pub struct StateChangeEvent {
|
||||
pub remote_discr: BfdDiscriminator,
|
||||
pub local_ip: IpAddr,
|
||||
pub remote_ip: IpAddr,
|
||||
pub interface: Option<String>,
|
||||
pub from_state: BfdState,
|
||||
pub to_state: BfdState,
|
||||
}
|
||||
@@ -92,16 +93,10 @@ impl ScriptHookSink {
|
||||
);
|
||||
if !output.status.success() {
|
||||
if !output.stdout.is_empty() {
|
||||
warn!(
|
||||
" stdout: \n{}",
|
||||
str::from_utf8(output.stdout.as_slice()).unwrap()
|
||||
);
|
||||
warn!(" stdout: \n{}", String::from_utf8_lossy(&output.stdout));
|
||||
}
|
||||
if !output.stderr.is_empty() {
|
||||
warn!(
|
||||
" stderr: \n{}",
|
||||
str::from_utf8(output.stderr.as_slice()).unwrap()
|
||||
);
|
||||
warn!(" stderr: \n{}", String::from_utf8_lossy(&output.stderr));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -150,6 +145,7 @@ impl ScriptHookSink {
|
||||
let local_ip_str = OsString::from(event.local_ip.to_string());
|
||||
let remote_discr_str = OsString::from(event.remote_discr.to_string());
|
||||
let local_discr_str = OsString::from(event.local_discr.to_string());
|
||||
let interface_str = OsString::from(event.interface.as_deref().unwrap_or_default());
|
||||
|
||||
args.push(event.to_state.into());
|
||||
args.push(&remote_ip_str);
|
||||
@@ -157,6 +153,7 @@ impl ScriptHookSink {
|
||||
env.push((OsStr::new("BFD_STATE"), event.to_state.into()));
|
||||
env.push((OsStr::new("BFD_LOCAL_ADDR"), &local_ip_str));
|
||||
env.push((OsStr::new("BFD_PEER_ADDR"), &remote_ip_str));
|
||||
env.push((OsStr::new("BFD_INTERFACE"), &interface_str));
|
||||
env.push((OsStr::new("BFD_LOCAL_DISCRIMINATOR"), &local_discr_str));
|
||||
env.push((OsStr::new("BFD_PEER_DISCRIMINATOR"), &remote_discr_str));
|
||||
for script in scripts {
|
||||
@@ -177,3 +174,226 @@ impl ScriptHookSink {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rstest::rstest;
|
||||
use std::{
|
||||
fs::{self as stdfs, Permissions},
|
||||
net::{Ipv4Addr, Ipv6Addr},
|
||||
os::unix::fs::PermissionsExt,
|
||||
sync::atomic::{AtomicU32, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("rust-bfd-hooks-{}-{}", std::process::id(), n));
|
||||
stdfs::create_dir_all(path.join("hooks")).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
fn hooks(&self) -> PathBuf {
|
||||
self.0.join("hooks")
|
||||
}
|
||||
fn out(&self) -> PathBuf {
|
||||
self.0.join("out")
|
||||
}
|
||||
fn script(&self, name: &str, mode: u32, body: &str) {
|
||||
let path = self.hooks().join(name);
|
||||
stdfs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
|
||||
stdfs::set_permissions(&path, Permissions::from_mode(mode)).unwrap();
|
||||
}
|
||||
fn append_script(&self, name: &str, mode: u32, line: &str) {
|
||||
self.script(
|
||||
name,
|
||||
mode,
|
||||
&format!("echo \"{line}\" >> {}", self.out().display()),
|
||||
);
|
||||
}
|
||||
fn output(&self) -> Vec<String> {
|
||||
stdfs::read_to_string(self.out())
|
||||
.map(|s| s.lines().map(str::to_owned).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = stdfs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn event(local: IpAddr, remote: IpAddr, from: BfdState, to: BfdState) -> EventMessage {
|
||||
EventMessage::StateChange(StateChangeEvent {
|
||||
local_discr: BfdDiscriminator(11),
|
||||
remote_discr: BfdDiscriminator(22),
|
||||
local_ip: local,
|
||||
remote_ip: remote,
|
||||
interface: None,
|
||||
from_state: from,
|
||||
to_state: to,
|
||||
})
|
||||
}
|
||||
|
||||
fn v4_event() -> EventMessage {
|
||||
event(
|
||||
Ipv4Addr::new(192, 0, 2, 1).into(),
|
||||
Ipv4Addr::new(192, 0, 2, 2).into(),
|
||||
BfdState::Init,
|
||||
BfdState::Up,
|
||||
)
|
||||
}
|
||||
|
||||
const ENV_LINE: &str = "$1|$2|$BFD_STATE|$BFD_LAST_STATE|$BFD_LOCAL_ADDR|$BFD_PEER_ADDR|$BFD_LOCAL_DISCRIMINATOR|$BFD_PEER_DISCRIMINATOR";
|
||||
|
||||
#[rstest]
|
||||
#[case::v4(
|
||||
Ipv4Addr::new(192, 0, 2, 1).into(),
|
||||
Ipv4Addr::new(192, 0, 2, 2).into(),
|
||||
BfdState::Init,
|
||||
BfdState::Up,
|
||||
"up|192.0.2.2|up|init|192.0.2.1|192.0.2.2|11|22"
|
||||
)]
|
||||
#[case::v6(
|
||||
Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).into(),
|
||||
Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 2).into(),
|
||||
BfdState::Up,
|
||||
BfdState::Down,
|
||||
"down|2001:db8::2|down|up|2001:db8::1|2001:db8::2|11|22"
|
||||
)]
|
||||
#[tokio::test]
|
||||
async fn passes_args_and_environment(
|
||||
#[case] local: IpAddr,
|
||||
#[case] remote: IpAddr,
|
||||
#[case] from: BfdState,
|
||||
#[case] to: BfdState,
|
||||
#[case] expected: &str,
|
||||
) {
|
||||
let t = TempDir::new();
|
||||
t.append_script("10-env", 0o755, ENV_LINE);
|
||||
ScriptHookSink::with_script_dir(t.hooks())
|
||||
.handle_event(&event(local, remote, from, to))
|
||||
.await;
|
||||
assert_eq!(t.output(), [expected]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn passes_interface() {
|
||||
let t = TempDir::new();
|
||||
t.append_script("10-env", 0o755, "${BFD_INTERFACE-unset}|$BFD_PEER_ADDR");
|
||||
let sink = ScriptHookSink::with_script_dir(t.hooks());
|
||||
sink.handle_event(&v4_event()).await;
|
||||
sink.handle_event(&EventMessage::StateChange(StateChangeEvent {
|
||||
local_discr: BfdDiscriminator(11),
|
||||
remote_discr: BfdDiscriminator(22),
|
||||
local_ip: "fe80::1".parse().unwrap(),
|
||||
remote_ip: "fe80::2".parse().unwrap(),
|
||||
interface: Some("eth1".to_owned()),
|
||||
from_state: BfdState::Init,
|
||||
to_state: BfdState::Up,
|
||||
}))
|
||||
.await;
|
||||
assert_eq!(t.output(), ["|192.0.2.2", "eth1|fe80::2"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn environment_is_cleared() {
|
||||
let t = TempDir::new();
|
||||
std::env::set_var("RUST_BFD_TEST_LEAK", "leaked");
|
||||
t.append_script(
|
||||
"10-env",
|
||||
0o755,
|
||||
"${RUST_BFD_TEST_LEAK:-unset}|${HOME:-unset}",
|
||||
);
|
||||
ScriptHookSink::with_script_dir(t.hooks())
|
||||
.handle_event(&v4_event())
|
||||
.await;
|
||||
assert_eq!(t.output(), ["unset|unset"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runs_scripts_in_lexicographic_order() {
|
||||
let t = TempDir::new();
|
||||
t.append_script("20-b", 0o755, "b");
|
||||
t.append_script("30-c", 0o755, "c");
|
||||
t.append_script("10-a", 0o755, "a");
|
||||
ScriptHookSink::with_script_dir(t.hooks())
|
||||
.handle_event(&v4_event())
|
||||
.await;
|
||||
assert_eq!(t.output(), ["a", "b", "c"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn skips_non_executable_files_and_directories() {
|
||||
let t = TempDir::new();
|
||||
t.append_script("10-run", 0o755, "run");
|
||||
t.append_script("20-noexec", 0o644, "noexec");
|
||||
let dir = t.hooks().join("30-dir");
|
||||
stdfs::create_dir(&dir).unwrap();
|
||||
stdfs::set_permissions(&dir, Permissions::from_mode(0o755)).unwrap();
|
||||
ScriptHookSink::with_script_dir(t.hooks())
|
||||
.handle_event(&v4_event())
|
||||
.await;
|
||||
assert_eq!(t.output(), ["run"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failing_script_does_not_stop_later_scripts() {
|
||||
let t = TempDir::new();
|
||||
t.script(
|
||||
"10-fail",
|
||||
0o755,
|
||||
"printf '\\377\\376'; printf '\\377' >&2; exit 3",
|
||||
);
|
||||
t.append_script("20-ok", 0o755, "ok");
|
||||
ScriptHookSink::with_script_dir(t.hooks())
|
||||
.handle_event(&v4_event())
|
||||
.await;
|
||||
assert_eq!(t.output(), ["ok"]);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::missing_dir("nope")]
|
||||
#[case::empty_dir("hooks")]
|
||||
#[tokio::test]
|
||||
async fn missing_or_empty_script_dir_is_a_noop(#[case] subdir: &str) {
|
||||
let t = TempDir::new();
|
||||
ScriptHookSink::with_script_dir(t.0.join(subdir))
|
||||
.handle_event(&v4_event())
|
||||
.await;
|
||||
assert!(t.output().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn events_sent_over_channel_run_hooks() {
|
||||
let t = TempDir::new();
|
||||
t.append_script("10-env", 0o755, ENV_LINE);
|
||||
let sink = ScriptHookSink::with_script_dir(t.hooks());
|
||||
let tx = sink.channel();
|
||||
let handle = Box::new(sink).run();
|
||||
tx.send(v4_event()).await.unwrap();
|
||||
tx.send(event(
|
||||
Ipv4Addr::new(192, 0, 2, 1).into(),
|
||||
Ipv4Addr::new(192, 0, 2, 2).into(),
|
||||
BfdState::Up,
|
||||
BfdState::Down,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
for _ in 0..100 {
|
||||
if t.output().len() >= 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
handle.abort();
|
||||
let out = t.output();
|
||||
assert_eq!(out.len(), 2);
|
||||
assert!(out[0].starts_with("up|") && out[1].starts_with("down|"));
|
||||
}
|
||||
}
|
||||
+600
-8
@@ -4,17 +4,200 @@ pub mod control;
|
||||
pub mod events;
|
||||
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
fmt::{self, Display},
|
||||
net::IpAddr,
|
||||
time::Instant,
|
||||
io,
|
||||
net::{IpAddr, SocketAddr, SocketAddrV6},
|
||||
os::fd::AsRawFd,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use log::debug;
|
||||
use nix::sys::socket::{getsockopt, setsockopt, sockopt};
|
||||
use nix::{
|
||||
net::if_::if_nametoindex,
|
||||
sys::socket::{
|
||||
bind, getsockopt, setsockopt, socket, sockopt, AddressFamily, SockFlag, SockProtocol,
|
||||
SockType, SockaddrIn, SockaddrIn6,
|
||||
},
|
||||
};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
use crate::bfd::*;
|
||||
|
||||
/// A snapshot of the packet count and inter-packet interval statistics for one direction of a session.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct IntervalStats {
|
||||
count: u64,
|
||||
min: Option<Duration>,
|
||||
max: Option<Duration>,
|
||||
mean: Option<Duration>,
|
||||
}
|
||||
impl IntervalStats {
|
||||
pub fn count(&self) -> u64 {
|
||||
self.count
|
||||
}
|
||||
pub fn min(&self) -> Option<Duration> {
|
||||
self.min
|
||||
}
|
||||
pub fn max(&self) -> Option<Duration> {
|
||||
self.max
|
||||
}
|
||||
pub fn mean(&self) -> Option<Duration> {
|
||||
self.mean
|
||||
}
|
||||
}
|
||||
impl Display for IntervalStats {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let ms = |d: Option<Duration>| {
|
||||
d.map_or("-".to_string(), |d| {
|
||||
format!("{:.0}", d.as_secs_f64() * 1000.0)
|
||||
})
|
||||
};
|
||||
write!(
|
||||
f,
|
||||
"{} pkts, interval min/avg/max {}/{}/{} ms",
|
||||
self.count,
|
||||
ms(self.min),
|
||||
ms(self.mean),
|
||||
ms(self.max)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// An optional `Instant` that can be shared between threads, stored as nanoseconds since its construction.
|
||||
/// Instants earlier than the construction time are clamped to it.
|
||||
#[derive(Debug)]
|
||||
pub struct AtomicInstant {
|
||||
epoch: Instant,
|
||||
nanos: AtomicU64,
|
||||
}
|
||||
impl AtomicInstant {
|
||||
const NONE: u64 = u64::MAX;
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
epoch: Instant::now(),
|
||||
nanos: AtomicU64::new(Self::NONE),
|
||||
}
|
||||
}
|
||||
pub fn load(&self) -> Option<Instant> {
|
||||
match self.nanos.load(Ordering::Relaxed) {
|
||||
Self::NONE => None,
|
||||
n => Some(self.epoch + Duration::from_nanos(n)),
|
||||
}
|
||||
}
|
||||
pub fn store(&self, value: Instant) {
|
||||
self.swap(value);
|
||||
}
|
||||
pub fn swap(&self, value: Instant) -> Option<Instant> {
|
||||
let n = u64::try_from(value.saturating_duration_since(self.epoch).as_nanos())
|
||||
.unwrap_or(Self::NONE - 1)
|
||||
.min(Self::NONE - 1);
|
||||
match self.nanos.swap(n, Ordering::Relaxed) {
|
||||
Self::NONE => None,
|
||||
prev => Some(self.epoch + Duration::from_nanos(prev)),
|
||||
}
|
||||
}
|
||||
pub fn clear(&self) {
|
||||
self.nanos.store(Self::NONE, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
impl Default for AtomicInstant {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lock-free accumulator for packet counts and inter-packet intervals. Updates are not atomic as a group, so it
|
||||
/// is intended for a single writer; a concurrent reader may observe a mix of old and new values.
|
||||
#[derive(Debug)]
|
||||
pub struct AtomicIntervalStats {
|
||||
count: AtomicU64,
|
||||
last: AtomicInstant,
|
||||
min_nanos: AtomicU64,
|
||||
max_nanos: AtomicU64,
|
||||
total_nanos: AtomicU64,
|
||||
}
|
||||
impl AtomicIntervalStats {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
count: AtomicU64::new(0),
|
||||
last: AtomicInstant::new(),
|
||||
min_nanos: AtomicU64::new(u64::MAX),
|
||||
max_nanos: AtomicU64::new(0),
|
||||
total_nanos: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
pub fn record(&self, now: Instant) {
|
||||
self.count.fetch_add(1, Ordering::Relaxed);
|
||||
if let Some(prev) = self.last.swap(now) {
|
||||
let nanos =
|
||||
u64::try_from(now.saturating_duration_since(prev).as_nanos()).unwrap_or(u64::MAX);
|
||||
self.min_nanos.fetch_min(nanos, Ordering::Relaxed);
|
||||
self.max_nanos.fetch_max(nanos, Ordering::Relaxed);
|
||||
self.total_nanos.fetch_add(nanos, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
pub fn reset(&self) {
|
||||
self.count.store(0, Ordering::Relaxed);
|
||||
self.last.clear();
|
||||
self.min_nanos.store(u64::MAX, Ordering::Relaxed);
|
||||
self.max_nanos.store(0, Ordering::Relaxed);
|
||||
self.total_nanos.store(0, Ordering::Relaxed);
|
||||
}
|
||||
pub fn snapshot(&self) -> IntervalStats {
|
||||
let count = self.count.load(Ordering::Relaxed);
|
||||
let intervals = count.saturating_sub(1);
|
||||
if intervals == 0 {
|
||||
return IntervalStats {
|
||||
count,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
let total = self.total_nanos.load(Ordering::Relaxed);
|
||||
IntervalStats {
|
||||
count,
|
||||
min: Some(Duration::from_nanos(self.min_nanos.load(Ordering::Relaxed))),
|
||||
max: Some(Duration::from_nanos(self.max_nanos.load(Ordering::Relaxed))),
|
||||
mean: Some(Duration::from_nanos(total / intervals)),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for AtomicIntervalStats {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt_ago(t: Option<Instant>) -> String {
|
||||
t.map_or("never".to_string(), |t| {
|
||||
format!("{}s ago", t.elapsed().as_secs())
|
||||
})
|
||||
}
|
||||
|
||||
/// A snapshot of a session's authentication state. Sequence numbers are `None` when not applicable or not yet known.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AuthStats {
|
||||
pub auth_type: BfdAuthType,
|
||||
pub key_id: u8,
|
||||
pub rcv_seq: Option<u32>,
|
||||
pub xmit_seq: Option<u32>,
|
||||
}
|
||||
impl Display for AuthStats {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let seq = |s: Option<u32>| s.map_or("-".to_string(), |s| s.to_string());
|
||||
write!(
|
||||
f,
|
||||
"{} KeyId:{} RcvSeq:{} XmitSeq:{}",
|
||||
self.auth_type,
|
||||
self.key_id,
|
||||
seq(self.rcv_seq),
|
||||
seq(self.xmit_seq)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BfdSessionStats {
|
||||
pub local_ip: IpAddr,
|
||||
@@ -23,13 +206,24 @@ pub struct BfdSessionStats {
|
||||
pub remote_discr: BfdDiscriminator,
|
||||
pub state: BfdState,
|
||||
pub last_diag: BfdDiagnostic,
|
||||
pub control_packets_rx: u64,
|
||||
pub control_packets_tx: u64,
|
||||
/// Valid (not discarded) packet statistics since the session last entered Up
|
||||
pub rx: IntervalStats,
|
||||
/// Every packet received over the life of the session, including discarded ones
|
||||
pub rx_received: u64,
|
||||
pub tx: IntervalStats,
|
||||
pub last_up: Option<Instant>,
|
||||
pub last_down: Option<Instant>,
|
||||
pub last_change: Instant,
|
||||
pub detect_time: BfdInterval,
|
||||
pub base_interval: BfdInterval,
|
||||
/// `None` when the session does not use authentication
|
||||
pub auth: Option<AuthStats>,
|
||||
}
|
||||
impl BfdSessionStats {
|
||||
pub fn with_auth(mut self, auth: Option<AuthStats>) -> Self {
|
||||
self.auth = auth;
|
||||
self
|
||||
}
|
||||
pub fn with_base_interval(mut self, base_interval: BfdInterval) -> Self {
|
||||
self.base_interval = base_interval;
|
||||
self
|
||||
@@ -40,9 +234,12 @@ impl Display for BfdSessionStats {
|
||||
writeln!(
|
||||
f,
|
||||
"{:<20} {:<9} {:>6} {:>6}",
|
||||
self.remote_ip, self.state, self.control_packets_rx, self.control_packets_tx
|
||||
self.remote_ip,
|
||||
self.state,
|
||||
self.rx.count(),
|
||||
self.tx.count()
|
||||
)?;
|
||||
write!(
|
||||
writeln!(
|
||||
f,
|
||||
" LocalDiscr:{} RemoteDiscr:{} DetectTime: {} TxTime: {} Diag:{} Last: {}s",
|
||||
self.local_discr,
|
||||
@@ -51,10 +248,122 @@ impl Display for BfdSessionStats {
|
||||
self.base_interval,
|
||||
self.last_diag,
|
||||
Instant::now().duration_since(self.last_change).as_secs()
|
||||
)?;
|
||||
writeln!(f, " Rx: {}", self.rx)?;
|
||||
writeln!(f, " Tx: {}", self.tx)?;
|
||||
match &self.auth {
|
||||
Some(auth) => writeln!(f, " Auth: {auth}")?,
|
||||
None => writeln!(f, " Auth: none")?,
|
||||
}
|
||||
write!(
|
||||
f,
|
||||
" Last Up: {} Last Down: {}",
|
||||
fmt_ago(self.last_up),
|
||||
fmt_ago(self.last_down)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_ipv6_link_local(addr: &IpAddr) -> bool {
|
||||
matches!(addr, IpAddr::V6(a) if a.segments()[0] & 0xffc0 == 0xfe80)
|
||||
}
|
||||
|
||||
/// Bind a UDP socket, optionally to a single interface (`SO_BINDTODEVICE`). The device is set before `bind` so that
|
||||
/// sockets on different interfaces can share an address and port. Must be called from within a Tokio runtime.
|
||||
pub fn bind_udp(addr: SocketAddr, interface: Option<&str>) -> io::Result<UdpSocket> {
|
||||
let family = match addr {
|
||||
SocketAddr::V4(_) => AddressFamily::Inet,
|
||||
SocketAddr::V6(_) => AddressFamily::Inet6,
|
||||
};
|
||||
let fd = socket(
|
||||
family,
|
||||
SockType::Datagram,
|
||||
SockFlag::SOCK_NONBLOCK | SockFlag::SOCK_CLOEXEC,
|
||||
None::<SockProtocol>,
|
||||
)?;
|
||||
if let Some(name) = interface {
|
||||
setsockopt(&fd, sockopt::BindToDevice, &OsString::from(name))?;
|
||||
}
|
||||
match addr {
|
||||
SocketAddr::V4(a) => bind(fd.as_raw_fd(), &SockaddrIn::from(a)),
|
||||
SocketAddr::V6(a) => bind(fd.as_raw_fd(), &SockaddrIn6::from(a)),
|
||||
}?;
|
||||
UdpSocket::from_std(std::net::UdpSocket::from(fd))
|
||||
}
|
||||
|
||||
/// A socket address for `ip`:`port`. An IPv6 link-local address is only meaningful with a scope, so it is scoped to
|
||||
/// `interface`, which is then required.
|
||||
pub fn scoped_socket_addr(
|
||||
ip: IpAddr,
|
||||
port: u16,
|
||||
interface: Option<&str>,
|
||||
) -> io::Result<SocketAddr> {
|
||||
match (ip, interface) {
|
||||
(IpAddr::V6(v6), Some(name)) if is_ipv6_link_local(&ip) => {
|
||||
let scope_id = if_nametoindex(name)?;
|
||||
Ok(SocketAddr::V6(SocketAddrV6::new(v6, port, 0, scope_id)))
|
||||
}
|
||||
(_, None) if is_ipv6_link_local(&ip) => Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("link-local address {ip} requires an interface"),
|
||||
)),
|
||||
_ => Ok(SocketAddr::new(ip, port)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Have the kernel discard datagrams that arrive with a TTL (IPv4) or Hop Limit (IPv6) other than `hop_limit`.
|
||||
///
|
||||
/// `IP_MINTTL` and `IPV6_MINHOPCOUNT` are only enforced for TCP, so this attaches a classic BPF socket filter that
|
||||
/// reads the field from the network header (`SKF_NET_OFF`). Discards are silent.
|
||||
pub fn require_hop_limit(sock: &UdpSocket, hop_limit: u8) -> io::Result<()> {
|
||||
// Offset of the TTL in the IPv4 header, and of the Hop Limit in the IPv6 header
|
||||
let field_offset = if sock.local_addr()?.is_ipv4() { 8 } else { 7 };
|
||||
let insn = |code: u32, jt: u8, jf: u8, k: u32| nix::libc::sock_filter {
|
||||
code: code as u16,
|
||||
jt,
|
||||
jf,
|
||||
k,
|
||||
};
|
||||
let mut program = [
|
||||
// A = the TTL / Hop Limit byte
|
||||
insn(
|
||||
nix::libc::BPF_LD | nix::libc::BPF_B | nix::libc::BPF_ABS,
|
||||
0,
|
||||
0,
|
||||
(nix::libc::SKF_NET_OFF + field_offset) as u32,
|
||||
),
|
||||
// if A == hop_limit, skip the drop
|
||||
insn(
|
||||
nix::libc::BPF_JMP | nix::libc::BPF_JEQ | nix::libc::BPF_K,
|
||||
1,
|
||||
0,
|
||||
hop_limit as u32,
|
||||
),
|
||||
insn(nix::libc::BPF_RET | nix::libc::BPF_K, 0, 0, 0),
|
||||
insn(nix::libc::BPF_RET | nix::libc::BPF_K, 0, 0, u32::MAX),
|
||||
];
|
||||
let fprog = nix::libc::sock_fprog {
|
||||
len: program.len() as u16,
|
||||
filter: program.as_mut_ptr(),
|
||||
};
|
||||
// SAFETY: `fprog` and the program it points to are valid for the duration of the call, and the kernel copies
|
||||
// the program during it.
|
||||
let res = unsafe {
|
||||
nix::libc::setsockopt(
|
||||
sock.as_raw_fd(),
|
||||
nix::libc::SOL_SOCKET,
|
||||
nix::libc::SO_ATTACH_FILTER,
|
||||
std::ptr::from_ref(&fprog).cast(),
|
||||
std::mem::size_of::<nix::libc::sock_fprog>() as nix::libc::socklen_t,
|
||||
)
|
||||
};
|
||||
if res == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std::io::Error> {
|
||||
let addr = sock.local_addr()?;
|
||||
if addr.is_ipv4() {
|
||||
@@ -70,7 +379,290 @@ pub fn set_ttl_or_hop_limit(sock: &UdpSocket, hop_limit: u8) -> Result<(), std::
|
||||
debug!("Got {} after setting {}", res, i32_hop_limit);
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
} else {
|
||||
panic!("UdpSocket with no address family ?!")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rstest::rstest;
|
||||
|
||||
fn record_offsets_ms(offsets_ms: &[u64]) -> AtomicIntervalStats {
|
||||
let stats = AtomicIntervalStats::new();
|
||||
let t0 = Instant::now();
|
||||
for &ms in offsets_ms {
|
||||
stats.record(t0 + Duration::from_millis(ms));
|
||||
}
|
||||
stats
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::empty(&[], 0, None, None, None)]
|
||||
#[case::single_packet_has_no_intervals(&[0], 1, None, None, None)]
|
||||
#[case::min_max_mean(&[0, 100, 400, 500], 4, Some(100), Some(300), Some(166))]
|
||||
fn interval_stats_summary(
|
||||
#[case] offsets_ms: &[u64],
|
||||
#[case] count: u64,
|
||||
#[case] min_ms: Option<u64>,
|
||||
#[case] max_ms: Option<u64>,
|
||||
#[case] mean_ms: Option<u128>,
|
||||
) {
|
||||
let s = record_offsets_ms(offsets_ms).snapshot();
|
||||
assert_eq!(s.count(), count);
|
||||
assert_eq!(s.min(), min_ms.map(Duration::from_millis));
|
||||
assert_eq!(s.max(), max_ms.map(Duration::from_millis));
|
||||
assert_eq!(s.mean().map(|m| m.as_millis()), mean_ms);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interval_stats_reset() {
|
||||
let stats = AtomicIntervalStats::new();
|
||||
let t0 = Instant::now();
|
||||
stats.record(t0);
|
||||
stats.record(t0 + Duration::from_millis(100));
|
||||
stats.reset();
|
||||
let s = stats.snapshot();
|
||||
assert_eq!(s.count(), 0);
|
||||
assert_eq!((s.min(), s.max(), s.mean()), (None, None, None));
|
||||
stats.record(t0 + Duration::from_millis(900));
|
||||
stats.record(t0 + Duration::from_millis(1000));
|
||||
assert_eq!(stats.snapshot().max(), Some(Duration::from_millis(100)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_instant_roundtrip() {
|
||||
let a = AtomicInstant::new();
|
||||
assert_eq!(a.load(), None);
|
||||
let t = Instant::now() + Duration::from_secs(5);
|
||||
assert_eq!(a.swap(t), None);
|
||||
assert_eq!(a.load(), Some(t));
|
||||
a.clear();
|
||||
assert_eq!(a.load(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_instant_swap_returns_previous() {
|
||||
let a = AtomicInstant::new();
|
||||
let t1 = Instant::now() + Duration::from_secs(1);
|
||||
let t2 = t1 + Duration::from_secs(1);
|
||||
a.store(t1);
|
||||
assert_eq!(a.swap(t2), Some(t1));
|
||||
assert_eq!(a.load(), Some(t2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_instant_clamps_before_epoch() {
|
||||
let a = AtomicInstant::new();
|
||||
let before = Instant::now().checked_sub(Duration::from_secs(1));
|
||||
let Some(before) = before else { return };
|
||||
a.store(before);
|
||||
let loaded = a.load().unwrap();
|
||||
assert!(loaded >= before);
|
||||
assert!(loaded <= Instant::now());
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::empty(IntervalStats::default(), "0 pkts, interval min/avg/max -/-/- ms")]
|
||||
#[case::four_packets(
|
||||
record_offsets_ms(&[0, 100, 400, 500]).snapshot(),
|
||||
"4 pkts, interval min/avg/max 100/167/300 ms"
|
||||
)]
|
||||
fn interval_stats_display(#[case] stats: IntervalStats, #[case] expected: &str) {
|
||||
assert_eq!(stats.to_string(), expected);
|
||||
}
|
||||
|
||||
fn session_stats(last_up: Option<Instant>, last_down: Option<Instant>) -> BfdSessionStats {
|
||||
let rx = AtomicIntervalStats::new();
|
||||
let tx = AtomicIntervalStats::new();
|
||||
let t0 = Instant::now();
|
||||
rx.record(t0);
|
||||
rx.record(t0 + Duration::from_millis(300));
|
||||
tx.record(t0);
|
||||
BfdSessionStats {
|
||||
local_ip: "192.0.2.1".parse().unwrap(),
|
||||
remote_ip: "192.0.2.2".parse().unwrap(),
|
||||
local_discr: BfdDiscriminator(10),
|
||||
remote_discr: BfdDiscriminator(20),
|
||||
state: BfdState::Up,
|
||||
last_diag: BfdDiagnostic::TimeExpired,
|
||||
rx: rx.snapshot(),
|
||||
rx_received: 2,
|
||||
tx: tx.snapshot(),
|
||||
last_up,
|
||||
last_down,
|
||||
last_change: Instant::now(),
|
||||
detect_time: BfdInterval::from_millis(900),
|
||||
base_interval: BfdInterval::from_secs(1),
|
||||
auth: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_stats_display_never() {
|
||||
let out = session_stats(None, None).to_string();
|
||||
let lines: Vec<&str> = out.lines().collect();
|
||||
assert_eq!(lines.len(), 6);
|
||||
assert_eq!(
|
||||
lines[0].split_whitespace().collect::<Vec<_>>(),
|
||||
["192.0.2.2", "Up", "2", "1"]
|
||||
);
|
||||
assert_eq!(
|
||||
lines[1].trim(),
|
||||
"LocalDiscr:10 RemoteDiscr:20 DetectTime: 900000us TxTime: 1000000us Diag:TimeExpired Last: 0s"
|
||||
);
|
||||
assert_eq!(
|
||||
lines[2],
|
||||
" Rx: 2 pkts, interval min/avg/max 300/300/300 ms"
|
||||
);
|
||||
assert_eq!(lines[3], " Tx: 1 pkts, interval min/avg/max -/-/- ms");
|
||||
assert_eq!(lines[4], " Auth: none");
|
||||
assert_eq!(lines[5], " Last Up: never Last Down: never");
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::meticulous_sha1(
|
||||
AuthStats {
|
||||
auth_type: BfdAuthType::MetKeyedSHA1,
|
||||
key_id: 3,
|
||||
rcv_seq: Some(100),
|
||||
xmit_seq: Some(7),
|
||||
},
|
||||
"\n Auth: meticulous-sha1 KeyId:3 RcvSeq:100 XmitSeq:7\n"
|
||||
)]
|
||||
#[case::md5_without_rcv_seq(
|
||||
AuthStats {
|
||||
auth_type: BfdAuthType::KeyedMD5,
|
||||
key_id: 1,
|
||||
rcv_seq: None,
|
||||
xmit_seq: Some(7),
|
||||
},
|
||||
"\n Auth: md5 KeyId:1 RcvSeq:- XmitSeq:7\n"
|
||||
)]
|
||||
fn session_stats_display_auth(#[case] auth: AuthStats, #[case] expected: &str) {
|
||||
let out = session_stats(None, None).with_auth(Some(auth)).to_string();
|
||||
assert!(out.contains(expected), "{out}");
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::last_up(true, false, "Last Up: 0s ago Last Down: never")]
|
||||
#[case::last_down(false, true, "Last Up: never Last Down: 0s ago")]
|
||||
fn session_stats_display_last_up_down(
|
||||
#[case] up: bool,
|
||||
#[case] down: bool,
|
||||
#[case] expected_suffix: &str,
|
||||
) {
|
||||
let now = Instant::now();
|
||||
let out = session_stats(up.then_some(now), down.then_some(now)).to_string();
|
||||
assert!(out.ends_with(expected_suffix), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_stats_with_base_interval() {
|
||||
let s = session_stats(None, None).with_base_interval(BfdInterval::from_millis(300));
|
||||
assert_eq!(s.base_interval, BfdInterval::from_millis(300));
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn set_ttl_v4(#[values(255, 64)] ttl: u8) {
|
||||
let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
set_ttl_or_hop_limit(&sock, ttl).unwrap();
|
||||
assert_eq!(sock.ttl().unwrap(), u32::from(ttl));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_hop_limit_v6() {
|
||||
let Ok(sock) = UdpSocket::bind("[::1]:0").await else {
|
||||
return;
|
||||
};
|
||||
set_ttl_or_hop_limit(&sock, 255).unwrap();
|
||||
assert_eq!(getsockopt(&sock, sockopt::Ipv6Ttl).unwrap(), 255);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::v4("127.0.0.1:0")]
|
||||
#[case::v6("[::1]:0")]
|
||||
#[tokio::test]
|
||||
async fn require_hop_limit_accepts_only_255(#[case] bind: &str) {
|
||||
let Ok(rx) = UdpSocket::bind(bind).await else {
|
||||
return;
|
||||
};
|
||||
require_hop_limit(&rx, 255).unwrap();
|
||||
let tx = UdpSocket::bind(bind).await.unwrap();
|
||||
for hop_limit in [1u8, 64, 254, 255] {
|
||||
set_ttl_or_hop_limit(&tx, hop_limit).unwrap();
|
||||
tx.send_to(&[hop_limit], rx.local_addr().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let mut buf = [0u8; 8];
|
||||
let n = rx.recv(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf[..n], [255]);
|
||||
let more = tokio::time::timeout(Duration::from_millis(100), rx.recv(&mut buf)).await;
|
||||
assert!(more.is_err(), "received a datagram with hop limit != 255");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bind_udp_without_interface() {
|
||||
let sock = bind_udp("127.0.0.1:0".parse().unwrap(), None).unwrap();
|
||||
assert!(sock.local_addr().unwrap().port() != 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bind_udp_to_loopback_interface() {
|
||||
let sock = bind_udp("127.0.0.1:0".parse().unwrap(), Some("lo")).unwrap();
|
||||
let addr = sock.local_addr().unwrap();
|
||||
let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
peer.send_to(b"x", addr).await.unwrap();
|
||||
let mut buf = [0u8; 1];
|
||||
let (n, _) = sock.recv_from(&mut buf).await.unwrap();
|
||||
assert_eq!(n, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bind_udp_rejects_unknown_interface() {
|
||||
assert!(bind_udp("127.0.0.1:0".parse().unwrap(), Some("nosuchif0")).is_err());
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::link_local_is_scoped("fe80::1", Some("lo"), "[fe80::1%{lo}]:3784")]
|
||||
#[case::global_v6_is_unscoped("2001:db8::1", Some("lo"), "[2001:db8::1]:3784")]
|
||||
#[case::v4_is_unscoped("192.0.2.1", None, "192.0.2.1:3784")]
|
||||
fn scoped_socket_addr_formats(
|
||||
#[case] addr: &str,
|
||||
#[case] interface: Option<&str>,
|
||||
#[case] expected: &str,
|
||||
) {
|
||||
let lo = if_nametoindex("lo").unwrap();
|
||||
let scoped = scoped_socket_addr(addr.parse().unwrap(), 3784, interface).unwrap();
|
||||
assert_eq!(
|
||||
scoped.to_string(),
|
||||
expected.replace("{lo}", &lo.to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::link_local_without_interface(None, Some(io::ErrorKind::InvalidInput))]
|
||||
#[case::link_local_unknown_interface(Some("nosuchif0"), None)]
|
||||
fn scoped_socket_addr_rejects(
|
||||
#[case] interface: Option<&str>,
|
||||
#[case] kind: Option<io::ErrorKind>,
|
||||
) {
|
||||
let err = scoped_socket_addr("fe80::1".parse().unwrap(), 3784, interface).unwrap_err();
|
||||
if let Some(kind) = kind {
|
||||
assert_eq!(err.kind(), kind);
|
||||
}
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::fe80("fe80::1", true)]
|
||||
#[case::febf("febf::1", true)]
|
||||
#[case::fec0("fec0::1", false)]
|
||||
#[case::global_v6("2001:db8::1", false)]
|
||||
#[case::v4_link_local("169.254.0.1", false)]
|
||||
fn link_local_detection(#[case] addr: &str, #[case] expected: bool) {
|
||||
assert_eq!(is_ipv6_link_local(&addr.parse().unwrap()), expected);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user