Skip to main content

bacnet_encoding/constructed/
recipient.rs

1//! `Recipient_List` full ASN.1 framing (ASHRAE 135-2020 Clauses 12.21, 21).
2//!
3//! The property is a BACnetLIST of `BACnetDestination`, so on the wire it is
4//! the destinations back to back with no list wrapper. A destination has
5//! seven members and none carries a context tag, so they travel in this order
6//! as application-tagged elements (the recipient CHOICE brings its own tags):
7//!
8//! | Member | Wire form |
9//! |---|---|
10//! | `valid-days` | Bit String (`BACnetDaysOfWeek`) |
11//! | `from-time` | Time |
12//! | `to-time` | Time |
13//! | `recipient` | `BACnetRecipient` CHOICE, see below |
14//! | `process-identifier` | Unsigned, 32-bit range |
15//! | `issue-confirmed-notifications` | Boolean |
16//! | `transitions` | Bit String (`BACnetEventTransitionBits`) |
17//!
18//! `BACnetRecipient` picks either `device [0]`, an object identifier, or
19//! `address [1]`, a `BACnetAddress`. The device form tags a primitive
20//! ObjectIdentifier — a context-specific PRIMITIVE tag 0, length 4.
21//! `BACnetAddress` is constructed (a 16-bit network number, then the MAC
22//! address as an OCTET STRING, both application-tagged), so `address [1]` is
23//! an opening tag 1 / application-tagged Unsigned16 + OCTET STRING / closing
24//! tag 1.
25//!
26//! A `BACnetAddress` MAC is at most [`BACnetAddress::MAX_MAC_LEN`] octets in
27//! both directions: [`decode_recipient`] refuses a longer one before copying
28//! it (#1124 for configured recipients, #1156 everywhere else) and
29//! [`encode_recipient`] refuses to write one. Every other codec that carries a
30//! `BACnetAddress` (ValueSource, the AuditLogQuery filters) shares
31//! [`check_decoded_mac_len`] and [`check_encoded_mac_len`], so the bound has
32//! one definition. The source addresses the stack learns off the network fit
33//! it too: the NPDU codec bounds SADR the same way (#1141), and the network
34//! layer drops a frame from a longer link-layer source MAC (#1198).
35
36use bacnet_types::bitstring::{DaysOfWeek, EventTransitionBits};
37use bacnet_types::constructed::{BACnetAddress, BACnetDestination, BACnetRecipient};
38use bacnet_types::error::Error;
39use bacnet_types::primitives::Time;
40use bacnet_types::MacAddr;
41use bytes::BytesMut;
42
43use crate::primitives;
44use crate::tags::{self, TagClass};
45
46use super::tagged::{
47    contents, decode_app_bit_string, decode_app_unsigned, decode_ctx_object_id, expect_closing,
48    misplaced_tag,
49};
50use super::MAX_FRAMED_ITEMS;
51
52/// The message for a `BACnetAddress` MAC of `length` octets, or `None` when it
53/// fits [`BACnetAddress::MAX_MAC_LEN`]. The one place the bound is compared.
54fn mac_len_excess(what: &str, length: usize) -> Option<String> {
55    (length > BACnetAddress::MAX_MAC_LEN).then(|| {
56        format!(
57            "{what}: mac-address of {length} octets exceeds the {}-octet limit",
58            BACnetAddress::MAX_MAC_LEN
59        )
60    })
61}
62
63/// Refuse, as a decode error at `offset`, a `BACnetAddress` mac-address whose
64/// OCTET STRING holds more than [`BACnetAddress::MAX_MAC_LEN`] octets (#1156),
65/// or any other OCTET STRING that names a MAC on a data link, such as the
66/// You-Are device MAC (#1200). Decoders call it on the tag's length, before
67/// copying any octet.
68pub fn check_decoded_mac_len(length: usize, offset: usize, what: &str) -> Result<(), Error> {
69    mac_len_excess(what, length).map_or(Ok(()), |message| Err(Error::overflow(offset, message)))
70}
71
72/// Refuse to encode a MAC longer than [`BACnetAddress::MAX_MAC_LEN`] octets,
73/// which [`check_decoded_mac_len`] would refuse on the way back in: a
74/// `BACnetAddress` mac-address (#1156) or the You-Are device MAC (#1200).
75pub fn check_encoded_mac_len(mac: &[u8], what: &str) -> Result<(), Error> {
76    mac_len_excess(what, mac.len()).map_or(Ok(()), |message| Err(Error::Encoding(message)))
77}
78
79/// [`check_encoded_mac_len`] for the address form of a recipient; the device
80/// form always encodes.
81pub(super) fn check_encoded_recipient(recipient: &BACnetRecipient) -> Result<(), Error> {
82    match recipient {
83        BACnetRecipient::Device(_) => Ok(()),
84        BACnetRecipient::Address(address) => {
85            check_encoded_mac_len(&address.mac_address, "BACnetRecipient")
86        }
87    }
88}
89
90/// Encode one [`BACnetDestination`].
91///
92/// The two bit-string members travel MSB-first per Clause 20.2.10:
93/// `BACnetDaysOfWeek` is 7 bits (monday(0) at 0x80), so the fill octet has 1
94/// unused bit; `BACnetEventTransitionBits` is 3 bits, so 5 unused.
95///
96/// A recipient MAC past [`BACnetAddress::MAX_MAC_LEN`] octets is an error,
97/// returned before `buf` changes.
98pub fn encode_destination(buf: &mut BytesMut, dest: &BACnetDestination) -> Result<(), Error> {
99    check_encoded_recipient(&dest.recipient)?;
100    write_destination(buf, dest);
101    Ok(())
102}
103
104/// Write a destination whose recipient has passed [`check_encoded_recipient`].
105fn write_destination(buf: &mut BytesMut, dest: &BACnetDestination) {
106    primitives::encode_app_bit_string(buf, 1, &[dest.valid_days.to_bacnet()]);
107    primitives::encode_app_time(buf, &dest.from_time);
108    primitives::encode_app_time(buf, &dest.to_time);
109    write_recipient(buf, &dest.recipient);
110    primitives::encode_app_unsigned(buf, dest.process_identifier as u64);
111    primitives::encode_app_boolean(buf, dest.issue_confirmed_notifications);
112    primitives::encode_app_bit_string(buf, 5, &[dest.transitions.to_bacnet()]);
113}
114
115/// Encode a `BACnetLIST of BACnetDestination`: plain concatenation, no
116/// wrapper (Clause 12.21 `Recipient_List`). Every destination is checked
117/// before `buf` changes, so a refused list writes nothing.
118pub fn encode_destination_list(
119    buf: &mut BytesMut,
120    destinations: &[BACnetDestination],
121) -> Result<(), Error> {
122    for dest in destinations {
123        check_encoded_recipient(&dest.recipient)?;
124    }
125    for dest in destinations {
126        write_destination(buf, dest);
127    }
128    Ok(())
129}
130
131/// Encode a [`BACnetRecipient`]. An address MAC past
132/// [`BACnetAddress::MAX_MAC_LEN`] octets is an error, returned before `buf`
133/// changes.
134pub fn encode_recipient(buf: &mut BytesMut, recipient: &BACnetRecipient) -> Result<(), Error> {
135    check_encoded_recipient(recipient)?;
136    write_recipient(buf, recipient);
137    Ok(())
138}
139
140/// Write a recipient that has passed [`check_encoded_recipient`].
141pub(super) fn write_recipient(buf: &mut BytesMut, recipient: &BACnetRecipient) {
142    match recipient {
143        BACnetRecipient::Device(oid) => {
144            // device [0] tags the primitive ObjectIdentifier.
145            tags::encode_tag(buf, 0, TagClass::Context, 4);
146            buf.extend_from_slice(&oid.encode());
147        }
148        BACnetRecipient::Address(address) => {
149            // address [1] tags the constructed BACnetAddress.
150            tags::encode_opening_tag(buf, 1);
151            primitives::encode_app_unsigned(buf, address.network_number as u64);
152            primitives::encode_app_octet_string(buf, &address.mac_address);
153            tags::encode_closing_tag(buf, 1);
154        }
155    }
156}
157
158/// Decode one [`BACnetRecipient`] at `offset`.
159///
160/// An address whose MAC is longer than [`BACnetAddress::MAX_MAC_LEN`] octets
161/// names no node this stack reaches, so it is a decode error, raised before
162/// the MAC is copied. That holds for a configured recipient (a Recipient_List
163/// destination or the Audit_Notification_Recipient, #1124) and for one a
164/// service carries or the stack reports (COV subscription lists, audit
165/// records, enrollment filters, #1156).
166pub fn decode_recipient(data: &[u8], offset: usize) -> Result<(BACnetRecipient, usize), Error> {
167    let what = "BACnetRecipient";
168    let (tag, pos) = tags::decode_tag(data, offset)?;
169    if tag.is_context(0) {
170        // device [0] tags the primitive ObjectIdentifier.
171        let (device, end) = decode_ctx_object_id(data, offset, 0, "BACnetRecipient device")?;
172        return Ok((BACnetRecipient::Device(device), end));
173    }
174    if tag.is_opening_tag(1) {
175        // network-number Unsigned16
176        let (network_number, pos) = decode_app_unsigned::<u64>(data, pos, what)?;
177        let network_number = u16::try_from(network_number).map_err(|_| {
178            Error::out_of_range(pos, format!("{what}: network-number exceeds Unsigned16"))
179        })?;
180        // mac-address OCTET STRING (a zero-length string is a broadcast)
181        let (mac_address, pos) = decode_app_mac_address(data, pos, what)?;
182        let end = expect_closing(data, pos, 1, "BACnetRecipient address")?;
183        return Ok((
184            BACnetRecipient::Address(BACnetAddress {
185                network_number,
186                mac_address,
187            }),
188            end,
189        ));
190    }
191    Err(misplaced_tag(
192        data,
193        &tag,
194        None,
195        offset,
196        format!(
197            "{what}: expected [0] (device) or [1] (address), got {}",
198            if tag.is_opening {
199                format!("opening tag [{}]", tag.number)
200            } else if tag.is_closing {
201                format!("closing tag [{}]", tag.number)
202            } else {
203                match tag.class {
204                    TagClass::Context => format!("primitive context tag [{}]", tag.number),
205                    TagClass::Application => format!("application tag {}", tag.number),
206                }
207            }
208        ),
209    ))
210}
211
212/// Decode one [`BACnetDestination`] at `offset`; returns it and the offset
213/// past the last member. Its recipient decodes through [`decode_recipient`],
214/// so an address MAC past [`BACnetAddress::MAX_MAC_LEN`] octets is refused
215/// (#1124).
216pub fn decode_destination(data: &[u8], offset: usize) -> Result<(BACnetDestination, usize), Error> {
217    let what = "BACnetDestination";
218    // valid-days: BACnetDaysOfWeek (bit 0 = Monday, MSB-first on the wire).
219    let ((days_unused, days_data), pos) = decode_app_bit_string(data, offset, what)?;
220    check_fixed_bit_string(
221        days_unused,
222        &days_data,
223        1,
224        "valid-days (BACnetDaysOfWeek: 7 bits)",
225    )?;
226    let valid_days = DaysOfWeek::from_bacnet(&days_data);
227    // from-time / to-time.
228    let (from_time, pos) = decode_app_time(data, pos, what)?;
229    let (to_time, pos) = decode_app_time(data, pos, what)?;
230    // recipient CHOICE, its address MAC bounded.
231    let (recipient, pos) = decode_recipient(data, pos)?;
232    // process-identifier Unsigned32.
233    let (process_identifier, pos) = decode_app_unsigned::<u64>(data, pos, what)?;
234    let process_identifier = u32::try_from(process_identifier).map_err(|_| {
235        Error::out_of_range(
236            pos,
237            format!("{what}: process-identifier exceeds Unsigned32"),
238        )
239    })?;
240    // issue-confirmed-notifications BOOLEAN (application-tagged: the value
241    // rides in the tag's L/V/T bits with no contents octets).
242    let (tag, pos) = tags::decode_tag(data, pos)?;
243    if tag.class != TagClass::Application || tag.number != tags::app_tag::BOOLEAN {
244        return Err(misplaced_tag(
245            data,
246            &tag,
247            None,
248            pos,
249            format!("{what}: expected application-tagged BOOLEAN"),
250        ));
251    }
252    let issue_confirmed_notifications = tag.length != 0;
253    // transitions: BACnetEventTransitionBits (3 bits).
254    let ((transitions_unused, transitions_data), pos) = decode_app_bit_string(data, pos, what)?;
255    check_fixed_bit_string(
256        transitions_unused,
257        &transitions_data,
258        5,
259        "transitions (BACnetEventTransitionBits: 3 bits)",
260    )?;
261    let transitions = EventTransitionBits::from_bacnet(&transitions_data);
262
263    Ok((
264        BACnetDestination {
265            valid_days,
266            from_time,
267            to_time,
268            recipient,
269            process_identifier,
270            issue_confirmed_notifications,
271            transitions,
272        },
273        pos,
274    ))
275}
276
277/// Decode a whole `Recipient_List` (`BACnetLIST of BACnetDestination` —
278/// concatenated entries). Every entry must parse; trailing garbage errors.
279pub fn decode_destination_list(data: &[u8]) -> Result<Vec<BACnetDestination>, Error> {
280    let mut destinations = Vec::new();
281    let mut pos = 0;
282    while pos < data.len() {
283        if destinations.len() >= MAX_FRAMED_ITEMS {
284            return Err(Error::overflow(
285                pos,
286                "Recipient_List: destination count exceeds limit",
287            ));
288        }
289        let (dest, new_pos) = decode_destination(data, pos)?;
290        destinations.push(dest);
291        pos = new_pos;
292    }
293    Ok(destinations)
294}
295
296// ---------------------------------------------------------------------------
297// Small application-tagged member helpers
298// ---------------------------------------------------------------------------
299
300/// Decode the application-tagged OCTET STRING of a `BACnetAddress` MAC,
301/// refusing one longer than [`BACnetAddress::MAX_MAC_LEN`] octets before
302/// copying it.
303pub(super) fn decode_app_mac_address(
304    data: &[u8],
305    offset: usize,
306    what: &str,
307) -> Result<(MacAddr, usize), Error> {
308    let (tag, pos) = tags::decode_tag(data, offset)?;
309    if tag.class != TagClass::Application || tag.number != tags::app_tag::OCTET_STRING {
310        return Err(misplaced_tag(
311            data,
312            &tag,
313            None,
314            offset,
315            format!("{what}: expected application-tagged OCTET STRING"),
316        ));
317    }
318    check_decoded_mac_len(tag.length as usize, offset, what)?;
319    let (mac, end) = contents(data, pos, tag.length)?;
320    Ok((MacAddr::from_slice(mac), end))
321}
322
323/// Decode an application-tagged Time member (exactly 4 contents octets).
324fn decode_app_time(data: &[u8], offset: usize, what: &str) -> Result<(Time, usize), Error> {
325    let (tag, pos) = tags::decode_tag(data, offset)?;
326    if tag.class != TagClass::Application || tag.number != tags::app_tag::TIME {
327        return Err(misplaced_tag(
328            data,
329            &tag,
330            None,
331            offset,
332            format!("{what}: expected application-tagged Time"),
333        ));
334    }
335    if tag.length != 4 {
336        return Err(Error::decoding(
337            offset,
338            format!(
339                "{what}: Time has {} contents octets, expected 4",
340                tag.length
341            ),
342        ));
343    }
344    let (octets, end) = contents(data, pos, 4)?;
345    Ok((Time::decode(octets)?, end))
346}
347
348/// Fixed-width bit-string member validation. Per Clause 20.2.10 (initial
349/// octet = unused-bit count; defined bits MSB-first) and the Clause 21
350/// productions, the named-bit sets here fit in exactly one subsequent
351/// octet: `BACnetDaysOfWeek` has 7 defined bits (unused_bits 1) and
352/// `BACnetEventTransitionBits` has 3 (unused_bits 5). A zero-length,
353/// overlong, or mismatched-unused-bits encoding is not a destination a
354/// notifier may act on — reject it rather than unpacking an all-zero
355/// (dormant) one.
356fn check_fixed_bit_string(
357    unused_bits: u8,
358    data: &[u8],
359    expected_unused: u8,
360    name: &str,
361) -> Result<(), Error> {
362    if data.len() != 1 || unused_bits != expected_unused {
363        return Err(Error::decoding(
364            0,
365            format!(
366                "{name}: expected 1 content octet with unused_bits {expected_unused} \
367                 (got {} content octet(s), unused_bits {unused_bits})",
368                data.len()
369            ),
370        ));
371    }
372    Ok(())
373}