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
use super::*;
use bacnet_server::server::ReinitializeContext;
use bacnet_types::enums::{ErrorClass, ErrorCode, ReinitializedState};
use bacnet_types::error::RemoteError;
use std::net::Ipv4Addr;

const PASSWORD: &str = "reinit-pw";

type Builder = crate::bip::BipEndpointBuilder;
type Client = bacnet_client::client::BACnetClient<bacnet_transport::bip::BipTransport>;
type Received = Arc<std::sync::Mutex<Vec<ReinitializeContext>>>;

/// A handler that records the context of each request it carries out.
fn recording(
    received: &Received,
) -> impl Fn(&ReinitializeContext, &mut ObjectDatabase) -> Result<(), Error>
+ Send
+ Sync
+ 'static
+ use<> {
    let recorded = Arc::clone(received);
    move |context: &ReinitializeContext, _: &mut ObjectDatabase| {
        recorded.lock().unwrap().push(context.clone());
        Ok(())
    }
}

fn states(received: &Received) -> Vec<ReinitializedState> {
    received.lock().unwrap().iter().map(|c| c.state).collect()
}

/// A running B/IP endpoint for Device 123, composed by `configure`, a client
/// to reach it, and the endpoint's B/IP address.
async fn running(
    configure: impl FnOnce(Builder) -> Builder,
) -> (
    EndpointSession<bacnet_transport::bip::BipTransport>,
    Client,
    [u8; 6],
) {
    let identity = crate::DeviceIdentity::new(123, 42).unwrap();
    let db = crate::identity::build_database_with_extra(&identity, vec![]).unwrap();
    let builder = Builder::new(Ipv4Addr::LOCALHOST, 0, Ipv4Addr::BROADCAST)
        .role(SessionRole::ServerOnly)
        .database(db)
        .device(identity);
    let mut endpoint = configure(builder).build_session().unwrap();
    endpoint.start().await.unwrap();
    // The endpoint bound port 0; the client talks to the port it actually got.
    let port = endpoint.bip_local_address().unwrap().port();
    let client = Client::bip_builder()
        .interface(Ipv4Addr::LOCALHOST)
        .port(0)
        .build()
        .await
        .unwrap();
    let mac = bacnet_transport::bvll::encode_bip_mac([127, 0, 0, 1], port);
    (endpoint, client, mac)
}

/// The Device's Protocol_Services_Supported, as bit positions.
async fn advertised(client: &Client, mac: &[u8; 6]) -> Vec<usize> {
    let ack = client
        .read_property(
            mac,
            oid(123),
            PropertyIdentifier::PROTOCOL_SERVICES_SUPPORTED,
            None,
        )
        .await
        .unwrap();
    let (profile, _) =
        bacnet_encoding::primitives::decode_application_value(&ack.property_value, 0).unwrap();
    services(profile)
}

async fn reinitialize(
    client: &Client,
    mac: &[u8; 6],
    state: ReinitializedState,
    password: Option<&str>,
) -> Result<(), Error> {
    tokio::time::timeout(
        Duration::from_secs(3),
        client.reinitialize_device(mac, state, password.map(str::to_owned)),
    )
    .await
    .expect("the endpoint answers")
}

fn assert_protocol_error(result: Result<(), Error>, class: ErrorClass, code: ErrorCode) {
    let error = result.unwrap_err();
    assert!(
        matches!(error, Error::Remote(RemoteError::Error { class: c, code: e })
            if c == class && e == code),
        "got {error:?}"
    );
}

/// `start` refuses with an error naming `expected`.
async fn assert_refused(
    session: &mut EndpointSession<impl TransportPort + 'static>,
    expected: &str,
) {
    let error = session.start().await.unwrap_err();
    assert!(error.to_string().contains(expected), "got {error}");
}

#[tokio::test]
async fn reinitialize_device_reaches_the_handler() {
    let received = Received::default();
    let (mut endpoint, mut client, mac) = running(|builder| {
        builder
            .reinitialize(recording(&received))
            .reinit_password(PASSWORD)
    })
    .await;

    reinitialize(
        &client,
        &mac,
        ReinitializedState::START_BACKUP,
        Some(PASSWORD),
    )
    .await
    .unwrap();
    assert_eq!(states(&received), vec![ReinitializedState::START_BACKUP]);
    let context = received.lock().unwrap()[0].clone();
    assert_eq!(context.source_mac.len(), 6);
    assert_eq!(context.source_network, None);

    // The Device advertises exactly what the responder executes.
    assert_eq!(advertised(&client, &mac).await, vec![12, 20]);

    client.stop().await.unwrap();
    endpoint.stop().await.unwrap();
}

#[tokio::test]
async fn a_wrong_password_never_reaches_the_handler() {
    let received = Received::default();
    let (mut endpoint, mut client, mac) = running(|builder| {
        builder
            .reinitialize(recording(&received))
            .reinit_password(PASSWORD)
    })
    .await;

    assert_protocol_error(
        reinitialize(
            &client,
            &mac,
            ReinitializedState::START_BACKUP,
            Some("wrong"),
        )
        .await,
        ErrorClass::SECURITY,
        ErrorCode::PASSWORD_FAILURE,
    );
    assert!(received.lock().unwrap().is_empty());

    client.stop().await.unwrap();
    endpoint.stop().await.unwrap();
}

/// With no password configured, any request reaches the handler, with or
/// without a password of its own.
#[tokio::test]
async fn without_a_password_any_request_reaches_the_handler() {
    let received = Received::default();
    let (mut endpoint, mut client, mac) =
        running(|builder| builder.reinitialize(recording(&received))).await;

    reinitialize(&client, &mac, ReinitializedState::WARMSTART, None)
        .await
        .unwrap();
    reinitialize(
        &client,
        &mac,
        ReinitializedState::ACTIVATE_CHANGES,
        Some("anything"),
    )
    .await
    .unwrap();
    assert_eq!(
        states(&received),
        vec![
            ReinitializedState::WARMSTART,
            ReinitializedState::ACTIVATE_CHANGES
        ]
    );

    client.stop().await.unwrap();
    endpoint.stop().await.unwrap();
}

/// With Device writes and ReinitializeDevice both enabled, the Device
/// advertises ReadProperty, WriteProperty and ReinitializeDevice, and
/// executes each.
#[tokio::test]
async fn read_write_and_reinitialize_are_advertised_together() {
    let received = Received::default();
    let (mut endpoint, mut client, mac) = running(|builder| {
        builder
            .device_writes(Arc::new(|_| true))
            .reinitialize(recording(&received))
    })
    .await;

    assert_eq!(advertised(&client, &mac).await, vec![12, 15, 20]);
    let mut value = BytesMut::new();
    bacnet_encoding::primitives::encode_app_character_string(&mut value, "both").unwrap();
    client
        .write_property(
            &mac,
            oid(123),
            PropertyIdentifier::DESCRIPTION,
            None,
            value.to_vec(),
            None,
        )
        .await
        .unwrap();
    assert_eq!(
        read(&endpoint, PropertyIdentifier::DESCRIPTION).await,
        PropertyValue::CharacterString("both".into())
    );
    reinitialize(&client, &mac, ReinitializedState::COLDSTART, None)
        .await
        .unwrap();
    assert_eq!(states(&received), vec![ReinitializedState::COLDSTART]);

    client.stop().await.unwrap();
    endpoint.stop().await.unwrap();
}

/// A panicking handler is answered SERVICES / OTHER, and the session's
/// dispatch survives it: a ReadProperty afterwards still succeeds.
#[tokio::test]
async fn a_panicking_handler_is_answered_and_the_session_keeps_serving() {
    let (mut endpoint, mut client, mac) = running(|builder| {
        builder.reinitialize(|_: &ReinitializeContext, _: &mut ObjectDatabase| {
            panic!("reinitialize handler panic")
        })
    })
    .await;

    assert_protocol_error(
        reinitialize(&client, &mac, ReinitializedState::WARMSTART, None).await,
        ErrorClass::SERVICES,
        ErrorCode::OTHER,
    );
    let name = tokio::time::timeout(
        Duration::from_secs(3),
        client.read_property(&mac, oid(123), PropertyIdentifier::OBJECT_NAME, None),
    )
    .await
    .expect("the session still answers")
    .unwrap();
    assert!(!name.property_value.is_empty());

    client.stop().await.unwrap();
    endpoint.stop().await.unwrap();
}

/// An identity may not advertise ReinitializeDevice unless the session executes it.
#[tokio::test]
async fn an_identity_advertising_reinitialize_needs_a_handler() {
    let (transport, _peer) = LoopbackTransport::pair(vec![0x01], vec![0x02]);
    let identity = crate::DeviceIdentity::new(123, 42)
        .unwrap()
        .with_services(&[
            ServiceSupported::READ_PROPERTY,
            ServiceSupported::REINITIALIZE_DEVICE,
        ]);
    let db = crate::identity::build_database_with_extra(&identity, vec![]).unwrap();
    let mut session =
        EndpointSession::new(transport, SessionRole::ServerOnly, SessionConfig::default())
            .unwrap()
            .with_database(db)
            .device(identity);

    assert_refused(
        &mut session,
        "Endpoint identity services do not match the responder's services",
    )
    .await;
}

#[tokio::test]
async fn reinitialize_needs_a_server_role() {
    let (transport, _peer) = LoopbackTransport::pair(vec![0x01], vec![0x02]);
    let mut session =
        EndpointSession::new(transport, SessionRole::ClientOnly, SessionConfig::default())
            .unwrap()
            .with_reinitialize(|_: &ReinitializeContext, _: &mut ObjectDatabase| Ok(()));
    assert_refused(&mut session, "ReinitializeDevice requires a server role").await;

    // With Device writes enabled too, the refusal names both.
    let (transport, _peer) = LoopbackTransport::pair(vec![0x01], vec![0x02]);
    let mut session =
        EndpointSession::new(transport, SessionRole::ClientOnly, SessionConfig::default())
            .unwrap()
            .with_device_writes(Arc::new(|_| true))
            .with_reinitialize(|_: &ReinitializeContext, _: &mut ObjectDatabase| Ok(()));
    assert_refused(
        &mut session,
        "Device writes and ReinitializeDevice require a server role",
    )
    .await;
}

/// A password with no handler would protect nothing, so startup refuses it,
/// on a session and through the B/IP builder alike.
#[tokio::test]
async fn a_password_without_a_handler_is_refused() {
    const REFUSAL: &str = "a ReinitializeDevice password requires a ReinitializeDevice handler";
    let (transport, _peer) = LoopbackTransport::pair(vec![0x01], vec![0x02]);
    let mut session =
        EndpointSession::new(transport, SessionRole::ServerOnly, SessionConfig::default())
            .unwrap()
            .with_database(database(&[123]))
            .with_reinit_password(PASSWORD);
    assert_refused(&mut session, REFUSAL).await;

    let mut session = Builder::new(Ipv4Addr::LOCALHOST, 0, Ipv4Addr::BROADCAST)
        .role(SessionRole::ServerOnly)
        .database(database(&[123]))
        .reinit_password(PASSWORD)
        .build_session()
        .unwrap();
    assert_refused(&mut session, REFUSAL).await;

    let Err(error) = Builder::new(Ipv4Addr::LOCALHOST, 0, Ipv4Addr::BROADCAST)
        .reinit_password(PASSWORD)
        .build_transport()
    else {
        panic!("a bare transport cannot keep a ReinitializeDevice password")
    };
    assert!(
        error
            .to_string()
            .contains("ReinitializeDevice and its password require build_session()"),
        "got {error}"
    );
}

/// A configured password over 20 characters could never be sent, and an
/// empty one never matched, so startup refuses both; 20 multi-octet
/// characters are within the limit (#2060, #2094).
#[tokio::test]
async fn a_password_over_twenty_characters_is_refused() {
    let session = |password: String| {
        let (transport, _peer) = LoopbackTransport::pair(vec![0x01], vec![0x02]);
        EndpointSession::new(transport, SessionRole::ServerOnly, SessionConfig::default())
            .unwrap()
            .with_database(database(&[123]))
            .with_reinitialize(|_: &ReinitializeContext, _: &mut ObjectDatabase| Ok(()))
            .with_reinit_password(password)
    };
    assert_refused(
        &mut session("é".repeat(21)),
        "reinit_password exceeds the 20-character limit",
    )
    .await;
    // An empty one could never match, since an empty request password
    // decodes as none (#2094).
    assert_refused(
        &mut session(String::new()),
        "reinit_password is empty; leave it unset for no password",
    )
    .await;
    let mut fits = session("é".repeat(20));
    fits.start().await.unwrap();
    fits.stop().await.unwrap();
}

/// The executed services follow the published lists, and each opt-in names
/// the session method that enables it.
#[test]
fn the_responder_lists_match_what_each_session_executes() {
    let session = |writes: bool, reinitialize: bool| {
        let (transport, _peer) = LoopbackTransport::pair(vec![0x01], vec![0x02]);
        let mut session =
            EndpointSession::new(transport, SessionRole::ServerOnly, SessionConfig::default())
                .unwrap();
        if writes {
            session = session.with_device_writes(Arc::new(|_| true));
        }
        if reinitialize {
            session =
                session.with_reinitialize(|_: &ReinitializeContext, _: &mut ObjectDatabase| Ok(()));
        }
        session.executed_services()
    };
    assert_eq!(session(false, false), RESPONDER_SERVICES);
    let all: Vec<_> = RESPONDER_SERVICES
        .iter()
        .copied()
        .chain(
            RESPONDER_OPT_IN_SERVICES
                .iter()
                .map(|opt_in| opt_in.service),
        )
        .collect();
    assert_eq!(session(true, true), all);
    assert_eq!(
        session(true, false),
        [
            ServiceSupported::READ_PROPERTY,
            ServiceSupported::WRITE_PROPERTY
        ]
    );

    let source = include_str!("device_writes.rs");
    for ResponderOptIn { service, method } in RESPONDER_OPT_IN_SERVICES {
        assert!(
            source.contains(&format!("pub fn {method}("))
                || source.contains(&format!("pub fn {method}<")),
            "{service:?} names an EndpointSession method that exists: {method}"
        );
    }
}