Skip to main content

spodes_rs/
server.rs

1//! A server-side request dispatcher (IEC 62056-5-3 / IEC 62056-53 server CF).
2//!
3//! [`crate::server::RequestDispatcher`] holds a set of COSEM interface objects and turns an
4//! incoming GET / SET / ACTION request APDU into the matching response APDU by
5//! routing it to the addressed object: GET reads an attribute, SET writes one
6//! (via [`crate::interface::InterfaceClass::set_attribute`]), ACTION invokes a method. Objects are
7//! addressed by their (class-id, logical-name) pair; an unknown address yields a
8//! `object-undefined` data-access-result rather than an error.
9//!
10//! Only the NORMAL and WITH-LIST variants are dispatched; block-transfer request
11//! types produce an EXCEPTION-RESPONSE, since block reassembly is the caller's
12//! responsibility.
13
14use crate::classes::association_ln::AssociationLn;
15use crate::interface::InterfaceClass;
16use crate::obis::ObisCode;
17use crate::security::AuthMechanism;
18
19use crate::classes::push_setup::{PushDeliveryRequest, PushSetup};
20use crate::service::acse::{self, AssociationResponse};
21use crate::service::action::{ActionRequest, ActionResponse};
22use crate::service::error::{service_error, state_error, ConfirmedServiceError, ExceptionResponse};
23use crate::service::get::{GetDataResult, GetRequest, GetResponse};
24use crate::service::initiate::{InitiateRequest, InitiateResponse};
25use crate::service::notification::DataNotification;
26use crate::service::set::{SetRequest, SetResponse};
27use crate::service::{data_access_result, tag, AttributeDescriptor, DataBlockSa, MethodDescriptor, ServiceError};
28use crate::types::CosemDataType;
29#[cfg(feature = "tracing")]
30use tracing::{debug, warn};
31
32/// Default block-transfer payload size. A GET result larger than this is sent in
33/// GET-RESPONSE-WITH-DATABLOCK blocks of at most this many octets.
34const DEFAULT_MAX_PDU: usize = 256;
35
36/// The DLMS version number negotiated by [`RequestDispatcher::handle_aarq`].
37const DLMS_VERSION: u8 = 6;
38
39/// The smallest client-max-receive-pdu-size the server accepts.
40const MIN_CLIENT_PDU: u16 = 12;
41
42/// Server-max-receive-pdu-size offered in the negotiated InitiateResponse.
43const SERVER_MAX_PDU: u16 = 0x0800;
44
45/// SPODES AA role conformance (AND with the client's proposal):
46/// - Public (LOWEST): get + block-get
47/// - Reader (LLS): + selective + action
48/// - Configurator (HLS): + set + block-set + data-notification (+ general-protection)
49const CONFORMANCE_PUBLIC: u32 = 0x00_10_10;
50const CONFORMANCE_READER: u32 = 0x00_10_15;
51const CONFORMANCE_CONFIGURATOR: u32 = 0x40_18_9D;
52
53/// `association_status` values (IEC 62056-6-2, Association LN attribute 8).
54mod association_status {
55    /// No association is open.
56    pub const NON_ASSOCIATED: u8 = 0;
57    /// The HLS handshake is still in progress (pass 3/4 pending).
58    pub const ASSOCIATION_PENDING: u8 = 1;
59    /// The association is open.
60    pub const ASSOCIATED: u8 = 2;
61}
62
63/// `initiateError` values of the ConfirmedServiceError sent when the
64/// InitiateRequest is rejected (IEC 62056-5-3).
65mod initiate_error {
66    /// The proposed DLMS version is lower than 6.
67    pub const DLMS_VERSION_TOO_LOW: u8 = 1;
68    /// The proposed conformance has no supported service in common.
69    pub const INCOMPATIBLE_CONFORMANCE: u8 = 2;
70    /// The proposed client PDU size is too small.
71    pub const PDU_SIZE_TOO_SHORT: u8 = 3;
72}
73
74/// An outbound GET result being delivered in blocks.
75#[derive(Debug, Clone)]
76pub struct PendingGet {
77    /// The serialized data awaiting block-by-block delivery.
78    pub data: Vec<u8>,
79    /// The block number of the next block to send.
80    pub next_block: u32,
81}
82
83/// An inbound SET value being reassembled from datablocks.
84#[derive(Debug, Clone)]
85pub struct PendingSet {
86    /// Target attribute of the in-progress SET.
87    pub attribute: AttributeDescriptor,
88    /// The accumulated A-XDR value bytes.
89    pub buffer: Vec<u8>,
90}
91
92/// Block-transfer state that must survive across APDUs on the same AA.
93///
94/// Hosts that rebuild a [`RequestDispatcher`] per request (e.g. from a shared
95/// object registry) should stash this on the connection and restore it before
96/// each `dispatch`.
97#[derive(Debug, Default, Clone)]
98pub struct PendingBlocks {
99    /// Outstanding GET datablock delivery, if any.
100    pub get: Option<PendingGet>,
101    /// Outstanding SET datablock reassembly, if any.
102    pub set: Option<PendingSet>,
103}
104
105/// A collection of COSEM objects that answers GET/SET/ACTION requests.
106pub struct RequestDispatcher {
107    objects: Vec<Box<dyn InterfaceClass>>,
108    max_pdu: usize,
109    pending_get: Option<PendingGet>,
110    pending_set: Option<PendingSet>,
111    /// Current association for access rights checking (IEC 62056-5-3, 5.3.7).
112    /// When set, GET/SET/ACTION are checked against the association's object_list.
113    association: Option<AssociationLn>,
114}
115
116impl Default for RequestDispatcher {
117    fn default() -> Self {
118        Self::new()
119    }
120}
121
122impl RequestDispatcher {
123    /// Creates an empty dispatcher with the default block size.
124    pub fn new() -> Self {
125        RequestDispatcher {
126            objects: Vec::new(),
127            max_pdu: DEFAULT_MAX_PDU,
128            pending_get: None,
129            pending_set: None,
130            association: None,
131        }
132    }
133
134    /// Sets the maximum block-transfer payload size (octets). Results larger
135    /// than this are delivered in GET-RESPONSE-WITH-DATABLOCK blocks.
136    pub fn set_max_pdu(&mut self, max_pdu: usize) {
137        self.max_pdu = max_pdu.max(1);
138    }
139
140    /// Registers an object.
141    pub fn add(&mut self, object: Box<dyn InterfaceClass>) {
142        #[cfg(feature = "tracing")]
143        debug!(
144            class_id = object.class_id(),
145            logical_name = %object.logical_name(),
146            "registering COSEM object"
147        );
148        self.objects.push(object);
149    }
150
151    /// Sets the current association for access rights checking.
152    /// When an association is set, all GET/SET/ACTION requests are checked
153    /// against the association's object_list access_rights.
154    pub fn set_association(&mut self, assoc: AssociationLn) {
155        #[cfg(feature = "tracing")]
156        debug!("setting association for access rights checking");
157        self.association = Some(assoc);
158    }
159
160    /// Restores block-transfer state previously taken with [`Self::take_pending`].
161    pub fn restore_pending(&mut self, pending: PendingBlocks) {
162        self.pending_get = pending.get;
163        self.pending_set = pending.set;
164    }
165
166    /// Takes block-transfer state so the host can persist it across requests.
167    pub fn take_pending(&mut self) -> PendingBlocks {
168        PendingBlocks { get: self.pending_get.take(), set: self.pending_set.take() }
169    }
170
171    /// Returns a reference to the current association, if any.
172    pub fn association(&self) -> Option<&AssociationLn> {
173        self.association.as_ref()
174    }
175
176    /// Returns a mutable reference to the current association, if any.
177    pub fn association_mut(&mut self) -> Option<&mut AssociationLn> {
178        self.association.as_mut()
179    }
180
181    /// Assembles a [`PushDeliveryRequest`] for `push_setup`'s ACTION method 1
182    /// (`push`): reads each object in `push_object_list` from this
183    /// dispatcher's registry, wraps the values in a DataNotification
184    /// (an Array when more than one object is listed), and pairs it with the
185    /// destination and client SAP from `push_setup`.
186    ///
187    /// Mirrors the reference implementation's `push_build_notification_body` /
188    /// `push_try_schedule_delivery`: the host is expected to call this from
189    /// the `push` ACTION handler (this dispatcher owns the object registry
190    /// that `PushSetup` itself does not hold) and then deliver `body` over the
191    /// configured transport.
192    pub fn build_push_delivery_request(
193        &mut self,
194        push_setup: &PushSetup,
195        long_invoke_id_and_priority: u32,
196    ) -> Result<PushDeliveryRequest, String> {
197        let objects = push_setup.push_object_list();
198        if objects.is_empty() {
199            return Err("No push objects configured".to_string());
200        }
201        let mut values = Vec::with_capacity(objects.len());
202        for entry in objects {
203            let obj = self
204                .find(entry.class_id, &entry.logical_name)
205                .ok_or_else(|| format!("Push object {} (class {}) not found", entry.logical_name, entry.class_id))?;
206            let value = obj
207                .attributes()
208                .into_iter()
209                .find(|(id, _)| *id == entry.attribute_index)
210                .map(|(_, v)| v)
211                .ok_or_else(|| format!("Push object has no attribute {}", entry.attribute_index))?;
212            values.push(value);
213        }
214        let body = if values.len() == 1 { values.remove(0) } else { CosemDataType::Array(values) };
215        let notification =
216            DataNotification { long_invoke_id_and_priority, date_time: Vec::new(), notification_body: body };
217        let encoded = notification.encode().map_err(|e| format!("Failed to encode push body: {e:?}"))?;
218        let destination = push_setup.send_destination_and_method();
219        Ok(PushDeliveryRequest {
220            destination: destination.destination.clone(),
221            transport_service: destination.transport_service,
222            client_sap: push_setup.push_client_sap(),
223            body: encoded,
224        })
225    }
226
227    /// Locates a registered object by class-id and logical name.
228    fn find(&mut self, class_id: u16, instance: &ObisCode) -> Option<&mut Box<dyn InterfaceClass>> {
229        self.objects.iter_mut().find(|o| o.class_id() == class_id && o.logical_name() == instance)
230    }
231
232    /// Checks whether a read is allowed for the given object and attribute.
233    /// Returns true if no association is set (unrestricted access).
234    fn check_read(&self, class_id: u16, instance: &ObisCode, attribute_id: i8) -> bool {
235        // No association — unrestricted.
236        self.association.as_ref().is_none_or(|assoc| assoc.can_read(class_id, instance, attribute_id))
237    }
238
239    /// Checks whether a write is allowed for the given object and attribute.
240    /// Returns true if no association is set (unrestricted access).
241    fn check_write(&self, class_id: u16, instance: &ObisCode, attribute_id: i8) -> bool {
242        // No association — unrestricted.
243        self.association.as_ref().is_none_or(|assoc| assoc.can_write(class_id, instance, attribute_id))
244    }
245
246    /// Checks whether a method invocation is allowed.
247    /// Returns true if no association is set (unrestricted access).
248    fn check_invoke(&self, class_id: u16, instance: &ObisCode, method_id: i8) -> bool {
249        // No association — unrestricted.
250        self.association.as_ref().is_none_or(|assoc| assoc.can_invoke(class_id, instance, method_id))
251    }
252
253    /// Reads one attribute, returning its value or a data-access-result code.
254    /// Checks access rights from the current association's object_list.
255    fn read_attribute(&mut self, d: &AttributeDescriptor) -> GetDataResult {
256        let attr_id = d.attribute_id;
257        // Check access rights first.
258        if !self.check_read(d.class_id, &d.instance_id, attr_id) {
259            #[cfg(feature = "tracing")]
260            warn!(
261                class_id = d.class_id,
262                instance = %d.instance_id,
263                attr_id,
264                "GET denied by access rights"
265            );
266            return GetDataResult::AccessResult(data_access_result::READ_WRITE_DENIED);
267        }
268        self.find(d.class_id, &d.instance_id).map_or_else(
269            || {
270                #[cfg(feature = "tracing")]
271                debug!(
272                    class_id = d.class_id,
273                    instance = %d.instance_id,
274                    attr_id,
275                    "GET: object undefined"
276                );
277                GetDataResult::AccessResult(data_access_result::OBJECT_UNDEFINED)
278            },
279            // Attribute ids are always <128 in practice (i8-valued on the wire).
280            #[allow(clippy::cast_possible_wrap)]
281            |obj| match obj.attributes().into_iter().find(|(id, _)| *id as i8 == attr_id) {
282                Some((_, value)) => {
283                    #[cfg(feature = "tracing")]
284                    debug!(
285                        class_id = d.class_id,
286                        instance = %d.instance_id,
287                        attr_id,
288                        "GET: success"
289                    );
290                    GetDataResult::Data(value)
291                }
292                None => GetDataResult::AccessResult(data_access_result::OBJECT_UNAVAILABLE),
293            },
294        )
295    }
296
297    /// Writes one attribute, returning a data-access-result code.
298    /// Checks access rights from the current association's object_list.
299    fn write_attribute(&mut self, d: &AttributeDescriptor, value: crate::types::CosemDataType) -> u8 {
300        // Check access rights first.
301        if !self.check_write(d.class_id, &d.instance_id, d.attribute_id) {
302            #[cfg(feature = "tracing")]
303            warn!(
304                class_id = d.class_id,
305                instance = %d.instance_id,
306                attr_id = d.attribute_id,
307                "SET denied by access rights"
308            );
309            return data_access_result::READ_WRITE_DENIED;
310        }
311        self.find(d.class_id, &d.instance_id).map_or_else(
312            || {
313                #[cfg(feature = "tracing")]
314                debug!(
315                    class_id = d.class_id,
316                    instance = %d.instance_id,
317                    attr_id = d.attribute_id,
318                    "SET: object undefined"
319                );
320                data_access_result::OBJECT_UNDEFINED
321            },
322            |obj| {
323                // Attribute ids are always <128 in practice (i8-valued on the wire).
324                #[allow(clippy::cast_sign_loss)]
325                let attribute_id = d.attribute_id as u8;
326                match obj.set_attribute(attribute_id, value) {
327                    Ok(()) => {
328                        #[cfg(feature = "tracing")]
329                        debug!(
330                            class_id = d.class_id,
331                            instance = %d.instance_id,
332                            attr_id = d.attribute_id,
333                            "SET: success"
334                        );
335                        data_access_result::SUCCESS
336                    }
337                    Err(_) => data_access_result::READ_WRITE_DENIED,
338                }
339            },
340        )
341    }
342
343    /// Invokes one method, returning the action-result and optional return data.
344    /// Checks method access rights from the current association's object_list.
345    fn invoke(
346        &mut self,
347        d: &MethodDescriptor,
348        params: Option<crate::types::CosemDataType>,
349    ) -> (u8, Option<GetDataResult>) {
350        // Check method access rights first.
351        if !self.check_invoke(d.class_id, &d.instance_id, d.method_id) {
352            #[cfg(feature = "tracing")]
353            warn!(
354                class_id = d.class_id,
355                instance = %d.instance_id,
356                method_id = d.method_id,
357                "ACTION denied by access rights"
358            );
359            return (data_access_result::READ_WRITE_DENIED, None);
360        }
361        // HLS reply_to_authentication and other Association LN methods must hit
362        // the live association state, not a cloned registry object.
363        let routed_to_assoc = d.class_id == 15
364            && self.association.is_some()
365            && (d.instance_id == ObisCode::new(0, 0, 40, 0, 0, 255)
366                || self.association.as_ref().is_some_and(|assoc| assoc.logical_name() == &d.instance_id));
367        if routed_to_assoc {
368            // Method ids are always <128 in practice (i8-valued on the wire).
369            #[allow(clippy::cast_sign_loss)]
370            let method_id = d.method_id as u8;
371            return match self.association.as_mut().expect("association routing").invoke_method(method_id, params) {
372                Ok(crate::types::CosemDataType::Null) => (data_access_result::SUCCESS, None),
373                Ok(value) => (data_access_result::SUCCESS, Some(GetDataResult::Data(value))),
374                Err(_) => (data_access_result::OTHER_REASON, None),
375            };
376        }
377        self.find(d.class_id, &d.instance_id).map_or_else(
378            || {
379                #[cfg(feature = "tracing")]
380                debug!(
381                    class_id = d.class_id,
382                    instance = %d.instance_id,
383                    method_id = d.method_id,
384                    "ACTION: object undefined"
385                );
386                (data_access_result::OBJECT_UNDEFINED, None)
387            },
388            |obj| {
389                // Method ids are always <128 in practice (i8-valued on the wire).
390                #[allow(clippy::cast_sign_loss)]
391                let method_id = d.method_id as u8;
392                match obj.invoke_method(method_id, params) {
393                    Ok(crate::types::CosemDataType::Null) => {
394                        #[cfg(feature = "tracing")]
395                        debug!(
396                            class_id = d.class_id,
397                            instance = %d.instance_id,
398                            method_id = d.method_id,
399                            "ACTION: success"
400                        );
401                        (data_access_result::SUCCESS, None)
402                    }
403                    Ok(value) => {
404                        #[cfg(feature = "tracing")]
405                        debug!(
406                            class_id = d.class_id,
407                            instance = %d.instance_id,
408                            method_id = d.method_id,
409                            "ACTION: success (with return value)"
410                        );
411                        (data_access_result::SUCCESS, Some(GetDataResult::Data(value)))
412                    }
413                    Err(_) => {
414                        #[cfg(feature = "tracing")]
415                        warn!(
416                            class_id = d.class_id,
417                            instance = %d.instance_id,
418                            method_id = d.method_id,
419                            "ACTION: method returned error"
420                        );
421                        (data_access_result::OTHER_REASON, None)
422                    }
423                }
424            },
425        )
426    }
427
428    /// Dispatches one request APDU to the addressed object and returns the
429    /// encoded response APDU. Malformed or unsupported requests yield an
430    /// EXCEPTION-RESPONSE. An AARQ is answered with an AARE via
431    /// [`Self::handle_aarq`].
432    pub fn dispatch(&mut self, request: &[u8]) -> Result<Vec<u8>, ServiceError> {
433        match request.first() {
434            Some(&acse::AARQ_TAG) => Ok(self.handle_aarq(request)),
435            Some(&acse::RLRQ_TAG) => Ok(self.handle_rlrq(request)),
436            Some(&tag) => {
437                if !self.xdlms_services_allowed(request) {
438                    return Ok(not_possible());
439                }
440                match tag {
441                    tag::GET_REQUEST => self.dispatch_get(request),
442                    tag::SET_REQUEST => Ok(self.dispatch_set(request)),
443                    tag::ACTION_REQUEST => self.dispatch_action(request),
444                    other => Ok(unsupported(other)),
445                }
446            }
447            None => Err(ServiceError::Truncated),
448        }
449    }
450
451    /// xDLMS GET/SET/ACTION are allowed only when associated. While HLS is
452    /// pending, only `reply_to_HLS_authentication` (Association LN method 1)
453    /// is accepted — everything else yields EXCEPTION-RESPONSE (C++
454    /// `hls_pending` gate / Yellow Book APPL_OPEN HLS pass 3).
455    fn xdlms_services_allowed(&self, request: &[u8]) -> bool {
456        match self.association.as_ref().map(AssociationLn::association_status) {
457            None | Some(association_status::ASSOCIATED) => true,
458            Some(association_status::ASSOCIATION_PENDING) => is_hls_pass3_action(request),
459            Some(_) => false,
460        }
461    }
462
463    /// Validates an AARQ against the configured association and answers with an
464    /// AARE carrying a structured ACSE diagnostic (IEC 62056-5-3 §7.3.5):
465    ///
466    /// * unsupported application context → `application-context-name-not-supported`;
467    /// * ciphering / title-bound HLS without an 8-octet calling-AP-title →
468    ///   `calling-AP-title-not-recognized`;
469    /// * bad InitiateRequest parameters → `initiateError` ConfirmedServiceError
470    ///   in the user-information (DLMS version / conformance / PDU size);
471    /// * missing, unknown, or mismatching authentication →
472    ///   `authentication-required` / `-mechanism-name-not-recognised` /
473    ///   `authentication-failure`;
474    /// * LLS: the calling-authentication-value is compared with the
475    ///   association's secret;
476    /// * HLS: the CtoS challenge is stored, a random StoC is generated and
477    ///   returned, and the association is left `association-pending` until the
478    ///   `reply_to_HLS_authentication` ACTION (pass 3/4) completes.
479    ///
480    /// Requires an association to be configured via [`Self::set_association`];
481    /// without one, only mechanism 0 (lowest) AARQs are accepted.
482    pub fn handle_aarq(&mut self, request: &[u8]) -> Vec<u8> {
483        use crate::service::acse::{
484            acse_diagnostic as diag, acse_provider_diagnostic as pdiag, application_context, AssociationRequest,
485            PROTOCOL_VERSION_1,
486        };
487
488        // Fresh AARQ clears any prior AA (C++ resets associated/hls_pending).
489        if let Some(assoc) = self.association.as_mut() {
490            assoc.set_association_status(association_status::NON_ASSOCIATED);
491        }
492
493        let Ok(aarq) = AssociationRequest::decode(request) else {
494            return reject_aare(application_context::LN, diag::NULL, false, None);
495        };
496        let echo_context = aarq.application_context;
497
498        // Application context: LN with or without ciphering.
499        if aarq.application_context != application_context::LN
500            && aarq.application_context != application_context::LN_CIPHERING
501        {
502            return reject_aare(application_context::LN, diag::APPLICATION_CONTEXT_NAME_NOT_SUPPORTED, false, None);
503        }
504
505        // Protocol-version must be absent or {version1} (`02 84`).
506        if let Some(pv) = aarq.protocol_version {
507            if pv != PROTOCOL_VERSION_1 {
508                return reject_aare(echo_context, pdiag::NO_COMMON_ACSE_VERSION, true, None);
509            }
510        }
511
512        // Ciphering and title-bound HLS mechanisms require an 8-octet client
513        // system title in the calling-AP-title.
514        let mech_id = aarq.mechanism_name.unwrap_or(0);
515        let title_bound = aarq.application_context == application_context::LN_CIPHERING || mech_id >= 5;
516        if title_bound && aarq.calling_ap_title.as_ref().map(Vec::len) != Some(8) {
517            return reject_aare(echo_context, diag::CALLING_AP_TITLE_NOT_RECOGNIZED, false, None);
518        }
519
520        // Validate the xDLMS InitiateRequest, when present and well-formed.
521        let initiate = InitiateRequest::decode(&aarq.user_information).ok();
522        if let Some(ireq) = &initiate {
523            let err = if ireq.proposed_dlms_version != 0 && ireq.proposed_dlms_version < DLMS_VERSION {
524                Some(initiate_error::DLMS_VERSION_TOO_LOW)
525            } else if ireq.proposed_conformance == 0 {
526                Some(initiate_error::INCOMPATIBLE_CONFORMANCE)
527            } else if ireq.client_max_receive_pdu_size > 0 && ireq.client_max_receive_pdu_size < MIN_CLIENT_PDU {
528                Some(initiate_error::PDU_SIZE_TOO_SHORT)
529            } else {
530                None
531            };
532            if let Some(value) = err {
533                return reject_aare(echo_context, diag::NULL, false, Some(value));
534            }
535        }
536
537        // Authentication, against the configured association (C++ `aarq_validate` order).
538        let required = self.association.as_ref().map(|a| a.authentication_mechanism()).unwrap_or(AuthMechanism::None);
539        if required != AuthMechanism::None {
540            let has_mech = aarq.mechanism_name.is_some();
541            let has_auth = aarq.calling_authentication_value.is_some();
542            if !has_mech && !has_auth {
543                return reject_aare(echo_context, diag::AUTHENTICATION_REQUIRED, false, None);
544            }
545            if let Some(bits) = aarq.sender_acse_requirements {
546                if bits != 0x80 {
547                    return reject_aare(echo_context, diag::AUTHENTICATION_FAILURE, false, None);
548                }
549            }
550            if !has_mech {
551                return reject_aare(echo_context, diag::AUTHENTICATION_FAILURE, false, None);
552            }
553            let Some(mech) = aarq.mechanism_name.and_then(AuthMechanism::from_id) else {
554                return reject_aare(echo_context, diag::AUTHENTICATION_MECHANISM_NAME_NOT_RECOGNISED, false, None);
555            };
556            if !has_auth && mech != AuthMechanism::None {
557                return reject_aare(echo_context, diag::AUTHENTICATION_FAILURE, false, None);
558            }
559            if !Self::aarq_mechanism_matches_assoc(mech, required) {
560                return reject_aare(echo_context, diag::AUTHENTICATION_FAILURE, false, None);
561            }
562        }
563
564        let mechanism = aarq.mechanism_name.and_then(AuthMechanism::from_id).unwrap_or(AuthMechanism::None);
565        let user_information = Self::negotiate_initiate_response(initiate.as_ref(), mechanism);
566        match mechanism {
567            AuthMechanism::None => {
568                if let Some(assoc) = self.association.as_mut() {
569                    assoc.set_association_status(association_status::ASSOCIATED);
570                }
571                AssociationResponse {
572                    protocol_version: Some(PROTOCOL_VERSION_1),
573                    application_context: echo_context,
574                    result: acse::result::ACCEPTED,
575                    diagnostic: diag::NULL,
576                    user_information,
577                    ..AssociationResponse::default()
578                }
579                .encode()
580            }
581            AuthMechanism::Lls => {
582                let secret_ok = match (&self.association, &aarq.calling_authentication_value) {
583                    (Some(assoc), Some(pw)) => !assoc.secret().is_empty() && assoc.secret() == pw.as_slice(),
584                    _ => false,
585                };
586                if !secret_ok {
587                    return reject_aare(echo_context, diag::AUTHENTICATION_FAILURE, false, None);
588                }
589                if let Some(assoc) = self.association.as_mut() {
590                    assoc.set_association_status(association_status::ASSOCIATED);
591                }
592                AssociationResponse {
593                    protocol_version: Some(PROTOCOL_VERSION_1),
594                    application_context: echo_context,
595                    result: acse::result::ACCEPTED,
596                    diagnostic: diag::NULL,
597                    user_information,
598                    ..AssociationResponse::default()
599                }
600                .encode()
601            }
602            _ => {
603                // HLS pass 1/2: store CtoS, reply with a fresh StoC; the
604                // handshake completes with the reply_to_HLS_authentication
605                // ACTION (pass 3/4), served by the Association LN object.
606                let Some(ctos) = aarq.calling_authentication_value else {
607                    return reject_aare(echo_context, diag::AUTHENTICATION_FAILURE, false, None);
608                };
609                let Some(assoc) = self.association.as_mut() else {
610                    return reject_aare(echo_context, diag::AUTHENTICATION_FAILURE, false, None);
611                };
612                assoc.set_ctos(ctos);
613                if let Some(title) = aarq.calling_ap_title {
614                    assoc.set_client_system_title(title);
615                }
616                assoc.set_hls_handshake_mechanism(mechanism);
617                let stoc = assoc.generate_stoc(16);
618                assoc.set_association_status(association_status::ASSOCIATION_PENDING);
619                // Responding-AP-title: required with ciphering / title-bound HLS
620                // (GMAC+); omit for manufacturer-specific HIGH security (mech 2) over plain LN (etalon).
621                let responding_ap_title = if echo_context == application_context::LN_CIPHERING
622                    || matches!(
623                        mechanism,
624                        AuthMechanism::HlsGmac
625                            | AuthMechanism::HlsSha256
626                            | AuthMechanism::HlsEcdsa
627                            | AuthMechanism::HlsGostCmac
628                            | AuthMechanism::HlsGostStreebog
629                            | AuthMechanism::HlsGostSignature
630                    ) {
631                    assoc.responding_ap_title_for_hls()
632                } else {
633                    None
634                };
635                AssociationResponse {
636                    protocol_version: Some(PROTOCOL_VERSION_1),
637                    application_context: echo_context,
638                    // Yellow Book: accepted + authentication-required while HLS pending.
639                    result: acse::result::ACCEPTED,
640                    diagnostic: diag::AUTHENTICATION_REQUIRED,
641                    responding_ap_title,
642                    mechanism_name: Some(mechanism.id()),
643                    responding_authentication_value: Some(stoc),
644                    user_information,
645                    ..AssociationResponse::default()
646                }
647                .encode()
648            }
649        }
650    }
651
652    /// Manufacturer-specific HIGH-level authentication advertises mechanism 2
653    /// (`HlsManufacturer`); СПОДЭС Configurator associations are configured as
654    /// HLS-GMAC (5). Accept that pairing for AARQ, then finish the handshake
655    /// with GMAC.
656    fn aarq_mechanism_matches_assoc(requested: AuthMechanism, required: AuthMechanism) -> bool {
657        requested == required || (requested == AuthMechanism::HlsManufacturer && required == AuthMechanism::HlsGmac)
658    }
659
660    /// Answers an RLRQ with RLRE (IEC 62056-5-3 §7.3.6) and clears any
661    /// configured association state back to non-associated. A malformed RLRQ
662    /// is still answered with a normal-release RLRE, since releasing is
663    /// best-effort.
664    pub fn handle_rlrq(&mut self, request: &[u8]) -> Vec<u8> {
665        use crate::service::acse::ReleaseRequest;
666        if let Some(assoc) = self.association.as_mut() {
667            assoc.set_association_status(association_status::NON_ASSOCIATED);
668        }
669        ReleaseRequest::decode_rlrq(request).map_or_else(
670            |_| ReleaseRequest { reason: Some(acse::release_reason::NORMAL), user_information: None }.encode_rlre(),
671            |release| release.encode_rlre(),
672        )
673    }
674
675    /// Role conformance advertised in AARE, matching C++ `aare` fill order.
676    fn role_conformance(mechanism: AuthMechanism) -> u32 {
677        if mechanism == AuthMechanism::None {
678            CONFORMANCE_PUBLIC
679        } else if mechanism.is_hls() {
680            CONFORMANCE_CONFIGURATOR
681        } else {
682            CONFORMANCE_READER
683        }
684    }
685
686    /// Builds the negotiated InitiateResponse: role conformance is ANDed with
687    /// the client's proposal and the PDU size capped by the client's maximum.
688    fn negotiate_initiate_response(ireq: Option<&InitiateRequest>, mechanism: AuthMechanism) -> Vec<u8> {
689        let mut conformance = Self::role_conformance(mechanism);
690        let mut pdu = SERVER_MAX_PDU;
691        if let Some(ireq) = ireq {
692            if ireq.proposed_conformance != 0 {
693                conformance &= ireq.proposed_conformance;
694            }
695            if ireq.client_max_receive_pdu_size > 0 && ireq.client_max_receive_pdu_size < pdu {
696                pdu = ireq.client_max_receive_pdu_size;
697            }
698        }
699        InitiateResponse {
700            negotiated_quality_of_service: None,
701            negotiated_dlms_version: DLMS_VERSION,
702            negotiated_conformance: conformance,
703            server_max_receive_pdu_size: pdu,
704            vaa_name: 0x0007,
705        }
706        .encode()
707    }
708
709    fn dispatch_get(&mut self, request: &[u8]) -> Result<Vec<u8>, ServiceError> {
710        // A malformed GET from an associated client is answered with a
711        // data-access-result instead of dropping the session (the invoke-id is
712        // salvaged from the raw APDU when present).
713        let Ok(decoded) = GetRequest::decode(request) else {
714            let invoke_id_and_priority = request.get(2).copied().unwrap_or(0);
715            return GetResponse::Normal {
716                invoke_id_and_priority,
717                result: GetDataResult::AccessResult(data_access_result::OTHER_REASON),
718            }
719            .encode();
720        };
721        match decoded {
722            GetRequest::Normal { invoke_id_and_priority, attribute, access_selection } => {
723                let read = self.read_attribute(&attribute);
724                match apply_selective_access(&attribute, read, access_selection.as_ref()) {
725                    // A too-large value is segmented into datablocks.
726                    GetDataResult::Data(value) => {
727                        let mut raw = Vec::new();
728                        value.serialize_ber(&mut raw)?;
729                        if raw.len() > self.max_pdu {
730                            return Ok(self.start_get_blocks(invoke_id_and_priority, raw));
731                        }
732                        GetResponse::Normal { invoke_id_and_priority, result: GetDataResult::Data(value) }.encode()
733                    }
734                    result => GetResponse::Normal { invoke_id_and_priority, result }.encode(),
735                }
736            }
737            GetRequest::WithList { invoke_id_and_priority, attributes } => {
738                let results = attributes
739                    .iter()
740                    .map(|(a, sel)| {
741                        let read = self.read_attribute(a);
742                        apply_selective_access(a, read, sel.as_ref())
743                    })
744                    .collect();
745                GetResponse::WithList { invoke_id_and_priority, results }.encode()
746            }
747            // Deliver the next block of a segmented result.
748            GetRequest::Next { invoke_id_and_priority, block_number } => {
749                Ok(self.next_get_block(invoke_id_and_priority, block_number))
750            }
751        }
752    }
753
754    /// Stores a segmented GET result and returns the first datablock response.
755    fn start_get_blocks(&mut self, invoke_id_and_priority: u8, data: Vec<u8>) -> Vec<u8> {
756        self.pending_get = Some(PendingGet { data, next_block: 1 });
757        self.next_get_block(invoke_id_and_priority, 0)
758    }
759
760    /// Returns the datablock following `acked_block` (0 for the first).
761    fn next_get_block(&mut self, invoke_id_and_priority: u8, acked_block: u32) -> Vec<u8> {
762        let max_pdu = self.max_pdu;
763        let Some(pending) = self.pending_get.as_mut() else {
764            return ExceptionResponse {
765                state_error: state_error::SERVICE_NOT_ALLOWED,
766                service_error: service_error::OPERATION_NOT_POSSIBLE,
767            }
768            .encode();
769        };
770        let block_number = pending.next_block;
771        // The client acknowledges the previous block by its number in GET-NEXT.
772        if acked_block != 0 && acked_block + 1 != block_number {
773            return ExceptionResponse {
774                state_error: state_error::SERVICE_NOT_ALLOWED,
775                service_error: service_error::OTHER_REASON,
776            }
777            .encode();
778        }
779        let start = (block_number as usize - 1) * max_pdu;
780        let end = (start + max_pdu).min(pending.data.len());
781        let chunk = pending.data[start..end].to_vec();
782        let last_block = end >= pending.data.len();
783        pending.next_block += 1;
784        let response =
785            GetResponse::WithDataBlock { invoke_id_and_priority, last_block, block_number, raw_data: Ok(chunk) };
786        if last_block {
787            self.pending_get = None;
788        }
789        response.encode().unwrap_or_default()
790    }
791
792    fn dispatch_set(&mut self, request: &[u8]) -> Vec<u8> {
793        // A malformed SET is answered with a data-access-result instead of
794        // dropping the session.
795        let Ok(decoded) = SetRequest::decode(request) else {
796            let invoke_id_and_priority = request.get(2).copied().unwrap_or(0);
797            return SetResponse::Normal { invoke_id_and_priority, result: data_access_result::OTHER_REASON }.encode();
798        };
799        match decoded {
800            SetRequest::Normal { invoke_id_and_priority, attribute, value, .. } => {
801                let result = self.write_attribute(&attribute, value);
802                SetResponse::Normal { invoke_id_and_priority, result }.encode()
803            }
804            SetRequest::WithList { invoke_id_and_priority, attributes, values } => {
805                let results = attributes.iter().zip(values).map(|((a, _), v)| self.write_attribute(a, v)).collect();
806                SetResponse::WithList { invoke_id_and_priority, results }.encode()
807            }
808            // Begin reassembling a block-transferred value.
809            SetRequest::WithFirstDatablock { invoke_id_and_priority, attribute, datablock, .. } => {
810                self.pending_set = Some(PendingSet { attribute, buffer: Vec::new() });
811                self.accumulate_set_block(invoke_id_and_priority, &datablock)
812            }
813            SetRequest::WithDatablock { invoke_id_and_priority, datablock } => {
814                if self.pending_set.is_none() {
815                    return not_possible();
816                }
817                self.accumulate_set_block(invoke_id_and_priority, &datablock)
818            }
819        }
820    }
821
822    /// Appends one SET datablock; on the last block, decodes and writes the value.
823    fn accumulate_set_block(&mut self, invoke_id_and_priority: u8, datablock: &DataBlockSa) -> Vec<u8> {
824        let Some(pending) = self.pending_set.as_mut() else {
825            return not_possible();
826        };
827        pending.buffer.extend_from_slice(&datablock.raw_data);
828        if !datablock.last_block {
829            return SetResponse::Datablock { invoke_id_and_priority, block_number: datablock.block_number }.encode();
830        }
831        // Final block: decode the accumulated A-XDR value and write it.
832        let PendingSet { attribute, buffer } = self.pending_set.take().unwrap();
833        let result = match CosemDataType::deserialize_ber(&buffer) {
834            Ok((value, _)) => self.write_attribute(&attribute, value),
835            Err(_) => data_access_result::TYPE_UNMATCHED,
836        };
837        SetResponse::LastDatablock { invoke_id_and_priority, result, block_number: datablock.block_number }.encode()
838    }
839
840    fn dispatch_action(&mut self, request: &[u8]) -> Result<Vec<u8>, ServiceError> {
841        match ActionRequest::decode(request)? {
842            ActionRequest::Normal { invoke_id_and_priority, method, parameters } => {
843                let (result, return_parameters) = self.invoke(&method, parameters);
844                ActionResponse::Normal { invoke_id_and_priority, result, return_parameters }.encode()
845            }
846            ActionRequest::WithList { invoke_id_and_priority, methods, parameters } => {
847                let mut params = parameters.into_iter();
848                let results = methods
849                    .iter()
850                    .map(|m| self.invoke(m, params.next().filter(|p| *p != crate::types::CosemDataType::Null)))
851                    .collect();
852                ActionResponse::WithList { invoke_id_and_priority, results }.encode()
853            }
854            ActionRequest::NextPblock { .. }
855            | ActionRequest::WithFirstPblock { .. }
856            | ActionRequest::WithPblock { .. } => Ok(not_possible()),
857        }
858    }
859}
860
861/// Applies GET selective access to a read result (IEC 62056-5-3 §7.4.1.6 /
862/// IEC 62056-6-2 §4.3.6.2). Only the ProfileGeneric buffer (class 7,
863/// attribute 2) is filtered:
864///
865/// * selector 2 (`entry_descriptor`) — keeps the 1-based entry window
866///   `[from_entry, to_entry]` of the buffer array; `to_entry` = 0 keeps all
867///   remaining entries.
868/// * selector 1 (`range_descriptor`) — value-range filtering needs the sort
869///   column; like the reference implementation the buffer is returned
870///   unfiltered.
871///
872/// Any other selector on the buffer, or a malformed descriptor, yields
873/// `other-reason`; selective access on other attributes is ignored.
874fn apply_selective_access(
875    attribute: &AttributeDescriptor,
876    read: GetDataResult,
877    selection: Option<&crate::service::get::AccessSelection>,
878) -> GetDataResult {
879    let Some(sel) = selection else { return read };
880    if attribute.class_id != 7 || attribute.attribute_id != 2 {
881        return read;
882    }
883    let GetDataResult::Data(CosemDataType::Array(rows)) = read else { return read };
884    match sel.selector {
885        1 => GetDataResult::Data(CosemDataType::Array(rows)),
886        2 => {
887            let fields = match &sel.parameters {
888                CosemDataType::Structure(fields) if fields.len() >= 2 => fields,
889                _ => return GetDataResult::AccessResult(data_access_result::OTHER_REASON),
890            };
891            let (Some(from), Some(to)) = (selective_index(&fields[0]), selective_index(&fields[1])) else {
892                return GetDataResult::AccessResult(data_access_result::OTHER_REASON);
893            };
894            if from == 0 {
895                return GetDataResult::AccessResult(data_access_result::OTHER_REASON);
896            }
897            let start = (from - 1) as usize;
898            let end = if to == 0 { rows.len() } else { (to as usize).min(rows.len()) };
899            let slice = if start < end { rows[start..end].to_vec() } else { Vec::new() };
900            GetDataResult::Data(CosemDataType::Array(slice))
901        }
902        _ => GetDataResult::AccessResult(data_access_result::OTHER_REASON),
903    }
904}
905
906/// Reads a non-negative COSEM integer used as a selective-access entry index.
907fn selective_index(value: &CosemDataType) -> Option<u32> {
908    match value {
909        CosemDataType::DoubleLongUnsigned(v) => Some(*v),
910        CosemDataType::LongUnsigned(v) => Some(u32::from(*v)),
911        CosemDataType::Unsigned(v) => Some(u32::from(*v)),
912        _ => None,
913    }
914}
915
916/// Builds a permanently-rejecting AARE with the given diagnostic;
917/// `initiate_err` adds an `initiateError` ConfirmedServiceError to the
918/// user-information. `diagnostic_is_provider` selects the acse-service-provider
919/// CHOICE (e.g. no-common-acse-version).
920fn reject_aare(
921    application_context: u8,
922    diagnostic: u8,
923    diagnostic_is_provider: bool,
924    initiate_err: Option<u8>,
925) -> Vec<u8> {
926    use crate::service::acse::PROTOCOL_VERSION_1;
927    let user_information = initiate_err.map_or_else(Vec::new, |value| {
928        ConfirmedServiceError {
929            service: crate::service::error::service::INITIATE_ERROR,
930            category: crate::service::error::category::INITIATE,
931            value,
932        }
933        .encode()
934    });
935    AssociationResponse {
936        protocol_version: Some(PROTOCOL_VERSION_1),
937        application_context,
938        result: acse::result::REJECTED_PERMANENT,
939        diagnostic,
940        diagnostic_is_provider,
941        user_information,
942        ..AssociationResponse::default()
943    }
944    .encode()
945}
946
947/// True when the APDU is Association LN `reply_to_HLS_authentication` (method 1).
948fn is_hls_pass3_action(request: &[u8]) -> bool {
949    match ActionRequest::decode(request) {
950        Ok(ActionRequest::Normal { method, .. }) => method.class_id == 15 && method.method_id == 1,
951        _ => false,
952    }
953}
954
955/// EXCEPTION-RESPONSE for an unsupported service tag.
956fn unsupported(_tag: u8) -> Vec<u8> {
957    ExceptionResponse { state_error: state_error::SERVICE_UNKNOWN, service_error: service_error::SERVICE_NOT_SUPPORTED }
958        .encode()
959}
960
961/// EXCEPTION-RESPONSE for a well-formed but unhandled request (e.g. block transfer).
962fn not_possible() -> Vec<u8> {
963    ExceptionResponse {
964        state_error: state_error::SERVICE_NOT_ALLOWED,
965        service_error: service_error::OPERATION_NOT_POSSIBLE,
966    }
967    .encode()
968}
969
970#[cfg(test)]
971mod tests {
972    use super::*;
973    use crate::classes::data::Data;
974    use crate::types::CosemDataType;
975
976    fn dispatcher_with_data() -> RequestDispatcher {
977        let mut d = RequestDispatcher::new();
978        let data = Data::new(ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), CosemDataType::LongUnsigned(0x1234));
979        d.add(Box::new(data));
980        d
981    }
982
983    /// An AssociationLn requiring the given mechanism, with an LLS secret.
984    fn association(mechanism: AuthMechanism) -> AssociationLn {
985        use crate::classes::association_ln::{AssociationLnConfig, AssociationLnVersion};
986        use crate::types::attrs::{AssociatedPartnersId, ContextName, XDLMSContextInfo};
987        AssociationLn::new(AssociationLnConfig {
988            logical_name: ObisCode::new(0, 0, 40, 0, 0, 255),
989            version: AssociationLnVersion::Version1,
990            object_list: vec![],
991            associated_partners_id: AssociatedPartnersId { client_sap: 0, server_sap: 1 },
992            application_context_name: ContextName::OctetString(vec![
993                0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01,
994            ]),
995            xdlms_context_info: XDLMSContextInfo {
996                conformance: vec![0x00; 18],
997                max_receive_pdu_size: 1024,
998                max_send_pdu_size: 1024,
999                dlms_version_number: 6,
1000                quality_of_service: -1,
1001                cyphering_info: vec![],
1002            },
1003            authentication_mechanism: mechanism,
1004            secret: b"password".to_vec(),
1005            association_status: 0,
1006            security_setup_reference: ObisCode::new(0, 0, 43, 0, 0, 255),
1007            user_list: vec![],
1008            current_user: None,
1009        })
1010    }
1011
1012    fn aarq(context: u8, mechanism: Option<u8>, auth: Option<&[u8]>) -> Vec<u8> {
1013        crate::service::acse::AssociationRequest {
1014            application_context: context,
1015            calling_ap_title: None,
1016            sender_acse_requirements: mechanism.map(|_| 0x80),
1017            mechanism_name: mechanism,
1018            calling_authentication_value: auth.map(<[u8]>::to_vec),
1019            user_information: InitiateRequest {
1020                dedicated_key: None,
1021                response_allowed: true,
1022                proposed_quality_of_service: None,
1023                proposed_dlms_version: 6,
1024                proposed_conformance: 0x00_18_5F,
1025                client_max_receive_pdu_size: 0x0400,
1026            }
1027            .encode(),
1028            ..Default::default()
1029        }
1030        .encode()
1031    }
1032
1033    #[test]
1034    fn aarq_lowest_is_accepted_without_association() {
1035        let mut d = dispatcher_with_data();
1036        let resp = d.dispatch(&aarq(1, None, None)).unwrap();
1037        let aare = AssociationResponse::decode(&resp).unwrap();
1038        assert_eq!(aare.result, acse::result::ACCEPTED);
1039        // Negotiated InitiateResponse: version 6, PDU capped by the client.
1040        let iresp = InitiateResponse::decode(&aare.user_information).unwrap();
1041        assert_eq!(iresp.negotiated_dlms_version, 6);
1042        assert_eq!(iresp.server_max_receive_pdu_size, 0x0400);
1043        // Public AA: get + block-get only (0x001010), AND with client proposal.
1044        assert_eq!(iresp.negotiated_conformance, 0x00_10_10);
1045    }
1046
1047    #[test]
1048    fn aarq_lls_reader_conformance() {
1049        let mut d = dispatcher_with_data();
1050        d.set_association(association(AuthMechanism::Lls));
1051        let resp = d.handle_aarq(&aarq(1, Some(1), Some(b"password")));
1052        let aare = AssociationResponse::decode(&resp).unwrap();
1053        assert_eq!(aare.result, acse::result::ACCEPTED);
1054        let iresp = InitiateResponse::decode(&aare.user_information).unwrap();
1055        assert_eq!(iresp.negotiated_conformance, 0x00_10_15);
1056    }
1057
1058    #[test]
1059    fn aarq_unsupported_context_is_rejected() {
1060        let mut d = dispatcher_with_data();
1061        // Short-name referencing (context 2) is not supported.
1062        let resp = d.handle_aarq(&aarq(2, None, None));
1063        let aare = AssociationResponse::decode(&resp).unwrap();
1064        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1065        assert_eq!(aare.diagnostic, acse::acse_diagnostic::APPLICATION_CONTEXT_NAME_NOT_SUPPORTED);
1066    }
1067
1068    #[test]
1069    fn aarq_without_auth_when_required_is_rejected() {
1070        let mut d = dispatcher_with_data();
1071        d.set_association(association(AuthMechanism::Lls));
1072        let resp = d.handle_aarq(&aarq(1, None, None));
1073        let aare = AssociationResponse::decode(&resp).unwrap();
1074        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1075        assert_eq!(aare.diagnostic, acse::acse_diagnostic::AUTHENTICATION_REQUIRED);
1076    }
1077
1078    #[test]
1079    fn aarq_lls_secret_is_checked() {
1080        let mut d = dispatcher_with_data();
1081        d.set_association(association(AuthMechanism::Lls));
1082        // Wrong password.
1083        let aare = AssociationResponse::decode(&d.handle_aarq(&aarq(1, Some(1), Some(b"wrong")))).unwrap();
1084        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1085        assert_eq!(aare.diagnostic, acse::acse_diagnostic::AUTHENTICATION_FAILURE);
1086        // Right password.
1087        let aare = AssociationResponse::decode(&d.handle_aarq(&aarq(1, Some(1), Some(b"password")))).unwrap();
1088        assert_eq!(aare.result, acse::result::ACCEPTED);
1089    }
1090
1091    #[test]
1092    fn aarq_mechanism_mismatch_is_rejected() {
1093        let mut d = dispatcher_with_data();
1094        d.set_association(association(AuthMechanism::HlsSha256));
1095        let resp = d.handle_aarq(&aarq(1, Some(1), Some(b"password")));
1096        let aare = AssociationResponse::decode(&resp).unwrap();
1097        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1098        assert_eq!(aare.diagnostic, acse::acse_diagnostic::AUTHENTICATION_FAILURE);
1099    }
1100
1101    #[test]
1102    fn aarq_hls_pass1_returns_stoc_and_leaves_pending() {
1103        let mut d = dispatcher_with_data();
1104        d.set_association(association(AuthMechanism::HlsSha256));
1105        // Title-bound HLS without a calling-AP-title is rejected.
1106        let aare = AssociationResponse::decode(&d.handle_aarq(&aarq(1, Some(6), Some(b"CTOS0123CTOS0123")))).unwrap();
1107        assert_eq!(aare.diagnostic, acse::acse_diagnostic::CALLING_AP_TITLE_NOT_RECOGNIZED);
1108
1109        // With an 8-octet title: accepted, StoC returned, pass 3/4 pending.
1110        let mut req =
1111            crate::service::acse::AssociationRequest::decode(&aarq(1, Some(6), Some(b"CTOS0123CTOS0123"))).unwrap();
1112        req.calling_ap_title = Some(b"CLIENT01".to_vec());
1113        let aare = AssociationResponse::decode(&d.handle_aarq(&req.encode())).unwrap();
1114        assert_eq!(aare.result, acse::result::ACCEPTED);
1115        assert_eq!(aare.diagnostic, acse::acse_diagnostic::AUTHENTICATION_REQUIRED);
1116        let stoc = aare.responding_authentication_value.expect("StoC missing");
1117        assert_eq!(stoc.len(), 16);
1118    }
1119
1120    #[test]
1121    fn aarq_bad_protocol_version_is_provider_reject() {
1122        let mut d = dispatcher_with_data();
1123        let mut req = crate::service::acse::AssociationRequest::decode(&aarq(1, None, None)).unwrap();
1124        req.protocol_version = Some([0x02, 0x44]);
1125        let aare = AssociationResponse::decode(&d.handle_aarq(&req.encode())).unwrap();
1126        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1127        assert!(aare.diagnostic_is_provider);
1128        assert_eq!(aare.diagnostic, acse::acse_provider_diagnostic::NO_COMMON_ACSE_VERSION);
1129    }
1130
1131    #[test]
1132    fn aarq_wrong_acse_requirements_is_auth_failure() {
1133        let mut d = dispatcher_with_data();
1134        d.set_association(association(AuthMechanism::Lls));
1135        let mut req = crate::service::acse::AssociationRequest::decode(&aarq(1, Some(1), Some(b"password"))).unwrap();
1136        req.sender_acse_requirements = Some(0x00);
1137        let aare = AssociationResponse::decode(&d.handle_aarq(&req.encode())).unwrap();
1138        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1139        assert_eq!(aare.diagnostic, acse::acse_diagnostic::AUTHENTICATION_FAILURE);
1140    }
1141
1142    #[test]
1143    fn aarq_missing_mechanism_with_auth_is_auth_failure() {
1144        let mut d = dispatcher_with_data();
1145        d.set_association(association(AuthMechanism::Lls));
1146        let mut req = crate::service::acse::AssociationRequest::decode(&aarq(1, None, None)).unwrap();
1147        req.sender_acse_requirements = Some(0x80);
1148        req.calling_authentication_value = Some(b"password".to_vec());
1149        let aare = AssociationResponse::decode(&d.handle_aarq(&req.encode())).unwrap();
1150        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1151        assert_eq!(aare.diagnostic, acse::acse_diagnostic::AUTHENTICATION_FAILURE);
1152    }
1153
1154    #[test]
1155    fn get_while_hls_pending_is_service_not_allowed() {
1156        let mut d = dispatcher_with_data();
1157        d.set_association(association(AuthMechanism::HlsSha1));
1158        let req =
1159            crate::service::acse::AssociationRequest::decode(&aarq(1, Some(4), Some(b"CTOS0123CTOS0123"))).unwrap();
1160        // HlsSha1 (4) is not title-bound (>=5); no calling-AP-title needed.
1161        let aare = AssociationResponse::decode(&d.handle_aarq(&req.encode())).unwrap();
1162        assert_eq!(aare.result, acse::result::ACCEPTED);
1163        assert_eq!(d.association().unwrap().association_status(), association_status::ASSOCIATION_PENDING);
1164
1165        let get = GetRequest::Normal {
1166            invoke_id_and_priority: 0xC0,
1167            attribute: AttributeDescriptor {
1168                class_id: 15,
1169                instance_id: ObisCode::new(0, 0, 40, 0, 0, 255),
1170                attribute_id: 1,
1171            },
1172            access_selection: None,
1173        }
1174        .encode()
1175        .unwrap();
1176        let resp = d.dispatch(&get).unwrap();
1177        assert_eq!(resp[0], 0xD8); // EXCEPTION-RESPONSE
1178        let ex = ExceptionResponse::decode(&resp).unwrap();
1179        assert_eq!(ex.state_error, state_error::SERVICE_NOT_ALLOWED);
1180        assert_eq!(ex.service_error, service_error::OPERATION_NOT_POSSIBLE);
1181
1182        // After HLS completes (status → associated), GET is allowed again.
1183        d.association_mut().unwrap().set_association_status(association_status::ASSOCIATED);
1184        let resp = d.dispatch(&get).unwrap();
1185        assert_ne!(resp[0], 0xD8, "GET after HLS must not be Exception");
1186    }
1187
1188    #[test]
1189    fn aarq_bad_initiate_yields_confirmed_service_error() {
1190        let mut d = dispatcher_with_data();
1191        let mut req = crate::service::acse::AssociationRequest::decode(&aarq(1, None, None)).unwrap();
1192        req.user_information = InitiateRequest {
1193            dedicated_key: None,
1194            response_allowed: true,
1195            proposed_quality_of_service: None,
1196            proposed_dlms_version: 5, // too low
1197            proposed_conformance: 0x00_18_5F,
1198            client_max_receive_pdu_size: 0x0400,
1199        }
1200        .encode();
1201        let aare = AssociationResponse::decode(&d.handle_aarq(&req.encode())).unwrap();
1202        assert_eq!(aare.result, acse::result::REJECTED_PERMANENT);
1203        let cse = ConfirmedServiceError::decode(&aare.user_information).unwrap();
1204        assert_eq!(cse.value, initiate_error::DLMS_VERSION_TOO_LOW);
1205    }
1206
1207    /// A registered object whose attribute 2 is writable, for SET reassembly.
1208    #[derive(Clone)]
1209    struct Writable {
1210        obis: ObisCode,
1211        value: CosemDataType,
1212    }
1213
1214    impl crate::interface::InterfaceClass for Writable {
1215        fn class_id(&self) -> u16 {
1216            1
1217        }
1218        fn version(&self) -> u8 {
1219            0
1220        }
1221        fn logical_name(&self) -> &ObisCode {
1222            &self.obis
1223        }
1224        fn attributes(&self) -> Vec<(u8, CosemDataType)> {
1225            vec![(1, CosemDataType::OctetString(self.obis.to_bytes())), (2, self.value.clone())]
1226        }
1227        fn methods(&self) -> Vec<(u8, String)> {
1228            vec![]
1229        }
1230        fn serialize_ber(&self, _: &mut Vec<u8>) -> Result<(), crate::types::BerError> {
1231            Ok(())
1232        }
1233        fn deserialize_ber(&mut self, _: &[u8]) -> Result<(), crate::types::BerError> {
1234            Ok(())
1235        }
1236        fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
1237            if attribute_id == 2 {
1238                self.value = value;
1239                Ok(())
1240            } else {
1241                Err("read only".to_string())
1242            }
1243        }
1244        fn invoke_method(&mut self, _: u8, _: Option<CosemDataType>) -> Result<CosemDataType, String> {
1245            Err("no methods".to_string())
1246        }
1247        fn as_any(&self) -> &dyn std::any::Any {
1248            self
1249        }
1250    }
1251
1252    #[test]
1253    fn large_get_is_delivered_in_datablocks() {
1254        // A 300-octet octet-string exceeds the small block size and is segmented.
1255        let obis = ObisCode::new(0, 0, 0x80, 0, 0, 0xFF);
1256        let big = CosemDataType::OctetString(vec![0xAB; 300]);
1257        let mut d = RequestDispatcher::new();
1258        d.set_max_pdu(128);
1259        d.add(Box::new(Data::new(obis.clone(), big.clone())));
1260
1261        let req = GetRequest::Normal {
1262            invoke_id_and_priority: 0xC1,
1263            attribute: AttributeDescriptor::new(1, obis, 2),
1264            access_selection: None,
1265        };
1266        let mut reassembled = Vec::new();
1267        let mut resp = GetResponse::decode(&d.dispatch(&req.encode().unwrap()).unwrap()).unwrap();
1268        let mut block = 1u32;
1269        loop {
1270            match resp {
1271                GetResponse::WithDataBlock { last_block, block_number, raw_data: Ok(chunk), .. } => {
1272                    assert_eq!(block_number, block);
1273                    reassembled.extend_from_slice(&chunk);
1274                    if last_block {
1275                        break;
1276                    }
1277                    let next = GetRequest::Next { invoke_id_and_priority: 0xC1, block_number };
1278                    resp = GetResponse::decode(&d.dispatch(&next.encode().unwrap()).unwrap()).unwrap();
1279                    block += 1;
1280                }
1281                other => panic!("expected datablock, got {other:?}"),
1282            }
1283        }
1284        // The reassembled blocks decode back to the original value.
1285        let (value, _) = CosemDataType::deserialize_ber(&reassembled).unwrap();
1286        assert_eq!(value, big);
1287    }
1288
1289    #[test]
1290    fn set_reassembles_datablocks_and_writes() {
1291        let obis = ObisCode::new(1, 0, 1, 8, 0, 0xFF);
1292        let mut d = RequestDispatcher::new();
1293        d.add(Box::new(Writable { obis: obis.clone(), value: CosemDataType::LongUnsigned(0) }));
1294
1295        // The value to write, split into two datablocks.
1296        let mut value_bytes = Vec::new();
1297        CosemDataType::OctetString(vec![0x5A; 40]).serialize_ber(&mut value_bytes).unwrap();
1298        let (first, second) = value_bytes.split_at(20);
1299
1300        let req1 = SetRequest::WithFirstDatablock {
1301            invoke_id_and_priority: 0xC1,
1302            attribute: AttributeDescriptor::new(1, obis.clone(), 2),
1303            access_selection: None,
1304            datablock: DataBlockSa { last_block: false, block_number: 1, raw_data: first.to_vec() },
1305        };
1306        let r1 = SetResponse::decode(&d.dispatch(&req1.encode().unwrap()).unwrap()).unwrap();
1307        assert!(matches!(r1, SetResponse::Datablock { block_number: 1, .. }));
1308
1309        let req2 = SetRequest::WithDatablock {
1310            invoke_id_and_priority: 0xC1,
1311            datablock: DataBlockSa { last_block: true, block_number: 2, raw_data: second.to_vec() },
1312        };
1313        let r2 = SetResponse::decode(&d.dispatch(&req2.encode().unwrap()).unwrap()).unwrap();
1314        assert_eq!(
1315            r2,
1316            SetResponse::LastDatablock {
1317                invoke_id_and_priority: 0xC1,
1318                result: data_access_result::SUCCESS,
1319                block_number: 2
1320            }
1321        );
1322
1323        // The reassembled value was written to the object.
1324        let got = d
1325            .dispatch(
1326                &GetRequest::Normal {
1327                    invoke_id_and_priority: 0xC1,
1328                    attribute: AttributeDescriptor::new(1, obis, 2),
1329                    access_selection: None,
1330                }
1331                .encode()
1332                .unwrap(),
1333            )
1334            .unwrap();
1335        match GetResponse::decode(&got).unwrap() {
1336            GetResponse::Normal { result: GetDataResult::Data(v), .. } => {
1337                assert_eq!(v, CosemDataType::OctetString(vec![0x5A; 40]));
1338            }
1339            other => panic!("unexpected {other:?}"),
1340        }
1341    }
1342
1343    #[test]
1344    fn malformed_get_returns_other_reason() {
1345        let mut d = dispatcher_with_data();
1346        // GET-REQUEST with an unknown choice (0x77) and a salvageable invoke-id.
1347        let resp = d.dispatch(&[tag::GET_REQUEST, 0x77, 0xC1]).unwrap();
1348        let decoded = GetResponse::decode(&resp).unwrap();
1349        assert_eq!(
1350            decoded,
1351            GetResponse::Normal {
1352                invoke_id_and_priority: 0xC1,
1353                result: GetDataResult::AccessResult(data_access_result::OTHER_REASON),
1354            }
1355        );
1356    }
1357
1358    #[test]
1359    fn malformed_set_returns_other_reason() {
1360        let mut d = dispatcher_with_data();
1361        let resp = d.dispatch(&[tag::SET_REQUEST, 0x77, 0xC1]).unwrap();
1362        let decoded = SetResponse::decode(&resp).unwrap();
1363        assert_eq!(
1364            decoded,
1365            SetResponse::Normal { invoke_id_and_priority: 0xC1, result: data_access_result::OTHER_REASON }
1366        );
1367    }
1368
1369    #[test]
1370    fn selective_access_by_entry_filters_profile_buffer() {
1371        use crate::classes::profile_generic::{ProfileGeneric, ProfileGenericConfig};
1372        use crate::service::get::AccessSelection;
1373
1374        let obis = ObisCode::new(1, 0, 99, 1, 0, 0xFF);
1375        let buffer: Vec<CosemDataType> =
1376            (1u32..=5).map(|i| CosemDataType::Structure(vec![CosemDataType::DoubleLongUnsigned(i)])).collect();
1377        let profile = ProfileGeneric::new(ProfileGenericConfig {
1378            logical_name: obis.clone(),
1379            version: 1,
1380            buffer,
1381            capture_objects: vec![],
1382            capture_period: 0,
1383            sort_method: crate::types::attrs::SortMethod::Fifo,
1384            sort_object: None,
1385            entries_in_use: 5,
1386            profile_entries: 10,
1387        });
1388        let mut d = RequestDispatcher::new();
1389        d.add(Box::new(profile));
1390
1391        // entry_descriptor: entries 2..4 (1-based, inclusive).
1392        let req = GetRequest::Normal {
1393            invoke_id_and_priority: 0xC1,
1394            attribute: AttributeDescriptor::new(7, obis, 2),
1395            access_selection: Some(AccessSelection {
1396                selector: 2,
1397                parameters: CosemDataType::Structure(vec![
1398                    CosemDataType::DoubleLongUnsigned(2),
1399                    CosemDataType::DoubleLongUnsigned(4),
1400                    CosemDataType::LongUnsigned(1),
1401                    CosemDataType::LongUnsigned(0),
1402                ]),
1403            }),
1404        };
1405        let resp = GetResponse::decode(&d.dispatch(&req.encode().unwrap()).unwrap()).unwrap();
1406        match resp {
1407            GetResponse::Normal { result: GetDataResult::Data(CosemDataType::Array(rows)), .. } => {
1408                assert_eq!(rows.len(), 3);
1409                assert_eq!(rows[0], CosemDataType::Structure(vec![CosemDataType::DoubleLongUnsigned(2)]));
1410                assert_eq!(rows[2], CosemDataType::Structure(vec![CosemDataType::DoubleLongUnsigned(4)]));
1411            }
1412            other => panic!("unexpected {other:?}"),
1413        }
1414    }
1415
1416    #[test]
1417    fn get_reads_registered_attribute() {
1418        let mut d = dispatcher_with_data();
1419        let req = GetRequest::Normal {
1420            invoke_id_and_priority: 0xC1,
1421            attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2),
1422            access_selection: None,
1423        };
1424        let resp = GetResponse::decode(&d.dispatch(&req.encode().unwrap()).unwrap()).unwrap();
1425        assert_eq!(
1426            resp,
1427            GetResponse::Normal {
1428                invoke_id_and_priority: 0xC1,
1429                result: GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)),
1430            }
1431        );
1432    }
1433
1434    #[test]
1435    fn get_unknown_object_returns_object_undefined() {
1436        let mut d = dispatcher_with_data();
1437        let req = GetRequest::Normal {
1438            invoke_id_and_priority: 0xC1,
1439            attribute: AttributeDescriptor::new(1, ObisCode::new(9, 9, 9, 9, 9, 9), 2),
1440            access_selection: None,
1441        };
1442        let resp = GetResponse::decode(&d.dispatch(&req.encode().unwrap()).unwrap()).unwrap();
1443        assert_eq!(
1444            resp,
1445            GetResponse::Normal {
1446                invoke_id_and_priority: 0xC1,
1447                result: GetDataResult::AccessResult(data_access_result::OBJECT_UNDEFINED),
1448            }
1449        );
1450    }
1451
1452    #[test]
1453    fn set_on_data_value_attribute_succeeds() {
1454        let mut d = dispatcher_with_data();
1455        let req = SetRequest::Normal {
1456            invoke_id_and_priority: 0xC1,
1457            attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2),
1458            access_selection: None,
1459            value: CosemDataType::LongUnsigned(0x9999),
1460        };
1461        let resp = SetResponse::decode(&d.dispatch(&req.encode().unwrap()).unwrap()).unwrap();
1462        assert_eq!(resp, SetResponse::Normal { invoke_id_and_priority: 0xC1, result: data_access_result::SUCCESS });
1463        let get = GetRequest::Normal {
1464            invoke_id_and_priority: 0xC1,
1465            attribute: AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2),
1466            access_selection: None,
1467        };
1468        let get_resp = GetResponse::decode(&d.dispatch(&get.encode().unwrap()).unwrap()).unwrap();
1469        assert_eq!(
1470            get_resp,
1471            GetResponse::Normal {
1472                invoke_id_and_priority: 0xC1,
1473                result: GetDataResult::Data(CosemDataType::LongUnsigned(0x9999)),
1474            }
1475        );
1476    }
1477
1478    #[test]
1479    fn get_with_list_reads_each_attribute() {
1480        let mut d = dispatcher_with_data();
1481        let req = GetRequest::WithList {
1482            invoke_id_and_priority: 0xC1,
1483            attributes: vec![
1484                (AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2), None),
1485                (AttributeDescriptor::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 1), None),
1486            ],
1487        };
1488        let resp = GetResponse::decode(&d.dispatch(&req.encode().unwrap()).unwrap()).unwrap();
1489        match resp {
1490            GetResponse::WithList { results, .. } => {
1491                assert_eq!(results[0], GetDataResult::Data(CosemDataType::LongUnsigned(0x1234)));
1492                // Attribute 1 is the logical name.
1493                assert!(matches!(results[1], GetDataResult::Data(CosemDataType::OctetString(_))));
1494            }
1495            _ => panic!("expected WITH-LIST response"),
1496        }
1497    }
1498
1499    #[test]
1500    fn rlrq_is_answered_with_rlre() {
1501        let mut d = dispatcher_with_data();
1502        let rlrq =
1503            crate::service::acse::ReleaseRequest { reason: Some(acse::release_reason::NORMAL), user_information: None }
1504                .encode_rlrq();
1505        let resp = d.dispatch(&rlrq).unwrap();
1506        assert_eq!(resp.first(), Some(&acse::RLRE_TAG));
1507    }
1508
1509    #[test]
1510    fn unsupported_tag_yields_exception_response() {
1511        let mut d = dispatcher_with_data();
1512        let resp = d.dispatch(&[tag::DATA_NOTIFICATION, 0x00]).unwrap();
1513        assert_eq!(resp[0], tag::EXCEPTION_RESPONSE);
1514    }
1515
1516    fn push_setup_config() -> crate::classes::push_setup::PushSetupConfig {
1517        use crate::types::attrs::{ConfirmationParameters, DateTime, SendDestinationAndMethod};
1518        crate::classes::push_setup::PushSetupConfig {
1519            logical_name: ObisCode::new(0, 0, 25, 9, 0, 255),
1520            version: 0,
1521            push_object_list: vec![],
1522            send_destination_and_method: SendDestinationAndMethod {
1523                transport_service: 0,
1524                destination: b"192.168.0.1:4059".to_vec(),
1525                message: 0,
1526            },
1527            communication_window: vec![],
1528            randomisation_start_interval: 0,
1529            number_of_retries: 3,
1530            repetition_delay: CosemDataType::LongUnsigned(0),
1531            port_reference: vec![],
1532            push_client_sap: 1,
1533            push_protection_parameters: vec![],
1534            push_operation_method: 0,
1535            confirmation_parameters: ConfirmationParameters { data: vec![] },
1536            last_confirmation_date_time: DateTime::new([0u8; 12]),
1537        }
1538    }
1539
1540    #[test]
1541    fn push_delivery_request_reads_registered_objects() {
1542        use crate::classes::push_setup::PushSetup;
1543        use crate::types::attrs::CaptureObjectDefinition;
1544
1545        let mut d = dispatcher_with_data();
1546        let mut config = push_setup_config();
1547        config.push_object_list = vec![CaptureObjectDefinition::new(1, ObisCode::new(0, 0, 0x80, 0, 0, 0xFF), 2, 0)];
1548        let push = PushSetup::new(config);
1549
1550        let req = d.build_push_delivery_request(&push, 1).unwrap();
1551        assert_eq!(req.destination, b"192.168.0.1:4059");
1552        assert_eq!(req.client_sap, 1);
1553        let decoded = DataNotification::decode(&req.body).unwrap();
1554        assert_eq!(decoded.notification_body, CosemDataType::LongUnsigned(0x1234));
1555    }
1556
1557    #[test]
1558    fn push_delivery_request_rejects_missing_object() {
1559        use crate::classes::push_setup::PushSetup;
1560        use crate::types::attrs::CaptureObjectDefinition;
1561
1562        let mut d = dispatcher_with_data();
1563        let mut config = push_setup_config();
1564        config.push_object_list = vec![CaptureObjectDefinition::new(1, ObisCode::new(9, 9, 9, 9, 9, 9), 2, 0)];
1565        let push = PushSetup::new(config);
1566
1567        assert!(d.build_push_delivery_request(&push, 1).is_err());
1568    }
1569}