Compare commits
7
Commits
0284ee17b1
...
ac154066e1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac154066e1 | ||
|
|
8321d01ffb | ||
|
|
eeeef5fb73 | ||
|
|
87e2011c05 | ||
|
|
0c19b955f9 | ||
|
|
5e5da0c78c | ||
|
|
ea56afd2f2 |
No files matched your search
Generated
+83
@@ -255,6 +255,12 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "equivalent"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "errno"
|
name = "errno"
|
||||||
version = "0.3.14"
|
version = "0.3.14"
|
||||||
@@ -370,12 +376,44 @@ dependencies = [
|
|||||||
"wasi",
|
"wasi",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hashbrown"
|
||||||
|
version = "0.17.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "heck"
|
name = "heck"
|
||||||
version = "0.5.0"
|
version = "0.5.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "humantime"
|
||||||
|
version = "2.4.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "humantime-serde"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c"
|
||||||
|
dependencies = [
|
||||||
|
"humantime",
|
||||||
|
"serde",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "indexmap"
|
||||||
|
version = "2.14.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||||
|
dependencies = [
|
||||||
|
"equivalent",
|
||||||
|
"hashbrown",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "is_terminal_polyfill"
|
name = "is_terminal_polyfill"
|
||||||
version = "1.70.2"
|
version = "1.70.2"
|
||||||
@@ -391,6 +429,12 @@ dependencies = [
|
|||||||
"either",
|
"either",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itoa"
|
||||||
|
version = "1.0.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jiff"
|
name = "jiff"
|
||||||
version = "0.2.38"
|
version = "0.2.38"
|
||||||
@@ -708,6 +752,8 @@ dependencies = [
|
|||||||
"clap",
|
"clap",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
"futures 0.3.34",
|
"futures 0.3.34",
|
||||||
|
"humantime",
|
||||||
|
"humantime-serde",
|
||||||
"itertools",
|
"itertools",
|
||||||
"log",
|
"log",
|
||||||
"nix",
|
"nix",
|
||||||
@@ -715,6 +761,8 @@ dependencies = [
|
|||||||
"nom-derive",
|
"nom-derive",
|
||||||
"proc-bitfield",
|
"proc-bitfield",
|
||||||
"rand",
|
"rand",
|
||||||
|
"serde",
|
||||||
|
"serde_yaml_ng",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-timer",
|
"tokio-timer",
|
||||||
]
|
]
|
||||||
@@ -725,12 +773,28 @@ version = "1.0.23"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ryu"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "scopeguard"
|
name = "scopeguard"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_core"
|
name = "serde_core"
|
||||||
version = "1.0.229"
|
version = "1.0.229"
|
||||||
@@ -751,6 +815,19 @@ dependencies = [
|
|||||||
"syn 3.0.9",
|
"syn 3.0.9",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_yaml_ng"
|
||||||
|
version = "0.10.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f"
|
||||||
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
|
"itoa",
|
||||||
|
"ryu",
|
||||||
|
"serde",
|
||||||
|
"unsafe-libyaml",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "signal-hook-registry"
|
name = "signal-hook-registry"
|
||||||
version = "1.4.8"
|
version = "1.4.8"
|
||||||
@@ -904,6 +981,12 @@ version = "1.0.27"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unsafe-libyaml"
|
||||||
|
version = "0.2.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "utf8parse"
|
name = "utf8parse"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
|
|||||||
+5
-1
@@ -7,9 +7,11 @@ edition = "2021"
|
|||||||
atomic = "0.6.0"
|
atomic = "0.6.0"
|
||||||
bytemuck = { version = "1.14.1", features = ["derive"] }
|
bytemuck = { version = "1.14.1", features = ["derive"] }
|
||||||
byteorder = "1.5.0"
|
byteorder = "1.5.0"
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive", "env"] }
|
||||||
env_logger = "0.11.1"
|
env_logger = "0.11.1"
|
||||||
futures = "0.3.30"
|
futures = "0.3.30"
|
||||||
|
humantime = "2.4.0"
|
||||||
|
humantime-serde = "1.1.1"
|
||||||
itertools = "0.12.1"
|
itertools = "0.12.1"
|
||||||
log = "0.4.20"
|
log = "0.4.20"
|
||||||
nix = { version = "0.31.3", features = ["fs", "socket"] }
|
nix = { version = "0.31.3", features = ["fs", "socket"] }
|
||||||
@@ -17,5 +19,7 @@ nom = "7.1.3"
|
|||||||
nom-derive = "0.10.1"
|
nom-derive = "0.10.1"
|
||||||
proc-bitfield = "0.3.1"
|
proc-bitfield = "0.3.1"
|
||||||
rand = "0.8.5"
|
rand = "0.8.5"
|
||||||
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
serde_yaml_ng = "0.10.0"
|
||||||
tokio = { version = "1.35.1", features = ["net", "full"] }
|
tokio = { version = "1.35.1", features = ["net", "full"] }
|
||||||
tokio-timer = "0.2.13"
|
tokio-timer = "0.2.13"
|
||||||
+12
-7
@@ -1,4 +1,7 @@
|
|||||||
FROM rust:1.94-bookworm AS builder
|
FROM rust:1.94-bookworm AS builder
|
||||||
|
# Statically linked musl build. Override for other architectures, e.g. --build-arg RUST_TARGET=aarch64-unknown-linux-musl
|
||||||
|
ARG RUST_TARGET=x86_64-unknown-linux-musl
|
||||||
|
RUN rustup target add ${RUST_TARGET}
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
# Build dependencies against stub sources so this layer is only invalidated by Cargo.toml/Cargo.lock changes.
|
# Build dependencies against stub sources so this layer is only invalidated by Cargo.toml/Cargo.lock changes.
|
||||||
@@ -6,18 +9,20 @@ COPY Cargo.toml Cargo.lock ./
|
|||||||
RUN mkdir -p src/bin \
|
RUN mkdir -p src/bin \
|
||||||
&& touch src/lib.rs \
|
&& touch src/lib.rs \
|
||||||
&& echo 'fn main() {}' > src/bin/rust-bfdd.rs \
|
&& echo 'fn main() {}' > src/bin/rust-bfdd.rs \
|
||||||
&& cargo build --release --locked --bin rust-bfdd \
|
&& cargo build --release --locked --target ${RUST_TARGET} --bin rust-bfdd \
|
||||||
&& rm -rf src
|
&& rm -rf src
|
||||||
|
|
||||||
COPY src ./src
|
COPY src ./src
|
||||||
# COPY keeps the host mtimes, which may predate the stub build; force cargo to rebuild the crate itself.
|
# COPY keeps the host mtimes, which may predate the stub build; force cargo to rebuild the crate itself.
|
||||||
RUN touch src/lib.rs src/bin/rust-bfdd.rs \
|
RUN touch src/lib.rs src/bin/rust-bfdd.rs \
|
||||||
&& cargo build --release --locked --bin rust-bfdd
|
&& cargo build --release --locked --target ${RUST_TARGET} --bin rust-bfdd \
|
||||||
|
&& mkdir -p /rootfs/etc/rust-bfd/hooks.d \
|
||||||
|
&& cp target/${RUST_TARGET}/release/rust-bfdd /rootfs/rust-bfdd
|
||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM scratch
|
||||||
RUN useradd --system --no-create-home --shell /usr/sbin/nologin bfd \
|
COPY --from=builder /rootfs/etc /etc
|
||||||
&& mkdir -p /etc/rust-bfd/hooks.d
|
COPY --from=builder /rootfs/rust-bfdd /usr/local/bin/rust-bfdd
|
||||||
COPY --from=builder /build/target/release/rust-bfdd /usr/local/bin/rust-bfdd
|
# No /etc/passwd in scratch, so use a numeric unprivileged user
|
||||||
USER bfd
|
USER 10001:10001
|
||||||
EXPOSE 3784/udp
|
EXPOSE 3784/udp
|
||||||
ENTRYPOINT ["/usr/local/bin/rust-bfdd"]
|
ENTRYPOINT ["/usr/local/bin/rust-bfdd"]
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# rust-bfd configuration. Install as /etc/rust-bfd/config.yaml (or pass --config / set BFD_CONFIG).
|
||||||
|
#
|
||||||
|
# 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).
|
||||||
|
# A peer is never allowed a zero interval or a detect_mult of 0.
|
||||||
|
defaults:
|
||||||
|
# Minimum interval between transmitted control packets that we would like to use once the session is Up. Sessions
|
||||||
|
# that are not Up transmit no faster than once per second regardless (RFC 5880 section 6.8.3).
|
||||||
|
# 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:
|
||||||
|
- address: 192.0.2.2
|
||||||
|
# Per-peer overrides of any `defaults` key:
|
||||||
|
# - address: 192.0.2.3
|
||||||
|
# desired_min_tx: 1s
|
||||||
|
# required_min_rx: 1s
|
||||||
|
# detect_mult: 5
|
||||||
+249
-106
@@ -1,15 +1,17 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use futures::future;
|
use futures::future;
|
||||||
|
use rust_bfd::config::{Config, ConfigError, ResolvedConfig, ResolvedPeer};
|
||||||
use rust_bfd::events::{EventMessageSink, ScriptHookSink, StateChangeEvent};
|
use rust_bfd::events::{EventMessageSink, ScriptHookSink, StateChangeEvent};
|
||||||
use rust_bfd::{bfd::*, events::EventMessage};
|
use rust_bfd::{bfd::*, events::EventMessage};
|
||||||
use rust_bfd::{set_ttl_or_hop_limit, BfdSessionStats};
|
use rust_bfd::{set_ttl_or_hop_limit, BfdSessionStats};
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::{HashMap, HashSet},
|
||||||
error::Error,
|
error::Error,
|
||||||
fmt::Display,
|
fmt::Display,
|
||||||
io::ErrorKind,
|
io::ErrorKind,
|
||||||
mem::swap,
|
mem::swap,
|
||||||
net::{IpAddr, SocketAddr},
|
net::{IpAddr, SocketAddr},
|
||||||
|
path::PathBuf,
|
||||||
sync::{atomic::Ordering, Arc},
|
sync::{atomic::Ordering, Arc},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
@@ -19,14 +21,15 @@ use std::{
|
|||||||
use tokio::sync::{oneshot, Mutex};
|
use tokio::sync::{oneshot, Mutex};
|
||||||
|
|
||||||
use env_logger::Env;
|
use env_logger::Env;
|
||||||
use log::{debug, info, warn};
|
use log::{debug, info, log_enabled, warn};
|
||||||
|
|
||||||
use nom_derive::Parse;
|
use nom_derive::Parse;
|
||||||
use rand::prelude::*;
|
use rand::prelude::*;
|
||||||
use tokio::io;
|
use tokio::io;
|
||||||
use tokio::net::UdpSocket;
|
use tokio::net::UdpSocket;
|
||||||
|
use tokio::signal::unix::{signal, SignalKind};
|
||||||
use tokio::sync::mpsc;
|
use tokio::sync::mpsc;
|
||||||
use tokio::task::{self, JoinHandle};
|
use tokio::task::JoinHandle;
|
||||||
use tokio::time;
|
use tokio::time;
|
||||||
|
|
||||||
use atomic::Atomic;
|
use atomic::Atomic;
|
||||||
@@ -37,12 +40,18 @@ const ECHO_PORT: u16 = 3785;
|
|||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(version, about = "BFD (RFC 5880) daemon")]
|
#[command(version, about = "BFD (RFC 5880) daemon")]
|
||||||
struct Args {
|
struct Args {
|
||||||
/// Local IP address to bind to and use as the source of BFD control packets
|
/// YAML configuration file [default: /etc/rust-bfd/config.yaml, ignored if absent]
|
||||||
#[arg(short, long, value_name = "IP")]
|
#[arg(short, long, value_name = "FILE", env = "BFD_CONFIG")]
|
||||||
bind: IpAddr,
|
config: Option<PathBuf>,
|
||||||
|
|
||||||
/// Peer IP address to establish a session with (repeatable; must match the bind address family)
|
/// Local IP address to bind to and use as the source of BFD control packets (repeatable). Replaces any bind
|
||||||
#[arg(short, long = "peer", value_name = "IP", required = true)]
|
/// addresses from the config file or environment.
|
||||||
|
#[arg(short, long, value_name = "IP")]
|
||||||
|
bind: Vec<IpAddr>,
|
||||||
|
|
||||||
|
/// Peer IP address to establish a session with, using the default timers (repeatable). Added to the peers from
|
||||||
|
/// the config file.
|
||||||
|
#[arg(short, long = "peer", value_name = "IP")]
|
||||||
peers: Vec<IpAddr>,
|
peers: Vec<IpAddr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,7 +302,7 @@ struct BfdSessionHandle {
|
|||||||
impl BfdSessionHandle {
|
impl BfdSessionHandle {
|
||||||
async fn new(
|
async fn new(
|
||||||
local_addr: IpAddr,
|
local_addr: IpAddr,
|
||||||
remote_addr: IpAddr,
|
peer: ResolvedPeer,
|
||||||
local_discr: BfdDiscriminator,
|
local_discr: BfdDiscriminator,
|
||||||
event_dispatcher: EventDispatcherHandle,
|
event_dispatcher: EventDispatcherHandle,
|
||||||
) -> io::Result<Self> {
|
) -> io::Result<Self> {
|
||||||
@@ -307,7 +316,7 @@ impl BfdSessionHandle {
|
|||||||
new_self.clone(),
|
new_self.clone(),
|
||||||
control_sock,
|
control_sock,
|
||||||
local_addr,
|
local_addr,
|
||||||
remote_addr,
|
peer,
|
||||||
local_discr,
|
local_discr,
|
||||||
event_dispatcher,
|
event_dispatcher,
|
||||||
);
|
);
|
||||||
@@ -340,9 +349,9 @@ struct BfdPeriodicSenderHandle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl BfdPeriodicSenderHandle {
|
impl BfdPeriodicSenderHandle {
|
||||||
fn new(bfd: BfdSessionHandle, interval: BfdInterval) -> Self {
|
fn new(bfd: BfdSessionHandle, interval: BfdInterval, detect_mult: u8) -> Self {
|
||||||
let (tx, rx) = mpsc::channel(32);
|
let (tx, rx) = mpsc::channel(32);
|
||||||
let mut periodic_sender = BfdPeriodicSender::new(rx, bfd, interval);
|
let mut periodic_sender = BfdPeriodicSender::new(rx, bfd, interval, detect_mult);
|
||||||
tokio::spawn(async move { periodic_sender.run().await });
|
tokio::spawn(async move { periodic_sender.run().await });
|
||||||
|
|
||||||
Self { tx }
|
Self { tx }
|
||||||
@@ -353,6 +362,13 @@ struct BfdPeriodicSender {
|
|||||||
rx: mpsc::Receiver<PeriodicControlCommand>,
|
rx: mpsc::Receiver<PeriodicControlCommand>,
|
||||||
bfd: BfdSessionHandle,
|
bfd: BfdSessionHandle,
|
||||||
cur_interval: BfdInterval,
|
cur_interval: BfdInterval,
|
||||||
|
detect_mult: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn jittered_delay(interval: time::Duration, detect_mult: u8) -> time::Duration {
|
||||||
|
// https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.7
|
||||||
|
let min_percent = if detect_mult == 1 { 90 } else { 75 };
|
||||||
|
rand::thread_rng().gen_range(interval * min_percent / 100..=interval)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BfdPeriodicSender {
|
impl BfdPeriodicSender {
|
||||||
@@ -360,30 +376,28 @@ impl BfdPeriodicSender {
|
|||||||
rx: mpsc::Receiver<PeriodicControlCommand>,
|
rx: mpsc::Receiver<PeriodicControlCommand>,
|
||||||
bfd: BfdSessionHandle,
|
bfd: BfdSessionHandle,
|
||||||
interval: BfdInterval,
|
interval: BfdInterval,
|
||||||
|
detect_mult: u8,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
rx,
|
rx,
|
||||||
bfd,
|
bfd,
|
||||||
cur_interval: interval,
|
cur_interval: interval,
|
||||||
|
detect_mult,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn next_delay(&self) -> time::Duration {
|
||||||
|
jittered_delay(self.cur_interval.into(), self.detect_mult)
|
||||||
|
}
|
||||||
async fn run(&mut self) {
|
async fn run(&mut self) {
|
||||||
let base_interval = self.cur_interval * 3 / 4;
|
|
||||||
let mut clock = time::interval(base_interval.into());
|
|
||||||
let mut running = true;
|
let mut running = true;
|
||||||
|
let mut next_tx = time::Instant::now() + self.next_delay();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = clock.tick(), if running => {
|
_ = time::sleep_until(next_tx), if running => {
|
||||||
let jitter = time::Duration::from_micros(
|
|
||||||
rand::thread_rng()
|
|
||||||
.gen_range(0..clock.period().as_micros() / 3)
|
|
||||||
.try_into()
|
|
||||||
.unwrap(),
|
|
||||||
);
|
|
||||||
time::sleep(jitter).await;
|
|
||||||
// debug!("tick! sent periodic control packet after {}ms", (base_interval + jitter).as_millis());
|
|
||||||
self.bfd.transmit_control_packet(false).await.unwrap();
|
self.bfd.transmit_control_packet(false).await.unwrap();
|
||||||
|
next_tx = time::Instant::now() + self.next_delay();
|
||||||
},
|
},
|
||||||
Some(cmd) = self.rx.recv() => {
|
Some(cmd) = self.rx.recv() => {
|
||||||
match cmd {
|
match cmd {
|
||||||
@@ -392,14 +406,15 @@ impl BfdPeriodicSender {
|
|||||||
debug!("Stopping periodic packets");
|
debug!("Stopping periodic packets");
|
||||||
running= false}
|
running= false}
|
||||||
,
|
,
|
||||||
PeriodicControlCommand::Start => { debug!("Starting periodic packets"); running = true },
|
PeriodicControlCommand::Start => {
|
||||||
|
debug!("Starting periodic packets");
|
||||||
|
running = true;
|
||||||
|
next_tx = time::Instant::now() + self.next_delay();
|
||||||
|
},
|
||||||
PeriodicControlCommand::SetMinInterval(i) => {
|
PeriodicControlCommand::SetMinInterval(i) => {
|
||||||
let base_interval: Duration = (i * 3 / 4).into();
|
self.cur_interval = i;
|
||||||
debug!("Updating base interval to {}ms (jittering {} to {}ms)", base_interval.as_millis(), base_interval.as_millis(), base_interval.as_millis() + base_interval.as_millis() / 3);
|
debug!("Updating transmit interval to {}ms", Duration::from(i).as_millis());
|
||||||
clock = time::interval_at(
|
next_tx = time::Instant::now() + self.next_delay();
|
||||||
time::Instant::now() + base_interval,
|
|
||||||
base_interval,
|
|
||||||
);
|
|
||||||
},
|
},
|
||||||
PeriodicControlCommand::SendPollResponse => {
|
PeriodicControlCommand::SendPollResponse => {
|
||||||
debug!("Sending poll response");
|
debug!("Sending poll response");
|
||||||
@@ -418,14 +433,17 @@ impl BfdSession {
|
|||||||
handle: BfdSessionHandle,
|
handle: BfdSessionHandle,
|
||||||
control_sock: UdpSocket,
|
control_sock: UdpSocket,
|
||||||
local_addr: IpAddr,
|
local_addr: IpAddr,
|
||||||
remote_addr: IpAddr,
|
peer: ResolvedPeer,
|
||||||
local_discr: BfdDiscriminator,
|
local_discr: BfdDiscriminator,
|
||||||
event_dispatcher: EventDispatcherHandle,
|
event_dispatcher: EventDispatcherHandle,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let mut rng = rand::thread_rng();
|
let mut rng = rand::thread_rng();
|
||||||
let periodic =
|
let periodic = BfdPeriodicSenderHandle::new(
|
||||||
BfdPeriodicSenderHandle::new(handle.clone(), time::Duration::from_secs(1).into());
|
handle.clone(),
|
||||||
let configured_desired_min_tx = BfdInterval::from_millis(300);
|
time::Duration::from_secs(1).into(),
|
||||||
|
peer.detect_mult,
|
||||||
|
);
|
||||||
|
let configured_desired_min_tx = peer.desired_min_tx;
|
||||||
let slow_desired_min_tx =
|
let slow_desired_min_tx =
|
||||||
std::cmp::max(configured_desired_min_tx, BfdInterval::from_secs(1));
|
std::cmp::max(configured_desired_min_tx, BfdInterval::from_secs(1));
|
||||||
|
|
||||||
@@ -446,18 +464,18 @@ impl BfdSession {
|
|||||||
state: BfdSessionState {
|
state: BfdSessionState {
|
||||||
control_sock: Arc::new(control_sock),
|
control_sock: Arc::new(control_sock),
|
||||||
local_ip: local_addr,
|
local_ip: local_addr,
|
||||||
peer_addr: remote_addr,
|
peer_addr: peer.address,
|
||||||
session_state: Atomic::new(BfdState::default()),
|
session_state: Atomic::new(BfdState::default()),
|
||||||
remote_session_state: Atomic::new(BfdState::default()),
|
remote_session_state: Atomic::new(BfdState::default()),
|
||||||
local_discr,
|
local_discr,
|
||||||
remote_discr: Atomic::new(BfdDiscriminator(0)),
|
remote_discr: Atomic::new(BfdDiscriminator(0)),
|
||||||
local_diag: Atomic::new(BfdDiagnostic::None),
|
local_diag: Atomic::new(BfdDiagnostic::None),
|
||||||
desired_min_tx_interval: Atomic::new(slow_desired_min_tx),
|
desired_min_tx_interval: Atomic::new(slow_desired_min_tx),
|
||||||
required_min_rx_interval: Atomic::new(BfdInterval::from_millis(300)),
|
required_min_rx_interval: Atomic::new(peer.required_min_rx),
|
||||||
remote_min_rx_interval: Atomic::new(BfdInterval::from_millis(300)),
|
remote_min_rx_interval: Atomic::new(BfdInterval::from_millis(300)),
|
||||||
demand_mode: Atomic::new(false),
|
demand_mode: Atomic::new(false),
|
||||||
remote_demand_mode: Atomic::new(false),
|
remote_demand_mode: Atomic::new(false),
|
||||||
detect_mult: Atomic::new(3),
|
detect_mult: Atomic::new(peer.detect_mult),
|
||||||
auth_type: Atomic::new(BfdAuthType::None),
|
auth_type: Atomic::new(BfdAuthType::None),
|
||||||
rcv_auth_seq: Atomic::new(0),
|
rcv_auth_seq: Atomic::new(0),
|
||||||
xmit_auth_seq: Atomic::new(rng.gen()),
|
xmit_auth_seq: Atomic::new(rng.gen()),
|
||||||
@@ -528,6 +546,10 @@ impl BfdSession {
|
|||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
self.state.set_session_state(new_state);
|
self.state.set_session_state(new_state);
|
||||||
|
// https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.7
|
||||||
|
// A BFD Control packet SHOULD be transmitted during the interval between periodic Control packet
|
||||||
|
// transmissions when the contents of that packet would differ from that in the previously transmitted packet
|
||||||
|
self.transmit_control_packet(false).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run(&mut self) {
|
async fn run(&mut self) {
|
||||||
@@ -975,9 +997,11 @@ impl EventDispatcherHandle {
|
|||||||
|
|
||||||
struct Bfdd {
|
struct Bfdd {
|
||||||
local: SocketAddr,
|
local: SocketAddr,
|
||||||
peers: Vec<SocketAddr>,
|
peers: Vec<ResolvedPeer>,
|
||||||
sessions_by_ip: HashMap<(IpAddr, IpAddr), BfdDiscriminator>,
|
sessions_by_ip: HashMap<(IpAddr, IpAddr), BfdDiscriminator>,
|
||||||
sessions_by_discr: HashMap<BfdDiscriminator, BfdSessionHandle>,
|
sessions_by_discr: HashMap<BfdDiscriminator, BfdSessionHandle>,
|
||||||
|
// Sources we have already warned about unmatched packets from; cleared per source once a packet matches again
|
||||||
|
unmatched_sources: std::sync::Mutex<HashSet<IpAddr>>,
|
||||||
|
|
||||||
control_socket: Arc<UdpSocket>,
|
control_socket: Arc<UdpSocket>,
|
||||||
|
|
||||||
@@ -985,24 +1009,18 @@ struct Bfdd {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Bfdd {
|
impl Bfdd {
|
||||||
async fn new(args: Args) -> Result<Self, Box<dyn Error>> {
|
async fn new(config: ResolvedConfig) -> Result<Self, Box<dyn Error>> {
|
||||||
let local = SocketAddr::new(args.bind, CONTROL_PORT);
|
let local = match config.bind.as_slice() {
|
||||||
if let Some(peer) = args
|
[addr] => SocketAddr::new(*addr, CONTROL_PORT),
|
||||||
.peers
|
addrs => {
|
||||||
.iter()
|
|
||||||
.find(|p| p.is_ipv4() != args.bind.is_ipv4())
|
|
||||||
{
|
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"peer {peer} is not the same address family as bind address {}",
|
"{} bind addresses configured, but only one is currently supported",
|
||||||
args.bind
|
addrs.len()
|
||||||
)
|
)
|
||||||
.into());
|
.into())
|
||||||
}
|
}
|
||||||
let peers = args
|
};
|
||||||
.peers
|
let peers = config.peers;
|
||||||
.into_iter()
|
|
||||||
.map(|ip| SocketAddr::new(ip, CONTROL_PORT))
|
|
||||||
.collect();
|
|
||||||
let sessions_by_ip = HashMap::new();
|
let sessions_by_ip = HashMap::new();
|
||||||
let sessions_by_discr = HashMap::new();
|
let sessions_by_discr = HashMap::new();
|
||||||
|
|
||||||
@@ -1016,7 +1034,7 @@ impl Bfdd {
|
|||||||
|
|
||||||
let event_dispatcher = EventDispatcherHandle::new().await;
|
let event_dispatcher = EventDispatcherHandle::new().await;
|
||||||
event_dispatcher
|
event_dispatcher
|
||||||
.add_sink(Box::new(ScriptHookSink::new()))
|
.add_sink(Box::new(ScriptHookSink::with_script_dir(config.hooks_dir)))
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@@ -1024,6 +1042,7 @@ impl Bfdd {
|
|||||||
peers,
|
peers,
|
||||||
sessions_by_ip,
|
sessions_by_ip,
|
||||||
sessions_by_discr,
|
sessions_by_discr,
|
||||||
|
unmatched_sources: std::sync::Mutex::new(HashSet::new()),
|
||||||
control_socket,
|
control_socket,
|
||||||
event_dispatcher,
|
event_dispatcher,
|
||||||
})
|
})
|
||||||
@@ -1037,14 +1056,14 @@ impl Bfdd {
|
|||||||
}
|
}
|
||||||
let session = BfdSessionHandle::new(
|
let session = BfdSessionHandle::new(
|
||||||
self.local.ip(),
|
self.local.ip(),
|
||||||
peer.ip(),
|
*peer,
|
||||||
local_discr,
|
local_discr,
|
||||||
self.event_dispatcher.clone(),
|
self.event_dispatcher.clone(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
self.sessions_by_ip
|
self.sessions_by_ip
|
||||||
.insert((self.local.ip(), peer.ip()), local_discr);
|
.insert((self.local.ip(), peer.address), local_discr);
|
||||||
self.sessions_by_discr.insert(local_discr, session);
|
self.sessions_by_discr.insert(local_discr, session);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -1075,13 +1094,38 @@ impl Bfdd {
|
|||||||
);
|
);
|
||||||
discr
|
discr
|
||||||
} else {
|
} else {
|
||||||
warn!("Unable to match packet to session with {}", addr.ip());
|
self.log_unmatched(
|
||||||
|
addr.ip(),
|
||||||
|
log::Level::Warn,
|
||||||
|
"no session configured for this address",
|
||||||
|
);
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
&packet.your_disc
|
&packet.your_disc
|
||||||
};
|
};
|
||||||
self.sessions_by_discr.get(our_disc)
|
let session = self.sessions_by_discr.get(our_disc);
|
||||||
|
if session.is_some() {
|
||||||
|
self.unmatched_sources.lock().unwrap().remove(&addr.ip());
|
||||||
|
} else {
|
||||||
|
self.log_unmatched(
|
||||||
|
addr.ip(),
|
||||||
|
log::Level::Info,
|
||||||
|
&format!("unknown Your Discriminator {our_disc}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
session
|
||||||
|
}
|
||||||
|
/// Log the first unmatched packet from a source at `level`, then at debug level until one matches again.
|
||||||
|
fn log_unmatched(&self, source: IpAddr, level: log::Level, reason: &str) {
|
||||||
|
if self.unmatched_sources.lock().unwrap().insert(source) {
|
||||||
|
log::log!(
|
||||||
|
level,
|
||||||
|
"Unable to match packet from {source}: {reason} (repeats are logged at debug level)"
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
debug!("Unable to match packet from {source}: {reason}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
async fn rx_packet(&self, addr: SocketAddr, packet: BfdPacket) {
|
async fn rx_packet(&self, addr: SocketAddr, packet: BfdPacket) {
|
||||||
if let Some(session) = self.session_for_packet(&addr, &packet) {
|
if let Some(session) = self.session_for_packet(&addr, &packet) {
|
||||||
@@ -1090,25 +1134,37 @@ impl Bfdd {
|
|||||||
.send(SessionControlCommand::RxPacket(packet))
|
.send(SessionControlCommand::RxPacket(packet))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
} else {
|
|
||||||
warn!("Unable to match packet to session with");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async fn session_report(&self) -> String {
|
||||||
|
future::join_all(
|
||||||
|
self.sessions_by_discr
|
||||||
|
.values()
|
||||||
|
.map(|session| async { session.get_stats().await.unwrap().to_string() }),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.join("\n\t")
|
||||||
|
}
|
||||||
|
async fn handle_datagram(&self, data: &[u8], addr: SocketAddr) {
|
||||||
|
let Ok((_leftover, packet)) = BfdPacket::parse(data) else {
|
||||||
|
warn!("Failed to parse packet");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
debug!("rx packet ({:?}): {:?}", addr.ip(), packet);
|
||||||
|
// If the Length field is greater than the payload of the encapsulating protocol, the packet MUST be
|
||||||
|
// discarded.
|
||||||
|
if packet.flags.length() as usize > data.len() {
|
||||||
|
warn!("discarding packet with length > payload");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.rx_packet(addr, packet).await
|
||||||
|
}
|
||||||
async fn run(mut self) -> io::Result<()> {
|
async fn run(mut self) -> io::Result<()> {
|
||||||
info!("rust-bfd starting up");
|
info!("rust-bfd starting up");
|
||||||
self.start_peers().await?;
|
self.start_peers().await?;
|
||||||
info!(
|
info!("configured sessions: {}", self.session_report().await);
|
||||||
"configured sessions: {}",
|
|
||||||
future::join_all(
|
|
||||||
self.sessions_by_discr
|
|
||||||
.values()
|
|
||||||
.map(|session| async { session.get_stats().await.unwrap().to_string() })
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.join("\n\t")
|
|
||||||
);
|
|
||||||
|
|
||||||
let rx_task = task::spawn(async move {
|
let mut sigusr1 = signal(SignalKind::user_defined1())?;
|
||||||
let mut buf = [0; 1024];
|
let mut buf = [0; 1024];
|
||||||
loop {
|
loop {
|
||||||
// TODO: All received BFD Control packets that are demultiplexed to the session MUST be discarded if
|
// TODO: All received BFD Control packets that are demultiplexed to the session MUST be discarded if
|
||||||
@@ -1116,44 +1172,30 @@ impl Bfdd {
|
|||||||
//
|
//
|
||||||
// TODO: Maybe it is okay to receive in the session-specific socket instead of this global one? But
|
// TODO: Maybe it is okay to receive in the session-specific socket instead of this global one? But
|
||||||
// the RFC mentions that we must demux based on discriminator only.
|
// the RFC mentions that we must demux based on discriminator only.
|
||||||
match self.control_socket.recv_from(&mut buf).await {
|
tokio::select! {
|
||||||
|
result = self.control_socket.recv_from(&mut buf) => match result {
|
||||||
Ok((len, addr)) => {
|
Ok((len, addr)) => {
|
||||||
if let Ok((_leftover, packet)) = BfdPacket::parse(&buf[..len]) {
|
self.handle_datagram(&buf[..len], addr).await;
|
||||||
debug!("rx packet ({:?}): {:?}", addr.ip(), packet);
|
if log_enabled!(log::Level::Debug) {
|
||||||
// If the Length field is greater than the payload of the encapsulating protocol, the packet MUST be
|
debug!("configured sessions: {}", self.session_report().await);
|
||||||
// discarded.
|
|
||||||
if packet.flags.length() as usize > len {
|
|
||||||
warn!("discarding packet with length > payload");
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
self.rx_packet(addr, packet).await
|
|
||||||
} else {
|
|
||||||
warn!("Failed to parse packet");
|
|
||||||
}
|
}
|
||||||
|
Err(e) => warn!("Error receiving from socket {e:?}"),
|
||||||
|
},
|
||||||
|
_ = sigusr1.recv() => {
|
||||||
|
info!("SIGUSR1 received");
|
||||||
|
info!("configured sessions: {}", self.session_report().await);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
debug!(
|
fn load_config(args: Args) -> Result<ResolvedConfig, ConfigError> {
|
||||||
"configured sessions: {}",
|
let mut config = Config::load(args.config.as_deref())?;
|
||||||
future::join_all(self.sessions_by_discr.values().map(
|
config.apply_env(|name| std::env::var(name).ok())?;
|
||||||
|session| async { session.get_stats().await.unwrap().to_string() }
|
config.apply_cli(args.bind, args.peers);
|
||||||
))
|
config.resolve()
|
||||||
.await
|
|
||||||
.join("\n\t")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Error receiving from socket {e:?}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
tokio::join!(rx_task)
|
|
||||||
.0
|
|
||||||
.expect("Unable to join on the receive thread");
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
@@ -1164,8 +1206,109 @@ async fn main() -> io::Result<()> {
|
|||||||
.format_timestamp_micros()
|
.format_timestamp_micros()
|
||||||
.init();
|
.init();
|
||||||
|
|
||||||
match Bfdd::new(args).await {
|
let config = load_config(args).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||||
|
if config.peers.is_empty() {
|
||||||
|
warn!("No peers configured");
|
||||||
|
}
|
||||||
|
|
||||||
|
match Bfdd::new(config).await {
|
||||||
Ok(bfdd) => bfdd.run().await,
|
Ok(bfdd) => bfdd.run().await,
|
||||||
Err(e) => Err(std::io::Error::other(e.to_string())),
|
Err(e) => Err(std::io::Error::other(e.to_string())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn jitter_is_uniform_over_rfc_range() {
|
||||||
|
// RFC 5880 6.8.7: each interval is reduced by a random 0-25% (0-10% when DetectMult is 1), so delays are
|
||||||
|
// spread over [floor, interval] with a mean at the midpoint, not clustered at either end.
|
||||||
|
let interval = time::Duration::from_millis(300);
|
||||||
|
const SAMPLES: u32 = 20_000;
|
||||||
|
for (mult, floor_ms, mean_ms) in [(3u8, 225.0, 262.5), (1, 270.0, 285.0)] {
|
||||||
|
let delays: Vec<f64> = (0..SAMPLES)
|
||||||
|
.map(|_| jittered_delay(interval, mult).as_secs_f64() * 1000.0)
|
||||||
|
.collect();
|
||||||
|
let mean = delays.iter().sum::<f64>() / f64::from(SAMPLES);
|
||||||
|
let min = delays.iter().copied().fold(f64::MAX, f64::min);
|
||||||
|
let max = delays.iter().copied().fold(f64::MIN, f64::max);
|
||||||
|
let width = 300.0 - floor_ms;
|
||||||
|
assert!(
|
||||||
|
(mean - mean_ms).abs() < 1.0,
|
||||||
|
"mult {mult}: mean {mean}ms, expected {mean_ms}ms"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
min < floor_ms + width * 0.02,
|
||||||
|
"mult {mult}: never approached the floor (min {min}ms)"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
max > 300.0 - width * 0.02,
|
||||||
|
"mult {mult}: never approached the interval (max {max}ms)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn periodic_sender_gaps_respect_rfc_floor() {
|
||||||
|
// Gaps are measured between actual sends, so jitter must not be layered onto a shorter fixed clock.
|
||||||
|
// Only the lower bound is asserted: scheduler overshoot can legitimately stretch a gap.
|
||||||
|
let interval = time::Duration::from_millis(40);
|
||||||
|
let floor = interval * 3 / 4;
|
||||||
|
let (tx, mut rx) = mpsc::channel(32);
|
||||||
|
let sender = BfdPeriodicSenderHandle::new(BfdSessionHandle { tx }, interval.into(), 3);
|
||||||
|
|
||||||
|
let mut sends = Vec::new();
|
||||||
|
while sends.len() < 40 {
|
||||||
|
match rx.recv().await {
|
||||||
|
Some(SessionControlCommand::TxControlPacket {
|
||||||
|
poll_response: false,
|
||||||
|
}) => sends.push(time::Instant::now()),
|
||||||
|
other => panic!("unexpected command (channel open: {})", other.is_some()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sender.tx.send(PeriodicControlCommand::Quit).await.unwrap();
|
||||||
|
|
||||||
|
for pair in sends.windows(2) {
|
||||||
|
let gap = pair[1] - pair[0];
|
||||||
|
assert!(
|
||||||
|
gap + time::Duration::from_millis(2) >= floor,
|
||||||
|
"gap {gap:?} below {floor:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn jitter_within_rfc_bounds() {
|
||||||
|
let interval = time::Duration::from_millis(300);
|
||||||
|
for (mult, floor_ms) in [(3, 225), (1, 270)] {
|
||||||
|
for _ in 0..1000 {
|
||||||
|
let d = jittered_delay(interval, mult);
|
||||||
|
assert!(
|
||||||
|
d >= time::Duration::from_millis(floor_ms),
|
||||||
|
"{d:?} below floor for mult {mult}"
|
||||||
|
);
|
||||||
|
assert!(d <= interval, "{d:?} above interval");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeated_bind_and_peer_flags() {
|
||||||
|
let args = Args::try_parse_from([
|
||||||
|
"rust-bfdd",
|
||||||
|
"-b",
|
||||||
|
"192.0.2.1",
|
||||||
|
"--bind",
|
||||||
|
"2001:db8::1",
|
||||||
|
"-p",
|
||||||
|
"192.0.2.2",
|
||||||
|
"--peer",
|
||||||
|
"2001:db8::2",
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(args.bind.len(), 2);
|
||||||
|
assert_eq!(args.peers.len(), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
+620
@@ -0,0 +1,620 @@
|
|||||||
|
//! Daemon configuration: YAML model, layered loading and validation.
|
||||||
|
//!
|
||||||
|
//! 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.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::HashSet,
|
||||||
|
error::Error,
|
||||||
|
fmt, fs, io,
|
||||||
|
net::IpAddr,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use serde::{de, Deserialize, Deserializer, Serialize};
|
||||||
|
|
||||||
|
use crate::bfd::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";
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
Io {
|
||||||
|
path: PathBuf,
|
||||||
|
source: io::Error,
|
||||||
|
},
|
||||||
|
Parse {
|
||||||
|
path: PathBuf,
|
||||||
|
source: serde_yaml_ng::Error,
|
||||||
|
},
|
||||||
|
Env {
|
||||||
|
var: &'static str,
|
||||||
|
message: String,
|
||||||
|
},
|
||||||
|
Invalid(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ConfigError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Io { path, source } => {
|
||||||
|
write!(f, "cannot read config file `{}`: {source}", path.display())
|
||||||
|
}
|
||||||
|
Self::Parse { path, source } => {
|
||||||
|
write!(f, "invalid config file `{}`: {source}", path.display())
|
||||||
|
}
|
||||||
|
Self::Env { var, message } => {
|
||||||
|
write!(f, "invalid environment variable {var}: {message}")
|
||||||
|
}
|
||||||
|
Self::Invalid(message) => write!(f, "invalid configuration: {message}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for ConfigError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
Self::Io { source, .. } => Some(source),
|
||||||
|
Self::Parse { source, .. } => Some(source),
|
||||||
|
Self::Env { .. } | Self::Invalid(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Timer and multiplier settings inherited by every peer that does not override them.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(default, deny_unknown_fields)]
|
||||||
|
pub struct Defaults {
|
||||||
|
#[serde(with = "humantime_serde")]
|
||||||
|
pub desired_min_tx: Duration,
|
||||||
|
#[serde(with = "humantime_serde")]
|
||||||
|
pub required_min_rx: Duration,
|
||||||
|
pub detect_mult: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Defaults {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
desired_min_tx: Duration::from_millis(300),
|
||||||
|
required_min_rx: Duration::from_millis(300),
|
||||||
|
detect_mult: 3,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, 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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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, Serialize, 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,
|
||||||
|
pub peers: Vec<PeerConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Config {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
bind: Vec::new(),
|
||||||
|
hooks_dir: PathBuf::from(DEFAULT_HOOKS_DIR),
|
||||||
|
defaults: Defaults::default(),
|
||||||
|
peers: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate and apply defaults to each peer.
|
||||||
|
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()
|
||||||
|
.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())
|
||||||
|
{
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"peer {} has no bind address of the same address family",
|
||||||
|
peer.address
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let what = |field: &str| format!("peer {} {field}", peer.address);
|
||||||
|
let detect_mult = peer.detect_mult.unwrap_or(self.defaults.detect_mult);
|
||||||
|
if detect_mult == 0 {
|
||||||
|
return Err(invalid(format!(
|
||||||
|
"{} must be at least 1",
|
||||||
|
what("detect_mult")
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(ResolvedPeer {
|
||||||
|
address: peer.address,
|
||||||
|
desired_min_tx: to_interval(
|
||||||
|
peer.desired_min_tx.unwrap_or(self.defaults.desired_min_tx),
|
||||||
|
&what("desired_min_tx"),
|
||||||
|
)?,
|
||||||
|
required_min_rx: to_interval(
|
||||||
|
peer.required_min_rx
|
||||||
|
.unwrap_or(self.defaults.required_min_rx),
|
||||||
|
&what("required_min_rx"),
|
||||||
|
)?,
|
||||||
|
detect_mult,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
|
||||||
|
// Validate the defaults even when no peer uses them, so that a bad value is not latent.
|
||||||
|
let d = &self.defaults;
|
||||||
|
to_interval(d.desired_min_tx, "defaults.desired_min_tx")?;
|
||||||
|
to_interval(d.required_min_rx, "defaults.required_min_rx")?;
|
||||||
|
if d.detect_mult == 0 {
|
||||||
|
return Err(invalid("defaults.detect_mult must be at least 1".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ResolvedConfig {
|
||||||
|
bind: self.bind.clone(),
|
||||||
|
hooks_dir: self.hooks_dir.clone(),
|
||||||
|
peers,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Zero is rejected for both intervals: a zero Required Min RX Interval is legal in RFC 5880 (it asks the peer to
|
||||||
|
/// stop sending periodic packets) but is not supported here.
|
||||||
|
fn to_interval(value: Duration, what: &str) -> Result<BfdInterval, ConfigError> {
|
||||||
|
let micros = value.as_micros();
|
||||||
|
if micros == 0 {
|
||||||
|
return Err(ConfigError::Invalid(format!(
|
||||||
|
"{what} must be greater than zero"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
u32::try_from(micros)
|
||||||
|
.map(BfdInterval::from_micros)
|
||||||
|
.map_err(|_| {
|
||||||
|
ConfigError::Invalid(format!(
|
||||||
|
"{what} of {} is too large (maximum is {} microseconds)",
|
||||||
|
humantime::format_duration(value),
|
||||||
|
u32::MAX
|
||||||
|
))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ResolvedConfig {
|
||||||
|
pub bind: Vec<IpAddr>,
|
||||||
|
pub hooks_dir: PathBuf,
|
||||||
|
pub peers: Vec<ResolvedPeer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct ResolvedPeer {
|
||||||
|
pub address: IpAddr,
|
||||||
|
pub desired_min_tx: BfdInterval,
|
||||||
|
pub required_min_rx: BfdInterval,
|
||||||
|
pub detect_mult: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
const FULL: &str = "
|
||||||
|
bind: 192.0.2.1
|
||||||
|
hooks_dir: /tmp/hooks
|
||||||
|
defaults:
|
||||||
|
desired_min_tx: 500ms
|
||||||
|
required_min_rx: 250ms
|
||||||
|
detect_mult: 5
|
||||||
|
peers:
|
||||||
|
- address: 192.0.2.2
|
||||||
|
- address: 192.0.2.3
|
||||||
|
desired_min_tx: 1s
|
||||||
|
detect_mult: 4
|
||||||
|
";
|
||||||
|
|
||||||
|
#[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.hooks_dir, PathBuf::from("/tmp/hooks"));
|
||||||
|
assert_eq!(config.defaults.desired_min_tx, Duration::from_millis(500));
|
||||||
|
assert_eq!(config.peers.len(), 2);
|
||||||
|
assert_eq!(config.peers[1].desired_min_tx, Some(Duration::from_secs(1)));
|
||||||
|
assert_eq!(config.peers[0].detect_mult, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn partial_defaults_keep_remaining_builtin_values() {
|
||||||
|
let config = Config::from_yaml("defaults:\n detect_mult: 7\n").unwrap();
|
||||||
|
assert_eq!(config.defaults.detect_mult, 7);
|
||||||
|
assert_eq!(config.defaults.desired_min_tx, Duration::from_millis(300));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peers_inherit_defaults_and_override() {
|
||||||
|
let resolved = Config::from_yaml(FULL).unwrap().resolve().unwrap();
|
||||||
|
let (a, b) = (resolved.peers[0], resolved.peers[1]);
|
||||||
|
assert_eq!(a.desired_min_tx, BfdInterval::from_millis(500));
|
||||||
|
assert_eq!(a.required_min_rx, BfdInterval::from_millis(250));
|
||||||
|
assert_eq!(a.detect_mult, 5);
|
||||||
|
assert_eq!(b.desired_min_tx, BfdInterval::from_secs(1));
|
||||||
|
assert_eq!(b.required_min_rx, BfdInterval::from_millis(250));
|
||||||
|
assert_eq!(b.detect_mult, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zero_peers_is_valid() {
|
||||||
|
let config = Config::from_yaml("bind: 192.0.2.1").unwrap();
|
||||||
|
assert!(config.resolve().unwrap().peers.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_requires_explicit_path_to_exist() {
|
||||||
|
let err = Config::load(Some(Path::new("/nonexistent/rust-bfd.yaml"))).unwrap_err();
|
||||||
|
assert!(matches!(err, ConfigError::Io { .. }));
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-1
@@ -60,9 +60,12 @@ impl Default for ScriptHookSink {
|
|||||||
|
|
||||||
impl ScriptHookSink {
|
impl ScriptHookSink {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
|
Self::with_script_dir("/etc/rust-bfd/hooks.d/")
|
||||||
|
}
|
||||||
|
pub fn with_script_dir(script_dir: impl Into<PathBuf>) -> Self {
|
||||||
let (tx_channel, rx_channel) = mpsc::channel(16);
|
let (tx_channel, rx_channel) = mpsc::channel(16);
|
||||||
Self {
|
Self {
|
||||||
script_dir: "/etc/rust-bfd/hooks.d/".into(),
|
script_dir: script_dir.into(),
|
||||||
tx_channel,
|
tx_channel,
|
||||||
rx_channel,
|
rx_channel,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod bfd;
|
pub mod bfd;
|
||||||
|
pub mod config;
|
||||||
pub mod control;
|
pub mod control;
|
||||||
pub mod events;
|
pub mod events;
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user