Skip to main content

dlms_cosem_kit/xdlms/
apdu.rs

1//! The APDU: one enum over everything the application layer can send.
2
3use crate::acse::{Aare, Aarq, Rlre, Rlrq};
4use crate::codec::{Decode, Encode, ErrorKind, Reader, Result, Writer};
5
6use super::access::{AccessRequest, AccessResponse};
7use super::error::{ConfirmedServiceError, ExceptionResponse};
8use super::gbt::GeneralBlockTransfer;
9use super::initiate::{InitiateRequest, InitiateResponse};
10use super::notify::{DataNotification, EventNotification};
11use super::protection::{CipheredService, GeneralCiphering, GeneralGloCiphering, GeneralSigning};
12use super::service::{ActionRequest, ActionResponse, GetRequest, GetResponse, SetRequest, SetResponse};
13#[cfg(feature = "sn")]
14use super::sn::{
15    InformationReportRequest, ReadRequest, ReadResponse, UnconfirmedWriteRequest, WriteRequest, WriteResponse,
16};
17use super::tag::{ApduTag, Protection};
18
19/// Anything the application layer can send.
20///
21/// Decoding never fails on an APDU merely because it is protected: a ciphered service
22/// decodes into [`Apdu::Ciphered`] with its security header intact, so a translator, a
23/// fuzzer or a router can handle it without a key. [`crate::security`] turns one back
24/// into a plain `Apdu`.
25#[derive(Debug, Clone, Copy, PartialEq)]
26#[non_exhaustive]
27#[allow(missing_docs)]
28pub enum Apdu<'a> {
29    Aarq(Aarq<'a>),
30    Aare(Aare<'a>),
31    Rlrq(Rlrq<'a>),
32    Rlre(Rlre<'a>),
33
34    InitiateRequest(InitiateRequest<'a>),
35    InitiateResponse(InitiateResponse),
36
37    GetRequest(GetRequest<'a>),
38    GetResponse(GetResponse<'a>),
39    SetRequest(SetRequest<'a>),
40    SetResponse(SetResponse<'a>),
41    ActionRequest(ActionRequest<'a>),
42    ActionResponse(ActionResponse<'a>),
43    AccessRequest(AccessRequest<'a>),
44    AccessResponse(AccessResponse<'a>),
45
46    DataNotification(DataNotification<'a>),
47    EventNotification(EventNotification<'a>),
48
49    /// The short-name services, behind the `sn` feature.
50    ///
51    /// Legacy addressing: an attribute is a sixteen-bit number rather than a class,
52    /// a logical name and an index. Still what an installed base of pre-logical-name
53    /// meters speaks.
54    #[cfg(feature = "sn")]
55    ReadRequest(ReadRequest<'a>),
56    #[cfg(feature = "sn")]
57    #[allow(missing_docs)]
58    ReadResponse(ReadResponse<'a>),
59    #[cfg(feature = "sn")]
60    #[allow(missing_docs)]
61    WriteRequest(WriteRequest<'a>),
62    #[cfg(feature = "sn")]
63    #[allow(missing_docs)]
64    WriteResponse(WriteResponse<'a>),
65    #[cfg(feature = "sn")]
66    #[allow(missing_docs)]
67    UnconfirmedWriteRequest(UnconfirmedWriteRequest<'a>),
68    #[cfg(feature = "sn")]
69    #[allow(missing_docs)]
70    InformationReportRequest(InformationReportRequest<'a>),
71
72    ExceptionResponse(ExceptionResponse),
73    ConfirmedServiceError(ConfirmedServiceError),
74    GeneralBlockTransfer(GeneralBlockTransfer<'a>),
75
76    /// A `glo-` or `ded-` protected service, still protected.
77    Ciphered {
78        /// Which protection was applied.
79        protection: Protection,
80        /// Which service is inside.
81        service: ApduTag,
82        /// The security header and payload.
83        body: CipheredService<'a>,
84    },
85    /// A `general-glo-ciphering` or `general-ded-ciphering` APDU, still protected.
86    GeneralCiphered {
87        /// Which protection was applied.
88        protection: Protection,
89        /// The originator and the protected service.
90        body: GeneralGloCiphering<'a>,
91    },
92    GeneralCiphering(GeneralCiphering<'a>),
93    GeneralSigning(GeneralSigning<'a>),
94
95    /// An APDU addressed through a gateway, with the network and device it is for.
96    Gateway {
97        /// True for a response.
98        response: bool,
99        /// Which network behind the gateway.
100        network_id: u8,
101        /// Which device on it.
102        physical_device_address: &'a [u8],
103        /// The APDU to forward.
104        payload: &'a [u8],
105    },
106}
107
108impl Apdu<'_> {
109    /// The tag this APDU encodes with.
110    #[must_use]
111    pub const fn tag(&self) -> ApduTag {
112        match self {
113            Self::Aarq(_) => ApduTag::Aarq,
114            Self::Aare(_) => ApduTag::Aare,
115            Self::Rlrq(_) => ApduTag::ReleaseRequest,
116            Self::Rlre(_) => ApduTag::ReleaseResponse,
117            Self::InitiateRequest(_) => ApduTag::InitiateRequest,
118            Self::InitiateResponse(_) => ApduTag::InitiateResponse,
119            Self::GetRequest(_) => ApduTag::GetRequest,
120            Self::GetResponse(_) => ApduTag::GetResponse,
121            Self::SetRequest(_) => ApduTag::SetRequest,
122            Self::SetResponse(_) => ApduTag::SetResponse,
123            Self::ActionRequest(_) => ApduTag::ActionRequest,
124            Self::ActionResponse(_) => ApduTag::ActionResponse,
125            Self::AccessRequest(_) => ApduTag::AccessRequest,
126            Self::AccessResponse(_) => ApduTag::AccessResponse,
127            Self::DataNotification(_) => ApduTag::DataNotification,
128            Self::EventNotification(_) => ApduTag::EventNotificationRequest,
129            #[cfg(feature = "sn")]
130            Self::ReadRequest(_) => ApduTag::ReadRequest,
131            #[cfg(feature = "sn")]
132            Self::ReadResponse(_) => ApduTag::ReadResponse,
133            #[cfg(feature = "sn")]
134            Self::WriteRequest(_) => ApduTag::WriteRequest,
135            #[cfg(feature = "sn")]
136            Self::WriteResponse(_) => ApduTag::WriteResponse,
137            #[cfg(feature = "sn")]
138            Self::UnconfirmedWriteRequest(_) => ApduTag::UnconfirmedWriteRequest,
139            #[cfg(feature = "sn")]
140            Self::InformationReportRequest(_) => ApduTag::InformationReportRequest,
141            Self::ExceptionResponse(_) => ApduTag::ExceptionResponse,
142            Self::ConfirmedServiceError(_) => ApduTag::ConfirmedServiceError,
143            Self::GeneralBlockTransfer(_) => ApduTag::GeneralBlockTransfer,
144            // A `Ciphered` whose service has no form under this protection cannot be
145            // encoded at all, and [`Encode`] refuses it. Reporting the plain service
146            // here keeps this method total without inventing a tag that names a
147            // different service — which is what reporting `exception-response` did.
148            Self::Ciphered { protection, service, .. } => match service.protected_as(*protection) {
149                Some(t) => t,
150                None => *service,
151            },
152            Self::GeneralCiphered { protection, .. } => match protection {
153                Protection::Dedicated => ApduTag::GeneralDedCiphering,
154                _ => ApduTag::GeneralGloCiphering,
155            },
156            Self::GeneralCiphering(_) => ApduTag::GeneralCiphering,
157            Self::GeneralSigning(_) => ApduTag::GeneralSigning,
158            Self::Gateway { response: true, .. } => ApduTag::GatewayResponse,
159            Self::Gateway { response: false, .. } => ApduTag::GatewayRequest,
160        }
161    }
162
163    /// True when this APDU is protected and must be unprotected before it means
164    /// anything.
165    #[must_use]
166    pub const fn is_protected(&self) -> bool {
167        matches!(
168            self,
169            Self::Ciphered { .. }
170                | Self::GeneralCiphered { .. }
171                | Self::GeneralCiphering(_)
172                | Self::GeneralSigning(_)
173        )
174    }
175}
176
177impl Encode for Apdu<'_> {
178    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
179        // The ACSE APDUs carry their own BER tag; everything else is tag then body.
180        match self {
181            Self::Aarq(v) => return v.encode(w),
182            Self::Aare(v) => return v.encode(w),
183            Self::Rlrq(v) => return v.encode(w),
184            Self::Rlre(v) => return v.encode(w),
185            // A ciphered service whose plain tag has no form under the requested
186            // protection is refused rather than written under some other tag. There is
187            // no `unreachable!()` anywhere on this path: every arm below returns a
188            // `Result`, so nothing reachable from the network can abort the process.
189            Self::Ciphered { protection, service, .. } if service.protected_as(*protection).is_none() => {
190                return Err(crate::codec::Error::new(ErrorKind::InvalidValue, w.written()));
191            }
192            _ => {}
193        }
194        w.write_u8(self.tag().as_u8())?;
195        match self {
196            // Handled above; kept as an arm so the match stays exhaustive and adding a
197            // variant is a compile error rather than a silent fall-through.
198            Self::Aarq(_) | Self::Aare(_) | Self::Rlrq(_) | Self::Rlre(_) => {
199                Err(crate::codec::Error::new(ErrorKind::InvalidValue, w.written()))
200            }
201            Self::InitiateRequest(v) => v.encode(w),
202            Self::InitiateResponse(v) => v.encode(w),
203            Self::GetRequest(v) => v.encode(w),
204            Self::GetResponse(v) => v.encode(w),
205            Self::SetRequest(v) => v.encode(w),
206            Self::SetResponse(v) => v.encode(w),
207            Self::ActionRequest(v) => v.encode(w),
208            Self::ActionResponse(v) => v.encode(w),
209            Self::AccessRequest(v) => v.encode(w),
210            Self::AccessResponse(v) => v.encode(w),
211            Self::DataNotification(v) => v.encode(w),
212            Self::EventNotification(v) => v.encode(w),
213            #[cfg(feature = "sn")]
214            Self::ReadRequest(v) => v.encode(w),
215            #[cfg(feature = "sn")]
216            Self::ReadResponse(v) => v.encode(w),
217            #[cfg(feature = "sn")]
218            Self::WriteRequest(v) => v.encode(w),
219            #[cfg(feature = "sn")]
220            Self::WriteResponse(v) => v.encode(w),
221            #[cfg(feature = "sn")]
222            Self::UnconfirmedWriteRequest(v) => v.encode(w),
223            #[cfg(feature = "sn")]
224            Self::InformationReportRequest(v) => v.encode(w),
225            Self::ExceptionResponse(v) => v.encode(w),
226            Self::ConfirmedServiceError(v) => v.encode(w),
227            Self::GeneralBlockTransfer(v) => v.encode(w),
228            Self::Ciphered { body, .. } => body.encode(w),
229            Self::GeneralCiphered { body, .. } => body.encode(w),
230            Self::GeneralCiphering(v) => v.encode(w),
231            Self::GeneralSigning(v) => v.encode(w),
232            Self::Gateway { network_id, physical_device_address, payload, .. } => {
233                w.write_u8(*network_id)?;
234                w.write_length_prefixed(physical_device_address)?;
235                w.write_bytes(payload)
236            }
237        }
238    }
239}
240
241impl<'a> Decode<'a> for Apdu<'a> {
242    fn decode(r: &mut Reader<'a>) -> Result<Self> {
243        let tag_byte = r.peek_u8()?;
244        let tag = ApduTag::from_u8(tag_byte).ok_or_else(|| r.err(ErrorKind::InvalidTag(tag_byte)))?;
245        // ACSE APDUs are BER and re-read their own tag.
246        match tag {
247            ApduTag::Aarq => return Ok(Self::Aarq(Aarq::decode(r)?)),
248            ApduTag::Aare => return Ok(Self::Aare(Aare::decode(r)?)),
249            ApduTag::ReleaseRequest => return Ok(Self::Rlrq(Rlrq::decode(r)?)),
250            ApduTag::ReleaseResponse => return Ok(Self::Rlre(Rlre::decode(r)?)),
251            _ => {}
252        }
253        r.skip(1)?;
254        if let Some((protection, service)) = tag.unprotect() {
255            return Ok(Self::Ciphered { protection, service, body: CipheredService::decode(r)? });
256        }
257        Ok(match tag {
258            ApduTag::InitiateRequest => Self::InitiateRequest(InitiateRequest::decode(r)?),
259            ApduTag::InitiateResponse => Self::InitiateResponse(InitiateResponse::decode(r)?),
260            ApduTag::GetRequest => Self::GetRequest(GetRequest::decode(r)?),
261            ApduTag::GetResponse => Self::GetResponse(GetResponse::decode(r)?),
262            ApduTag::SetRequest => Self::SetRequest(SetRequest::decode(r)?),
263            ApduTag::SetResponse => Self::SetResponse(SetResponse::decode(r)?),
264            ApduTag::ActionRequest => Self::ActionRequest(ActionRequest::decode(r)?),
265            ApduTag::ActionResponse => Self::ActionResponse(ActionResponse::decode(r)?),
266            ApduTag::AccessRequest => Self::AccessRequest(AccessRequest::decode(r)?),
267            ApduTag::AccessResponse => Self::AccessResponse(AccessResponse::decode(r)?),
268            ApduTag::DataNotification => Self::DataNotification(DataNotification::decode(r)?),
269            ApduTag::EventNotificationRequest => Self::EventNotification(EventNotification::decode(r)?),
270            #[cfg(feature = "sn")]
271            ApduTag::ReadRequest => Self::ReadRequest(ReadRequest::decode(r)?),
272            #[cfg(feature = "sn")]
273            ApduTag::ReadResponse => Self::ReadResponse(ReadResponse::decode(r)?),
274            #[cfg(feature = "sn")]
275            ApduTag::WriteRequest => Self::WriteRequest(WriteRequest::decode(r)?),
276            #[cfg(feature = "sn")]
277            ApduTag::WriteResponse => Self::WriteResponse(WriteResponse::decode(r)?),
278            #[cfg(feature = "sn")]
279            ApduTag::UnconfirmedWriteRequest => {
280                Self::UnconfirmedWriteRequest(UnconfirmedWriteRequest::decode(r)?)
281            }
282            #[cfg(feature = "sn")]
283            ApduTag::InformationReportRequest => {
284                Self::InformationReportRequest(InformationReportRequest::decode(r)?)
285            }
286            ApduTag::ExceptionResponse => Self::ExceptionResponse(ExceptionResponse::decode(r)?),
287            ApduTag::ConfirmedServiceError => Self::ConfirmedServiceError(ConfirmedServiceError::decode(r)?),
288            ApduTag::GeneralBlockTransfer => Self::GeneralBlockTransfer(GeneralBlockTransfer::decode(r)?),
289            ApduTag::GeneralGloCiphering => Self::GeneralCiphered {
290                protection: Protection::Global,
291                body: GeneralGloCiphering::decode(r)?,
292            },
293            ApduTag::GeneralDedCiphering => Self::GeneralCiphered {
294                protection: Protection::Dedicated,
295                body: GeneralGloCiphering::decode(r)?,
296            },
297            ApduTag::GeneralCiphering => Self::GeneralCiphering(GeneralCiphering::decode(r)?),
298            ApduTag::GeneralSigning => Self::GeneralSigning(GeneralSigning::decode(r)?),
299            ApduTag::GatewayRequest | ApduTag::GatewayResponse => Self::Gateway {
300                response: tag == ApduTag::GatewayResponse,
301                network_id: r.u8()?,
302                physical_device_address: r.length_prefixed()?,
303                payload: r.take_rest(),
304            },
305            _ => return Err(r.err_back(ErrorKind::InvalidTag(tag_byte), 1)),
306        })
307    }
308}