Skip to main content

dlms_cosem_kit/xdlms/
error.rs

1//! The two ways a server refuses an APDU outright.
2
3use crate::codec::{Decode, Encode, Reader, Result, Writer};
4
5/// Why the APDU was not acceptable at all.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum StateError {
9    /// The service is not allowed in the current association state.
10    ServiceNotAllowed,
11    /// The service is not one the server knows.
12    ServiceUnknown,
13    /// A code this crate does not name.
14    Other(u8),
15}
16
17impl StateError {
18    /// From the wire byte.
19    #[must_use]
20    pub const fn from_u8(v: u8) -> Self {
21        match v {
22            1 => Self::ServiceNotAllowed,
23            2 => Self::ServiceUnknown,
24            other => Self::Other(other),
25        }
26    }
27
28    /// The wire byte.
29    #[must_use]
30    pub const fn as_u8(self) -> u8 {
31        match self {
32            Self::ServiceNotAllowed => 1,
33            Self::ServiceUnknown => 2,
34            Self::Other(v) => v,
35        }
36    }
37}
38
39/// What about the APDU was unacceptable.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum ServiceError {
43    /// The operation cannot be performed.
44    OperationNotPossible,
45    /// The service is not supported.
46    ServiceNotSupported,
47    /// Unspecified.
48    OtherReason,
49    /// The APDU exceeded the negotiated maximum size.
50    PduTooLong,
51    /// The APDU could not be deciphered: wrong key, wrong system title, bad tag.
52    DecipheringError,
53    /// The invocation counter was not greater than the last one accepted.
54    InvocationCounterError,
55    /// A code this crate does not name.
56    Other(u8),
57}
58
59impl ServiceError {
60    /// From the wire byte.
61    #[must_use]
62    pub const fn from_u8(v: u8) -> Self {
63        match v {
64            1 => Self::OperationNotPossible,
65            2 => Self::ServiceNotSupported,
66            3 => Self::OtherReason,
67            4 => Self::PduTooLong,
68            5 => Self::DecipheringError,
69            6 => Self::InvocationCounterError,
70            other => Self::Other(other),
71        }
72    }
73
74    /// The wire byte.
75    #[must_use]
76    pub const fn as_u8(self) -> u8 {
77        match self {
78            Self::OperationNotPossible => 1,
79            Self::ServiceNotSupported => 2,
80            Self::OtherReason => 3,
81            Self::PduTooLong => 4,
82            Self::DecipheringError => 5,
83            Self::InvocationCounterError => 6,
84            Self::Other(v) => v,
85        }
86    }
87}
88
89/// The server refused the APDU.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct ExceptionResponse {
92    /// The state that made it unacceptable.
93    pub state_error: StateError,
94    /// What was wrong.
95    pub service_error: ServiceError,
96    /// For [`ServiceError::InvocationCounterError`], the counter value the server
97    /// expects next.
98    ///
99    /// A client may use it to resynchronise **deliberately**; doing so automatically
100    /// would let anyone who can spoof one exception response replay an old frame.
101    pub expected_invocation_counter: Option<u32>,
102}
103
104impl Encode for ExceptionResponse {
105    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
106        w.write_u8(self.state_error.as_u8())?;
107        w.write_u8(self.service_error.as_u8())?;
108        if let Some(ic) = self.expected_invocation_counter {
109            w.write_u32(ic)?;
110        }
111        Ok(())
112    }
113}
114
115impl<'a> Decode<'a> for ExceptionResponse {
116    fn decode(r: &mut Reader<'a>) -> Result<Self> {
117        let state_error = StateError::from_u8(r.u8()?);
118        let service_error = ServiceError::from_u8(r.u8()?);
119        // The counter is only present for the counter error, and only in the later
120        // editions that added it — so it is decoded when it is there and not required.
121        let expected_invocation_counter =
122            if service_error == ServiceError::InvocationCounterError && r.remaining() >= 4 {
123                Some(r.u32()?)
124            } else {
125                None
126            };
127        Ok(Self { state_error, service_error, expected_invocation_counter })
128    }
129}
130
131/// A service-level error carried as its own APDU, used mostly by the ACSE-era services.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133pub struct ConfirmedServiceError {
134    /// Which service failed, as its `[n]` choice tag.
135    pub service: u8,
136    /// The error class.
137    pub error_class: u8,
138    /// The error code within the class.
139    pub error_code: u8,
140}
141
142impl Encode for ConfirmedServiceError {
143    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
144        w.write_bytes(&[self.service, self.error_class, self.error_code])
145    }
146
147    fn encoded_len(&self) -> usize {
148        3
149    }
150}
151
152impl<'a> Decode<'a> for ConfirmedServiceError {
153    fn decode(r: &mut Reader<'a>) -> Result<Self> {
154        Ok(Self { service: r.u8()?, error_class: r.u8()?, error_code: r.u8()? })
155    }
156}