Skip to main content

spodes_rs/
session.rs

1//! A client-side session driver tying the transport, service and ciphering
2//! layers together (IEC 62056-5-3 / IEC 62056-53 client CF).
3//!
4//! [`crate::session::ClientSession`] wraps any [`crate::transport::DataLinkLayer`] (HDLC or wrapper) and exposes
5//! the confirmed COSEM services — association, GET, SET, ACTION, release — as
6//! blocking request/response round trips. When a [`crate::service::ciphering::SecurityContext`] is
7//! configured, request APDUs are protected with global (glo-) ciphering and the
8//! matching ciphered responses are transparently unprotected; the client
9//! invocation counter is advanced after every protected request.
10//!
11//! # Timeouts and retries
12//!
13//! Use the `ClientSessionBuilder` to configure per-request timeouts and
14//! automatic retries for transient errors:
15//!
16//! ```no_run
17//! # use spodes_rs::session::ClientSessionBuilder;
18//! # use spodes_rs::transport::wrapper::Wrapper;
19//! # use spodes_rs::transport::MemoryTransport;
20//! # fn example() {
21//! let transport = MemoryTransport::new();
22//! let wrapper = Wrapper::new(transport, 1, 1024);
23//! let mut session = ClientSessionBuilder::new(wrapper)
24//!     .request_timeout(std::time::Duration::from_secs(5))
25//!     .max_retries(3)
26//!     .retry_delay(std::time::Duration::from_millis(200))
27//!     .build();
28//! # }
29//! ```
30
31use std::io;
32use std::time::{Duration, Instant};
33
34#[cfg(feature = "tracing")]
35use tracing::{debug, error, info, trace, warn};
36
37use crate::obis::ObisCode;
38use crate::service::acse;
39use crate::service::acse::{AssociationRequest, AssociationResponse, ReleaseRequest, ReleaseResponse};
40use crate::service::action::{ActionRequest, ActionResponse};
41use crate::service::ciphering::{self, glo, SecurityContext};
42use crate::service::gbt;
43use crate::service::get::{GetRequest, GetResponse};
44use crate::service::set::{SetRequest, SetResponse};
45use crate::service::{invoke_id_and_priority, tag, AttributeDescriptor, MethodDescriptor, RawApdu};
46use crate::transport::DataLinkLayer;
47use crate::types::CosemDataType;
48
49/// Errors raised by the session driver.
50#[derive(Debug)]
51pub enum SessionError {
52    /// A transport-level I/O error.
53    Io(io::Error),
54    /// A service APDU could not be encoded or decoded.
55    Service(crate::service::ServiceError),
56    /// Applying or removing APDU protection failed.
57    Cipher(ciphering::CipherError),
58    /// The peer replied with an APDU whose tag was not expected here.
59    UnexpectedApdu(u8),
60    /// The request timed out waiting for a response.
61    Timeout,
62    /// Maximum number of retries exceeded.
63    MaxRetries(u32),
64}
65
66/// Configuration for timeouts and retries.
67#[derive(Debug, Clone)]
68pub struct SessionConfig {
69    /// Maximum time to wait for a response before retrying or failing.
70    pub request_timeout: Option<Duration>,
71    /// Maximum number of retry attempts for transient errors.
72    pub max_retries: u32,
73    /// Delay between retry attempts.
74    pub retry_delay: Duration,
75}
76
77impl Default for SessionConfig {
78    fn default() -> Self {
79        SessionConfig { request_timeout: None, max_retries: 0, retry_delay: Duration::from_millis(100) }
80    }
81}
82
83impl SessionConfig {
84    /// Creates a new config with default values.
85    pub fn new() -> Self {
86        Self::default()
87    }
88
89    /// Sets the request timeout.
90    #[must_use]
91    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
92        self.request_timeout = Some(timeout);
93        self
94    }
95
96    /// Sets the maximum number of retries.
97    #[must_use]
98    pub fn with_max_retries(mut self, retries: u32) -> Self {
99        self.max_retries = retries;
100        self
101    }
102
103    /// Sets the delay between retries.
104    #[must_use]
105    pub fn with_retry_delay(mut self, delay: Duration) -> Self {
106        self.retry_delay = delay;
107        self
108    }
109}
110
111impl std::fmt::Display for SessionError {
112    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113        match self {
114            SessionError::Io(e) => write!(f, "transport I/O error: {e}"),
115            SessionError::Service(e) => write!(f, "service error: {e}"),
116            SessionError::Cipher(e) => write!(f, "ciphering error: {e:?}"),
117            SessionError::UnexpectedApdu(t) => write!(f, "unexpected response APDU tag 0x{t:02X}"),
118            SessionError::Timeout => write!(f, "request timed out"),
119            SessionError::MaxRetries(n) => write!(f, "maximum retries ({n}) exceeded"),
120        }
121    }
122}
123
124impl std::error::Error for SessionError {}
125
126impl From<io::Error> for SessionError {
127    fn from(e: io::Error) -> Self {
128        SessionError::Io(e)
129    }
130}
131
132impl From<crate::service::ServiceError> for SessionError {
133    fn from(e: crate::service::ServiceError) -> Self {
134        SessionError::Service(e)
135    }
136}
137
138impl From<ciphering::CipherError> for SessionError {
139    fn from(e: ciphering::CipherError) -> Self {
140        SessionError::Cipher(e)
141    }
142}
143
144/// The two directional ciphering contexts of a secured session. Each direction
145/// has its own initialization-vector stream: outbound APDUs use the client's
146/// system-title and invocation counter, inbound APDUs the server's. The
147/// service-specific glo-ciphering APDU does not carry the originator title, so
148/// both titles must be known out of band (from the AARQ/AARE exchange).
149struct Ciphers {
150    /// Protects outbound requests (client system-title, client counter).
151    tx: SecurityContext,
152    /// Removes protection from inbound responses (server system-title).
153    rx: SecurityContext,
154}
155
156/// General block transfer configuration for a session (IEC 62056-5-3 §9.3):
157/// requests/responses whose service qualifies (see [`gbt::applies_to_apdu`])
158/// and exceed `block_payload_max` are segmented into GBT blocks instead of
159/// sent as a single frame.
160#[derive(Debug, Clone, Copy)]
161struct GbtConfig {
162    /// Maximum payload octets per block (the overall block size minus the
163    /// GBT header, see [`gbt::HEADER_MAX`]).
164    block_payload_max: usize,
165    /// Confirmed-mode window size (0 = unconfirmed: no ack is awaited
166    /// between blocks).
167    window: u8,
168    /// Whether the streaming variant is used.
169    streaming: bool,
170}
171
172impl GbtConfig {
173    fn new(block_size: usize) -> Self {
174        let block_payload_max = block_size.saturating_sub(gbt::HEADER_MAX).max(1);
175        GbtConfig { block_payload_max, window: 0, streaming: false }
176    }
177}
178
179/// Current state of the application association.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum AssociationState {
182    /// No association established.
183    Idle,
184    /// AARQ sent, waiting for AARE.
185    Pending,
186    /// Association established and active.
187    Associated,
188}
189
190/// A blocking client session over a framing sub-layer `L`.
191pub struct ClientSession<L: DataLinkLayer> {
192    link: L,
193    invoke_id: u8,
194    high_priority: bool,
195    cipher: Option<Ciphers>,
196    gbt: Option<GbtConfig>,
197    config: SessionConfig,
198    state: AssociationState,
199    /// Negotiated application context (from AARQ/AARE).
200    application_context: u8,
201    /// Negotiated mechanism (from AARQ/AARE).
202    mechanism: Option<u8>,
203}
204
205/// Builder for AARQ construction with a fluent API.
206pub struct AarqBuilder {
207    application_context: u8,
208    calling_ap_title: Option<Vec<u8>>,
209    mechanism_name: Option<u8>,
210    calling_authentication_value: Option<Vec<u8>>,
211    user_information: Vec<u8>,
212}
213
214impl AarqBuilder {
215    /// Creates a new AARQ builder with LN referencing (no ciphering).
216    pub fn new() -> Self {
217        AarqBuilder {
218            application_context: acse::application_context::LN,
219            calling_ap_title: None,
220            mechanism_name: None,
221            calling_authentication_value: None,
222            user_information: Vec::new(),
223        }
224    }
225
226    /// Sets the application context (LN, SN, LN_CIPHERING, SN_CIPHERING).
227    #[must_use]
228    pub fn application_context(mut self, ctx: u8) -> Self {
229        self.application_context = ctx;
230        self
231    }
232
233    /// Sets the calling AP title (client system title) for ciphering.
234    #[must_use]
235    pub fn calling_ap_title(mut self, title: Vec<u8>) -> Self {
236        self.calling_ap_title = Some(title);
237        self
238    }
239
240    /// Sets the authentication mechanism (LLS, HLS_MD5, HLS_SHA1, HLS_GMAC).
241    #[must_use]
242    pub fn mechanism(mut self, mech: u8) -> Self {
243        self.mechanism_name = Some(mech);
244        self
245    }
246
247    /// Sets the calling authentication value (LLS password or HLS challenge).
248    #[must_use]
249    pub fn authentication_value(mut self, value: Vec<u8>) -> Self {
250        self.calling_authentication_value = Some(value);
251        self
252    }
253
254    /// Sets the user information (InitiateRequest APDU).
255    #[must_use]
256    pub fn user_information(mut self, info: Vec<u8>) -> Self {
257        self.user_information = info;
258        self
259    }
260
261    /// Builds the AARQ request.
262    pub fn build(self) -> AssociationRequest {
263        AssociationRequest {
264            protocol_version: None,
265            application_context: self.application_context,
266            calling_ap_title: self.calling_ap_title,
267            sender_acse_requirements: self.mechanism_name.map(|_| 0x80),
268            mechanism_name: self.mechanism_name,
269            calling_authentication_value: self.calling_authentication_value,
270            user_information: self.user_information,
271        }
272    }
273}
274
275impl Default for AarqBuilder {
276    fn default() -> Self {
277        Self::new()
278    }
279}
280
281/// Builder for creating a [`ClientSession`] with custom configuration.
282pub struct ClientSessionBuilder<L: DataLinkLayer> {
283    link: L,
284    config: SessionConfig,
285    tx_cipher: Option<SecurityContext>,
286    rx_cipher: Option<SecurityContext>,
287    gbt: Option<GbtConfig>,
288}
289
290impl<L: DataLinkLayer> ClientSessionBuilder<L> {
291    /// Creates a new builder with the given transport link.
292    pub fn new(link: L) -> Self {
293        ClientSessionBuilder { link, config: SessionConfig::default(), tx_cipher: None, rx_cipher: None, gbt: None }
294    }
295
296    /// Sets the request timeout. If a response is not received within this
297    /// duration, the request is retried (if retries are configured) or
298    /// a [`SessionError::Timeout`] error is returned.
299    #[must_use]
300    pub fn request_timeout(mut self, timeout: Duration) -> Self {
301        self.config.request_timeout = Some(timeout);
302        self
303    }
304
305    /// Sets the maximum number of retry attempts for transient errors
306    /// (I/O errors, unexpected APDUs). Set to 0 for no retries.
307    #[must_use]
308    pub fn max_retries(mut self, retries: u32) -> Self {
309        self.config.max_retries = retries;
310        self
311    }
312
313    /// Sets the delay between retry attempts.
314    #[must_use]
315    pub fn retry_delay(mut self, delay: Duration) -> Self {
316        self.config.retry_delay = delay;
317        self
318    }
319
320    /// Configures global ciphering for the session.
321    #[must_use]
322    pub fn with_ciphering(mut self, tx: SecurityContext, rx: SecurityContext) -> Self {
323        self.tx_cipher = Some(tx);
324        self.rx_cipher = Some(rx);
325        self
326    }
327
328    /// Enables general block transfer (IEC 62056-5-3 §9.3) for requests and
329    /// responses whose service qualifies (see [`gbt::applies_to_apdu`]) and
330    /// exceed `block_size` octets: they are segmented into GBT blocks instead
331    /// of sent as a single frame. Unconfirmed by default (no ack between
332    /// blocks); see [`ClientSessionBuilder::gbt_window`] for confirmed mode.
333    #[must_use]
334    pub fn with_gbt(mut self, block_size: usize) -> Self {
335        self.gbt = Some(GbtConfig::new(block_size));
336        self
337    }
338
339    /// Sets the confirmed-mode window size for GBT (0 = unconfirmed).
340    /// Has no effect unless [`ClientSessionBuilder::with_gbt`] was called.
341    #[must_use]
342    pub fn gbt_window(mut self, window: u8) -> Self {
343        if let Some(g) = self.gbt.as_mut() {
344            g.window = window;
345        }
346        self
347    }
348
349    /// Enables the streaming variant of GBT. Has no effect unless
350    /// [`ClientSessionBuilder::with_gbt`] was called.
351    #[must_use]
352    pub fn gbt_streaming(mut self, enabled: bool) -> Self {
353        if let Some(g) = self.gbt.as_mut() {
354            g.streaming = enabled;
355        }
356        self
357    }
358
359    /// Builds the [`ClientSession`].
360    pub fn build(self) -> ClientSession<L> {
361        let cipher = match (self.tx_cipher, self.rx_cipher) {
362            (Some(tx), Some(rx)) => Some(Ciphers { tx, rx }),
363            _ => None,
364        };
365        ClientSession {
366            link: self.link,
367            invoke_id: 1,
368            high_priority: true,
369            cipher,
370            gbt: self.gbt,
371            config: self.config,
372            state: AssociationState::Idle,
373            application_context: acse::application_context::LN,
374            mechanism: None,
375        }
376    }
377}
378
379impl<L: DataLinkLayer> ClientSession<L> {
380    /// Creates a plaintext session (no APDU ciphering).
381    pub fn new(link: L) -> Self {
382        ClientSession {
383            link,
384            invoke_id: 1,
385            high_priority: true,
386            cipher: None,
387            gbt: None,
388            config: SessionConfig::default(),
389            state: AssociationState::Idle,
390            application_context: acse::application_context::LN,
391            mechanism: None,
392        }
393    }
394
395    /// Creates a session that protects request APDUs with global ciphering.
396    ///
397    /// `tx_context` protects outbound requests (client system-title / counter);
398    /// `rx_context` removes protection from inbound responses (server
399    /// system-title). Both are typically derived from the AARQ/AARE exchange.
400    pub fn with_ciphering(link: L, tx_context: SecurityContext, rx_context: SecurityContext) -> Self {
401        ClientSession {
402            link,
403            invoke_id: 1,
404            high_priority: true,
405            cipher: Some(Ciphers { tx: tx_context, rx: rx_context }),
406            gbt: None,
407            config: SessionConfig::default(),
408            state: AssociationState::Idle,
409            application_context: acse::application_context::LN_CIPHERING,
410            mechanism: None,
411        }
412    }
413
414    /// Enables general block transfer (IEC 62056-5-3 §9.3) for requests and
415    /// responses whose service qualifies (see [`gbt::applies_to_apdu`]) and
416    /// exceed `block_size` octets. Unconfirmed by default; see
417    /// [`Self::set_gbt_window`] for confirmed mode.
418    pub fn enable_gbt(&mut self, block_size: usize) {
419        self.gbt = Some(GbtConfig::new(block_size));
420    }
421
422    /// Disables general block transfer, restoring single-frame sends.
423    pub fn disable_gbt(&mut self) {
424        self.gbt = None;
425    }
426
427    /// Sets the confirmed-mode window size for GBT (0 = unconfirmed). Has no
428    /// effect unless GBT is enabled.
429    pub fn set_gbt_window(&mut self, window: u8) {
430        if let Some(g) = self.gbt.as_mut() {
431            g.window = window;
432        }
433    }
434
435    /// Enables or disables the streaming variant of GBT. Has no effect
436    /// unless GBT is enabled.
437    pub fn set_gbt_streaming(&mut self, enabled: bool) {
438        if let Some(g) = self.gbt.as_mut() {
439            g.streaming = enabled;
440        }
441    }
442
443    /// Returns a builder for configuring this session's timeouts and retries.
444    pub fn builder(link: L) -> ClientSessionBuilder<L> {
445        ClientSessionBuilder::new(link)
446    }
447
448    /// Returns the underlying framing layer.
449    pub fn into_inner(self) -> L {
450        self.link
451    }
452
453    /// Returns a reference to the current session configuration.
454    pub fn config(&self) -> &SessionConfig {
455        &self.config
456    }
457
458    /// Updates the session configuration.
459    pub fn set_config(&mut self, config: SessionConfig) {
460        self.config = config;
461    }
462
463    /// Sets the request timeout.
464    pub fn set_request_timeout(&mut self, timeout: Duration) {
465        self.config.request_timeout = Some(timeout);
466    }
467
468    /// Sets the maximum number of retries.
469    pub fn set_max_retries(&mut self, retries: u32) {
470        self.config.max_retries = retries;
471    }
472
473    /// Sets the retry delay.
474    pub fn set_retry_delay(&mut self, delay: Duration) {
475        self.config.retry_delay = delay;
476    }
477
478    /// The invoke-id-and-priority octet for the next request.
479    fn iiap(&self) -> u8 {
480        invoke_id_and_priority(self.invoke_id, true, self.high_priority)
481    }
482
483    /// Returns the current association state.
484    pub fn state(&self) -> AssociationState {
485        self.state
486    }
487
488    /// Returns the negotiated application context.
489    pub fn application_context(&self) -> u8 {
490        self.application_context
491    }
492
493    /// Returns the negotiated authentication mechanism, if any.
494    pub fn mechanism(&self) -> Option<u8> {
495        self.mechanism
496    }
497
498    /// Returns true if the session is currently associated.
499    pub fn is_associated(&self) -> bool {
500        self.state == AssociationState::Associated
501    }
502
503    /// Opens an application association by exchanging AARQ / AARE. The ACSE APDUs
504    /// are sent as-is (any ciphering is inside their user-information field).
505    ///
506    /// On success, updates the session state to `Associated` and records the
507    /// negotiated application context and mechanism.
508    pub fn associate(&mut self, request: &AssociationRequest) -> Result<AssociationResponse, SessionError> {
509        #[cfg(feature = "tracing")]
510        info!("sending AARQ association request");
511        self.state = AssociationState::Pending;
512        self.application_context = request.application_context;
513        self.mechanism = request.mechanism_name;
514        self.link.send_apdu(&request.encode())?;
515        let reply = self.link.receive_apdu()?;
516        let response = AssociationResponse::decode(&reply)?;
517        #[cfg(feature = "tracing")]
518        info!(result = response.result, "received AARE association response");
519        if response.result == acse::result::ACCEPTED {
520            self.state = AssociationState::Associated;
521        } else {
522            self.state = AssociationState::Idle;
523        }
524        Ok(response)
525    }
526
527    /// Convenience method: associates with no security (mechanism 0).
528    pub fn associate_no_security(&mut self, initiate_request: Vec<u8>) -> Result<AssociationResponse, SessionError> {
529        let aarq = AarqBuilder::new()
530            .application_context(acse::application_context::LN)
531            .user_information(initiate_request)
532            .build();
533        self.associate(&aarq)
534    }
535
536    /// Convenience method: associates with Low-Level Security (password).
537    pub fn associate_lls(
538        &mut self,
539        password: Vec<u8>,
540        initiate_request: Vec<u8>,
541    ) -> Result<AssociationResponse, SessionError> {
542        let aarq = AarqBuilder::new()
543            .application_context(acse::application_context::LN)
544            .mechanism(acse::mechanism::LLS)
545            .authentication_value(password)
546            .user_information(initiate_request)
547            .build();
548        self.associate(&aarq)
549    }
550
551    /// Convenience method: associates with High-Level Security (SHA-1).
552    pub fn associate_hls_sha1(
553        &mut self,
554        challenge: Vec<u8>,
555        initiate_request: Vec<u8>,
556    ) -> Result<AssociationResponse, SessionError> {
557        let aarq = AarqBuilder::new()
558            .application_context(acse::application_context::LN)
559            .mechanism(acse::mechanism::HLS_SHA1)
560            .authentication_value(challenge)
561            .user_information(initiate_request)
562            .build();
563        self.associate(&aarq)
564    }
565
566    /// Convenience method: associates with GMAC (mechanism 5) and ciphering.
567    pub fn associate_gmac(
568        &mut self,
569        client_system_title: Vec<u8>,
570        initiate_request: Vec<u8>,
571    ) -> Result<AssociationResponse, SessionError> {
572        let aarq = AarqBuilder::new()
573            .application_context(acse::application_context::LN_CIPHERING)
574            .calling_ap_title(client_system_title)
575            .mechanism(acse::mechanism::HLS_GMAC)
576            .user_information(initiate_request)
577            .build();
578        self.associate(&aarq)
579    }
580
581    /// Gracefully releases the association by exchanging RLRQ / RLRE.
582    ///
583    /// On success, resets the session state to `Idle`.
584    pub fn release(&mut self, request: &ReleaseRequest) -> Result<ReleaseResponse, SessionError> {
585        #[cfg(feature = "tracing")]
586        info!("sending RLRQ release request");
587        self.link.send_apdu(&request.encode_rlrq())?;
588        let reply = self.link.receive_apdu()?;
589        let response = ReleaseResponse::decode_rlre(&reply)?;
590        #[cfg(feature = "tracing")]
591        info!("received RLRE release response");
592        self.state = AssociationState::Idle;
593        Ok(response)
594    }
595
596    /// Convenience method: releases with normal reason.
597    pub fn release_normal(&mut self) -> Result<ReleaseResponse, SessionError> {
598        let rlrq = ReleaseRequest { reason: Some(acse::release_reason::NORMAL), user_information: None };
599        self.release(&rlrq)
600    }
601
602    // ========================================================================
603    // Raw APDU support
604    // ========================================================================
605
606    /// Sends a raw APDU and receives a raw response without parsing.
607    ///
608    /// This method bypasses the typed service layer and works directly with
609    /// raw bytes, which is useful for:
610    /// - Manufacturer-specific APDUs
611    /// - Extension APDUs not defined in IEC 62056-5-3
612    /// - Testing and debugging
613    /// - Custom protocol extensions
614    ///
615    /// If ciphering is configured, the raw APDU is protected/unprotected
616    /// transparently.
617    pub fn send_raw(&mut self, apdu: &RawApdu) -> Result<RawApdu, SessionError> {
618        #[cfg(feature = "tracing")]
619        debug!(tag = format_args!("0x{:02X}", apdu.tag()), body_len = apdu.body().len(), "sending raw APDU");
620        let encoded = apdu.encode();
621        let outgoing = match &self.cipher {
622            None => encoded,
623            Some(c) => {
624                // Determine the glo tag from the raw tag
625                let glo_tag = match apdu.tag() {
626                    tag::GET_REQUEST => glo::GET_REQUEST,
627                    tag::SET_REQUEST => glo::SET_REQUEST,
628                    tag::ACTION_REQUEST => glo::ACTION_REQUEST,
629                    tag::GET_RESPONSE => glo::GET_RESPONSE,
630                    tag::SET_RESPONSE => glo::SET_RESPONSE,
631                    tag::ACTION_RESPONSE => glo::ACTION_RESPONSE,
632                    _ => apdu.tag(), // pass through unknown tags
633                };
634                ciphering::protect(&c.tx, glo_tag, &encoded)?
635            }
636        };
637        self.link.send_apdu(&outgoing)?;
638        if let Some(c) = &mut self.cipher {
639            c.tx.invocation_counter = c.tx.invocation_counter.wrapping_add(1);
640        }
641
642        let reply = self.link.receive_apdu()?;
643        let response = match &self.cipher {
644            None => RawApdu::from_bytes(&reply)?,
645            Some(c) => {
646                let (_, plaintext) = ciphering::unprotect(&mut c.rx.clone(), &reply)?;
647                RawApdu::from_bytes(&plaintext)?
648            }
649        };
650        #[cfg(feature = "tracing")]
651        debug!(tag = format_args!("0x{:02X}", response.tag()), body_len = response.body().len(), "received raw APDU");
652        Ok(response)
653    }
654
655    /// Sends raw bytes and receives raw bytes without any parsing or protection.
656    ///
657    /// This is the lowest-level send/receive method, bypassing even the
658    /// raw APDU framing. Use for completely custom protocols.
659    pub fn send_raw_bytes(&mut self, data: &[u8]) -> Result<Vec<u8>, SessionError> {
660        #[cfg(feature = "tracing")]
661        debug!(len = data.len(), "sending raw bytes");
662        self.link.send_apdu(data)?;
663        let reply = self.link.receive_apdu()?;
664        #[cfg(feature = "tracing")]
665        debug!(len = reply.len(), "received raw bytes");
666        Ok(reply)
667    }
668
669    /// Creates a raw APDU with the given tag and body.
670    pub fn make_raw_apdu(tag: u8, body: Vec<u8>) -> RawApdu {
671        RawApdu::new(tag, body)
672    }
673
674    /// Parses a raw APDU from bytes.
675    pub fn parse_raw_apdu(bytes: &[u8]) -> Result<RawApdu, SessionError> {
676        Ok(RawApdu::from_bytes(bytes)?)
677    }
678
679    /// Reads one attribute (GET-REQUEST-NORMAL).
680    pub fn get(&mut self, class_id: u16, instance: ObisCode, attribute_id: i8) -> Result<GetResponse, SessionError> {
681        #[cfg(feature = "tracing")]
682        debug!(class_id, instance = %instance, attribute_id, "sending GET request");
683        let request = GetRequest::Normal {
684            invoke_id_and_priority: self.iiap(),
685            attribute: AttributeDescriptor::new(class_id, instance, attribute_id),
686            access_selection: None,
687        };
688        let reply = self.transact(&request.encode()?, glo::GET_REQUEST, tag::GET_RESPONSE)?;
689        let response = GetResponse::decode(&reply)?;
690        #[cfg(feature = "tracing")]
691        debug!("GET response received");
692        Ok(response)
693    }
694
695    /// Writes one attribute (SET-REQUEST-NORMAL).
696    pub fn set(
697        &mut self,
698        class_id: u16,
699        instance: ObisCode,
700        attribute_id: i8,
701        value: CosemDataType,
702    ) -> Result<SetResponse, SessionError> {
703        #[cfg(feature = "tracing")]
704        debug!(class_id, instance = %instance, attribute_id, "sending SET request");
705        let request = SetRequest::Normal {
706            invoke_id_and_priority: self.iiap(),
707            attribute: AttributeDescriptor::new(class_id, instance, attribute_id),
708            access_selection: None,
709            value,
710        };
711        let reply = self.transact(&request.encode()?, glo::SET_REQUEST, tag::SET_RESPONSE)?;
712        let response = SetResponse::decode(&reply)?;
713        #[cfg(feature = "tracing")]
714        debug!("SET response received");
715        Ok(response)
716    }
717
718    /// Invokes one method (ACTION-REQUEST-NORMAL).
719    pub fn action(
720        &mut self,
721        class_id: u16,
722        instance: ObisCode,
723        method_id: i8,
724        parameters: Option<CosemDataType>,
725    ) -> Result<ActionResponse, SessionError> {
726        #[cfg(feature = "tracing")]
727        debug!(class_id, instance = %instance, method_id, "sending ACTION request");
728        let request = ActionRequest::Normal {
729            invoke_id_and_priority: self.iiap(),
730            method: MethodDescriptor::new(class_id, instance, method_id),
731            parameters,
732        };
733        let reply = self.transact(&request.encode()?, glo::ACTION_REQUEST, tag::ACTION_RESPONSE)?;
734        let response = ActionResponse::decode(&reply)?;
735        #[cfg(feature = "tracing")]
736        debug!("ACTION response received");
737        Ok(response)
738    }
739
740    /// Sends one request APDU and returns the plaintext response APDU.
741    ///
742    /// Without ciphering the request is sent verbatim. With ciphering it is
743    /// protected under `glo_request_tag`, the invocation counter is advanced, and
744    /// the ciphered response is unprotected. The returned APDU is expected to
745    /// carry `expected_response_tag`.
746    ///
747    /// If timeouts and retries are configured via [`SessionConfig`], this method
748    /// will retry on transient errors (I/O errors, unexpected APDUs) up to
749    /// `max_retries` times with the configured `retry_delay` between attempts.
750    fn transact(
751        &mut self,
752        plain_request: &[u8],
753        glo_request_tag: u8,
754        expected_response_tag: u8,
755    ) -> Result<Vec<u8>, SessionError> {
756        let max_attempts = self.config.max_retries + 1;
757        let mut last_error = None;
758
759        for attempt in 0..max_attempts {
760            if attempt > 0 {
761                #[cfg(feature = "tracing")]
762                warn!(attempt, max_attempts, "retrying after transient error");
763                std::thread::sleep(self.config.retry_delay);
764            }
765
766            let result = self.transact_once(plain_request, glo_request_tag, expected_response_tag);
767
768            match result {
769                Ok(reply) => {
770                    #[cfg(feature = "tracing")]
771                    trace!(attempt, "transaction completed successfully");
772                    return Ok(reply);
773                }
774                Err(SessionError::Io(e)) if is_transient_io(&e) && attempt + 1 < max_attempts => {
775                    #[cfg(feature = "tracing")]
776                    warn!(attempt, error = %e, "transient I/O error, will retry");
777                    last_error = Some(SessionError::Io(e));
778                }
779                Err(SessionError::UnexpectedApdu(t)) if attempt + 1 < max_attempts => {
780                    #[cfg(feature = "tracing")]
781                    warn!(attempt, tag = format_args!("0x{t:02X}"), "unexpected APDU tag, will retry");
782                    last_error = Some(SessionError::UnexpectedApdu(t));
783                }
784                Err(e) => return Err(e),
785            }
786        }
787
788        #[cfg(feature = "tracing")]
789        error!(max_attempts, "all retry attempts exhausted");
790        Err(last_error.unwrap_or(SessionError::MaxRetries(max_attempts)))
791    }
792
793    /// Single attempt at a transaction (no retries).
794    fn transact_once(
795        &mut self,
796        plain_request: &[u8],
797        glo_request_tag: u8,
798        expected_response_tag: u8,
799    ) -> Result<Vec<u8>, SessionError> {
800        let deadline = self.config.request_timeout.map(|t| Instant::now() + t);
801
802        let outgoing = match &self.cipher {
803            None => plain_request.to_vec(),
804            Some(c) => {
805                #[cfg(feature = "tracing")]
806                trace!(counter = c.tx.invocation_counter, "encrypting request APDU");
807                ciphering::protect(&c.tx, glo_request_tag, plain_request)?
808            }
809        };
810        #[cfg(feature = "tracing")]
811        trace!(len = outgoing.len(), "sending APDU");
812        // Segment via general block transfer when it's enabled, the plain
813        // request's service qualifies, and the (possibly ciphered) frame
814        // exceeds the configured block size; qualification is checked on the
815        // plain request so ciphering doesn't change whether GBT applies.
816        match &self.gbt {
817            Some(g) if gbt::applies_to_apdu(plain_request) && outgoing.len() > g.block_payload_max => {
818                gbt::send(&mut self.link, &outgoing, g.block_payload_max, g.window, g.streaming)?;
819            }
820            _ => self.link.send_apdu(&outgoing)?,
821        }
822        if let Some(c) = &mut self.cipher {
823            // Advance our sending counter for the next protected request.
824            c.tx.invocation_counter = c.tx.invocation_counter.wrapping_add(1);
825        }
826
827        // Check timeout before receive
828        if let Some(deadline) = deadline {
829            if Instant::now() >= deadline {
830                #[cfg(feature = "tracing")]
831                warn!("request timed out before receive");
832                return Err(SessionError::Timeout);
833            }
834        }
835
836        let reply = self.link.receive_apdu()?;
837        let reply = if reply.first() == Some(&gbt::GENERAL_BLOCK_TRANSFER) {
838            gbt::receive(&mut self.link, &reply)?
839        } else {
840            reply
841        };
842
843        // Check timeout after receive
844        if let Some(deadline) = deadline {
845            if Instant::now() >= deadline {
846                #[cfg(feature = "tracing")]
847                warn!("request timed out after receive");
848                return Err(SessionError::Timeout);
849            }
850        }
851
852        #[cfg(feature = "tracing")]
853        trace!(len = reply.len(), "received APDU");
854
855        let response_tag = *reply.first().ok_or(crate::service::ServiceError::Truncated)?;
856        if response_tag == expected_response_tag {
857            return Ok(reply);
858        }
859        if let Some(c) = &mut self.cipher {
860            // A ciphered response: unprotect it with the inbound (server)
861            // context and expect the plain response tag.
862            let (_, plaintext) = ciphering::unprotect(&mut c.rx, &reply)?;
863            let plain_tag = *plaintext.first().ok_or(crate::service::ServiceError::Truncated)?;
864            if plain_tag == expected_response_tag {
865                return Ok(plaintext);
866            }
867            return Err(SessionError::UnexpectedApdu(plain_tag));
868        }
869        Err(SessionError::UnexpectedApdu(response_tag))
870    }
871}
872
873/// Checks if an I/O error is transient and worth retrying.
874fn is_transient_io(e: &io::Error) -> bool {
875    matches!(
876        e.kind(),
877        io::ErrorKind::WouldBlock
878            | io::ErrorKind::TimedOut
879            | io::ErrorKind::ConnectionReset
880            | io::ErrorKind::ConnectionAborted
881            | io::ErrorKind::Interrupted
882    )
883}
884
885#[cfg(test)]
886mod tests {
887    use super::*;
888    use crate::service::acse::{application_context, mechanism, result};
889    use crate::service::get::GetDataResult;
890    use crate::transport::wrapper::Wrapper;
891    use crate::transport::MemoryTransport;
892
893    /// A loopback data-link that echoes a fixed, pre-loaded response APDU for the
894    /// next `receive_apdu`, capturing what the client sent.
895    struct LoopLink {
896        wrapper: Wrapper<MemoryTransport>,
897        canned: std::collections::VecDeque<Vec<u8>>,
898        sent: Vec<Vec<u8>>,
899    }
900
901    impl LoopLink {
902        fn new() -> Self {
903            LoopLink {
904                wrapper: Wrapper::new(MemoryTransport::new(), 1, 16),
905                canned: Default::default(),
906                sent: Vec::new(),
907            }
908        }
909
910        fn queue_response(&mut self, apdu: Vec<u8>) {
911            self.canned.push_back(apdu);
912        }
913    }
914
915    impl DataLinkLayer for LoopLink {
916        fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()> {
917            self.sent.push(apdu.to_vec());
918            Ok(())
919        }
920
921        fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
922            // Round-trip the canned APDU through the real wrapper codec so the
923            // framing path is exercised.
924            let apdu = self.canned.pop_front().unwrap_or_default();
925            self.wrapper.send_apdu(&apdu)?;
926            self.wrapper.receive_apdu()
927        }
928    }
929
930    #[test]
931    fn associate_exchanges_aarq_aare() {
932        let mut link = LoopLink::new();
933        let aare = AssociationResponse {
934            application_context: application_context::LN,
935            result: result::ACCEPTED,
936            diagnostic: 0,
937            responding_ap_title: None,
938            responding_authentication_value: None,
939            user_information: vec![0x08, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x01, 0xF4, 0x00, 0x07],
940            ..Default::default()
941        };
942        link.queue_response(aare.encode());
943        let mut session = ClientSession::new(link);
944        let aarq = AssociationRequest {
945            application_context: application_context::LN,
946            calling_ap_title: None,
947            mechanism_name: Some(mechanism::LLS),
948            calling_authentication_value: Some(b"12345678".to_vec()),
949            user_information: vec![0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0],
950            ..Default::default()
951        };
952        let got = session.associate(&aarq).unwrap();
953        assert_eq!(got, aare);
954        // The AARQ was actually transmitted.
955        assert_eq!(session.into_inner().sent[0], aarq.encode());
956    }
957
958    #[test]
959    fn get_round_trips_plaintext() {
960        let mut link = LoopLink::new();
961        let response = GetResponse::Normal {
962            invoke_id_and_priority: 0xC1,
963            result: GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
964        };
965        link.queue_response(response.encode().unwrap());
966        let mut session = ClientSession::new(link);
967        let got = session.get(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2).unwrap();
968        assert_eq!(got, response);
969    }
970
971    #[test]
972    fn get_round_trips_with_ciphering() {
973        // A server context that will produce the ciphered GET-RESPONSE.
974        let policy = crate::security::SecurityPolicy::AuthenticationEncryption;
975        let suite = crate::security::SecuritySuite::Suite0;
976        let ek = vec![0x00; 16];
977        let ak = vec![0x11; 16];
978        let server_title = vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x01];
979        let client_title = vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E];
980
981        let response = GetResponse::Normal {
982            invoke_id_and_priority: 0xC1,
983            result: GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
984        };
985        let server_ctx =
986            SecurityContext::for_suite(policy, suite, ek.clone(), ak.clone(), server_title.clone(), 5).unwrap();
987        let ciphered_response =
988            ciphering::protect(&server_ctx, glo::GET_RESPONSE, &response.encode().unwrap()).unwrap();
989
990        let mut link = LoopLink::new();
991        link.queue_response(ciphered_response);
992        // Outbound context: client title/counter. Inbound context: server title.
993        let tx_ctx = SecurityContext::for_suite(policy, suite, ek.clone(), ak.clone(), client_title, 1).unwrap();
994        let rx_ctx = SecurityContext::for_suite(policy, suite, ek, ak, server_title, 5).unwrap();
995        let mut session = ClientSession::with_ciphering(link, tx_ctx, rx_ctx);
996        let got = session.get(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2).unwrap();
997        assert_eq!(got, response);
998
999        // The request went out ciphered (glo-get-request tag 0xC8) and the
1000        // counter advanced.
1001        let link = session.into_inner();
1002        assert_eq!(link.sent[0][0], glo::GET_REQUEST);
1003    }
1004
1005    // ========================================================================
1006    // Timeout and retry tests
1007    // ========================================================================
1008
1009    #[test]
1010    fn builder_configures_timeout_and_retries() {
1011        let link = LoopLink::new();
1012        let session = ClientSession::builder(link)
1013            .request_timeout(Duration::from_secs(5))
1014            .max_retries(3)
1015            .retry_delay(Duration::from_millis(50))
1016            .build();
1017
1018        assert_eq!(session.config().request_timeout, Some(Duration::from_secs(5)));
1019        assert_eq!(session.config().max_retries, 3);
1020        assert_eq!(session.config().retry_delay, Duration::from_millis(50));
1021    }
1022
1023    #[test]
1024    fn set_config_updates_session() {
1025        let link = LoopLink::new();
1026        let mut session = ClientSession::new(link);
1027
1028        session.set_request_timeout(Duration::from_secs(10));
1029        session.set_max_retries(5);
1030        session.set_retry_delay(Duration::from_millis(200));
1031
1032        assert_eq!(session.config().request_timeout, Some(Duration::from_secs(10)));
1033        assert_eq!(session.config().max_retries, 5);
1034        assert_eq!(session.config().retry_delay, Duration::from_millis(200));
1035    }
1036
1037    #[test]
1038    fn get_retries_on_transient_io_error() {
1039        use std::sync::{Arc, Mutex};
1040
1041        struct FailingLink {
1042            #[allow(dead_code)]
1043            wrapper: Wrapper<MemoryTransport>,
1044            fail_count: Arc<Mutex<u32>>,
1045            fail_until: u32,
1046        }
1047
1048        impl FailingLink {
1049            fn new(fail_until: u32) -> Self {
1050                FailingLink {
1051                    wrapper: Wrapper::new(MemoryTransport::new(), 1, 16),
1052                    fail_count: Arc::new(Mutex::new(0)),
1053                    fail_until,
1054                }
1055            }
1056        }
1057
1058        impl DataLinkLayer for FailingLink {
1059            fn send_apdu(&mut self, _apdu: &[u8]) -> io::Result<()> {
1060                Ok(())
1061            }
1062
1063            fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
1064                let mut count = self.fail_count.lock().unwrap();
1065                *count += 1;
1066                if *count <= self.fail_until {
1067                    return Err(io::Error::new(io::ErrorKind::ConnectionReset, "simulated failure"));
1068                }
1069                // Return a valid GET response
1070                let response = GetResponse::Normal {
1071                    invoke_id_and_priority: 0xC1,
1072                    result: GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
1073                };
1074                response.encode().map_err(|e| io::Error::other(e.to_string()))
1075            }
1076        }
1077
1078        let fail_until = 2;
1079        let link = FailingLink::new(fail_until);
1080
1081        let mut session = ClientSession::builder(link).max_retries(3).retry_delay(Duration::from_millis(10)).build();
1082
1083        let got = session.get(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2).unwrap();
1084        assert_eq!(
1085            got,
1086            GetResponse::Normal {
1087                invoke_id_and_priority: 0xC1,
1088                result: GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
1089            }
1090        );
1091    }
1092
1093    #[test]
1094    fn get_fails_after_max_retries() {
1095        struct AlwaysFailLink {
1096            #[allow(dead_code)]
1097            wrapper: Wrapper<MemoryTransport>,
1098        }
1099
1100        impl AlwaysFailLink {
1101            fn new() -> Self {
1102                AlwaysFailLink { wrapper: Wrapper::new(MemoryTransport::new(), 1, 16) }
1103            }
1104        }
1105
1106        impl DataLinkLayer for AlwaysFailLink {
1107            fn send_apdu(&mut self, _apdu: &[u8]) -> io::Result<()> {
1108                Ok(())
1109            }
1110
1111            fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
1112                Err(io::Error::new(io::ErrorKind::ConnectionReset, "always fails"))
1113            }
1114        }
1115
1116        let link = AlwaysFailLink::new();
1117        let mut session = ClientSession::builder(link).max_retries(2).retry_delay(Duration::from_millis(10)).build();
1118
1119        let result = session.get(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2);
1120        assert!(result.is_err());
1121        match result.unwrap_err() {
1122            SessionError::Io(e) => assert_eq!(e.kind(), io::ErrorKind::ConnectionReset),
1123            other => panic!("expected Io error, got: {other:?}"),
1124        }
1125    }
1126
1127    #[test]
1128    fn default_config_has_no_retries() {
1129        let link = LoopLink::new();
1130        let session = ClientSession::new(link);
1131        assert_eq!(session.config().max_retries, 0);
1132        assert_eq!(session.config().request_timeout, None);
1133    }
1134
1135    #[test]
1136    fn session_error_display() {
1137        assert_eq!(SessionError::Timeout.to_string(), "request timed out");
1138        assert_eq!(SessionError::MaxRetries(5).to_string(), "maximum retries (5) exceeded");
1139    }
1140
1141    // ========================================================================
1142    // AARQ/AARE tests
1143    // ========================================================================
1144
1145    #[test]
1146    fn aarq_builder_creates_valid_aarq() {
1147        let aarq = AarqBuilder::new()
1148            .application_context(acse::application_context::LN)
1149            .mechanism(acse::mechanism::LLS)
1150            .authentication_value(b"password".to_vec())
1151            .user_information(vec![0x01, 0x00])
1152            .build();
1153
1154        assert_eq!(aarq.application_context, acse::application_context::LN);
1155        assert_eq!(aarq.mechanism_name, Some(acse::mechanism::LLS));
1156        assert_eq!(aarq.calling_authentication_value, Some(b"password".to_vec()));
1157        assert_eq!(aarq.user_information, vec![0x01, 0x00]);
1158    }
1159
1160    #[test]
1161    fn aarq_builder_default_is_ln_no_security() {
1162        let aarq = AarqBuilder::new().build();
1163        assert_eq!(aarq.application_context, acse::application_context::LN);
1164        assert_eq!(aarq.mechanism_name, None);
1165        assert_eq!(aarq.calling_ap_title, None);
1166    }
1167
1168    #[test]
1169    fn aarq_builder_with_ciphering() {
1170        let aarq = AarqBuilder::new()
1171            .application_context(acse::application_context::LN_CIPHERING)
1172            .calling_ap_title(vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x01])
1173            .mechanism(acse::mechanism::HLS_GMAC)
1174            .user_information(vec![0x01])
1175            .build();
1176
1177        assert_eq!(aarq.application_context, acse::application_context::LN_CIPHERING);
1178        assert!(aarq.calling_ap_title.is_some());
1179        assert_eq!(aarq.mechanism_name, Some(acse::mechanism::HLS_GMAC));
1180    }
1181
1182    #[test]
1183    fn associate_updates_state() {
1184        let mut link = LoopLink::new();
1185        let aare = AssociationResponse {
1186            application_context: acse::application_context::LN,
1187            result: acse::result::ACCEPTED,
1188            diagnostic: 0,
1189            responding_ap_title: None,
1190            responding_authentication_value: None,
1191            user_information: vec![],
1192            ..Default::default()
1193        };
1194        link.queue_response(aare.encode());
1195
1196        let mut session = ClientSession::new(link);
1197        assert_eq!(session.state(), AssociationState::Idle);
1198        assert!(!session.is_associated());
1199
1200        let aarq = AssociationRequest {
1201            application_context: acse::application_context::LN,
1202            calling_ap_title: None,
1203            mechanism_name: None,
1204            calling_authentication_value: None,
1205            user_information: vec![],
1206            ..Default::default()
1207        };
1208        let resp = session.associate(&aarq).unwrap();
1209        assert_eq!(resp.result, acse::result::ACCEPTED);
1210        assert_eq!(session.state(), AssociationState::Associated);
1211        assert!(session.is_associated());
1212        assert_eq!(session.application_context(), acse::application_context::LN);
1213    }
1214
1215    #[test]
1216    fn associate_rejected_sets_idle() {
1217        let mut link = LoopLink::new();
1218        let aare = AssociationResponse {
1219            application_context: acse::application_context::LN,
1220            result: acse::result::REJECTED_PERMANENT,
1221            diagnostic: 1,
1222            responding_ap_title: None,
1223            responding_authentication_value: None,
1224            user_information: vec![],
1225            ..Default::default()
1226        };
1227        link.queue_response(aare.encode());
1228
1229        let mut session = ClientSession::new(link);
1230        let aarq = AssociationRequest {
1231            application_context: acse::application_context::LN,
1232            calling_ap_title: None,
1233            mechanism_name: None,
1234            calling_authentication_value: None,
1235            user_information: vec![],
1236            ..Default::default()
1237        };
1238        let resp = session.associate(&aarq).unwrap();
1239        assert_eq!(resp.result, acse::result::REJECTED_PERMANENT);
1240        assert_eq!(session.state(), AssociationState::Idle);
1241        assert!(!session.is_associated());
1242    }
1243
1244    #[test]
1245    fn associate_no_security_convenience() {
1246        let mut link = LoopLink::new();
1247        let aare = AssociationResponse {
1248            application_context: acse::application_context::LN,
1249            result: acse::result::ACCEPTED,
1250            diagnostic: 0,
1251            responding_ap_title: None,
1252            responding_authentication_value: None,
1253            user_information: vec![],
1254            ..Default::default()
1255        };
1256        link.queue_response(aare.encode());
1257
1258        let mut session = ClientSession::new(link);
1259        let resp = session.associate_no_security(vec![0x01, 0x00]).unwrap();
1260        assert_eq!(resp.result, acse::result::ACCEPTED);
1261        assert!(session.is_associated());
1262        assert_eq!(session.mechanism(), None);
1263    }
1264
1265    #[test]
1266    fn associate_lls_convenience() {
1267        let mut link = LoopLink::new();
1268        let aare = AssociationResponse {
1269            application_context: acse::application_context::LN,
1270            result: acse::result::ACCEPTED,
1271            diagnostic: 0,
1272            responding_ap_title: None,
1273            responding_authentication_value: None,
1274            user_information: vec![],
1275            ..Default::default()
1276        };
1277        link.queue_response(aare.encode());
1278
1279        let mut session = ClientSession::new(link);
1280        let resp = session.associate_lls(b"12345678".to_vec(), vec![0x01, 0x00]).unwrap();
1281        assert_eq!(resp.result, acse::result::ACCEPTED);
1282        assert!(session.is_associated());
1283        assert_eq!(session.mechanism(), Some(acse::mechanism::LLS));
1284    }
1285
1286    #[test]
1287    fn release_resets_state() {
1288        let mut link = LoopLink::new();
1289        let aare = AssociationResponse {
1290            application_context: acse::application_context::LN,
1291            result: acse::result::ACCEPTED,
1292            diagnostic: 0,
1293            responding_ap_title: None,
1294            responding_authentication_value: None,
1295            user_information: vec![],
1296            ..Default::default()
1297        };
1298        link.queue_response(aare.encode());
1299        // Queue RLRE response
1300        let rlre = ReleaseRequest { reason: Some(acse::release_reason::NORMAL), user_information: None };
1301        link.queue_response(rlre.encode_rlre());
1302
1303        let mut session = ClientSession::new(link);
1304        let aarq = AssociationRequest {
1305            application_context: acse::application_context::LN,
1306            calling_ap_title: None,
1307            mechanism_name: None,
1308            calling_authentication_value: None,
1309            user_information: vec![],
1310            ..Default::default()
1311        };
1312        session.associate(&aarq).unwrap();
1313        assert!(session.is_associated());
1314
1315        session.release_normal().unwrap();
1316        assert_eq!(session.state(), AssociationState::Idle);
1317        assert!(!session.is_associated());
1318    }
1319
1320    #[test]
1321    fn release_normal_convenience() {
1322        let mut link = LoopLink::new();
1323        let rlre = ReleaseRequest { reason: Some(acse::release_reason::NORMAL), user_information: None };
1324        link.queue_response(rlre.encode_rlre());
1325
1326        let mut session = ClientSession::new(link);
1327        let resp = session.release_normal().unwrap();
1328        assert_eq!(resp.reason, Some(acse::release_reason::NORMAL));
1329    }
1330
1331    #[test]
1332    fn aarq_builder_encodes_correctly() {
1333        let aarq = AarqBuilder::new().mechanism(acse::mechanism::LLS).authentication_value(b"test".to_vec()).build();
1334        let encoded = aarq.encode();
1335        // Should be a valid AARQ APDU
1336        assert_eq!(encoded[0], acse::AARQ_TAG);
1337        // Should decode back correctly
1338        let decoded = AssociationRequest::decode(&encoded).unwrap();
1339        assert_eq!(decoded.mechanism_name, Some(acse::mechanism::LLS));
1340        assert_eq!(decoded.calling_authentication_value, Some(b"test".to_vec()));
1341    }
1342
1343    // ========================================================================
1344    // Raw APDU tests
1345    // ========================================================================
1346
1347    #[test]
1348    fn raw_apdu_encode_decode_round_trip() {
1349        let raw = RawApdu::new(0xC0, vec![0x01, 0x02, 0x03]);
1350        let encoded = raw.encode();
1351        let decoded = RawApdu::from_bytes(&encoded).unwrap();
1352        assert_eq!(decoded.tag(), 0xC0);
1353        assert_eq!(decoded.body(), &[0x01, 0x02, 0x03]);
1354    }
1355
1356    #[test]
1357    fn raw_apdu_from_bytes_round_trip() {
1358        let bytes = vec![0xC1, 0x04, 0x01, 0x02, 0x03, 0x04];
1359        let raw = RawApdu::from_bytes(&bytes).unwrap();
1360        assert_eq!(raw.tag(), 0xC1);
1361        assert_eq!(raw.body(), &[0x01, 0x02, 0x03, 0x04]);
1362        assert_eq!(raw.encode(), bytes);
1363    }
1364
1365    #[test]
1366    fn raw_apdu_empty_body() {
1367        let raw = RawApdu::new(0xC2, vec![]);
1368        let encoded = raw.encode();
1369        assert_eq!(encoded, vec![0xC2, 0x00]);
1370        let decoded = RawApdu::from_bytes(&encoded).unwrap();
1371        assert_eq!(decoded.body().len(), 0);
1372    }
1373
1374    #[test]
1375    fn raw_apdu_large_body() {
1376        let body = vec![0xAA; 256];
1377        let raw = RawApdu::new(0xC3, body.clone());
1378        let encoded = raw.encode();
1379        let decoded = RawApdu::from_bytes(&encoded).unwrap();
1380        assert_eq!(decoded.body(), &body);
1381    }
1382
1383    #[test]
1384    fn raw_apdu_into_parts() {
1385        let raw = RawApdu::new(0xC4, vec![0x01, 0x02]);
1386        let (tag, body) = raw.into_parts();
1387        assert_eq!(tag, 0xC4);
1388        assert_eq!(body, vec![0x01, 0x02]);
1389    }
1390
1391    #[test]
1392    fn send_raw_round_trip() {
1393        let mut link = LoopLink::new();
1394        let response = RawApdu::new(0xC4, vec![0x08, 0x00, 0x06]);
1395        link.queue_response(response.encode());
1396
1397        let mut session = ClientSession::new(link);
1398        let request = RawApdu::new(0xC0, vec![0xC1, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02]);
1399        let reply = session.send_raw(&request).unwrap();
1400        assert_eq!(reply.tag(), 0xC4);
1401        assert_eq!(reply.body(), &[0x08, 0x00, 0x06]);
1402    }
1403
1404    #[test]
1405    fn send_raw_bytes_round_trip() {
1406        let mut link = LoopLink::new();
1407        link.queue_response(vec![0xC4, 0x03, 0x08, 0x00, 0x06]);
1408
1409        let mut session = ClientSession::new(link);
1410        let request = vec![0xC0, 0x09, 0xC1, 0x01, 0x00, 0x00, 0x80, 0x00, 0x00, 0xFF, 0x02];
1411        let reply = session.send_raw_bytes(&request).unwrap();
1412        assert_eq!(reply, vec![0xC4, 0x03, 0x08, 0x00, 0x06]);
1413    }
1414
1415    #[test]
1416    fn make_raw_apdu_helper() {
1417        let raw = ClientSession::<LoopLink>::make_raw_apdu(0xC0, vec![0x01]);
1418        assert_eq!(raw.tag(), 0xC0);
1419        assert_eq!(raw.body(), &[0x01]);
1420    }
1421}