From c99cb81bbc70b767d81ea429a92015ff9e2ae05d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 6 Aug 2026 16:56:05 +0700 Subject: [PATCH] Add MMS association and report subscription runtime --- ASSOCIATION_RUNTIME_PROFILE.md | 69 +++ CMakeLists.txt | 11 +- MIGRATION_CHECKLIST.md | 15 + PORT_STATUS.md | 28 +- README.md | 11 + VALIDATION.txt | 47 +- .../ariec61850/mms/association_runtime.hpp | 209 ++++++++ .../mms/report_subscription_runtime.hpp | 134 +++++ src/mms/association_runtime.cpp | 471 ++++++++++++++++++ src/mms/report_subscription_runtime.cpp | 412 +++++++++++++++ tests/test_mms_runtime.cpp | 407 +++++++++++++++ 11 files changed, 1780 insertions(+), 34 deletions(-) create mode 100644 ASSOCIATION_RUNTIME_PROFILE.md create mode 100644 include/ariec61850/mms/association_runtime.hpp create mode 100644 include/ariec61850/mms/report_subscription_runtime.hpp create mode 100644 src/mms/association_runtime.cpp create mode 100644 src/mms/report_subscription_runtime.cpp create mode 100644 tests/test_mms_runtime.cpp diff --git a/ASSOCIATION_RUNTIME_PROFILE.md b/ASSOCIATION_RUNTIME_PROFILE.md new file mode 100644 index 000000000..6b60c589a --- /dev/null +++ b/ASSOCIATION_RUNTIME_PROFILE.md @@ -0,0 +1,69 @@ +# MMS Association and Report Subscription Runtime Profile + +## Scope + +Phase 4B adds the stateful runtime that joins the deterministic Phase 3 association codecs +and Phase 4A reporting codecs. The runtime is transport-injected: an application supplies an +`MmsByteTransport` implementation, while the core owns TPKT/COTP framing, Session, +Presentation, ACSE/MMS association, confirmed-service routing, and RCB subscription state. + +## Association lifecycle + +`MmsAssociationRuntime` implements: + +1. byte-transport connect with deadline and `std::stop_token` cancellation; +2. COTP Connection Request/Confirm negotiation and TPDU-size capture; +3. ISO Session Connect, Presentation CP, ACSE AARQ, and MMS Initiate exchange; +4. accepted/rejected association validation and negotiated MMS limits; +5. segmented COTP send and bounded reassembly on receive; +6. monotonically allocated bounded invoke IDs; +7. confirmed-response/error routing while interleaved InformationReports are queued; +8. explicit timeout, cancellation, fault, and disconnect events; and +9. best-effort COTP Disconnect Request before closing the injected transport. + +A failed or timed-out confirmed exchange faults the association because the transport stream +may no longer have a trustworthy request/response boundary. Reconnect is explicit: close or +fault the old runtime state, refill/recreate the transport as required, and call `connect` again. + +## Report subscription lifecycle + +`MmsReportSubscriptionRuntime` implements a persistent static-DataSet RCB workflow: + +1. re-probe the selected RCB immediately before any write; +2. refuse takeover when `RptEna`, reservation, or availability evidence indicates another + session owns the RCB; +3. optionally reserve an URCB using `Resv=true`; +4. optionally write `DatSet`, `TrgOps`, and `OptFlds`; +5. enable with `RptEna=true`; +6. optionally request GI after enable; +7. receive, decode, map, and monitor InformationReports until stop/cancellation/fault; +8. disable only when this runtime enabled the RCB; +9. release only reservations touched by this runtime; and +10. record `cleanup_required` when the association is lost before cleanup completes. + +`retry_cleanup` can be called after a successful reconnect. BRCB `EntryID` resume, purge +policy, buffer-overflow recovery, and dynamic DataSet create/delete remain separate work. + +## Safety and ownership rules + +- The core does not silently take over an already enabled or reserved RCB. +- Cleanup writes are limited to state touched by the current runtime instance. +- The runtime does not include a default TCP socket implementation; live network access is + possible only when an application explicitly supplies an `MmsByteTransport`. +- No control service, SBO state machine, file service, dynamic DataSet create/delete, or + automatic BRCB replay is enabled by this phase. + +## Validation + +The scripted transport regression covers: + +- successful COTP/ACSE/MMS association and negotiated limits; +- cancellation followed by a clean reconnect; +- confirmed request/response routing with an interleaved InformationReport; +- confirmed-exchange timeout and fault transition; +- URCB probe, reserve, enable, GI, report receive, disable, and reservation release; +- cleanup-required state after association loss; and +- refusal to take over an enabled RCB. + +The repository has 16 CTest entries through Phase 4B. Local GCC, Clang, and Clang +ASan/UBSan runs pass all 16 tests with warnings treated as errors. diff --git a/CMakeLists.txt b/CMakeLists.txt index 5ce9bf07d..e322bcc1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.20) project(ARIEC61850Cpp - VERSION 0.12.0 + VERSION 0.13.0 DESCRIPTION "Incremental C++20 port of the ARIEC61850 protocol stack" LANGUAGES CXX) @@ -27,6 +27,8 @@ add_library(ariec61850_core src/mms/services.cpp src/mms/invoke_router.cpp src/mms/reporting.cpp + src/mms/association_runtime.cpp + src/mms/report_subscription_runtime.cpp src/sampled_values/pdu_codec.cpp src/sampled_values/frame_codec.cpp src/sampled_values/quality.cpp @@ -181,6 +183,13 @@ if(ARIEC61850_BUILD_TESTS) ariec61850_apply_sanitizers(ariec61850_reporting_tests) add_test(NAME ariec61850_reporting_tests COMMAND ariec61850_reporting_tests) + add_executable(ariec61850_mms_runtime_tests tests/test_mms_runtime.cpp) + target_link_libraries(ariec61850_mms_runtime_tests PRIVATE ARIEC61850::core) + target_compile_features(ariec61850_mms_runtime_tests PRIVATE cxx_std_20) + ariec61850_apply_warnings(ariec61850_mms_runtime_tests) + ariec61850_apply_sanitizers(ariec61850_mms_runtime_tests) + add_test(NAME ariec61850_mms_runtime_tests COMMAND ariec61850_mms_runtime_tests) + add_executable(ariec61850_fuzz_smoke_tests tests/test_fuzz_smoke.cpp) target_link_libraries(ariec61850_fuzz_smoke_tests PRIVATE ARIEC61850::core) target_include_directories(ariec61850_fuzz_smoke_tests PRIVATE diff --git a/MIGRATION_CHECKLIST.md b/MIGRATION_CHECKLIST.md index 4964b3a79..b70de0286 100644 --- a/MIGRATION_CHECKLIST.md +++ b/MIGRATION_CHECKLIST.md @@ -98,6 +98,20 @@ until laboratory interoperability is complete. - [x] Bounded offline report stream/frame retention. - [x] MMS-reporting mutation smoke and LLVM libFuzzer corpus. +### Phase 4B — association and subscription runtime + +- [x] Transport-injected TPKT/COTP/Session/Presentation/ACSE/MMS lifecycle. +- [x] Negotiated TPDU and MMS association limits. +- [x] Deadline and `std::stop_token` cancellation paths. +- [x] Bounded invoke-ID allocation and confirmed-result routing. +- [x] InformationReport delivery while confirmed requests are pending. +- [x] RCB re-probe and occupied-control takeover protection. +- [x] URCB reservation, RptEna enable/disable, optional GI, and touched-state cleanup. +- [x] Persistent report polling and Phase 4A monitor ingestion. +- [x] Cleanup-required evidence and retry path after association loss. +- [ ] Built-in TCP socket transport and physical IED association validation. +- [ ] BRCB EntryID resume, purge decisioning, and buffer-overflow recovery. + ### Later Phase 4 work - [ ] Direct and SBO control state machines. @@ -121,6 +135,7 @@ until laboratory interoperability is complete. - [x] Full stacked-branch GCC/Clang/MSVC and security workflows through Phase 3C. - [x] PR #6 through PR #10 squash-merged sequentially to `main`. - [x] Full main-based branch GCC/Clang/MSVC and security workflows through Phase 4A. +- [x] Full stacked-branch GCC/Clang/MSVC and security workflows through Phase 4B. - [ ] Controlled physical-lab process-bus capture evidence. - [ ] C# and C++ executable-oracle comparison in one CI job. diff --git a/PORT_STATUS.md b/PORT_STATUS.md index 8275a359c..fd3ebed2e 100644 --- a/PORT_STATUS.md +++ b/PORT_STATUS.md @@ -2,7 +2,7 @@ ## Current milestone -**Phase 4A — offline DataSet/RCB inventory, InformationReport parsing, and bounded report monitoring are implemented and validated on the published branch.** +**Phase 4B — transport-injected association lifecycle and persistent report-subscription runtime are implemented and validated on the published stacked branch.** ## Delivered modules @@ -19,7 +19,9 @@ | Sequence and segmentation continuity tracker | Implemented | | Bounded offline report monitor | Implemented | | MMS reporting mutation smoke/libFuzzer | Complete | -| Active MMS association/client runtime | Disabled | +| Transport-injected MMS association/client runtime | Implemented | +| Persistent RCB subscription runtime | Implemented | +| Built-in TCP socket transport | Not included | ## Phase 4A behavior @@ -34,13 +36,22 @@ The offline reporting layer: - detects sequence gaps, duplicates, wraps, resets, configuration/DataSet changes, buffer overflow, and segmentation discontinuity; and - retains only configured numbers of streams and recent frames. +## Phase 4B behavior + +- TPKT/COTP, Session, Presentation, ACSE, and MMS Initiate are orchestrated as one bounded lifecycle. +- Confirmed service responses are routed by invoke ID while InformationReports remain deliverable. +- Deadline and cancellation failures produce explicit fault/cancel events. +- A selected RCB is re-probed before writes and occupied RCBs are not taken over. +- URCB reservation, optional DatSet/TrgOps/OptFlds writes, RptEna, GI, polling, stop, and cleanup retry are stateful. +- Lost associations preserve cleanup-required evidence instead of pretending the RCB was disabled. + ## Validation - GNU C++ 14.2, Release, warnings as errors: passed. - Clang 17, Release, warnings as errors: passed. - Clang 17, ASan + UBSan: passed. - Eleven deterministic Phase 4A reporting groups: passed. -- Full repository CTest: 15/15 passed. +- Full repository CTest: 16/16 passed through Phase 4B. - C# exact OptFlds/report-item shape: passed. - Local MMS-reporting libFuzzer: 5,000 runs, no crash artifact. - GitHub GCC, Clang, and Windows MSVC matrix: passed. @@ -49,11 +60,12 @@ The offline reporting layer: ## Remaining acceptance gates -- Live association lifecycle, timeout, cancellation, RCB enable/reservation, GI, and IED interoperability remain outside this phase. -- Direct/SBO control and file services remain later Phase 4 work. +- Built-in platform TCP transport and physical IED interoperability remain separate acceptance work. +- BRCB EntryID resume, purge/buffer-overflow recovery, dynamic DataSet lifecycle, Direct/SBO control, and file services remain later work. ## Safety boundary -Phase 4A consumes saved bytes and supplied discovery/read evidence only. It does not open -a socket, connect to an IED, enable or reserve an RCB, trigger GI, execute a live read or -write, or perform a control operation. +Phase 4B can perform association and RCB Read/Write operations only through an explicitly +injected `MmsByteTransport`. The core does not provide or auto-enable a socket backend. It +never takes over an occupied RCB and only cleans up state touched by the current runtime. +Control operations, dynamic DataSet mutation, and file services are not exposed. diff --git a/README.md b/README.md index 5ff7f397a..382525f4e 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,17 @@ interoperability are complete. No enabled runtime opens TCP sockets, Npcap, raw sockets, or a network interface. Physical IED interoperability and all active transmission remain gated. +## Phase 4B: association and report-subscription runtime + +The C++ core now includes a transport-injected MMS association runtime and persistent RCB +subscription state machine. It performs COTP, Session, Presentation, ACSE/MMS Initiate, +confirmed-service routing, timeout/cancellation handling, RCB re-probe, URCB reservation, +`RptEna`, optional GI, InformationReport delivery, and ownership-aware cleanup. See +`ASSOCIATION_RUNTIME_PROFILE.md`. + +The core deliberately does not ship a default socket transport in this phase. Applications +that intentionally enable live IED access must provide an `MmsByteTransport` implementation. + ## Build ### Windows — Visual Studio diff --git a/VALIDATION.txt b/VALIDATION.txt index ba6e20b0c..81d691b27 100644 --- a/VALIDATION.txt +++ b/VALIDATION.txt @@ -1,42 +1,39 @@ -ARIEC61850 C++ Phase 4A local validation +ARIEC61850 C++ Phase 4B validation Date: 2026-08-06 GNU C++ 14.2 / Release / warnings-as-errors: Configure: PASS Build: PASS - CTest: PASS (15/15) + CTest: PASS (16/16) Clang 17 / Release / warnings-as-errors: Configure: PASS Build: PASS - CTest: PASS (15/15) + CTest: PASS (16/16) Clang 17 / RelWithDebInfo / ASan + UBSan: Configure: PASS Build: PASS - CTest: PASS (15/15) + CTest: PASS (16/16) -Phase 4A deterministic evidence: - - DataSet and BRCB/URCB inventory grouping - - GetNamedVariableListAttributes request/response round trips - - InformationReport raw MMS and P-DATA round trips - - exact C# OptFlds/report-item semantic vector - - included values, partial failures, data references, and reasons - - RCB attribute state and availability confidence mapping - - sequence gap/duplicate/wrap/reset and configuration/DataSet changes - - buffer-overflow and segmented-report continuity - - bounded stream and frame retention - - malformed/trailing/limit rejection and deterministic mutation smoke - -Local libFuzzer: - MMS-reporting corpus: PASS (5,000 runs, no crash artifact) +Phase 4B deterministic evidence: + - COTP/ACSE/MMS association success and negotiated limits + - cancelled connect followed by explicit reconnect + - confirmed response routing with interleaved InformationReport + - confirmed-exchange timeout and association fault transition + - RCB live-state re-probe before any write + - URCB Resv=true, RptEna=true, optional GI, report delivery, and cleanup + - occupied/enabled RCB takeover protection + - cleanup-required state after association loss + - persistent report mapping into the bounded Phase 4A monitor GitHub Actions: - GCC / Clang / Windows MSVC matrix: PASS (15/15 tests on each compiler) - Clang ASan + UBSan: PASS (15/15 tests) - Ten-corpus libFuzzer smoke: PASS (including MMS reporting; no crash artifact) + GCC / Clang / Windows MSVC matrix: PASS + Clang ASan + UBSan: PASS + Existing ten-corpus libFuzzer: PASS (no crash artifact) -Physical interoperability: - Active TCP association: DISABLED - Live RCB enable/reservation/GI: DISABLED - Live IED read/write/control: DISABLED +Runtime boundary: + Byte transport interface: IMPLEMENTED + Built-in TCP socket backend: NOT INCLUDED + Physical IED association: NOT VALIDATED + Direct/SBO control and file service: DISABLED diff --git a/include/ariec61850/mms/association_runtime.hpp b/include/ariec61850/mms/association_runtime.hpp new file mode 100644 index 000000000..ef2296abc --- /dev/null +++ b/include/ariec61850/mms/association_runtime.hpp @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "ariec61850/mms/invoke_router.hpp" +#include "ariec61850/mms/pdu.hpp" +#include "ariec61850/osi/tpkt.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ar::iec61850::mms { + +class MmsAssociationRuntimeError : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +class MmsTransportTimeoutError final : public MmsAssociationRuntimeError { +public: + using MmsAssociationRuntimeError::MmsAssociationRuntimeError; +}; + +class MmsTransportCancelledError final : public MmsAssociationRuntimeError { +public: + using MmsAssociationRuntimeError::MmsAssociationRuntimeError; +}; + +struct MmsEndpoint final { + std::string host; + std::uint16_t port{102U}; + + friend bool operator==(const MmsEndpoint&, const MmsEndpoint&) = default; +}; + +class MmsByteTransport { +public: + using Clock = std::chrono::steady_clock; + using Deadline = Clock::time_point; + + virtual ~MmsByteTransport() = default; + + virtual void connect( + const MmsEndpoint& endpoint, + Deadline deadline, + std::stop_token stop_token) = 0; + virtual void send( + std::span bytes, + Deadline deadline, + std::stop_token stop_token) = 0; + [[nodiscard]] virtual std::vector receive( + Deadline deadline, + std::stop_token stop_token) = 0; + virtual void close() noexcept = 0; + [[nodiscard]] virtual bool connected() const noexcept = 0; +}; + +enum class MmsAssociationRuntimeState : std::uint8_t { + disconnected, + transport_connecting, + transport_connected, + cotp_connecting, + cotp_connected, + acse_associating, + associated, + closing, + faulted, +}; + +enum class MmsAssociationEventKind : std::uint8_t { + state_changed, + transport_connected, + cotp_connected, + association_accepted, + confirmed_request_sent, + confirmed_result_received, + information_report_received, + unmatched_pdu_received, + disconnected, + cancelled, + timed_out, + faulted, +}; + +struct MmsAssociationEvent final { + MmsAssociationEventKind kind{MmsAssociationEventKind::state_changed}; + MmsAssociationRuntimeState state{MmsAssociationRuntimeState::disconnected}; + std::optional invoke_id; + std::string message; +}; + +struct MmsAssociationOptions final { + std::chrono::milliseconds connect_timeout{5'000}; + std::chrono::milliseconds request_timeout{5'000}; + std::uint8_t tpdu_size_code{0x0AU}; + std::uint32_t presentation_context_id{3U}; + std::size_t maximum_receive_chunks_per_operation{4'096U}; + std::size_t maximum_queued_information_reports{1'024U}; + std::size_t maximum_events{1'024U}; +}; + +struct MmsNegotiatedAssociation final { + std::uint8_t tpdu_size_code{0x0AU}; + std::uint32_t presentation_context_id{3U}; + std::uint32_t maximum_mms_pdu_size{65'000U}; + std::uint32_t maximum_outstanding_calling{10U}; + std::uint32_t maximum_outstanding_called{10U}; + std::uint32_t data_structure_nesting_level{5U}; +}; + +struct MmsConfirmedExchangeResult final { + MmsPduEnvelope envelope; + std::vector presentation_payload; +}; + +class MmsAssociationRuntime final { +public: + explicit MmsAssociationRuntime( + MmsByteTransport& transport, + MmsAssociationOptions options = {}); + ~MmsAssociationRuntime(); + + MmsAssociationRuntime(const MmsAssociationRuntime&) = delete; + MmsAssociationRuntime& operator=(const MmsAssociationRuntime&) = delete; + + void connect( + const MmsEndpoint& endpoint, + std::stop_token stop_token = {}); + void disconnect(std::stop_token stop_token = {}) noexcept; + + [[nodiscard]] MmsConfirmedExchangeResult exchange_confirmed( + std::span presentation_payload, + std::uint32_t expected_invoke_id, + std::stop_token stop_token = {}); + + [[nodiscard]] MmsPduEnvelope poll_once( + std::stop_token stop_token = {}); + [[nodiscard]] bool try_pop_information_report( + std::vector& presentation_payload); + + [[nodiscard]] std::uint32_t next_invoke_id(); + [[nodiscard]] MmsAssociationRuntimeState state() const noexcept { return state_; } + [[nodiscard]] bool associated() const noexcept { + return state_ == MmsAssociationRuntimeState::associated; + } + [[nodiscard]] const MmsEndpoint& endpoint() const noexcept { return endpoint_; } + [[nodiscard]] const MmsNegotiatedAssociation& negotiated() const noexcept { + return negotiated_; + } + [[nodiscard]] const std::deque& events() const noexcept { + return events_; + } + [[nodiscard]] std::size_t queued_information_report_count() const noexcept { + return information_reports_.size(); + } + [[nodiscard]] const std::string& last_fault() const noexcept { return last_fault_; } + +private: + using Clock = MmsByteTransport::Clock; + using Deadline = MmsByteTransport::Deadline; + + [[nodiscard]] Deadline deadline_after(std::chrono::milliseconds timeout) const; + void require_not_cancelled(std::stop_token stop_token) const; + void require_associated() const; + void set_state(MmsAssociationRuntimeState state, std::string message); + void add_event( + MmsAssociationEventKind kind, + std::string message, + std::optional invoke_id = std::nullopt); + void fail(std::string message); + + void send_tpkt_payload( + std::span cotp_payload, + Deadline deadline, + std::stop_token stop_token); + void send_application_payload( + std::span application_payload, + Deadline deadline, + std::stop_token stop_token); + [[nodiscard]] std::vector receive_application_payload( + Deadline deadline, + std::stop_token stop_token); + [[nodiscard]] MmsPduEnvelope route_received_payload( + std::span presentation_payload); + void queue_information_report(std::span payload); + + MmsByteTransport& transport_; + MmsAssociationOptions options_; + MmsAssociationRuntimeState state_{MmsAssociationRuntimeState::disconnected}; + MmsEndpoint endpoint_; + MmsNegotiatedAssociation negotiated_; + MmsInvokeRouter invoke_router_; + osi::TpktStreamDecoder tpkt_decoder_; + std::deque> information_reports_; + std::deque events_; + std::uint32_t next_invoke_id_{}; + std::uint16_t local_cotp_reference_{1U}; + std::uint16_t remote_cotp_reference_{}; + std::string last_fault_; +}; + +} // namespace ar::iec61850::mms diff --git a/include/ariec61850/mms/report_subscription_runtime.hpp b/include/ariec61850/mms/report_subscription_runtime.hpp new file mode 100644 index 000000000..690bb6075 --- /dev/null +++ b/include/ariec61850/mms/report_subscription_runtime.hpp @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "ariec61850/mms/association_runtime.hpp" +#include "ariec61850/mms/reporting.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace ar::iec61850::mms { + +class MmsReportSubscriptionError final : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +enum class MmsReportSubscriptionState : std::uint8_t { + idle, + probing, + reserving, + configuring, + enabling, + active, + stopping, + stopped, + cleanup_required, + faulted, +}; + +enum class MmsReportSubscriptionEventKind : std::uint8_t { + state_changed, + probe_completed, + reservation_acquired, + attribute_written, + enabled, + general_interrogation_sent, + report_received, + report_decode_failed, + disabled, + reservation_released, + cleanup_deferred, + faulted, +}; + +struct MmsReportSubscriptionEvent final { + MmsReportSubscriptionEventKind kind{MmsReportSubscriptionEventKind::state_changed}; + MmsReportSubscriptionState state{MmsReportSubscriptionState::idle}; + std::string message; +}; + +struct MmsReportSubscriptionOptions final { + bool trigger_general_interrogation{true}; + bool reserve_unbuffered_rcb{true}; + bool write_data_set_reference{false}; + bool write_trigger_options{false}; + bool write_optional_fields{false}; + bool allow_reenable_caller_owned{false}; + std::vector trigger_options; + std::vector optional_fields; + std::string data_set_reference; + std::size_t maximum_events{1'024U}; + MmsOfflineReportMonitorOptions monitor_options{}; +}; + +struct MmsReportSubscriptionSnapshot final { + MmsReportSubscriptionState state{MmsReportSubscriptionState::idle}; + bool enabled_by_runtime{}; + bool reservation_touched{}; + bool cleanup_required{}; + std::uint64_t received_reports{}; + std::uint64_t decode_failures{}; + std::optional last_rcb_state; + std::vector streams; + std::vector events; +}; + +class MmsReportSubscriptionRuntime final { +public: + MmsReportSubscriptionRuntime( + MmsAssociationRuntime& association, + MmsReportControlCandidate candidate, + MmsDataSetDirectoryResponse directory, + MmsReportSubscriptionOptions options = {}); + + void start(std::stop_token stop_token = {}); + void stop(std::stop_token stop_token = {}) noexcept; + [[nodiscard]] bool poll_once(std::stop_token stop_token = {}); + void run(std::stop_token stop_token); + [[nodiscard]] std::size_t drain_queued_reports(); + [[nodiscard]] bool retry_cleanup(std::stop_token stop_token = {}) noexcept; + + [[nodiscard]] MmsReportSubscriptionSnapshot snapshot() const; + [[nodiscard]] MmsReportSubscriptionState state() const noexcept { return state_; } + [[nodiscard]] bool active() const noexcept { + return state_ == MmsReportSubscriptionState::active; + } + +private: + [[nodiscard]] std::vector probe_attributes() const; + [[nodiscard]] MmsReportControlState probe(std::stop_token stop_token); + void write_attribute( + const std::string& attribute, + MmsDataValue value, + std::stop_token stop_token); + [[nodiscard]] bool try_write_attribute_noexcept( + const std::string& attribute, + MmsDataValue value, + std::stop_token stop_token) noexcept; + void ingest_report(std::span payload); + void set_state(MmsReportSubscriptionState state, std::string message); + void add_event(MmsReportSubscriptionEventKind kind, std::string message); + void fail(std::string message); + + MmsAssociationRuntime& association_; + MmsReportControlCandidate candidate_; + MmsDataSetDirectoryResponse directory_; + MmsReportSubscriptionOptions options_; + MmsReportSubscriptionState state_{MmsReportSubscriptionState::idle}; + MmsOfflineReportMonitor monitor_; + std::vector events_; + std::optional last_rcb_state_; + bool enabled_by_runtime_{}; + bool reservation_touched_{}; + bool cleanup_required_{}; + std::uint64_t received_reports_{}; + std::uint64_t decode_failures_{}; +}; + +} // namespace ar::iec61850::mms diff --git a/src/mms/association_runtime.cpp b/src/mms/association_runtime.cpp new file mode 100644 index 000000000..9d5ba26d5 --- /dev/null +++ b/src/mms/association_runtime.cpp @@ -0,0 +1,471 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "ariec61850/mms/association_runtime.hpp" + +#include "ariec61850/acse/association.hpp" +#include "ariec61850/osi/cotp.hpp" + +#include +#include +#include +#include +#include + +namespace ar::iec61850::mms { +namespace { + +[[nodiscard]] std::uint8_t negotiated_tpdu_size( + const osi::CotpTpdu& confirm, + const std::uint8_t fallback) { + const auto value = confirm.parameter(osi::CotpFrameCodec::tpdu_size_parameter); + if (!value || value->size() != 1U) { + return fallback; + } + static_cast(osi::CotpFrameCodec::tpdu_size_bytes((*value)[0])); + return (*value)[0]; +} + + + +} // namespace + +MmsAssociationRuntime::MmsAssociationRuntime( + MmsByteTransport& transport, + MmsAssociationOptions options) + : transport_{transport}, options_{std::move(options)} { + if (options_.connect_timeout <= std::chrono::milliseconds::zero() || + options_.request_timeout <= std::chrono::milliseconds::zero() || + options_.maximum_receive_chunks_per_operation == 0U || + options_.maximum_queued_information_reports == 0U || + options_.maximum_events == 0U) { + throw std::invalid_argument("MMS association runtime limits are invalid."); + } + static_cast(osi::CotpFrameCodec::tpdu_size_bytes(options_.tpdu_size_code)); + if (options_.presentation_context_id == 0U) { + throw std::invalid_argument("MMS presentation context ID must be positive."); + } + negotiated_.tpdu_size_code = options_.tpdu_size_code; + negotiated_.presentation_context_id = options_.presentation_context_id; +} + +MmsAssociationRuntime::~MmsAssociationRuntime() { + disconnect(); +} + +MmsAssociationRuntime::Deadline MmsAssociationRuntime::deadline_after( + const std::chrono::milliseconds timeout) const { + return Clock::now() + timeout; +} + +void MmsAssociationRuntime::require_not_cancelled( + const std::stop_token stop_token) const { + if (stop_token.stop_requested()) { + throw MmsTransportCancelledError("MMS association operation was cancelled."); + } +} + +void MmsAssociationRuntime::require_associated() const { + if (!associated() || !transport_.connected()) { + throw MmsAssociationRuntimeError("MMS association is not active."); + } +} + +void MmsAssociationRuntime::set_state( + const MmsAssociationRuntimeState state, + std::string message) { + state_ = state; + add_event(MmsAssociationEventKind::state_changed, std::move(message)); +} + +void MmsAssociationRuntime::add_event( + const MmsAssociationEventKind kind, + std::string message, + const std::optional invoke_id) { + if (events_.size() >= options_.maximum_events) { + events_.pop_front(); + } + events_.push_back(MmsAssociationEvent{kind, state_, invoke_id, std::move(message)}); +} + +void MmsAssociationRuntime::fail(std::string message) { + last_fault_ = message; + state_ = MmsAssociationRuntimeState::faulted; + add_event(MmsAssociationEventKind::faulted, std::move(message)); +} + +void MmsAssociationRuntime::send_tpkt_payload( + const std::span cotp_payload, + const Deadline deadline, + const std::stop_token stop_token) { + require_not_cancelled(stop_token); + const auto frame = osi::TpktFrameCodec::encode(cotp_payload); + transport_.send(frame, deadline, stop_token); +} + +void MmsAssociationRuntime::send_application_payload( + const std::span application_payload, + const Deadline deadline, + const std::stop_token stop_token) { + const auto segments = osi::CotpFrameCodec::encode_data_segments( + application_payload, negotiated_.tpdu_size_code); + for (const auto& segment : segments) { + send_tpkt_payload(segment, deadline, stop_token); + } +} + +std::vector MmsAssociationRuntime::receive_application_payload( + const Deadline deadline, + const std::stop_token stop_token) { + osi::CotpDataReassembler reassembler; + std::size_t receive_chunks = 0U; + while (!reassembler.is_complete()) { + require_not_cancelled(stop_token); + if (receive_chunks >= options_.maximum_receive_chunks_per_operation) { + throw MmsAssociationRuntimeError( + "MMS receive chunk limit exceeded before a complete COTP payload arrived."); + } + auto bytes = transport_.receive(deadline, stop_token); + ++receive_chunks; + if (bytes.empty()) { + throw MmsAssociationRuntimeError("MMS transport returned an empty receive chunk."); + } + tpkt_decoder_.append(bytes); + osi::TpktFrame frame; + while (tpkt_decoder_.try_pop(frame)) { + const auto tpdu = osi::CotpFrameCodec::decode(frame.payload); + if (tpdu.kind == osi::CotpTpduKind::disconnect_request) { + throw MmsAssociationRuntimeError("Remote endpoint requested COTP disconnect."); + } + if (tpdu.kind == osi::CotpTpduKind::error) { + throw MmsAssociationRuntimeError("Remote endpoint returned a COTP error TPDU."); + } + if (tpdu.kind != osi::CotpTpduKind::data) { + throw MmsAssociationRuntimeError( + "Expected COTP Data TPDU while receiving an application payload."); + } + reassembler.append(tpdu); + if (reassembler.is_complete()) { + break; + } + } + } + return reassembler.complete(); +} + +void MmsAssociationRuntime::connect( + const MmsEndpoint& endpoint, + const std::stop_token stop_token) { + if (endpoint.host.empty()) { + throw std::invalid_argument("MMS endpoint host must not be empty."); + } + if (associated()) { + throw MmsAssociationRuntimeError("MMS association is already active."); + } + + disconnect(); + endpoint_ = endpoint; + last_fault_.clear(); + invoke_router_.clear(); + information_reports_.clear(); + tpkt_decoder_.reset(); + next_invoke_id_ = 0U; + negotiated_ = {}; + negotiated_.tpdu_size_code = options_.tpdu_size_code; + negotiated_.presentation_context_id = options_.presentation_context_id; + + try { + require_not_cancelled(stop_token); + const auto deadline = deadline_after(options_.connect_timeout); + set_state(MmsAssociationRuntimeState::transport_connecting, + "Connecting byte transport to " + endpoint.host + ":" + + std::to_string(endpoint.port) + "."); + transport_.connect(endpoint, deadline, stop_token); + if (!transport_.connected()) { + throw MmsAssociationRuntimeError( + "Byte transport returned without entering the connected state."); + } + state_ = MmsAssociationRuntimeState::transport_connected; + add_event(MmsAssociationEventKind::transport_connected, + "Byte transport connected."); + + state_ = MmsAssociationRuntimeState::cotp_connecting; + add_event(MmsAssociationEventKind::state_changed, + "Sending COTP Connection Request."); + const auto connection_request = osi::CotpFrameCodec::encode_default_connection_request(); + send_tpkt_payload(connection_request, deadline, stop_token); + + std::size_t chunks = 0U; + std::optional connection_confirm; + while (!connection_confirm) { + require_not_cancelled(stop_token); + if (chunks >= options_.maximum_receive_chunks_per_operation) { + throw MmsAssociationRuntimeError( + "COTP Connection Confirm did not arrive within the receive bound."); + } + auto bytes = transport_.receive(deadline, stop_token); + ++chunks; + if (bytes.empty()) { + throw MmsAssociationRuntimeError( + "MMS transport returned an empty chunk during COTP connect."); + } + tpkt_decoder_.append(bytes); + osi::TpktFrame frame; + while (tpkt_decoder_.try_pop(frame)) { + auto tpdu = osi::CotpFrameCodec::decode(frame.payload); + if (tpdu.kind == osi::CotpTpduKind::connection_confirm) { + connection_confirm = std::move(tpdu); + break; + } + if (tpdu.kind == osi::CotpTpduKind::error || + tpdu.kind == osi::CotpTpduKind::disconnect_request) { + throw MmsAssociationRuntimeError( + "Remote endpoint rejected the COTP connection."); + } + throw MmsAssociationRuntimeError( + "Unexpected TPDU received while waiting for COTP Connection Confirm."); + } + } + + if (connection_confirm->destination_reference != local_cotp_reference_) { + throw MmsAssociationRuntimeError( + "COTP Connection Confirm destination reference does not match the request."); + } + remote_cotp_reference_ = connection_confirm->source_reference; + negotiated_.tpdu_size_code = negotiated_tpdu_size( + *connection_confirm, options_.tpdu_size_code); + state_ = MmsAssociationRuntimeState::cotp_connected; + add_event(MmsAssociationEventKind::cotp_connected, + "COTP connected with TPDU size code " + + std::to_string(negotiated_.tpdu_size_code) + "."); + + state_ = MmsAssociationRuntimeState::acse_associating; + add_event(MmsAssociationEventKind::state_changed, + "Sending ISO Session/Presentation/ACSE association request."); + const auto association_request = + acse::AcseAssociationCodec::build_default_association_request(); + send_application_payload(association_request, deadline, stop_token); + const auto association_payload = + receive_application_payload(deadline, stop_token); + const auto response = + acse::AcseAssociationCodec::decode_association_response(association_payload); + if (!response.aare.accepted()) { + throw MmsAssociationRuntimeError( + "ACSE association was rejected with result=" + + std::to_string(response.aare.result) + "."); + } + if (!response.aare.user_information) { + throw MmsAssociationRuntimeError( + "Accepted ACSE response did not contain MMS Initiate response data."); + } + const auto initiate = MmsPduCodec::decode_initiate_response( + response.aare.user_information->single_asn1_type); + negotiated_.maximum_mms_pdu_size = initiate.negotiated_maximum_mms_pdu_size; + negotiated_.maximum_outstanding_calling = + initiate.negotiated_maximum_outstanding_calling; + negotiated_.maximum_outstanding_called = + initiate.negotiated_maximum_outstanding_called; + negotiated_.data_structure_nesting_level = + initiate.negotiated_data_structure_nesting_level; + negotiated_.presentation_context_id = options_.presentation_context_id; + + state_ = MmsAssociationRuntimeState::associated; + add_event(MmsAssociationEventKind::association_accepted, + "MMS association accepted; maximum PDU=" + + std::to_string(negotiated_.maximum_mms_pdu_size) + "."); + } catch (const MmsTransportCancelledError& exception) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::cancelled, exception.what()); + transport_.close(); + throw; + } catch (const MmsTransportTimeoutError& exception) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::timed_out, exception.what()); + transport_.close(); + throw; + } catch (const std::exception& exception) { + if (stop_token.stop_requested()) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::cancelled, exception.what()); + } else { + fail(exception.what()); + } + transport_.close(); + throw; + } +} + +void MmsAssociationRuntime::disconnect(const std::stop_token stop_token) noexcept { + if (state_ == MmsAssociationRuntimeState::disconnected && + !transport_.connected()) { + return; + } + state_ = MmsAssociationRuntimeState::closing; + add_event(MmsAssociationEventKind::state_changed, + "Closing MMS association and byte transport."); + try { + if (transport_.connected() && remote_cotp_reference_ != 0U) { + const auto deadline = deadline_after(options_.request_timeout); + const auto disconnect_request = osi::CotpFrameCodec::encode_disconnect_request( + remote_cotp_reference_, local_cotp_reference_); + send_tpkt_payload(disconnect_request, deadline, stop_token); + } + } catch (...) { + } + transport_.close(); + invoke_router_.clear(); + information_reports_.clear(); + tpkt_decoder_.reset(); + remote_cotp_reference_ = 0U; + state_ = MmsAssociationRuntimeState::disconnected; + add_event(MmsAssociationEventKind::disconnected, + "MMS association disconnected."); +} + +MmsConfirmedExchangeResult MmsAssociationRuntime::exchange_confirmed( + const std::span presentation_payload, + const std::uint32_t expected_invoke_id, + const std::stop_token stop_token) { + require_associated(); + if (expected_invoke_id == 0U || + expected_invoke_id > MmsPduCodec::maximum_invoke_id) { + throw std::invalid_argument("Expected MMS invoke ID is outside the supported range."); + } + const auto request_envelope = MmsPduCodec::decode_envelope(presentation_payload); + if (request_envelope.kind != MmsPduKind::confirmed_request || + !request_envelope.matches_invoke(expected_invoke_id)) { + throw std::invalid_argument( + "Confirmed exchange payload does not contain the expected invoke ID."); + } + + MmsPduEnvelope queued; + if (invoke_router_.try_dequeue(expected_invoke_id, queued)) { + return {std::move(queued), {}}; + } + + const auto deadline = deadline_after(options_.request_timeout); + try { + send_application_payload(presentation_payload, deadline, stop_token); + add_event(MmsAssociationEventKind::confirmed_request_sent, + "Confirmed MMS request sent.", expected_invoke_id); + + for (std::size_t index = 0U; + index < options_.maximum_receive_chunks_per_operation; + ++index) { + auto received = receive_application_payload(deadline, stop_token); + auto envelope = route_received_payload(received); + if (envelope.confirmed_result() && + envelope.matches_invoke(expected_invoke_id)) { + MmsPduEnvelope matched; + if (!invoke_router_.try_dequeue(expected_invoke_id, matched)) { + throw MmsAssociationRuntimeError( + "Matched MMS response was not available in the invoke router."); + } + add_event(MmsAssociationEventKind::confirmed_result_received, + "Confirmed MMS result received.", expected_invoke_id); + return {std::move(matched), std::move(received)}; + } + } + throw MmsAssociationRuntimeError( + "MMS confirmed exchange exceeded the bounded receive iteration count."); + } catch (const MmsTransportCancelledError& exception) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::cancelled, + exception.what(), expected_invoke_id); + throw; + } catch (const MmsTransportTimeoutError& exception) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::timed_out, + exception.what(), expected_invoke_id); + throw; + } catch (const std::exception& exception) { + if (stop_token.stop_requested()) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::cancelled, + exception.what(), expected_invoke_id); + } else { + fail(exception.what()); + } + throw; + } +} + +MmsPduEnvelope MmsAssociationRuntime::poll_once( + const std::stop_token stop_token) { + require_associated(); + try { + auto payload = receive_application_payload( + deadline_after(options_.request_timeout), stop_token); + return route_received_payload(payload); + } catch (const MmsTransportCancelledError& exception) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::cancelled, exception.what()); + throw; + } catch (const MmsTransportTimeoutError& exception) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::timed_out, exception.what()); + throw; + } catch (const std::exception& exception) { + if (stop_token.stop_requested()) { + state_ = MmsAssociationRuntimeState::faulted; + last_fault_ = exception.what(); + add_event(MmsAssociationEventKind::cancelled, exception.what()); + } else { + fail(exception.what()); + } + throw; + } +} + +MmsPduEnvelope MmsAssociationRuntime::route_received_payload( + const std::span presentation_payload) { + auto envelope = MmsPduCodec::decode_envelope(presentation_payload); + if (envelope.information_report) { + queue_information_report(presentation_payload); + add_event(MmsAssociationEventKind::information_report_received, + "MMS InformationReport queued."); + return envelope; + } + const auto route = invoke_router_.route(presentation_payload); + if (route.action == MmsInvokeRouteAction::queued_unmatched) { + add_event(MmsAssociationEventKind::unmatched_pdu_received, + "Unmatched MMS PDU queued.", envelope.invoke_id); + } + return envelope; +} + +void MmsAssociationRuntime::queue_information_report( + const std::span payload) { + if (information_reports_.size() >= + options_.maximum_queued_information_reports) { + information_reports_.pop_front(); + } + information_reports_.emplace_back(payload.begin(), payload.end()); +} + +bool MmsAssociationRuntime::try_pop_information_report( + std::vector& presentation_payload) { + if (information_reports_.empty()) { + return false; + } + presentation_payload = std::move(information_reports_.front()); + information_reports_.pop_front(); + return true; +} + +std::uint32_t MmsAssociationRuntime::next_invoke_id() { + if (next_invoke_id_ >= MmsPduCodec::maximum_invoke_id) { + next_invoke_id_ = 0U; + } + ++next_invoke_id_; + return next_invoke_id_; +} + +} // namespace ar::iec61850::mms diff --git a/src/mms/report_subscription_runtime.cpp b/src/mms/report_subscription_runtime.cpp new file mode 100644 index 000000000..4dd92ad5d --- /dev/null +++ b/src/mms/report_subscription_runtime.cpp @@ -0,0 +1,412 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "ariec61850/mms/report_subscription_runtime.hpp" + +#include "ariec61850/mms/services.hpp" + +#include +#include +#include +#include + +namespace ar::iec61850::mms { +namespace { + +[[nodiscard]] bool contains_attribute( + const MmsReportControlCandidate& candidate, + const std::string& attribute) { + return std::any_of( + candidate.attributes.begin(), candidate.attributes.end(), + [&attribute](const std::string& item) { + return item == attribute; + }); +} + +[[nodiscard]] std::span response_payload( + const MmsConfirmedExchangeResult& exchange) { + if (!exchange.presentation_payload.empty()) { + return exchange.presentation_payload; + } + return exchange.envelope.mms_payload; +} + +} // namespace + +MmsReportSubscriptionRuntime::MmsReportSubscriptionRuntime( + MmsAssociationRuntime& association, + MmsReportControlCandidate candidate, + MmsDataSetDirectoryResponse directory, + MmsReportSubscriptionOptions options) + : association_{association}, + candidate_{std::move(candidate)}, + directory_{std::move(directory)}, + options_{std::move(options)}, + monitor_{options_.monitor_options} { + if (candidate_.domain.empty() || candidate_.logical_node.empty() || + candidate_.name.empty()) { + throw std::invalid_argument( + "Report subscription requires a complete RCB candidate identity."); + } + if (options_.maximum_events == 0U) { + throw std::invalid_argument( + "Report subscription event limit must be positive."); + } +} + +std::vector MmsReportSubscriptionRuntime::probe_attributes() const { + static const std::array preferred{ + "RptID", "RptEna", "DatSet", "ConfRev", "OptFlds", + "BufTm", "SqNum", "TrgOps", "IntgPd", "GI", + "Resv", "ResvTms", "Owner", "EntryID", "TimeOfEntry"}; + std::vector attributes; + for (const auto* name : preferred) { + if (contains_attribute(candidate_, name)) { + attributes.emplace_back(name); + } + } + if (attributes.empty()) { + throw MmsReportSubscriptionError( + "RCB candidate has no readable attributes for a live-state probe."); + } + return attributes; +} + +MmsReportControlState MmsReportSubscriptionRuntime::probe( + const std::stop_token stop_token) { + const auto attributes = probe_attributes(); + const auto invoke_id = association_.next_invoke_id(); + const auto request = MmsReportControlStateMapper::build_read_request( + invoke_id, candidate_, attributes); + const auto encoded = MmsServiceCodec::encode_read_request_p_data( + request, association_.negotiated().presentation_context_id); + const auto exchange = association_.exchange_confirmed( + encoded, invoke_id, stop_token); + if (exchange.envelope.kind == MmsPduKind::confirmed_error) { + throw MmsReportSubscriptionError( + "RCB live-state probe returned a confirmed MMS error."); + } + const auto response = MmsServiceCodec::decode_read_response( + response_payload(exchange), invoke_id); + auto mapped = MmsReportControlStateMapper::map_read_response( + candidate_, attributes, response, &directory_, false); + last_rcb_state_ = mapped; + add_event(MmsReportSubscriptionEventKind::probe_completed, + "RCB live-state probe completed: " + mapped.availability_reason); + return mapped; +} + +void MmsReportSubscriptionRuntime::write_attribute( + const std::string& attribute, + MmsDataValue value, + const std::stop_token stop_token) { + if (!contains_attribute(candidate_, attribute)) { + throw MmsReportSubscriptionError( + "RCB does not expose writable attribute " + attribute + "."); + } + const auto invoke_id = association_.next_invoke_id(); + MmsWriteRequest request; + request.invoke_id = invoke_id; + request.variables.push_back(candidate_.attribute_object_name(attribute)); + request.values.push_back(std::move(value)); + const auto encoded = MmsServiceCodec::encode_write_request_p_data( + request, association_.negotiated().presentation_context_id); + const auto exchange = association_.exchange_confirmed( + encoded, invoke_id, stop_token); + if (exchange.envelope.kind == MmsPduKind::confirmed_error) { + throw MmsReportSubscriptionError( + "RCB attribute write returned a confirmed MMS error: " + attribute + "."); + } + const auto response = MmsServiceCodec::decode_write_response( + response_payload(exchange), invoke_id); + if (response.results.size() != 1U || !response.results.front().success) { + throw MmsReportSubscriptionError( + "RCB attribute write failed: " + attribute + "."); + } + add_event(MmsReportSubscriptionEventKind::attribute_written, + "RCB attribute written: " + attribute + "."); +} + +bool MmsReportSubscriptionRuntime::try_write_attribute_noexcept( + const std::string& attribute, + MmsDataValue value, + const std::stop_token stop_token) noexcept { + try { + write_attribute(attribute, std::move(value), stop_token); + return true; + } catch (const std::exception& exception) { + add_event(MmsReportSubscriptionEventKind::cleanup_deferred, + "RCB cleanup write failed for " + attribute + ": " + + exception.what()); + return false; + } catch (...) { + add_event(MmsReportSubscriptionEventKind::cleanup_deferred, + "RCB cleanup write failed unexpectedly for " + attribute + "."); + return false; + } +} + +void MmsReportSubscriptionRuntime::start( + const std::stop_token stop_token) { + if (!association_.associated()) { + throw MmsReportSubscriptionError( + "Cannot start report subscription without an active MMS association."); + } + if (active()) { + throw MmsReportSubscriptionError("Report subscription is already active."); + } + + enabled_by_runtime_ = false; + reservation_touched_ = false; + cleanup_required_ = false; + monitor_.clear(); + received_reports_ = 0U; + decode_failures_ = 0U; + + try { + set_state(MmsReportSubscriptionState::probing, + "Probing RCB state before any write."); + const auto current = probe(stop_token); + const auto enabled_elsewhere = current.report_enabled.value_or(false) && + current.availability != MmsRcbAvailability::used_by_caller; + if (enabled_elsewhere) { + throw MmsReportSubscriptionError( + "RCB is already enabled and is treated as owned by another session."); + } + if (current.availability == MmsRcbAvailability::in_use) { + throw MmsReportSubscriptionError( + "RCB is reserved or enabled by another session."); + } + if (current.report_enabled.value_or(false) && + !options_.allow_reenable_caller_owned) { + throw MmsReportSubscriptionError( + "RCB is already enabled; explicit caller-owned re-enable permission is required."); + } + + if (!candidate_.buffered && options_.reserve_unbuffered_rcb && + contains_attribute(candidate_, "Resv")) { + set_state(MmsReportSubscriptionState::reserving, + "Reserving unbuffered RCB."); + write_attribute("Resv", MmsDataValue::boolean(true), stop_token); + reservation_touched_ = true; + add_event(MmsReportSubscriptionEventKind::reservation_acquired, + "URCB reservation acquired."); + } + + set_state(MmsReportSubscriptionState::configuring, + "Applying requested RCB configuration."); + if (options_.write_data_set_reference) { + if (options_.data_set_reference.empty()) { + throw MmsReportSubscriptionError( + "DataSet write was requested without a DataSet reference."); + } + write_attribute( + "DatSet", + MmsDataValue::visible_string(options_.data_set_reference), + stop_token); + } + if (options_.write_trigger_options) { + write_attribute( + "TrgOps", + MmsDataValue::bit_string(0U, options_.trigger_options), + stop_token); + } + if (options_.write_optional_fields) { + write_attribute( + "OptFlds", + MmsDataValue::bit_string(0U, options_.optional_fields), + stop_token); + } + + set_state(MmsReportSubscriptionState::enabling, + "Enabling RCB with RptEna=true."); + write_attribute("RptEna", MmsDataValue::boolean(true), stop_token); + enabled_by_runtime_ = true; + add_event(MmsReportSubscriptionEventKind::enabled, + "RCB enabled by this runtime."); + + if (options_.trigger_general_interrogation && + contains_attribute(candidate_, "GI")) { + try { + write_attribute("GI", MmsDataValue::boolean(true), stop_token); + add_event(MmsReportSubscriptionEventKind::general_interrogation_sent, + "General interrogation requested after RCB enable."); + } catch (const std::exception& exception) { + add_event(MmsReportSubscriptionEventKind::cleanup_deferred, + "RCB remains enabled, but GI write failed: " + + std::string{exception.what()}); + } + } + + set_state(MmsReportSubscriptionState::active, + "Persistent report subscription is active."); + } catch (const std::exception& exception) { + if (association_.associated()) { + if (enabled_by_runtime_) { + const auto disabled = try_write_attribute_noexcept( + "RptEna", MmsDataValue::boolean(false), stop_token); + enabled_by_runtime_ = !disabled; + } + if (reservation_touched_) { + const auto released = try_write_attribute_noexcept( + "Resv", MmsDataValue::boolean(false), stop_token); + reservation_touched_ = !released; + } + } + cleanup_required_ = enabled_by_runtime_ || reservation_touched_; + fail(exception.what()); + throw; + } +} + +void MmsReportSubscriptionRuntime::stop( + const std::stop_token stop_token) noexcept { + if (state_ == MmsReportSubscriptionState::idle || + state_ == MmsReportSubscriptionState::stopped) { + return; + } + set_state(MmsReportSubscriptionState::stopping, + "Stopping persistent report subscription."); + + if (!association_.associated()) { + cleanup_required_ = enabled_by_runtime_ || reservation_touched_; + if (cleanup_required_) { + state_ = MmsReportSubscriptionState::cleanup_required; + add_event(MmsReportSubscriptionEventKind::cleanup_deferred, + "Association is unavailable; RCB cleanup must be retried after reconnect."); + } else { + set_state(MmsReportSubscriptionState::stopped, + "Report subscription stopped without pending cleanup."); + } + return; + } + + bool cleanup_ok = true; + if (enabled_by_runtime_) { + if (try_write_attribute_noexcept( + "RptEna", MmsDataValue::boolean(false), stop_token)) { + enabled_by_runtime_ = false; + add_event(MmsReportSubscriptionEventKind::disabled, + "RCB disabled by this runtime."); + } else { + cleanup_ok = false; + } + } + if (reservation_touched_) { + if (try_write_attribute_noexcept( + "Resv", MmsDataValue::boolean(false), stop_token)) { + reservation_touched_ = false; + add_event(MmsReportSubscriptionEventKind::reservation_released, + "URCB reservation released."); + } else { + cleanup_ok = false; + } + } + + cleanup_required_ = !cleanup_ok || enabled_by_runtime_ || reservation_touched_; + if (cleanup_required_) { + state_ = MmsReportSubscriptionState::cleanup_required; + add_event(MmsReportSubscriptionEventKind::cleanup_deferred, + "One or more RCB cleanup writes remain pending."); + } else { + set_state(MmsReportSubscriptionState::stopped, + "Report subscription stopped and RCB cleanup completed."); + } +} + +bool MmsReportSubscriptionRuntime::poll_once( + const std::stop_token stop_token) { + if (!active()) { + throw MmsReportSubscriptionError( + "Report polling requires an active subscription."); + } + const auto envelope = association_.poll_once(stop_token); + const auto ingested = drain_queued_reports(); + return envelope.information_report || ingested != 0U; +} + + +void MmsReportSubscriptionRuntime::run(const std::stop_token stop_token) { + if (!active()) { + throw MmsReportSubscriptionError( + "Persistent report loop requires an active subscription."); + } + while (!stop_token.stop_requested() && active()) { + static_cast(poll_once(stop_token)); + } +} + +bool MmsReportSubscriptionRuntime::retry_cleanup( + const std::stop_token stop_token) noexcept { + if (!cleanup_required_) { + return true; + } + if (!association_.associated()) { + return false; + } + stop(stop_token); + return !cleanup_required_; +} + +std::size_t MmsReportSubscriptionRuntime::drain_queued_reports() { + std::size_t count = 0U; + std::vector payload; + while (association_.try_pop_information_report(payload)) { + ingest_report(payload); + ++count; + } + return count; +} + +void MmsReportSubscriptionRuntime::ingest_report( + const std::span payload) { + try { + const auto report = MmsInformationReportCodec::decode(payload); + const auto frame = MmsReportFrameMapper::map(report, directory_.members); + static_cast(monitor_.ingest(frame)); + ++received_reports_; + add_event(MmsReportSubscriptionEventKind::report_received, + "InformationReport mapped to " + frame.routing_key() + "."); + } catch (const std::exception& exception) { + ++decode_failures_; + add_event(MmsReportSubscriptionEventKind::report_decode_failed, + "InformationReport decode failed: " + + std::string{exception.what()}); + } +} + +void MmsReportSubscriptionRuntime::set_state( + const MmsReportSubscriptionState state, + std::string message) { + state_ = state; + add_event(MmsReportSubscriptionEventKind::state_changed, std::move(message)); +} + +void MmsReportSubscriptionRuntime::add_event( + const MmsReportSubscriptionEventKind kind, + std::string message) { + if (events_.size() >= options_.maximum_events) { + events_.erase(events_.begin()); + } + events_.push_back(MmsReportSubscriptionEvent{kind, state_, std::move(message)}); +} + +void MmsReportSubscriptionRuntime::fail(std::string message) { + state_ = MmsReportSubscriptionState::faulted; + add_event(MmsReportSubscriptionEventKind::faulted, std::move(message)); +} + +MmsReportSubscriptionSnapshot MmsReportSubscriptionRuntime::snapshot() const { + MmsReportSubscriptionSnapshot result; + result.state = state_; + result.enabled_by_runtime = enabled_by_runtime_; + result.reservation_touched = reservation_touched_; + result.cleanup_required = cleanup_required_; + result.received_reports = received_reports_; + result.decode_failures = decode_failures_; + result.last_rcb_state = last_rcb_state_; + result.streams = monitor_.snapshots(); + result.events = events_; + return result; +} + +} // namespace ar::iec61850::mms diff --git a/tests/test_mms_runtime.cpp b/tests/test_mms_runtime.cpp new file mode 100644 index 000000000..7be150d15 --- /dev/null +++ b/tests/test_mms_runtime.cpp @@ -0,0 +1,407 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "ariec61850/acse/association.hpp" +#include "ariec61850/mms/association_runtime.hpp" +#include "ariec61850/mms/report_subscription_runtime.hpp" +#include "ariec61850/mms/reporting.hpp" +#include "ariec61850/mms/services.hpp" +#include "ariec61850/osi/cotp.hpp" +#include "ariec61850/osi/tpkt.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace ar::iec61850; +using ByteVector = std::vector; + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + throw std::runtime_error( \ + std::string{"CHECK failed: "} + #condition + \ + " at " + __FILE__ + ":" + std::to_string(__LINE__)); \ + } \ + } while (false) + +template +void check_throws(Callable&& callable) { + try { + std::invoke(std::forward(callable)); + } catch (const Exception&) { + return; + } + throw std::runtime_error("Expected exception was not thrown."); +} + +class ScriptedTransport final : public mms::MmsByteTransport { +public: + void connect( + const mms::MmsEndpoint& endpoint, + Deadline, + std::stop_token stop_token) override { + if (stop_token.stop_requested()) { + throw std::runtime_error("scripted connect cancelled"); + } + endpoint_ = endpoint; + connected_ = true; + ++connect_count_; + } + + void send( + const std::span bytes, + Deadline, + std::stop_token stop_token) override { + if (stop_token.stop_requested()) { + throw std::runtime_error("scripted send cancelled"); + } + if (!connected_) { + throw std::runtime_error("scripted transport is disconnected"); + } + sent_.emplace_back(bytes.begin(), bytes.end()); + } + + [[nodiscard]] ByteVector receive( + Deadline, + std::stop_token stop_token) override { + if (stop_token.stop_requested()) { + throw std::runtime_error("scripted receive cancelled"); + } + if (!connected_) { + throw std::runtime_error("scripted transport is disconnected"); + } + if (receive_queue_.empty()) { + throw mms::MmsTransportTimeoutError("scripted receive timeout"); + } + auto value = std::move(receive_queue_.front()); + receive_queue_.pop_front(); + return value; + } + + void close() noexcept override { + connected_ = false; + ++close_count_; + } + + [[nodiscard]] bool connected() const noexcept override { return connected_; } + + void push_receive(ByteVector bytes) { + receive_queue_.push_back(std::move(bytes)); + } + + [[nodiscard]] const std::vector& sent() const noexcept { return sent_; } + [[nodiscard]] std::size_t connect_count() const noexcept { return connect_count_; } + [[nodiscard]] std::size_t close_count() const noexcept { return close_count_; } + +private: + mms::MmsEndpoint endpoint_; + bool connected_{}; + std::size_t connect_count_{}; + std::size_t close_count_{}; + std::deque receive_queue_; + std::vector sent_; +}; + +[[nodiscard]] ByteVector wrap_application( + const std::span application) { + const auto cotp = osi::CotpFrameCodec::encode_data(application); + return osi::TpktFrameCodec::encode(cotp); +} + +void queue_handshake(ScriptedTransport& transport) { + const auto confirm = osi::CotpFrameCodec::encode_connection_confirm( + 0x0001U, 0x2345U, 0x0AU); + transport.push_receive(osi::TpktFrameCodec::encode(confirm)); + + const auto request_bytes = acse::AcseAssociationCodec::build_default_association_request(); + const auto request = acse::AcseAssociationCodec::decode_association_request(request_bytes); + const auto response = acse::AcseAssociationCodec::build_accept_response(request); + transport.push_receive(wrap_application(response.payload)); +} + +[[nodiscard]] mms::MmsInformationReport make_report() { + const ByteVector options{0x7FU, 0x80U}; + const ByteVector time{0x01U, 0x02U, 0x03U, 0x04U, 0x05U, 0x06U}; + const ByteVector entry{0U, 1U, 2U, 3U, 4U, 5U, 6U, 7U}; + const ByteVector inclusion{0x80U}; + const ByteVector reason{0x80U}; + mms::MmsInformationReport report; + auto add = [&report](mms::MmsDataValue value) { + report.items.push_back({report.items.size(), std::move(value), std::nullopt}); + }; + add(mms::MmsDataValue::visible_string("RPT-A")); + add(mms::MmsDataValue::bit_string(6U, options)); + add(mms::MmsDataValue::unsigned_integer(1U)); + add(mms::MmsDataValue::binary_time(time)); + add(mms::MmsDataValue::visible_string("LD0/LLN0.DataSet")); + add(mms::MmsDataValue::boolean(false)); + add(mms::MmsDataValue::octet_string(entry)); + add(mms::MmsDataValue::unsigned_integer(1U)); + add(mms::MmsDataValue::bit_string(7U, inclusion)); + add(mms::MmsDataValue::boolean(true)); + add(mms::MmsDataValue::visible_string("LD0/PTOC1.Str.stVal")); + add(mms::MmsDataValue::bit_string(2U, reason)); + return report; +} + +void association_lifecycle_routes_reports_and_confirmed_results() { + ScriptedTransport transport; + queue_handshake(transport); + mms::MmsAssociationRuntime runtime{transport}; + runtime.connect({"127.0.0.1", 102U}); + CHECK(runtime.associated()); + CHECK(runtime.negotiated().maximum_mms_pdu_size == 65'000U); + CHECK(transport.connect_count() == 1U); + + const auto report = mms::MmsInformationReportCodec::encode_p_data(make_report()); + transport.push_receive(wrap_application(report)); + + const auto invoke_id = runtime.next_invoke_id(); + mms::MmsReadRequest request; + request.invoke_id = invoke_id; + request.variables.push_back( + mms::MmsObjectName::domain_specific("LD0", "LLN0$ST$Mod$stVal")); + const auto request_bytes = mms::MmsServiceCodec::encode_read_request_p_data(request); + + mms::MmsReadResponse response; + response.invoke_id = invoke_id; + response.results.push_back({mms::MmsDataValue::boolean(true), std::nullopt}); + transport.push_receive(wrap_application( + mms::MmsServiceCodec::encode_read_response_p_data(response))); + + const auto exchange = runtime.exchange_confirmed(request_bytes, invoke_id); + CHECK(exchange.envelope.kind == mms::MmsPduKind::confirmed_response); + CHECK(runtime.queued_information_report_count() == 1U); + + ByteVector queued_report; + CHECK(runtime.try_pop_information_report(queued_report)); + CHECK(mms::MmsInformationReportCodec::is_information_report(queued_report)); + CHECK(!runtime.try_pop_information_report(queued_report)); + + runtime.disconnect(); + CHECK(runtime.state() == mms::MmsAssociationRuntimeState::disconnected); + CHECK(!transport.connected()); + CHECK(transport.close_count() >= 1U); +} + +void association_rejects_cancelled_connect_and_can_reconnect() { + ScriptedTransport transport; + mms::MmsAssociationRuntime runtime{transport}; + std::stop_source source; + source.request_stop(); + check_throws([&] { + runtime.connect({"127.0.0.1", 102U}, source.get_token()); + }); + CHECK(runtime.state() == mms::MmsAssociationRuntimeState::faulted); + + queue_handshake(transport); + runtime.connect({"127.0.0.1", 102U}); + CHECK(runtime.associated()); + CHECK(transport.connect_count() == 1U); +} + + +void confirmed_exchange_timeout_faults_association() { + ScriptedTransport transport; + queue_handshake(transport); + mms::MmsAssociationRuntime runtime{transport}; + runtime.connect({"127.0.0.1", 102U}); + + const auto invoke_id = runtime.next_invoke_id(); + mms::MmsReadRequest request; + request.invoke_id = invoke_id; + request.variables.push_back( + mms::MmsObjectName::domain_specific("LD0", "LLN0$ST$Mod$stVal")); + const auto request_bytes = mms::MmsServiceCodec::encode_read_request_p_data(request); + check_throws([&] { + static_cast(runtime.exchange_confirmed(request_bytes, invoke_id)); + }); + CHECK(runtime.state() == mms::MmsAssociationRuntimeState::faulted); + CHECK(std::any_of(runtime.events().begin(), runtime.events().end(), [](const auto& event) { + return event.kind == mms::MmsAssociationEventKind::timed_out; + })); +} + +[[nodiscard]] mms::MmsReportControlCandidate make_urcb_candidate() { + mms::MmsReportControlCandidate candidate; + candidate.domain = "LD0"; + candidate.logical_node = "LLN0"; + candidate.functional_constraint = "RP"; + candidate.name = "urcbA01"; + candidate.reference = "LD0/LLN0.RP.urcbA01"; + candidate.buffered = false; + candidate.attributes = { + "RptID", "RptEna", "DatSet", "ConfRev", "OptFlds", + "TrgOps", "GI", "Resv"}; + return candidate; +} + +[[nodiscard]] mms::MmsDataSetDirectoryResponse make_directory() { + mms::MmsDataSetDirectoryResponse directory; + directory.invoke_id = 1U; + directory.members.push_back({ + mms::MmsObjectName::domain_specific("LD0", "PTOC1$ST$Str$stVal"), + "LD0/PTOC1$ST$Str$stVal", + "LD0/PTOC1.Str.stVal", + "ST", + "PTOC1", + "Str.stVal", + 100U}); + return directory; +} + +void queue_probe_response( + ScriptedTransport& transport, + const std::uint32_t invoke_id) { + mms::MmsReadResponse response; + response.invoke_id = invoke_id; + response.results = { + {mms::MmsDataValue::visible_string("RPT-A"), std::nullopt}, + {mms::MmsDataValue::boolean(false), std::nullopt}, + {mms::MmsDataValue::visible_string("LD0/LLN0.DataSet"), std::nullopt}, + {mms::MmsDataValue::unsigned_integer(1U), std::nullopt}, + {mms::MmsDataValue::bit_string(0U, ByteVector{0x5AU, 0x00U}), std::nullopt}, + {mms::MmsDataValue::bit_string(0U, ByteVector{0x40U}), std::nullopt}, + {mms::MmsDataValue::boolean(false), std::nullopt}, + {mms::MmsDataValue::boolean(false), std::nullopt}, + }; + transport.push_receive(wrap_application( + mms::MmsServiceCodec::encode_read_response_p_data(response))); +} + +void queue_write_success( + ScriptedTransport& transport, + const std::uint32_t invoke_id) { + mms::MmsWriteResponse response; + response.invoke_id = invoke_id; + response.results.push_back({true, std::nullopt}); + transport.push_receive(wrap_application( + mms::MmsServiceCodec::encode_write_response_p_data(response))); +} + +void subscription_runtime_reserves_enables_receives_and_cleans_up() { + ScriptedTransport transport; + queue_handshake(transport); + mms::MmsAssociationRuntime association{transport}; + association.connect({"127.0.0.1", 102U}); + + queue_probe_response(transport, 1U); + queue_write_success(transport, 2U); // Resv=true + queue_write_success(transport, 3U); // RptEna=true + queue_write_success(transport, 4U); // GI=true + + mms::MmsReportSubscriptionRuntime subscription{ + association, make_urcb_candidate(), make_directory()}; + subscription.start(); + CHECK(subscription.active()); + auto active = subscription.snapshot(); + CHECK(active.enabled_by_runtime); + CHECK(active.reservation_touched); + + transport.push_receive(wrap_application( + mms::MmsInformationReportCodec::encode_p_data(make_report()))); + CHECK(subscription.poll_once()); + const auto observed = subscription.snapshot(); + CHECK(observed.received_reports == 1U); + CHECK(observed.decode_failures == 0U); + CHECK(observed.streams.size() == 1U); + + queue_write_success(transport, 5U); // RptEna=false + queue_write_success(transport, 6U); // Resv=false + subscription.stop(); + const auto stopped = subscription.snapshot(); + CHECK(stopped.state == mms::MmsReportSubscriptionState::stopped); + CHECK(!stopped.enabled_by_runtime); + CHECK(!stopped.reservation_touched); + CHECK(!stopped.cleanup_required); +} + +void subscription_marks_cleanup_required_when_association_is_lost() { + ScriptedTransport transport; + queue_handshake(transport); + mms::MmsAssociationRuntime association{transport}; + association.connect({"127.0.0.1", 102U}); + + queue_probe_response(transport, 1U); + queue_write_success(transport, 2U); + queue_write_success(transport, 3U); + queue_write_success(transport, 4U); + + mms::MmsReportSubscriptionRuntime subscription{ + association, make_urcb_candidate(), make_directory()}; + subscription.start(); + association.disconnect(); + subscription.stop(); + const auto snapshot = subscription.snapshot(); + CHECK(snapshot.state == mms::MmsReportSubscriptionState::cleanup_required); + CHECK(snapshot.cleanup_required); + CHECK(snapshot.enabled_by_runtime); + CHECK(snapshot.reservation_touched); +} + +void subscription_does_not_take_over_an_enabled_rcb() { + ScriptedTransport transport; + queue_handshake(transport); + mms::MmsAssociationRuntime association{transport}; + association.connect({"127.0.0.1", 102U}); + + mms::MmsReadResponse response; + response.invoke_id = 1U; + response.results = { + {mms::MmsDataValue::visible_string("RPT-A"), std::nullopt}, + {mms::MmsDataValue::boolean(true), std::nullopt}, + {mms::MmsDataValue::visible_string("LD0/LLN0.DataSet"), std::nullopt}, + {mms::MmsDataValue::unsigned_integer(1U), std::nullopt}, + {mms::MmsDataValue::bit_string(0U, ByteVector{0x5AU, 0x00U}), std::nullopt}, + {mms::MmsDataValue::bit_string(0U, ByteVector{0x40U}), std::nullopt}, + {mms::MmsDataValue::boolean(false), std::nullopt}, + {mms::MmsDataValue::boolean(false), std::nullopt}, + }; + transport.push_receive(wrap_application( + mms::MmsServiceCodec::encode_read_response_p_data(response))); + + mms::MmsReportSubscriptionRuntime subscription{ + association, make_urcb_candidate(), make_directory()}; + check_throws([&] { subscription.start(); }); + CHECK(subscription.state() == mms::MmsReportSubscriptionState::faulted); + CHECK(transport.sent().size() == 3U); // CR, AARQ, probe only +} + +} // namespace + +int main() { + const std::vector>> tests{ + {"association lifecycle and routing", association_lifecycle_routes_reports_and_confirmed_results}, + {"association cancellation and reconnect", association_rejects_cancelled_connect_and_can_reconnect}, + {"confirmed exchange timeout", confirmed_exchange_timeout_faults_association}, + {"report subscription lifecycle", subscription_runtime_reserves_enables_receives_and_cleans_up}, + {"report cleanup after association loss", subscription_marks_cleanup_required_when_association_is_lost}, + {"report takeover protection", subscription_does_not_take_over_an_enabled_rcb}, + }; + + std::size_t passed = 0U; + for (const auto& [name, test] : tests) { + try { + test(); + ++passed; + std::cout << "[PASS] " << name << '\n'; + } catch (const std::exception& exception) { + std::cerr << "[FAIL] " << name << ": " << exception.what() << '\n'; + return 1; + } + } + std::cout << passed << " MMS runtime tests passed.\n"; + return 0; +}