Skip to main content

dlms_cosem_kit/
acse.rs

1//! ACSE — establishing and releasing an application association.
2//!
3//! The AARQ/AARE exchange decides four things at once: which application context (so,
4//! whether the association is ciphered and whether it uses logical or short names),
5//! which authentication mechanism, what each side's system title is, and — inside the
6//! user-information field, in A-XDR — what services and PDU sizes both sides accept.
7//!
8//! Get any one of those wrong and the association still opens, then fails later in a
9//! way that looks like a different bug. So each is a typed field here, and an unknown
10//! value is preserved rather than defaulted.
11
12use crate::ber::{Tlv, iter_tlv, read_tlv, write_constructed, write_tlv};
13use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, Writer};
14
15/// The object identifier prefix all DLMS context and mechanism names share:
16/// `2.16.756.5.8` — joint-iso-itu-t(2) country(16) ch(756) dlms-ua(5).
17const OID_PREFIX: [u8; 5] = [0x60, 0x85, 0x74, 0x05, 0x08];
18
19/// How objects are addressed in an association.
20///
21/// Not a per-request choice: it is decided once, by the application context the AARQ
22/// proposes, and both ends are bound to it for the life of the association. It lives
23/// here rather than with either engine because the context is where it is *stated*.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum Referencing {
26    /// By class, logical name and attribute index. What every modern meter uses.
27    #[default]
28    LogicalName,
29    /// By sixteen-bit short name. Kept for an installed base of older meters, and behind
30    /// the `sn` feature.
31    ShortName,
32}
33
34/// Which naming and protection the association uses.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum ApplicationContext {
37    /// Logical-name referencing, no ciphering.
38    LogicalName,
39    /// Short-name referencing, no ciphering.
40    ShortName,
41    /// Logical-name referencing with ciphering.
42    LogicalNameCiphered,
43    /// Short-name referencing with ciphering.
44    ShortNameCiphered,
45    /// A context this crate does not know, kept so the refusal can name it.
46    Other(u8),
47}
48
49impl ApplicationContext {
50    /// The final arc of the object identifier.
51    #[must_use]
52    pub const fn arc(self) -> u8 {
53        match self {
54            Self::LogicalName => 1,
55            Self::ShortName => 2,
56            Self::LogicalNameCiphered => 3,
57            Self::ShortNameCiphered => 4,
58            Self::Other(v) => v,
59        }
60    }
61
62    /// From the final arc.
63    #[must_use]
64    pub const fn from_arc(v: u8) -> Self {
65        match v {
66            1 => Self::LogicalName,
67            2 => Self::ShortName,
68            3 => Self::LogicalNameCiphered,
69            4 => Self::ShortNameCiphered,
70            other => Self::Other(other),
71        }
72    }
73
74    /// True when the association protects its APDUs.
75    #[must_use]
76    pub const fn is_ciphered(self) -> bool {
77        matches!(self, Self::LogicalNameCiphered | Self::ShortNameCiphered)
78    }
79
80    /// True when objects are addressed by logical name.
81    #[must_use]
82    pub const fn is_logical_name(self) -> bool {
83        matches!(self, Self::LogicalName | Self::LogicalNameCiphered)
84    }
85
86    /// The context for a referencing mode, ciphered or not.
87    #[must_use]
88    pub const fn for_referencing(referencing: Referencing, ciphered: bool) -> Self {
89        match (referencing, ciphered) {
90            (Referencing::LogicalName, false) => Self::LogicalName,
91            (Referencing::LogicalName, true) => Self::LogicalNameCiphered,
92            (Referencing::ShortName, false) => Self::ShortName,
93            (Referencing::ShortName, true) => Self::ShortNameCiphered,
94        }
95    }
96
97    /// How this context addresses objects.
98    #[must_use]
99    pub const fn referencing(self) -> Referencing {
100        if self.is_logical_name() { Referencing::LogicalName } else { Referencing::ShortName }
101    }
102
103    /// The same context with ciphering switched on or off.
104    #[must_use]
105    pub const fn with_ciphering(self, ciphered: bool) -> Self {
106        match (self.is_logical_name(), ciphered) {
107            (true, false) => Self::LogicalName,
108            (true, true) => Self::LogicalNameCiphered,
109            (false, false) => Self::ShortName,
110            (false, true) => Self::ShortNameCiphered,
111        }
112    }
113}
114
115/// How the client proves who it is.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum AuthMechanism {
118    /// No authentication. The public client.
119    None,
120    /// Low level security: the password is sent in the AARQ.
121    Low,
122    /// High level security, manufacturer-specific. Not implemented by this crate.
123    HighManufacturer,
124    /// High level security using MD5. Obsolete.
125    HighMd5,
126    /// High level security using SHA-1. Obsolete.
127    HighSha1,
128    /// High level security using GMAC — the mechanism in general use.
129    HighGmac,
130    /// High level security using SHA-256.
131    HighSha256,
132    /// High level security using ECDSA.
133    HighEcdsa,
134    /// A mechanism this crate does not know.
135    Other(u8),
136}
137
138impl AuthMechanism {
139    /// The final arc of the object identifier.
140    #[must_use]
141    pub const fn arc(self) -> u8 {
142        match self {
143            Self::None => 0,
144            Self::Low => 1,
145            Self::HighManufacturer => 2,
146            Self::HighMd5 => 3,
147            Self::HighSha1 => 4,
148            Self::HighGmac => 5,
149            Self::HighSha256 => 6,
150            Self::HighEcdsa => 7,
151            Self::Other(v) => v,
152        }
153    }
154
155    /// From the final arc.
156    #[must_use]
157    pub const fn from_arc(v: u8) -> Self {
158        match v {
159            0 => Self::None,
160            1 => Self::Low,
161            2 => Self::HighManufacturer,
162            3 => Self::HighMd5,
163            4 => Self::HighSha1,
164            5 => Self::HighGmac,
165            6 => Self::HighSha256,
166            7 => Self::HighEcdsa,
167            other => Self::Other(other),
168        }
169    }
170
171    /// True when the mechanism needs the two extra passes that exchange challenges.
172    #[must_use]
173    pub const fn is_high_level(self) -> bool {
174        !matches!(self, Self::None | Self::Low)
175    }
176}
177
178/// Whether the server accepted the association.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum AssociationResult {
181    /// Accepted.
182    Accepted,
183    /// Refused, and asking again will not help.
184    RejectedPermanent,
185    /// Refused for now.
186    RejectedTransient,
187    /// A value this crate does not know.
188    Other(u8),
189}
190
191impl AssociationResult {
192    /// From the wire value.
193    #[must_use]
194    pub const fn from_u8(v: u8) -> Self {
195        match v {
196            0 => Self::Accepted,
197            1 => Self::RejectedPermanent,
198            2 => Self::RejectedTransient,
199            other => Self::Other(other),
200        }
201    }
202
203    /// The wire value.
204    #[must_use]
205    pub const fn as_u8(self) -> u8 {
206        match self {
207            Self::Accepted => 0,
208            Self::RejectedPermanent => 1,
209            Self::RejectedTransient => 2,
210            Self::Other(v) => v,
211        }
212    }
213}
214
215/// Why the server answered as it did.
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub enum Diagnostic {
218    /// Attributed to the peer application.
219    User(UserDiagnostic),
220    /// Attributed to the association-control service itself.
221    Provider(u8),
222}
223
224/// The `acse-service-user` diagnostics that matter in DLMS.
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226#[non_exhaustive]
227pub enum UserDiagnostic {
228    /// No diagnostic; the association was accepted.
229    Null,
230    /// No reason given.
231    NoReasonGiven,
232    /// The proposed application context is not supported — usually a client asking for
233    /// ciphering from a meter that has none, or short names from a logical-name meter.
234    ApplicationContextNameNotSupported,
235    /// The mechanism name is not one the server knows.
236    AuthenticationMechanismNameNotRecognised,
237    /// The server requires a mechanism name and none was offered.
238    AuthenticationMechanismNameRequired,
239    /// The credentials were wrong.
240    AuthenticationFailure,
241    /// The server requires authentication for this association.
242    AuthenticationRequired,
243    /// A value this crate does not name.
244    Other(u8),
245}
246
247impl UserDiagnostic {
248    /// From the wire value.
249    #[must_use]
250    pub const fn from_u8(v: u8) -> Self {
251        match v {
252            0 => Self::Null,
253            1 => Self::NoReasonGiven,
254            2 => Self::ApplicationContextNameNotSupported,
255            11 => Self::AuthenticationMechanismNameNotRecognised,
256            12 => Self::AuthenticationMechanismNameRequired,
257            13 => Self::AuthenticationFailure,
258            14 => Self::AuthenticationRequired,
259            other => Self::Other(other),
260        }
261    }
262
263    /// The wire value.
264    #[must_use]
265    pub const fn as_u8(self) -> u8 {
266        match self {
267            Self::Null => 0,
268            Self::NoReasonGiven => 1,
269            Self::ApplicationContextNameNotSupported => 2,
270            Self::AuthenticationMechanismNameNotRecognised => 11,
271            Self::AuthenticationMechanismNameRequired => 12,
272            Self::AuthenticationFailure => 13,
273            Self::AuthenticationRequired => 14,
274            Self::Other(v) => v,
275        }
276    }
277}
278
279/// Why an association is being released.
280#[derive(Debug, Clone, Copy, PartialEq, Eq)]
281pub enum ReleaseReason {
282    /// The client is finished.
283    Normal,
284    /// The client wants the association released urgently.
285    Urgent,
286    /// The client is not saying.
287    UserDefined,
288    /// A value this crate does not know.
289    Other(u8),
290}
291
292impl ReleaseReason {
293    /// From the wire value.
294    #[must_use]
295    pub const fn from_u8(v: u8) -> Self {
296        match v {
297            0 => Self::Normal,
298            1 => Self::Urgent,
299            30 => Self::UserDefined,
300            other => Self::Other(other),
301        }
302    }
303
304    /// The wire value.
305    #[must_use]
306    pub const fn as_u8(self) -> u8 {
307        match self {
308            Self::Normal => 0,
309            Self::Urgent => 1,
310            Self::UserDefined => 30,
311            Self::Other(v) => v,
312        }
313    }
314}
315
316/// The client's association request.
317#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
318pub struct Aarq<'a> {
319    /// Which naming and protection.
320    pub application_context: Option<ApplicationContext>,
321    /// The server's system title, when the client names it.
322    pub called_ap_title: Option<&'a [u8]>,
323    /// The client's system title. Required for GMAC and for any ciphered context,
324    /// because it is half of every nonce the client will use.
325    pub calling_ap_title: Option<&'a [u8]>,
326    /// A qualifier some profiles use to select a key set.
327    pub calling_ae_qualifier: Option<&'a [u8]>,
328    /// The ACSE requirements bit string; `0x0780` means "authentication used".
329    pub sender_acse_requirements: bool,
330    /// Which authentication mechanism.
331    pub mechanism_name: Option<AuthMechanism>,
332    /// The password for low level security, or the client's challenge for high level.
333    pub calling_authentication_value: Option<&'a [u8]>,
334    /// The xDLMS InitiateRequest, ciphered when the context says so.
335    pub user_information: Option<&'a [u8]>,
336}
337
338impl Encode for Aarq<'_> {
339    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
340        write_constructed(w, 0x60, |w| {
341            if let Some(ctx) = self.application_context {
342                write_constructed(w, 0xA1, |w| write_tlv(w, 0x06, &oid(1, ctx.arc())))?;
343            }
344            if let Some(t) = self.called_ap_title {
345                write_constructed(w, 0xA2, |w| write_tlv(w, 0x04, t))?;
346            }
347            if let Some(t) = self.calling_ap_title {
348                write_constructed(w, 0xA6, |w| write_tlv(w, 0x04, t))?;
349            }
350            if let Some(q) = self.calling_ae_qualifier {
351                write_constructed(w, 0xA7, |w| write_tlv(w, 0x04, q))?;
352            }
353            if self.sender_acse_requirements {
354                write_tlv(w, 0x8A, &[0x07, 0x80])?;
355            }
356            if let Some(m) = self.mechanism_name {
357                write_tlv(w, 0x8B, &oid(2, m.arc()))?;
358            }
359            if let Some(v) = self.calling_authentication_value {
360                write_constructed(w, 0xAC, |w| write_tlv(w, 0x80, v))?;
361            }
362            if let Some(u) = self.user_information {
363                write_constructed(w, 0xBE, |w| write_tlv(w, 0x04, u))?;
364            }
365            Ok(())
366        })
367    }
368}
369
370impl<'a> Decode<'a> for Aarq<'a> {
371    fn decode(r: &mut Reader<'a>) -> Result<Self> {
372        let outer = read_tlv(r)?;
373        if outer.tag != 0x60 {
374            return Err(Error::new(ErrorKind::InvalidTag(outer.tag), outer.offset));
375        }
376        let mut out = Self::default();
377        for tlv in iter_tlv(outer.value, outer.offset) {
378            let tlv = tlv?;
379            match tlv.context_number() {
380                Some(1) => out.application_context = Some(ApplicationContext::from_arc(oid_arc(&tlv)?)),
381                Some(2) => out.called_ap_title = Some(inner_octets(&tlv, 0x04)?),
382                Some(6) => out.calling_ap_title = Some(inner_octets(&tlv, 0x04)?),
383                Some(7) => out.calling_ae_qualifier = Some(inner_octets(&tlv, 0x04)?),
384                Some(10) => out.sender_acse_requirements = authentication_bit(tlv.value),
385                Some(11) => out.mechanism_name = Some(AuthMechanism::from_arc(implicit_oid_arc(&tlv)?)),
386                Some(12) => out.calling_authentication_value = Some(inner_octets(&tlv, 0x80)?),
387                Some(30) => out.user_information = Some(inner_octets(&tlv, 0x04)?),
388                _ => {}
389            }
390        }
391        Ok(out)
392    }
393}
394
395/// The server's answer.
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub struct Aare<'a> {
398    /// Which naming and protection the server agrees to.
399    pub application_context: Option<ApplicationContext>,
400    /// Accepted or refused.
401    pub result: AssociationResult,
402    /// Why.
403    pub diagnostic: Diagnostic,
404    /// The server's system title. Required for a ciphered association, because it is
405    /// half of every nonce the server will use.
406    pub responding_ap_title: Option<&'a [u8]>,
407    /// The ACSE requirements bit string.
408    pub responder_acse_requirements: bool,
409    /// Which authentication mechanism the server will use.
410    pub mechanism_name: Option<AuthMechanism>,
411    /// The server's challenge for high level security.
412    pub responding_authentication_value: Option<&'a [u8]>,
413    /// The xDLMS InitiateResponse, or a ConfirmedServiceError when the association was
414    /// refused for an xDLMS reason.
415    pub user_information: Option<&'a [u8]>,
416}
417
418impl Default for Aare<'_> {
419    fn default() -> Self {
420        Self {
421            application_context: None,
422            result: AssociationResult::Accepted,
423            diagnostic: Diagnostic::User(UserDiagnostic::Null),
424            responding_ap_title: None,
425            responder_acse_requirements: false,
426            mechanism_name: None,
427            responding_authentication_value: None,
428            user_information: None,
429        }
430    }
431}
432
433impl Aare<'_> {
434    /// True when the server accepted.
435    #[must_use]
436    pub const fn is_accepted(&self) -> bool {
437        matches!(self.result, AssociationResult::Accepted)
438    }
439}
440
441impl Encode for Aare<'_> {
442    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
443        write_constructed(w, 0x61, |w| {
444            if let Some(ctx) = self.application_context {
445                write_constructed(w, 0xA1, |w| write_tlv(w, 0x06, &oid(1, ctx.arc())))?;
446            }
447            write_constructed(w, 0xA2, |w| write_tlv(w, 0x02, &[self.result.as_u8()]))?;
448            write_constructed(w, 0xA3, |w| match self.diagnostic {
449                Diagnostic::User(d) => write_constructed(w, 0xA1, |w| write_tlv(w, 0x02, &[d.as_u8()])),
450                Diagnostic::Provider(d) => write_constructed(w, 0xA2, |w| write_tlv(w, 0x02, &[d])),
451            })?;
452            if let Some(t) = self.responding_ap_title {
453                write_constructed(w, 0xA4, |w| write_tlv(w, 0x04, t))?;
454            }
455            if self.responder_acse_requirements {
456                write_tlv(w, 0x88, &[0x07, 0x80])?;
457            }
458            if let Some(m) = self.mechanism_name {
459                write_tlv(w, 0x89, &oid(2, m.arc()))?;
460            }
461            if let Some(v) = self.responding_authentication_value {
462                write_constructed(w, 0xAA, |w| write_tlv(w, 0x80, v))?;
463            }
464            if let Some(u) = self.user_information {
465                write_constructed(w, 0xBE, |w| write_tlv(w, 0x04, u))?;
466            }
467            Ok(())
468        })
469    }
470}
471
472impl<'a> Decode<'a> for Aare<'a> {
473    fn decode(r: &mut Reader<'a>) -> Result<Self> {
474        let outer = read_tlv(r)?;
475        if outer.tag != 0x61 {
476            return Err(Error::new(ErrorKind::InvalidTag(outer.tag), outer.offset));
477        }
478        let mut out = Self::default();
479        for tlv in iter_tlv(outer.value, outer.offset) {
480            let tlv = tlv?;
481            match tlv.context_number() {
482                Some(1) => out.application_context = Some(ApplicationContext::from_arc(oid_arc(&tlv)?)),
483                Some(2) => {
484                    let inner = read_tlv(&mut tlv.reader())?;
485                    out.result = AssociationResult::from_u8(inner.as_u8()?);
486                }
487                Some(3) => {
488                    let inner = read_tlv(&mut tlv.reader())?;
489                    let value = read_tlv(&mut inner.reader())?.as_u8()?;
490                    out.diagnostic = match inner.context_number() {
491                        Some(1) => Diagnostic::User(UserDiagnostic::from_u8(value)),
492                        _ => Diagnostic::Provider(value),
493                    };
494                }
495                Some(4) => out.responding_ap_title = Some(inner_octets(&tlv, 0x04)?),
496                Some(8) => out.responder_acse_requirements = authentication_bit(tlv.value),
497                Some(9) => out.mechanism_name = Some(AuthMechanism::from_arc(implicit_oid_arc(&tlv)?)),
498                Some(10) => out.responding_authentication_value = Some(inner_octets(&tlv, 0x80)?),
499                Some(30) => out.user_information = Some(inner_octets(&tlv, 0x04)?),
500                _ => {}
501            }
502        }
503        Ok(out)
504    }
505}
506
507/// The server's answer to a release request.
508///
509/// Values from ISO/IEC 8650-1 `Release-response-reason`, which Gurux agrees with; the
510/// Green Book excerpt on disk does not print them (derived).
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512pub enum ReleaseResponseReason {
513    /// The association is released.
514    Normal,
515    /// The server is not finished and refuses the release.
516    NotFinished,
517    /// The server is not saying.
518    UserDefined,
519    /// A value this crate does not know.
520    Other(u8),
521}
522
523impl ReleaseResponseReason {
524    /// From the wire value.
525    #[must_use]
526    pub const fn from_u8(v: u8) -> Self {
527        match v {
528            0 => Self::Normal,
529            1 => Self::NotFinished,
530            30 => Self::UserDefined,
531            other => Self::Other(other),
532        }
533    }
534
535    /// The wire value.
536    #[must_use]
537    pub const fn as_u8(self) -> u8 {
538        match self {
539            Self::Normal => 0,
540            Self::NotFinished => 1,
541            Self::UserDefined => 30,
542            Self::Other(v) => v,
543        }
544    }
545}
546
547/// The client asks to release the association.
548#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
549pub struct Rlrq<'a> {
550    /// Why, when given.
551    pub reason: Option<ReleaseReason>,
552    /// A ciphered InitiateRequest, when the profile requires the release to be
553    /// protected too.
554    pub user_information: Option<&'a [u8]>,
555}
556
557/// The server confirms the release.
558#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
559pub struct Rlre<'a> {
560    /// Whether it is released, when given. Absent means released.
561    pub reason: Option<ReleaseResponseReason>,
562    /// A ciphered InitiateResponse, when the profile requires it.
563    pub user_information: Option<&'a [u8]>,
564}
565
566macro_rules! release_codec {
567    ($ty:ident, $tag:literal, $reason:ident) => {
568        impl Encode for $ty<'_> {
569            fn encode(&self, w: &mut dyn Writer) -> Result<()> {
570                write_constructed(w, $tag, |w| {
571                    if let Some(reason) = self.reason {
572                        write_tlv(w, 0x80, &[reason.as_u8()])?;
573                    }
574                    if let Some(u) = self.user_information {
575                        write_constructed(w, 0xBE, |w| write_tlv(w, 0x04, u))?;
576                    }
577                    Ok(())
578                })
579            }
580        }
581
582        impl<'a> Decode<'a> for $ty<'a> {
583            fn decode(r: &mut Reader<'a>) -> Result<Self> {
584                let outer = read_tlv(r)?;
585                if outer.tag != $tag {
586                    return Err(Error::new(ErrorKind::InvalidTag(outer.tag), outer.offset));
587                }
588                let mut out = Self::default();
589                for tlv in iter_tlv(outer.value, outer.offset) {
590                    let tlv = tlv?;
591                    match tlv.context_number() {
592                        Some(0) => out.reason = Some($reason::from_u8(tlv.as_u8()?)),
593                        Some(30) => out.user_information = Some(inner_octets(&tlv, 0x04)?),
594                        _ => {}
595                    }
596                }
597                Ok(out)
598            }
599        }
600    };
601}
602
603release_codec!(Rlrq, 0x62, ReleaseReason);
604release_codec!(Rlre, 0x63, ReleaseResponseReason);
605
606/// `2.16.756.5.8.<branch>.<arc>` as BER contents.
607fn oid(branch: u8, arc: u8) -> [u8; 7] {
608    let mut out = [0u8; 7];
609    out[..5].copy_from_slice(&OID_PREFIX);
610    out[5] = branch;
611    out[6] = arc;
612    out
613}
614
615/// The final arc of an object identifier inside an explicitly tagged container.
616fn oid_arc(tlv: &Tlv<'_>) -> Result<u8> {
617    let inner = read_tlv(&mut tlv.reader())?;
618    if inner.tag != 0x06 {
619        return Err(Error::new(ErrorKind::InvalidTag(inner.tag), inner.offset));
620    }
621    check_oid_prefix(inner.value, inner.offset)
622}
623
624/// The final arc of an implicitly tagged object identifier.
625fn implicit_oid_arc(tlv: &Tlv<'_>) -> Result<u8> {
626    check_oid_prefix(tlv.value, tlv.offset)
627}
628
629fn check_oid_prefix(value: &[u8], offset: usize) -> Result<u8> {
630    if value.len() != 7 || value[..5] != OID_PREFIX {
631        return Err(Error::new(ErrorKind::InvalidValue, offset));
632    }
633    Ok(value[6])
634}
635
636/// The contents of a single TLV of tag `expected` inside `tlv`.
637fn inner_octets<'a>(tlv: &Tlv<'a>, expected: u8) -> Result<&'a [u8]> {
638    if !tlv.is_constructed() {
639        // An implicit octet string: the contents are the value itself.
640        return Ok(tlv.value);
641    }
642    let inner = read_tlv(&mut tlv.reader())?;
643    if inner.tag != expected {
644        return Err(Error::new(ErrorKind::InvalidTag(inner.tag), inner.offset));
645    }
646    Ok(inner.value)
647}
648
649/// The `authentication` bit of an ACSE-requirements BIT STRING.
650///
651/// A BER bit string is `[unused-bit-count, content…]`, and bit 0 — `authentication` — is
652/// the *most significant* bit of the first content byte. Reading the last byte instead
653/// happens to work for the one-byte form every stack sends (`07 80`) and silently
654/// reports "no authentication" for any longer one.
655fn authentication_bit(value: &[u8]) -> bool {
656    value.get(1).is_some_and(|b| *b & 0x80 != 0)
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662    use crate::codec::SliceWriter;
663
664    #[test]
665    fn the_context_and_mechanism_oids_are_the_dlms_ua_arcs() {
666        assert_eq!(oid(1, 1), [0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01]);
667        assert_eq!(oid(2, 5), [0x60, 0x85, 0x74, 0x05, 0x08, 0x02, 0x05]);
668    }
669
670    #[test]
671    fn a_low_level_security_aarq_round_trips() {
672        let aarq = Aarq {
673            application_context: Some(ApplicationContext::LogicalName),
674            calling_ap_title: None,
675            sender_acse_requirements: true,
676            mechanism_name: Some(AuthMechanism::Low),
677            calling_authentication_value: Some(b"12345678"),
678            user_information: Some(&[
679                0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0,
680            ]),
681            ..Default::default()
682        };
683        let mut buf = [0u8; 128];
684        let mut w = SliceWriter::new(&mut buf);
685        aarq.encode(&mut w).unwrap();
686        let bytes = w.as_slice();
687        assert_eq!(bytes[0], 0x60, "AARQ is [APPLICATION 0]");
688        assert_eq!(bytes[1] as usize, bytes.len() - 2, "length covers the rest");
689        let back = Aarq::from_bytes(bytes).unwrap();
690        assert_eq!(back, aarq);
691    }
692
693    #[test]
694    fn a_ciphered_hls_aarq_carries_both_system_title_and_challenge() {
695        let title = [0x4Du8, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E];
696        let challenge = [0xAAu8; 16];
697        let aarq = Aarq {
698            application_context: Some(ApplicationContext::LogicalNameCiphered),
699            calling_ap_title: Some(&title),
700            sender_acse_requirements: true,
701            mechanism_name: Some(AuthMechanism::HighGmac),
702            calling_authentication_value: Some(&challenge),
703            user_information: Some(&[0x21, 0x30, 0x00, 0x00, 0x00, 0x01, 0xFF]),
704            ..Default::default()
705        };
706        let mut buf = [0u8; 128];
707        let mut w = SliceWriter::new(&mut buf);
708        aarq.encode(&mut w).unwrap();
709        let back = Aarq::from_bytes(w.as_slice()).unwrap();
710        assert_eq!(back.calling_ap_title, Some(&title[..]));
711        assert_eq!(back.calling_authentication_value, Some(&challenge[..]));
712        assert_eq!(back.mechanism_name, Some(AuthMechanism::HighGmac));
713        assert!(back.application_context.unwrap().is_ciphered());
714    }
715
716    #[test]
717    fn an_accepted_aare_round_trips() {
718        let aare = Aare {
719            application_context: Some(ApplicationContext::LogicalName),
720            result: AssociationResult::Accepted,
721            diagnostic: Diagnostic::User(UserDiagnostic::Null),
722            user_information: Some(&[
723                0x08, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0x00, 0x00, 0x07,
724            ]),
725            ..Default::default()
726        };
727        let mut buf = [0u8; 128];
728        let mut w = SliceWriter::new(&mut buf);
729        aare.encode(&mut w).unwrap();
730        assert_eq!(w.as_slice()[0], 0x61);
731        let back = Aare::from_bytes(w.as_slice()).unwrap();
732        assert_eq!(back, aare);
733        assert!(back.is_accepted());
734    }
735
736    #[test]
737    fn a_refusal_keeps_its_diagnostic() {
738        let aare = Aare {
739            result: AssociationResult::RejectedPermanent,
740            diagnostic: Diagnostic::User(UserDiagnostic::AuthenticationFailure),
741            ..Default::default()
742        };
743        let mut buf = [0u8; 64];
744        let mut w = SliceWriter::new(&mut buf);
745        aare.encode(&mut w).unwrap();
746        let back = Aare::from_bytes(w.as_slice()).unwrap();
747        assert!(!back.is_accepted());
748        assert_eq!(back.diagnostic, Diagnostic::User(UserDiagnostic::AuthenticationFailure));
749    }
750
751    #[test]
752    fn a_provider_diagnostic_is_not_mistaken_for_a_user_one() {
753        let aare = Aare {
754            result: AssociationResult::RejectedTransient,
755            diagnostic: Diagnostic::Provider(1),
756            ..Default::default()
757        };
758        let mut buf = [0u8; 64];
759        let mut w = SliceWriter::new(&mut buf);
760        aare.encode(&mut w).unwrap();
761        assert_eq!(Aare::from_bytes(w.as_slice()).unwrap().diagnostic, Diagnostic::Provider(1));
762    }
763
764    #[test]
765    fn release_round_trips() {
766        let rlrq = Rlrq { reason: Some(ReleaseReason::Normal), user_information: None };
767        let mut buf = [0u8; 32];
768        let mut w = SliceWriter::new(&mut buf);
769        rlrq.encode(&mut w).unwrap();
770        assert_eq!(w.as_slice(), [0x62, 0x03, 0x80, 0x01, 0x00]);
771        assert_eq!(Rlrq::from_bytes(w.as_slice()).unwrap(), rlrq);
772
773        let rlre = Rlre { reason: Some(ReleaseResponseReason::NotFinished), user_information: None };
774        let mut w = SliceWriter::new(&mut buf);
775        rlre.encode(&mut w).unwrap();
776        assert_eq!(w.as_slice(), [0x63, 0x03, 0x80, 0x01, 0x01]);
777        assert_eq!(Rlre::from_bytes(w.as_slice()).unwrap(), rlre);
778    }
779
780    /// The bit string is `[unused-bits, content…]` and `authentication` is the top bit
781    /// of the *first* content byte. Every stack sends the one-byte form, so reading the
782    /// last byte works until somebody sends a longer one — and then authentication
783    /// silently reads as absent.
784    #[test]
785    fn the_authentication_bit_is_read_from_the_first_content_byte() {
786        // The one-byte form everyone sends.
787        let tlv = read_tlv(&mut Reader::new(&[0x8A, 0x02, 0x07, 0x80])).unwrap();
788        assert!(authentication_bit(tlv.value));
789        // A two-byte content with the same bit set. `.last()` would see 0x00 here.
790        let tlv = read_tlv(&mut Reader::new(&[0x8A, 0x03, 0x00, 0x80, 0x00])).unwrap();
791        assert!(authentication_bit(tlv.value), "a longer bit string must not lose the bit");
792        // And genuinely absent.
793        let tlv = read_tlv(&mut Reader::new(&[0x8A, 0x02, 0x07, 0x00])).unwrap();
794        assert!(!authentication_bit(tlv.value));
795        // A bit string with no content byte at all says nothing.
796        let tlv = read_tlv(&mut Reader::new(&[0x8A, 0x01, 0x00])).unwrap();
797        assert!(!authentication_bit(tlv.value));
798    }
799
800    #[test]
801    fn an_unknown_context_arc_is_kept_not_defaulted() {
802        let aarq = Aarq { application_context: Some(ApplicationContext::Other(9)), ..Default::default() };
803        let mut buf = [0u8; 64];
804        let mut w = SliceWriter::new(&mut buf);
805        aarq.encode(&mut w).unwrap();
806        assert_eq!(
807            Aarq::from_bytes(w.as_slice()).unwrap().application_context,
808            Some(ApplicationContext::Other(9))
809        );
810    }
811}