dlms_cosem_kit/client/session.rs
1//! The client session.
2
3use crate::acse::{
4 Aare, Aarq, ApplicationContext, AssociationResult, AuthMechanism, Diagnostic, Referencing, ReleaseReason,
5 ReleaseResponseReason, Rlrq,
6};
7use crate::axdr::Data;
8use crate::codec::{Decode, Encode, Error, ErrorKind, Reader, Result, SliceWriter, Writer};
9use crate::cosem::InterfaceClass;
10use crate::obis::Obis;
11use crate::security::wrap::{Incoming, Outgoing, protect_apdu, unprotect_apdu, unprotect_apdu_in_place};
12use crate::security::{
13 CryptoProvider, InvocationCounter, Protector, ReplayWindow, SecurityPolicy, SystemTitle,
14};
15use crate::xdlms::{
16 AccessRequestSpecification, ActionRequest, Apdu, ApduTag, AttributeDescriptor,
17 AttributeDescriptorWithSelection, Conformance, DataAccessResult, DataBlockSA, ExceptionResponse,
18 GbtAction, GbtRecvCursor, GeneralBlockTransfer, GetDataResult, GetRequest, GetResponse, InitiateRequest,
19 InitiateResponse, InvokeId, List, LongInvokeId, MethodDescriptor, Protection, SelectiveAccess,
20 SetRequest, SetResponse,
21};
22
23/// The APDUs a client accepts from a server with no protection on them, even in a
24/// ciphered association.
25///
26/// The ACSE ones precede the association and cannot be protected as APDUs — their
27/// user-information is protected instead. `exception-response` is here because it has no
28/// ciphered tag of its own: a server that has not negotiated `general-protection` has no
29/// way to protect one, and refusing it means a ciphered client turns every server
30/// refusal into a decode error and never learns what the meter actually said. It carries
31/// no data and changes no state on this side; it is a diagnostic, and it is treated as
32/// an unauthenticated one.
33const PLAIN_FROM_SERVER: &[ApduTag] = &[ApduTag::Aare, ApduTag::ReleaseResponse, ApduTag::ExceptionResponse];
34
35/// What the AARE's user information may be when the association is not ciphered.
36const PLAIN_INITIATE: &[ApduTag] = &[ApduTag::InitiateResponse, ApduTag::ConfirmedServiceError];
37
38/// What the session is doing.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum SessionState {
41 /// No association.
42 Idle,
43 /// An AARQ has gone out and the AARE has not come back.
44 Associating,
45 /// High level security: the challenges have been exchanged and the client's reply
46 /// to the server's challenge is outstanding.
47 AuthenticatingHls,
48 /// Ready for services.
49 Associated,
50 /// A release request has gone out.
51 Releasing,
52 /// The association is over. It was refused, released, or abandoned locally.
53 Closed,
54}
55
56/// What the client must do next in the association handshake.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum AssociationStep {
59 /// The association is open.
60 Established,
61 /// High level security requires a reply to the server's challenge; call
62 /// [`ClientSession::hls_reply_request`].
63 HlsReplyRequired,
64 /// The server refused, with its reason.
65 Rejected {
66 /// Accepted, permanently rejected or transiently rejected.
67 result: AssociationResult,
68 /// Why.
69 diagnostic: Diagnostic,
70 },
71 /// The server answered the AARQ with an exception rather than an AARE, so the
72 /// association was never attempted.
73 ///
74 /// The case worth acting on is `invocation-counter-error`: it carries the counter
75 /// the server expects next, and a client whose stored value went stale — a restart
76 /// from a backup, most often — can move to it with
77 /// [`ClientSession::set_invocation_counter`] and associate again. The exception is
78 /// unprotected and anyone can forge one, so the value is *reported* rather than
79 /// applied: moving a counter is the caller's decision because moving it backwards
80 /// burns the key.
81 Exception(ExceptionResponse),
82}
83
84/// What a response carried.
85#[derive(Debug, Clone, Copy, PartialEq)]
86pub enum Response<'a> {
87 /// A value.
88 Data(Data<'a>),
89 /// One result per attribute of a [`ClientSession::get_request_with_list`], in the
90 /// order they were asked for. Each is a value or the reason there is none.
91 DataList(List<'a, GetDataResult<'a>>),
92 /// The server refused the request.
93 DataError(DataAccessResult),
94 /// One block of a value; ask for the next with
95 /// [`ClientSession::get_next_block_request`].
96 Block {
97 /// True when no further block follows.
98 last: bool,
99 /// This block's number.
100 number: u32,
101 /// The fragment.
102 data: &'a [u8],
103 },
104 /// One result per attribute of a [`ClientSession::set_request_with_list`], in the
105 /// order they were asked for.
106 ResultList(List<'a, DataAccessResult>),
107 /// One outcome per method of a [`ClientSession::action_request_with_list`], in the
108 /// order they were asked for.
109 ActionResults(List<'a, crate::xdlms::ActionResponseWithOptionalData<'a>>),
110 /// The server took a block of a long SET or ACTION parameter and wants the next;
111 /// send it with [`ClientSession::next_block_request`].
112 BlockAccepted {
113 /// The block the server acknowledged.
114 number: u32,
115 },
116 /// The answers to an [`ClientSession::access_request`], one per item in the order
117 /// they were asked for.
118 Access {
119 /// One value per item — `null-data` where the item produced none.
120 data: List<'a, Data<'a>>,
121 /// One outcome per item.
122 results: List<'a, crate::xdlms::AccessResponseSpecification>,
123 },
124 /// One answer per entry of a [`ClientSession::read_request`], in order.
125 #[cfg(feature = "sn")]
126 ReadResults(List<'a, crate::xdlms::ReadResult<'a>>),
127 /// One outcome per entry of a [`ClientSession::write_request`], in order.
128 #[cfg(feature = "sn")]
129 WriteResults(List<'a, crate::xdlms::WriteResult>),
130 /// A write or an invocation succeeded.
131 Ok,
132 /// A method returned a value.
133 ActionResult {
134 /// Whether the method ran.
135 result: crate::xdlms::ActionResult,
136 /// What it returned, if anything.
137 value: Option<Data<'a>>,
138 },
139 /// The server refused the APDU itself.
140 Exception(ExceptionResponse),
141 /// The server answered the release. Absent or [`ReleaseResponseReason::Normal`]
142 /// means released; anything else is the server refusing. Either way this session is
143 /// closed.
144 Released {
145 /// The server's reason, when given.
146 reason: Option<ReleaseResponseReason>,
147 },
148 /// A block of a response arriving as general block transfer, inside a window the
149 /// server is still streaming. Receive the next APDU; send nothing.
150 Pending,
151 /// A block of a response arriving as general block transfer, which the server wants
152 /// acknowledged. Send these bytes, then receive the next APDU.
153 Acknowledge(GbtAck),
154 /// The server acknowledged blocks of a request this client is sending as general
155 /// block transfer: everything up to `acked`, and it can take `window` more.
156 BlocksAcked {
157 /// The highest block the server received in order.
158 acked: u16,
159 /// How many blocks the server will take before it acknowledges again.
160 window: u8,
161 },
162}
163
164/// A general-block-transfer acknowledgement, ready to send.
165///
166/// Seven bytes held by value, so answering a block needs no buffer of the caller's and
167/// borrows nothing the next call overwrites.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct GbtAck {
170 bytes: [u8; 7],
171}
172
173impl GbtAck {
174 fn new(acked: u16, window: u8) -> Result<Self> {
175 let mut bytes = [0u8; 7];
176 let mut w = SliceWriter::new(&mut bytes);
177 Apdu::GeneralBlockTransfer(GeneralBlockTransfer::ack(acked, window)).encode(&mut w)?;
178 Ok(Self { bytes })
179 }
180
181 /// The APDU to send.
182 #[must_use]
183 pub const fn as_bytes(&self) -> &[u8] {
184 &self.bytes
185 }
186}
187
188/// How the client identifies itself and what it demands.
189#[derive(Debug, Clone)]
190pub struct ClientConfig {
191 /// The client service access point: 0x10 public, 0x20 reader, 0x30 management.
192 pub client_sap: u8,
193 /// The client's system title. Required for GMAC authentication and for any
194 /// ciphered association, because it is half of every nonce the client sends under.
195 pub system_title: Option<SystemTitle>,
196 /// Which authentication mechanism to propose.
197 pub mechanism: AuthMechanism,
198 /// The low-level-security password, or the high-level-security shared secret.
199 pub password: Option<crate::security::Secret>,
200 /// What protection to apply.
201 ///
202 /// Set `dedicated` to propose a dedicated-key association; the key itself comes from
203 /// the provider, and an association is refused rather than opened if the provider
204 /// has none.
205 pub security: SecurityPolicy,
206 /// The largest APDU the client will accept.
207 pub max_pdu_size: u16,
208 /// What the client proposes it can do.
209 pub conformance: Conformance,
210 /// How objects are addressed.
211 pub referencing: Referencing,
212 /// How long a challenge to send. The Blue Book allows eight to sixty-four bytes;
213 /// shorter is weaker and there is no reason to go below sixteen.
214 pub challenge_len: usize,
215 /// The last invocation counter this client used before it started.
216 ///
217 /// Zero is right only for a client that has never sent under these keys. Restarting
218 /// from zero against an unchanged key reuses every nonce it used before, and a
219 /// repeated GCM nonce leaks the authentication subkey. Persist
220 /// [`ClientSession::invocation_counter`] and restore it here.
221 pub invocation_counter: u32,
222 /// How far out of order the server's invocation counters may arrive.
223 ///
224 /// Zero — strictly increasing — is right for HDLC and TCP.
225 pub replay_window: u32,
226 /// How many general-block-transfer blocks this client takes before it acknowledges,
227 /// announced to the server in every acknowledgement. Clamped to `1..=63`.
228 ///
229 /// Larger windows cost fewer round trips on a slow link and need nothing more: the
230 /// blocks land in the caller's buffer whatever the window.
231 pub gbt_window: u8,
232}
233
234impl Default for ClientConfig {
235 fn default() -> Self {
236 Self {
237 client_sap: 0x10,
238 system_title: None,
239 mechanism: AuthMechanism::None,
240 password: None,
241 security: SecurityPolicy::NONE,
242 max_pdu_size: 1024,
243 conformance: Conformance::CLIENT_DEFAULT,
244 referencing: Referencing::LogicalName,
245 challenge_len: 16,
246 invocation_counter: 0,
247 replay_window: 0,
248 gbt_window: 4,
249 }
250 }
251}
252
253/// A client association.
254///
255/// `N` is the scratch buffer the session uses to build an APDU before protecting it.
256/// It must be at least as large as the largest APDU the client sends; 1024 covers
257/// every request that is not a block transfer.
258#[derive(Debug)]
259pub struct ClientSession<P, const N: usize = 1024> {
260 config: ClientConfig,
261 protector: Protector<P>,
262 state: SessionState,
263 invoke_id: u8,
264 /// The invoke id of the request whose response has not arrived yet.
265 ///
266 /// A `get-request-next` continues an outstanding request and must carry *its* invoke
267 /// id: a fresh one names a different invocation, and a server that checks will
268 /// refuse it while a server that does not will answer a block of the wrong thing.
269 outstanding: Option<InvokeId>,
270 invocation_counter: InvocationCounter,
271 /// Which of the server's invocation counters have already been spent.
272 peer_replay: ReplayWindow,
273 negotiated: Option<InitiateResponse>,
274 server_system_title: Option<SystemTitle>,
275 client_challenge: [u8; 64],
276 client_challenge_len: usize,
277 server_challenge: [u8; 64],
278 server_challenge_len: usize,
279 /// A response arriving as general block transfer, gathering in the caller's buffer.
280 gbt_rx: Option<GbtRecvCursor>,
281 scratch: [u8; N],
282}
283
284/// What one general-block-transfer APDU came to.
285enum GbtStep {
286 /// Nothing to decode yet.
287 Answer(Response<'static>),
288 /// The whole response is in the caller's buffer at this range, protection removed.
289 Complete(core::ops::Range<usize>),
290}
291
292impl<P: CryptoProvider, const N: usize> ClientSession<P, N> {
293 /// A session that will use `provider` for cryptography.
294 pub fn new(config: ClientConfig, provider: P) -> Self {
295 // Before the association is open there is no dedicated key at either end, so the
296 // protector starts on the global key set and is switched over in
297 // `handle_associate_response`.
298 let policy = config.security.global();
299 let invocation_counter = InvocationCounter::new(config.invocation_counter);
300 let peer_replay = ReplayWindow::new(config.replay_window);
301 Self {
302 config,
303 protector: Protector::new(provider, policy),
304 state: SessionState::Idle,
305 invoke_id: 0,
306 outstanding: None,
307 invocation_counter,
308 peer_replay,
309 negotiated: None,
310 server_system_title: None,
311 client_challenge: [0; 64],
312 client_challenge_len: 0,
313 server_challenge: [0; 64],
314 server_challenge_len: 0,
315 gbt_rx: None,
316 scratch: [0; N],
317 }
318 }
319
320 /// What the session is doing.
321 #[must_use]
322 pub const fn state(&self) -> SessionState {
323 self.state
324 }
325
326 /// What both sides agreed to, once the association is open.
327 #[must_use]
328 pub const fn negotiated(&self) -> Option<&InitiateResponse> {
329 self.negotiated.as_ref()
330 }
331
332 /// The server's system title, learned from the AARE.
333 #[must_use]
334 pub const fn server_system_title(&self) -> Option<SystemTitle> {
335 self.server_system_title
336 }
337
338 /// The invocation counter the client last sent under.
339 ///
340 /// Persist this. Restoring a lower value after a restart reuses a nonce; see
341 /// [`ClientConfig::invocation_counter`].
342 #[must_use]
343 pub const fn invocation_counter(&self) -> u32 {
344 self.invocation_counter.get()
345 }
346
347 /// Start the invocation counter from a known value, after reading the meter's
348 /// record of it or restoring one from storage.
349 ///
350 /// Only ever move it *forward*. There is no check here, because a client that has
351 /// just read a higher value out of the meter's own counter object is doing the
352 /// right thing and a client that sets it backwards is burning the key either way.
353 pub const fn set_invocation_counter(&mut self, value: u32) {
354 self.invocation_counter = InvocationCounter::new(value);
355 }
356
357 /// The highest invocation counter accepted from the server, if any.
358 #[must_use]
359 pub const fn peer_invocation_counter(&self) -> Option<u32> {
360 self.peer_replay.highest()
361 }
362
363 /// The largest payload a block of a long SET or ACTION parameter may carry.
364 ///
365 /// Deliberately conservative: every header field is counted at its longest, and
366 /// protection at its worst case. A few wasted bytes per block cost one extra block
367 /// on a very long transfer; a block one byte too large is a request the server drops.
368 fn max_fragment(&self) -> Result<core::num::NonZeroUsize> {
369 self.max_fragment_less(0)
370 }
371
372 /// The same, with `extra` bytes of header this transfer carries beyond the fixed
373 /// part — the encoded selective-access descriptor of a blocked SET, which rides in
374 /// the first block and is as long as the selector makes it.
375 ///
376 /// Every block is sized as though it carried the descriptor, not just the first.
377 /// That wastes a few bytes per block on a long transfer; sizing only the first block
378 /// down would make the later ones a different size for no gain, and getting *that*
379 /// arithmetic wrong produces a request the server drops with nothing to point at.
380 fn max_fragment_less(&self, extra: usize) -> Result<core::num::NonZeroUsize> {
381 // The block header at its longest: APDU tag, request choice, invoke id, the
382 // attribute or method descriptor, the selective-access usage flag, the last-block
383 // flag, the four-byte block number, and a length prefix in its longest form.
384 const HEADER_MAX: usize = 1 + 1 + 1 + 9 + 1 + 1 + 4 + 5;
385 // The `glo-` tag, the ciphered service's length prefix at its longest, the
386 // security control byte, the invocation counter and the GCM tag.
387 const PROTECTION_MAX: usize = 1 + 5 + 1 + 4 + 12;
388 let overhead = if self.config.security.is_none() { 0 } else { PROTECTION_MAX };
389 let ceiling =
390 self.negotiated.as_ref().map_or(self.config.max_pdu_size, |n| n.server_max_receive_pdu_size);
391 let fragment = usize::from(ceiling)
392 .saturating_sub(HEADER_MAX)
393 .saturating_sub(overhead)
394 .saturating_sub(extra)
395 .min(N);
396 // A negotiated PDU size that leaves no room for a payload cannot carry a blocked
397 // transfer at all, and a transfer of zero-length blocks would never finish.
398 core::num::NonZeroUsize::new(fragment).ok_or(Error::new(ErrorKind::InvalidLength, 0))
399 }
400
401 fn next_long_invoke_id(&mut self) -> LongInvokeId {
402 self.invoke_id = self.invoke_id.wrapping_add(1) & 0x0F;
403 self.gbt_rx = None;
404 // ACSE's short invoke id is not in play for an ACCESS exchange, so nothing is
405 // outstanding under one: leaving a stale id here would have a later block
406 // request continue an invocation that is over.
407 self.outstanding = None;
408 LongInvokeId::new(u32::from(self.invoke_id)).confirmed()
409 }
410
411 fn next_invoke_id(&mut self) -> InvokeId {
412 self.invoke_id = self.invoke_id.wrapping_add(1) & 0x0F;
413 // A new request abandons a response still arriving in blocks: its remaining
414 // blocks answer a question nobody is asking any more.
415 self.gbt_rx = None;
416 let id = InvokeId::confirmed(self.invoke_id);
417 self.outstanding = Some(id);
418 id
419 }
420
421 fn application_context(&self) -> ApplicationContext {
422 ApplicationContext::for_referencing(self.config.referencing, !self.config.security.is_none())
423 }
424
425 /// Build the AARQ that opens the association.
426 ///
427 /// # Errors
428 /// When the buffer is too small, when high level security is configured without a
429 /// system title, or when a challenge is needed and the provider has no entropy.
430 pub fn associate_request(&mut self, out: &mut [u8]) -> Result<usize> {
431 // Proposing short-name referencing from a build that left the `sn` feature out
432 // would open an association with no services in it. Refusing here says so before
433 // a byte goes out, rather than after a handshake that appeared to work.
434 #[cfg(not(feature = "sn"))]
435 if self.config.referencing == Referencing::ShortName {
436 return Err(Error::new(ErrorKind::Unsupported, 0));
437 }
438 let ciphered = !self.config.security.is_none();
439 if (ciphered || self.config.mechanism == AuthMechanism::HighGmac)
440 && self.config.system_title.is_none()
441 {
442 // Without a system title the client cannot form a nonce, so every frame it
443 // sent would share one — which is worse than not connecting.
444 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
445 }
446
447 let mut initiate = InitiateRequest {
448 proposed_dlms_version: crate::xdlms::DLMS_VERSION,
449 proposed_conformance: self.config.conformance,
450 client_max_receive_pdu_size: self.config.max_pdu_size,
451 ..Default::default()
452 };
453 // The dedicated key travels inside the ciphered InitiateRequest, so it is only
454 // ever offered in a ciphered context — sending one in the clear would publish it.
455 if ciphered && self.config.security.dedicated() {
456 initiate.dedicated_key =
457 Some(self.protector.provider().dedicated_key().ok_or(Error::new(ErrorKind::Unsupported, 0))?);
458 }
459
460 // The InitiateRequest is protected on its own, inside the user information.
461 let mut plain = [0u8; 64];
462 let mut pw = SliceWriter::new(&mut plain);
463 pw.write_u8(ApduTag::InitiateRequest.as_u8())?;
464 initiate.encode(&mut pw)?;
465 let plain_len = pw.written();
466
467 let mut user_info = [0u8; 160];
468 let user_info = if ciphered {
469 let ic = self.next_counter()?;
470 let title = self.config.system_title.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
471 let mut body = [0u8; 128];
472 // Always the *global* key set, whatever the association will use afterwards:
473 // the dedicated key is delivered inside this very message, so the peer
474 // cannot yet hold it. Protecting the InitiateRequest with it produces a
475 // frame nobody can open.
476 let payload = self.protector.protect_as(
477 self.config.security.global(),
478 &title,
479 ic,
480 self.auth_key()?,
481 &plain[..plain_len],
482 &mut body,
483 )?;
484 let mut w = SliceWriter::new(&mut user_info);
485 let tag = ApduTag::InitiateRequest
486 .protected_as(Protection::Global)
487 .ok_or(Error::new(ErrorKind::Unsupported, 0))?;
488 w.write_u8(tag.as_u8())?;
489 crate::xdlms::CipheredService {
490 security_control: self.config.security.control(),
491 invocation_counter: ic,
492 payload,
493 }
494 .encode(&mut w)?;
495 let n = w.written();
496 &user_info[..n]
497 } else {
498 &plain[..plain_len]
499 };
500
501 let challenge = if self.config.mechanism.is_high_level() {
502 let len = self.config.challenge_len.clamp(8, 64);
503 self.protector.provider().random(&mut self.client_challenge[..len])?;
504 self.client_challenge_len = len;
505 Some(&self.client_challenge[..len])
506 } else {
507 self.config.password.as_ref().map(crate::security::Secret::expose)
508 };
509
510 let aarq = Aarq {
511 application_context: Some(self.application_context()),
512 called_ap_title: None,
513 calling_ap_title: self.config.system_title.as_ref().map(|t| &t.0[..]),
514 calling_ae_qualifier: None,
515 sender_acse_requirements: self.config.mechanism != AuthMechanism::None,
516 mechanism_name: (self.config.mechanism != AuthMechanism::None).then_some(self.config.mechanism),
517 calling_authentication_value: challenge,
518 user_information: Some(user_info),
519 };
520 let mut w = SliceWriter::new(out);
521 aarq.encode(&mut w)?;
522 self.state = SessionState::Associating;
523 Ok(w.written())
524 }
525
526 /// Consume the AARE and say what happens next.
527 ///
528 /// # Errors
529 /// When the APDU is not an AARE, when the negotiated version is not one this crate
530 /// speaks, or when the server's InitiateResponse cannot be unprotected.
531 pub fn handle_associate_response(&mut self, apdu: &[u8]) -> Result<AssociationStep> {
532 // A server that cannot even get as far as an AARE answers with an exception.
533 // Decoding it as a malformed AARE would turn the one message that says how to
534 // recover into `invalid tag 0xd8`.
535 if apdu.first().copied() == Some(ApduTag::ExceptionResponse.as_u8()) {
536 self.state = SessionState::Closed;
537 return Ok(AssociationStep::Exception(ExceptionResponse::from_bytes(
538 apdu.get(1..).unwrap_or(&[]),
539 )?));
540 }
541 let aare = Aare::from_bytes(apdu)?;
542 if let Some(title) = aare.responding_ap_title {
543 self.server_system_title = Some(SystemTitle::from_slice(title)?);
544 }
545 if !aare.is_accepted() {
546 self.state = SessionState::Closed;
547 return Ok(AssociationStep::Rejected { result: aare.result, diagnostic: aare.diagnostic });
548 }
549
550 // An accepted association must be the one that was asked for. The context says
551 // whether the association is ciphered and how objects are named, and the
552 // mechanism says how the client proves who it is; a server that answers "yes"
553 // to a *different* pair has not agreed to anything the client proposed. The
554 // ACSE fields are not protected, so this is not by itself an authentication —
555 // it is the check that stops the handshake continuing under the wrong
556 // assumptions, which is where a downgrade would otherwise be laundered into a
557 // session that never notices.
558 let proposed = self.application_context();
559 if aare.application_context.is_some_and(|got| got != proposed) {
560 self.state = SessionState::Closed;
561 return Ok(AssociationStep::Rejected {
562 result: AssociationResult::RejectedPermanent,
563 diagnostic: Diagnostic::User(crate::acse::UserDiagnostic::ApplicationContextNameNotSupported),
564 });
565 }
566 if aare.mechanism_name.is_some_and(|got| got != self.config.mechanism) {
567 self.state = SessionState::Closed;
568 return Ok(AssociationStep::Rejected {
569 result: AssociationResult::RejectedPermanent,
570 diagnostic: Diagnostic::User(
571 crate::acse::UserDiagnostic::AuthenticationMechanismNameNotRecognised,
572 ),
573 });
574 }
575 // A server that names no mechanism has not accepted the one that was proposed.
576 if self.config.mechanism != AuthMechanism::None && aare.mechanism_name.is_none() {
577 self.state = SessionState::Closed;
578 return Ok(AssociationStep::Rejected {
579 result: AssociationResult::RejectedPermanent,
580 diagnostic: Diagnostic::User(crate::acse::UserDiagnostic::AuthenticationRequired),
581 });
582 }
583
584 if let Some(user_info) = aare.user_information {
585 let mut buf = [0u8; 256];
586 // The InitiateResponse is protected globally for the same reason the request
587 // is, so it is unprotected under the global policy rather than the
588 // association's.
589 let plain = self.unprotect_initiate(user_info, &mut buf)?;
590 let mut r = Reader::new(plain);
591 let tag = r.u8()?;
592 match ApduTag::from_u8(tag) {
593 Some(ApduTag::InitiateResponse) => {
594 let resp = InitiateResponse::decode(&mut r)?;
595 resp.check_version()?;
596 self.negotiated = Some(resp);
597 }
598 Some(ApduTag::ConfirmedServiceError) => {
599 self.state = SessionState::Closed;
600 return Ok(AssociationStep::Rejected {
601 result: AssociationResult::RejectedPermanent,
602 diagnostic: aare.diagnostic,
603 });
604 }
605 _ => return Err(Error::new(ErrorKind::UnexpectedMessage, 0)),
606 }
607 }
608
609 // From here on the association's own protection applies, which is the dedicated
610 // key set when one was delivered in the InitiateRequest.
611 if self.config.security.dedicated() {
612 self.protector.set_dedicated(true);
613 }
614
615 if self.config.mechanism.is_high_level() {
616 let challenge =
617 aare.responding_authentication_value.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
618 if challenge.len() > 64 {
619 return Err(Error::new(ErrorKind::InvalidLength, 0));
620 }
621 self.server_challenge[..challenge.len()].copy_from_slice(challenge);
622 self.server_challenge_len = challenge.len();
623 self.state = SessionState::AuthenticatingHls;
624 return Ok(AssociationStep::HlsReplyRequired);
625 }
626
627 self.state = SessionState::Associated;
628 Ok(AssociationStep::Established)
629 }
630
631 /// Build the `reply_to_HLS_authentication` request that answers the server's
632 /// challenge.
633 ///
634 /// # Errors
635 /// When the mechanism is not one this crate implements, or the session is not at
636 /// this step.
637 pub fn hls_reply_request(&mut self, out: &mut [u8]) -> Result<usize> {
638 if self.state != SessionState::AuthenticatingHls {
639 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
640 }
641 if self.config.mechanism != AuthMechanism::HighGmac {
642 // Mechanisms 3, 4, 6 and 7 are named by the standard but their exact
643 // constructions are not in the material this crate was built from, and a
644 // guessed construction authenticates nothing.
645 return Err(Error::new(ErrorKind::Unsupported, 0));
646 }
647 let title = self.config.system_title.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
648 let ic = self.next_counter()?;
649 let mut reply = [0u8; 17];
650 self.protector.hls_gmac_response(
651 &title,
652 ic,
653 self.auth_key()?,
654 &self.server_challenge[..self.server_challenge_len],
655 &mut reply,
656 )?;
657
658 let descriptor = MethodDescriptor::new(15, Obis::new(0, 0, 40, 0, 0, 255), 1);
659 let request = ActionRequest::Normal {
660 invoke_id: self.next_invoke_id(),
661 descriptor,
662 parameters: Some(Data::OctetString(&reply)),
663 };
664 self.send(&Apdu::ActionRequest(request), out)
665 }
666
667 /// Consume the server's answer to the HLS reply.
668 ///
669 /// # Errors
670 /// [`ErrorKind::BadTag`] when the server's proof does not match the challenge the
671 /// client sent — which means the server does not hold the key, and the association
672 /// must not be used.
673 pub fn handle_hls_reply_response(&mut self, apdu: &[u8]) -> Result<AssociationStep> {
674 let mut buf = [0u8; 512];
675 let plain = self.unprotect_into(apdu, &mut buf)?;
676 let apdu = Apdu::from_bytes(plain)?;
677 let Apdu::ActionResponse(crate::xdlms::ActionResponse::Normal { response, .. }) = apdu else {
678 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
679 };
680 if !response.result.is_success() {
681 self.state = SessionState::Closed;
682 return Ok(AssociationStep::Rejected {
683 result: AssociationResult::RejectedPermanent,
684 diagnostic: Diagnostic::User(crate::acse::UserDiagnostic::AuthenticationFailure),
685 });
686 }
687 let proof = response
688 .return_parameters
689 .and_then(|p| p.value().ok())
690 .and_then(|d| d.as_bytes())
691 .ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
692 let peer = self.server_system_title.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
693 self.protector.verify_hls_gmac(
694 &peer,
695 self.auth_key()?,
696 &self.client_challenge[..self.client_challenge_len],
697 proof,
698 )?;
699 self.state = SessionState::Associated;
700 Ok(AssociationStep::Established)
701 }
702
703 /// Build a GET request for one attribute.
704 ///
705 /// # Errors
706 /// When the association is not open, when the server did not agree to GET, or when
707 /// the buffer is too small.
708 pub fn get_request(
709 &mut self,
710 descriptor: AttributeDescriptor,
711 access: Option<SelectiveAccess<'_>>,
712 out: &mut [u8],
713 ) -> Result<usize> {
714 self.require_associated()?;
715 self.require_conformance(Conformance::GET)?;
716 if access.is_some() {
717 self.require_conformance(Conformance::SELECTIVE_ACCESS)?;
718 }
719 let request = GetRequest::Normal { invoke_id: self.next_invoke_id(), descriptor, access };
720 self.send(&Apdu::GetRequest(request), out)
721 }
722
723 /// Build a GET request for an attribute of a typed class.
724 ///
725 /// # Errors
726 /// As [`ClientSession::get_request`].
727 pub fn get<C: InterfaceClass>(
728 &mut self,
729 logical_name: Obis,
730 attribute: i8,
731 out: &mut [u8],
732 ) -> Result<usize> {
733 self.get_request(AttributeDescriptor::new(C::CLASS_ID, logical_name, attribute), None, out)
734 }
735
736 /// Build a GET request for several attributes at once.
737 ///
738 /// One round trip instead of one per attribute. On a GPRS or LPWAN link the round
739 /// trip dominates everything else, so reading thirty registers one at a time is not
740 /// thirty times the bytes — it is thirty times the latency, which is the difference
741 /// between a meter read taking a second and taking a minute.
742 ///
743 /// Each item gets its own result: a list where one attribute is unreadable comes
744 /// back with a value for the others and a [`DataAccessResult`] in that one's place,
745 /// so a single denied object does not lose the whole read.
746 ///
747 /// # Errors
748 /// When the association is not open, when the server did not agree to
749 /// [`Conformance::GET`] or [`Conformance::MULTIPLE_REFERENCES`], when the list is
750 /// empty, or when a buffer is too small.
751 pub fn get_request_with_list(
752 &mut self,
753 items: &[AttributeDescriptorWithSelection<'_>],
754 out: &mut [u8],
755 ) -> Result<usize> {
756 self.require_associated()?;
757 self.require_conformance(Conformance::GET)?;
758 self.require_conformance(Conformance::MULTIPLE_REFERENCES)?;
759 if items.is_empty() {
760 // An empty list is a request for nothing that still costs a round trip.
761 return Err(Error::new(ErrorKind::InvalidValue, 0));
762 }
763 if items.iter().any(|i| i.access.is_some()) {
764 self.require_conformance(Conformance::SELECTIVE_ACCESS)?;
765 }
766
767 // The elements are encoded into a local buffer and handed over as raw bytes,
768 // because `List` is a borrowed view: it never owns what it describes.
769 let mut encoded = [0u8; N];
770 let mut lw = SliceWriter::new(&mut encoded);
771 for item in items {
772 item.encode(&mut lw)?;
773 }
774 let n = lw.written();
775 let request = GetRequest::WithList {
776 invoke_id: self.next_invoke_id(),
777 list: List::from_raw(items.len(), &encoded[..n]),
778 };
779 self.send(&Apdu::GetRequest(request), out)
780 }
781
782 /// Build the request for the next block of a long response.
783 ///
784 /// `block_number` acknowledges the block just received; the server answers with the
785 /// one after it. The request carries the invoke id of the read it is continuing, not
786 /// a fresh one — a `get-request-next` is part of an invocation already in flight,
787 /// and giving it a new id asks the server about something it has never been asked.
788 ///
789 /// # Errors
790 /// When the association is not open, when no request is outstanding to continue, or
791 /// when the buffer is too small.
792 pub fn get_next_block_request(&mut self, block_number: u32, out: &mut [u8]) -> Result<usize> {
793 self.require_associated()?;
794 let invoke_id = self.outstanding.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
795 let request = GetRequest::Next { invoke_id, block_number };
796 self.send(&Apdu::GetRequest(request), out)
797 }
798
799 /// Build a SET request.
800 ///
801 /// # Errors
802 /// When the association is not open, when the server did not agree to SET, or when
803 /// the buffer is too small.
804 pub fn set_request(
805 &mut self,
806 descriptor: AttributeDescriptor,
807 access: Option<SelectiveAccess<'_>>,
808 value: Data<'_>,
809 out: &mut [u8],
810 ) -> Result<usize> {
811 self.require_associated()?;
812 self.require_conformance(Conformance::SET)?;
813 if access.is_some() {
814 self.require_conformance(Conformance::SELECTIVE_ACCESS)?;
815 }
816 let request = SetRequest::Normal { invoke_id: self.next_invoke_id(), descriptor, access, value };
817 self.send(&Apdu::SetRequest(request), out)
818 }
819
820 /// Write several attributes in one exchange, one result each.
821 ///
822 /// The values are positional: value *i* is written to attribute *i*. A server
823 /// answers with one [`DataAccessResult`] per item, so a single refused write does
824 /// not lose the batch.
825 ///
826 /// # Errors
827 /// When the association is not open, when the server did not agree to
828 /// [`Conformance::SET`] or [`Conformance::MULTIPLE_REFERENCES`], when the two lists
829 /// are different lengths, or when a buffer is too small.
830 pub fn set_request_with_list(
831 &mut self,
832 items: &[AttributeDescriptorWithSelection<'_>],
833 values: &[Data<'_>],
834 out: &mut [u8],
835 ) -> Result<usize> {
836 self.require_associated()?;
837 self.require_conformance(Conformance::SET)?;
838 self.require_conformance(Conformance::MULTIPLE_REFERENCES)?;
839 if items.is_empty() || items.len() != values.len() {
840 return Err(Error::new(ErrorKind::InvalidValue, 0));
841 }
842 if items.iter().any(|i| i.access.is_some()) {
843 self.require_conformance(Conformance::SELECTIVE_ACCESS)?;
844 }
845
846 // Both lists are encoded into one buffer, back to back, because `List` is a
847 // borrowed view that never owns what it describes.
848 let mut encoded = [0u8; N];
849 let mut lw = SliceWriter::new(&mut encoded);
850 for item in items {
851 item.encode(&mut lw)?;
852 }
853 let descriptors_end = lw.written();
854 for value in values {
855 value.encode(&mut lw)?;
856 }
857 let end = lw.written();
858 let request = SetRequest::WithList {
859 invoke_id: self.next_invoke_id(),
860 descriptors: List::from_raw(items.len(), encoded.get(..descriptors_end).unwrap_or(&[])),
861 values: List::from_raw(values.len(), encoded.get(descriptors_end..end).unwrap_or(&[])),
862 };
863 self.send(&Apdu::SetRequest(request), out)
864 }
865
866 /// Invoke several methods in one exchange, one result each.
867 ///
868 /// The parameters are positional: parameter *i* goes to method *i*, and a method that
869 /// takes none gets `null-data` in its slot. The answer is a
870 /// [`Response::ActionResults`] with one outcome per method, so a method that refuses
871 /// does not lose the batch — which matters more here than for a read, because a batch
872 /// that opened a breaker and then failed would otherwise report only the failure.
873 ///
874 /// # Errors
875 /// When the association is not open, when the server did not agree to
876 /// [`Conformance::ACTION`] or [`Conformance::MULTIPLE_REFERENCES`], when the two
877 /// lists are different lengths, or when a buffer is too small.
878 pub fn action_request_with_list(
879 &mut self,
880 descriptors: &[MethodDescriptor],
881 parameters: &[Option<Data<'_>>],
882 out: &mut [u8],
883 ) -> Result<usize> {
884 self.require_associated()?;
885 self.require_conformance(Conformance::ACTION)?;
886 self.require_conformance(Conformance::MULTIPLE_REFERENCES)?;
887 if descriptors.is_empty()
888 || descriptors.len() != parameters.len()
889 || descriptors.len() > crate::xdlms::MAX_ACCESS_ITEMS
890 {
891 return Err(Error::new(ErrorKind::InvalidValue, 0));
892 }
893
894 let mut encoded = [0u8; N];
895 let mut lw = SliceWriter::new(&mut encoded);
896 for d in descriptors {
897 d.encode(&mut lw)?;
898 }
899 let descriptors_end = lw.written();
900 for p in parameters {
901 p.unwrap_or(Data::Null).encode(&mut lw)?;
902 }
903 let end = lw.written();
904 let request = ActionRequest::WithList {
905 invoke_id: self.next_invoke_id(),
906 descriptors: List::from_raw(descriptors.len(), encoded.get(..descriptors_end).unwrap_or(&[])),
907 parameters: List::from_raw(parameters.len(), encoded.get(descriptors_end..end).unwrap_or(&[])),
908 };
909 self.send(&Apdu::ActionRequest(request), out)
910 }
911
912 /// Begin writing several attributes whose values together exceed the PDU size.
913 ///
914 /// `values` is the **encoded** `value-list` — a count prefix and one `Data` per
915 /// attribute, which is exactly what [`ClientSession::encode_value_list`] produces —
916 /// and it stays the caller's, as every other long value does.
917 ///
918 /// # Errors
919 /// When the association is not open, or the server did not agree to
920 /// [`Conformance::MULTIPLE_REFERENCES`] and
921 /// [`Conformance::BLOCK_TRANSFER_WITH_SET_OR_WRITE`].
922 pub fn set_transfer_with_list<'v>(
923 &mut self,
924 items: &'v [AttributeDescriptorWithSelection<'v>],
925 values: &'v [u8],
926 scratch: &'v mut [u8],
927 ) -> Result<BlockSender<'v>> {
928 self.require_associated()?;
929 self.require_conformance(Conformance::SET)?;
930 self.require_conformance(Conformance::MULTIPLE_REFERENCES)?;
931 self.require_conformance(Conformance::BLOCK_TRANSFER_WITH_SET_OR_WRITE)?;
932 if items.is_empty() || items.len() > crate::xdlms::MAX_ACCESS_ITEMS {
933 return Err(Error::new(ErrorKind::InvalidValue, 0));
934 }
935 // The descriptor list rides in the first block, so it counts against the
936 // fragment size the same way a single write's selector does.
937 let mut lw = SliceWriter::new(scratch);
938 for item in items {
939 item.encode(&mut lw)?;
940 }
941 let n = lw.written();
942 let list = List::from_raw(items.len(), lw.finish().get(..n).unwrap_or(&[]));
943 let extra = list.encoded_len();
944 Ok(BlockSender {
945 target: BlockTarget::AttributeList(list),
946 bytes: values,
947 sent: 0,
948 block: 0,
949 fragment: self.max_fragment_less(extra)?,
950 })
951 }
952
953 /// Encode a `value-list` for [`ClientSession::set_transfer_with_list`].
954 ///
955 /// A free function on the session rather than a method on a list type, because what
956 /// it produces is the *field* — count prefix included — and that is the thing the
957 /// blocks carry.
958 ///
959 /// # Errors
960 /// When `out` is too small.
961 pub fn encode_value_list(values: &[Data<'_>], out: &mut [u8]) -> Result<usize> {
962 let mut w = SliceWriter::new(out);
963 w.write_length(values.len())?;
964 for v in values {
965 v.encode(&mut w)?;
966 }
967 Ok(w.written())
968 }
969
970 /// Begin writing a value larger than the negotiated PDU size.
971 ///
972 /// `value` is the **encoded** attribute value, and it stays the caller's: how large
973 /// a value a deployment writes is not a decision for this crate, and a session that
974 /// buffered it would put a ceiling on it that nothing in the standard has. Drive the
975 /// transfer with [`ClientSession::next_block_request`] until it reports done.
976 ///
977 /// # Errors
978 /// When the association is not open, or the server did not agree to
979 /// [`Conformance::BLOCK_TRANSFER_WITH_SET_OR_WRITE`].
980 pub fn set_transfer<'v>(
981 &mut self,
982 descriptor: AttributeDescriptor,
983 access: Option<SelectiveAccess<'v>>,
984 value: &'v [u8],
985 ) -> Result<BlockSender<'v>> {
986 self.require_associated()?;
987 self.require_conformance(Conformance::SET)?;
988 self.require_conformance(Conformance::BLOCK_TRANSFER_WITH_SET_OR_WRITE)?;
989 let extra = access.map_or(0, |a| a.encoded_len());
990 Ok(BlockSender {
991 target: BlockTarget::Attribute { descriptor, access },
992 bytes: value,
993 sent: 0,
994 block: 0,
995 fragment: self.max_fragment_less(extra)?,
996 })
997 }
998
999 /// Begin invoking a method whose parameter is larger than the negotiated PDU size.
1000 ///
1001 /// # Errors
1002 /// When the association is not open, or the server did not agree to
1003 /// [`Conformance::BLOCK_TRANSFER_WITH_ACTION`].
1004 pub fn action_transfer<'v>(
1005 &mut self,
1006 descriptor: MethodDescriptor,
1007 parameters: &'v [u8],
1008 ) -> Result<BlockSender<'v>> {
1009 self.require_associated()?;
1010 self.require_conformance(Conformance::ACTION)?;
1011 self.require_conformance(Conformance::BLOCK_TRANSFER_WITH_ACTION)?;
1012 Ok(BlockSender {
1013 target: BlockTarget::Method(descriptor),
1014 bytes: parameters,
1015 sent: 0,
1016 block: 0,
1017 fragment: self.max_fragment()?,
1018 })
1019 }
1020
1021 /// Emit the next block of a transfer started with [`ClientSession::set_transfer`] or
1022 /// [`ClientSession::action_transfer`].
1023 ///
1024 /// Every block of one transfer carries the same invoke id: a fresh one names a
1025 /// different invocation, and a server that checks refuses it while one that does not
1026 /// writes the fragment into something else.
1027 ///
1028 /// # Errors
1029 /// When the transfer is already finished, or the buffer is too small.
1030 pub fn next_block_request(&mut self, sender: &mut BlockSender<'_>, out: &mut [u8]) -> Result<usize> {
1031 self.require_associated()?;
1032 if sender.is_done() {
1033 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
1034 }
1035 let first = sender.block == 0;
1036 let invoke_id = if first {
1037 self.next_invoke_id()
1038 } else {
1039 self.outstanding.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?
1040 };
1041 let end = sender.sent.saturating_add(sender.fragment.get()).min(sender.bytes.len());
1042 let raw_data = sender.bytes.get(sender.sent..end).unwrap_or(&[]);
1043 let last_block = end == sender.bytes.len();
1044 let block_number = sender.block.saturating_add(1);
1045 let block = DataBlockSA { last_block, block_number, raw_data };
1046
1047 let apdu = match (first, sender.target) {
1048 (true, BlockTarget::Attribute { descriptor, access }) => {
1049 Apdu::SetRequest(SetRequest::WithFirstDataBlock { invoke_id, descriptor, access, block })
1050 }
1051 (false, BlockTarget::Attribute { .. }) => {
1052 Apdu::SetRequest(SetRequest::WithDataBlock { invoke_id, block })
1053 }
1054 (true, BlockTarget::Method(descriptor)) => {
1055 Apdu::ActionRequest(ActionRequest::WithFirstPblock { invoke_id, descriptor, block })
1056 }
1057 (false, BlockTarget::Method(_)) => {
1058 Apdu::ActionRequest(ActionRequest::WithPblock { invoke_id, block })
1059 }
1060 (true, BlockTarget::AttributeList(descriptors)) => {
1061 Apdu::SetRequest(SetRequest::WithListAndFirstDataBlock { invoke_id, descriptors, block })
1062 }
1063 (false, BlockTarget::AttributeList(_)) => {
1064 Apdu::SetRequest(SetRequest::WithDataBlock { invoke_id, block })
1065 }
1066 };
1067 let n = self.send(&apdu, out)?;
1068 sender.sent = end;
1069 sender.block = block_number;
1070 Ok(n)
1071 }
1072
1073 /// Ask for the next block of a long ACTION *result*.
1074 ///
1075 /// The counterpart of [`ClientSession::get_next_block_request`] for a method that
1076 /// returns more than one APDU can carry.
1077 ///
1078 /// # Errors
1079 /// When the association is not open, or no invocation is outstanding.
1080 pub fn action_next_block_request(&mut self, block_number: u32, out: &mut [u8]) -> Result<usize> {
1081 self.require_associated()?;
1082 let invoke_id = self.outstanding.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
1083 let request = ActionRequest::NextPblock { invoke_id, block_number };
1084 self.send(&Apdu::ActionRequest(request), out)
1085 }
1086
1087 /// Read, write and invoke in one exchange — the ACCESS service.
1088 ///
1089 /// This is what a battery-powered device on a low-power network uses: the cost there
1090 /// is round trips, not bytes, and ACCESS is the only service that mixes the three
1091 /// operations into one. It has no ciphered tag of its own, so in a protected
1092 /// association it travels inside `general-glo-ciphering` and needs
1093 /// [`Conformance::GENERAL_PROTECTION`] as well as [`Conformance::ACCESS`].
1094 ///
1095 /// The answer comes back as [`Response::Access`], positionally: entry *i* of the
1096 /// result list is the outcome of item *i*, and entry *i* of the data list is what it
1097 /// produced — `null-data` for a write, and for a read that failed.
1098 ///
1099 /// # Errors
1100 /// When the association is not open, when the server did not agree to
1101 /// [`Conformance::ACCESS`], when `items` is empty, or when a buffer is too small.
1102 pub fn access_request(&mut self, items: &[AccessItem<'_>], out: &mut [u8]) -> Result<usize> {
1103 self.require_associated()?;
1104 self.require_conformance(Conformance::ACCESS)?;
1105 if items.is_empty() || items.len() > crate::xdlms::MAX_ACCESS_ITEMS {
1106 return Err(Error::new(ErrorKind::InvalidValue, 0));
1107 }
1108
1109 let mut encoded = [0u8; N];
1110 let mut lw = SliceWriter::new(&mut encoded);
1111 for item in items {
1112 item.specification().encode(&mut lw)?;
1113 }
1114 let spec_end = lw.written();
1115 // One data entry per specification entry, in order. A GET contributes
1116 // `null-data`, which is what keeps the three lists aligned by position.
1117 for item in items {
1118 match item {
1119 AccessItem::Get { .. } => Data::Null.encode(&mut lw)?,
1120 AccessItem::Set { value, .. } => value.encode(&mut lw)?,
1121 AccessItem::Action { parameters, .. } => {
1122 parameters.unwrap_or(Data::Null).encode(&mut lw)?;
1123 }
1124 }
1125 }
1126 let end = lw.written();
1127
1128 let request = crate::xdlms::AccessRequest {
1129 long_invoke_id: self.next_long_invoke_id(),
1130 date_time: crate::xdlms::OptionalDateTime(None),
1131 specification: List::from_raw(items.len(), encoded.get(..spec_end).unwrap_or(&[])),
1132 data: List::from_raw(items.len(), encoded.get(spec_end..end).unwrap_or(&[])),
1133 };
1134 self.send(&Apdu::AccessRequest(request), out)
1135 }
1136
1137 /// Read attributes by **short name** — the legacy addressing mode.
1138 ///
1139 /// One entry per thing to read, answered by a [`Response::ReadResults`] with one
1140 /// result in the same position. A short name is an object's base name plus an
1141 /// offset; [`crate::cosem::ShortName`] computes one, and the base names come from
1142 /// the meter's own `Association SN` object list.
1143 ///
1144 /// Short-name referencing is a property of the *association*, not of a request:
1145 /// set [`ClientConfig::referencing`] to [`Referencing::ShortName`] so the AARQ
1146 /// proposes the short-name application context. A meter that answered a
1147 /// logical-name association with short names would be answering a different
1148 /// question, so this refuses to send one into the wrong context.
1149 ///
1150 /// # Errors
1151 /// When the association is not open or is not a short-name one, when the server did
1152 /// not agree to [`Conformance::READ`], when the list is empty, or when a buffer is
1153 /// too small.
1154 #[cfg(feature = "sn")]
1155 pub fn read_request(
1156 &mut self,
1157 items: &[crate::xdlms::VariableAccess<'_>],
1158 out: &mut [u8],
1159 ) -> Result<usize> {
1160 self.require_associated()?;
1161 self.require_short_name()?;
1162 self.require_conformance(Conformance::READ)?;
1163 if items.is_empty() {
1164 return Err(Error::new(ErrorKind::InvalidValue, 0));
1165 }
1166 let mut encoded = [0u8; N];
1167 let mut lw = SliceWriter::new(&mut encoded);
1168 for item in items {
1169 item.encode(&mut lw)?;
1170 }
1171 let n = lw.written();
1172 let request = crate::xdlms::ReadRequest {
1173 specification: List::from_raw(items.len(), encoded.get(..n).unwrap_or(&[])),
1174 };
1175 // The short-name services carry no invoke id at all, so nothing is outstanding
1176 // under one: leaving a stale id here would let a later block request continue an
1177 // invocation that is over.
1178 self.outstanding = None;
1179 self.send(&Apdu::ReadRequest(request), out)
1180 }
1181
1182 /// Ask for the next block of a long short-name read.
1183 ///
1184 /// `block_number` acknowledges the block just received. Unlike the logical-name
1185 /// services this is an ordinary read entry rather than a form of its own, which is
1186 /// why it takes the same path.
1187 ///
1188 /// # Errors
1189 /// As [`ClientSession::read_request`].
1190 #[cfg(feature = "sn")]
1191 pub fn read_next_block_request(&mut self, block_number: u16, out: &mut [u8]) -> Result<usize> {
1192 self.read_request(&[crate::xdlms::VariableAccess::BlockNumber(block_number)], out)
1193 }
1194
1195 /// Write attributes by **short name**.
1196 ///
1197 /// The two lists are positional: value *i* goes to entry *i*. The answer is a
1198 /// [`Response::WriteResults`] with one outcome per entry, so a single refused write
1199 /// does not lose the batch.
1200 ///
1201 /// # Errors
1202 /// When the association is not open or is not a short-name one, when the server did
1203 /// not agree to [`Conformance::WRITE`], when the two lists are different lengths, or
1204 /// when a buffer is too small.
1205 #[cfg(feature = "sn")]
1206 pub fn write_request(
1207 &mut self,
1208 items: &[crate::xdlms::VariableAccess<'_>],
1209 values: &[Data<'_>],
1210 out: &mut [u8],
1211 ) -> Result<usize> {
1212 self.require_short_name_write(items, values)?;
1213 // Both lists go into one local buffer, back to back, because `List` is a
1214 // borrowed view that never owns what it describes — and a local rather than a
1215 // field of the session, so building the APDU afterwards does not conflict with
1216 // it.
1217 let mut encoded = [0u8; N];
1218 let mut lw = SliceWriter::new(&mut encoded);
1219 for item in items {
1220 item.encode(&mut lw)?;
1221 }
1222 let spec_end = lw.written();
1223 for value in values {
1224 value.encode(&mut lw)?;
1225 }
1226 let end = lw.written();
1227 let request = crate::xdlms::WriteRequest {
1228 specification: List::from_raw(items.len(), encoded.get(..spec_end).unwrap_or(&[])),
1229 values: List::from_raw(values.len(), encoded.get(spec_end..end).unwrap_or(&[])),
1230 };
1231 self.outstanding = None;
1232 self.send(&Apdu::WriteRequest(request), out)
1233 }
1234
1235 /// The same write, with no answer expected.
1236 ///
1237 /// `unconfirmed-write` is a distinct service rather than a flag on the confirmed one,
1238 /// and this is a distinct method for the same reason: a caller that sends one must
1239 /// not then wait for a reply. It costs [`Conformance::UNCONFIRMED_WRITE`] rather than
1240 /// [`Conformance::WRITE`].
1241 ///
1242 /// # Errors
1243 /// As [`ClientSession::write_request`].
1244 #[cfg(feature = "sn")]
1245 pub fn unconfirmed_write_request(
1246 &mut self,
1247 items: &[crate::xdlms::VariableAccess<'_>],
1248 values: &[Data<'_>],
1249 out: &mut [u8],
1250 ) -> Result<usize> {
1251 self.require_short_name_write(items, values)?;
1252 self.require_conformance(Conformance::UNCONFIRMED_WRITE)?;
1253 let mut encoded = [0u8; N];
1254 let mut lw = SliceWriter::new(&mut encoded);
1255 for item in items {
1256 item.encode(&mut lw)?;
1257 }
1258 let spec_end = lw.written();
1259 for value in values {
1260 value.encode(&mut lw)?;
1261 }
1262 let end = lw.written();
1263 let request = crate::xdlms::UnconfirmedWriteRequest {
1264 specification: List::from_raw(items.len(), encoded.get(..spec_end).unwrap_or(&[])),
1265 values: List::from_raw(values.len(), encoded.get(spec_end..end).unwrap_or(&[])),
1266 };
1267 self.outstanding = None;
1268 self.send(&Apdu::UnconfirmedWriteRequest(request), out)
1269 }
1270
1271 /// The checks both short-name writes share.
1272 #[cfg(feature = "sn")]
1273 fn require_short_name_write(
1274 &self,
1275 items: &[crate::xdlms::VariableAccess<'_>],
1276 values: &[Data<'_>],
1277 ) -> Result<()> {
1278 self.require_associated()?;
1279 self.require_short_name()?;
1280 self.require_conformance(Conformance::WRITE)?;
1281 if items.is_empty() || items.len() != values.len() {
1282 return Err(Error::new(ErrorKind::InvalidValue, 0));
1283 }
1284 Ok(())
1285 }
1286
1287 /// Build an ACTION request.
1288 ///
1289 /// # Errors
1290 /// When the association is not open, when the server did not agree to ACTION, or
1291 /// when the buffer is too small.
1292 pub fn action_request(
1293 &mut self,
1294 descriptor: MethodDescriptor,
1295 parameters: Option<Data<'_>>,
1296 out: &mut [u8],
1297 ) -> Result<usize> {
1298 self.require_associated()?;
1299 self.require_conformance(Conformance::ACTION)?;
1300 let request = ActionRequest::Normal { invoke_id: self.next_invoke_id(), descriptor, parameters };
1301 self.send(&Apdu::ActionRequest(request), out)
1302 }
1303
1304 /// Build the request that releases the association.
1305 ///
1306 /// # Errors
1307 /// When the buffer is too small.
1308 pub fn release_request(&mut self, out: &mut [u8]) -> Result<usize> {
1309 let rlrq = Rlrq { reason: Some(ReleaseReason::Normal), user_information: None };
1310 let mut w = SliceWriter::new(out);
1311 rlrq.encode(&mut w)?;
1312 self.state = SessionState::Releasing;
1313 Ok(w.written())
1314 }
1315
1316 /// Consume a response APDU.
1317 ///
1318 /// `buf` receives the unprotected APDU, and the returned [`Response`] borrows from
1319 /// it. That is why it is a parameter: the caller decides where a decrypted APDU
1320 /// lives, and it lives no longer than the caller lets it.
1321 ///
1322 /// **General block transfer.** A response the server sends as GBT arrives one block
1323 /// per call. Each block is gathered into `buf`, so pass **the same buffer** for every
1324 /// block of one response, large enough for the whole protected response. Until it is
1325 /// complete the answer is [`Response::Pending`] (receive again) or
1326 /// [`Response::Acknowledge`] (send its bytes, then receive again); then it is the
1327 /// response itself. The [`Client`](crate::client::Client) driver does all of this.
1328 ///
1329 /// # Errors
1330 /// When the APDU is malformed, protected more weakly than the policy demands, or
1331 /// not a response at all; when a GBT response outgrows `buf`.
1332 pub fn handle_response<'b>(&mut self, apdu: &[u8], buf: &'b mut [u8]) -> Result<Response<'b>> {
1333 self.handle_response_bytes(apdu, buf).map(|(response, _)| response)
1334 }
1335
1336 // The driver also needs the authenticated plaintext to copy the exact wire value.
1337 pub(super) fn handle_response_bytes<'b>(
1338 &mut self,
1339 apdu: &[u8],
1340 buf: &'b mut [u8],
1341 ) -> Result<(Response<'b>, &'b [u8])> {
1342 let plain: &'b [u8] = if apdu.first() == Some(&ApduTag::GeneralBlockTransfer.as_u8()) {
1343 match self.take_gbt_block(apdu, buf)? {
1344 GbtStep::Answer(r) => return Ok((r, &[])),
1345 GbtStep::Complete(range) => {
1346 let done: &'b [u8] = buf;
1347 done.get(range).ok_or(Error::new(ErrorKind::InvalidLength, 0))?
1348 }
1349 }
1350 } else {
1351 // A whole response while blocks were arriving ends that transfer: the server
1352 // has moved on, and gathering more of it would splice two answers.
1353 self.gbt_rx = None;
1354 self.unprotect_into(apdu, buf)?
1355 };
1356 let decoded = Apdu::from_bytes(plain)?;
1357 // An answer must be to the question that was asked. On a shared link — an
1358 // RS-485 bus, a concentrator multiplexing several meters — a response with
1359 // somebody else's invoke id is a reading attributed to the wrong request, and
1360 // nothing downstream can tell.
1361 if let Some(outstanding) = self.outstanding {
1362 if let Some(got) = response_invoke_id(&decoded) {
1363 if got.id() != outstanding.id() {
1364 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
1365 }
1366 }
1367 }
1368 let response = match decoded {
1369 Apdu::GetResponse(GetResponse::Normal { result, .. }) => match result.value() {
1370 Ok(d) => Response::Data(d),
1371 Err(e) => Response::DataError(e),
1372 },
1373 Apdu::GetResponse(GetResponse::WithList { results, .. }) => Response::DataList(results),
1374 Apdu::GetResponse(GetResponse::WithDataBlock { block, .. }) => match block.result {
1375 Ok(data) => Response::Block { last: block.last_block, number: block.block_number, data },
1376 Err(e) => Response::DataError(e),
1377 },
1378 Apdu::SetResponse(
1379 SetResponse::Normal { result, .. } | SetResponse::LastDataBlock { result, .. },
1380 ) => {
1381 if result.is_success() {
1382 Response::Ok
1383 } else {
1384 Response::DataError(result)
1385 }
1386 }
1387 Apdu::SetResponse(SetResponse::DataBlock { block_number, .. }) => {
1388 Response::BlockAccepted { number: block_number }
1389 }
1390 Apdu::SetResponse(
1391 SetResponse::WithList { results, .. } | SetResponse::LastDataBlockWithList { results, .. },
1392 ) => Response::ResultList(results),
1393 Apdu::ActionResponse(crate::xdlms::ActionResponse::Normal { response, .. }) => {
1394 Response::ActionResult {
1395 result: response.result,
1396 value: response.return_parameters.and_then(|p| p.value().ok()),
1397 }
1398 }
1399 Apdu::ActionResponse(crate::xdlms::ActionResponse::NextPblock { block_number, .. }) => {
1400 Response::BlockAccepted { number: block_number }
1401 }
1402 Apdu::ActionResponse(crate::xdlms::ActionResponse::WithList { responses, .. }) => {
1403 Response::ActionResults(responses)
1404 }
1405 Apdu::ActionResponse(crate::xdlms::ActionResponse::WithPblock { block, .. }) => {
1406 Response::Block { last: block.last_block, number: block.block_number, data: block.raw_data }
1407 }
1408 Apdu::AccessResponse(r) => Response::Access { data: r.data, results: r.response_specification },
1409 #[cfg(feature = "sn")]
1410 Apdu::ReadResponse(r) => Response::ReadResults(r.results),
1411 #[cfg(feature = "sn")]
1412 Apdu::WriteResponse(r) => Response::WriteResults(r.results),
1413 Apdu::ExceptionResponse(e) => Response::Exception(e),
1414 Apdu::Rlre(rlre) => {
1415 self.state = SessionState::Closed;
1416 Response::Released { reason: rlre.reason }
1417 }
1418 _ => return Err(Error::new(ErrorKind::UnexpectedMessage, 0)),
1419 };
1420 Ok((response, plain))
1421 }
1422
1423 #[cfg(feature = "std")]
1424 pub(super) fn abandon(&mut self) {
1425 self.gbt_rx = None;
1426 self.outstanding = None;
1427 self.state = SessionState::Closed;
1428 }
1429
1430 #[cfg(feature = "std")]
1431 pub(super) fn received_gbt_bytes(&self) -> usize {
1432 self.gbt_rx.as_ref().map_or(0, GbtRecvCursor::len)
1433 }
1434
1435 /// Encode an APDU, protecting it when the policy says so.
1436 fn send(&mut self, apdu: &Apdu<'_>, out: &mut [u8]) -> Result<usize> {
1437 let mut w = SliceWriter::new(&mut self.scratch);
1438 apdu.encode(&mut w)?;
1439 let plain_len = w.written();
1440 self.send_plain(plain_len, out)
1441 }
1442
1443 /// Protect and emit whatever the first `plain_len` bytes of the scratch buffer hold.
1444 fn send_plain(&mut self, plain_len: usize, out: &mut [u8]) -> Result<usize> {
1445 if self.config.security.is_none() {
1446 let mut w = SliceWriter::new(out);
1447 w.write_bytes(self.scratch.get(..plain_len).unwrap_or(&[]))?;
1448 return Ok(w.written());
1449 }
1450 let ctx = Outgoing {
1451 system_title: self.config.system_title.ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?,
1452 invocation_counter: self.invocation_counter.next()?,
1453 auth_key: self.protector.auth_key(),
1454 policy: self.protector.policy(),
1455 general_allowed: self.general_protection_agreed(),
1456 };
1457 let plain = self.scratch.get(..plain_len).unwrap_or(&[]);
1458 protect_apdu(&self.protector, &ctx, plain, out)
1459 }
1460
1461 /// Remove protection from the AARE's user information, which is protected with the
1462 /// global key set even when the association will use a dedicated one.
1463 fn unprotect_initiate<'b>(&mut self, apdu: &[u8], buf: &'b mut [u8]) -> Result<&'b [u8]> {
1464 let ctx = Incoming {
1465 local: self.config.system_title,
1466 peer: self.server_system_title,
1467 auth_key: self.protector.auth_key(),
1468 policy: self.config.security.global(),
1469 plain_allowed: PLAIN_INITIATE,
1470 };
1471 unprotect_apdu(&self.protector, &ctx, &mut self.peer_replay, apdu, buf)
1472 }
1473
1474 /// Remove protection from an incoming APDU, if it has any.
1475 /// Take one general-block-transfer APDU of a response.
1476 ///
1477 /// Blocks are gathered into `buf` — the caller's, and the same one on every call of a
1478 /// transfer — and protection comes off the whole response once, in place, with the same
1479 /// policy check as a single APDU: a block is never decrypted alone, and a plaintext
1480 /// response smuggled in blocks into a ciphered association is refused as a downgrade.
1481 fn take_gbt_block(&mut self, apdu: &[u8], buf: &mut [u8]) -> Result<GbtStep> {
1482 if self.state != SessionState::Associated {
1483 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
1484 }
1485 let Apdu::GeneralBlockTransfer(block) = Apdu::from_bytes(apdu)? else {
1486 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
1487 };
1488 // An empty block that is not the last one is an acknowledgement of blocks this
1489 // client is sending.
1490 if block.block_data.is_empty() && !block.control.last_block() {
1491 return Ok(GbtStep::Answer(Response::BlocksAcked {
1492 acked: block.block_number_ack,
1493 window: block.control.window(),
1494 }));
1495 }
1496 let mut cursor = match self.gbt_rx {
1497 Some(c) => c,
1498 None if block.block_number == 1 => GbtRecvCursor::new(self.config.gbt_window),
1499 // A block from the middle of a transfer nobody started.
1500 None => return Err(Error::new(ErrorKind::UnexpectedMessage, 0)),
1501 };
1502 let action = match cursor.push(buf, &block) {
1503 Ok(a) => a,
1504 Err(e) => {
1505 self.gbt_rx = None;
1506 return Err(e);
1507 }
1508 };
1509 match action {
1510 GbtAction::Await => {
1511 self.gbt_rx = Some(cursor);
1512 Ok(GbtStep::Answer(Response::Pending))
1513 }
1514 GbtAction::Acknowledge => {
1515 self.gbt_rx = Some(cursor);
1516 Ok(GbtStep::Answer(Response::Acknowledge(GbtAck::new(
1517 cursor.acknowledged(),
1518 cursor.window(),
1519 )?)))
1520 }
1521 GbtAction::Complete => {
1522 self.gbt_rx = None;
1523 let ctx = Incoming {
1524 local: self.config.system_title,
1525 peer: self.server_system_title,
1526 auth_key: self.protector.auth_key(),
1527 policy: self.protector.policy(),
1528 plain_allowed: PLAIN_FROM_SERVER,
1529 };
1530 let range =
1531 unprotect_apdu_in_place(&self.protector, &ctx, &mut self.peer_replay, buf, cursor.len())?;
1532 // A reassembled response may not itself be another block transfer.
1533 if buf.get(range.start) == Some(&ApduTag::GeneralBlockTransfer.as_u8()) {
1534 return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
1535 }
1536 Ok(GbtStep::Complete(range))
1537 }
1538 }
1539 }
1540
1541 /// True while a response is arriving as general block transfer.
1542 #[must_use]
1543 pub const fn is_receiving_blocks(&self) -> bool {
1544 self.gbt_rx.is_some()
1545 }
1546
1547 fn unprotect_into<'b>(&mut self, apdu: &[u8], buf: &'b mut [u8]) -> Result<&'b [u8]> {
1548 let ctx = Incoming {
1549 local: self.config.system_title,
1550 peer: self.server_system_title,
1551 auth_key: self.protector.auth_key(),
1552 policy: self.protector.policy(),
1553 plain_allowed: PLAIN_FROM_SERVER,
1554 };
1555 unprotect_apdu(&self.protector, &ctx, &mut self.peer_replay, apdu, buf)
1556 }
1557
1558 fn auth_key(&self) -> Result<&[u8]> {
1559 self.protector.auth_key().ok_or(Error::new(ErrorKind::Unsupported, 0))
1560 }
1561
1562 fn next_counter(&mut self) -> Result<u32> {
1563 self.invocation_counter.next()
1564 }
1565
1566 /// Refuse a short-name service in an association that named objects the other way.
1567 ///
1568 /// The referencing mode is chosen once, in the application context the AARQ
1569 /// proposes; a `read-request` sent into a logical-name association asks a question
1570 /// the peer has not agreed to answer, and a peer that answered anyway would be
1571 /// answering a different one.
1572 #[cfg(feature = "sn")]
1573 fn require_short_name(&self) -> Result<()> {
1574 if self.config.referencing == Referencing::ShortName {
1575 Ok(())
1576 } else {
1577 Err(Error::new(ErrorKind::UnexpectedMessage, 0))
1578 }
1579 }
1580
1581 fn require_associated(&self) -> Result<()> {
1582 if self.state == SessionState::Associated {
1583 Ok(())
1584 } else {
1585 Err(Error::new(ErrorKind::UnexpectedMessage, 0))
1586 }
1587 }
1588
1589 /// Whether `general-glo-ciphering` may be used, which the peer has to have agreed
1590 /// to: it is the `general-protection` bit of the conformance block and nothing else.
1591 fn general_protection_agreed(&self) -> bool {
1592 self.negotiated
1593 .as_ref()
1594 .is_some_and(|n| n.negotiated_conformance.contains(Conformance::GENERAL_PROTECTION))
1595 }
1596
1597 fn require_conformance(&self, required: Conformance) -> Result<()> {
1598 match &self.negotiated {
1599 Some(n) => n.negotiated_conformance.require(required),
1600 None => Ok(()),
1601 }
1602 }
1603}
1604
1605/// Gathers the fragments of a blocked response into one value.
1606///
1607/// A response too large for the negotiated PDU size arrives as a run of
1608/// `get-response-with-datablock` APDUs, each carrying a slice of the encoded value.
1609/// Only the concatenation is decodable: a fragment boundary falls wherever the server's
1610/// buffer ran out, which is very often in the middle of a length prefix.
1611///
1612/// The buffer is the caller's: how large a load profile may be is a property of the
1613/// deployment, not a decision for this crate.
1614///
1615/// ```
1616/// use dlms_cosem_kit::client::BlockCollector;
1617///
1618/// let mut storage = [0u8; 64];
1619/// let mut blocks = BlockCollector::new(&mut storage);
1620/// blocks.push(1, &[0x02, 0x02, 0x11])?; // a structure of two, first field…
1621/// blocks.push(2, &[0x07, 0x11, 0x09])?; // …split mid-value
1622/// let value = blocks.value()?;
1623/// assert_eq!(value.as_structure().unwrap().len(), 2);
1624/// # Ok::<(), dlms_cosem_kit::Error>(())
1625/// ```
1626#[derive(Debug)]
1627pub struct BlockCollector<'a> {
1628 buf: &'a mut [u8],
1629 len: usize,
1630 last_block: u32,
1631}
1632
1633impl<'a> BlockCollector<'a> {
1634 /// A collector filling `buf`.
1635 ///
1636 /// `buf` must be large enough for the whole encoded value; the largest attribute a
1637 /// meter will return is a profile buffer, and its size is a property of the meter
1638 /// rather than of the protocol.
1639 #[must_use]
1640 pub fn new(buf: &'a mut [u8]) -> Self {
1641 Self { buf, len: 0, last_block: 0 }
1642 }
1643
1644 /// Append one block.
1645 ///
1646 /// Block numbers must arrive consecutively from one. That check is not bookkeeping:
1647 /// a duplicated or reordered fragment concatenated in the wrong place produces a
1648 /// byte string that very often still *decodes*, into a value that is simply wrong —
1649 /// a meter reading no error ever attaches to.
1650 ///
1651 /// # Errors
1652 /// [`ErrorKind::UnexpectedMessage`] when `block_number` is not the one expected;
1653 /// [`ErrorKind::BufferTooSmall`] when the value does not fit.
1654 pub fn push(&mut self, block_number: u32, data: &[u8]) -> Result<()> {
1655 if block_number != self.last_block.saturating_add(1) {
1656 return Err(Error::new(ErrorKind::UnexpectedMessage, self.len));
1657 }
1658 let end = self.len.checked_add(data.len()).ok_or(Error::new(ErrorKind::InvalidLength, self.len))?;
1659 let capacity = self.buf.len();
1660 let at = self.len;
1661 let slot = self
1662 .buf
1663 .get_mut(at..end)
1664 .ok_or(Error::new(ErrorKind::BufferTooSmall { needed: end.saturating_sub(capacity) }, at))?;
1665 slot.copy_from_slice(data);
1666 self.len = end;
1667 self.last_block = block_number;
1668 Ok(())
1669 }
1670
1671 /// The number of the last block accepted; zero before the first.
1672 ///
1673 /// This is what [`ClientSession::get_next_block_request`] acknowledges.
1674 #[must_use]
1675 pub const fn last_block(&self) -> u32 {
1676 self.last_block
1677 }
1678
1679 /// How many bytes have been gathered.
1680 #[must_use]
1681 pub const fn len(&self) -> usize {
1682 self.len
1683 }
1684
1685 /// True before any block has been pushed.
1686 #[must_use]
1687 pub const fn is_empty(&self) -> bool {
1688 self.len == 0
1689 }
1690
1691 /// The bytes gathered so far.
1692 #[must_use]
1693 pub fn bytes(&self) -> &[u8] {
1694 self.buf.get(..self.len).unwrap_or(&[])
1695 }
1696
1697 /// Decode what has been gathered.
1698 ///
1699 /// # Errors
1700 /// Whatever decoding the value returns — including [`ErrorKind::Truncated`] if this
1701 /// is called before the last block has arrived.
1702 pub fn value(&self) -> Result<Data<'_>> {
1703 Data::from_bytes_in(self.bytes())
1704 }
1705
1706 /// Decode what has been gathered as the result list of a `get-request-with-list`.
1707 ///
1708 /// A blocked response carries the encoded body of whichever response form it is, so
1709 /// the fragments of a list read reassemble into a list rather than into a value.
1710 /// Calling the wrong one of this and [`BlockCollector::value`] is a decode error,
1711 /// not a wrong answer.
1712 ///
1713 /// # Errors
1714 /// Whatever decoding the list returns.
1715 pub fn results(&self) -> Result<List<'_, GetDataResult<'_>>> {
1716 List::from_bytes(self.bytes())
1717 }
1718
1719 /// Forget everything, ready for another read into the same buffer.
1720 pub const fn reset(&mut self) {
1721 self.len = 0;
1722 self.last_block = 0;
1723 }
1724}
1725
1726/// The invoke id a confirmed response echoes, for the services that carry one.
1727///
1728/// `None` for the APDUs that have no invoke id at all — the ACSE ones, the exception
1729/// response, and ACCESS, which uses a long invoke id of its own.
1730const fn response_invoke_id(apdu: &Apdu<'_>) -> Option<InvokeId> {
1731 Some(match apdu {
1732 Apdu::GetResponse(
1733 GetResponse::Normal { invoke_id, .. }
1734 | GetResponse::WithDataBlock { invoke_id, .. }
1735 | GetResponse::WithList { invoke_id, .. },
1736 ) => *invoke_id,
1737 Apdu::SetResponse(
1738 SetResponse::Normal { invoke_id, .. }
1739 | SetResponse::DataBlock { invoke_id, .. }
1740 | SetResponse::LastDataBlock { invoke_id, .. }
1741 | SetResponse::LastDataBlockWithList { invoke_id, .. }
1742 | SetResponse::WithList { invoke_id, .. },
1743 ) => *invoke_id,
1744 Apdu::ActionResponse(
1745 crate::xdlms::ActionResponse::Normal { invoke_id, .. }
1746 | crate::xdlms::ActionResponse::WithPblock { invoke_id, .. }
1747 | crate::xdlms::ActionResponse::WithList { invoke_id, .. }
1748 | crate::xdlms::ActionResponse::NextPblock { invoke_id, .. },
1749 ) => *invoke_id,
1750 _ => return None,
1751 })
1752}
1753
1754/// Which service a [`BlockSender`] is feeding.
1755#[derive(Debug, Clone, Copy, PartialEq)]
1756enum BlockTarget<'a> {
1757 /// A SET: the first block carries the attribute descriptor and any selector.
1758 Attribute { descriptor: AttributeDescriptor, access: Option<SelectiveAccess<'a>> },
1759 /// An ACTION: the first block carries the method descriptor.
1760 Method(MethodDescriptor),
1761 /// A batched SET: the first block carries the whole attribute list.
1762 AttributeList(List<'a, AttributeDescriptorWithSelection<'a>>),
1763}
1764
1765/// A value going out block by block, because it is larger than one APDU can carry.
1766///
1767/// The mirror of [`BlockCollector`]: that one gathers a long *response*, this one emits a
1768/// long *request*. The bytes stay the caller's in both directions, for the same reason —
1769/// how large a value a deployment writes is a property of the deployment, and a session
1770/// that buffered it would put a ceiling on it that nothing in the standard has.
1771///
1772/// Every block of one transfer carries the same invoke id, which the session keeps.
1773#[derive(Debug, Clone, Copy)]
1774pub struct BlockSender<'a> {
1775 target: BlockTarget<'a>,
1776 bytes: &'a [u8],
1777 sent: usize,
1778 block: u32,
1779 /// Non-zero by construction: a `div_ceil` by a plain `usize` leaves a
1780 /// divide-by-zero panic path in the object code, and a fragment of zero would in
1781 /// any case never finish.
1782 fragment: core::num::NonZeroUsize,
1783}
1784
1785impl BlockSender<'_> {
1786 /// True when every block has gone out.
1787 #[must_use]
1788 pub const fn is_done(&self) -> bool {
1789 self.block > 0 && self.sent >= self.bytes.len()
1790 }
1791
1792 /// How many bytes are still to go.
1793 #[must_use]
1794 pub const fn remaining(&self) -> usize {
1795 self.bytes.len().saturating_sub(self.sent)
1796 }
1797
1798 /// The number of the last block emitted; zero before the first.
1799 #[must_use]
1800 pub const fn block(&self) -> u32 {
1801 self.block
1802 }
1803
1804 /// How many blocks this transfer will take in total.
1805 #[must_use]
1806 pub const fn blocks(&self) -> usize {
1807 // An empty value is still one block: it has to be sent for the server to learn
1808 // that it is the last one.
1809 let n = self.bytes.len().div_ceil(self.fragment.get());
1810 if n == 0 { 1 } else { n }
1811 }
1812}
1813
1814/// One operation inside an [`ClientSession::access_request`].
1815///
1816/// ACCESS is the only service that mixes reads, writes and invocations into a single
1817/// exchange, which is what makes it the right one for a link where a round trip costs
1818/// more than a kilobyte.
1819#[derive(Debug, Clone, Copy, PartialEq)]
1820pub enum AccessItem<'a> {
1821 /// Read an attribute.
1822 Get {
1823 /// Which attribute.
1824 descriptor: AttributeDescriptor,
1825 /// Which part of it.
1826 access: Option<SelectiveAccess<'a>>,
1827 },
1828 /// Write an attribute.
1829 Set {
1830 /// Which attribute.
1831 descriptor: AttributeDescriptor,
1832 /// Which part of it.
1833 access: Option<SelectiveAccess<'a>>,
1834 /// The new value.
1835 value: Data<'a>,
1836 },
1837 /// Invoke a method.
1838 Action {
1839 /// Which method.
1840 descriptor: MethodDescriptor,
1841 /// Its parameter, if it takes one.
1842 parameters: Option<Data<'a>>,
1843 },
1844}
1845
1846impl<'a> AccessItem<'a> {
1847 fn specification(&self) -> AccessRequestSpecification<'a> {
1848 match *self {
1849 Self::Get { descriptor, access: None } => AccessRequestSpecification::Get(descriptor),
1850 Self::Get { descriptor, access: Some(access) } => {
1851 AccessRequestSpecification::GetWithSelection(AttributeDescriptorWithSelection {
1852 descriptor,
1853 access: Some(access),
1854 })
1855 }
1856 Self::Set { descriptor, access: None, .. } => AccessRequestSpecification::Set(descriptor),
1857 Self::Set { descriptor, access: Some(access), .. } => {
1858 AccessRequestSpecification::SetWithSelection(AttributeDescriptorWithSelection {
1859 descriptor,
1860 access: Some(access),
1861 })
1862 }
1863 Self::Action { descriptor, .. } => AccessRequestSpecification::Action(descriptor),
1864 }
1865 }
1866}