Compare commits

...
7 Commits
Author SHA1 Message Date
ktims 0284ee17b1 clippies 2026-10-22 15:47:16 -07:00
ktims dcbf25ebe0 Add Dockerfile
Multi-stage build producing a slim image with rust-bfdd as the entrypoint. Dependencies are built against stub sources in their own layer so source-only changes do not rebuild them.
2026-10-22 15:44:39 -07:00
ktims 146f8d4c32 Log session table at debug level
The per-packet session dump is too noisy at info.
2026-10-22 15:41:08 -07:00
ktims 4773c9e4f7 Fix protocol conformance issues found in interop testing
Implement the Poll Sequence (initiate on reaching Up when the configured interval is lower than the slow-start one; respond to Poll with Final; terminate on Final) and apply DesiredMinTxInterval changes per RFC 5880 section 6.8.3, keeping the slow rate until the peer has acknowledged. Never set the Demand bit unless demand mode is active, clear the C bit (this implementation shares fate with the control plane), discard packets whose Length exceeds the received payload, and log effective timer changes.
2026-10-22 15:41:08 -07:00
ktims 0bd4f8766a Bind session sockets without panicking
Select a random unused source port in the RFC 5881 range (retrying on EADDRINUSE) instead of unwrapping a pure-random bind. Propagate bind errors out of session start-up, store the local IP on the session instead of unwrapping local_addr(), and log (rather than panic on) receive errors in the rx loop.
2026-10-22 15:41:08 -07:00
ktims c7a6ed16e4 Add command line arguments
Replace the hard-coded addresses with clap arguments: --bind <IP> and one or more --peer <IP>. Peers must match the address family of the bind address. Also updates Cargo.lock.
2026-10-22 15:41:08 -07:00
ktims 0bb1f437ae Declare nix dependency
lib.rs and events.rs already use nix; it was missing from Cargo.toml so the crate did not build.
2026-10-22 15:41:08 -07:00
7 changed files with 645 additions and 482 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
target
.git
Dockerfile
.dockerignore
Generated
+385 -347
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -7,10 +7,12 @@ 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"] }
env_logger = "0.11.1" env_logger = "0.11.1"
futures = "0.3.30" futures = "0.3.30"
itertools = "0.12.1" itertools = "0.12.1"
log = "0.4.20" log = "0.4.20"
nix = { version = "0.31.3", features = ["fs", "socket"] }
nom = "7.1.3" nom = "7.1.3"
nom-derive = "0.10.1" nom-derive = "0.10.1"
proc-bitfield = "0.3.1" proc-bitfield = "0.3.1"
+23
View File
@@ -0,0 +1,23 @@
FROM rust:1.94-bookworm AS builder
WORKDIR /build
# Build dependencies against stub sources so this layer is only invalidated by Cargo.toml/Cargo.lock changes.
COPY Cargo.toml Cargo.lock ./
RUN mkdir -p src/bin \
&& touch src/lib.rs \
&& echo 'fn main() {}' > src/bin/rust-bfdd.rs \
&& cargo build --release --locked --bin rust-bfdd \
&& rm -rf src
COPY src ./src
# COPY keeps the host mtimes, which may predate the stub build; force cargo to rebuild the crate itself.
RUN touch src/lib.rs src/bin/rust-bfdd.rs \
&& cargo build --release --locked --bin rust-bfdd
FROM debian:bookworm-slim
RUN useradd --system --no-create-home --shell /usr/sbin/nologin bfd \
&& mkdir -p /etc/rust-bfd/hooks.d
COPY --from=builder /build/target/release/rust-bfdd /usr/local/bin/rust-bfdd
USER bfd
EXPOSE 3784/udp
ENTRYPOINT ["/usr/local/bin/rust-bfdd"]
+14 -8
View File
@@ -1,4 +1,10 @@
use std::{ffi::{OsStr, OsString}, fmt::{self, Display}, io::Cursor, ops::{Div, Mul}, time}; use std::{
ffi::OsStr,
fmt::{self, Display},
io::Cursor,
ops::{Div, Mul},
time,
};
use bytemuck::NoUninit; use bytemuck::NoUninit;
use byteorder::{BigEndian, WriteBytesExt}; use byteorder::{BigEndian, WriteBytesExt};
@@ -56,13 +62,13 @@ impl Display for BfdState {
} }
} }
impl Into<&OsStr> for BfdState { impl From<BfdState> for &OsStr {
fn into(self) -> &'static OsStr { fn from(val: BfdState) -> Self {
match self { match val {
Self::AdminDown => OsStr::new("AdminDown"), BfdState::AdminDown => OsStr::new("AdminDown"),
Self::Init => OsStr::new("Init"), BfdState::Init => OsStr::new("Init"),
Self::Down => OsStr::new("Down"), BfdState::Down => OsStr::new("Down"),
Self::Up => OsStr::new("Up"), BfdState::Up => OsStr::new("Up"),
} }
} }
} }
+207 -122
View File
@@ -1,8 +1,8 @@
use clap::Parser;
use futures::future; use futures::future;
use rust_bfd::events::{EventMessageSink, ScriptHookSink, StateChangeEvent}; use rust_bfd::events::{EventMessageSink, ScriptHookSink, StateChangeEvent};
use rust_bfd::{set_ttl_or_hop_limit, BfdSessionStats};
use rust_bfd::{bfd::*, events::EventMessage}; use rust_bfd::{bfd::*, events::EventMessage};
use std::net::Ipv6Addr; use rust_bfd::{set_ttl_or_hop_limit, BfdSessionStats};
use std::{ use std::{
collections::HashMap, collections::HashMap,
error::Error, error::Error,
@@ -10,18 +10,16 @@ use std::{
io::ErrorKind, io::ErrorKind,
mem::swap, mem::swap,
net::{IpAddr, SocketAddr}, net::{IpAddr, SocketAddr},
str::FromStr,
sync::{atomic::Ordering, Arc}, sync::{atomic::Ordering, Arc},
time::{Duration, Instant}, time::{Duration, Instant},
}; };
// Necessary until a hop_limit method is added to UdpSocket // Necessary until a hop_limit method is added to UdpSocket
use nix::sys::socket::{setsockopt, sockopt};
use tokio::sync::{oneshot, Mutex}; use tokio::sync::{oneshot, Mutex};
use env_logger::Env; use env_logger::Env;
use log::{debug, error, info, warn}; use log::{debug, info, warn};
use nom_derive::Parse; use nom_derive::Parse;
use rand::prelude::*; use rand::prelude::*;
@@ -36,6 +34,43 @@ use atomic::Atomic;
const CONTROL_PORT: u16 = 3784; const CONTROL_PORT: u16 = 3784;
const ECHO_PORT: u16 = 3785; const ECHO_PORT: u16 = 3785;
#[derive(Parser, Debug)]
#[command(version, about = "BFD (RFC 5880) daemon")]
struct Args {
/// Local IP address to bind to and use as the source of BFD control packets
#[arg(short, long, value_name = "IP")]
bind: IpAddr,
/// Peer IP address to establish a session with (repeatable; must match the bind address family)
#[arg(short, long = "peer", value_name = "IP", required = true)]
peers: Vec<IpAddr>,
}
// RFC 5881 section 4: the source port MUST be in the range 49152 to 65535.
const SOURCE_PORT_RANGE: std::ops::RangeInclusive<u16> = 49152..=65535;
const SOURCE_PORT_BIND_ATTEMPTS: usize = 32;
/// Bind a UDP socket on a random unused port in the RFC 5881 source port range, with TTL/hop limit 255.
async fn bind_control_socket(local_addr: IpAddr) -> io::Result<UdpSocket> {
for _ in 0..SOURCE_PORT_BIND_ATTEMPTS {
let port = rand::thread_rng().gen_range(SOURCE_PORT_RANGE);
match UdpSocket::bind(SocketAddr::new(local_addr, port)).await {
Ok(sock) => {
set_ttl_or_hop_limit(&sock, 255)?;
return Ok(sock);
}
Err(e) if e.kind() == ErrorKind::AddrInUse => continue,
Err(e) => return Err(e),
}
}
Err(io::Error::new(
ErrorKind::AddrInUse,
format!(
"no free source port found for {local_addr} after {SOURCE_PORT_BIND_ATTEMPTS} attempts"
),
))
}
const ORDERING: Ordering = Ordering::Relaxed; const ORDERING: Ordering = Ordering::Relaxed;
#[derive(Debug)] #[derive(Debug)]
@@ -59,6 +94,7 @@ impl Error for BfdError {}
#[derive(Debug)] #[derive(Debug)]
struct BfdSessionState { struct BfdSessionState {
control_sock: Arc<UdpSocket>, // immutable control_sock: Arc<UdpSocket>, // immutable
local_ip: IpAddr, // immutable and Copy
peer_addr: IpAddr, // immutable and Copy peer_addr: IpAddr, // immutable and Copy
session_state: Atomic<BfdState>, // mutable by any thread session_state: Atomic<BfdState>, // mutable by any thread
remote_session_state: Atomic<BfdState>, // mutable by rx thread remote_session_state: Atomic<BfdState>, // mutable by rx thread
@@ -90,6 +126,9 @@ impl BfdSessionState {
fn control_sock(&self) -> Arc<UdpSocket> { fn control_sock(&self) -> Arc<UdpSocket> {
self.control_sock.clone() self.control_sock.clone()
} }
fn local_ip(&self) -> IpAddr {
self.local_ip
}
fn peer_addr(&self) -> IpAddr { fn peer_addr(&self) -> IpAddr {
self.peer_addr self.peer_addr
} }
@@ -202,13 +241,17 @@ struct BfdSession {
tx: mpsc::Sender<SessionControlCommand>, tx: mpsc::Sender<SessionControlCommand>,
rx_watchdog: Option<mpsc::Sender<WatchdogReset>>, rx_watchdog: Option<mpsc::Sender<WatchdogReset>>,
cur_interval: BfdInterval, cur_interval: BfdInterval,
// Configured DesiredMinTxInterval; advertised only once Up (RFC 5880 6.8.3 requires >= 1s otherwise)
configured_desired_min_tx: BfdInterval,
// DesiredMinTxInterval actually used for the transmit rate; lags the advertised value during a Poll Sequence
effective_desired_min_tx: BfdInterval,
event_dispatcher: EventDispatcherHandle, event_dispatcher: EventDispatcherHandle,
} }
impl From<&BfdSessionState> for BfdSessionStats { impl From<&BfdSessionState> for BfdSessionStats {
fn from(state: &BfdSessionState) -> Self { fn from(state: &BfdSessionState) -> Self {
Self { Self {
local_ip: state.control_sock().local_addr().unwrap().ip(), local_ip: state.local_ip(),
remote_ip: state.peer_addr(), remote_ip: state.peer_addr(),
local_discr: state.local_discr(), local_discr: state.local_discr(),
remote_discr: state.remote_discr(), remote_discr: state.remote_discr(),
@@ -253,25 +296,24 @@ impl BfdSessionHandle {
remote_addr: IpAddr, remote_addr: IpAddr,
local_discr: BfdDiscriminator, local_discr: BfdDiscriminator,
event_dispatcher: EventDispatcherHandle, event_dispatcher: EventDispatcherHandle,
) -> Self { ) -> io::Result<Self> {
let control_sock = bind_control_socket(local_addr).await?;
let (tx, rx) = mpsc::channel(32); let (tx, rx) = mpsc::channel(32);
let new_self = Self { tx }; let new_self = Self { tx };
let periodic =
BfdPeriodicSenderHandle::new(new_self.clone(), time::Duration::from_secs(1).into());
let mut session = BfdSession::new( let mut session = BfdSession::new(
rx, rx,
new_self.tx.clone(), new_self.clone(),
periodic, control_sock,
local_addr, local_addr,
remote_addr, remote_addr,
local_discr, local_discr,
event_dispatcher, event_dispatcher,
) );
.await;
tokio::spawn(async move { session.run().await }); tokio::spawn(async move { session.run().await });
new_self Ok(new_self)
} }
async fn transmit_control_packet( async fn transmit_control_packet(
&self, &self,
@@ -332,7 +374,7 @@ impl BfdPeriodicSender {
loop { loop {
tokio::select! { tokio::select! {
_ = clock.tick(), if running == true => { _ = clock.tick(), if running => {
let jitter = time::Duration::from_micros( let jitter = time::Duration::from_micros(
rand::thread_rng() rand::thread_rng()
.gen_range(0..clock.period().as_micros() / 3) .gen_range(0..clock.period().as_micros() / 3)
@@ -355,8 +397,8 @@ impl BfdPeriodicSender {
let base_interval: Duration = (i * 3 / 4).into(); let base_interval: Duration = (i * 3 / 4).into();
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 base interval to {}ms (jittering {} to {}ms)", base_interval.as_millis(), base_interval.as_millis(), base_interval.as_millis() + base_interval.as_millis() / 3);
clock = time::interval_at( clock = time::interval_at(
time::Instant::now() + base_interval.into(), time::Instant::now() + base_interval,
base_interval.into(), base_interval,
); );
}, },
PeriodicControlCommand::SendPollResponse => { PeriodicControlCommand::SendPollResponse => {
@@ -371,23 +413,22 @@ impl BfdPeriodicSender {
} }
impl BfdSession { impl BfdSession {
async fn new( fn new(
rx: mpsc::Receiver<SessionControlCommand>, rx: mpsc::Receiver<SessionControlCommand>,
tx: mpsc::Sender<SessionControlCommand>, handle: BfdSessionHandle,
periodic: BfdPeriodicSenderHandle, control_sock: UdpSocket,
local_addr: IpAddr, local_addr: IpAddr,
remote_addr: IpAddr, remote_addr: IpAddr,
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 =
BfdPeriodicSenderHandle::new(handle.clone(), time::Duration::from_secs(1).into());
let configured_desired_min_tx = BfdInterval::from_millis(300);
let slow_desired_min_tx =
std::cmp::max(configured_desired_min_tx, BfdInterval::from_secs(1));
//TODO: select a random unused port instead of pure random
let source_port: u16 = rng.gen_range(49152..=65535);
let control_sock = UdpSocket::bind(SocketAddr::new(local_addr, source_port))
.await
.unwrap();
set_ttl_or_hop_limit(&control_sock, 255).unwrap();
// control_sock // control_sock
// .connect(SocketAddr::new(remote_addr, CONTROL_PORT)) // .connect(SocketAddr::new(remote_addr, CONTROL_PORT))
// .await?; // .await?;
@@ -395,20 +436,23 @@ impl BfdSession {
// Incoming packets will come over the channel from the mux, since they don't send to the reciprocal port // Incoming packets will come over the channel from the mux, since they don't send to the reciprocal port
Self { Self {
rx, rx,
tx, tx: handle.tx,
periodic, periodic,
rx_watchdog: None, rx_watchdog: None,
cur_interval: BfdInterval::from_secs(1), cur_interval: BfdInterval::from_secs(1),
configured_desired_min_tx,
effective_desired_min_tx: slow_desired_min_tx,
event_dispatcher, event_dispatcher,
state: BfdSessionState { state: BfdSessionState {
control_sock: Arc::new(control_sock), control_sock: Arc::new(control_sock),
local_ip: local_addr,
peer_addr: remote_addr, peer_addr: remote_addr,
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(BfdInterval::from_millis(300)), 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(BfdInterval::from_millis(300)),
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),
@@ -437,7 +481,7 @@ impl BfdSession {
.dispatch(EventMessage::StateChange(StateChangeEvent { .dispatch(EventMessage::StateChange(StateChangeEvent {
local_discr: self.state.local_discr(), local_discr: self.state.local_discr(),
remote_discr: self.state.remote_discr(), remote_discr: self.state.remote_discr(),
local_ip: self.state.control_sock().local_addr().unwrap().ip(), //TODO: shouldn't unwrap here, it will crash the program local_ip: self.state.local_ip(),
remote_ip: self.state.peer_addr(), remote_ip: self.state.peer_addr(),
from_state: self.state.session_state(), from_state: self.state.session_state(),
to_state: new_state, to_state: new_state,
@@ -452,27 +496,34 @@ impl BfdSession {
*self.state.last_state_change.lock().await = Instant::now(); *self.state.last_state_change.lock().await = Instant::now();
match (self.state.session_state(), new_state) { match (self.state.session_state(), new_state) {
(BfdState::Up, BfdState::AdminDown | BfdState::Down | BfdState::Init) => { (BfdState::Up, BfdState::AdminDown | BfdState::Down | BfdState::Init) => {
if self.rx_watchdog.is_some() { if let Some(watchdog) = self.rx_watchdog.as_mut() {
self.rx_watchdog watchdog.send(WatchdogReset::Terminate).await.unwrap();
.as_mut()
.unwrap()
.send(WatchdogReset::Terminate)
.await
.unwrap();
}; };
// When bfd.SessionState is not Up, the system MUST set bfd.DesiredMinTxInterval to a value of not // When bfd.SessionState is not Up, the system MUST set bfd.DesiredMinTxInterval to a value of not
// less than one second (1,000,000 microseconds). This is intended to ensure that the bandwidth // less than one second (1,000,000 microseconds). This is intended to ensure that the bandwidth
// consumed by BFD sessions that are not Up is negligible, particularly in the case where a neighbor // consumed by BFD sessions that are not Up is negligible, particularly in the case where a neighbor
// may not be running BFD. // may not be running BFD.
self.state.set_desired_min_tx_interval(std::cmp::min( self.state.set_desired_min_tx_interval(std::cmp::max(
self.state.desired_min_tx_interval(), self.configured_desired_min_tx,
BfdInterval::from_secs(1), BfdInterval::from_secs(1),
)); ));
self.state.set_poll_mode(false);
self.set_effective_desired_min_tx(self.state.desired_min_tx_interval());
self.update_transmit_interval().await; self.update_transmit_interval().await;
} }
(BfdState::AdminDown | BfdState::Down | BfdState::Init, BfdState::Up) => { (BfdState::AdminDown | BfdState::Down | BfdState::Init, BfdState::Up) => {
self.start_watchdog().await; self.start_watchdog().await;
self.state.set_local_diag(BfdDiagnostic::None); // This doesn't seem to be required by the spec but seems sensible and at least FRR does it. self.state.set_local_diag(BfdDiagnostic::None); // This doesn't seem to be required by the spec but seems sensible and at least FRR does it.
// Advertise the configured interval now, but per section 6.8.3 keep transmitting at the old (slower)
// rate until a Poll Sequence confirms the peer has seen the change.
self.state
.set_desired_min_tx_interval(self.configured_desired_min_tx);
if self.configured_desired_min_tx < self.effective_desired_min_tx {
self.state.set_poll_mode(true);
} else {
self.set_effective_desired_min_tx(self.configured_desired_min_tx);
self.update_transmit_interval().await;
}
} }
_ => {} _ => {}
} }
@@ -487,7 +538,7 @@ impl BfdSession {
self.receive_control_packet(&packet).await; self.receive_control_packet(&packet).await;
} }
SessionControlCommand::GetSessionStats { respond_to } => { SessionControlCommand::GetSessionStats { respond_to } => {
let mut stats = let stats =
BfdSessionStats::from(&self.state).with_base_interval(self.cur_interval); BfdSessionStats::from(&self.state).with_base_interval(self.cur_interval);
respond_to.send(stats).unwrap() respond_to.send(stats).unwrap()
} }
@@ -515,11 +566,8 @@ impl BfdSession {
self.state.poll_mode() self.state.poll_mode()
}) })
.with_final_(poll_response) .with_final_(poll_response)
.with_cpi(true) .with_cpi(false)
.with_demand( .with_demand(self.state.demand_mode())
self.state.session_state() == BfdState::Up
&& self.state.remote_session_state() == BfdState::Up,
)
.with_detect_mult(self.state.detect_mult()) .with_detect_mult(self.state.detect_mult())
.with_length(24), .with_length(24),
my_disc: self.state.local_discr(), my_disc: self.state.local_discr(),
@@ -533,20 +581,17 @@ impl BfdSession {
let dest = self.state.peer_addr; let dest = self.state.peer_addr;
self.state.control_packets_tx.fetch_add(1, ORDERING); self.state.control_packets_tx.fetch_add(1, ORDERING);
debug!("tx packet: {:?}", packet); debug!("tx packet: {:?}", packet);
match socket if let Err(e) = socket
.send_to( .send_to(
packet.serialize().unwrap().as_ref(), packet.serialize().unwrap().as_ref(),
SocketAddr::new(dest, CONTROL_PORT), SocketAddr::new(dest, CONTROL_PORT),
) )
.await .await
{ {
Err(e) => { warn!(
warn!( "Error sending packet to {:?}:{} ({:?})",
"Error sending packet to {:?}:{} ({:?})", dest, CONTROL_PORT, e
dest, CONTROL_PORT, e );
);
}
Ok(_) => {}
} }
} }
@@ -583,14 +628,12 @@ impl BfdSession {
}); });
let mut temporary = Some(tx); let mut temporary = Some(tx);
swap(&mut temporary, &mut self.rx_watchdog); swap(&mut temporary, &mut self.rx_watchdog);
if temporary.is_some() { if let Some(old_watchdog) = temporary.as_mut() {
debug!( debug!(
"Updating old watchdog with new detection time ({}ms)", "Updating old watchdog with new detection time ({}ms)",
duration.as_millis() duration.as_millis()
); );
temporary old_watchdog
.as_mut()
.unwrap()
.send(WatchdogReset::Terminate) .send(WatchdogReset::Terminate)
.await .await
.unwrap_or(()) .unwrap_or(())
@@ -606,13 +649,8 @@ impl BfdSession {
// remote system, and bfd.SessionState is Init or Up, the session has // remote system, and bfd.SessionState is Init or Up, the session has
// gone down -- the local system MUST set bfd.SessionState to Down and // gone down -- the local system MUST set bfd.SessionState to Down and
// bfd.LocalDiag to 1 (Control Detection Time Expired). // bfd.LocalDiag to 1 (Control Detection Time Expired).
if self.rx_watchdog.is_some() { if let Some(watchdog) = self.rx_watchdog.as_ref() {
let _ = self let _ = watchdog.send(WatchdogReset::ReceivedPacket).await;
.rx_watchdog
.as_ref()
.unwrap()
.send(WatchdogReset::ReceivedPacket)
.await;
} }
self.state.control_packets_rx.fetch_add(1, ORDERING); self.state.control_packets_rx.fetch_add(1, ORDERING);
let received_state = match p.flags.state() { let received_state = match p.flags.state() {
@@ -633,8 +671,6 @@ impl BfdSession {
warn!("Invalid packet length {}, discarding", p.flags.length()); warn!("Invalid packet length {}, discarding", p.flags.length());
return; return;
} }
// TODO: If the Length field is greater than the payload of the encapsulating protocol, the packet MUST be
// discarded.
// If the Detect Mult field is zero, the packet MUST be discarded. // If the Detect Mult field is zero, the packet MUST be discarded.
if p.flags.detect_mult() == 0 { if p.flags.detect_mult() == 0 {
@@ -711,14 +747,16 @@ impl BfdSession {
} }
// If a Poll Sequence is being transmitted by the local system and the Final (F) bit in the received packet is // If a Poll Sequence is being transmitted by the local system and the Final (F) bit in the received packet is
// set, the Poll Sequence MUST be terminated. // set, the Poll Sequence MUST be terminated.
// if self.state.poll_mode() && p.flags.final_() {
// TODO: poll stuff self.state.set_poll_mode(false);
self.set_effective_desired_min_tx(self.state.desired_min_tx_interval());
}
// Update the transmit interval as described in section 6.8.2. // Update the transmit interval as described in section 6.8.2.
self.update_transmit_interval().await; self.update_transmit_interval().await;
// Update the Detection Time as described in section 6.8.4. // Update the Detection Time as described in section 6.8.4.
self.update_detection_time(&p).await; self.update_detection_time(p).await;
// If bfd.SessionState is AdminDown // If bfd.SessionState is AdminDown
// Discard the packet // Discard the packet
@@ -787,19 +825,39 @@ impl BfdSession {
// If the Poll (P) bit is set, send a BFD Control packet to the remote system with the Poll (P) bit clear, // If the Poll (P) bit is set, send a BFD Control packet to the remote system with the Poll (P) bit clear,
// and the Final (F) bit set (see section 6.8.7). // and the Final (F) bit set (see section 6.8.7).
if p.flags.poll() {} if p.flags.poll() {
self.transmit_control_packet(true).await;
}
// If the packet was not discarded, it has been received for purposes of the Detection Time expiration rules // If the packet was not discarded, it has been received for purposes of the Detection Time expiration rules
// in section 6.8.4. // in section 6.8.4.
} }
} }
fn set_effective_desired_min_tx(&mut self, value: BfdInterval) {
if value != self.effective_desired_min_tx {
info!(
"Peer {} effective desired-min-tx {} -> {}",
self.state.peer_addr(),
self.effective_desired_min_tx,
value
);
}
self.effective_desired_min_tx = value;
}
// https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.2 // https://datatracker.ietf.org/doc/html/rfc5880#section-6.8.2
async fn update_transmit_interval(&mut self) { async fn update_transmit_interval(&mut self) {
let new_base_interval = std::cmp::max( let new_base_interval = std::cmp::max(
self.state.desired_min_tx_interval(), self.effective_desired_min_tx,
self.state.remote_min_rx_interval(), self.state.remote_min_rx_interval(),
); );
if new_base_interval != self.cur_interval { if new_base_interval != self.cur_interval {
info!(
"Peer {} transmit interval {} -> {}",
self.state.peer_addr(),
self.cur_interval,
new_base_interval
);
self.periodic self.periodic
.tx .tx
.send(PeriodicControlCommand::SetMinInterval(new_base_interval)) .send(PeriodicControlCommand::SetMinInterval(new_base_interval))
@@ -813,18 +871,22 @@ impl BfdSession {
async fn update_detection_time(&mut self, p: &BfdPacket) { async fn update_detection_time(&mut self, p: &BfdPacket) {
let old = self.state.detection_time(); let old = self.state.detection_time();
self.state.set_detection_time(if !self.state.demand_mode() { self.state.set_detection_time(if !self.state.demand_mode() {
(p.flags.detect_mult() as u32 p.flags.detect_mult() as u32
* std::cmp::max(self.state.required_min_rx_interval(), p.desired_min_tx)) * std::cmp::max(self.state.required_min_rx_interval(), p.desired_min_tx)
.into()
} else { } else {
(self.state.detect_mult() as u32 self.state.detect_mult() as u32
* std::cmp::max( * std::cmp::max(
self.state.desired_min_tx_interval(), self.state.desired_min_tx_interval(),
self.state.remote_min_rx_interval(), self.state.remote_min_rx_interval(),
)) )
.into()
}); });
if old != self.state.detection_time() { if old != self.state.detection_time() {
info!(
"Peer {} detection time {} -> {}",
self.state.peer_addr(),
old,
self.state.detection_time()
);
self.start_watchdog().await self.start_watchdog().await
} }
} }
@@ -923,14 +985,24 @@ struct Bfdd {
} }
impl Bfdd { impl Bfdd {
async fn new() -> Result<Self, Box<dyn Error>> { async fn new(args: Args) -> Result<Self, Box<dyn Error>> {
// let local = SocketAddr::from_str("192.168.255.2:3784").unwrap(); let local = SocketAddr::new(args.bind, CONTROL_PORT);
let local = SocketAddr::new(Ipv6Addr::from_str("2001:db8::2").unwrap().into(), 3784); if let Some(peer) = args
let peers = vec![ .peers
// SocketAddr::from_str("192.168.122.132:3784").unwrap(), .iter()
// SocketAddr::from_str("192.168.255.1:3784").unwrap(), .find(|p| p.is_ipv4() != args.bind.is_ipv4())
SocketAddr::new(Ipv6Addr::from_str("2001:db8::1").unwrap().into(), 3784), {
]; return Err(format!(
"peer {peer} is not the same address family as bind address {}",
args.bind
)
.into());
}
let peers = args
.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();
@@ -940,7 +1012,7 @@ impl Bfdd {
// If BFD authentication is not in use on a session, all BFD Control packets for the session MUST be sent with a // If BFD authentication is not in use on a session, all BFD Control packets for the session MUST be sent with a
// Time to Live (TTL) or Hop Limit value of 255. // Time to Live (TTL) or Hop Limit value of 255.
set_ttl_or_hop_limit(&control_socket, 255)?; set_ttl_or_hop_limit(&control_socket, 255)?;
let echo_socket = Arc::new(UdpSocket::bind(SocketAddr::new(local.ip(), ECHO_PORT)).await?); let _echo_socket = Arc::new(UdpSocket::bind(SocketAddr::new(local.ip(), ECHO_PORT)).await?);
let event_dispatcher = EventDispatcherHandle::new().await; let event_dispatcher = EventDispatcherHandle::new().await;
event_dispatcher event_dispatcher
@@ -956,11 +1028,11 @@ impl Bfdd {
event_dispatcher, event_dispatcher,
}) })
} }
async fn start_peers(&mut self) { async fn start_peers(&mut self) -> io::Result<()> {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
for peer in &self.peers { for peer in &self.peers {
let mut local_discr = BfdDiscriminator(0); let mut local_discr = BfdDiscriminator(0);
while local_discr.0 == 0 || self.sessions_by_discr.get(&local_discr).is_some() { while local_discr.0 == 0 || self.sessions_by_discr.contains_key(&local_discr) {
local_discr = BfdDiscriminator(rng.gen()); local_discr = BfdDiscriminator(rng.gen());
} }
let session = BfdSessionHandle::new( let session = BfdSessionHandle::new(
@@ -969,12 +1041,13 @@ impl Bfdd {
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.ip()), local_discr);
self.sessions_by_discr.insert(local_discr, session); self.sessions_by_discr.insert(local_discr, session);
} }
Ok(())
} }
fn session_for_packet( fn session_for_packet(
&self, &self,
@@ -991,11 +1064,10 @@ impl Bfdd {
// source address field can change or the interface over which the packets are received can change, but // source address field can change or the interface over which the packets are received can change, but
// the packets will still be associated with the proper session). // the packets will still be associated with the proper session).
let our_disc = if packet.your_disc == BfdDiscriminator(0) { let our_disc = if packet.your_disc == BfdDiscriminator(0) {
if let Some(discr) = self if let Some(discr) = self.sessions_by_ip.get(&(self.local.ip(), addr.ip())) {
.sessions_by_ip // A restarted peer starts over with Your Discriminator of zero. We deliberately keep the existing
.get(&(self.control_socket.local_addr().unwrap().ip(), addr.ip())) // session: the RFC 5880 section 6.8.6 state machine takes it Down (diag: Neighbor signaled session
{ // down) and bfd.RemoteDiscr is relearned from the new My Discriminator.
// TODO: Probably we should destroy the old session here?
debug!( debug!(
"Found session for unknown discriminator from {}: {}", "Found session for unknown discriminator from {}: {}",
addr.ip(), addr.ip(),
@@ -1020,12 +1092,11 @@ impl Bfdd {
.unwrap(); .unwrap();
} else { } else {
warn!("Unable to match packet to session with"); warn!("Unable to match packet to session with");
return;
} }
} }
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: {}", "configured sessions: {}",
future::join_all( future::join_all(
@@ -1037,33 +1108,45 @@ impl Bfdd {
.join("\n\t") .join("\n\t")
); );
let rx_task = let rx_task = task::spawn(async move {
task::spawn(async move { 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 // the received TTL or Hop Limit is not equal to 255. Need raw sockets for this.
// the received TTL or Hop Limit is not equal to 255. Need raw sockets for this. //
// // TODO: Maybe it is okay to receive in the session-specific socket instead of this global one? But
// 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 {
let (len, addr) = self.control_socket.recv_from(&mut buf).await.unwrap(); // TODO: fallibility? Ok((len, addr)) => {
if let Ok((_leftover, packet)) = BfdPacket::parse(&buf[..len]) { if let Ok((_leftover, packet)) = BfdPacket::parse(&buf[..len]) {
debug!("rx packet ({:?}): {:?}", addr.ip(), packet); debug!("rx packet ({:?}): {:?}", addr.ip(), packet);
self.rx_packet(addr, packet).await // If the Length field is greater than the payload of the encapsulating protocol, the packet MUST be
} else { // discarded.
warn!("Failed to parse packet"); 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");
}
info!( debug!(
"configured sessions: {}", "configured sessions: {}",
future::join_all(self.sessions_by_discr.values().map(|session| async { future::join_all(self.sessions_by_discr.values().map(
session.get_stats().await.unwrap().to_string() |session| async { session.get_stats().await.unwrap().to_string() }
})) ))
.await .await
.join("\n\t") .join("\n\t")
); );
}
Err(e) => {
warn!("Error receiving from socket {e:?}");
continue;
}
} }
}); }
});
tokio::join!(rx_task) tokio::join!(rx_task)
.0 .0
@@ -1075,12 +1158,14 @@ impl Bfdd {
#[tokio::main] #[tokio::main]
async fn main() -> io::Result<()> { async fn main() -> io::Result<()> {
let args = Args::parse();
env_logger::Builder::from_env(Env::default().default_filter_or("info")) env_logger::Builder::from_env(Env::default().default_filter_or("info"))
.format_timestamp_micros() .format_timestamp_micros()
.init(); .init();
match Bfdd::new().await { match Bfdd::new(args).await {
Ok(bfdd) => bfdd.run().await, Ok(bfdd) => bfdd.run().await,
Err(e) => Err(std::io::Error::new(ErrorKind::Other, e.to_string())), Err(e) => Err(std::io::Error::other(e.to_string())),
} }
} }
+10 -5
View File
@@ -3,12 +3,11 @@ use std::{
ffi::{OsStr, OsString}, ffi::{OsStr, OsString},
net::IpAddr, net::IpAddr,
path::PathBuf, path::PathBuf,
process::ExitStatus,
}; };
use itertools::Itertools; use itertools::Itertools;
use log::{debug, info, warn}; use log::{debug, info, warn};
use nix::unistd::{self, eaccess}; use nix::unistd;
use tokio::{ use tokio::{
fs, process, fs, process,
sync::mpsc, sync::mpsc,
@@ -53,6 +52,12 @@ impl EventMessageSink for ScriptHookSink {
} }
} }
impl Default for ScriptHookSink {
fn default() -> Self {
Self::new()
}
}
impl ScriptHookSink { impl ScriptHookSink {
pub fn new() -> Self { pub fn new() -> Self {
let (tx_channel, rx_channel) = mpsc::channel(16); let (tx_channel, rx_channel) = mpsc::channel(16);
@@ -83,13 +88,13 @@ impl ScriptHookSink {
output.status output.status
); );
if !output.status.success() { if !output.status.success() {
if output.stdout.len() > 0 { if !output.stdout.is_empty() {
warn!( warn!(
" stdout: \n{}", " stdout: \n{}",
str::from_utf8(output.stdout.as_slice()).unwrap() str::from_utf8(output.stdout.as_slice()).unwrap()
); );
} }
if output.stderr.len() > 0 { if !output.stderr.is_empty() {
warn!( warn!(
" stderr: \n{}", " stderr: \n{}",
str::from_utf8(output.stderr.as_slice()).unwrap() str::from_utf8(output.stderr.as_slice()).unwrap()
@@ -133,7 +138,7 @@ impl ScriptHookSink {
.map_or(OsString::new(), |file| file.to_owned()) .map_or(OsString::new(), |file| file.to_owned())
}); });
if scripts.len() > 0 { if !scripts.is_empty() {
// Build context // Build context
let mut args = Vec::<&OsStr>::new(); let mut args = Vec::<&OsStr>::new();
let mut env = Vec::<(&OsStr, &OsStr)>::new(); let mut env = Vec::<(&OsStr, &OsStr)>::new();