bacnet-server 0.15.0

BACnet server: APDU dispatch and service handlers
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
use super::request_admission::{Class, Rejection};
use super::*;

impl<T: TransportPort + 'static> BACnetServer<T> {
    /// Admit an answer to a confirmed request this server sent. With
    /// `local_network`, this network's number, known, an answer relayed with
    /// it as SNET answers a request sent to its SADR (#1465), and teaches no
    /// next hop: sends to this network go out locally.
    async fn admit_notification_terminal(
        learned_routers: &Arc<Mutex<LearnedRouterCache>>,
        notification_transactions: &Arc<NotificationTransactions>,
        source_mac: &[u8],
        source_network: Option<&NpduAddress>,
        local_network: Option<u16>,
        apdu: &Apdu,
    ) -> bool {
        if !notification_transactions.admit_terminal(
            source_mac,
            source_network,
            local_network,
            apdu,
        ) {
            return false;
        }

        if let Some(source) = source_network.filter(|source| {
            !source.mac_address.is_empty() && Some(source.network) != local_network
        }) {
            learned_routers
                .lock()
                .await
                .learn_router(source.network, &MacAddr::from_slice(source_mac));
        }
        true
    }

    async fn route_segmented_send_event(
        seg_ack_senders: &Arc<segmented_send::SegmentedSendRegistry>,
        key: SegKey,
        event: SegmentedSendEvent,
    ) -> bool {
        let handle = {
            let senders = seg_ack_senders.lock();
            senders.get(&key).cloned()
        };

        let Some(handle) = handle else {
            return false;
        };

        match event {
            SegmentedSendEvent::Abort(abort) => {
                handle.send_control(SegmentedSendControlEvent::Abort(abort));
                true
            }
            SegmentedSendEvent::SegmentAck(ack) => {
                let invoke_id = ack.invoke_id;
                let seq = ack.sequence_number;
                if !handle.accepts_segment_ack(&ack) {
                    debug!(
                        invoke_id,
                        seq,
                        negative = ack.negative_ack,
                        "Ignoring SegmentAck outside current segmented-send window"
                    );
                    return true;
                }

                match handle.segment_ack_tx.try_send(ack) {
                    Ok(()) => true,
                    Err(mpsc::error::TrySendError::Full(_)) => {
                        warn_throttled!(
                            seg_ack_senders.warning,
                            invoke_id,
                            seq,
                            "Dropping SegmentAck because segmented-send queue is full"
                        );
                        true
                    }
                    Err(mpsc::error::TrySendError::Closed(_)) => false,
                }
            }
        }
    }

    /// Answer a confirmed request refused for capacity with a server Abort,
    /// on one of the abort workers. The Abort's addressing is rebuilt from
    /// `received` here rather than copied ahead of admission, so an admitted
    /// request never pays for it (#1713).
    fn spawn_overload_abort(
        ctx: &DispatchContext<T>,
        source_mac: &[u8],
        received: &bacnet_network::layer::ReceivedApdu,
        invoke_id: u8,
        reply_tx: Option<oneshot::Sender<Bytes>>,
    ) {
        let network = Arc::clone(&ctx.services.network);
        let mac = MacAddr::from_slice(source_mac);
        let source = received.source_network.clone();
        let route = received.response_route();
        let peer = super::request_peer::canonical_requester(&mac, source.as_ref());
        let _ = ctx
            .request_tasks
            .try_spawn(Class::Abort, peer, || async move {
                requests::confirmed_response::send_overload_response(
                    &network,
                    &Apdu::Abort(AbortPdu {
                        sent_by_server: true,
                        invoke_id,
                        abort_reason: AbortReason::OUT_OF_RESOURCES,
                    }),
                    &mac,
                    source.as_ref(),
                    &route,
                    reply_tx,
                )
                .await;
            });
    }

    /// Dispatch a received APDU.
    ///
    /// ConfirmedRequest and UnconfirmedRequest handlers are spawned as
    /// independent tasks so the dispatch loop can immediately process the
    /// next incoming APDU.  This allows the server to handle multiple
    /// client requests concurrently (e.g. concurrent ReadProperty via
    /// the RwLock on ObjectDatabase).
    ///
    /// Fast-path APDU types (SimpleAck, Error, Reject, Abort, SegmentAck)
    /// remain inline since they are sub-microsecond TSM lookups.
    pub(super) async fn dispatch(
        ctx: &DispatchContext<T>,
        source_mac: &[u8],
        apdu: Apdu,
        mut received: bacnet_network::layer::ReceivedApdu,
    ) {
        let DispatchContext {
            services,
            confirmed_request_tracker,
            clock: _,
            discovery_limiter,
            time_sync_limiter: _,
            request_tasks,
        } = ctx;
        let RequestServices {
            network,
            seg_ack_senders,
            learned_routers,
            notification_transactions,
            ..
        } = &**services;
        if notification_transactions
            .application_sealed
            .load(Ordering::Acquire)
            && matches!(
                apdu,
                Apdu::ConfirmedRequest(_) | Apdu::UnconfirmedRequest(_)
            )
        {
            return;
        }
        // Ingress provenance travels with `received` into request diagnostics
        // and authorization. NotificationTransactions owns outgoing terminal
        // admission; learned_routers stores only next hops from admitted replies.
        let route = received.response_route();
        match apdu {
            Apdu::ConfirmedRequest(req) => {
                // LSO-only replay path (server level, separate budget).
                // Retransmitted already-executed confirmed LSO within the
                // window resends byte-identical bytes with a single execution.
                // Pending in-flight duplicates preserve DISCARD. This is a
                // local service-specific extension, not a Standard mandate.
                if req.service_choice == ConfirmedServiceChoice::LIFE_SAFETY_OPERATION {
                    let lso_pending = match confirmed_request_tracker.lso.begin(
                        source_mac,
                        received.source_network.as_ref(),
                        received.provenance.clone(),
                        req.clone(),
                    ) {
                        LsoAdmission::Replay(bytes) => {
                            let reply_tx = received.reply_tx.take();
                            let replay_mac = MacAddr::from_slice(source_mac);
                            let replay_network = received.source_network.clone();
                            requests::confirmed_response::send_replay_bytes(
                                network,
                                &bytes,
                                &replay_mac,
                                replay_network.as_ref(),
                                &route,
                                reply_tx,
                            )
                            .await;
                            return;
                        }
                        LsoAdmission::DuplicatePending => return,
                        LsoAdmission::New(pending) => pending,
                    };
                    let invoke_id = req.invoke_id;
                    let mut reply_tx = received.reply_tx.take();
                    let services = services.clone();
                    let requester_mac = MacAddr::from_slice(source_mac);
                    let source_network = received.source_network.clone();
                    let descendants = request_tasks.spawner();
                    let peer = super::request_peer::canonical_requester(
                        &requester_mac,
                        source_network.as_ref(),
                    );
                    let class = super::request_admission::confirmed_class(
                        req.service_choice,
                        &req.service_request,
                    );
                    let result = request_tasks.try_spawn(class, peer, || {
                        let reply_tx = reply_tx.take();
                        async move {
                            Self::handle_admitted_confirmed_request(
                                &services,
                                &descendants,
                                RequestOrigin {
                                    mac: &requester_mac,
                                    network: source_network,
                                    route,
                                },
                                req,
                                reply_tx,
                                Some(ConfirmedRequestOwnership::LifeSafety(lso_pending)),
                            )
                            .await;
                        }
                    });
                    if result == Err(Rejection::Overloaded) {
                        Self::spawn_overload_abort(ctx, source_mac, &received, invoke_id, reply_tx);
                    }
                    return;
                }
                let pending = match confirmed_request_tracker.begin(
                    source_mac,
                    received.source_network.as_ref(),
                    received.provenance.clone(),
                    req.clone(),
                ) {
                    ConfirmedRequestAdmission::Duplicate => return,
                    ConfirmedRequestAdmission::New(pending) => pending,
                };
                let invoke_id = req.invoke_id;
                let mut reply_tx = received.reply_tx.take();
                let services = services.clone();
                let requester_mac = MacAddr::from_slice(source_mac);
                let source_network = received.source_network.clone();
                let descendants = request_tasks.spawner();
                let peer = super::request_peer::canonical_requester(
                    &requester_mac,
                    source_network.as_ref(),
                );
                let class = super::request_admission::confirmed_class(
                    req.service_choice,
                    &req.service_request,
                );
                let result = request_tasks.try_spawn(class, peer, || {
                    Self::run_admitted_confirmed_request(requests::read_property::AdmittedRequest {
                        services,
                        request_tasks: descendants,
                        source_mac: requester_mac,
                        source_network,
                        route,
                        req,
                        reply_tx: reply_tx.take(),
                        ownership: Some(ConfirmedRequestOwnership::Generic(pending)),
                    })
                });
                if result == Err(Rejection::Overloaded) {
                    // ASHRAE 135-2020 §§5.4.5.3, 18.10: resource exhaustion
                    // before service execution is reported by a server Abort.
                    // Eight owned sends bound this response work. If all are
                    // busy, the counted silent drop is a known local limitation.
                    Self::spawn_overload_abort(ctx, source_mac, &received, invoke_id, reply_tx);
                }
            }
            Apdu::UnconfirmedRequest(req) => {
                let now = runtime_clock::now();
                if req.service_choice == UnconfirmedServiceChoice::WHO_IS {
                    match discovery_limiter.pre_check_who_is(&req.service_request, &received, now) {
                        PreCheckDecision::Admit => {}
                        PreCheckDecision::OutOfRange => {
                            debug!("WhoIs instance range does not include local device; dropped");
                            return;
                        }
                        PreCheckDecision::Coalesced => {
                            debug!("WhoIs duplicate coalesced within window");
                            return;
                        }
                        PreCheckDecision::ThrottledSource => {
                            debug!("WhoIs throttled: source rate/byte limit exceeded");
                            return;
                        }
                        PreCheckDecision::ThrottledGlobal => {
                            debug!("WhoIs throttled: global rate/byte limit exceeded");
                            return;
                        }
                        // Nothing can answer it: drop it here, before a
                        // task is spawned and it is decoded again.
                        PreCheckDecision::DecodeError => {
                            debug!("Malformed WhoIs dropped");
                            return;
                        }
                    }
                } else if req.service_choice == UnconfirmedServiceChoice::WHO_HAS {
                    match discovery_limiter.pre_check_who_has(&req.service_request, &received, now)
                    {
                        PreCheckDecision::Admit => {}
                        PreCheckDecision::OutOfRange => {
                            debug!("WhoHas instance range does not include local device; dropped");
                            return;
                        }
                        PreCheckDecision::Coalesced => {
                            debug!("WhoHas duplicate/negative coalesced within window");
                            return;
                        }
                        PreCheckDecision::ThrottledSource => {
                            debug!("WhoHas throttled: source rate/byte limit exceeded");
                            return;
                        }
                        PreCheckDecision::ThrottledGlobal => {
                            debug!("WhoHas throttled: global rate/byte limit exceeded");
                            return;
                        }
                        PreCheckDecision::DecodeError => {
                            debug!("Malformed WhoHas dropped");
                            return;
                        }
                    }
                }

                let services = ctx.unconfirmed_services();
                let peer = super::request_peer::canonical_requester(
                    source_mac,
                    received.source_network.as_ref(),
                );
                let _ = request_tasks.try_spawn(Class::Unconfirmed, peer, || async move {
                    Self::handle_unconfirmed_request(&services, req, &received).await;
                });
            }
            // Fast paths — remain inline (bounded synchronous admission)
            Apdu::SimpleAck(sa) => {
                let invoke_id = sa.invoke_id;
                let admitted = Self::admit_notification_terminal(
                    learned_routers,
                    notification_transactions,
                    source_mac,
                    received.source_network.as_ref(),
                    network.local_network_number().get(),
                    &Apdu::SimpleAck(sa),
                )
                .await;
                debug!(
                    invoke_id,
                    admitted, "SimpleAck received for outgoing confirmed notification"
                );
            }
            Apdu::Error(err) => {
                let invoke_id = err.invoke_id;
                let error_class = err.error_class.to_raw();
                let error_code = err.error_code.to_raw();
                let admitted = Self::admit_notification_terminal(
                    learned_routers,
                    notification_transactions,
                    source_mac,
                    received.source_network.as_ref(),
                    network.local_network_number().get(),
                    &Apdu::Error(err),
                )
                .await;
                debug!(
                    invoke_id,
                    error_class,
                    error_code,
                    admitted,
                    "Error received for outgoing confirmed notification"
                );
            }
            Apdu::Reject(rej) => {
                let invoke_id = rej.invoke_id;
                let admitted = Self::admit_notification_terminal(
                    learned_routers,
                    notification_transactions,
                    source_mac,
                    received.source_network.as_ref(),
                    network.local_network_number().get(),
                    &Apdu::Reject(rej),
                )
                .await;
                debug!(
                    invoke_id,
                    admitted, "Reject received for outgoing confirmed notification"
                );
            }
            Apdu::Abort(abort) => {
                let invoke_id = abort.invoke_id;
                let routed_segmented = if abort.sent_by_server {
                    false
                } else {
                    let key = segmented_transaction_key(
                        source_mac,
                        received.source_network.as_ref(),
                        invoke_id,
                        route.provenance(),
                    );
                    Self::route_segmented_send_event(
                        seg_ack_senders,
                        key,
                        SegmentedSendEvent::Abort(abort.clone()),
                    )
                    .await
                };
                let admitted = Self::admit_notification_terminal(
                    learned_routers,
                    notification_transactions,
                    source_mac,
                    received.source_network.as_ref(),
                    network.local_network_number().get(),
                    &Apdu::Abort(abort),
                )
                .await;
                debug!(
                    invoke_id,
                    routed_segmented,
                    admitted,
                    "Abort received for outgoing confirmed notification or segmented response"
                );
            }
            Apdu::SegmentAck(sa) => {
                let invoke_id = sa.invoke_id;
                if sa.sent_by_server {
                    debug!(
                        invoke_id,
                        seq = sa.sequence_number,
                        "Server ignoring SegmentAck with server bit set"
                    );
                    return;
                }

                let key = segmented_transaction_key(
                    source_mac,
                    received.source_network.as_ref(),
                    invoke_id,
                    route.provenance(),
                );
                if !Self::route_segmented_send_event(
                    seg_ack_senders,
                    key,
                    SegmentedSendEvent::SegmentAck(sa),
                )
                .await
                {
                    debug!(
                        invoke_id,
                        "Server ignoring SegmentAck for unknown transaction"
                    );
                }
            }
            Apdu::ComplexAck(ack) => {
                let invoke_id = ack.invoke_id;
                let admitted = Self::admit_notification_terminal(
                    learned_routers,
                    notification_transactions,
                    source_mac,
                    received.source_network.as_ref(),
                    network.local_network_number().get(),
                    &Apdu::ComplexAck(ack),
                )
                .await;
                if admitted {
                    debug!(invoke_id, "ComplexAck answered a read this server sent");
                } else {
                    debug!(invoke_id, "Server ignoring ComplexAck it has no read for");
                }
            }
        }
    }
}