Skip to main content

dlms_cosem_kit/client/
driver.rs

1//! A blocking client: the session, a transport, and every loop a meter read needs.
2//!
3//! [`ClientSession`] is sans-I/O and stays that way — it is what runs in firmware and under
4//! an async runtime. This is the layer a head-end or a tool wants on top of it: one call
5//! per service, with association (high-level security included), service-level block
6//! transfer and general block transfer in both directions handled inside, and either owned values
7//! or GET results borrowing caller-provided storage.
8//!
9//! ```no_run
10//! use dlms_cosem_kit::client::{Client, ClientConfig, ClientError, Transport};
11//! use dlms_cosem_kit::obis::Obis;
12//! use dlms_cosem_kit::security::{KeyRing, RustCryptoProvider};
13//!
14//! // `link` is a `transport::WrapperTransport`, a `transport::HdlcTransport`, or your own.
15//! fn read_energy(link: impl Transport) -> Result<(), ClientError> {
16//!     let mut meter: Client<_, _> =
17//!         Client::connect(link, ClientConfig::default(), RustCryptoProvider::os(KeyRing::default()))?;
18//!     let energy = meter.read_scaled(3, Obis::new(1, 0, 1, 8, 0, 255))?;
19//!     println!("{energy}");
20//!     meter.release()?;
21//!     Ok(())
22//! }
23//! ```
24
25use std::io;
26use std::vec;
27use std::vec::Vec;
28
29use crate::acse::{AssociationResult, Diagnostic, ReleaseResponseReason};
30use crate::axdr::{Data, DataBuf, ScaledValue, Unit};
31use crate::codec::{Decode, Encode, Error, ErrorKind, SliceWriter, Writer};
32use crate::obis::Obis;
33use crate::security::CryptoProvider;
34use crate::xdlms::{
35    ActionResult, ApduTag, AttributeDescriptor, AttributeDescriptorWithSelection, Conformance,
36    DataAccessResult, ExceptionResponse, GbtSender, InitiateResponse, MethodDescriptor, SelectiveAccess,
37};
38
39use super::{AssociationStep, ClientConfig, ClientSession, Response};
40
41/// Something that carries one APDU at a time to a meter and back.
42///
43/// Framing is the transport's business — the wrapper header, HDLC frames and their
44/// segmentation, a radio's own encapsulation — and so is reassembling a stream into whole
45/// APDUs. Two operations rather than one request/response call, because a meter streaming
46/// general-block-transfer blocks sends several APDUs for one request.
47///
48/// [`WrapperTransport`](crate::transport::WrapperTransport) and
49/// [`HdlcTransport`](crate::transport::HdlcTransport) are the two this crate ships.
50pub trait Transport {
51    /// Send one APDU.
52    ///
53    /// # Errors
54    /// When the link fails.
55    fn send(&mut self, apdu: &[u8]) -> io::Result<()>;
56
57    /// Receive one APDU into `buf`, returning its length.
58    ///
59    /// # Errors
60    /// When the link fails, times out, or delivers an APDU larger than `buf`.
61    fn recv(&mut self, buf: &mut [u8]) -> io::Result<usize>;
62
63    /// Close the link after the association is released. The default does nothing.
64    ///
65    /// # Errors
66    /// When the link fails.
67    fn close(&mut self) -> io::Result<()> {
68        Ok(())
69    }
70}
71
72impl<T: Transport + ?Sized> Transport for &mut T {
73    fn send(&mut self, apdu: &[u8]) -> io::Result<()> {
74        (**self).send(apdu)
75    }
76    fn recv(&mut self, buf: &mut [u8]) -> io::Result<usize> {
77        (**self).recv(buf)
78    }
79    fn close(&mut self) -> io::Result<()> {
80        (**self).close()
81    }
82}
83
84impl<T: Transport + ?Sized> Transport for std::boxed::Box<T> {
85    fn send(&mut self, apdu: &[u8]) -> io::Result<()> {
86        (**self).send(apdu)
87    }
88    fn recv(&mut self, buf: &mut [u8]) -> io::Result<usize> {
89        (**self).recv(buf)
90    }
91    fn close(&mut self) -> io::Result<()> {
92        (**self).close()
93    }
94}
95
96/// Everything a [`Client`] call can fail with.
97///
98/// Every arm carries codes, results and offsets — never key material or a decrypted
99/// payload — so an error can be logged as it is.
100#[derive(Debug)]
101#[non_exhaustive]
102pub enum ClientError {
103    /// The transport failed: a socket error, a timeout, a peer that closed the link.
104    Io(io::Error),
105    /// A malformed, unexpected or unverifiable APDU; the byte offset says where.
106    Protocol(Error),
107    /// The meter refused the association.
108    Rejected {
109        /// Its result.
110        result: AssociationResult,
111        /// Its reason.
112        diagnostic: Diagnostic,
113    },
114    /// The meter refused the APDU itself. For a ciphered association the commonest cause
115    /// is a stale invocation counter, and then `expected_invocation_counter` names the
116    /// value to move to.
117    Exception(ExceptionResponse),
118    /// The meter refused a read or a write.
119    Refused(DataAccessResult),
120    /// A method did not run.
121    ActionFailed(ActionResult),
122    /// The response exceeded the configured byte budget.
123    ResponseTooLarge {
124        /// Maximum encoded result bytes for this call.
125        limit: usize,
126        /// An unfinished or unverified transfer was abandoned. Open a fresh connection.
127        reconnect_required: bool,
128    },
129    /// The meter answered the release but did not release: its reason.
130    ReleaseRefused(ReleaseResponseReason),
131    /// The association has already ended on this side, after a transfer that had to be
132    /// abandoned. Nothing was sent. Connect again.
133    NotAssociated,
134    /// A response of a kind the request cannot have.
135    Unexpected,
136}
137
138impl core::fmt::Display for ClientError {
139    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
140        match self {
141            Self::Io(e) => write!(f, "transport: {e}"),
142            Self::Protocol(e) => write!(f, "protocol: {e}"),
143            Self::Rejected { result, diagnostic } => {
144                write!(f, "association rejected: {result:?} ({diagnostic:?})")
145            }
146            Self::Exception(e) => match e.expected_invocation_counter {
147                Some(n) => write!(
148                    f,
149                    "the meter refused the request ({:?}); it expects invocation counter {n}",
150                    e.service_error
151                ),
152                None => {
153                    write!(f, "the meter refused the request: {:?} / {:?}", e.state_error, e.service_error)
154                }
155            },
156            Self::Refused(r) => write!(f, "refused: {r:?}"),
157            Self::ActionFailed(r) => write!(f, "method failed: {r:?}"),
158            Self::ResponseTooLarge { limit, reconnect_required } => {
159                write!(f, "response exceeds the {limit}-byte budget")?;
160                if *reconnect_required {
161                    f.write_str("; reconnect before retrying")?;
162                }
163                Ok(())
164            }
165            Self::ReleaseRefused(r) => write!(f, "the meter refused the release: {r:?}"),
166            Self::NotAssociated => f.write_str("the association has ended; connect again"),
167            Self::Unexpected => f.write_str("a response of the wrong kind"),
168        }
169    }
170}
171
172impl std::error::Error for ClientError {
173    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
174        match self {
175            Self::Io(e) => Some(e),
176            Self::Protocol(e) => Some(e),
177            _ => None,
178        }
179    }
180}
181
182impl From<io::Error> for ClientError {
183    fn from(e: io::Error) -> Self {
184        Self::Io(e)
185    }
186}
187
188impl From<Error> for ClientError {
189    fn from(e: Error) -> Self {
190        Self::Protocol(e)
191    }
192}
193
194/// What a step of an exchange decided.
195enum Step<R> {
196    /// The answer.
197    Done(R),
198    /// Send `request[..n]` and keep going.
199    Send(usize),
200}
201
202/// The bytes a [`Client`] keeps between calls, apart from the session.
203struct Buffers {
204    /// Where requests are built.
205    request: Vec<u8>,
206    /// Where responses are decrypted and GBT blocks gathered.
207    response: Vec<u8>,
208    /// One APDU as the transport delivered it.
209    frame: Vec<u8>,
210}
211
212/// A blocking DLMS client over a [`Transport`].
213///
214/// `N` is the session's request buffer: the largest request it builds before block
215/// transfer takes over. Single-value reads accept at most 64 KiB of encoded A-XDR data
216/// by default. Set the limit with [`Client::with_response_capacity`] or supply a smaller
217/// output slice to [`Client::get_into`]. Transport framing and protection use separate
218/// workspace.
219///
220/// Call [`Client::release`] to release the association before dropping the client.
221pub struct Client<T, P, const N: usize = 1024> {
222    session: ClientSession<P, N>,
223    transport: T,
224    bufs: Buffers,
225    value_limit: usize,
226}
227
228impl<T, P: CryptoProvider, const N: usize> core::fmt::Debug for Client<T, P, N> {
229    /// The session's state and counters only: never the provider, whose keys these are,
230    /// and never a buffer, which may hold a decrypted response.
231    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
232        f.debug_struct("Client")
233            .field("state", &self.session.state())
234            .field("invocation_counter", &self.session.invocation_counter())
235            .field("negotiated", &self.session.negotiated())
236            .finish_non_exhaustive()
237    }
238}
239
240/// Default limit in encoded result bytes.
241const DEFAULT_RESPONSE_CAPACITY: usize = 64 * 1024;
242
243/// What the GBT block header costs around its data, worst case.
244const GBT_HEADER_MAX: usize = 1 + 1 + 2 + 2 + 3;
245
246impl<T: Transport, P: CryptoProvider, const N: usize> Client<T, P, N> {
247    /// Associate over `transport`, running every pass the mechanism needs.
248    ///
249    /// Returns only once the association is **established** — for high-level security,
250    /// after the meter has proven it holds the key, not merely after it accepted ours.
251    ///
252    /// # Errors
253    /// [`ClientError::Rejected`] or [`ClientError::Exception`] when the meter refuses;
254    /// [`ClientError::Protocol`] when its proof does not verify; [`ClientError::Io`].
255    pub fn connect(transport: T, config: ClientConfig, provider: P) -> Result<Self, ClientError> {
256        let frame_len = usize::from(config.max_pdu_size).max(256).saturating_add(64);
257        let mut client = Self {
258            session: ClientSession::new(config, provider),
259            transport,
260            value_limit: DEFAULT_RESPONSE_CAPACITY,
261            bufs: Buffers {
262                request: vec![0; N.saturating_add(64)],
263                response: vec![0; frame_len],
264                frame: vec![0; frame_len],
265            },
266        };
267        client.associate()?;
268        Ok(client)
269    }
270
271    /// Set the maximum encoded value size for a GET, including its A-XDR type tag.
272    /// The default is 64 KiB. The limit also bounds the encoded result list for a
273    /// list GET and the encoded return value of an ACTION. A smaller caller buffer
274    /// further limits a [`get_into`](Self::get_into) call.
275    ///
276    /// The configured receive PDU determines the frame size independently of this limit.
277    /// GBT may stage up to the effective limit plus one receive frame for the
278    /// protected APDU envelope. Set transport timeouts and wire budgets separately.
279    #[must_use]
280    pub fn with_response_capacity(mut self, bytes: usize) -> Self {
281        self.value_limit = bytes;
282        let ceiling = bytes.saturating_add(self.bufs.frame.len());
283        if self.bufs.response.len() > ceiling {
284            self.bufs.response.truncate(ceiling);
285            self.bufs.response.shrink_to_fit();
286        }
287        self
288    }
289
290    fn associate(&mut self) -> Result<(), ClientError> {
291        let n = self.session.associate_request(&mut self.bufs.request)?;
292        self.transport.send(self.bufs.request.get(..n).unwrap_or(&[]))?;
293        let m = self.transport.recv(&mut self.bufs.frame)?;
294        let mut step = self.session.handle_associate_response(self.bufs.frame.get(..m).unwrap_or(&[]))?;
295        if step == AssociationStep::HlsReplyRequired {
296            let n = self.session.hls_reply_request(&mut self.bufs.request)?;
297            self.transport.send(self.bufs.request.get(..n).unwrap_or(&[]))?;
298            let m = self.transport.recv(&mut self.bufs.frame)?;
299            step = self.session.handle_hls_reply_response(self.bufs.frame.get(..m).unwrap_or(&[]))?;
300        }
301        match step {
302            AssociationStep::Established => Ok(()),
303            AssociationStep::Rejected { result, diagnostic } => {
304                Err(ClientError::Rejected { result, diagnostic })
305            }
306            AssociationStep::Exception(e) => Err(ClientError::Exception(e)),
307            // A second "reply required" is a meter that will not finish the handshake.
308            AssociationStep::HlsReplyRequired => Err(ClientError::Unexpected),
309        }
310    }
311
312    /// Read an attribute.
313    ///
314    /// # Errors
315    /// [`ClientError::Refused`] with the meter's reason, [`ClientError::ResponseTooLarge`]
316    /// with the effective limit and recovery status, or a transport or protocol error.
317    pub fn get(&mut self, attribute: AttributeDescriptor) -> Result<DataBuf, ClientError> {
318        self.get_owned(attribute, None)
319    }
320
321    /// Read part of an attribute — a range of a profile, by entry or by date.
322    ///
323    /// # Errors
324    /// As [`Client::get`].
325    pub fn get_selected(
326        &mut self,
327        attribute: AttributeDescriptor,
328        access: SelectiveAccess<'_>,
329    ) -> Result<DataBuf, ClientError> {
330        self.get_owned(attribute, Some(access))
331    }
332
333    /// Read one attribute, optionally selected, into caller-owned storage.
334    ///
335    /// The result borrows only `out`; the client can issue another request while the
336    /// value is in use. The slice must fit the entire encoded value including its tag.
337    /// On error its contents are unspecified.
338    ///
339    /// # Errors
340    /// [`ClientError::ResponseTooLarge`] reports the effective limit. A completed,
341    /// verified response leaves the association usable. If `reconnect_required` is
342    /// true, the session is closed locally. [`ClientError::Refused`] preserves the
343    /// meter's access result.
344    pub fn get_into<'a>(
345        &mut self,
346        attribute: AttributeDescriptor,
347        access: Option<SelectiveAccess<'_>>,
348        out: &'a mut [u8],
349    ) -> Result<Data<'a>, ClientError> {
350        let limit = self.value_limit.min(out.len());
351        let mut blocks = Blocks::new(SliceWriter::new(out), limit);
352        self.read_value(
353            attribute,
354            access,
355            &mut blocks,
356            |writer, _, encoded| Ok(writer.write_bytes(encoded)?),
357            |_| Ok(()),
358        )?;
359        Ok(Data::from_bytes(blocks.bytes.finish())?)
360    }
361
362    fn get_owned(
363        &mut self,
364        attribute: AttributeDescriptor,
365        access: Option<SelectiveAccess<'_>>,
366    ) -> Result<DataBuf, ClientError> {
367        let mut blocks = Blocks::new(Vec::new(), self.value_limit);
368        self.read_value(
369            attribute,
370            access,
371            &mut blocks,
372            |_, value, _| Ok(DataBuf::from_data(&value)?),
373            |bytes| Ok(DataBuf::parse(bytes)?),
374        )
375    }
376
377    /// Read several attributes in one round trip, one result each.
378    ///
379    /// A refused attribute does not fail the call: its slot holds the reason.
380    ///
381    /// # Errors
382    /// When the whole request fails.
383    pub fn get_list(
384        &mut self,
385        attributes: &[AttributeDescriptor],
386    ) -> Result<Vec<Result<DataBuf, DataAccessResult>>, ClientError> {
387        self.ensure_associated()?;
388        let items: Vec<_> = attributes
389            .iter()
390            .map(|d| AttributeDescriptorWithSelection { descriptor: *d, access: None })
391            .collect();
392        let n = self.session.get_request_with_list(&items, &mut self.bufs.request)?;
393        let limit = self.value_limit;
394        let mut blocks = Blocks::new(Vec::new(), limit);
395        self.run(n, limit, |session, response, request, plain| {
396            let results = match response {
397                Response::DataList(results) if blocks.last == 0 => {
398                    // The GET tag, choice and invoke id precede the encoded list.
399                    blocks.check_size(plain.len().saturating_sub(3), true)?;
400                    results
401                }
402                Response::Block { last, number, data } => {
403                    blocks.push(number, last, data)?;
404                    if !last {
405                        return Ok(Step::Send(session.get_next_block_request(number, request)?));
406                    }
407                    crate::xdlms::List::<crate::xdlms::GetDataResult<'_>>::from_bytes(&blocks.bytes)?
408                }
409                Response::DataError(e) => return Err(ClientError::Refused(e)),
410                _ => return Err(ClientError::Unexpected),
411            };
412            if results.len() != attributes.len() {
413                return Err(ClientError::Unexpected);
414            }
415            let mut out = Vec::with_capacity(results.len());
416            for result in results.iter() {
417                out.push(match result?.value() {
418                    Ok(d) => Ok(DataBuf::from_data(&d)?),
419                    Err(e) => Err(e),
420                });
421            }
422            Ok(Step::Done(out))
423        })
424    }
425
426    /// Read a register's value with its scaler and unit — the attribute pair a register,
427    /// an extended register and a demand register (classes 3, 4, 5) all carry as 2 and 3 —
428    /// in one round trip.
429    ///
430    /// # Errors
431    /// When either attribute is refused, or is not the shape a register's is.
432    pub fn read_scaled(&mut self, class_id: u16, logical_name: Obis) -> Result<ScaledValue, ClientError> {
433        let attrs = [
434            AttributeDescriptor::new(class_id, logical_name, 2),
435            AttributeDescriptor::new(class_id, logical_name, 3),
436        ];
437        let mut results = self.get_list(&attrs)?.into_iter();
438        let value = results.next().ok_or(ClientError::Unexpected)?.map_err(ClientError::Refused)?;
439        let scaler_unit = results.next().ok_or(ClientError::Unexpected)?.map_err(ClientError::Refused)?;
440        let value = value.as_i64().ok_or(ClientError::Refused(DataAccessResult::TypeUnmatched))?;
441        let [scaler, unit] = scaler_unit.as_structure().unwrap_or(&[]) else {
442            return Err(ClientError::Refused(DataAccessResult::TypeUnmatched));
443        };
444        let scaler = scaler.as_i64().and_then(|s| i8::try_from(s).ok());
445        let unit = unit.as_i64().and_then(|u| u8::try_from(u).ok());
446        match (scaler, unit) {
447            (Some(s), Some(u)) => Ok(ScaledValue::new(value, s, Unit(u))),
448            _ => Err(ClientError::Refused(DataAccessResult::TypeUnmatched)),
449        }
450    }
451
452    /// Write an attribute. A value too large for one APDU is sent in blocks.
453    ///
454    /// # Errors
455    /// [`ClientError::Refused`] with the meter's reason; any transport or protocol error.
456    pub fn set(&mut self, attribute: AttributeDescriptor, value: &Data<'_>) -> Result<(), ClientError> {
457        self.ensure_associated()?;
458        let encoded = encode(value)?;
459        let whole = self.session.set_request(attribute, None, *value, &mut self.bufs.request);
460        let n = match whole {
461            Ok(n) if self.fits(n) || self.gbt() => n,
462            // Too large for one APDU and no GBT: the service's own block form, if agreed.
463            Ok(_) | Err(Error { kind: ErrorKind::BufferTooSmall { .. }, .. }) => {
464                let mut sender = self.session.set_transfer(attribute, None, &encoded)?;
465                let n = self.session.next_block_request(&mut sender, &mut self.bufs.request)?;
466                return self.run(n, self.value_limit, |session, response, request, _| match response {
467                    Response::BlockAccepted { .. } => {
468                        Ok(Step::Send(session.next_block_request(&mut sender, request)?))
469                    }
470                    Response::Ok => Ok(Step::Done(())),
471                    Response::DataError(e) => Err(ClientError::Refused(e)),
472                    _ => Err(ClientError::Unexpected),
473                });
474            }
475            Err(e) => return Err(e.into()),
476        };
477        self.run(n, self.value_limit, |_, response, _, _| match response {
478            Response::Ok => Ok(Step::Done(())),
479            Response::DataError(e) => Err(ClientError::Refused(e)),
480            _ => Err(ClientError::Unexpected),
481        })
482    }
483
484    /// Invoke a method, returning what it returned. A parameter too large for one APDU is
485    /// sent in blocks, and so is a return value too large for one.
486    ///
487    /// # Errors
488    /// [`ClientError::ActionFailed`] with the method's result; any transport or protocol
489    /// error.
490    pub fn action(
491        &mut self,
492        method: MethodDescriptor,
493        parameter: Option<&Data<'_>>,
494    ) -> Result<Option<DataBuf>, ClientError> {
495        self.ensure_associated()?;
496        let whole = self.session.action_request(method, parameter.copied(), &mut self.bufs.request);
497        let mut blocks = Blocks::new(Vec::new(), self.value_limit);
498        let n = match whole {
499            Ok(n) if self.fits(n) || self.gbt() => n,
500            Ok(_) | Err(Error { kind: ErrorKind::BufferTooSmall { .. }, .. }) => {
501                let encoded = encode(parameter.ok_or(ClientError::Unexpected)?)?;
502                let mut sender = self.session.action_transfer(method, &encoded)?;
503                let n = self.session.next_block_request(&mut sender, &mut self.bufs.request)?;
504                return self.run(n, self.value_limit, |session, response, request, plain| match response {
505                    Response::BlockAccepted { .. } if !sender.is_done() => {
506                        Ok(Step::Send(session.next_block_request(&mut sender, request)?))
507                    }
508                    other => action_outcome(session, other, request, &mut blocks, plain),
509                });
510            }
511            Err(e) => return Err(e.into()),
512        };
513        self.run(n, self.value_limit, |session, response, request, plain| {
514            action_outcome(session, response, request, &mut blocks, plain)
515        })
516    }
517
518    /// Release the association, close the link and hand the transport back — only once
519    /// the meter has confirmed the release.
520    ///
521    /// Success means a release response arrived and released: commit what the
522    /// association read on it. The link is closed on every path.
523    ///
524    /// # Errors
525    /// [`ClientError::ReleaseRefused`] with the meter's reason;
526    /// [`ClientError::NotAssociated`] after a transfer that ended the association (use
527    /// [`Client::disconnect`]); [`ClientError::Io`] when the link fails or the meter
528    /// closes it before answering; [`ClientError::Exception`] or a protocol error.
529    pub fn release(mut self) -> Result<T, ClientError> {
530        let released = self.confirm_release();
531        let closed = self.transport.close();
532        released?;
533        closed?;
534        Ok(self.transport)
535    }
536
537    /// Close the link without releasing the association, handing the transport back.
538    ///
539    /// For a session that has already ended, or a meter that ends associations by
540    /// dropping the link.
541    ///
542    /// ```no_run
543    /// # use dlms_cosem_kit::client::{Client, ClientError, Transport};
544    /// # use dlms_cosem_kit::security::CryptoProvider;
545    /// # use dlms_cosem_kit::xdlms::AttributeDescriptor;
546    /// fn read_once<T: Transport, P: CryptoProvider>(
547    ///     mut meter: Client<T, P>,
548    ///     profile: AttributeDescriptor,
549    /// ) -> Result<T, ClientError> {
550    ///     match meter.get(profile) {
551    ///         // The transfer was abandoned and the association is gone: nothing to release.
552    ///         Err(ClientError::ResponseTooLarge { reconnect_required: true, .. }) => meter.disconnect(),
553    ///         Err(e) => Err(e),
554    ///         Ok(_rows) => meter.release(), // commit `_rows` once this succeeds
555    ///     }
556    /// }
557    /// ```
558    ///
559    /// # Errors
560    /// When closing the link fails.
561    pub fn disconnect(mut self) -> Result<T, ClientError> {
562        self.transport.close()?;
563        Ok(self.transport)
564    }
565
566    fn confirm_release(&mut self) -> Result<(), ClientError> {
567        self.ensure_associated()?;
568        let n = self.session.release_request(&mut self.bufs.request)?;
569        self.transport.send(self.bufs.request.get(..n).unwrap_or(&[]))?;
570        let m = self.transport.recv(&mut self.bufs.frame)?;
571        let frame = self.bufs.frame.get(..m).ok_or(ClientError::Unexpected)?;
572        match self.session.handle_response(frame, &mut self.bufs.response)? {
573            Response::Released { reason: None | Some(ReleaseResponseReason::Normal) } => Ok(()),
574            Response::Released { reason: Some(reason) } => Err(ClientError::ReleaseRefused(reason)),
575            Response::Exception(e) => Err(ClientError::Exception(e)),
576            _ => Err(ClientError::Unexpected),
577        }
578    }
579
580    fn ensure_associated(&self) -> Result<(), ClientError> {
581        if self.session.state() == super::SessionState::Closed {
582            return Err(ClientError::NotAssociated);
583        }
584        Ok(())
585    }
586
587    /// The invocation counter this client will use next.
588    ///
589    /// **Persist it** before the process ends and pass it back as
590    /// [`ClientConfig::invocation_counter`] next time: restarting from an old value under
591    /// an unchanged key repeats GCM nonces, and a repeated nonce leaks the key's
592    /// authentication subkey.
593    #[must_use]
594    pub const fn invocation_counter(&self) -> u32 {
595        self.session.invocation_counter()
596    }
597
598    /// What the meter agreed to.
599    #[must_use]
600    pub const fn negotiated(&self) -> Option<&InitiateResponse> {
601        self.session.negotiated()
602    }
603
604    /// The session underneath, for anything this layer does not wrap.
605    #[must_use]
606    pub const fn session(&self) -> &ClientSession<P, N> {
607        &self.session
608    }
609
610    /// The session underneath, mutably.
611    pub const fn session_mut(&mut self) -> &mut ClientSession<P, N> {
612        &mut self.session
613    }
614
615    /// The transport underneath.
616    pub const fn transport_mut(&mut self) -> &mut T {
617        &mut self.transport
618    }
619
620    fn server_max(&self) -> usize {
621        self.session.negotiated().map_or(usize::MAX, |n| match n.server_max_receive_pdu_size {
622            0 => usize::MAX,
623            size => usize::from(size),
624        })
625    }
626
627    fn fits(&self, n: usize) -> bool {
628        n <= self.server_max()
629    }
630
631    fn gbt(&self) -> bool {
632        self.session
633            .negotiated()
634            .is_some_and(|n| n.negotiated_conformance.contains(Conformance::GENERAL_BLOCK_TRANSFER))
635    }
636
637    /// A value-returning read: whole, in service-level blocks, or over GBT.
638    fn read_value<W: Writer, R>(
639        &mut self,
640        attribute: AttributeDescriptor,
641        access: Option<SelectiveAccess<'_>>,
642        blocks: &mut Blocks<W>,
643        whole: impl Fn(&mut W, Data<'_>, &[u8]) -> Result<R, ClientError>,
644        reassembled: impl Fn(&W) -> Result<R, ClientError>,
645    ) -> Result<R, ClientError> {
646        self.ensure_associated()?;
647        let n = self.session.get_request(attribute, access, &mut self.bufs.request)?;
648        self.run(n, blocks.limit, |session, response, request, plain| match response {
649            Response::Data(value) if blocks.last == 0 => {
650                // The validated GetResponseNormal consists of tag, choice, invoke id,
651                // success choice, then the original encoded Data through the end.
652                let encoded = plain.get(4..).ok_or(ClientError::Unexpected)?;
653                blocks.check_size(encoded.len(), true)?;
654                Ok(Step::Done(whole(&mut blocks.bytes, value, encoded)?))
655            }
656            Response::DataError(e) => Err(ClientError::Refused(e)),
657            Response::Block { last, number, data } => {
658                blocks.push(number, last, data)?;
659                if last {
660                    Ok(Step::Done(reassembled(&blocks.bytes)?))
661                } else {
662                    Ok(Step::Send(session.get_next_block_request(number, request)?))
663                }
664            }
665            _ => Err(ClientError::Unexpected),
666        })
667    }
668
669    /// Send `request[..n]`, then feed every APDU that comes back to the session until
670    /// `step` has its answer.
671    ///
672    /// GBT on the way in is invisible to `step`: blocks are gathered and acknowledged
673    /// here, and `step` sees the reassembled response. Exceptions end the call.
674    fn run<R>(
675        &mut self,
676        n: usize,
677        limit: usize,
678        mut step: impl FnMut(
679            &mut ClientSession<P, N>,
680            Response<'_>,
681            &mut [u8],
682            &[u8],
683        ) -> Result<Step<R>, ClientError>,
684    ) -> Result<R, ClientError> {
685        let Self { session, transport, bufs, .. } = self;
686        let server_max = session.negotiated().map_or(usize::MAX, |i| match i.server_max_receive_pdu_size {
687            0 => usize::MAX,
688            size => usize::from(size),
689        });
690        let gbt = session
691            .negotiated()
692            .is_some_and(|i| i.negotiated_conformance.contains(Conformance::GENERAL_BLOCK_TRANSFER));
693        let mut pending = Some(n);
694        loop {
695            if let Some(n) = pending.take() {
696                let request = bufs.request.get(..n).unwrap_or(&[]);
697                if n > server_max && gbt {
698                    send_as_gbt(
699                        session,
700                        transport,
701                        request,
702                        server_max,
703                        &mut bufs.frame,
704                        &mut bufs.response,
705                    )?;
706                } else {
707                    transport.send(request)?;
708                }
709            }
710            let m = transport.recv(&mut bufs.frame)?;
711            let frame = bufs.frame.get(..m).ok_or(ClientError::Unexpected)?;
712            let is_gbt = frame.first() == Some(&ApduTag::GeneralBlockTransfer.as_u8());
713            // A protected GBT response must be staged until authentication completes.
714            // Reserve only as blocks arrive and allow one frame for envelope overhead.
715            let ceiling = limit.saturating_add(bufs.frame.len());
716            if is_gbt {
717                let wanted = session.received_gbt_bytes().saturating_add(m).min(ceiling);
718                if wanted > bufs.response.len() {
719                    let size = wanted.max(bufs.response.len().saturating_mul(2).min(ceiling));
720                    bufs.response.reserve_exact(size.saturating_sub(bufs.response.len()));
721                    bufs.response.resize(size, 0);
722                }
723            }
724            let workspace_len = bufs.response.len().min(ceiling);
725            let workspace = bufs.response.get_mut(..workspace_len).ok_or(ClientError::Unexpected)?;
726            let (response, plain) = match session.handle_response_bytes(frame, workspace) {
727                Err(Error { kind: ErrorKind::BufferTooSmall { .. }, .. }) if is_gbt => {
728                    session.abandon();
729                    return Err(ClientError::ResponseTooLarge { limit, reconnect_required: true });
730                }
731                result => result?,
732            };
733            match response {
734                Response::Pending => {}
735                Response::Acknowledge(ack) => transport.send(ack.as_bytes())?,
736                Response::Exception(e) => return Err(ClientError::Exception(e)),
737                other => match step(session, other, &mut bufs.request, plain) {
738                    Ok(Step::Done(r)) => return Ok(r),
739                    Ok(Step::Send(n)) => pending = Some(n),
740                    Err(e) => {
741                        if matches!(e, ClientError::ResponseTooLarge { reconnect_required: true, .. }) {
742                            session.abandon();
743                        }
744                        return Err(e);
745                    }
746                },
747            }
748        }
749    }
750}
751
752/// Send a request too large for the meter's PDU size as general block transfer, one block
753/// per acknowledgement. The last block's answer is the response, left for the caller.
754fn send_as_gbt<T: Transport, P: CryptoProvider, const N: usize>(
755    session: &mut ClientSession<P, N>,
756    transport: &mut T,
757    request: &[u8],
758    server_max: usize,
759    frame: &mut [u8],
760    response: &mut [u8],
761) -> Result<(), ClientError> {
762    let fragment = server_max.saturating_sub(GBT_HEADER_MAX);
763    let mut sender = GbtSender::new(request, fragment, 1, false)?;
764    let mut out = vec![0u8; fragment.saturating_add(GBT_HEADER_MAX)];
765    loop {
766        let Some((tag, rest)) = out.split_first_mut() else {
767            return Err(ClientError::Protocol(Error::new(ErrorKind::BufferTooSmall { needed: 1 }, 0)));
768        };
769        let Some(n) = sender.next_block(rest)? else {
770            return Err(ClientError::Unexpected);
771        };
772        *tag = ApduTag::GeneralBlockTransfer.as_u8();
773        transport.send(out.get(..=n).unwrap_or(&[]))?;
774        if usize::from(sender.block()) == usize::from(sender.blocks()) {
775            return Ok(());
776        }
777        let m = transport.recv(frame)?;
778        match session.handle_response(frame.get(..m).unwrap_or(&[]), response)? {
779            Response::BlocksAcked { acked, window } => sender.acknowledge_with_window(acked, window)?,
780            Response::Exception(e) => return Err(ClientError::Exception(e)),
781            _ => return Err(ClientError::Unexpected),
782        }
783    }
784}
785
786/// Map an ACTION response, following a blocked return value to its end.
787fn action_outcome<P: CryptoProvider, const N: usize>(
788    session: &mut ClientSession<P, N>,
789    response: Response<'_>,
790    request: &mut [u8],
791    blocks: &mut Blocks<Vec<u8>>,
792    plain: &[u8],
793) -> Result<Step<Option<DataBuf>>, ClientError> {
794    match response {
795        Response::Ok => Ok(Step::Done(None)),
796        Response::ActionResult { result: ActionResult::Success, value } if blocks.last == 0 => {
797            if value.is_some() {
798                // Tag, choice, invoke id, action result, presence and data-result choice.
799                blocks.check_size(plain.len().saturating_sub(6), true)?;
800            }
801            Ok(Step::Done(value.map(|v| DataBuf::from_data(&v)).transpose()?))
802        }
803        Response::ActionResult { result, .. } if !result.is_success() => {
804            Err(ClientError::ActionFailed(result))
805        }
806        Response::Block { last, number, data } => {
807            blocks.push(number, last, data)?;
808            if last {
809                Ok(Step::Done(Some(DataBuf::parse(&blocks.bytes)?)))
810            } else {
811                Ok(Step::Send(session.action_next_block_request(number, request)?))
812            }
813        }
814        _ => Err(ClientError::Unexpected),
815    }
816}
817
818/// A value arriving in service-level blocks, insisting they come consecutively from one.
819///
820/// A duplicated or reordered fragment concatenated in the wrong place usually still
821/// decodes — into a value that is wrong and carries no error.
822struct Blocks<W> {
823    bytes: W,
824    last: u32,
825    limit: usize,
826}
827
828impl<W: Writer> Blocks<W> {
829    fn new(bytes: W, limit: usize) -> Self {
830        Self { bytes, last: 0, limit }
831    }
832
833    fn check_size(&self, additional: usize, last: bool) -> Result<(), ClientError> {
834        if additional > self.limit.saturating_sub(self.bytes.written()) {
835            return Err(ClientError::ResponseTooLarge { limit: self.limit, reconnect_required: !last });
836        }
837        Ok(())
838    }
839
840    fn push(&mut self, number: u32, last: bool, data: &[u8]) -> Result<(), ClientError> {
841        if self.last.checked_add(1) != Some(number) || (!last && data.is_empty()) {
842            return Err(ClientError::Protocol(Error::new(
843                ErrorKind::UnexpectedMessage,
844                self.bytes.written(),
845            )));
846        }
847        self.check_size(data.len(), last)?;
848        self.bytes.write_bytes(data)?;
849        self.last = number;
850        Ok(())
851    }
852}
853
854fn encode(value: &Data<'_>) -> Result<Vec<u8>, ClientError> {
855    let mut out = Vec::new();
856    value.encode(&mut out)?;
857    Ok(out)
858}