From b677b182df0f9b4953f04e8380733b39be56f4cc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 10 Aug 2026 21:32:19 +0700 Subject: [PATCH 1/5] Add dynamic DataSet MMS service API --- include/ariec61850/mms/dynamic_data_set.hpp | 154 ++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 include/ariec61850/mms/dynamic_data_set.hpp diff --git a/include/ariec61850/mms/dynamic_data_set.hpp b/include/ariec61850/mms/dynamic_data_set.hpp new file mode 100644 index 000000000..8b0f1abb3 --- /dev/null +++ b/include/ariec61850/mms/dynamic_data_set.hpp @@ -0,0 +1,154 @@ +// 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 +#include +#include + +namespace ar::iec61850::mms { + +class MmsDynamicDataSetError final : public std::runtime_error { +public: + using std::runtime_error::runtime_error; +}; + +struct MmsDefineNamedVariableListRequest final { + std::uint32_t invoke_id{}; + MmsObjectName data_set_name; + std::vector members; + + friend bool operator==(const MmsDefineNamedVariableListRequest&, + const MmsDefineNamedVariableListRequest&) = default; +}; + +struct MmsDefineNamedVariableListResponse final { + std::uint32_t invoke_id{}; + + friend bool operator==(const MmsDefineNamedVariableListResponse&, + const MmsDefineNamedVariableListResponse&) = default; +}; + +struct MmsDeleteNamedVariableListRequest final { + std::uint32_t invoke_id{}; + MmsObjectName data_set_name; + + friend bool operator==(const MmsDeleteNamedVariableListRequest&, + const MmsDeleteNamedVariableListRequest&) = default; +}; + +struct MmsDeleteNamedVariableListResponse final { + std::uint32_t invoke_id{}; + std::optional number_matched; + std::optional number_deleted; + + [[nodiscard]] bool deleted() const noexcept { + return number_deleted.value_or(0U) > 0U; + } + + friend bool operator==(const MmsDeleteNamedVariableListResponse&, + const MmsDeleteNamedVariableListResponse&) = default; +}; + +class MmsNamedVariableListCodec final { +public: + static constexpr std::int32_t define_service_tag = 11; + static constexpr std::int32_t delete_service_tag = 13; + static constexpr std::size_t maximum_members = 65'536U; + + [[nodiscard]] static std::vector encode_define_request_pdu( + const MmsDefineNamedVariableListRequest& request); + [[nodiscard]] static std::vector encode_define_request_p_data( + const MmsDefineNamedVariableListRequest& request, + std::uint32_t presentation_context_id = 3U); + [[nodiscard]] static MmsDefineNamedVariableListRequest decode_define_request( + std::span presentation_or_mms_payload); + + [[nodiscard]] static std::vector encode_define_response_pdu( + const MmsDefineNamedVariableListResponse& response); + [[nodiscard]] static std::vector encode_define_response_p_data( + const MmsDefineNamedVariableListResponse& response, + std::uint32_t presentation_context_id = 3U); + [[nodiscard]] static MmsDefineNamedVariableListResponse decode_define_response( + std::span presentation_or_mms_payload, + std::optional expected_invoke_id = std::nullopt); + + [[nodiscard]] static std::vector encode_delete_request_pdu( + const MmsDeleteNamedVariableListRequest& request); + [[nodiscard]] static std::vector encode_delete_request_p_data( + const MmsDeleteNamedVariableListRequest& request, + std::uint32_t presentation_context_id = 3U); + [[nodiscard]] static MmsDeleteNamedVariableListRequest decode_delete_request( + std::span presentation_or_mms_payload); + + [[nodiscard]] static std::vector encode_delete_response_pdu( + const MmsDeleteNamedVariableListResponse& response); + [[nodiscard]] static std::vector encode_delete_response_p_data( + const MmsDeleteNamedVariableListResponse& response, + std::uint32_t presentation_context_id = 3U); + [[nodiscard]] static MmsDeleteNamedVariableListResponse decode_delete_response( + std::span presentation_or_mms_payload, + std::optional expected_invoke_id = std::nullopt); +}; + +struct MmsDynamicDataSetOptions final { + // Dynamic report DataSets are safest when intentionally small. The wire codec + // supports the full bounded MMS list size, while this operational default can + // be raised explicitly by a caller that has verified the target IED limits. + std::size_t maximum_members{64U}; + bool verify_after_create{true}; +}; + +struct MmsDynamicDataSetCreateResult final { + std::string data_set_reference; + MmsDefineNamedVariableListResponse define_response; + std::optional verified_directory; +}; + +enum class MmsDynamicDataSetDeletePolicy : std::uint8_t { + owned_only, + explicit_override, +}; + +class MmsDynamicDataSetRuntime final { +public: + explicit MmsDynamicDataSetRuntime( + MmsAssociationRuntime& association, + MmsDynamicDataSetOptions options = {}); + + [[nodiscard]] MmsDynamicDataSetCreateResult create( + const std::string& data_set_reference, + std::span members, + std::stop_token stop_token = {}); + + [[nodiscard]] MmsDeleteNamedVariableListResponse remove( + const std::string& data_set_reference, + MmsDynamicDataSetDeletePolicy policy = MmsDynamicDataSetDeletePolicy::owned_only, + std::stop_token stop_token = {}); + + [[nodiscard]] bool owns(const std::string& data_set_reference) const; + [[nodiscard]] std::vector owned_data_sets() const; + +private: + [[nodiscard]] std::string normalize_reference(const std::string& reference) const; + [[nodiscard]] MmsDeleteNamedVariableListResponse remove_impl( + const std::string& normalized_reference, + std::stop_token stop_token); + [[nodiscard]] MmsDataSetDirectoryResponse verify( + const MmsObjectName& data_set_name, + std::stop_token stop_token); + + MmsAssociationRuntime& association_; + MmsDynamicDataSetOptions options_{}; + std::set> owned_data_sets_; +}; + +} // namespace ar::iec61850::mms From c4e19047a5f1693b226cc17fc490db1df866b919 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 10 Aug 2026 21:33:53 +0700 Subject: [PATCH 2/5] Implement dynamic DataSet MMS lifecycle --- src/mms/dynamic_data_set.cpp | 517 +++++++++++++++++++++++++++++++++++ 1 file changed, 517 insertions(+) create mode 100644 src/mms/dynamic_data_set.cpp diff --git a/src/mms/dynamic_data_set.cpp b/src/mms/dynamic_data_set.cpp new file mode 100644 index 000000000..f3a20d9fd --- /dev/null +++ b/src/mms/dynamic_data_set.cpp @@ -0,0 +1,517 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "ariec61850/mms/dynamic_data_set.hpp" + +#include "ariec61850/asn1/ber.hpp" +#include "ariec61850/mms/pdu.hpp" +#include "ariec61850/mms/services.hpp" + +#include +#include +#include +#include + +namespace ar::iec61850::mms { +namespace { + +using asn1::BerClass; +using asn1::BerReader; +using asn1::BerTlv; +using asn1::BerWriter; + +[[nodiscard]] std::vector concat( + const std::initializer_list> parts) { + std::size_t total = 0U; + for (const auto part : parts) { + if (part.size() > MmsPduCodec::maximum_pdu_bytes - total) { + throw MmsDynamicDataSetError( + "Dynamic DataSet encoding exceeds the configured MMS PDU limit."); + } + total += part.size(); + } + + std::vector result; + result.reserve(total); + for (const auto part : parts) { + result.insert(result.end(), part.begin(), part.end()); + } + return result; +} + +[[nodiscard]] std::vector positive_integer_content( + const std::uint32_t value) { + auto encoded = BerWriter::encode_unsigned_integer(value); + if (encoded.empty()) { + encoded.push_back(0U); + } + if ((encoded.front() & 0x80U) != 0U) { + encoded.insert(encoded.begin(), 0U); + } + return encoded; +} + +[[nodiscard]] std::uint32_t read_u32( + const BerTlv& tlv, + const char* field_name) { + const auto value = BerReader::read_unsigned_integer(tlv); + if (!value || *value > std::numeric_limits::max()) { + throw MmsDynamicDataSetError( + std::string{"Dynamic DataSet "} + field_name + + " is not an unsigned 32-bit value."); + } + return static_cast(*value); +} + +void validate_data_set_name(const MmsObjectName& name) { + if (name.kind != MmsObjectNameKind::domain_specific || + name.domain.empty() || name.item.empty() || + name.item.find('$') == std::string::npos) { + throw MmsDynamicDataSetError( + "Dynamic DataSet name must be domain-specific IEC 61850 LD/LN.DataSetName."); + } + static_cast(MmsServiceCodec::encode_object_name(name)); +} + +void validate_members(const std::span members) { + if (members.empty() || members.size() > MmsNamedVariableListCodec::maximum_members) { + throw MmsDynamicDataSetError( + "Dynamic DataSet member count is outside the configured MMS limit."); + } + + std::set> unique; + for (const auto& member : members) { + if (member.kind != MmsObjectNameKind::domain_specific || + member.domain.empty() || member.item.empty()) { + throw MmsDynamicDataSetError( + "Dynamic DataSet members must be domain-specific MMS named variables."); + } + static_cast(MmsServiceCodec::encode_object_name(member)); + if (!unique.insert(member.reference()).second) { + throw MmsDynamicDataSetError( + "Dynamic DataSet contains a duplicate MMS member reference."); + } + } +} + +[[nodiscard]] std::vector encode_variable_definition( + const MmsObjectName& name) { + const auto encoded_name = MmsServiceCodec::encode_object_name(name); + const auto variable_specification = BerWriter::encode_tlv(0xA0U, encoded_name); + return BerWriter::encode_tlv(0x30U, variable_specification); +} + +[[nodiscard]] MmsObjectName decode_variable_definition(const BerTlv& definition) { + if (definition.encoded_tag != 0x30U || !definition.constructed) { + throw MmsDynamicDataSetError( + "Dynamic DataSet member is not an MMS VariableList SEQUENCE."); + } + const auto fields = BerReader::read_children(definition.value); + if (fields.size() != 1U || fields[0].encoded_tag != 0xA0U || + !fields[0].constructed) { + throw MmsDynamicDataSetError( + "Dynamic DataSet member has an invalid variableSpecification."); + } + return MmsServiceCodec::decode_object_name(fields[0].value); +} + +[[nodiscard]] std::vector reencode_tlv(const BerTlv& tlv) { + return BerWriter::encode_tlv(tlv.encoded_tag, tlv.value); +} + +[[nodiscard]] std::span response_payload( + const MmsConfirmedExchangeResult& exchange) { + if (!exchange.presentation_payload.empty()) { + return exchange.presentation_payload; + } + return exchange.envelope.mms_payload; +} + +void require_confirmed_response( + const MmsConfirmedExchangeResult& exchange, + const char* operation) { + if (exchange.envelope.kind == MmsPduKind::confirmed_error) { + throw MmsDynamicDataSetError( + std::string{"MMS "} + operation + " returned a Confirmed-Error PDU."); + } + if (exchange.envelope.kind != MmsPduKind::confirmed_response) { + throw MmsDynamicDataSetError( + std::string{"MMS "} + operation + + " did not return a Confirmed-Response PDU."); + } +} + +} // namespace + +std::vector MmsNamedVariableListCodec::encode_define_request_pdu( + const MmsDefineNamedVariableListRequest& request) { + validate_data_set_name(request.data_set_name); + validate_members(request.members); + + const auto list_name = MmsServiceCodec::encode_object_name(request.data_set_name); + std::vector definitions; + for (const auto& member : request.members) { + const auto definition = encode_variable_definition(member); + if (definition.size() > MmsPduCodec::maximum_pdu_bytes - definitions.size()) { + throw MmsDynamicDataSetError( + "Dynamic DataSet member definitions exceed the configured MMS PDU limit."); + } + definitions.insert(definitions.end(), definition.begin(), definition.end()); + } + const auto list_of_variable = BerWriter::encode_tlv(0xA0U, definitions); + const auto body = concat({list_name, list_of_variable}); + return MmsPduCodec::encode_confirmed_request( + {request.invoke_id, define_service_tag, true, body}); +} + +std::vector MmsNamedVariableListCodec::encode_define_request_p_data( + const MmsDefineNamedVariableListRequest& request, + const std::uint32_t presentation_context_id) { + const auto pdu = encode_define_request_pdu(request); + return MmsPduCodec::wrap_p_data(pdu, presentation_context_id); +} + +MmsDefineNamedVariableListRequest MmsNamedVariableListCodec::decode_define_request( + const std::span presentation_or_mms_payload) { + const auto mms = MmsPduCodec::extract_mms_payload(presentation_or_mms_payload); + const auto request = MmsPduCodec::decode_confirmed_request(mms); + if (request.service_tag != define_service_tag || !request.service_constructed) { + throw MmsDynamicDataSetError( + "MMS request is not DefineNamedVariableList."); + } + + const auto fields = BerReader::read_children(request.service_value); + if (fields.size() != 2U || fields[0].encoded_tag != 0xA1U || + !fields[0].constructed || fields[1].encoded_tag != 0xA0U || + !fields[1].constructed) { + throw MmsDynamicDataSetError( + "DefineNamedVariableList request fields are invalid."); + } + + MmsDefineNamedVariableListRequest result; + result.invoke_id = request.invoke_id; + const auto encoded_list_name = reencode_tlv(fields[0]); + result.data_set_name = MmsServiceCodec::decode_object_name(encoded_list_name); + validate_data_set_name(result.data_set_name); + + const auto definitions = BerReader::read_children(fields[1].value); + if (definitions.empty() || definitions.size() > maximum_members) { + throw MmsDynamicDataSetError( + "DefineNamedVariableList member count is outside the configured limit."); + } + result.members.reserve(definitions.size()); + for (const auto& definition : definitions) { + result.members.push_back(decode_variable_definition(definition)); + } + validate_members(result.members); + return result; +} + +std::vector MmsNamedVariableListCodec::encode_define_response_pdu( + const MmsDefineNamedVariableListResponse& response) { + // ISO 9506 DefineNamedVariableList success is the service choice [11] + // with an empty value. The primitive tag (0x8B) matches the C# oracle. + return MmsPduCodec::encode_confirmed_response( + {response.invoke_id, define_service_tag, false, {}}); +} + +std::vector MmsNamedVariableListCodec::encode_define_response_p_data( + const MmsDefineNamedVariableListResponse& response, + const std::uint32_t presentation_context_id) { + const auto pdu = encode_define_response_pdu(response); + return MmsPduCodec::wrap_p_data(pdu, presentation_context_id); +} + +MmsDefineNamedVariableListResponse MmsNamedVariableListCodec::decode_define_response( + const std::span presentation_or_mms_payload, + const std::optional expected_invoke_id) { + const auto mms = MmsPduCodec::extract_mms_payload(presentation_or_mms_payload); + const auto response = MmsPduCodec::decode_confirmed_response(mms); + if (expected_invoke_id && response.invoke_id != *expected_invoke_id) { + throw MmsDynamicDataSetError( + "DefineNamedVariableList response invoke ID mismatch."); + } + if (response.service_tag != define_service_tag || !response.service_value.empty()) { + throw MmsDynamicDataSetError( + "MMS response is not an empty successful DefineNamedVariableList response."); + } + return {response.invoke_id}; +} + +std::vector MmsNamedVariableListCodec::encode_delete_request_pdu( + const MmsDeleteNamedVariableListRequest& request) { + validate_data_set_name(request.data_set_name); + const auto list_name = MmsServiceCodec::encode_object_name(request.data_set_name); + const auto list_of_variable_list_name = BerWriter::encode_tlv(0xA1U, list_name); + return MmsPduCodec::encode_confirmed_request( + {request.invoke_id, delete_service_tag, true, list_of_variable_list_name}); +} + +std::vector MmsNamedVariableListCodec::encode_delete_request_p_data( + const MmsDeleteNamedVariableListRequest& request, + const std::uint32_t presentation_context_id) { + const auto pdu = encode_delete_request_pdu(request); + return MmsPduCodec::wrap_p_data(pdu, presentation_context_id); +} + +MmsDeleteNamedVariableListRequest MmsNamedVariableListCodec::decode_delete_request( + const std::span presentation_or_mms_payload) { + const auto mms = MmsPduCodec::extract_mms_payload(presentation_or_mms_payload); + const auto request = MmsPduCodec::decode_confirmed_request(mms); + if (request.service_tag != delete_service_tag || !request.service_constructed) { + throw MmsDynamicDataSetError( + "MMS request is not DeleteNamedVariableList."); + } + + const auto fields = BerReader::read_children(request.service_value); + if (fields.size() != 1U || fields[0].encoded_tag != 0xA1U || + !fields[0].constructed) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList request listOfVariableListName is invalid."); + } + const auto names = BerReader::read_children(fields[0].value); + if (names.size() != 1U || names[0].encoded_tag != 0xA1U || + !names[0].constructed) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList must contain exactly one domain-specific list name."); + } + + const auto encoded_name = reencode_tlv(names[0]); + auto data_set_name = MmsServiceCodec::decode_object_name(encoded_name); + validate_data_set_name(data_set_name); + return {request.invoke_id, std::move(data_set_name)}; +} + +std::vector MmsNamedVariableListCodec::encode_delete_response_pdu( + const MmsDeleteNamedVariableListResponse& response) { + std::vector body; + if (response.number_matched) { + const auto value = positive_integer_content(*response.number_matched); + const auto field = BerWriter::encode_tlv( + BerClass::context_specific, false, 0, value); + body.insert(body.end(), field.begin(), field.end()); + } + if (response.number_deleted) { + const auto value = positive_integer_content(*response.number_deleted); + const auto field = BerWriter::encode_tlv( + BerClass::context_specific, false, 1, value); + body.insert(body.end(), field.begin(), field.end()); + } + if (body.empty()) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList response requires matched or deleted count evidence."); + } + return MmsPduCodec::encode_confirmed_response( + {response.invoke_id, delete_service_tag, true, body}); +} + +std::vector MmsNamedVariableListCodec::encode_delete_response_p_data( + const MmsDeleteNamedVariableListResponse& response, + const std::uint32_t presentation_context_id) { + const auto pdu = encode_delete_response_pdu(response); + return MmsPduCodec::wrap_p_data(pdu, presentation_context_id); +} + +MmsDeleteNamedVariableListResponse MmsNamedVariableListCodec::decode_delete_response( + const std::span presentation_or_mms_payload, + const std::optional expected_invoke_id) { + const auto mms = MmsPduCodec::extract_mms_payload(presentation_or_mms_payload); + const auto response = MmsPduCodec::decode_confirmed_response(mms); + if (expected_invoke_id && response.invoke_id != *expected_invoke_id) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList response invoke ID mismatch."); + } + if (response.service_tag != delete_service_tag || !response.service_constructed) { + throw MmsDynamicDataSetError( + "MMS response is not DeleteNamedVariableList."); + } + + MmsDeleteNamedVariableListResponse result; + result.invoke_id = response.invoke_id; + const auto fields = BerReader::read_children(response.service_value); + for (const auto& field : fields) { + if (field.tag_class != BerClass::context_specific || field.constructed) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList response contains an invalid count field."); + } + if (field.tag_number == 0) { + if (result.number_matched) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList response repeats numberMatched."); + } + result.number_matched = read_u32(field, "numberMatched"); + } else if (field.tag_number == 1) { + if (result.number_deleted) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList response repeats numberDeleted."); + } + result.number_deleted = read_u32(field, "numberDeleted"); + } else { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList response contains an unknown field."); + } + } + if (!result.number_matched && !result.number_deleted) { + throw MmsDynamicDataSetError( + "DeleteNamedVariableList response contains no count evidence."); + } + return result; +} + +MmsDynamicDataSetRuntime::MmsDynamicDataSetRuntime( + MmsAssociationRuntime& association, + MmsDynamicDataSetOptions options) + : association_{association}, options_{options} { + if (options_.maximum_members == 0U || + options_.maximum_members > MmsNamedVariableListCodec::maximum_members) { + throw std::invalid_argument( + "Dynamic DataSet operational member limit is outside the codec bounds."); + } +} + +std::string MmsDynamicDataSetRuntime::normalize_reference( + const std::string& reference) const { + auto name = MmsDataSetDirectoryCodec::parse_data_set_reference(reference); + if (name.kind != MmsObjectNameKind::domain_specific) { + throw MmsDynamicDataSetError( + "Dynamic DataSet reference must use IEC 61850 LD/LN.DataSetName form."); + } + if (name.item.find('$') == std::string::npos) { + name.item = "LLN0$" + name.item; + } + validate_data_set_name(name); + return MmsDataSetDirectoryCodec::to_iec_reference(name); +} + +MmsDataSetDirectoryResponse MmsDynamicDataSetRuntime::verify( + const MmsObjectName& data_set_name, + const std::stop_token stop_token) { + const auto invoke_id = association_.next_invoke_id(); + const MmsDataSetDirectoryRequest request{invoke_id, data_set_name}; + const auto encoded = MmsDataSetDirectoryCodec::encode_request_p_data( + request, association_.negotiated().presentation_context_id); + const auto exchange = association_.exchange_confirmed( + encoded, invoke_id, stop_token); + require_confirmed_response(exchange, "GetNamedVariableListAttributes verification"); + return MmsDataSetDirectoryCodec::decode_response( + response_payload(exchange), invoke_id); +} + +MmsDynamicDataSetCreateResult MmsDynamicDataSetRuntime::create( + const std::string& data_set_reference, + const std::span members, + const std::stop_token stop_token) { + if (!association_.associated()) { + throw MmsDynamicDataSetError( + "Cannot create a dynamic DataSet without an active MMS association."); + } + if (members.empty() || members.size() > options_.maximum_members) { + throw MmsDynamicDataSetError( + "Dynamic DataSet member count exceeds the configured operational limit."); + } + validate_members(members); + + const auto normalized = normalize_reference(data_set_reference); + if (owned_data_sets_.contains(normalized)) { + throw MmsDynamicDataSetError( + "This runtime already owns the requested dynamic DataSet reference."); + } + const auto data_set_name = MmsDataSetDirectoryCodec::parse_data_set_reference(normalized); + + const auto invoke_id = association_.next_invoke_id(); + MmsDefineNamedVariableListRequest request; + request.invoke_id = invoke_id; + request.data_set_name = data_set_name; + request.members.assign(members.begin(), members.end()); + const auto encoded = MmsNamedVariableListCodec::encode_define_request_p_data( + request, association_.negotiated().presentation_context_id); + const auto exchange = association_.exchange_confirmed( + encoded, invoke_id, stop_token); + require_confirmed_response(exchange, "DefineNamedVariableList"); + const auto define_response = MmsNamedVariableListCodec::decode_define_response( + response_payload(exchange), invoke_id); + + MmsDynamicDataSetCreateResult result; + result.data_set_reference = normalized; + result.define_response = define_response; + + if (options_.verify_after_create) { + try { + const auto directory = verify(data_set_name, stop_token); + if (directory.members.size() != members.size()) { + throw MmsDynamicDataSetError( + "Dynamic DataSet verification returned a different member count."); + } + for (std::size_t index = 0U; index < members.size(); ++index) { + if (directory.members[index].object_name != members[index]) { + throw MmsDynamicDataSetError( + "Dynamic DataSet verification returned different member ordering/content."); + } + } + result.verified_directory = directory; + } catch (...) { + try { + static_cast(remove_impl(normalized, stop_token)); + } catch (...) { + // The creation error remains primary; callers can inspect the IED + // if best-effort rollback also failed. + } + throw; + } + } + + owned_data_sets_.insert(normalized); + return result; +} + +MmsDeleteNamedVariableListResponse MmsDynamicDataSetRuntime::remove_impl( + const std::string& normalized_reference, + const std::stop_token stop_token) { + const auto data_set_name = + MmsDataSetDirectoryCodec::parse_data_set_reference(normalized_reference); + const auto invoke_id = association_.next_invoke_id(); + const MmsDeleteNamedVariableListRequest request{invoke_id, data_set_name}; + const auto encoded = MmsNamedVariableListCodec::encode_delete_request_p_data( + request, association_.negotiated().presentation_context_id); + const auto exchange = association_.exchange_confirmed( + encoded, invoke_id, stop_token); + require_confirmed_response(exchange, "DeleteNamedVariableList"); + return MmsNamedVariableListCodec::decode_delete_response( + response_payload(exchange), invoke_id); +} + +MmsDeleteNamedVariableListResponse MmsDynamicDataSetRuntime::remove( + const std::string& data_set_reference, + const MmsDynamicDataSetDeletePolicy policy, + const std::stop_token stop_token) { + if (!association_.associated()) { + throw MmsDynamicDataSetError( + "Cannot delete a dynamic DataSet without an active MMS association."); + } + const auto normalized = normalize_reference(data_set_reference); + const auto owned = owned_data_sets_.contains(normalized); + if (!owned && policy != MmsDynamicDataSetDeletePolicy::explicit_override) { + throw MmsDynamicDataSetError( + "Refusing to delete a DataSet not created by this runtime; use explicit_override intentionally."); + } + + const auto response = remove_impl(normalized, stop_token); + if (response.deleted() || response.number_matched.value_or(1U) == 0U) { + owned_data_sets_.erase(normalized); + } + return response; +} + +bool MmsDynamicDataSetRuntime::owns( + const std::string& data_set_reference) const { + try { + return owned_data_sets_.contains(normalize_reference(data_set_reference)); + } catch (...) { + return false; + } +} + +std::vector MmsDynamicDataSetRuntime::owned_data_sets() const { + return {owned_data_sets_.begin(), owned_data_sets_.end()}; +} + +} // namespace ar::iec61850::mms From aa5a49b01759fb9361cd572ff0510a58045f4956 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 10 Aug 2026 21:34:55 +0700 Subject: [PATCH 3/5] Add dynamic DataSet parity tests --- tests/test_dynamic_data_set.cpp | 217 ++++++++++++++++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 tests/test_dynamic_data_set.cpp diff --git a/tests/test_dynamic_data_set.cpp b/tests/test_dynamic_data_set.cpp new file mode 100644 index 000000000..c7708690b --- /dev/null +++ b/tests/test_dynamic_data_set.cpp @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "ariec61850/mms/dynamic_data_set.hpp" +#include "ariec61850/mms/pdu.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using ar::iec61850::mms::MmsAssociationRuntime; +using ar::iec61850::mms::MmsByteTransport; +using ar::iec61850::mms::MmsDataSetDirectoryCodec; +using ar::iec61850::mms::MmsDefineNamedVariableListRequest; +using ar::iec61850::mms::MmsDefineNamedVariableListResponse; +using ar::iec61850::mms::MmsDeleteNamedVariableListRequest; +using ar::iec61850::mms::MmsDeleteNamedVariableListResponse; +using ar::iec61850::mms::MmsDynamicDataSetError; +using ar::iec61850::mms::MmsDynamicDataSetRuntime; +using ar::iec61850::mms::MmsEndpoint; +using ar::iec61850::mms::MmsNamedVariableListCodec; +using ar::iec61850::mms::MmsObjectName; +using ar::iec61850::mms::MmsPduCodec; + +#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."); +} + +std::vector from_hex(const std::string& text) { + std::vector result; + int high = -1; + for (const auto ch : text) { + int value = -1; + if (ch >= '0' && ch <= '9') { + value = ch - '0'; + } else if (ch >= 'A' && ch <= 'F') { + value = 10 + ch - 'A'; + } else if (ch >= 'a' && ch <= 'f') { + value = 10 + ch - 'a'; + } else { + continue; + } + if (high < 0) { + high = value; + } else { + result.push_back(static_cast((high << 4) | value)); + high = -1; + } + } + if (high >= 0) { + throw std::invalid_argument("Odd-length hexadecimal test vector."); + } + return result; +} + +bool contains_ascii( + const std::vector& bytes, + const std::string& text) { + const std::vector needle{text.begin(), text.end()}; + return std::search(bytes.begin(), bytes.end(), needle.begin(), needle.end()) != bytes.end(); +} + +class NullTransport final : public MmsByteTransport { +public: + void connect(const MmsEndpoint&, Deadline, std::stop_token) override {} + void send(std::span, Deadline, std::stop_token) override {} + [[nodiscard]] std::vector receive(Deadline, std::stop_token) override { + return {}; + } + void close() noexcept override {} + [[nodiscard]] bool connected() const noexcept override { return false; } +}; + +MmsDefineNamedVariableListRequest oracle_define_request() { + MmsDefineNamedVariableListRequest request; + request.invoke_id = 8U; + request.data_set_name = MmsDataSetDirectoryCodec::parse_data_set_reference( + "LD0/LLN0.AR_DYN_DS01"); + request.members = { + MmsObjectName::domain_specific("LD0", "PTOC1$ST$Str$stVal"), + MmsObjectName::domain_specific("LD0", "MMXU1$MX$PhV$phsA$cVal$mag$f")}; + return request; +} + +void define_request_matches_csharp_shape_and_round_trips() { + const auto request = oracle_define_request(); + const auto encoded = MmsNamedVariableListCodec::encode_define_request_pdu(request); + const auto generic = MmsPduCodec::decode_confirmed_request(encoded); + + CHECK(generic.invoke_id == 8U); + CHECK(generic.service_tag == MmsNamedVariableListCodec::define_service_tag); + CHECK(generic.service_constructed); + CHECK(contains_ascii(encoded, "AR_DYN_DS01")); + CHECK(contains_ascii(encoded, "PTOC1$ST$Str$stVal")); + CHECK(contains_ascii(encoded, "MMXU1$MX$PhV$phsA$cVal$mag$f")); + + const auto decoded = MmsNamedVariableListCodec::decode_define_request(encoded); + CHECK(decoded == request); +} + +void define_response_accepts_and_emits_csharp_oracle_vector() { + const auto oracle = from_hex("A10502010A8B00"); + const auto wrapped = MmsPduCodec::wrap_p_data(oracle); + const auto decoded = MmsNamedVariableListCodec::decode_define_response(wrapped, 10U); + CHECK(decoded.invoke_id == 10U); + + const auto encoded = MmsNamedVariableListCodec::encode_define_response_pdu({10U}); + CHECK(encoded == oracle); +} + +void delete_request_matches_csharp_shape_and_round_trips() { + const MmsDeleteNamedVariableListRequest request{ + 11U, + MmsDataSetDirectoryCodec::parse_data_set_reference( + "LD0/GGIO1.AR_DYN_DS01")}; + const auto encoded = MmsNamedVariableListCodec::encode_delete_request_pdu(request); + const auto generic = MmsPduCodec::decode_confirmed_request(encoded); + + CHECK(generic.invoke_id == 11U); + CHECK(generic.service_tag == MmsNamedVariableListCodec::delete_service_tag); + CHECK(generic.service_constructed); + CHECK(contains_ascii(encoded, "GGIO1$AR_DYN_DS01")); + + const auto decoded = MmsNamedVariableListCodec::decode_delete_request(encoded); + CHECK(decoded == request); +} + +void delete_response_reads_and_emits_csharp_oracle_counts() { + const auto oracle = from_hex("A10B02010BAD06800101810101"); + const auto wrapped = MmsPduCodec::wrap_p_data(oracle); + const auto decoded = MmsNamedVariableListCodec::decode_delete_response(wrapped, 11U); + CHECK(decoded.number_matched == 1U); + CHECK(decoded.number_deleted == 1U); + CHECK(decoded.deleted()); + + const MmsDeleteNamedVariableListResponse response{ + 11U, 1U, 1U}; + const auto encoded = MmsNamedVariableListCodec::encode_delete_response_pdu(response); + CHECK(encoded == oracle); +} + +void invalid_or_unsafe_requests_fail_closed() { + auto empty = oracle_define_request(); + empty.members.clear(); + check_throws([&] { + static_cast(MmsNamedVariableListCodec::encode_define_request_pdu(empty)); + }); + + auto duplicate = oracle_define_request(); + duplicate.members.push_back(duplicate.members.front()); + check_throws([&] { + static_cast(MmsNamedVariableListCodec::encode_define_request_pdu(duplicate)); + }); + + auto vmd = oracle_define_request(); + vmd.data_set_name = MmsObjectName::vmd("AR_DYN_DS01"); + check_throws([&] { + static_cast(MmsNamedVariableListCodec::encode_define_request_pdu(vmd)); + }); + + const auto oracle = from_hex("A10502010A8B00"); + check_throws([&] { + static_cast(MmsNamedVariableListCodec::decode_define_response(oracle, 99U)); + }); +} + +void runtime_requires_live_association_before_mutation() { + NullTransport transport; + MmsAssociationRuntime association{transport}; + MmsDynamicDataSetRuntime runtime{association}; + const auto request = oracle_define_request(); + check_throws([&] { + static_cast(runtime.create( + "LD0/LLN0.AR_DYN_DS01", request.members)); + }); +} + +} // namespace + +int main() { + try { + define_request_matches_csharp_shape_and_round_trips(); + define_response_accepts_and_emits_csharp_oracle_vector(); + delete_request_matches_csharp_shape_and_round_trips(); + delete_response_reads_and_emits_csharp_oracle_counts(); + invalid_or_unsafe_requests_fail_closed(); + runtime_requires_live_association_before_mutation(); + std::cout << "Dynamic DataSet tests passed.\n"; + return 0; + } catch (const std::exception& exception) { + std::cerr << "Dynamic DataSet test failure: " << exception.what() << '\n'; + return 1; + } +} From 44589451a414b264c5b34d9f0410695996ceb31d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 10 Aug 2026 21:36:12 +0700 Subject: [PATCH 4/5] Wire dynamic DataSet module into core and CTest --- CMakeLists.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index e322bcc1b..ce4b7a73d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,6 +25,7 @@ add_library(ariec61850_core src/mms/data_codec.cpp src/mms/pdu.cpp src/mms/services.cpp + src/mms/dynamic_data_set.cpp src/mms/invoke_router.cpp src/mms/reporting.cpp src/mms/association_runtime.cpp @@ -176,6 +177,13 @@ if(ARIEC61850_BUILD_TESTS) ariec61850_apply_sanitizers(ariec61850_mms_services_tests) add_test(NAME ariec61850_mms_services_tests COMMAND ariec61850_mms_services_tests) + add_executable(ariec61850_dynamic_data_set_tests tests/test_dynamic_data_set.cpp) + target_link_libraries(ariec61850_dynamic_data_set_tests PRIVATE ARIEC61850::core) + target_compile_features(ariec61850_dynamic_data_set_tests PRIVATE cxx_std_20) + ariec61850_apply_warnings(ariec61850_dynamic_data_set_tests) + ariec61850_apply_sanitizers(ariec61850_dynamic_data_set_tests) + add_test(NAME ariec61850_dynamic_data_set_tests COMMAND ariec61850_dynamic_data_set_tests) + add_executable(ariec61850_reporting_tests tests/test_reporting.cpp) target_link_libraries(ariec61850_reporting_tests PRIVATE ARIEC61850::core) target_compile_features(ariec61850_reporting_tests PRIVATE cxx_std_20) From 584632fc07b2d3de9735434047ee8ba2170e3631 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Mon, 10 Aug 2026 21:38:08 +0700 Subject: [PATCH 5/5] Document dynamic DataSet safety and acceptance profile --- DYNAMIC_DATASET_PROFILE.md | 71 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 DYNAMIC_DATASET_PROFILE.md diff --git a/DYNAMIC_DATASET_PROFILE.md b/DYNAMIC_DATASET_PROFILE.md new file mode 100644 index 000000000..9ea3feeba --- /dev/null +++ b/DYNAMIC_DATASET_PROFILE.md @@ -0,0 +1,71 @@ +# Dynamic DataSet Profile + +## Scope + +This profile ports the ARIEC61850 dynamic DataSet lifecycle to the C++ stack without coupling it to IEC 61850 control sequencing. + +Implemented MMS services: + +- `DefineNamedVariableList` — service choice `[11]` +- `DeleteNamedVariableList` — service choice `[13]` +- `GetNamedVariableListAttributes` verification through the existing DataSet-directory codec + +The codec is symmetric: request and response encode/decode are available so the same wire model can be reused by a future MMS server dispatcher. + +## Reference and member rules + +Dynamic DataSets use domain-specific IEC 61850 references: + +`LD/LN.DataSetName` + +The operational runtime also accepts `LD/DataSetName` and normalizes it to `LD/LLN0.DataSetName`, matching the C# oracle behavior. + +Members are ordered domain-specific MMS named variables. Duplicate members are rejected. Member ordering is treated as semantic because IEC 61850 report values are mapped to DataSet members by index. + +## Safe create lifecycle + +`MmsDynamicDataSetRuntime::create()` requires an already associated `MmsAssociationRuntime` and performs: + +1. validate the DataSet identity and bounded member list; +2. send exactly one `DefineNamedVariableList` request; +3. require a matching successful confirmed response; +4. by default, issue `GetNamedVariableListAttributes` for the new DataSet; +5. require exact member count, content, and ordering; +6. record local ownership only after the create path succeeds. + +If verification fails after a successful Define, the runtime attempts one best-effort Delete rollback and then propagates the original failure. It does not retry creation automatically. + +The operational default is 64 members. Callers can raise the limit explicitly up to the bounded codec maximum after validating target-IED payload and resource limits. + +## Safe delete lifecycle + +Deletion is default-deny for DataSets the runtime did not create. + +`owned_only` is the default policy. `explicit_override` must be selected deliberately to delete an unowned DataSet. This prevents a reporting client from accidentally deleting a static or another client's DataSet merely because the reference is known. + +No network operation is performed from a destructor. Cleanup is always explicit so shutdown and association-loss behavior remain observable. + +## C# parity evidence + +The dedicated C++ test target includes the ARIEC61850 C# oracle vectors for: + +- successful `DefineNamedVariableList` response: `A10502010A8B00`; +- successful `DeleteNamedVariableList` matched/deleted response: `A10B02010BAD06800101810101`; +- Define request service/member shape; +- Delete request service/list-name shape. + +The tests also round-trip both request types, reject empty/duplicate/invalid definitions, verify invoke-ID correlation, and require an active association before any mutation. + +## Acceptance boundary + +Hosted CI can establish deterministic wire parity, parser/encoder safety, portability, and integration with the existing association runtime. It cannot establish physical IED mutation interoperability. + +Before claiming live Dynamic DataSet interoperability, retain evidence from a non-operational lab IED showing: + +1. `DefineNamedVariableList` accepted for a small DataSet; +2. immediate `GetNamedVariableListAttributes` returns the exact requested ordered members; +3. an available RCB can bind to that DataSet and report values map by the verified indexes; +4. `DeleteNamedVariableList` reports the expected matched/deleted counts after RCB disable/unbind; +5. reconnect and failure cases do not cause an unrelated/static DataSet to be deleted. + +Smart Control is intentionally outside this profile and may progress independently.