bacnet-client 0.15.0

BACnet async client: TSM, segmentation, discovery, and service APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use std::collections::HashMap;
use std::sync::{Arc, Mutex as StdMutex, MutexGuard as StdMutexGuard};
use std::time::{Duration, Instant as StdInstant};

use bacnet_network::layer::ReceivedNetworkControl;
use bacnet_npdu::{NetworkMessageType, RejectMessageReason, RejectMessageToNetwork};
use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
use tokio::time::Instant as TokioInstant;

use super::*;
use crate::tsm::CompletionOutcome;

/// Smallest routed NPDU envelope required across the standard data links.
const CONSERVATIVE_ROUTED_PATH_MAX_NPDU: u16 = 228;
/// Hard bound covering gates, configured evidence, and learned evidence.
pub(super) const MAX_ROUTED_PATH_ENTRIES: usize = 256;

/// Whether a router MAC or forwarded source MAC fits a routed path: 1 to
/// [`MAX_MAC_LEN`](bacnet_npdu::MAX_MAC_LEN) octets. The NPDU codec carries no longer SADR
/// or DADR (#1141), and the network layer drops a frame from a longer
/// link-layer source (#1198), so a longer MAC could never complete a routed
/// request (#1267).
fn routed_mac_fits(length: usize) -> bool {
    (1..=bacnet_npdu::MAX_MAC_LEN).contains(&length)
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct RoutedPathKey {
    immediate_router_mac: MacAddr,
    dnet: u16,
}

impl RoutedPathKey {
    fn new(immediate_router_mac: &[u8], dnet: u16) -> Self {
        Self {
            immediate_router_mac: MacAddr::from_slice(immediate_router_mac),
            dnet,
        }
    }
}

#[derive(Clone, Copy, Debug)]
enum ConfiguredLimitProvenance {
    ExplicitApi,
}

struct ConfiguredPathLimit {
    max_npdu: u16,
    provenance: ConfiguredLimitProvenance,
    observed_at: StdInstant,
}

struct LearnedPathLimit {
    exclusive_max_npdu: u16,
    observed_at: StdInstant,
}

struct ActiveRoutedSend {
    path: RoutedPathKey,
    tsm_mac: MacAddr,
    invoke_id: u8,
    owner: TransactionOwner,
    forwarded_npci_len: u16,
    outgoing_apdu_len: Option<u16>,
    ingress_floor: u64,
}

struct RoutedPathEntry {
    gate: Arc<AsyncMutex<()>>,
    configured: Option<ConfiguredPathLimit>,
    learned: Option<LearnedPathLimit>,
    active: Option<ActiveRoutedSend>,
    last_used: u64,
    quarantine_started: Option<TokioInstant>,
    generation_attempts: u32,
    generation_terminal_observed: bool,
}

impl RoutedPathEntry {
    fn new(last_used: u64) -> Self {
        Self {
            gate: Arc::new(AsyncMutex::new(())),
            configured: None,
            learned: None,
            active: None,
            last_used,
            quarantine_started: None,
            generation_attempts: 0,
            generation_terminal_observed: false,
        }
    }
}

struct RoutedPathState {
    entries: HashMap<RoutedPathKey, RoutedPathEntry>,
    next_use: u64,
    capacity: usize,
}

pub(super) struct RoutedPathLimits {
    state: StdMutex<RoutedPathState>,
    quarantine_horizon: Duration,
}

impl RoutedPathLimits {
    pub(super) fn new(quarantine_horizon: Duration) -> Self {
        Self::with_capacity(MAX_ROUTED_PATH_ENTRIES, quarantine_horizon)
    }

    fn with_capacity(capacity: usize, quarantine_horizon: Duration) -> Self {
        assert!(capacity > 0, "routed path capacity must be nonzero");
        Self {
            state: StdMutex::new(RoutedPathState {
                entries: HashMap::new(),
                next_use: 0,
                capacity,
            }),
            quarantine_horizon,
        }
    }

    fn state(&self) -> StdMutexGuard<'_, RoutedPathState> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// How many path entries exist, in use or idle.
    #[cfg(test)]
    pub(super) fn entry_count(&self) -> usize {
        self.state().entries.len()
    }

    /// Reserve and lock the path through `router_mac` to `dnet`. A router MAC
    /// outside [`routed_mac_fits`] is refused before any entry is reserved.
    pub(super) async fn acquire(
        self: &Arc<Self>,
        router_mac: &[u8],
        dnet: u16,
    ) -> Result<RoutedPathLease, Error> {
        if !routed_mac_fits(router_mac.len()) {
            return Err(Error::Encoding(format!(
                "immediate router MAC address must contain 1..={} octets",
                bacnet_npdu::MAX_MAC_LEN
            )));
        }
        let key = RoutedPathKey::new(router_mac, dnet);
        let gate = self.reserve_gate(&key)?;
        let gate = gate.lock_owned().await;
        self.wait_for_quarantine(&key).await;
        Ok(RoutedPathLease {
            limits: Arc::clone(self),
            key,
            _gate: gate,
        })
    }

    fn reserve_gate(&self, key: &RoutedPathKey) -> Result<Arc<AsyncMutex<()>>, Error> {
        let mut state = self.state();
        let last_used = bump_use(&mut state);
        if let Some(entry) = state.entries.get_mut(key) {
            entry.last_used = last_used;
            return Ok(Arc::clone(&entry.gate));
        }

        if state.entries.len() >= state.capacity {
            let reclaim = state
                .entries
                .iter()
                .filter(|(_, entry)| self.is_safely_reclaimable(entry))
                .min_by(|(key_a, entry_a), (key_b, entry_b)| {
                    entry_a
                        .last_used
                        .cmp(&entry_b.last_used)
                        .then_with(|| key_a.cmp(key_b))
                })
                .map(|(key, _)| key.clone());
            if let Some(reclaim) = reclaim {
                state.entries.remove(&reclaim);
            }
        }
        if state.entries.len() >= state.capacity {
            return Err(Error::RoutedPathCapacityExceeded {
                capacity: state.capacity,
            });
        }

        let entry = RoutedPathEntry::new(last_used);
        let gate = Arc::clone(&entry.gate);
        state.entries.insert(key.clone(), entry);
        Ok(gate)
    }

    fn is_safely_reclaimable(&self, entry: &RoutedPathEntry) -> bool {
        entry.configured.is_none()
            && entry.learned.is_none()
            && entry.active.is_none()
            && Arc::strong_count(&entry.gate) == 1
            && entry
                .quarantine_started
                .is_none_or(|started| started.elapsed() >= self.quarantine_horizon)
    }

    async fn wait_for_quarantine(&self, key: &RoutedPathKey) {
        loop {
            let remaining = {
                let mut state = self.state();
                let last_used = bump_use(&mut state);
                let entry = state
                    .entries
                    .get_mut(key)
                    .expect("a held or waiting gate keeps its path entry resident");
                entry.last_used = last_used;
                match entry.quarantine_started {
                    Some(started) => {
                        let remaining = self.quarantine_horizon.saturating_sub(started.elapsed());
                        if remaining.is_zero() {
                            entry.quarantine_started = None;
                            entry.generation_attempts = 0;
                            entry.generation_terminal_observed = false;
                            None
                        } else {
                            Some(remaining)
                        }
                    }
                    None => {
                        entry.generation_attempts = 0;
                        entry.generation_terminal_observed = false;
                        None
                    }
                }
            };
            let Some(remaining) = remaining else {
                return;
            };
            tokio::time::sleep(remaining).await;
        }
    }

    pub(super) fn install_active(
        &self,
        target: ConfirmedTarget<'_>,
        tsm_mac: MacAddr,
        invoke_id: u8,
        owner: TransactionOwner,
        forwarded_npci_len: u16,
        ingress_floor: u64,
    ) {
        let ConfirmedTarget::Routed {
            router_mac,
            dest_network,
            ..
        } = target
        else {
            return;
        };
        let key = RoutedPathKey::new(router_mac, dest_network);
        let mut state = self.state();
        let entry = state
            .entries
            .get_mut(&key)
            .expect("the routed path lease keeps its entry resident");
        debug_assert!(
            entry.active.is_none(),
            "the per-path gate permits only one active routed request"
        );
        entry.active = Some(ActiveRoutedSend {
            path: key,
            tsm_mac,
            invoke_id,
            owner,
            forwarded_npci_len,
            outgoing_apdu_len: None,
            ingress_floor,
        });
    }

    pub(super) fn authorize_attempt(
        &self,
        target: ConfirmedTarget<'_>,
        tsm_mac: &MacAddr,
        invoke_id: u8,
        owner: &TransactionOwner,
        outgoing_apdu_len: usize,
    ) -> bool {
        let ConfirmedTarget::Routed {
            router_mac,
            dest_network,
            ..
        } = target
        else {
            return true;
        };
        let Ok(outgoing_apdu_len) = u16::try_from(outgoing_apdu_len) else {
            return false;
        };
        let key = RoutedPathKey::new(router_mac, dest_network);
        let mut state = self.state();
        let Some(entry) = state.entries.get_mut(&key) else {
            return false;
        };
        let Some(active) = entry.active.as_mut() else {
            return false;
        };
        if active.tsm_mac != *tsm_mac
            || active.invoke_id != invoke_id
            || !active.owner.same_as(owner)
        {
            return false;
        }
        active.outgoing_apdu_len = Some(outgoing_apdu_len);
        entry.generation_attempts = entry.generation_attempts.saturating_add(1);
        true
    }

    pub(super) async fn handle_network_control(
        &self,
        tsm: &Arc<Mutex<Tsm>>,
        control: ReceivedNetworkControl,
    ) {
        if control.npdu.message_type != Some(NetworkMessageType::REJECT_MESSAGE_TO_NETWORK) {
            return;
        }
        let Ok(reject) = RejectMessageToNetwork::decode(&control.npdu.payload) else {
            return;
        };
        if reject.reason != RejectMessageReason::MESSAGE_TOO_LONG {
            return;
        }

        let Some(active) = self.claim_active(
            &control.source_mac,
            reject.network,
            control.ingress_sequence,
        ) else {
            return;
        };
        let outcome = tsm.lock().await.complete_network_path_too_long_for_owner(
            &active.tsm_mac,
            active.invoke_id,
            &active.owner,
            reject.network,
        );
        if outcome == CompletionOutcome::Delivered {
            self.commit_learned_limit(active);
        }
    }

    fn claim_active(
        &self,
        router_mac: &[u8],
        dnet: u16,
        ingress_sequence: u64,
    ) -> Option<ActiveRoutedSend> {
        let key = RoutedPathKey::new(router_mac, dnet);
        let mut state = self.state();
        let entry = state.entries.get_mut(&key)?;
        if entry.active.as_ref().is_none_or(|active| {
            active.outgoing_apdu_len.is_none()
                || active.path != key
                || ingress_sequence <= active.ingress_floor
        }) {
            return None;
        }
        entry.active.take()
    }

    fn commit_learned_limit(&self, active: ActiveRoutedSend) {
        let Some(attempted_npdu) = active
            .outgoing_apdu_len
            .and_then(|apdu| active.forwarded_npci_len.checked_add(apdu))
        else {
            return;
        };
        let mut state = self.state();
        let entry = state
            .entries
            .get_mut(&active.path)
            .expect("the reason-4 claimant still holds its routed path gate");
        let exclusive_max_npdu = entry.learned.as_ref().map_or(attempted_npdu, |learned| {
            learned.exclusive_max_npdu.min(attempted_npdu)
        });
        entry.learned = Some(LearnedPathLimit {
            exclusive_max_npdu,
            observed_at: StdInstant::now(),
        });
    }
}

pub(super) struct RoutedPathLease {
    limits: Arc<RoutedPathLimits>,
    key: RoutedPathKey,
    _gate: OwnedMutexGuard<()>,
}

impl RoutedPathLease {
    /// The APDU allowance left on this path after the forwarded NPCI that
    /// [`forwarded_npci_len`] measured.
    pub(super) fn max_apdu(&self, forwarded_npci_len: u16) -> u16 {
        let state = self.limits.state();
        let entry = state
            .entries
            .get(&self.key)
            .expect("path entry remains present while its gate is held");
        let configured_or_conservative =
            entry
                .configured
                .as_ref()
                .map_or(CONSERVATIVE_ROUTED_PATH_MAX_NPDU, |configured| {
                    tracing::trace!(
                        max_npdu = configured.max_npdu,
                        provenance = ?configured.provenance,
                        age = ?configured.observed_at.elapsed(),
                        "Using configured routed-path NPDU limit"
                    );
                    configured.max_npdu
                });
        let effective_npdu = entry
            .learned
            .as_ref()
            .map_or(configured_or_conservative, |learned| {
                tracing::trace!(
                    exclusive_max_npdu = learned.exclusive_max_npdu,
                    age = ?learned.observed_at.elapsed(),
                    "Applying learned routed-path upper bound"
                );
                configured_or_conservative.min(learned.exclusive_max_npdu.saturating_sub(1))
            });
        effective_npdu.saturating_sub(forwarded_npci_len)
    }

    /// Mark a source-correlated terminal response for the current generation.
    /// One attempted frame plus its terminal response proves there cannot be a
    /// second reason-4 still in flight for that generation. Multi-frame or
    /// retried generations remain ambiguous and are quarantined on drop.
    pub(super) fn mark_terminal_observed(&self) {
        let mut state = self.limits.state();
        let entry = state
            .entries
            .get_mut(&self.key)
            .expect("path entry remains present while its gate is held");
        entry.generation_terminal_observed = entry.generation_attempts == 1;
    }

    fn configure(&self, max_npdu: u16) {
        let mut state = self.limits.state();
        let entry = state
            .entries
            .get_mut(&self.key)
            .expect("path entry remains present while its gate is held");
        entry.configured = Some(ConfiguredPathLimit {
            max_npdu,
            provenance: ConfiguredLimitProvenance::ExplicitApi,
            observed_at: StdInstant::now(),
        });
        entry.learned = None;
    }

    fn clear(&self) {
        let mut state = self.limits.state();
        let entry = state
            .entries
            .get_mut(&self.key)
            .expect("path entry remains present while its gate is held");
        entry.configured = None;
        entry.learned = None;
    }
}

impl Drop for RoutedPathLease {
    fn drop(&mut self) {
        let mut state = self.limits.state();
        if let Some(entry) = state.entries.get_mut(&self.key) {
            entry.active = None;
            if entry.generation_attempts > 0 && !entry.generation_terminal_observed {
                entry.quarantine_started = Some(TokioInstant::now());
            }
            entry.generation_attempts = 0;
            entry.generation_terminal_observed = false;
        }
    }
}

fn bump_use(state: &mut RoutedPathState) -> u64 {
    state.next_use = state.next_use.saturating_add(1);
    state.next_use
}

pub(super) fn routed_path_quarantine_horizon(config: &ClientConfig) -> Duration {
    // Reuse the configured complete request/retry horizon instead of adding a
    // separate arbitrary stale-control timer. A zero timeout still receives
    // one millisecond, the existing configuration's millisecond granularity,
    // so ambiguous generations never skip quarantine entirely.
    let attempts = u64::from(config.apdu_retries).saturating_add(1);
    Duration::from_millis(config.apdu_timeout_ms.saturating_mul(attempts).max(1))
}

/// The NPCI a router adds when it forwards a request to the DADR: the fixed
/// fields plus DADR and the SADR it fills with the local source MAC. A DADR or
/// source MAC outside [`routed_mac_fits`] is refused (#1267): an empty DADR
/// would have the remote router broadcast the request (#1278).
pub(super) fn forwarded_npci_len(
    dadr_len: usize,
    local_source_mac_len: usize,
) -> Result<u16, Error> {
    check_routed_dadr(dadr_len)?;
    if !routed_mac_fits(local_source_mac_len) {
        return Err(Error::Encoding(format!(
            "local source MAC address for routed forwarding must contain 1..={} octets",
            bacnet_npdu::MAX_MAC_LEN
        )));
    }
    Ok(u16::try_from(9 + dadr_len + local_source_mac_len)
        .expect("two addresses within bacnet_npdu::MAX_MAC_LEN fit a u16"))
}

impl<T: TransportPort + 'static> BACnetClient<T> {
    /// Configure the maximum NPDU for one immediate-router/DNET path.
    ///
    /// The update waits for any request already active on the same path. It
    /// replaces the previous configured value and deliberately clears learned
    /// reason-4 evidence for that path. A router MAC outside 1 to
    /// [`MAX_MAC_LEN`](bacnet_npdu::MAX_MAC_LEN) octets or a DNET outside 1..=65534 is
    /// refused with [`Error::Encoding`].
    pub async fn configure_routed_path_max_npdu(
        &self,
        router_mac: &[u8],
        dnet: u16,
        max_npdu: u16,
    ) -> Result<(), Error> {
        check_remote_dnet(dnet)?;
        let lease = self.routed_path_limits.acquire(router_mac, dnet).await?;
        lease.configure(max_npdu);
        Ok(())
    }

    /// Restore one immediate-router/DNET path to the conservative default.
    ///
    /// The update waits for an active request and clears both configured and
    /// learned reason-4 evidence. Later requests therefore use the 228-octet
    /// conservative routed NPDU envelope until new evidence is supplied. The
    /// router MAC and DNET are checked as in
    /// [`configure_routed_path_max_npdu`](Self::configure_routed_path_max_npdu).
    pub async fn clear_routed_path_limit(&self, router_mac: &[u8], dnet: u16) -> Result<(), Error> {
        check_remote_dnet(dnet)?;
        let lease = self.routed_path_limits.acquire(router_mac, dnet).await?;
        lease.clear();
        Ok(())
    }
}

/// Whether `dnet` names one remote network: 1..=65534. DNET 0 names no
/// network and 65535 is the global broadcast, so neither can key a routed path
/// or address a confirmed request (Clauses 6.2.2.1 and 6.3, #1278). The path
/// APIs and every routed confirmed request share this check;
/// [`RoutedPathLimits::acquire`] checks the router MAC.
pub(super) fn check_remote_dnet(dnet: u16) -> Result<(), Error> {
    if dnet == 0 || dnet == u16::MAX {
        return Err(Error::Encoding("routed DNET must be in 1..=65534".into()));
    }
    Ok(())
}

/// A DADR that names one station: 1 to [`MAX_MAC_LEN`](bacnet_npdu::MAX_MAC_LEN) octets.
/// With no DADR the router on DNET broadcasts the NPDU, and a broadcast
/// network address carries only unconfirmed requests (Clause 6.3).
fn check_routed_dadr(dadr_len: usize) -> Result<(), Error> {
    if !routed_mac_fits(dadr_len) {
        return Err(Error::Encoding(format!(
            "routed destination MAC address must contain 1..={} octets",
            bacnet_npdu::MAX_MAC_LEN
        )));
    }
    Ok(())
}

/// Refuse a routed confirmed destination that does not name exactly one
/// device: a DNET [`check_remote_dnet`] refuses or a DADR outside
/// [`routed_mac_fits`]. The client's own request path runs it on the target
/// as named, before a target on the local network is sent locally, and
/// measures the forwarded NPCI with [`forwarded_npci_len`] only for a target
/// still routed.
pub(crate) fn check_routed_unicast(dnet: u16, dadr_len: usize) -> Result<(), Error> {
    check_remote_dnet(dnet)?;
    check_routed_dadr(dadr_len)
}

#[cfg(test)]
#[path = "routed_path_limits_tests.rs"]
mod tests;