bacnet-endpoint 0.15.0

BACnet endpoint that owns one transport and runs client and server roles through it
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
//! Session-private source Audit ownership. No discovery cache or persistent outbox.
use std::net::Ipv4Addr;
use std::sync::{Arc, Weak};

use bacnet_client::{
    EndpointOperationAck, EndpointOperationRequest, EndpointReadAck, EndpointReadRequest,
    EndpointRequester,
};
use bacnet_endpoint_core::coordinator::CanonicalPeer;
use bacnet_endpoint_core::endpoint_ingress::{EndpointApduDestination, EndpointEgress};
use bacnet_objects::audit::AuditReporterStatus;
use bacnet_objects::database::ObjectDatabase;
use bacnet_objects::traits::BACnetObject;
use bacnet_server::server::{
    __endpoint_AuditFailureContext as AuditFailureContext,
    __endpoint_AuditFailureQueue as AuditFailureQueue,
    __endpoint_AuditFailureTicket as AuditFailureTicket,
    __endpoint_NotificationTransactions as NotificationTransactions,
};
use bacnet_transport::bvll::decode_bip_mac;
use bacnet_transport::port::DataAttribute;
use bacnet_types::MacAddr;
use bacnet_types::bitstring::AuditOperationFlags;
use bacnet_types::constructed::{
    AuditPropertyReference, BACnetAddress, BACnetAuditNotification, BACnetRecipient,
};
use bacnet_types::enums::{AuditLevel, AuditOperation, ObjectType, PropertyIdentifier};
use bacnet_types::error::Error;
use bacnet_types::primitives::{BACnetTimeStamp, ObjectIdentifier, PropertyValue};
use tokio::sync::{RwLock, Semaphore, oneshot};

#[path = "source_recipient.rs"]
pub(crate) mod recipient;
use bacnet_objects::database::AuditOwnership;
use bacnet_objects::device::AuditRecipientChangeSink;
use recipient::{SourceRecipient, SourceRoutes};

#[path = "source_audit_delivery.rs"]
mod delivery;
#[path = "source_audit_failures.rs"]
mod failures;

pub(crate) struct SourceAudit {
    /// Released off the runtime by whichever caller, worker or session
    /// drops the source last (#1561).
    db: crate::held_database::HeldDatabase,
    selected: ObjectIdentifier,
    device: ObjectIdentifier,
    runtime: Weak<SourceRecipient>,
    broadcast: Ipv4Addr,
    egress: EndpointEgress,
    notifications: Weak<NotificationTransactions>,
    operations: Arc<Semaphore>,
    max_apdu: u16,
    failures: Arc<AuditFailureQueue<MacAddr>>,
    #[cfg(test)]
    pub(crate) summary_queue_full: tokio::sync::Notify,
}

impl SourceAudit {
    pub(crate) fn new(
        db: Arc<RwLock<ObjectDatabase>>,
        selected: ObjectIdentifier,
        routes: SourceRoutes,
        broadcast: Ipv4Addr,
        egress: EndpointEgress,
        notifications: &Arc<NotificationTransactions>,
        max_apdu: u16,
    ) -> Result<(Arc<Self>, Arc<SourceRecipient>), Error> {
        let mut database = db.try_write().expect("unshared startup database");
        let device = database
            .local_device()
            .identifier()
            .expect("preflight local Device");
        let status = database
            .get(&selected)
            .and_then(|object| object.audit_reporter_internal())
            .expect("preflight Reporter")
            .status_internal();
        let initial = database
            .get_mut(&device)
            .and_then(|object| object.device_authority_internal())
            .and_then(|authority| authority.provisioned_audit_recipient().cloned())
            .expect("preflight recipient");
        routes.validate_initial(&initial)?;
        status.set_configured(routes.resolve(&initial).is_some());
        let failures = Arc::new(AuditFailureQueue::default());
        let runtime = Arc::new(SourceRecipient {
            device,
            status,
            routes,
            owner: AuditOwnership::for_source(device, selected),
            sequence: database.event_sequence_internal(),
            egress: egress.clone(),
            notifications: Arc::downgrade(notifications),
            max_apdu,
            failures: Arc::clone(&failures),
        });
        let source = Arc::new(Self {
            db: crate::held_database::HeldDatabase::new(Arc::clone(&db)),
            selected,
            device,
            runtime: Arc::downgrade(&runtime),
            broadcast,
            egress,
            notifications: Arc::downgrade(notifications),
            operations: Arc::new(Semaphore::new(64)),
            max_apdu,
            failures,
            #[cfg(test)]
            summary_queue_full: tokio::sync::Notify::new(),
        });
        database
            .with_object_adapter(&selected, |slot| {
                crate::session::source_reporter::install(slot, &runtime.owner)
            })?
            .expect("preflight Reporter")?;
        let sink: Arc<dyn AuditRecipientChangeSink> = runtime.clone();
        database
            .get_mut(&device)
            .unwrap()
            .device_authority_internal()
            .unwrap()
            .install_audit_recipient(&sink)?;
        database.protect_audit_internal(&runtime.owner)?;
        notifications.set_audit_owner(&runtime.owner);
        Ok((source, runtime))
    }

    #[cfg(test)]
    pub(crate) fn available_operations(&self) -> usize {
        self.operations.available_permits()
    }

    pub(crate) fn close(&self) {
        if let Some(runtime) = self.runtime.upgrade() {
            runtime.seal();
        }
        self.operations.close();
    }

    pub(crate) async fn read(
        self: &Arc<Self>,
        requester: &EndpointRequester,
        destination: EndpointApduDestination,
        attributes: Vec<DataAttribute>,
        request: EndpointReadRequest,
    ) -> Result<EndpointReadAck, Error> {
        self.operate(
            requester,
            destination,
            attributes,
            EndpointOperationRequest::Read(request),
            None,
        )
        .await?
        .into_read()
    }

    pub(crate) async fn write(
        self: &Arc<Self>,
        requester: &EndpointRequester,
        destination: EndpointApduDestination,
        request: bacnet_services::write_property::WritePropertyRequest,
        commandability: crate::roles::Commandability,
    ) -> Result<(), Error> {
        let priority = match commandability {
            crate::roles::Commandability::Commandable => Some(request.priority.unwrap_or(16)),
            crate::roles::Commandability::Noncommandable => None,
        };
        self.operate(
            requester,
            destination,
            Vec::new(),
            EndpointOperationRequest::Write(request),
            priority,
        )
        .await?
        .into_write()
    }

    async fn operate(
        self: &Arc<Self>,
        requester: &EndpointRequester,
        destination: EndpointApduDestination,
        attributes: Vec<DataAttribute>,
        request: EndpointOperationRequest,
        command_priority: Option<u8>,
    ) -> Result<EndpointOperationAck, Error> {
        request.validate()?;
        let identities = request.identities();
        let audit_operation = match &request {
            EndpointOperationRequest::Read(_) => AuditOperation::READ,
            EndpointOperationRequest::Write(_) => AuditOperation::WRITE,
        };
        let target_value = match &request {
            EndpointOperationRequest::Write(write) if write.property_value.len() <= 32 => {
                Some(write.property_value.clone())
            }
            _ => None,
        };
        // Wait for the destination's turn first (#1542), in the caller's
        // task: a wait holds no admission permit and no database guard, a
        // caller giving up then cancels nothing admitted, and the record's
        // timestamp below is taken once the request may go.
        let operation = requester
            .pace_operation(destination, attributes, request)
            .await?;
        // Bound every retained operation, including time before lease acquisition
        // and after dispatch releases the request lease. Never spawn permit waiters.
        let permit = Arc::clone(&self.operations)
            .try_acquire_owned()
            .map_err(|_| Error::Encoding("source Audit admission is closed or full".into()))?;
        let mut db = self.db.write().await;
        if self.operations.is_closed() {
            return Err(Error::Encoding("endpoint shutdown".into()));
        }
        let runtime = self
            .runtime
            .upgrade()
            .filter(|runtime| runtime.owner.is_active())
            .ok_or_else(|| Error::Encoding("endpoint shutdown".into()))?;
        let reporter = db
            .get(&self.selected)
            .and_then(|object| object.audit_reporter_internal())
            .ok_or_else(|| Error::Encoding("source Reporter is unavailable".into()))?;
        if reporter
            .property_list()
            .contains(&PropertyIdentifier::MONITORED_OBJECTS)
        {
            reporter.status_internal().set_configured(false);
            return Err(Error::Encoding(
                "source Audit does not support Monitored_Objects".into(),
            ));
        }
        let level = match reporter.read_property(PropertyIdentifier::AUDIT_LEVEL, None)? {
            PropertyValue::Enumerated(level) => AuditLevel::from_raw(level),
            _ => return Err(Error::Encoding("invalid source audit level".into())),
        };
        let operations =
            match reporter.read_property(PropertyIdentifier::AUDITABLE_OPERATIONS, None)? {
                PropertyValue::BitString { unused_bits, data } => {
                    AuditOperationFlags::from_bacnet(unused_bits, &data)?
                }
                _ => return Err(Error::Encoding("invalid source operation flags".into())),
            };
        let priority_allowed = if let Some(priority) = command_priority {
            match reporter.read_property(PropertyIdentifier::AUDIT_PRIORITY_FILTER, None)? {
                PropertyValue::BitString { unused_bits, data } => {
                    bacnet_types::bitstring::BACnetPriorityFilter::from_bacnet(unused_bits, &data)?
                        .contains(priority)
                }
                _ => return Err(Error::Encoding("invalid source priority filter".into())),
            }
        } else {
            true
        };
        let eligible: Vec<_> = identities
            .into_iter()
            .enumerate()
            .filter(|(_, (_, property, _))| {
                level != AuditLevel::NONE
                    && operations.contains(audit_operation)
                    && priority_allowed
                    && !(level == AuditLevel::AUDIT_CONFIG
                        && *property == PropertyIdentifier::PRESENT_VALUE)
            })
            .collect();
        if eligible.is_empty() {
            drop(db);
            drop(runtime);
            drop(permit);
            return operation.prepare()?.execute().await.result;
        }
        let status = reporter.status_internal();
        let confirmed = reporter.confirmed_internal();
        let route = runtime.recipient_route(&db);
        status.set_configured(route.is_some());
        let Some(route) = route else {
            drop(db);
            drop(runtime);
            drop(permit);
            return operation.prepare()?.execute().await.result;
        };
        // A routed destination on this network goes to the station directly
        // (#1403), as pacing localized it, so it is audited as the direct
        // operation it is.
        let EndpointApduDestination::Direct { destination_mac } = operation.destination() else {
            return Err(Error::Encoding(
                "audited operation requires direct B/IP IPv4 unicast".into(),
            ));
        };
        let destination_mac = destination_mac.clone();
        let (ip, port) = decode_bip_mac(&destination_mac)?;
        let ip = Ipv4Addr::from(ip);
        if ip.is_unspecified()
            || ip.is_multicast()
            || ip.is_broadcast()
            || ip == self.broadcast
            || port == 0
        {
            return Err(Error::Encoding(
                "audited operation requires direct B/IP IPv4 unicast".into(),
            ));
        }
        let device = self.device;
        if db.local_device().identifier() != Some(device) {
            status.set_configured(false);
            return Err(Error::Encoding("source Device is unavailable".into()));
        }
        let operation = operation.prepare()?;
        let timestamp = match db
            .clock_frame()
            .filter(|frame| frame.is_valid_actual_datetime())
        {
            Some(frame) => BACnetTimeStamp::DateTime {
                date: frame.local_date,
                time: frame.local_time,
            },
            None => BACnetTimeStamp::SequenceNumber(db.next_event_sequence_number()),
        };
        let failure = status.auditing_failure_epoch().and_then(|epoch| {
            self.failures.observe(AuditFailureContext {
                status: Arc::clone(&status),
                epoch,
                device,
                confirmed,
                peer: CanonicalPeer::direct(route.as_slice()),
                route: route.clone(),
                max_apdu: u32::from(self.max_apdu),
            })
        });
        let completion = status.begin_delivery();
        let notification = BACnetAuditNotification {
            source_timestamp: Some(timestamp),
            target_timestamp: None,
            source_device: BACnetRecipient::Device(device),
            source_object: None,
            operation: audit_operation,
            source_comment: None,
            target_comment: None,
            invoke_id: Some(operation.invoke_id()),
            source_user_id: None,
            source_user_role: None,
            target_device: BACnetRecipient::Address(BACnetAddress {
                network_number: 0,
                mac_address: destination_mac,
            }),
            target_object: None,
            target_property: None,
            target_priority: command_priority,
            target_value,
            current_value: None,
            result: None,
        };
        status.set_configured(true);
        drop(db);
        drop(runtime);
        let owner = self
            .notifications
            .upgrade()
            .ok_or_else(|| Error::Encoding("endpoint shutdown".into()))?;
        let weak_owner = Arc::downgrade(&owner);
        let source = Arc::clone(self);
        let (reply, response) = oneshot::channel();
        // Spawn/close are serialized by the same worker owner. A rejected spawn
        // drops the operation, permit and reply. The worker never retains owner.
        owner.spawn(async move {
            let _permit = permit;
            let outcome = operation.execute().await;
            if outcome.attempted {
                // Correlation of the complete ACK precedes every occurrence's
                // projection. Whole-operation failure fans out the same failure.
                let results = outcome
                    .result
                    .as_ref()
                    .ok()
                    .and_then(EndpointOperationAck::as_read)
                    .map(EndpointReadAck::audit_results);
                let device = outcome
                    .result
                    .as_ref()
                    .ok()
                    .and_then(EndpointOperationAck::as_read)
                    .and_then(EndpointReadAck::target_device);
                if let Some(owner) = weak_owner.upgrade() {
                    for (position, (object, property, index)) in eligible {
                        let mut record = notification.clone();
                        record.target_object = Some(object);
                        record.target_property = Some(AuditPropertyReference {
                            property_identifier: property,
                            property_array_index: index.map(u64::from),
                        });
                        if let Some(results) = &results {
                            record.target_object = Some(results[position].0);
                            record.result = results[position].1;
                        } else {
                            record.result = delivery::result(&outcome.result);
                        }
                        if let Some(device) = device {
                            record.target_device = BACnetRecipient::Device(device);
                        }
                        delivery::admit(
                            &source,
                            &owner,
                            confirmed,
                            route.clone(),
                            record,
                            delivery::Completion::new(Arc::clone(&status), completion),
                            failure.clone(),
                        );
                    }
                }
            }
            let _ = reply.send(outcome.result);
        });
        drop(owner);
        response
            .await
            .map_err(|_| Error::Encoding("endpoint shutdown".into()))?
    }

    /// Report an operation a peer carried out on this device as a whole,
    /// such as an accepted ReinitializeDevice reset, backup or restore step
    /// (Clause 19.6, Table 19-5, #1564), with `source` as its requester.
    ///
    /// Clause 19.6.2 casts this Reporter as the source-side one; sending
    /// these target-side records through it, the session's only Reporter,
    /// is a local choice.
    ///
    /// The session's one Reporter filters it by its Audit_Level and
    /// Auditable_Operations. The record names this Device as its target and
    /// no object, property or value, carries the target timestamp, and has
    /// no Result: only an operation carried out is reported. It goes to the
    /// Device's recipient as the source records do, admitted before this
    /// returns. Called under the database guard.
    pub(crate) fn device_operation(
        self: &Arc<Self>,
        db: &mut ObjectDatabase,
        operation: AuditOperation,
        source: &bacnet_objects::device::AuditWriteSource,
    ) {
        if self.operations.is_closed() {
            return;
        }
        let Some(runtime) = self
            .runtime
            .upgrade()
            .filter(|runtime| runtime.owner.is_active())
        else {
            return;
        };
        let Some(reporter) = db
            .get(&self.selected)
            .and_then(|object| object.audit_reporter_internal())
        else {
            return;
        };
        let level = match reporter.read_property(PropertyIdentifier::AUDIT_LEVEL, None) {
            Ok(PropertyValue::Enumerated(level)) => AuditLevel::from_raw(level),
            _ => return,
        };
        let operations =
            match reporter.read_property(PropertyIdentifier::AUDITABLE_OPERATIONS, None) {
                Ok(PropertyValue::BitString { unused_bits, data }) => {
                    match AuditOperationFlags::from_bacnet(unused_bits, &data) {
                        Ok(operations) => operations,
                        Err(_) => return,
                    }
                }
                _ => return,
            };
        if level == AuditLevel::NONE || !operations.contains(operation) {
            return;
        }
        let status = reporter.status_internal();
        let confirmed = reporter.confirmed_internal();
        let route = runtime.recipient_route(db);
        status.set_configured(route.is_some());
        let (Some(route), Some(owner)) = (route, self.notifications.upgrade()) else {
            return;
        };
        let device = self.device;
        if db.local_device().identifier() != Some(device) {
            status.set_configured(false);
            return;
        }
        let timestamp = match db
            .clock_frame()
            .filter(|frame| frame.is_valid_actual_datetime())
        {
            Some(frame) => BACnetTimeStamp::DateTime {
                date: frame.local_date,
                time: frame.local_time,
            },
            None => BACnetTimeStamp::SequenceNumber(db.next_event_sequence_number()),
        };
        let failure = status.auditing_failure_epoch().and_then(|epoch| {
            self.failures.observe(AuditFailureContext {
                status: Arc::clone(&status),
                epoch,
                device,
                confirmed,
                peer: CanonicalPeer::direct(route.as_slice()),
                route: route.clone(),
                max_apdu: u32::from(self.max_apdu),
            })
        });
        let completion = delivery::Completion::new(Arc::clone(&status), status.begin_delivery());
        let record = BACnetAuditNotification {
            source_timestamp: None,
            target_timestamp: Some(timestamp),
            source_device: source.device.clone(),
            source_object: None,
            operation,
            source_comment: None,
            target_comment: None,
            invoke_id: Some(source.invoke_id),
            source_user_id: None,
            source_user_role: None,
            target_device: BACnetRecipient::Device(device),
            target_object: None,
            target_property: None,
            target_priority: None,
            target_value: None,
            current_value: None,
            result: None,
        };
        delivery::admit(self, &owner, confirmed, route, record, completion, failure);
    }
}

#[cfg(test)]
#[path = "source_read_failure_admission_tests.rs"]
mod failure_admission_tests;