From 5f4d1b4c2c17997e4306fb148aad5c75ddd6c54b Mon Sep 17 00:00:00 2001 From: tkeairns Date: Mon, 30 Nov 2026 17:39:57 -0800 Subject: [PATCH 1/2] full: IEC 61850 MMS server on TCP 102 beside GOOSE lib/mms: a server for one logical device from a const table, as lib/goose publishes one. Discovery, reads at any level, data sets, one buffered and one unbuffered report control block, two clients at once, identify and status. No controls, files, setting groups or TLS. The core is free of I/O (tests/lib/mms); the Zephyr glue is one thread on sockets, with a bounded send and TCP keepalive. nodes/full serves what its GOOSE publishes: ds_pdu through brcb_pdu01, ds_dcdc through urcb_dcdc01, every data object with q and t. zelosfull.cid is the station file. testing/suites/mms checks it with an MMS client on the host. --- README.md | 2 +- can-full/README.md | 23 +- can-full/justfile | 4 +- include/zelos/mms.h | 364 +++++++++++ lib/CMakeLists.txt | 1 + lib/Kconfig | 1 + lib/mms/CMakeLists.txt | 9 + lib/mms/Kconfig | 16 + lib/mms/core/mms_ber.c | 210 ++++++ lib/mms/core/mms_core.c | 660 +++++++++++++++++++ lib/mms/core/mms_internal.h | 169 +++++ lib/mms/core/mms_model.c | 459 +++++++++++++ lib/mms/core/mms_report.c | 865 ++++++++++++++++++++++++ lib/mms/core/mms_service.c | 524 +++++++++++++++ lib/mms/zephyr/mms.c | 255 ++++++++ nodes/full/CMakeLists.txt | 6 +- nodes/full/sample.yaml | 3 +- nodes/full/src/main.c | 7 +- nodes/full/src/mms.c | 123 ++++ nodes/full/src/mms.h | 7 + nodes/full/zelosfull.cid | 83 +++ nodes/pdu/src/pdu.c | 8 +- snippets/mms/mms.conf | 9 + snippets/mms/snippet.yml | 3 + testing/pyproject.toml | 1 + testing/suites/mms/test_server.py | 214 ++++++ testing/uv.lock | 13 +- tests/lib/mms/CMakeLists.txt | 5 + tests/lib/mms/prj.conf | 3 + tests/lib/mms/src/main.c | 1011 +++++++++++++++++++++++++++++ tests/lib/mms/testcase.yaml | 5 + 31 files changed, 5052 insertions(+), 11 deletions(-) create mode 100644 include/zelos/mms.h create mode 100644 lib/mms/CMakeLists.txt create mode 100644 lib/mms/Kconfig create mode 100644 lib/mms/core/mms_ber.c create mode 100644 lib/mms/core/mms_core.c create mode 100644 lib/mms/core/mms_internal.h create mode 100644 lib/mms/core/mms_model.c create mode 100644 lib/mms/core/mms_report.c create mode 100644 lib/mms/core/mms_service.c create mode 100644 lib/mms/zephyr/mms.c create mode 100644 nodes/full/src/mms.c create mode 100644 nodes/full/src/mms.h create mode 100644 nodes/full/zelosfull.cid create mode 100644 snippets/mms/mms.conf create mode 100644 snippets/mms/snippet.yml create mode 100644 testing/suites/mms/test_server.py create mode 100644 tests/lib/mms/CMakeLists.txt create mode 100644 tests/lib/mms/prj.conf create mode 100644 tests/lib/mms/src/main.c create mode 100644 tests/lib/mms/testcase.yaml diff --git a/README.md b/README.md index 74abede..065d795 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ rather than copying them. | `zephyr/`, `CMakeLists.txt`, `Kconfig` | This repository as a Zephyr module, contributing `lib/` | | `nodes/` | Zephyr applications, one per node, each reusable by any bench: `vcu`, `bms`, `dcdc`, `pdu`, `console`, `motor`; `full` runs the DC-DC, the genset (its sources in `genset`, built only into `full`) and the PDU in one image | | `lib/`, `include/zelos/` | Code the nodes share, each piece off until a node's `prj.conf` enables it. `lib/can` owns the controller: every protocol sends through its one queue, lowest id first | -| `snippets/` | Protocols any node can build with, e.g. `-S xcp`, `-S uds`, `-S autosar`, `-S ethernet`, `-S goose` | +| `snippets/` | Protocols any node can build with, e.g. `-S xcp`, `-S uds`, `-S autosar`, `-S ethernet`, `-S goose`, `-S mms` | | `dbc/` | Wire formats of the shared nodes: `bench.dbc` (classic), `genset.dbc` (J1939), and `full.dbc`, both merged, the one file tools load; `lib/codec_/` and `full.dbc` are generated by `just dbc` | | `arxml/` | `can-full.arxml`, the can-full bench as an AUTOSAR R19-11 System Template; the DC-DC's AUTOSAR tables are generated from it (`just arxml`) | | `toolchain/` | The firmware build image | diff --git a/can-full/README.md b/can-full/README.md index 616557f..8a54b0c 100644 --- a/can-full/README.md +++ b/can-full/README.md @@ -48,7 +48,7 @@ same default, so run one bench at a time or move one. |---|---|---|---| | VCU | `../nodes/vcu` | | `0x101` | | BMS | `../nodes/bms` | | `0x200`-`0x202` | -| DC-DC | `../nodes/full` (`../nodes/dcdc`, XCP, UDS, AUTOSAR, Ethernet and GOOSE) | XCP on CAN, UDS on ISO-TP, AUTOSAR PDUs; IPv4 and GOOSE on Ethernet | `0x300`; AUTOSAR `0x310`-`0x315`; CRO `0x6F0`, DTO `0x6F1`; UDS `0x7E0`, functional `0x7DF`, responses `0x7E8`; `10.1.1.75/24`; GOOSE APPIDs `0x0001`, `0x0002` | +| DC-DC | `../nodes/full` (`../nodes/dcdc`, XCP, UDS, AUTOSAR, Ethernet, GOOSE and MMS) | XCP on CAN, UDS on ISO-TP, AUTOSAR PDUs; IPv4, GOOSE and MMS on Ethernet | `0x300`; AUTOSAR `0x310`-`0x315`; CRO `0x6F0`, DTO `0x6F1`; UDS `0x7E0`, functional `0x7DF`, responses `0x7E8`; `10.1.1.75/24`; GOOSE APPIDs `0x0001`, `0x0002`; MMS on TCP 102 | | Signal generator | `../nodes/full/src/waveform.c` | Classic CAN | `0x7F0` `Waveform` every 2 ms: sine, square and sawtooth of one phase, chirped 1 to 100 Hz over 20 s; the lowest-priority id, for plots | | genset | `../nodes/full` (`../nodes/genset`) | J1939 | 29-bit, source address `0x80` | | PDU | `../nodes/full` (`../nodes/pdu`) | CANopen, node-id `0x20` | NMT `0x000`, SYNC `0x080`, TIME `0x100`, EMCY `0x0A0`, TPDO1 `0x1A0`, RPDO1 `0x220`, TPDO2 `0x2A0`, RPDO2 `0x320`, TPDO3 `0x3A0`, SDO `0x5A0`/`0x620`, heartbeat `0x720` | @@ -105,6 +105,24 @@ both control blocks: `0x01` toggles simulation, `0x02` toggles ndsCom, `0x03` adds one to confRev. Any capture tool on a host on the same switch shows them, e.g. `tcpdump -i ether proto 0x88b8`, or Wireshark's GOOSE dissector. +The same logical device is served over IEC 61850-8-1 MMS on TCP 102 (`../lib/mms`, +`../nodes/full/src/mms.c`), to two clients at once, without TLS or +authentication. `../nodes/full/zelosfull.cid` is its station file. Each data +object reads with its value, quality and time: `XSWI1`-`XSWI8` `Pos`, +`PTRC1`-`PTRC8` `Tr`, `EmcyGGIO1` `IntIn1` for the PDU; `OutMMDC1` `Vol` and +`Amp`, `InMMDC1` `Amp`, `STMP1` `Tmp`, `CycGGIO1` `CntVal1` for the DC-DC. The +data sets are GOOSE's own, one report control block each: + +| Report control block | Kind | Data set | Reports | +|---|---|---|---| +| `LLN0$BR$brcb_pdu01` | buffered | `ds_pdu` | a PDU change as it happens; the last 32 kept while no client is connected and replayed to one that resumes from its last EntryID | +| `LLN0$RP$urcb_dcdc01` | unbuffered | `ds_dcdc` | the DC-DC's members that moved, every 100 ms | + +Both start with data change, quality change and general interrogation as +triggers and no integrity period; a client sets its own. The node has no clock: +time stamps are time since boot, flagged clock not synchronized. No controls, +files or setting groups. + As an AUTOSAR ECU it sends what `../arxml/can-full.arxml` (an AUTOSAR R19-11 System Template of this bench, `bench.dbc` included) describes: E2E profiles 1, 2 and 5, a container with short headers, a multiplexed PDU and a SecOC profile 1 @@ -225,6 +243,7 @@ limit, `0x1003` for a wrong key, `0x1` for any other command. | `../testing/suites/doip` | DC-DC | Its UDS server as a DoIP entity (ISO 13400-2, `../lib/doip`), checked with a client written from the standard and with zelos-can's (doipclient), as the UDS and OBD extensions connect: vehicle identification by plain request, EID and VIN, answered within 500 ms, and one responder to a broadcast; entity status, power mode, header NACKs; routing activation's codes (0x10, 0x00, 0x02, 0x03 and 0x01 decided by alive checks, 0x06), initial inactivity; diagnostic messages acknowledged, NACKed (0x02, 0x03, 0x04 above MDS) or answered; three announcements 500 ms apart after a reset. The UDS conformance suite, unchanged, over DoIP. One server, two transports: a CAN tester's session gives the DoIP tester 0x21 and only OBD, and S3 still ends it; a closed DoIP owner's output returns at once; a pending routine answers its own tester. Core: ztests in `../tests/lib/doip` | | `../testing/suites/someip` | DC-DC | Its SOME/IP service (DcdcService `0x5A00`, `../lib/someip`) and its SD, checked with a client written from the PRS: offers every second with TTL 3 and the service's UDP endpoint (where the SD group reaches the host: on this bench, not on the hardware bench, whose switch forwards it to IGMPv2 members only); FindService answered unicast within 100 ms; a subscription acknowledged, the Setpoint field's value at once, then DcdcStatus every 100 ms with none missing, each equal, within the frame's resolution, to the DCDC_Status of the same Counter; the getter equal to DID `0x0200`, and the notifier within 150 ms of a write over UDS; 0x28 stops the events, not SD or the getter; error codes; StopOffer at a reset, and the Reboot flag after it. Core: ztests in `../tests/lib/someip` | | `../testing/suites/goose` | DC-DC, PDU | Its GOOSE (`../lib/goose`) captured raw on the host interface on the node's subnet and decoded by a BER walk written from IEC 61850-8-1 Annex A: both control blocks with their destinations, references, goID and data set sizes; timeAllowedtoLive twice the period, or one of the on-change ladder's; stNum and sqNum in sequence, none missed; `gcb_dcdc` every 100 ms (within 5 % on hardware). Needs CAP_NET_RAW, which the bench's tester has. Core: ztests in `../tests/lib/goose` | +| `../testing/suites/mms` | DC-DC, PDU | Its MMS server (`../lib/mms`) with an MMS client on the host: the data sets and report control blocks the station file declares; a data object read with its quality and time; the unbuffered block reporting the DC-DC every 100 ms, none missed; a PDU channel switched over CANopen reported by the buffered block, and a change made while no client was connected replayed to the client that resumes. Core: ztests in `../tests/lib/mms` | | `../testing/suites/full` | all three | Every protocol at once for `--soak-s` (120 s here, 10 s on hardware): XCP DAQ, a UDS 64 KiB download and upload loop, CANopen operational with SYNC every 10 ms and RPDO1, J1939 and DCDC_Status. No EMCY, no DAQ sample lost, periods kept, and the node's counters (UDS DID `0x0110`) show no TX queue overflow, TX error or RX FIFO overrun | The suites drive the other nodes' roles themselves when those nodes are absent, @@ -233,7 +252,7 @@ Every test sets its own preconditions over the bus rather than assuming a fresh boot. `just test`, and CI on every change, run the core: xcp, j1939, canopen, autosar, -eth, the DoIP entity, goose and the coexistence suite, one boot and each protocol +eth, the DoIP entity, goose, mms and the coexistence suite, one boot and each protocol touched once. The rest (UDS conformance on CAN and over DoIP, DTCs and resets, DoIP arbitration, SOME/IP, OBD) run with `just test-all`, on hardware with `just hil`, and on CI for a pull request labelled `ci-full`, on demand, and diff --git a/can-full/justfile b/can-full/justfile index 4493eb9..68c9ce7 100644 --- a/can-full/justfile +++ b/can-full/justfile @@ -10,12 +10,12 @@ NODES := "vcu bms full" # Each node with a suite, as node:suite, in the order they run. `just test-all` # runs every suite on the bench; `just hil` runs one node's. full's # coexistence suite runs every protocol at once. -SUITES := "full:xcp full:uds full:obd full:j1939 full:canopen full:autosar full:eth full:doip full:someip full:goose full:full" +SUITES := "full:xcp full:uds full:obd full:j1939 full:canopen full:autosar full:eth full:doip full:someip full:goose full:mms full:full" # The core: one boot, each protocol touched once, then every protocol at once. # `just test` and CI run these on every change; the rest (UDS conformance on # CAN and DoIP, DTCs and resets, DoIP arbitration, SOME/IP, OBD) run while that # area is worked on, on hardware (`just hil`) and on CI by label or on schedule. -CORE := "full:xcp full:j1939 full:canopen full:autosar full:eth full:doip/test_entity.py full:goose full:full" +CORE := "full:xcp full:j1939 full:canopen full:autosar full:eth full:doip/test_entity.py full:goose full:mms full:full" # The firmware is built by the repository's shared recipes, one level up. FIRMWARE := quote(just_executable()) + " --justfile " + quote(justfile_directory() / ".." / "justfile") diff --git a/include/zelos/mms.h b/include/zelos/mms.h new file mode 100644 index 0000000..652209f --- /dev/null +++ b/include/zelos/mms.h @@ -0,0 +1,364 @@ +/* + * IEC 61850-8-1 MMS server, Edition 2: one logical device served from a const + * table on TCP 102 (RFC 1006 TPKT, ISO 8073 class 0, ISO 8327 session, ISO + * 8823 presentation, ISO 8650 ACSE, ISO 9506 MMS). No TLS, no authentication. + * + * Services: initiate, conclude, status, identify, getNameList (the domain; + * its named variables at every level, in the table's order; its named + * variable lists), getVariableAccessAttributes and read at any level (logical node, functional + * constraint, data object, attribute), read of several variables and of a + * named variable list, getNamedVariableListAttributes, write of report control + * block attributes, informationReport. A write to anything else answers + * object-access-denied, to a name that does not exist object-non-existent. + * Any other confirmed service is rejected (unrecognized-service). No controls, + * files, setting groups, logs, GOOSE control block objects, dynamic data sets, + * arrays, alternate access or specificationWithResult. + * + * Two clients at once. A third is answered a session REFUSE (congestion) and + * closed; a fourth connection is not taken. A connection that has not + * associated within 5 s is closed. Nothing times an associated client out: + * TCP keepalive finds a dead one. Malformed or oversized input + * closes that connection and no other. BER with definite lengths only. + * + * The MMS PDU is at most ZELOS_MMS_PDU_SIZE both ways, less if the client + * proposes less; a client proposing under ZELOS_MMS_PDU_MIN is closed. A name + * list that does not fit goes in pages (moreFollows, continueAfter; an unknown + * continueAfter answers continuation-invalid). Any other response that does + * not fit answers the service error pdu-size. Data TPDUs go out no larger + * than the size the connection negotiated (2048 at most, 128 if the client + * names none) and come in at any size, joined into one message. + * + * Values: the model's read() fills them; the core keeps the last copy, serves + * reads from it and reports its changes. They are read when poked, every + * scan_ms, and before a read is served. A quality leaf without a value is + * always good. A time leaf is core-owned: when a value of its data object last + * changed, as time since boot from 1970-01-01 with the quality "clock not + * synchronized"; 0 until the first change. + * + * Report control blocks (IEC 61850-7-2), attributes in the order of 8-1: + * RptID, RptEna, Resv (unbuffered only), DatSet, ConfRev, OptFlds, BufTm, + * SqNum, TrgOps, IntgPd, GI, then PurgeBuf, EntryID, TimeofEntry and ResvTms + * (buffered only), then Owner. At start: RptID the block's reference, TrgOps + * data change, quality change and general interrogation, OptFlds sequence + * number, time stamp, reason and data set name, BufTm 0, IntgPd 0. + * - A block belongs to the connection that reserved it (Resv, ResvTms above + * 0) or enabled it; Owner is that client's address. Another connection's + * write answers temporarily-unavailable, as does any write but RptEna and + * GI while the block is enabled, and GI while it is not. ConfRev, SqNum, + * TimeofEntry and Owner are read-only (object-access-denied). + * - When its connection closes the block is disabled and released; a + * buffered one with ResvTms above 0 stays reserved that many seconds for + * a client of the same address. ResvTms -1 is not used. + * - Triggers: data change (a value leaf), quality change (a quality leaf), + * integrity every IntgPd ms, general interrogation. Changes within BufTm + * ms of the first go in one report; a member changing twice sends the + * first report at once. SqNum starts at 0 when enabled and wraps at 8 + * bits unbuffered, 16 buffered. + * - Every OptFlds bit but segmentation is honoured; that bit reads back + * clear. RptEna is refused (object-attribute-inconsistent) without a data + * set, or when the block's largest report would not fit the connection's + * PDU. + * - Buffered: entries are kept in a ring of ZELOS_MMS_ENTRIES, also while + * the block is disabled or no client is connected. Enabling sends every + * entry not sent yet, oldest first, ZELOS_MMS_BURST per tick. Writing the + * EntryID of a report received sends everything after it; all zeros, + * everything held; an EntryID no longer held, or of an earlier boot, is + * refused on that attribute (object-value-invalid). BufOvfl marks the + * first report after an unsent entry was overwritten. General + * interrogation is never buffered and follows the entries waiting. + * Integrity reports are made only while the block is enabled: buffered + * without a client they would push the changes out of the ring. + * - Writing an attribute the value it has purges nothing. Changing RptID, + * DatSet, BufTm, TrgOps or IntgPd purges the buffer, as does PurgeBuf. + * - TimeofEntry is a BINARY-TIME, which cannot hold a date before 1984: it + * is time since boot from 1984-01-01. + * + * A send that fails closes that connection. The core never waits on a client; + * the socket layer's send may, for half a second at most. + */ + +#ifndef ZELOS_MMS_H_ +#define ZELOS_MMS_H_ + +#include +#include +#include + +#define ZELOS_MMS_PORT 102 +/* Clients at once, and one more connection to refuse a third with. */ +#define ZELOS_MMS_CLIENTS 2 +#define ZELOS_MMS_SOCKETS (ZELOS_MMS_CLIENTS + 1) +/* Largest MMS PDU sent or taken, and the least a client may propose. */ +#define ZELOS_MMS_PDU_SIZE 1024 +#define ZELOS_MMS_PDU_MIN 256 +/* Longest domain or item name (IEC 61850-8-1), and "domain/item". */ +#define ZELOS_MMS_NAME_MAX 64 +#define ZELOS_MMS_REF_MAX (2 * ZELOS_MMS_NAME_MAX + 1) +/* The model's limits: values, members of one data set, report control blocks. */ +#define ZELOS_MMS_VALUES_MAX 32 +#define ZELOS_MMS_MEMBERS_MAX 24 +#define ZELOS_MMS_RCBS_MAX 4 +#define ZELOS_MMS_BUFFERED_MAX 2 +/* Entries a buffered block keeps, and how many it sends per tick. */ +#define ZELOS_MMS_ENTRIES 32 +#define ZELOS_MMS_BURST 8 +/* A leaf without a value: a quality that is always good, or a time. */ +#define ZELOS_MMS_NO_VALUE 0xFF +/* A report control block without a data set. */ +#define ZELOS_MMS_NO_DATA_SET 0xFF + +enum zelos_mms_type { + ZELOS_MMS_BOOLEAN, + /* Dbpos (IEC 61850-7-3): a 2-bit BIT STRING, intermediate 0, off 1, on 2, bad 3. */ + ZELOS_MMS_DBPOS, + /* An enumeration such as Beh: INTEGER, 8 bits. */ + ZELOS_MMS_ENUM, + ZELOS_MMS_INT32, + ZELOS_MMS_UINT32, + ZELOS_MMS_FLOAT32, + /* Quality (IEC 61850-7-3): a 13-bit BIT STRING. */ + ZELOS_MMS_QUALITY, + /* The data object's time stamp, kept by the core. */ + ZELOS_MMS_TIME, +}; + +/* One value, of its leaf's type. Zeroed before read() fills it. */ +union zelos_mms_value { + bool boolean; + uint8_t dbpos; + /* ZELOS_MMS_ENUM and ZELOS_MMS_INT32. */ + int32_t i32; + uint32_t u32; + float f32; + /* The 13 bits from bit 15 down: 0 good, 0x4000 invalid, 0xC000 questionable. */ + uint16_t quality; +}; + +/* A data attribute: "XSWI1", "ST", "Pos$stVal". */ +struct zelos_mms_leaf { + const char *ln; + const char *fc; + const char *path; + uint8_t type; + /* Its place in the values read() fills, or ZELOS_MMS_NO_VALUE. */ + uint8_t value; +}; + +/* A data set: "LLN0$ds", its members as indices into the leaves. */ +struct zelos_mms_data_set { + const char *name; + const uint8_t *members; + uint8_t count; +}; + +/* A report control block: "LLN0", "brcb01". Its logical node must have a leaf. */ +struct zelos_mms_rcb { + const char *ln; + const char *name; + bool buffered; + /* Index into the data sets: DatSet at start. */ + uint8_t data_set; + uint32_t conf_rev; +}; + +/* + * The server's model: one logical device. The leaves go depth first: those of + * one logical node together, of one functional constraint within it together, + * and so on down the path. A time leaf stamps the values of its own data + * object (the path's first part). Data set members are not time leaves. + */ +struct zelos_mms_model { + /* The logical device: the MMS domain. */ + const char *ld; + /* What identify answers. */ + const char *vendor; + const char *name; + const char *revision; + const struct zelos_mms_leaf *leaves; + uint8_t leaf_count; + const struct zelos_mms_data_set *data_sets; + uint8_t data_set_count; + const struct zelos_mms_rcb *rcbs; + uint8_t rcb_count; + /* Fill value_count values; any not written stays 0. */ + uint8_t value_count; + void (*read)(union zelos_mms_value *values); + /* Read the values at least this often, ms; 0: only when poked or read. */ + uint16_t scan_ms; +}; + +#if defined(CONFIG_ZELOS_MMS) + +/** + * Serve the model once lib/eth's address is up. Call once; the model must + * outlive the node. 0, or -errno: -EINVAL for a model the core refuses. + */ +int zelos_mms_start(const struct zelos_mms_model *model); + +/* A value may have changed: read them within 10 ms and report what did. Any context. */ +void zelos_mms_poke(void); + +#endif /* CONFIG_ZELOS_MMS */ + +/* + * The protocol core, free of I/O: bytes in, TPKTs out through ops. `now` is + * milliseconds on any monotonic clock that starts near 0 at boot. One thread + * drives it. Only zelos_mms_core_tick() says when it next has something to do: + * call it after every accept, receive and close, and again by the time it + * returns. + */ + +struct zelos_mms_ops { + /* + * Send one TPKT on socket s, all of it. The bytes are the core's and + * change once send returns. Every client waits while it does, so it + * bounds its wait. False: it failed, and the core closes s. + */ + bool (*send)(void *ctx, int s, const uint8_t *data, size_t len); + /* Close socket s. */ + void (*close)(void *ctx, int s); +}; + +/* Headers before an MMS PDU: TPKT and data TPDU, session, presentation. */ +#define ZELOS_MMS_HEAD 32 +#define ZELOS_MMS_FRAME_MAX (ZELOS_MMS_HEAD + ZELOS_MMS_PDU_SIZE) +/* Largest session message taken: its headers, then an MMS PDU. */ +#define ZELOS_MMS_SPDU_MAX (24 + ZELOS_MMS_PDU_SIZE) +/* TPKT header and the longest TPDU header taken. */ +#define ZELOS_MMS_TPDU_HEADER_MAX 64 + +enum zelos_mms_state { + ZELOS_MMS_FREE, + /* TCP only. */ + ZELOS_MMS_OPEN, + /* Transport connected. */ + ZELOS_MMS_CONNECTED, + ZELOS_MMS_ASSOCIATED, +}; + +struct zelos_mms_conn { + uint8_t state; + /* The client's address, for Owner. */ + uint8_t peer[16]; + uint8_t peer_len; + /* Closed at this time unless associated. */ + int64_t deadline; + /* Negotiated: the largest TPDU and MMS PDU. */ + uint16_t tpdu_size; + uint16_t pdu_size; + /* The presentation context identifiers the client chose. */ + uint8_t acse_ctx; + uint8_t mms_ctx; + /* The TPDU being received: header bytes so far, user data bytes to come. */ + uint8_t hdr_have; + uint16_t data_left; + uint8_t hdr[ZELOS_MMS_TPDU_HEADER_MAX]; + /* The session message being reassembled. */ + uint16_t have; + uint8_t buf[ZELOS_MMS_SPDU_MAX]; +}; + +/* One report as a buffered block keeps it; members by their place in the data set. */ +struct zelos_mms_entry { + uint64_t id; + int64_t time; + uint32_t inclusion; + /* Every member's reason for inclusion, or 0: each one's own change. */ + uint8_t reason; + union zelos_mms_value value[ZELOS_MMS_MEMBERS_MAX]; +}; + +struct zelos_mms_ring { + struct zelos_mms_entry entry[ZELOS_MMS_ENTRIES]; + /* Where the next entry goes; entries held; the newest of them not sent yet. */ + uint8_t head; + uint8_t count; + uint8_t unsent; + /* An unsent entry was overwritten: BufOvfl on the next report. */ + bool overflow; + /* The last EntryID given, and the newest one no longer held. */ + uint64_t last; + uint64_t lost; + /* TimeofEntry: when the last entry was made. */ + int64_t time; +}; + +struct zelos_mms_rcb_state { + char rpt_id[ZELOS_MMS_REF_MAX + 1]; + uint8_t data_set; + bool enabled; + bool resv; + int16_t resv_tms; + /* The socket that reserved or enabled it, or -1; its address. */ + int8_t conn; + uint8_t owner[16]; + uint8_t owner_len; + /* Buffered, its connection gone: reserved for the owner's address until then. */ + int64_t hold_until; + uint8_t trg_ops; + uint16_t opt_flds; + uint32_t buf_tm; + uint32_t intg_pd; + uint16_t sq_num; + /* A general interrogation is due. */ + bool gi; + /* Members changed and not reported yet, since when, and when BufTm ends. */ + uint32_t pending; + int64_t pending_since; + int64_t pending_until; + int64_t integrity_at; + /* A buffered block's ring, or NULL. */ + struct zelos_mms_ring *ring; +}; + +struct zelos_mms_core { + const struct zelos_mms_model *model; + const struct zelos_mms_ops *ops; + void *ctx; + /* The time of the call being served. */ + int64_t now; + int64_t scan_at; + struct zelos_mms_conn conn[ZELOS_MMS_SOCKETS]; + struct zelos_mms_rcb_state rcb[ZELOS_MMS_RCBS_MAX]; + struct zelos_mms_ring ring[ZELOS_MMS_BUFFERED_MAX]; + /* The values as last read, and when each last changed. */ + union zelos_mms_value last[ZELOS_MMS_VALUES_MAX]; + int64_t changed[ZELOS_MMS_VALUES_MAX]; + uint8_t out[ZELOS_MMS_FRAME_MAX]; +}; + +/** + * Check the model, read its values once and set every block to its start + * state. boot: a number that differs from boot to boot (a random one), the + * upper half of every EntryID, so that an EntryID of an earlier boot is not + * taken for one of this boot. 0, or -EINVAL: a limit above is exceeded, a name + * is too long or empty, the leaves are not depth first, an index is out of + * range. + */ +int zelos_mms_core_init(struct zelos_mms_core *mms, const struct zelos_mms_model *model, + uint32_t boot, const struct zelos_mms_ops *ops, void *ctx); + +/** + * A TCP connection came in from peer (4 or 16 address bytes). + * @return its socket index, or -1: none free, close it. + */ +int zelos_mms_core_accept(struct zelos_mms_core *mms, const uint8_t *peer, size_t peer_len, + int64_t now); + +/** Bytes received on socket s, any split. */ +void zelos_mms_core_receive(struct zelos_mms_core *mms, int s, const uint8_t *data, size_t len, + int64_t now); + +/** Close socket s (the peer closed it, the link went down): ops->close, then free. */ +void zelos_mms_core_close(struct zelos_mms_core *mms, int s, int64_t now); + +/** Run the timers and send the reports due. @return When to call again at the latest. */ +int64_t zelos_mms_core_tick(struct zelos_mms_core *mms, int64_t now); + +/** A value may have changed: read them now, then as zelos_mms_core_tick(). */ +int64_t zelos_mms_core_poke(struct zelos_mms_core *mms, int64_t now); + +/* Associated clients. */ +uint8_t zelos_mms_core_clients(const struct zelos_mms_core *mms); + +#endif /* ZELOS_MMS_H_ */ diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index f701c89..e24a096 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -11,3 +11,4 @@ add_subdirectory_ifdef(CONFIG_ZELOS_ETH eth) add_subdirectory_ifdef(CONFIG_ZELOS_DOIP_CORE doip) add_subdirectory_ifdef(CONFIG_ZELOS_SOMEIP_CORE someip) add_subdirectory_ifdef(CONFIG_ZELOS_GOOSE_CORE goose) +add_subdirectory_ifdef(CONFIG_ZELOS_MMS_CORE mms) diff --git a/lib/Kconfig b/lib/Kconfig index 212e493..bd6650a 100644 --- a/lib/Kconfig +++ b/lib/Kconfig @@ -21,3 +21,4 @@ rsource "eth/Kconfig" rsource "doip/Kconfig" rsource "someip/Kconfig" rsource "goose/Kconfig" +rsource "mms/Kconfig" diff --git a/lib/mms/CMakeLists.txt b/lib/mms/CMakeLists.txt new file mode 100644 index 0000000..ed1278e --- /dev/null +++ b/lib/mms/CMakeLists.txt @@ -0,0 +1,9 @@ +zephyr_library() +zephyr_library_sources( + core/mms_ber.c + core/mms_core.c + core/mms_model.c + core/mms_report.c + core/mms_service.c +) +zephyr_library_sources_ifdef(CONFIG_ZELOS_MMS zephyr/mms.c) diff --git a/lib/mms/Kconfig b/lib/mms/Kconfig new file mode 100644 index 0000000..cec3a57 --- /dev/null +++ b/lib/mms/Kconfig @@ -0,0 +1,16 @@ +config ZELOS_MMS + bool "IEC 61850 MMS server" + depends on ZELOS_ETH && NET_TCP && NET_SOCKETS + select ZELOS_MMS_CORE + select ZELOS_REBOOT + help + One logical device on TCP 102 from a const table: discovery, + reads, data sets, buffered and unbuffered reports, two clients + at once, from one thread. See include/zelos/mms.h. + +config ZELOS_MMS_CORE + bool "MMS server core" + help + The protocol stack, services and report control blocks without + sockets. ZELOS_MMS selects it; on its own it is only useful to + unit tests. diff --git a/lib/mms/core/mms_ber.c b/lib/mms/core/mms_ber.c new file mode 100644 index 0000000..70e3c32 --- /dev/null +++ b/lib/mms/core/mms_ber.c @@ -0,0 +1,210 @@ +/* BER for the MMS core (ITU-T X.690): definite lengths, one-byte tags. */ + +#include "mms_internal.h" + +void mms_put(struct mms_enc *e, const void *src, size_t n) +{ + if (e->overflow || e->cap - e->len < n) { + e->overflow = true; + return; + } + if (n == 0) { + return; + } + memcpy(&e->buf[e->len], src, n); + e->len += n; +} + +static void put_u8(struct mms_enc *e, uint8_t v) +{ + mms_put(e, &v, 1); +} + +void mms_tlv(struct mms_enc *e, uint8_t tag, const void *v, size_t n) +{ + put_u8(e, tag); + if (n >= 0x100) { + put_u8(e, 0x82); + put_u8(e, (uint8_t)(n >> 8)); + } else if (n >= 0x80) { + put_u8(e, 0x81); + } + put_u8(e, (uint8_t)n); + mms_put(e, v, n); +} + +void mms_begin(struct mms_enc *e, uint8_t tag) +{ + if (e->depth == MMS_ENC_DEPTH) { + e->overflow = true; + return; + } + put_u8(e, tag); + e->open[e->depth++] = (uint16_t)e->len; + /* The length, once known. */ + put_u8(e, 0); +} + +void mms_end(struct mms_enc *e) +{ + size_t at; + size_t n; + size_t extra; + + if (e->overflow || e->depth == 0) { + e->overflow = true; + return; + } + at = e->open[--e->depth]; + n = e->len - at - 1; + extra = n < 0x80 ? 0 : n < 0x100 ? 1 : 2; + if (e->cap - e->len < extra) { + e->overflow = true; + return; + } + memmove(&e->buf[at + 1 + extra], &e->buf[at + 1], n); + e->len += extra; + if (extra == 0) { + e->buf[at] = (uint8_t)n; + } else if (extra == 1) { + e->buf[at] = 0x81; + e->buf[at + 1] = (uint8_t)n; + } else { + e->buf[at] = 0x82; + e->buf[at + 1] = (uint8_t)(n >> 8); + e->buf[at + 2] = (uint8_t)n; + } +} + +void mms_u8(struct mms_enc *e, uint8_t tag, uint8_t v) +{ + mms_tlv(e, tag, &v, 1); +} + +void mms_str(struct mms_enc *e, uint8_t tag, const char *s) +{ + mms_tlv(e, tag, s, strlen(s)); +} + +/* INTEGER, minimal two's complement: a leading byte that only repeats the sign goes. */ +void mms_int(struct mms_enc *e, uint8_t tag, int64_t v) +{ + uint8_t be[8]; + size_t i = 0; + + for (size_t k = 0; k < sizeof(be); k++) { + be[k] = (uint8_t)((uint64_t)v >> (56 - 8 * k)); + } + while (i < sizeof(be) - 1 && ((be[i] == 0x00 && (be[i + 1] & 0x80) == 0) || + (be[i] == 0xFF && (be[i + 1] & 0x80) != 0))) { + i++; + } + mms_tlv(e, tag, be + i, sizeof(be) - i); +} + +void mms_bool(struct mms_enc *e, uint8_t tag, bool v) +{ + mms_u8(e, tag, v ? 0xFF : 0x00); +} + +void mms_value(struct mms_enc *e, uint8_t type, union zelos_mms_value v) +{ + uint32_t bits; + + switch (type) { + case ZELOS_MMS_BOOLEAN: + mms_bool(e, MMS_BOOL, v.boolean); + break; + case ZELOS_MMS_DBPOS: + /* 2 bits, the first the most significant; 6 of the octet unused. */ + mms_tlv(e, MMS_BIT_STRING, (uint8_t[]){6, (uint8_t)((v.dbpos & 0x3) << 6)}, 2); + break; + case ZELOS_MMS_ENUM: + case ZELOS_MMS_INT32: + mms_int(e, MMS_INTEGER, v.i32); + break; + case ZELOS_MMS_UINT32: + mms_int(e, MMS_UNSIGNED, v.u32); + break; + case ZELOS_MMS_FLOAT32: + /* Exponent width 8, then IEEE 754 single, big-endian. */ + memcpy(&bits, &v.f32, sizeof(bits)); + mms_tlv(e, MMS_FLOAT, + (uint8_t[]){8, (uint8_t)(bits >> 24), (uint8_t)(bits >> 16), + (uint8_t)(bits >> 8), (uint8_t)bits}, + 5); + break; + case ZELOS_MMS_QUALITY: + /* 13 bits; 3 of the second octet unused. */ + mms_tlv(e, MMS_BIT_STRING, + (uint8_t[]){3, (uint8_t)(v.quality >> 8), (uint8_t)(v.quality & 0xF8)}, 3); + break; + default: + e->overflow = true; + break; + } +} + +bool mms_next(const uint8_t **p, const uint8_t *end, struct mms_tlv *t) +{ + const uint8_t *q = *p; + size_t len; + + if (end - q < 2 || (q[0] & 0x1F) == 0x1F) { + return false; + } + t->tag = q[0]; + len = q[1]; + q += 2; + if (len == 0x81) { + if (end - q < 1) { + return false; + } + len = q[0]; + q += 1; + } else if (len == 0x82) { + if (end - q < 2) { + return false; + } + len = (size_t)q[0] << 8 | q[1]; + q += 2; + } else if (len >= 0x80) { + /* Indefinite, or longer than any message taken. */ + return false; + } + if ((size_t)(end - q) < len) { + return false; + } + t->v = q; + t->len = len; + *p = q + len; + return true; +} + +bool mms_find(const struct mms_tlv *in, uint8_t tag, struct mms_tlv *t) +{ + const uint8_t *p = in->v; + const uint8_t *end = in->v + in->len; + + while (p < end && mms_next(&p, end, t)) { + if (t->tag == tag) { + return true; + } + } + return false; +} + +bool mms_get_int(const struct mms_tlv *t, int64_t *v) +{ + uint64_t u; + + if (t->len == 0 || t->len > 8) { + return false; + } + u = (t->v[0] & 0x80) != 0 ? UINT64_MAX : 0; + for (size_t i = 0; i < t->len; i++) { + u = u << 8 | t->v[i]; + } + *v = (int64_t)u; + return true; +} diff --git a/lib/mms/core/mms_core.c b/lib/mms/core/mms_core.c new file mode 100644 index 0000000..b0213fb --- /dev/null +++ b/lib/mms/core/mms_core.c @@ -0,0 +1,660 @@ +/* + * MMS server core. No I/O: see include/zelos/mms.h. This file is the stack + * under MMS (TPKT, class 0 transport, session, presentation, ACSE with the MMS + * initiate); the services are in mms_service.c, the model's objects in + * mms_model.c, the report control blocks in mms_report.c. + */ + +#include "mms_internal.h" + +#define ASSOCIATE_MS 5000 + +/* TPDU codes (ISO 8073) and the TPDU size parameter: 2^code octets. */ +#define TPDU_CR 0xE0 +#define TPDU_CC 0xD0 +#define TPDU_DT 0xF0 +#define TPDU_EOT 0x80 +#define TPDU_SIZE 0xC0 +#define TPDU_CODE_MIN 7 +#define TPDU_CODE_MAX 11 +/* TPKT header, then the data TPDU's. */ +#define TPKT 4 +#define DT_HEADER 7 + +/* Session SPDUs (ISO 8327) and parameters. */ +#define SPDU_FINISH 0x09 +#define SPDU_DISCONNECT 0x0A +#define SPDU_REFUSE 0x0C +#define SPDU_CONNECT 0x0D +#define SPDU_ACCEPT 0x0E +#define SESSION_USER_DATA 0xC1 +#define SESSION_EXTENDED_USER_DATA 0xC2 +/* SPM congestion at connect time. */ +#define REFUSE_CONGESTION 0x83 + +#define INITIATE_REQUEST 0xA8 +#define INITIATE_RESPONSE 0xA9 + +/* Abstract syntaxes: ACSE, and MMS (ISO 9506-2); the BER transfer syntax; MMS over ACSE. */ +static const uint8_t acse_syntax[] = {0x52, 0x01, 0x00, 0x01}; +static const uint8_t mms_syntax[] = {0x28, 0xCA, 0x22, 0x02, 0x01}; +static const uint8_t ber_syntax[] = {0x51, 0x01}; +static const uint8_t mms_context[] = {0x28, 0xCA, 0x22, 0x02, 0x03}; + +/* + * ParameterSupportOptions str2, vnam, vlis, and ServiceSupportOptions + * getNameList, read, write, getVariableAccessAttributes, + * getNamedVariableListAttributes, informationReport, conclude. + */ +#define PARAMETER_CBB 0x61 +static const uint8_t services[] = {3, 0x4E, 0x08, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x01, 0x10}; +#define NESTING 10 + +uint8_t zelos_mms_core_clients(const struct zelos_mms_core *mms) +{ + uint8_t n = 0; + + for (int i = 0; i < ZELOS_MMS_SOCKETS; i++) { + n += mms->conn[i].state == ZELOS_MMS_ASSOCIATED; + } + return n; +} + +int zelos_mms_core_init(struct zelos_mms_core *mms, const struct zelos_mms_model *model, + uint32_t boot, const struct zelos_mms_ops *ops, void *ctx) +{ + const int err = mms_model_check(model); + + if (err != 0) { + return err; + } + memset(mms, 0, sizeof(*mms)); + mms->model = model; + mms->ops = ops; + mms->ctx = ctx; + /* The values at start, before any block looks at them: no change, no report. */ + mms_scan(mms); + memset(mms->changed, 0, sizeof(mms->changed)); + mms_rcb_init(mms, boot); + return 0; +} + +int zelos_mms_core_accept(struct zelos_mms_core *mms, const uint8_t *peer, size_t peer_len, + int64_t now) +{ + for (int i = 0; i < ZELOS_MMS_SOCKETS; i++) { + struct zelos_mms_conn *conn = &mms->conn[i]; + + if (conn->state == ZELOS_MMS_FREE) { + memset(conn, 0, sizeof(*conn)); + conn->state = ZELOS_MMS_OPEN; + conn->deadline = now + ASSOCIATE_MS; + conn->peer_len = (uint8_t)MMS_MIN(peer_len, sizeof(conn->peer)); + if (conn->peer_len > 0) { + memcpy(conn->peer, peer, conn->peer_len); + } + return i; + } + } + return -1; +} + +static void close_now(struct zelos_mms_core *mms, int s) +{ + if (mms->conn[s].state == ZELOS_MMS_FREE) { + return; + } + mms->ops->close(mms->ctx, s); + mms->conn[s].state = ZELOS_MMS_FREE; + mms_rcb_closed(mms, s); +} + +void zelos_mms_core_close(struct zelos_mms_core *mms, int s, int64_t now) +{ + mms->now = now; + close_now(mms, s); +} + +/* A socket that closed while its answer was made gets nothing more. */ +static void send(struct zelos_mms_core *mms, int s, const uint8_t *data, size_t len) +{ + if (mms->conn[s].state != ZELOS_MMS_FREE && !mms->ops->send(mms->ctx, s, data, len)) { + close_now(mms, s); + } +} + +/* + * Send the session message at p as data TPDUs of the negotiated size. Each + * TPDU's header is written over the DT_HEADER bytes before its data: free + * room before the first, bytes already sent before the others. + */ +static void transmit(struct zelos_mms_core *mms, int s, uint8_t *p, size_t len) +{ + const struct zelos_mms_conn *conn = &mms->conn[s]; + const size_t room = conn->tpdu_size - (DT_HEADER - TPKT); + + do { + const size_t n = MMS_MIN(len, room); + uint8_t *tpkt = p - DT_HEADER; + + tpkt[0] = 3; + tpkt[1] = 0; + tpkt[2] = (uint8_t)((DT_HEADER + n) >> 8); + tpkt[3] = (uint8_t)(DT_HEADER + n); + tpkt[4] = 2; + tpkt[5] = TPDU_DT; + tpkt[6] = n == len ? TPDU_EOT : 0; + send(mms, s, tpkt, DT_HEADER + n); + p += n; + len -= n; + } while (len > 0 && conn->state != ZELOS_MMS_FREE); +} + +/* A BER tag and length before p; where they start. */ +static uint8_t *wrap(uint8_t *p, uint8_t tag, size_t len) +{ + if (len >= 0x100) { + *--p = (uint8_t)len; + *--p = (uint8_t)(len >> 8); + *--p = 0x82; + } else if (len >= 0x80) { + *--p = (uint8_t)len; + *--p = 0x81; + } else { + *--p = (uint8_t)len; + } + *--p = tag; + return p; +} + +/* A session code and length before p: one octet, or 0xFF and two. */ +static uint8_t *session_wrap(uint8_t *p, uint8_t code, size_t len) +{ + if (len >= 0xFF) { + *--p = (uint8_t)len; + *--p = (uint8_t)(len >> 8); + *--p = 0xFF; + } else { + *--p = (uint8_t)len; + } + *--p = code; + return p; +} + +/* Presentation user data in context ctx around the len bytes at &out[ZELOS_MMS_HEAD]. */ +static uint8_t *user_data(struct zelos_mms_core *mms, uint8_t ctx, size_t len) +{ + uint8_t *end = &mms->out[ZELOS_MMS_HEAD + len]; + uint8_t *p = wrap(&mms->out[ZELOS_MMS_HEAD], 0xA0, len); + + *--p = ctx; + *--p = 1; + *--p = 0x02; + p = wrap(p, 0x30, (size_t)(end - p)); + return wrap(p, 0x61, (size_t)(end - p)); +} + +void mms_send_pdu(struct zelos_mms_core *mms, int s, size_t len) +{ + uint8_t *end = &mms->out[ZELOS_MMS_HEAD + len]; + uint8_t *p = user_data(mms, mms->conn[s].mms_ctx, len); + + /* Give tokens, then data transfer: both empty. */ + *--p = 0x00; + *--p = 0x01; + *--p = 0x00; + *--p = 0x01; + transmit(mms, s, p, (size_t)(end - p)); +} + +/* A session length at *p, which moves past it. */ +static bool session_len(const uint8_t **p, const uint8_t *end, size_t *len) +{ + const uint8_t *q = *p; + + if (end - q < 1) { + return false; + } + *len = *q++; + if (*len == 0xFF) { + if (end - q < 2) { + return false; + } + *len = (size_t)q[0] << 8 | q[1]; + q += 2; + } + if ((size_t)(end - q) < *len) { + return false; + } + *p = q; + return true; +} + +/* The user data of the session message in buf: its parameter 193 or 194. */ +static bool session_user_data(const uint8_t *buf, size_t have, struct mms_tlv *data) +{ + const uint8_t *p = buf + 1; + const uint8_t *end = buf + have; + size_t len; + + if (have < 2 || !session_len(&p, end, &len)) { + return false; + } + end = p + len; + while (p < end) { + const uint8_t code = *p++; + + if (!session_len(&p, end, &len)) { + return false; + } + if (code == SESSION_USER_DATA || code == SESSION_EXTENDED_USER_DATA) { + data->v = p; + data->len = len; + return true; + } + p += len; + } + return false; +} + +/* A presentation context identifier: one octet, below 128. */ +static bool context_id(const struct mms_tlv *in, uint8_t *id) +{ + struct mms_tlv t; + + if (!mms_find(in, 0x02, &t) || t.len != 1 || t.v[0] >= 0x80) { + return false; + } + *id = t.v[0]; + return true; +} + +static bool is_syntax(const struct mms_tlv *t, const uint8_t *oid, size_t len) +{ + return t->len == len && memcmp(t->v, oid, len) == 0; +} + +/* + * The session CONNECT in buf: a presentation CP, in it an ACSE AARQ, in it an + * MMS initiate-Request. Answer ACCEPT with CPA, AARE and initiate-Response. + * False: not understood, or its PDU size is too small. + */ +static bool associate(struct zelos_mms_core *mms, int s) +{ + /* ACCEPT's own parameters: version 2, no extended concatenation; duplex. */ + static const uint8_t accept[] = {0x05, 0x06, 0x13, 0x01, 0x00, 0x16, + 0x01, 0x02, 0x14, 0x02, 0x00, 0x02}; + struct zelos_mms_conn *conn = &mms->conn[s]; + struct mms_enc e = {.buf = &mms->out[ZELOS_MMS_HEAD], .cap = ZELOS_MMS_PDU_SIZE}; + struct mms_tlv data; + struct mms_tlv cp; + struct mms_tlv normal; + struct mms_tlv contexts; + struct mms_tlv selector; + struct mms_tlv t; + struct mms_tlv initiate; + struct mms_tlv detail; + const uint8_t *p; + const uint8_t *end; + uint8_t *q; + int64_t pdu_size = ZELOS_MMS_PDU_SIZE; + int64_t calling = 1; + int64_t called = 1; + int64_t nesting = NESTING; + uint8_t cbb = PARAMETER_CBB; + bool acse = false; + bool mms_found = false; + + if (!session_user_data(conn->buf, conn->have, &data)) { + return false; + } + p = data.v; + if (!mms_next(&p, data.v + data.len, &cp) || cp.tag != 0x31 || + !mms_find(&cp, 0xA2, &normal) || !mms_find(&normal, 0xA4, &contexts)) { + return false; + } + + /* CPA: normal mode, the called selector back, a result for each context. */ + mms_begin(&e, 0x31); + mms_begin(&e, 0xA0); + mms_u8(&e, 0x80, 1); + mms_end(&e); + mms_begin(&e, 0xA2); + if (mms_find(&normal, 0x82, &selector)) { + mms_tlv(&e, 0x83, selector.v, selector.len); + } + mms_begin(&e, 0xA5); + p = contexts.v; + end = contexts.v + contexts.len; + while (p < end) { + struct mms_tlv context; + struct mms_tlv syntax; + uint8_t id; + + if (!mms_next(&p, end, &context) || !context_id(&context, &id) || + !mms_find(&context, 0x06, &syntax)) { + return false; + } + mms_begin(&e, 0x30); + if (is_syntax(&syntax, acse_syntax, sizeof(acse_syntax))) { + acse = true; + conn->acse_ctx = id; + } else if (is_syntax(&syntax, mms_syntax, sizeof(mms_syntax))) { + mms_found = true; + conn->mms_ctx = id; + } else { + /* Provider rejection: abstract syntax not supported. */ + mms_u8(&e, 0x80, 2); + mms_u8(&e, 0x82, 1); + mms_end(&e); + continue; + } + mms_u8(&e, 0x80, 0); + mms_tlv(&e, 0x81, ber_syntax, sizeof(ber_syntax)); + mms_end(&e); + } + mms_end(&e); + + /* Down to the initiate-Request: user data, PDV list, AARQ, user information, EXTERNAL. */ + if (!acse || !mms_found || !mms_find(&normal, 0x61, &t) || !mms_find(&t, 0x30, &t) || + !mms_find(&t, 0xA0, &t) || !mms_find(&t, 0x60, &t) || !mms_find(&t, 0xBE, &t) || + !mms_find(&t, 0x28, &t) || !mms_find(&t, 0xA0, &t) || + !mms_find(&t, INITIATE_REQUEST, &initiate)) { + return false; + } + /* Each limit: the lesser of the client's and the server's. */ + if (mms_find(&initiate, 0x80, &t) && + (!mms_get_int(&t, &pdu_size) || pdu_size < ZELOS_MMS_PDU_MIN)) { + return false; + } + if (!mms_find(&initiate, 0x81, &t) || !mms_get_int(&t, &calling) || + !mms_find(&initiate, 0x82, &t) || !mms_get_int(&t, &called) || calling < 1 || + called < 0) { + return false; + } + if (mms_find(&initiate, 0x83, &t) && (!mms_get_int(&t, &nesting) || nesting < 0)) { + return false; + } + if (mms_find(&initiate, 0xA4, &detail) && mms_find(&detail, 0x81, &t) && t.len >= 2) { + cbb &= t.v[1]; + } + conn->pdu_size = (uint16_t)MMS_MIN(pdu_size, ZELOS_MMS_PDU_SIZE); + + mms_begin(&e, 0x61); + mms_begin(&e, 0x30); + mms_u8(&e, 0x02, conn->acse_ctx); + mms_begin(&e, 0xA0); + /* AARE: the MMS application context, accepted, no diagnostic. */ + mms_begin(&e, 0x61); + mms_begin(&e, 0xA1); + mms_tlv(&e, 0x06, mms_context, sizeof(mms_context)); + mms_end(&e); + mms_begin(&e, 0xA2); + mms_u8(&e, 0x02, 0); + mms_end(&e); + mms_begin(&e, 0xA3); + mms_begin(&e, 0xA1); + mms_u8(&e, 0x02, 0); + mms_end(&e); + mms_end(&e); + mms_begin(&e, 0xBE); + mms_begin(&e, 0x28); + mms_u8(&e, 0x02, conn->mms_ctx); + mms_begin(&e, 0xA0); + mms_begin(&e, INITIATE_RESPONSE); + mms_int(&e, 0x80, conn->pdu_size); + mms_int(&e, 0x81, MMS_MIN(calling, 1)); + mms_int(&e, 0x82, MMS_MIN(called, 1)); + mms_int(&e, 0x83, MMS_MIN(nesting, NESTING)); + mms_begin(&e, 0xA4); + /* Version 1. */ + mms_u8(&e, 0x80, 1); + mms_tlv(&e, 0x81, (uint8_t[]){5, cbb, 0}, 3); + mms_tlv(&e, 0x82, services, sizeof(services)); + while (e.depth > 0) { + mms_end(&e); + } + if (e.overflow) { + return false; + } + + /* ACCEPT: its parameters, then all of the above as user data. */ + end = &mms->out[ZELOS_MMS_HEAD + e.len]; + q = session_wrap(&mms->out[ZELOS_MMS_HEAD], SESSION_USER_DATA, e.len); + q -= sizeof(accept); + memcpy(q, accept, sizeof(accept)); + q = session_wrap(q, SPDU_ACCEPT, (size_t)(end - q)); + conn->state = ZELOS_MMS_ASSOCIATED; + transmit(mms, s, q, (size_t)(end - q)); + return true; +} + +/* A whole session message in buf. False: close. */ +static bool spdu(struct zelos_mms_core *mms, int s) +{ + static const uint8_t data_transfer[] = {0x01, 0x00, 0x01, 0x00}; + /* RLRE, reason normal. */ + static const uint8_t released[] = {0x63, 0x03, 0x80, 0x01, 0x00}; + struct zelos_mms_conn *conn = &mms->conn[s]; + struct mms_tlv t = {.v = &conn->buf[sizeof(data_transfer)]}; + uint8_t id; + uint8_t *q; + uint8_t *end; + + if (conn->have == 0) { + return false; + } + if (conn->state == ZELOS_MMS_CONNECTED) { + if (conn->buf[0] != SPDU_CONNECT) { + return false; + } + if (zelos_mms_core_clients(mms) >= ZELOS_MMS_CLIENTS) { + q = &mms->out[ZELOS_MMS_HEAD]; + q[0] = SPDU_REFUSE; + q[1] = 3; + /* Reason code. */ + q[2] = 0x32; + q[3] = 1; + q[4] = REFUSE_CONGESTION; + transmit(mms, s, q, 5); + return false; + } + return associate(mms, s); + } + if (conn->buf[0] == SPDU_FINISH) { + /* DISCONNECT with the release response, then the connection goes. */ + memcpy(&mms->out[ZELOS_MMS_HEAD], released, sizeof(released)); + end = &mms->out[ZELOS_MMS_HEAD + sizeof(released)]; + q = user_data(mms, conn->acse_ctx, sizeof(released)); + q = session_wrap(q, SESSION_USER_DATA, (size_t)(end - q)); + q = session_wrap(q, SPDU_DISCONNECT, (size_t)(end - q)); + transmit(mms, s, q, (size_t)(end - q)); + return false; + } + /* Give tokens and data transfer, then presentation user data: a PDV list. */ + if (conn->have < sizeof(data_transfer) || + memcmp(conn->buf, data_transfer, sizeof(data_transfer)) != 0) { + /* ABORT, or anything else. */ + return false; + } + t.len = conn->have - sizeof(data_transfer); + if (!mms_find(&t, 0x61, &t) || !mms_find(&t, 0x30, &t) || !context_id(&t, &id) || + id != conn->mms_ctx || !mms_find(&t, 0xA0, &t)) { + return false; + } + return mms_pdu(mms, s, t.v, t.len); +} + +/* + * A connection request in hdr. Answer the confirm, class 0: the peer's + * reference, this socket's, a TPDU size no larger than the request's or 2048 + * (128 if it names none), and its TSAP identifiers back. + */ +static bool connection_request(struct zelos_mms_core *mms, int s) +{ + struct zelos_mms_conn *conn = &mms->conn[s]; + /* From the length indicator: code, references, class, then parameters to cr[li]. */ + const uint8_t *cr = &conn->hdr[TPKT]; + const size_t end = (size_t)cr[0] + 1; + uint8_t *cc = mms->out; + /* After the confirm's fixed part and its size parameter. */ + uint8_t *out = &cc[TPKT + 10]; + uint8_t code = TPDU_CODE_MIN; + size_t n; + + if (conn->state != ZELOS_MMS_OPEN || end < 7 || conn->data_left != 0) { + return false; + } + for (n = 7; n + 2 <= end && n + 2 + cr[n + 1] <= end; n += 2 + cr[n + 1]) { + if (cr[n] == TPDU_SIZE && cr[n + 1] == 1) { + code = cr[n + 2] < TPDU_CODE_MIN ? TPDU_CODE_MIN + : cr[n + 2] > TPDU_CODE_MAX ? TPDU_CODE_MAX + : cr[n + 2]; + } else if (cr[n] == 0xC1 || cr[n] == 0xC2) { + memcpy(out, &cr[n], 2 + cr[n + 1]); + out += 2 + cr[n + 1]; + } + } + if (n != end) { + return false; + } + n = (size_t)(out - cc); + cc[0] = 3; + cc[1] = 0; + cc[2] = 0; + cc[3] = (uint8_t)n; + cc[TPKT] = (uint8_t)(n - TPKT - 1); + cc[TPKT + 1] = TPDU_CC; + cc[TPKT + 2] = cr[4]; + cc[TPKT + 3] = cr[5]; + cc[TPKT + 4] = 0; + cc[TPKT + 5] = (uint8_t)(s + 1); + cc[TPKT + 6] = 0; + cc[TPKT + 7] = TPDU_SIZE; + cc[TPKT + 8] = 1; + cc[TPKT + 9] = code; + conn->tpdu_size = (uint16_t)(1U << code); + conn->state = ZELOS_MMS_CONNECTED; + send(mms, s, cc, n); + return true; +} + +/* A TPDU's header is complete in hdr. False: close. */ +static bool tpdu(struct zelos_mms_core *mms, int s) +{ + const struct zelos_mms_conn *conn = &mms->conn[s]; + + switch (conn->hdr[TPKT + 1] & 0xF0) { + case TPDU_DT: + return conn->state >= ZELOS_MMS_CONNECTED && conn->hdr[TPKT] == 2 && + conn->data_left <= sizeof(conn->buf) - conn->have; + case TPDU_CR: + return connection_request(mms, s); + default: + /* Disconnect, error, and what class 0 does not have. */ + return false; + } +} + +void zelos_mms_core_receive(struct zelos_mms_core *mms, int s, const uint8_t *data, size_t len, + int64_t now) +{ + struct zelos_mms_conn *conn = &mms->conn[s]; + + mms->now = now; + while (len > 0 && conn->state != ZELOS_MMS_FREE) { + size_t n; + + if (conn->data_left == 0) { + /* The TPKT header and the TPDU's length indicator, then its header. */ + const size_t want = + conn->hdr_have <= TPKT ? TPKT + 1 : TPKT + 1 + conn->hdr[TPKT]; + size_t size; + + n = MMS_MIN(len, want - conn->hdr_have); + memcpy(&conn->hdr[conn->hdr_have], data, n); + conn->hdr_have += (uint8_t)n; + data += n; + len -= n; + if (conn->hdr_have <= TPKT) { + continue; + } + size = (size_t)conn->hdr[2] << 8 | conn->hdr[3]; + /* A length indicator covers at least a code and one octet more. */ + if (conn->hdr[0] != 3 || conn->hdr[TPKT] < 2 || + conn->hdr[TPKT] > sizeof(conn->hdr) - TPKT - 1 || + size < (size_t)TPKT + 1 + conn->hdr[TPKT]) { + close_now(mms, s); + return; + } + if (conn->hdr_have < TPKT + 1 + conn->hdr[TPKT]) { + continue; + } + conn->data_left = (uint16_t)(size - TPKT - 1 - conn->hdr[TPKT]); + if (!tpdu(mms, s)) { + close_now(mms, s); + return; + } + } else { + n = MMS_MIN(len, conn->data_left); + memcpy(&conn->buf[conn->have], data, n); + conn->have += (uint16_t)n; + conn->data_left -= (uint16_t)n; + data += n; + len -= n; + } + if (conn->data_left > 0) { + continue; + } + conn->hdr_have = 0; + if ((conn->hdr[TPKT + 1] & 0xF0) == TPDU_DT && + (conn->hdr[TPKT + 2] & TPDU_EOT) != 0) { + const bool ok = spdu(mms, s); + + conn->have = 0; + if (!ok) { + close_now(mms, s); + return; + } + } + } + /* What a write set going: a general interrogation, the entries of a block enabled. */ + (void)mms_report_run(mms); +} + +int64_t zelos_mms_core_tick(struct zelos_mms_core *mms, int64_t now) +{ + int64_t next = MMS_FOREVER; + int64_t reports; + + mms->now = now; + for (int i = 0; i < ZELOS_MMS_SOCKETS; i++) { + const struct zelos_mms_conn *conn = &mms->conn[i]; + + if (conn->state != ZELOS_MMS_OPEN && conn->state != ZELOS_MMS_CONNECTED) { + continue; + } + if (now >= conn->deadline) { + close_now(mms, i); + } else { + next = MMS_MIN(next, conn->deadline); + } + } + if (mms->model->scan_ms > 0) { + if (now >= mms->scan_at) { + mms_scan(mms); + mms->scan_at = now + mms->model->scan_ms; + } + next = MMS_MIN(next, mms->scan_at); + } + reports = mms_report_run(mms); + return MMS_MIN(next, reports); +} + +int64_t zelos_mms_core_poke(struct zelos_mms_core *mms, int64_t now) +{ + mms->now = now; + mms_scan(mms); + return zelos_mms_core_tick(mms, now); +} diff --git a/lib/mms/core/mms_internal.h b/lib/mms/core/mms_internal.h new file mode 100644 index 0000000..a60840c --- /dev/null +++ b/lib/mms/core/mms_internal.h @@ -0,0 +1,169 @@ +/* What the MMS core's files share. Not an API: see include/zelos/mms.h. */ + +#ifndef ZELOS_MMS_INTERNAL_H_ +#define ZELOS_MMS_INTERNAL_H_ + +#include + +#include + +/* Evaluates both twice: no calls in its arguments. */ +#define MMS_MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MMS_FOREVER INT64_MAX + +/* DataAccessError (ISO 9506-2); MMS_SUCCESS is none. */ +enum { + MMS_SUCCESS = -1, + MMS_TEMPORARILY_UNAVAILABLE = 2, + MMS_ACCESS_DENIED = 3, + MMS_TYPE_INCONSISTENT = 7, + MMS_ATTRIBUTE_INCONSISTENT = 8, + MMS_ACCESS_UNSUPPORTED = 9, + MMS_NON_EXISTENT = 10, + MMS_VALUE_INVALID = 11, +}; + +/* MMS Data and TypeSpecification tags. */ +enum { + MMS_STRUCTURE = 0xA2, + MMS_BOOL = 0x83, + MMS_BIT_STRING = 0x84, + MMS_INTEGER = 0x85, + MMS_UNSIGNED = 0x86, + MMS_FLOAT = 0x87, + MMS_OCTET_STRING = 0x89, + MMS_VISIBLE_STRING = 0x8A, + MMS_BINARY_TIME = 0x8C, + MMS_UTC_TIME = 0x91, +}; + +/* A report control block's attributes, in the order of IEC 61850-8-1. */ +enum { + MMS_RPT_ID, + MMS_RPT_ENA, + MMS_RESV, + MMS_DAT_SET, + MMS_CONF_REV, + MMS_OPT_FLDS, + MMS_BUF_TM, + MMS_SQ_NUM, + MMS_TRG_OPS, + MMS_INTG_PD, + MMS_GI, + MMS_PURGE_BUF, + MMS_ENTRY_ID, + MMS_TIME_OF_ENTRY, + MMS_RESV_TMS, + MMS_OWNER, + MMS_RCB_ATTRS, +}; + +/* + * A BER writer over a fixed buffer. A TLV whose length is not known yet is + * opened and closed; closing moves its content to make room for a long length. + * Past the buffer or the depth it sets overflow and writes no more. + */ +#define MMS_ENC_DEPTH 24 + +struct mms_enc { + uint8_t *buf; + size_t len; + size_t cap; + bool overflow; + uint8_t depth; + uint16_t open[MMS_ENC_DEPTH]; +}; + +void mms_put(struct mms_enc *e, const void *src, size_t n); +void mms_tlv(struct mms_enc *e, uint8_t tag, const void *v, size_t n); +void mms_begin(struct mms_enc *e, uint8_t tag); +void mms_end(struct mms_enc *e); +void mms_u8(struct mms_enc *e, uint8_t tag, uint8_t v); +void mms_str(struct mms_enc *e, uint8_t tag, const char *s); +void mms_int(struct mms_enc *e, uint8_t tag, int64_t v); +void mms_bool(struct mms_enc *e, uint8_t tag, bool v); +/* A leaf's value as MMS Data; not for ZELOS_MMS_TIME. */ +void mms_value(struct mms_enc *e, uint8_t type, union zelos_mms_value v); + +/* One TLV of a definite length and a one-byte tag. */ +struct mms_tlv { + uint8_t tag; + const uint8_t *v; + size_t len; +}; + +/* The TLV at *p, which moves past it. False: malformed, or it passes end. */ +bool mms_next(const uint8_t **p, const uint8_t *end, struct mms_tlv *t); +/* The first TLV with this tag inside in. */ +bool mms_find(const struct mms_tlv *in, uint8_t tag, struct mms_tlv *t); +/* An INTEGER's value, of up to 8 bytes. */ +bool mms_get_int(const struct mms_tlv *t, int64_t *v); + +/* + * The model as the names MMS serves: every leaf, then after a logical node's + * last leaf its unbuffered and its buffered blocks' attributes. + */ +struct mms_object { + /* A model leaf, or -1: attribute attr of block rcb. */ + int16_t leaf; + uint8_t rcb; + uint8_t attr; +}; + +struct mms_iter { + uint8_t leaf; + uint8_t pass; + uint8_t rcb; + uint8_t attr; + struct mms_object at; + /* The item name, "LN$FC$..."; its untruncated length. */ + size_t len; + char name[ZELOS_MMS_NAME_MAX + 1]; +}; + +/* The next name, from a zeroed iterator. False: no more. */ +bool mms_iter_next(const struct zelos_mms_model *model, struct mms_iter *it); +int mms_model_check(const struct zelos_mms_model *model); +/* a + sep + b into out (cap bytes, NUL included); the length it needs. */ +size_t mms_join(char *out, size_t cap, const char *a, char sep, const char *b); +/* A leaf's item name; its length. */ +size_t mms_leaf_name(const struct zelos_mms_model *model, uint8_t leaf, char *out); +/* The data set named item, or -1. */ +int mms_data_set(const struct zelos_mms_model *model, const uint8_t *item, size_t len); + +enum { + MMS_NONE, + MMS_LEAF, + MMS_BRANCH, +}; + +/* What item names: MMS_LEAF fills *at. */ +int mms_lookup(const struct zelos_mms_core *mms, const uint8_t *item, size_t len, + struct mms_object *at); +/* The object item names, as Data or as a TypeSpecification. MMS_NONE writes nothing. */ +int mms_object(const struct zelos_mms_core *mms, struct mms_enc *e, const uint8_t *item, size_t len, + bool type); +/* A model leaf's value as Data. */ +void mms_leaf_value(const struct zelos_mms_core *mms, struct mms_enc *e, uint8_t leaf); + +const char *mms_rcb_attr(uint8_t attr); +bool mms_rcb_has(const struct zelos_mms_rcb *rcb, uint8_t attr); +void mms_rcb_init(struct zelos_mms_core *mms, uint32_t boot); +void mms_rcb_value(const struct zelos_mms_core *mms, struct mms_enc *e, uint8_t rcb, uint8_t attr); +void mms_rcb_type(struct mms_enc *e, const struct zelos_mms_rcb *rcb, uint8_t attr); +/* Write an attribute from socket s. MMS_SUCCESS or a DataAccessError. */ +int mms_rcb_write(struct zelos_mms_core *mms, uint8_t rcb, uint8_t attr, const struct mms_tlv *data, + int s); +/* Socket s closed: its blocks are disabled and released or held. */ +void mms_rcb_closed(struct zelos_mms_core *mms, int s); +/* Read the values and note what changed. */ +void mms_scan(struct zelos_mms_core *mms); +/* Send the reports due. When to run again at the latest. */ +int64_t mms_report_run(struct zelos_mms_core *mms); + +/* One MMS PDU from an associated client. False: malformed, close. */ +bool mms_pdu(struct zelos_mms_core *mms, int s, const uint8_t *p, size_t len); +/* Send the MMS PDU of len bytes at &mms->out[ZELOS_MMS_HEAD] on socket s. */ +void mms_send_pdu(struct zelos_mms_core *mms, int s, size_t len); + +#endif /* ZELOS_MMS_INTERNAL_H_ */ diff --git a/lib/mms/core/mms_model.c b/lib/mms/core/mms_model.c new file mode 100644 index 0000000..8d2e885 --- /dev/null +++ b/lib/mms/core/mms_model.c @@ -0,0 +1,459 @@ +/* + * The model as MMS objects, no I/O: the item names of a logical device + * (IEC 61850-8-1: LN$FC$DO$DA...), and the value or type of the object a name + * stands for at any level, built from the leaves below it without recursion. + */ + +#include "mms_internal.h" + +#include + +/* TimeQuality: clock not synchronized, accuracy unspecified. */ +#define TIME_QUALITY 0x3F +#define MSEC_PER_S 1000 + +size_t mms_join(char *out, size_t cap, const char *a, char sep, const char *b) +{ + const size_t na = strlen(a); + const size_t nb = strlen(b); + size_t n = 0; + + for (size_t i = 0; i < na + 1 + nb; i++) { + const char c = i < na ? a[i] : i == na ? sep : b[i - na - 1]; + + if (n + 1 < cap) { + out[n++] = c; + } + } + out[n] = 0; + return na + 1 + nb; +} + +size_t mms_leaf_name(const struct zelos_mms_model *model, uint8_t leaf, char *out) +{ + const struct zelos_mms_leaf *l = &model->leaves[leaf]; + char part[ZELOS_MMS_NAME_MAX + 1]; + const size_t n = mms_join(part, sizeof(part), l->ln, '$', l->fc); + + /* Too long already: the caller sees it by the length. */ + return mms_join(out, sizeof(part), part, '$', l->path) + (n > ZELOS_MMS_NAME_MAX ? n : 0); +} + +static bool same_node(const struct zelos_mms_model *model, uint8_t a, uint8_t b) +{ + return strcmp(model->leaves[a].ln, model->leaves[b].ln) == 0; +} + +bool mms_iter_next(const struct zelos_mms_model *model, struct mms_iter *it) +{ + char part[ZELOS_MMS_NAME_MAX + 1]; + + for (;;) { + if (it->leaf >= model->leaf_count) { + return false; + } + if (it->pass == 0) { + it->at = (struct mms_object){.leaf = it->leaf}; + it->len = mms_leaf_name(model, it->leaf, it->name); + if (it->leaf + 1 == model->leaf_count || + !same_node(model, it->leaf, it->leaf + 1)) { + /* The logical node's last leaf: its blocks follow. */ + it->pass = 1; + it->rcb = 0; + it->attr = 0; + } else { + it->leaf++; + } + return true; + } + for (; it->rcb < model->rcb_count; it->rcb++, it->attr = 0) { + const struct zelos_mms_rcb *rcb = &model->rcbs[it->rcb]; + + if (rcb->buffered != (it->pass == 2) || + strcmp(rcb->ln, model->leaves[it->leaf].ln) != 0) { + continue; + } + while (it->attr < MMS_RCB_ATTRS) { + const uint8_t attr = it->attr++; + + if (!mms_rcb_has(rcb, attr)) { + continue; + } + it->at = (struct mms_object){-1, it->rcb, attr}; + it->len = mms_join(part, sizeof(part), rcb->ln, '$', + rcb->buffered ? "BR" : "RP"); + if (it->len <= ZELOS_MMS_NAME_MAX) { + it->len = mms_join(it->name, sizeof(it->name), part, '$', + rcb->name); + } + if (it->len <= ZELOS_MMS_NAME_MAX) { + memcpy(part, it->name, it->len + 1); + it->len = mms_join(it->name, sizeof(it->name), part, '$', + mms_rcb_attr(attr)); + } + return true; + } + } + it->rcb = 0; + it->attr = 0; + if (it->pass == 1) { + it->pass = 2; + } else { + it->pass = 0; + it->leaf++; + } + } +} + +/* Components of a name: 0 if one is empty. */ +static uint8_t depth_of(const char *name) +{ + uint8_t n = 1; + + for (size_t i = 0;; i++) { + if (name[i] == '$' || name[i] == 0) { + if (i == 0 || name[i - 1] == '$') { + return 0; + } + if (name[i] == 0) { + return n; + } + n++; + } + } +} + +/* Leading components two names share. */ +static uint8_t shared(const char *a, const char *b) +{ + uint8_t n = 0; + + for (size_t i = 0;; i++) { + const bool end_a = a[i] == '$' || a[i] == 0; + const bool end_b = b[i] == '$' || b[i] == 0; + + if (end_a && end_b) { + n++; + if (a[i] == 0 || b[i] == 0) { + return n; + } + } else if (a[i] != b[i]) { + return n; + } + } +} + +/* Component i of a name, its length in *len. */ +static const char *component(const char *name, uint8_t i, size_t *len) +{ + while (i > 0) { + if (*name++ == '$') { + i--; + } + } + *len = strcspn(name, "$"); + return name; +} + +static bool is(const uint8_t *item, size_t len, const char *name) +{ + return strlen(name) == len && memcmp(item, name, len) == 0; +} + +int mms_data_set(const struct zelos_mms_model *model, const uint8_t *item, size_t len) +{ + for (int i = 0; i < model->data_set_count; i++) { + if (is(item, len, model->data_sets[i].name)) { + return i; + } + } + return -1; +} + +int mms_model_check(const struct zelos_mms_model *model) +{ + struct mms_iter a = {0}; + size_t buffered = 0; + + if (model->vendor == NULL || model->name == NULL || model->revision == NULL || + model->ld[0] == 0 || strlen(model->ld) > ZELOS_MMS_NAME_MAX || model->leaf_count == 0 || + model->value_count > ZELOS_MMS_VALUES_MAX || model->rcb_count > ZELOS_MMS_RCBS_MAX || + model->data_set_count >= ZELOS_MMS_NO_DATA_SET) { + return -EINVAL; + } + for (size_t i = 0; i < model->leaf_count; i++) { + const struct zelos_mms_leaf *l = &model->leaves[i]; + + if (l->type > ZELOS_MMS_TIME || + (l->value >= model->value_count && + (l->value != ZELOS_MMS_NO_VALUE || l->type < ZELOS_MMS_QUALITY)) || + (l->type == ZELOS_MMS_TIME && l->value != ZELOS_MMS_NO_VALUE)) { + return -EINVAL; + } + } + for (size_t i = 0; i < model->data_set_count; i++) { + const struct zelos_mms_data_set *ds = &model->data_sets[i]; + + if (depth_of(ds->name) != 2 || strlen(ds->name) > ZELOS_MMS_NAME_MAX || + ds->count == 0 || ds->count > ZELOS_MMS_MEMBERS_MAX) { + return -EINVAL; + } + for (size_t m = 0; m < ds->count; m++) { + if (ds->members[m] >= model->leaf_count || + model->leaves[ds->members[m]].type == ZELOS_MMS_TIME) { + return -EINVAL; + } + } + } + for (size_t i = 0; i < model->rcb_count; i++) { + const struct zelos_mms_rcb *rcb = &model->rcbs[i]; + bool node = false; + + for (size_t l = 0; l < model->leaf_count; l++) { + node = node || strcmp(model->leaves[l].ln, rcb->ln) == 0; + } + if (!node || rcb->data_set >= model->data_set_count) { + return -EINVAL; + } + buffered += rcb->buffered; + } + if (buffered > ZELOS_MMS_BUFFERED_MAX) { + return -EINVAL; + } + /* Depth first: further down the list, a name shares no more with this one. */ + while (mms_iter_next(model, &a)) { + struct mms_iter b = a; + const uint8_t depth = depth_of(a.name); + uint8_t most = depth; + + if (a.len > ZELOS_MMS_NAME_MAX || depth == 0) { + return -EINVAL; + } + while (mms_iter_next(model, &b)) { + const uint8_t n = + b.len > ZELOS_MMS_NAME_MAX ? most : shared(a.name, b.name); + + /* The same name, a leaf above another, or a branch left and entered again. + */ + if (n >= depth || n == depth_of(b.name) || n > most) { + return -EINVAL; + } + most = n; + } + } + return 0; +} + +/* Does the name start with the object item names, at a component's end? */ +static bool below(const char *name, const uint8_t *item, size_t len) +{ + return strlen(name) >= len && memcmp(name, item, len) == 0 && + (name[len] == '$' || name[len] == 0); +} + +int mms_lookup(const struct zelos_mms_core *mms, const uint8_t *item, size_t len, + struct mms_object *at) +{ + struct mms_iter it = {0}; + + if (len == 0 || len > ZELOS_MMS_NAME_MAX) { + return MMS_NONE; + } + while (mms_iter_next(mms->model, &it)) { + if (below(it.name, item, len)) { + *at = it.at; + return it.name[len] == 0 ? MMS_LEAF : MMS_BRANCH; + } + } + return MMS_NONE; +} + +/* When a value of the leaf's data object last changed. */ +static int64_t stamp(const struct zelos_mms_core *mms, uint8_t leaf) +{ + const struct zelos_mms_leaf *t = &mms->model->leaves[leaf]; + const size_t object = strcspn(t->path, "$"); + int64_t at = 0; + + for (size_t i = 0; i < mms->model->leaf_count; i++) { + const struct zelos_mms_leaf *l = &mms->model->leaves[i]; + + if (l->value < mms->model->value_count && strcmp(l->ln, t->ln) == 0 && + strcmp(l->fc, t->fc) == 0 && strcspn(l->path, "$") == object && + memcmp(l->path, t->path, object) == 0 && mms->changed[l->value] > at) { + at = mms->changed[l->value]; + } + } + return at; +} + +void mms_leaf_value(const struct zelos_mms_core *mms, struct mms_enc *e, uint8_t leaf) +{ + const struct zelos_mms_leaf *l = &mms->model->leaves[leaf]; + union zelos_mms_value v = {0}; + + if (l->type == ZELOS_MMS_TIME) { + const int64_t ms = stamp(mms, leaf); + const uint32_t s = (uint32_t)(ms / MSEC_PER_S); + /* The fraction of a second in 24 bits. */ + const uint32_t frac = (uint32_t)(((uint64_t)(ms % MSEC_PER_S) << 24) / MSEC_PER_S); + + mms_tlv(e, MMS_UTC_TIME, + (uint8_t[]){(uint8_t)(s >> 24), (uint8_t)(s >> 16), (uint8_t)(s >> 8), + (uint8_t)s, (uint8_t)(frac >> 16), (uint8_t)(frac >> 8), + (uint8_t)frac, TIME_QUALITY}, + 8); + return; + } + if (l->value != ZELOS_MMS_NO_VALUE) { + v = mms->last[l->value]; + } + mms_value(e, l->type, v); +} + +/* A leaf's TypeSpecification (ISO 9506-2); a bit string's negative size is its most. */ +static void leaf_type(struct mms_enc *e, uint8_t type) +{ + switch (type) { + case ZELOS_MMS_BOOLEAN: + mms_tlv(e, MMS_BOOL, NULL, 0); + break; + case ZELOS_MMS_DBPOS: + mms_int(e, MMS_BIT_STRING, 2); + break; + case ZELOS_MMS_ENUM: + mms_int(e, MMS_INTEGER, 8); + break; + case ZELOS_MMS_INT32: + mms_int(e, MMS_INTEGER, 32); + break; + case ZELOS_MMS_UINT32: + mms_int(e, MMS_UNSIGNED, 32); + break; + case ZELOS_MMS_FLOAT32: + /* Format width 32, exponent width 8. */ + mms_begin(e, 0xA7); + mms_int(e, 0x02, 32); + mms_int(e, 0x02, 8); + mms_end(e); + break; + case ZELOS_MMS_QUALITY: + mms_int(e, MMS_BIT_STRING, -13); + break; + default: + mms_tlv(e, MMS_UTC_TIME, NULL, 0); + break; + } +} + +static void leaf(const struct zelos_mms_core *mms, struct mms_enc *e, const struct mms_object *at, + bool type) +{ + if (at->leaf < 0) { + if (type) { + mms_rcb_type(e, &mms->model->rcbs[at->rcb], at->attr); + } else { + mms_rcb_value(mms, e, at->rcb, at->attr); + } + } else if (type) { + leaf_type(e, mms->model->leaves[at->leaf].type); + } else { + mms_leaf_value(mms, e, (uint8_t)at->leaf); + } +} + +/* + * A structure opens. As a type it is a component of the one above: a name and + * a type, the type a structure with a list of components. + */ +static void open_structure(struct mms_enc *e, const char *name, size_t len, bool type) +{ + if (type && name != NULL) { + mms_begin(e, 0x30); + mms_tlv(e, 0x80, name, len); + mms_begin(e, 0xA1); + } + mms_begin(e, MMS_STRUCTURE); + if (type) { + mms_begin(e, 0xA1); + } +} + +static void close_structure(struct mms_enc *e, bool named, bool type) +{ + mms_end(e); + if (type) { + mms_end(e); + } + if (type && named) { + mms_end(e); + mms_end(e); + } +} + +int mms_object(const struct zelos_mms_core *mms, struct mms_enc *e, const uint8_t *item, size_t len, + bool type) +{ + struct mms_iter it = {0}; + char prev[ZELOS_MMS_NAME_MAX + 1]; + /* The item's depth, and the structures open below it. */ + uint8_t base = 0; + uint8_t opened = 0; + bool found = false; + + if (len == 0 || len > ZELOS_MMS_NAME_MAX) { + return MMS_NONE; + } + while (mms_iter_next(mms->model, &it)) { + const uint8_t depth = depth_of(it.name); + uint8_t keep; + size_t n; + const char *name; + + if (!below(it.name, item, len)) { + if (found) { + break; + } + continue; + } + if (it.name[len] == 0) { + leaf(mms, e, &it.at, type); + return MMS_LEAF; + } + if (!found) { + found = true; + base = depth - depth_of(&it.name[len + 1]); + open_structure(e, NULL, 0, type); + keep = 0; + } else { + keep = shared(prev, it.name) - base; + } + for (; opened > keep; opened--) { + close_structure(e, true, type); + } + for (; base + opened < depth - 1; opened++) { + name = component(it.name, base + opened, &n); + open_structure(e, name, n, type); + } + if (type) { + name = component(it.name, depth - 1, &n); + mms_begin(e, 0x30); + mms_tlv(e, 0x80, name, n); + mms_begin(e, 0xA1); + } + leaf(mms, e, &it.at, type); + if (type) { + mms_end(e); + mms_end(e); + } + memcpy(prev, it.name, sizeof(prev)); + } + if (!found) { + return MMS_NONE; + } + for (; opened > 0; opened--) { + close_structure(e, true, type); + } + close_structure(e, false, type); + return MMS_BRANCH; +} diff --git a/lib/mms/core/mms_report.c b/lib/mms/core/mms_report.c new file mode 100644 index 0000000..e4b8817 --- /dev/null +++ b/lib/mms/core/mms_report.c @@ -0,0 +1,865 @@ +/* + * Report control blocks (IEC 61850-7-2, mapped by 8-1), no I/O: their + * attributes, change detection over the model's values, the buffered blocks' + * rings, and the report as an informationReport on the list RPT. + */ + +#include "mms_internal.h" + +/* TrgOps and the reason for inclusion, as their first octet; bit 0 is reserved. */ +#define DCHG 0x40 +#define QCHG 0x20 +#define INTEGRITY 0x08 +#define GI 0x04 +#define TRG_OPS 0x7C + +/* OptFlds, as its two octets; bit 0 is reserved, bit 9 (segmentation) is not kept. */ +#define OPT_SEQ 0x4000 +#define OPT_TIME 0x2000 +#define OPT_REASON 0x1000 +#define OPT_DATA_SET 0x0800 +#define OPT_DATA_REF 0x0400 +#define OPT_BUF_OVFL 0x0200 +#define OPT_ENTRY_ID 0x0100 +#define OPT_CONF_REV 0x0080 +#define OPT_FLDS 0x7F80 + +#define URCB 1 +#define BRCB 2 +#define MSEC_PER_DAY 86400000 +#define MSEC_PER_S 1000 + +static const struct { + const char *name; + uint8_t kinds; +} attrs[MMS_RCB_ATTRS] = { + [MMS_RPT_ID] = {"RptID", URCB | BRCB}, + [MMS_RPT_ENA] = {"RptEna", URCB | BRCB}, + [MMS_RESV] = {"Resv", URCB}, + [MMS_DAT_SET] = {"DatSet", URCB | BRCB}, + [MMS_CONF_REV] = {"ConfRev", URCB | BRCB}, + [MMS_OPT_FLDS] = {"OptFlds", URCB | BRCB}, + [MMS_BUF_TM] = {"BufTm", URCB | BRCB}, + [MMS_SQ_NUM] = {"SqNum", URCB | BRCB}, + [MMS_TRG_OPS] = {"TrgOps", URCB | BRCB}, + [MMS_INTG_PD] = {"IntgPd", URCB | BRCB}, + [MMS_GI] = {"GI", URCB | BRCB}, + [MMS_PURGE_BUF] = {"PurgeBuf", BRCB}, + [MMS_ENTRY_ID] = {"EntryID", BRCB}, + [MMS_TIME_OF_ENTRY] = {"TimeofEntry", BRCB}, + [MMS_RESV_TMS] = {"ResvTms", BRCB}, + [MMS_OWNER] = {"Owner", URCB | BRCB}, +}; + +const char *mms_rcb_attr(uint8_t attr) +{ + return attrs[attr].name; +} + +bool mms_rcb_has(const struct zelos_mms_rcb *rcb, uint8_t attr) +{ + return (attrs[attr].kinds & (rcb->buffered ? BRCB : URCB)) != 0; +} + +/* The block's reference, "LD/LN$BR$name": its RptID unless one is written. */ +static void block_ref(const struct zelos_mms_core *mms, uint8_t r, char *out) +{ + const struct zelos_mms_rcb *rcb = &mms->model->rcbs[r]; + char part[ZELOS_MMS_NAME_MAX + 1]; + char item[ZELOS_MMS_NAME_MAX + 1]; + + mms_join(part, sizeof(part), rcb->ln, '$', rcb->buffered ? "BR" : "RP"); + mms_join(item, sizeof(item), part, '$', rcb->name); + mms_join(out, ZELOS_MMS_REF_MAX + 1, mms->model->ld, '/', item); +} + +/* DatSet: "LD/LN$name", or empty for none. */ +static void data_set_ref(const struct zelos_mms_core *mms, uint8_t data_set, char *out) +{ + out[0] = 0; + if (data_set != ZELOS_MMS_NO_DATA_SET) { + mms_join(out, ZELOS_MMS_REF_MAX + 1, mms->model->ld, '/', + mms->model->data_sets[data_set].name); + } +} + +void mms_rcb_init(struct zelos_mms_core *mms, uint32_t boot) +{ + size_t rings = 0; + + for (uint8_t r = 0; r < mms->model->rcb_count; r++) { + struct zelos_mms_rcb_state *st = &mms->rcb[r]; + + block_ref(mms, r, st->rpt_id); + st->data_set = mms->model->rcbs[r].data_set; + st->conn = -1; + st->trg_ops = DCHG | QCHG | GI; + st->opt_flds = OPT_SEQ | OPT_TIME | OPT_REASON | OPT_DATA_SET; + if (mms->model->rcbs[r].buffered) { + st->ring = &mms->ring[rings++]; + st->ring->last = (uint64_t)boot << 32; + st->ring->lost = st->ring->last; + } + } +} + +/* BINARY-TIME with a date: ms of the day, then days since 1984-01-01. */ +static void binary_time(struct mms_enc *e, int64_t ms) +{ + const uint32_t of_day = (uint32_t)(ms % MSEC_PER_DAY); + const uint16_t days = (uint16_t)(ms / MSEC_PER_DAY); + + mms_tlv(e, MMS_BINARY_TIME, + (uint8_t[]){(uint8_t)(of_day >> 24), (uint8_t)(of_day >> 16), + (uint8_t)(of_day >> 8), (uint8_t)of_day, (uint8_t)(days >> 8), + (uint8_t)days}, + 6); +} + +static void entry_id(struct mms_enc *e, uint64_t id) +{ + uint8_t be[8]; + + for (size_t i = 0; i < sizeof(be); i++) { + be[i] = (uint8_t)(id >> (56 - 8 * i)); + } + mms_tlv(e, MMS_OCTET_STRING, be, sizeof(be)); +} + +void mms_rcb_value(const struct zelos_mms_core *mms, struct mms_enc *e, uint8_t rcb, uint8_t attr) +{ + const struct zelos_mms_rcb_state *st = &mms->rcb[rcb]; + char ref[ZELOS_MMS_REF_MAX + 1]; + + switch (attr) { + case MMS_RPT_ID: + mms_str(e, MMS_VISIBLE_STRING, st->rpt_id); + break; + case MMS_RPT_ENA: + mms_bool(e, MMS_BOOL, st->enabled); + break; + case MMS_RESV: + mms_bool(e, MMS_BOOL, st->resv); + break; + case MMS_DAT_SET: + data_set_ref(mms, st->data_set, ref); + mms_str(e, MMS_VISIBLE_STRING, ref); + break; + case MMS_CONF_REV: + mms_int(e, MMS_UNSIGNED, mms->model->rcbs[rcb].conf_rev); + break; + case MMS_OPT_FLDS: + mms_tlv(e, MMS_BIT_STRING, + (uint8_t[]){6, (uint8_t)(st->opt_flds >> 8), (uint8_t)st->opt_flds}, 3); + break; + case MMS_BUF_TM: + mms_int(e, MMS_UNSIGNED, st->buf_tm); + break; + case MMS_SQ_NUM: + mms_int(e, MMS_UNSIGNED, st->sq_num); + break; + case MMS_TRG_OPS: + mms_tlv(e, MMS_BIT_STRING, (uint8_t[]){2, st->trg_ops}, 2); + break; + case MMS_INTG_PD: + mms_int(e, MMS_UNSIGNED, st->intg_pd); + break; + case MMS_GI: + mms_bool(e, MMS_BOOL, st->gi); + break; + case MMS_PURGE_BUF: + mms_bool(e, MMS_BOOL, false); + break; + case MMS_ENTRY_ID: + entry_id(e, st->ring->last); + break; + case MMS_TIME_OF_ENTRY: + binary_time(e, st->ring->time); + break; + case MMS_RESV_TMS: + mms_int(e, MMS_INTEGER, st->resv_tms); + break; + default: + mms_tlv(e, MMS_OCTET_STRING, st->owner, st->owner_len); + break; + } +} + +/* TypeSpecification: a size below 0 is the most a variable-length one holds. */ +void mms_rcb_type(struct mms_enc *e, const struct zelos_mms_rcb *rcb, uint8_t attr) +{ + switch (attr) { + case MMS_RPT_ID: + case MMS_DAT_SET: + mms_int(e, MMS_VISIBLE_STRING, -ZELOS_MMS_REF_MAX); + break; + case MMS_CONF_REV: + case MMS_BUF_TM: + case MMS_INTG_PD: + mms_int(e, MMS_UNSIGNED, 32); + break; + case MMS_OPT_FLDS: + mms_int(e, MMS_BIT_STRING, -10); + break; + case MMS_SQ_NUM: + mms_int(e, MMS_UNSIGNED, rcb->buffered ? 16 : 8); + break; + case MMS_TRG_OPS: + mms_int(e, MMS_BIT_STRING, -6); + break; + case MMS_ENTRY_ID: + mms_int(e, MMS_OCTET_STRING, 8); + break; + case MMS_TIME_OF_ENTRY: + /* With a date: 6 octets. */ + mms_bool(e, MMS_BINARY_TIME, true); + break; + case MMS_RESV_TMS: + mms_int(e, MMS_INTEGER, 16); + break; + case MMS_OWNER: + mms_int(e, MMS_OCTET_STRING, -64); + break; + default: + mms_tlv(e, MMS_BOOL, NULL, 0); + break; + } +} + +static uint32_t all_members(const struct zelos_mms_data_set *ds) +{ + return (uint32_t)((1ULL << ds->count) - 1); +} + +/* The most a member's value takes as Data. */ +static size_t value_max(uint8_t type) +{ + return type == ZELOS_MMS_BOOLEAN ? 3 + : type == ZELOS_MMS_DBPOS ? 4 + : type == ZELOS_MMS_QUALITY ? 5 + : 7; +} + +/* The block's largest report as an MMS PDU: every member, each value at its longest. */ +static size_t report_max(const struct zelos_mms_core *mms, uint8_t r) +{ + const struct zelos_mms_model *model = mms->model; + const struct zelos_mms_rcb_state *st = &mms->rcb[r]; + const struct zelos_mms_data_set *ds = &model->data_sets[st->data_set]; + const size_t ld = strlen(model->ld); + char name[ZELOS_MMS_NAME_MAX + 1]; + /* The PDU down to the access results, RptID, OptFlds, the inclusion bits. */ + size_t n = 24 + 3 + strlen(st->rpt_id) + 5 + 3 + (ds->count + 7) / 8; + + n += (st->opt_flds & OPT_SEQ) != 0 ? 5 : 0; + n += (st->opt_flds & OPT_TIME) != 0 ? 8 : 0; + n += (st->opt_flds & OPT_DATA_SET) != 0 ? 3 + ld + 1 + strlen(ds->name) : 0; + n += (st->opt_flds & OPT_BUF_OVFL) != 0 ? 3 : 0; + n += (st->opt_flds & OPT_ENTRY_ID) != 0 ? 10 : 0; + n += (st->opt_flds & OPT_CONF_REV) != 0 ? 7 : 0; + for (size_t m = 0; m < ds->count; m++) { + if ((st->opt_flds & OPT_DATA_REF) != 0) { + n += 3 + ld + 1 + mms_leaf_name(model, ds->members[m], name); + } + n += value_max(model->leaves[ds->members[m]].type); + n += (st->opt_flds & OPT_REASON) != 0 ? 4 : 0; + } + return n; +} + +/* One report to the block's client. */ +static void send_report(struct zelos_mms_core *mms, uint8_t r, const struct zelos_mms_entry *en) +{ + const struct zelos_mms_model *model = mms->model; + struct zelos_mms_rcb_state *st = &mms->rcb[r]; + struct zelos_mms_ring *ring = st->ring; + const struct zelos_mms_data_set *ds = &model->data_sets[st->data_set]; + /* An unbuffered block has no BufOvfl and no EntryID. */ + const uint16_t opt = st->opt_flds & + (ring != NULL ? OPT_FLDS : OPT_FLDS & ~(OPT_BUF_OVFL | OPT_ENTRY_ID)); + struct mms_enc e = {.buf = &mms->out[ZELOS_MMS_HEAD], .cap = mms->conn[st->conn].pdu_size}; + uint8_t bits[1 + (ZELOS_MMS_MEMBERS_MAX + 7) / 8] = {(uint8_t)((8 - ds->count % 8) % 8)}; + char ref[ZELOS_MMS_REF_MAX + 1]; + char name[ZELOS_MMS_NAME_MAX + 1]; + + /* unconfirmed-PDU, informationReport, variableListName RPT (vmd-specific). */ + mms_begin(&e, 0xA3); + mms_begin(&e, 0xA0); + mms_begin(&e, 0xA1); + mms_tlv(&e, 0x80, "RPT", 3); + mms_end(&e); + mms_begin(&e, 0xA0); + mms_str(&e, MMS_VISIBLE_STRING, st->rpt_id); + mms_tlv(&e, MMS_BIT_STRING, (uint8_t[]){6, (uint8_t)(opt >> 8), (uint8_t)opt}, 3); + if ((opt & OPT_SEQ) != 0) { + mms_int(&e, MMS_UNSIGNED, st->sq_num); + } + if ((opt & OPT_TIME) != 0) { + binary_time(&e, en->time); + } + if ((opt & OPT_DATA_SET) != 0) { + data_set_ref(mms, st->data_set, ref); + mms_str(&e, MMS_VISIBLE_STRING, ref); + } + if ((opt & OPT_BUF_OVFL) != 0) { + mms_bool(&e, MMS_BOOL, ring->overflow); + } + if ((opt & OPT_ENTRY_ID) != 0) { + entry_id(&e, en->id); + } + if ((opt & OPT_CONF_REV) != 0) { + mms_int(&e, MMS_UNSIGNED, model->rcbs[r].conf_rev); + } + for (size_t m = 0; m < ds->count; m++) { + if ((en->inclusion >> m & 1) != 0) { + bits[1 + m / 8] |= (uint8_t)(0x80 >> (m % 8)); + } + } + mms_tlv(&e, MMS_BIT_STRING, bits, 1 + (ds->count + 7) / 8); + for (size_t m = 0; m < ds->count && (opt & OPT_DATA_REF) != 0; m++) { + if ((en->inclusion >> m & 1) != 0) { + mms_leaf_name(model, ds->members[m], name); + mms_join(ref, sizeof(ref), model->ld, '/', name); + mms_str(&e, MMS_VISIBLE_STRING, ref); + } + } + for (size_t m = 0; m < ds->count; m++) { + if ((en->inclusion >> m & 1) != 0) { + mms_value(&e, model->leaves[ds->members[m]].type, en->value[m]); + } + } + for (size_t m = 0; m < ds->count && (opt & OPT_REASON) != 0; m++) { + const bool quality = model->leaves[ds->members[m]].type == ZELOS_MMS_QUALITY; + const uint8_t reason = en->reason != 0 ? en->reason : quality ? QCHG : DCHG; + + if ((en->inclusion >> m & 1) != 0) { + mms_tlv(&e, MMS_BIT_STRING, (uint8_t[]){1, reason}, 2); + } + } + mms_end(&e); + mms_end(&e); + mms_end(&e); + + if (ring != NULL) { + ring->overflow = false; + } + st->sq_num = (st->sq_num + 1) & (ring != NULL ? 0xFFFF : 0xFF); + /* RptEna was refused unless the largest report fits: it does. */ + if (!e.overflow) { + mms_send_pdu(mms, st->conn, e.len); + } +} + +/* A report of the members in inclusion, their values as last read. */ +static void fill(const struct zelos_mms_core *mms, uint8_t r, struct zelos_mms_entry *en, + uint32_t inclusion, uint8_t reason, int64_t time) +{ + const struct zelos_mms_model *model = mms->model; + const struct zelos_mms_data_set *ds = &model->data_sets[mms->rcb[r].data_set]; + + memset(en, 0, sizeof(*en)); + en->time = time; + en->inclusion = inclusion; + en->reason = reason; + for (size_t m = 0; m < ds->count; m++) { + const uint8_t value = model->leaves[ds->members[m]].value; + + if (value < model->value_count) { + en->value[m] = mms->last[value]; + } + } +} + +/* Buffered: into the ring, the oldest entry making room. Unbuffered: to the client now. */ +static void emit(struct zelos_mms_core *mms, uint8_t r, const struct zelos_mms_entry *en) +{ + struct zelos_mms_rcb_state *st = &mms->rcb[r]; + struct zelos_mms_ring *ring = st->ring; + + if (ring == NULL) { + if (st->enabled) { + send_report(mms, r, en); + } + return; + } + if (ring->count == ZELOS_MMS_ENTRIES) { + ring->lost = ring->entry[ring->head].id; + if (ring->unsent == ring->count) { + ring->unsent--; + ring->overflow = true; + } + ring->count--; + } + ring->entry[ring->head] = *en; + ring->entry[ring->head].id = ++ring->last; + ring->head = (uint8_t)((ring->head + 1) % ZELOS_MMS_ENTRIES); + ring->count++; + ring->unsent++; + ring->time = en->time; +} + +/* The changes waiting on BufTm, as one report. */ +static void flush(struct zelos_mms_core *mms, uint8_t r) +{ + struct zelos_mms_rcb_state *st = &mms->rcb[r]; + struct zelos_mms_entry en; + + if (st->pending == 0) { + return; + } + fill(mms, r, &en, st->pending, 0, st->pending_since); + st->pending = 0; + emit(mms, r, &en); +} + +static void purge(struct zelos_mms_rcb_state *st) +{ + st->pending = 0; + if (st->ring != NULL) { + st->ring->count = 0; + st->ring->unsent = 0; + st->ring->overflow = false; + st->ring->lost = st->ring->last; + } +} + +static void take(const struct zelos_mms_core *mms, struct zelos_mms_rcb_state *st, int s) +{ + const struct zelos_mms_conn *conn = &mms->conn[s]; + + st->conn = (int8_t)s; + st->hold_until = 0; + memcpy(st->owner, conn->peer, conn->peer_len); + st->owner_len = conn->peer_len; +} + +static void release(struct zelos_mms_rcb_state *st) +{ + st->conn = -1; + st->hold_until = 0; + st->owner_len = 0; + st->resv = false; + st->resv_tms = 0; +} + +static void disable(struct zelos_mms_rcb_state *st) +{ + st->enabled = false; + st->gi = false; + if (st->ring == NULL) { + st->pending = 0; + } +} + +/* Another connection holds the block, or it is kept for another address. */ +static bool held(const struct zelos_mms_core *mms, const struct zelos_mms_rcb_state *st, int s) +{ + const struct zelos_mms_conn *conn = &mms->conn[s]; + + if (st->conn >= 0) { + return st->conn != s; + } + return mms->now < st->hold_until && (conn->peer_len != st->owner_len || + memcmp(conn->peer, st->owner, st->owner_len) != 0); +} + +static bool get_number(const struct mms_tlv *d, int64_t *v) +{ + return (d->tag == MMS_INTEGER || d->tag == MMS_UNSIGNED) && d->len <= 5 && + mms_get_int(d, v); +} + +/* A bit string's first 16 bits, those past its length clear. */ +static bool get_bits(const struct mms_tlv *d, uint16_t *v) +{ + const size_t n = d->len - 1; + uint8_t b[2] = {0, 0}; + + if (d->tag != MMS_BIT_STRING || d->len < 1 || d->v[0] > (n == 0 ? 0 : 7)) { + return false; + } + for (size_t i = 0; i < MMS_MIN(n, sizeof(b)); i++) { + b[i] = d->v[1 + i]; + } + if (n >= 1 && n <= sizeof(b)) { + b[n - 1] &= (uint8_t)(0xFF << d->v[0]); + } + *v = (uint16_t)(b[0] << 8 | b[1]); + return true; +} + +/* An EntryID a client read from a report: the entries after it are the unsent ones. */ +static int resume(struct zelos_mms_ring *ring, const uint8_t *v) +{ + uint64_t id = 0; + uint8_t unsent = 0; + + for (size_t i = 0; i < 8; i++) { + id = id << 8 | v[i]; + } + if (id == 0) { + ring->unsent = ring->count; + return MMS_SUCCESS; + } + if (id < ring->lost || id > ring->last) { + return MMS_VALUE_INVALID; + } + while (unsent < ring->count && + ring->entry[(ring->head + ZELOS_MMS_ENTRIES - 1 - unsent) % ZELOS_MMS_ENTRIES].id > + id) { + unsent++; + } + ring->unsent = unsent; + ring->overflow = false; + return MMS_SUCCESS; +} + +int mms_rcb_write(struct zelos_mms_core *mms, uint8_t rcb, uint8_t attr, const struct mms_tlv *d, + int s) +{ + const struct zelos_mms_model *model = mms->model; + struct zelos_mms_rcb_state *st = &mms->rcb[rcb]; + const size_t ld = strlen(model->ld); + char ref[ZELOS_MMS_REF_MAX + 1]; + int64_t n = 0; + uint16_t bits = 0; + bool on = false; + int ds = ZELOS_MMS_NO_DATA_SET; + + if (held(mms, st, s)) { + return MMS_TEMPORARILY_UNAVAILABLE; + } + switch (attr) { + case MMS_CONF_REV: + case MMS_SQ_NUM: + case MMS_TIME_OF_ENTRY: + case MMS_OWNER: + return MMS_ACCESS_DENIED; + case MMS_RPT_ENA: + case MMS_RESV: + case MMS_GI: + case MMS_PURGE_BUF: + if (d->tag != MMS_BOOL || d->len != 1) { + return MMS_TYPE_INCONSISTENT; + } + on = d->v[0] != 0; + break; + case MMS_OPT_FLDS: + case MMS_TRG_OPS: + if (!get_bits(d, &bits)) { + return MMS_TYPE_INCONSISTENT; + } + break; + case MMS_BUF_TM: + case MMS_INTG_PD: + case MMS_RESV_TMS: + if (!get_number(d, &n)) { + return MMS_TYPE_INCONSISTENT; + } + if (n < 0 || n > (attr == MMS_RESV_TMS ? INT16_MAX : UINT32_MAX)) { + return MMS_VALUE_INVALID; + } + break; + case MMS_ENTRY_ID: + if (d->tag != MMS_OCTET_STRING || d->len != 8) { + return MMS_TYPE_INCONSISTENT; + } + break; + default: + if (d->tag != MMS_VISIBLE_STRING) { + return MMS_TYPE_INCONSISTENT; + } + break; + } + if (st->enabled && attr != MMS_RPT_ENA && attr != MMS_GI) { + return MMS_TEMPORARILY_UNAVAILABLE; + } + + switch (attr) { + case MMS_RPT_ENA: + if (on == st->enabled) { + break; + } + if (!on) { + disable(st); + if (!st->resv && st->resv_tms == 0) { + release(st); + } + break; + } + if (st->data_set == ZELOS_MMS_NO_DATA_SET || + report_max(mms, rcb) > mms->conn[s].pdu_size) { + return MMS_ATTRIBUTE_INCONSISTENT; + } + take(mms, st, s); + st->enabled = true; + st->sq_num = 0; + st->integrity_at = mms->now + st->intg_pd; + break; + case MMS_GI: + if (on && !st->enabled) { + return MMS_TEMPORARILY_UNAVAILABLE; + } + st->gi = st->gi || (on && (st->trg_ops & GI) != 0); + break; + case MMS_RESV: + if (on) { + take(mms, st, s); + st->resv = true; + } else { + release(st); + } + break; + case MMS_RESV_TMS: + if (n > 0) { + take(mms, st, s); + st->resv_tms = (int16_t)n; + } else { + release(st); + } + break; + case MMS_RPT_ID: + if (d->len > ZELOS_MMS_REF_MAX) { + return MMS_VALUE_INVALID; + } + for (size_t i = 0; i < d->len; i++) { + if (d->v[i] < 0x20 || d->v[i] > 0x7E) { + return MMS_VALUE_INVALID; + } + } + memcpy(ref, d->v, d->len); + ref[d->len] = 0; + if (d->len == 0) { + block_ref(mms, rcb, ref); + } + if (strcmp(ref, st->rpt_id) != 0) { + memcpy(st->rpt_id, ref, sizeof(ref)); + purge(st); + } + break; + case MMS_DAT_SET: + if (d->len > 0) { + if (d->len <= ld + 1 || memcmp(d->v, model->ld, ld) != 0 || + d->v[ld] != '/') { + return MMS_VALUE_INVALID; + } + ds = mms_data_set(model, &d->v[ld + 1], d->len - ld - 1); + if (ds < 0) { + return MMS_VALUE_INVALID; + } + } + if (ds != st->data_set) { + st->data_set = (uint8_t)ds; + purge(st); + } + break; + case MMS_OPT_FLDS: + st->opt_flds = bits & OPT_FLDS; + break; + case MMS_TRG_OPS: + if ((bits >> 8 & TRG_OPS) != st->trg_ops) { + st->trg_ops = bits >> 8 & TRG_OPS; + purge(st); + } + break; + case MMS_BUF_TM: + if (n != st->buf_tm) { + st->buf_tm = (uint32_t)n; + purge(st); + } + break; + case MMS_INTG_PD: + if (n != st->intg_pd) { + st->intg_pd = (uint32_t)n; + purge(st); + } + break; + case MMS_PURGE_BUF: + if (on) { + purge(st); + } + break; + default: + return resume(st->ring, d->v); + } + return MMS_SUCCESS; +} + +void mms_rcb_closed(struct zelos_mms_core *mms, int s) +{ + for (uint8_t r = 0; r < mms->model->rcb_count; r++) { + struct zelos_mms_rcb_state *st = &mms->rcb[r]; + + if (st->conn != s) { + continue; + } + disable(st); + if (st->resv_tms > 0) { + st->conn = -1; + st->hold_until = mms->now + (int64_t)st->resv_tms * MSEC_PER_S; + } else { + release(st); + } + } +} + +/* v with nothing set but its type's own bits, so that two compare by their bytes. */ +static union zelos_mms_value clean(uint8_t type, union zelos_mms_value v) +{ + union zelos_mms_value out; + + memset(&out, 0, sizeof(out)); + switch (type) { + case ZELOS_MMS_BOOLEAN: + out.boolean = v.boolean; + break; + case ZELOS_MMS_DBPOS: + out.dbpos = v.dbpos & 0x3; + break; + case ZELOS_MMS_FLOAT32: + out.f32 = v.f32; + break; + case ZELOS_MMS_QUALITY: + out.quality = v.quality & 0xFFF8; + break; + default: + out.u32 = v.u32; + break; + } + return out; +} + +/* The block's members among the values that changed, by its trigger options. */ +static uint32_t triggered(const struct zelos_mms_core *mms, uint8_t r, const bool *changed) +{ + const struct zelos_mms_model *model = mms->model; + const struct zelos_mms_rcb_state *st = &mms->rcb[r]; + const struct zelos_mms_data_set *ds; + uint32_t hit = 0; + + /* An unbuffered block that is not enabled notes nothing. */ + if (st->data_set == ZELOS_MMS_NO_DATA_SET || (st->ring == NULL && !st->enabled)) { + return 0; + } + ds = &model->data_sets[st->data_set]; + for (size_t m = 0; m < ds->count; m++) { + const struct zelos_mms_leaf *l = &model->leaves[ds->members[m]]; + const uint8_t trigger = l->type == ZELOS_MMS_QUALITY ? QCHG : DCHG; + + if (l->value < model->value_count && changed[l->value] && + (st->trg_ops & trigger) != 0) { + hit |= 1U << m; + } + } + return hit; +} + +void mms_scan(struct zelos_mms_core *mms) +{ + const struct zelos_mms_model *model = mms->model; + union zelos_mms_value now[ZELOS_MMS_VALUES_MAX]; + bool changed[ZELOS_MMS_VALUES_MAX] = {false}; + bool any = false; + + memset(now, 0, sizeof(now)); + model->read(now); + for (size_t i = 0; i < model->leaf_count; i++) { + const struct zelos_mms_leaf *l = &model->leaves[i]; + + if (l->value < model->value_count) { + now[l->value] = clean(l->type, now[l->value]); + /* By its bytes: a NaN that stays is no change. */ + changed[l->value] = + memcmp(&now[l->value], &mms->last[l->value], sizeof(now[0])) != 0; + any = any || changed[l->value]; + } + } + if (!any) { + return; + } + /* A member that changes again while its first change waits: that report goes first. */ + for (uint8_t r = 0; r < model->rcb_count; r++) { + if ((triggered(mms, r, changed) & mms->rcb[r].pending) != 0) { + flush(mms, r); + } + } + for (size_t i = 0; i < model->value_count; i++) { + if (changed[i]) { + mms->last[i] = now[i]; + mms->changed[i] = mms->now; + } + } + for (uint8_t r = 0; r < model->rcb_count; r++) { + struct zelos_mms_rcb_state *st = &mms->rcb[r]; + const uint32_t hit = triggered(mms, r, changed); + + if (hit != 0 && st->pending == 0) { + st->pending_since = mms->now; + st->pending_until = mms->now + st->buf_tm; + } + st->pending |= hit; + } +} + +int64_t mms_report_run(struct zelos_mms_core *mms) +{ + const int64_t now = mms->now; + int64_t next = MMS_FOREVER; + + for (uint8_t r = 0; r < mms->model->rcb_count; r++) { + struct zelos_mms_rcb_state *st = &mms->rcb[r]; + struct zelos_mms_ring *ring = st->ring; + struct zelos_mms_entry en; + bool integrity; + + if (st->conn < 0 && st->hold_until != 0 && now >= st->hold_until) { + release(st); + } + integrity = st->enabled && (st->trg_ops & INTEGRITY) != 0 && st->intg_pd > 0; + /* What changed goes before an integrity report or a general interrogation. */ + if (now >= st->pending_until || st->gi || (integrity && now >= st->integrity_at)) { + flush(mms, r); + } + if (integrity && st->enabled && now >= st->integrity_at) { + fill(mms, r, &en, all_members(&mms->model->data_sets[st->data_set]), + INTEGRITY, now); + emit(mms, r, &en); + st->integrity_at += st->intg_pd; + /* Late: on from now, no catch-up burst. */ + if (st->integrity_at <= now) { + st->integrity_at = now + st->intg_pd; + } + } + for (int i = 0; + i < ZELOS_MMS_BURST && ring != NULL && st->enabled && ring->unsent > 0; i++) { + const size_t at = + (ring->head + ZELOS_MMS_ENTRIES - ring->unsent) % ZELOS_MMS_ENTRIES; + + ring->unsent--; + send_report(mms, r, &ring->entry[at]); + } + if (st->enabled && st->gi && (ring == NULL || ring->unsent == 0)) { + fill(mms, r, &en, all_members(&mms->model->data_sets[st->data_set]), GI, + now); + if (ring != NULL) { + en.id = ++ring->last; + } + st->gi = false; + send_report(mms, r, &en); + } + + if (st->conn < 0 && st->hold_until != 0) { + next = MMS_MIN(next, st->hold_until); + } + if (st->pending != 0) { + next = MMS_MIN(next, st->pending_until); + } + if (st->enabled && (st->trg_ops & INTEGRITY) != 0 && st->intg_pd > 0) { + next = MMS_MIN(next, st->integrity_at); + } + if (st->enabled && (st->gi || (ring != NULL && ring->unsent > 0))) { + next = now; + } + } + return next; +} diff --git a/lib/mms/core/mms_service.c b/lib/mms/core/mms_service.c new file mode 100644 index 0000000..aa09def --- /dev/null +++ b/lib/mms/core/mms_service.c @@ -0,0 +1,524 @@ +/* + * MMS PDUs from an associated client (ISO 9506-2), no I/O: the confirmed + * services, and the reject or error every other request gets. + */ + +#include "mms_internal.h" + +/* Confirmed services by their request tag, and other PDUs. */ +#define STATUS 0x80 +#define GET_NAME_LIST 0xA1 +#define IDENTIFY 0x82 +#define READ 0xA4 +#define WRITE 0xA5 +#define GET_VARIABLE_ACCESS_ATTRIBUTES 0xA6 +#define GET_NAMED_VARIABLE_LIST_ATTRIBUTES 0xAC +#define CONFIRMED_REQUEST 0xA0 +#define CONFIRMED_RESPONSE 0xA1 +#define CONFIRMED_ERROR 0xA2 +#define REJECT 0xA4 +#define CANCEL_REQUEST 0x85 +#define INITIATE_REQUEST 0xA8 +#define CONCLUDE_REQUEST 0x8B +#define CONCLUDE_RESPONSE 0x8C + +/* ServiceError: class, then code. */ +#define ERROR_DEFINITION 2 +#define OBJECT_UNDEFINED 1 +#define ERROR_SERVICE 4 +#define PDU_SIZE 3 +#define CONTINUATION_INVALID 4 +#define ERROR_ACCESS 7 +#define OBJECT_ACCESS_UNSUPPORTED 1 + +/* RejectPDU: the PDU type rejected, then why. */ +#define REJECT_CONFIRMED_REQUEST 0x81 +#define UNRECOGNIZED_SERVICE 1 +#define INVALID_ARGUMENT 4 +#define REJECT_CANCEL_REQUEST 0x87 +#define INVALID_INVOKE_ID 1 + +/* getNameList object classes. */ +#define CLASS_NAMED_VARIABLE 0 +#define CLASS_NAMED_VARIABLE_LIST 2 +#define CLASS_DOMAIN 9 + +/* What a name list page keeps free for moreFollows and the lengths around it. */ +#define LIST_TAIL 12 + +/* A response's start: the PDU tag, then the request's invokeID under id_tag. */ +static void begin(struct zelos_mms_core *mms, int s, struct mms_enc *e, uint8_t pdu, uint8_t id_tag, + const struct mms_tlv *id) +{ + *e = (struct mms_enc){ + .buf = &mms->out[ZELOS_MMS_HEAD], + .cap = mms->conn[s].pdu_size, + }; + mms_begin(e, pdu); + mms_tlv(e, id_tag, id->v, id->len); +} + +static void error(struct zelos_mms_core *mms, int s, const struct mms_tlv *id, uint8_t kind, + uint8_t code) +{ + struct mms_enc e; + + begin(mms, s, &e, CONFIRMED_ERROR, 0x80, id); + mms_begin(&e, 0xA2); + mms_begin(&e, 0xA0); + mms_u8(&e, 0x80 | kind, code); + mms_end(&e); + mms_end(&e); + mms_end(&e); + mms_send_pdu(mms, s, e.len); +} + +static void reject(struct zelos_mms_core *mms, int s, const struct mms_tlv *id, uint8_t type, + uint8_t code) +{ + struct mms_enc e; + + begin(mms, s, &e, REJECT, 0x80, id); + mms_u8(&e, type, code); + mms_end(&e); + mms_send_pdu(mms, s, e.len); +} + +/* A confirmed response is complete: send it, or pdu-size if it did not fit. */ +static void respond(struct zelos_mms_core *mms, int s, const struct mms_tlv *id, struct mms_enc *e) +{ + mms_end(e); + if (e->overflow || e->depth != 0) { + error(mms, s, id, ERROR_SERVICE, PDU_SIZE); + return; + } + mms_send_pdu(mms, s, e->len); +} + +static bool is(const struct mms_tlv *t, const char *name) +{ + return strlen(name) == t->len && memcmp(t->v, name, t->len) == 0; +} + +/* The item of an ObjectName, if it is domain-specific and of this domain. */ +static bool object_item(const struct zelos_mms_core *mms, const struct mms_tlv *name, + struct mms_tlv *item) +{ + struct mms_tlv specific; + struct mms_tlv domain; + const uint8_t *p; + + if (!mms_find(name, 0xA1, &specific)) { + return false; + } + p = specific.v; + return mms_next(&p, specific.v + specific.len, &domain) && domain.tag == 0x1A && + mms_next(&p, specific.v + specific.len, item) && item->tag == 0x1A && + is(&domain, mms->model->ld); +} + +/* A page of a name list, after the name continueAfter gives. */ +struct list { + struct mms_enc *e; + const struct mms_tlv *after; + bool started; + bool more; +}; + +/* The list's next name. False: the page is full. */ +static bool list_name(struct list *l, const char *name, size_t len) +{ + if (!l->started) { + l->started = l->after->len == len && memcmp(l->after->v, name, len) == 0; + return true; + } + if (l->e->cap - l->e->len < 2 + len + LIST_TAIL) { + l->more = true; + return false; + } + mms_tlv(l->e, 0x1A, name, len); + return true; +} + +/* Every level of every name once: "LN", "LN$FC", "LN$FC$DO"... */ +static void list_variables(const struct zelos_mms_core *mms, struct list *l) +{ + struct mms_iter it = {0}; + char prev[ZELOS_MMS_NAME_MAX + 1] = ""; + + while (mms_iter_next(mms->model, &it)) { + for (size_t i = 1; i <= it.len; i++) { + if (it.name[i] != '$' && it.name[i] != 0) { + continue; + } + /* New unless the name before had it too. */ + if ((strncmp(prev, it.name, i) != 0 || (prev[i] != '$' && prev[i] != 0)) && + !list_name(l, it.name, i)) { + return; + } + } + memcpy(prev, it.name, sizeof(prev)); + } +} + +static void get_name_list(struct zelos_mms_core *mms, int s, const struct mms_tlv *id, + const struct mms_tlv *req) +{ + const struct zelos_mms_model *model = mms->model; + struct mms_tlv t; + struct mms_tlv kind; + struct mms_tlv scope; + struct mms_tlv after = {0}; + struct mms_enc e; + struct list l = {.e = &e, .after = &after}; + const uint8_t *p; + + if (!mms_find(req, 0xA0, &t) || !mms_find(&t, 0x80, &kind) || kind.len != 1 || + !mms_find(req, 0xA1, &t)) { + reject(mms, s, id, REJECT_CONFIRMED_REQUEST, INVALID_ARGUMENT); + return; + } + p = t.v; + if (!mms_next(&p, t.v + t.len, &scope)) { + reject(mms, s, id, REJECT_CONFIRMED_REQUEST, INVALID_ARGUMENT); + return; + } + if (scope.tag == 0x81 && !is(&scope, model->ld)) { + error(mms, s, id, ERROR_DEFINITION, OBJECT_UNDEFINED); + return; + } + l.started = !mms_find(req, 0x82, &after); + + begin(mms, s, &e, CONFIRMED_RESPONSE, 0x02, id); + mms_begin(&e, GET_NAME_LIST); + mms_begin(&e, 0xA0); + if (scope.tag == 0x80 && kind.v[0] == CLASS_DOMAIN) { + /* VMD-specific: the one domain. */ + list_name(&l, model->ld, strlen(model->ld)); + } else if (scope.tag == 0x81 && kind.v[0] == CLASS_NAMED_VARIABLE) { + list_variables(mms, &l); + } else if (scope.tag == 0x81 && kind.v[0] == CLASS_NAMED_VARIABLE_LIST) { + for (size_t i = 0; i < model->data_set_count; i++) { + const char *name = model->data_sets[i].name; + + if (!list_name(&l, name, strlen(name))) { + break; + } + } + } else { + /* Nothing of any other class or scope: an empty list. */ + l.started = l.started || after.len == 0; + } + if (!l.started) { + error(mms, s, id, ERROR_SERVICE, CONTINUATION_INVALID); + return; + } + mms_end(&e); + mms_bool(&e, 0x81, l.more); + mms_end(&e); + respond(mms, s, id, &e); +} + +static void failure(struct mms_enc *e, int code) +{ + mms_u8(e, 0x80, (uint8_t)code); +} + +static void read_variables(struct zelos_mms_core *mms, int s, const struct mms_tlv *id, + const struct mms_tlv *req) +{ + const struct zelos_mms_model *model = mms->model; + struct mms_tlv t; + struct mms_tlv spec; + struct mms_tlv item; + struct mms_enc e; + const uint8_t *p; + int ds; + + if (mms_find(req, 0x80, &t) && (t.len != 1 || t.v[0] != 0)) { + /* specificationWithResult. */ + error(mms, s, id, ERROR_ACCESS, OBJECT_ACCESS_UNSUPPORTED); + return; + } + if (!mms_find(req, 0xA1, &t)) { + reject(mms, s, id, REJECT_CONFIRMED_REQUEST, INVALID_ARGUMENT); + return; + } + p = t.v; + if (!mms_next(&p, t.v + t.len, &spec) || (spec.tag != 0xA0 && spec.tag != 0xA1)) { + reject(mms, s, id, REJECT_CONFIRMED_REQUEST, INVALID_ARGUMENT); + return; + } + /* Before the response is begun: a change found may send a report. */ + mms_scan(mms); + + begin(mms, s, &e, CONFIRMED_RESPONSE, 0x02, id); + mms_begin(&e, READ); + mms_begin(&e, 0xA1); + if (spec.tag == 0xA1) { + /* A named variable list: its members in order. */ + ds = object_item(mms, &spec, &item) ? mms_data_set(model, item.v, item.len) : -1; + if (ds < 0) { + error(mms, s, id, ERROR_DEFINITION, OBJECT_UNDEFINED); + return; + } + for (size_t m = 0; m < model->data_sets[ds].count; m++) { + mms_leaf_value(mms, &e, model->data_sets[ds].members[m]); + } + } + for (p = spec.v; spec.tag == 0xA0 && p < spec.v + spec.len;) { + struct mms_tlv variable; + struct mms_tlv name; + + if (!mms_next(&p, spec.v + spec.len, &variable) || variable.tag != 0x30 || + !mms_find(&variable, 0xA0, &name)) { + reject(mms, s, id, REJECT_CONFIRMED_REQUEST, INVALID_ARGUMENT); + return; + } + if (mms_find(&variable, 0xA5, &t)) { + /* Alternate access. */ + failure(&e, MMS_ACCESS_UNSUPPORTED); + } else if (!object_item(mms, &name, &item) || + mms_object(mms, &e, item.v, item.len, false) == MMS_NONE) { + failure(&e, MMS_NON_EXISTENT); + } + } + mms_end(&e); + mms_end(&e); + respond(mms, s, id, &e); +} + +/* How many TLVs in is made of, or -1: malformed. */ +static int count(const struct mms_tlv *in) +{ + const uint8_t *p = in->v; + struct mms_tlv t; + int n = 0; + + while (p < in->v + in->len) { + if (!mms_next(&p, in->v + in->len, &t)) { + return -1; + } + n++; + } + return n; +} + +static void write_variables(struct zelos_mms_core *mms, int s, const struct mms_tlv *id, + const struct mms_tlv *req) +{ + const uint8_t *p = req->v; + const uint8_t *v; + const uint8_t *d; + struct mms_tlv spec; + struct mms_tlv data; + struct mms_enc e; + int values; + + if (!mms_next(&p, req->v + req->len, &spec) || !mms_next(&p, req->v + req->len, &data) || + data.tag != 0xA0 || (spec.tag != 0xA0 && spec.tag != 0xA1)) { + reject(mms, s, id, REJECT_CONFIRMED_REQUEST, INVALID_ARGUMENT); + return; + } + values = count(&data); + /* A value for each variable, checked before any is written. */ + if (values <= 0 || (spec.tag == 0xA0 && count(&spec) != values)) { + reject(mms, s, id, REJECT_CONFIRMED_REQUEST, INVALID_ARGUMENT); + return; + } + + begin(mms, s, &e, CONFIRMED_RESPONSE, 0x02, id); + mms_begin(&e, WRITE); + v = spec.v; + d = data.v; + for (int i = 0; i < values; i++) { + struct mms_tlv variable; + struct mms_tlv name; + struct mms_tlv item; + struct mms_tlv value; + struct mms_object at; + /* A named variable list holds nothing that can be written. */ + int code = MMS_ACCESS_DENIED; + + (void)mms_next(&d, data.v + data.len, &value); + if (spec.tag == 0xA0) { + (void)mms_next(&v, spec.v + spec.len, &variable); + if (!mms_find(&variable, 0xA0, &name) || !object_item(mms, &name, &item)) { + code = MMS_NON_EXISTENT; + } else { + switch (mms_lookup(mms, item.v, item.len, &at)) { + case MMS_NONE: + code = MMS_NON_EXISTENT; + break; + case MMS_LEAF: + if (at.leaf < 0) { + code = mms_rcb_write(mms, at.rcb, at.attr, &value, + s); + } + break; + default: + break; + } + } + } + if (code == MMS_SUCCESS) { + mms_tlv(&e, 0x81, NULL, 0); + } else { + failure(&e, code); + } + } + mms_end(&e); + respond(mms, s, id, &e); +} + +static void get_variable_access_attributes(struct zelos_mms_core *mms, int s, + const struct mms_tlv *id, const struct mms_tlv *req) +{ + struct mms_tlv name; + struct mms_tlv item; + struct mms_enc e; + + begin(mms, s, &e, CONFIRMED_RESPONSE, 0x02, id); + mms_begin(&e, GET_VARIABLE_ACCESS_ATTRIBUTES); + /* mmsDeletable: no. */ + mms_bool(&e, 0x80, false); + mms_begin(&e, 0xA2); + if (!mms_find(req, 0xA0, &name) || !object_item(mms, &name, &item) || + mms_object(mms, &e, item.v, item.len, true) == MMS_NONE) { + error(mms, s, id, ERROR_DEFINITION, OBJECT_UNDEFINED); + return; + } + mms_end(&e); + mms_end(&e); + respond(mms, s, id, &e); +} + +static void get_named_variable_list_attributes(struct zelos_mms_core *mms, int s, + const struct mms_tlv *id, const struct mms_tlv *req) +{ + const struct zelos_mms_model *model = mms->model; + struct mms_tlv item; + struct mms_enc e; + char name[ZELOS_MMS_NAME_MAX + 1]; + const int ds = object_item(mms, req, &item) ? mms_data_set(model, item.v, item.len) : -1; + + if (ds < 0) { + error(mms, s, id, ERROR_DEFINITION, OBJECT_UNDEFINED); + return; + } + begin(mms, s, &e, CONFIRMED_RESPONSE, 0x02, id); + mms_begin(&e, GET_NAMED_VARIABLE_LIST_ATTRIBUTES); + mms_bool(&e, 0x80, false); + mms_begin(&e, 0xA1); + for (size_t m = 0; m < model->data_sets[ds].count; m++) { + mms_leaf_name(model, model->data_sets[ds].members[m], name); + mms_begin(&e, 0x30); + mms_begin(&e, 0xA0); + mms_begin(&e, 0xA1); + mms_str(&e, 0x1A, model->ld); + mms_str(&e, 0x1A, name); + mms_end(&e); + mms_end(&e); + mms_end(&e); + } + mms_end(&e); + mms_end(&e); + respond(mms, s, id, &e); +} + +/* status: state changes allowed, operational. identify: the model's three names. */ +static void vmd(struct zelos_mms_core *mms, int s, const struct mms_tlv *id, uint8_t service) +{ + const struct zelos_mms_model *model = mms->model; + struct mms_enc e; + + begin(mms, s, &e, CONFIRMED_RESPONSE, 0x02, id); + mms_begin(&e, 0x20 | service); + if (service == STATUS) { + mms_u8(&e, 0x80, 0); + mms_u8(&e, 0x81, 0); + } else { + mms_str(&e, 0x80, model->vendor); + mms_str(&e, 0x81, model->name); + mms_str(&e, 0x82, model->revision); + } + mms_end(&e); + respond(mms, s, id, &e); +} + +bool mms_pdu(struct zelos_mms_core *mms, int s, const uint8_t *p, size_t len) +{ + const uint8_t *end = p + len; + struct mms_tlv top; + struct mms_tlv id; + struct mms_tlv req; + + if (len < 2) { + return false; + } + switch (p[0]) { + case CONFIRMED_REQUEST: + break; + case CONCLUDE_REQUEST: + mms->out[ZELOS_MMS_HEAD] = CONCLUDE_RESPONSE; + mms->out[ZELOS_MMS_HEAD + 1] = 0; + mms_send_pdu(mms, s, 2); + return true; + case CANCEL_REQUEST: + /* Requests are answered as they come: none is ever outstanding. */ + if (!mms_next(&p, end, &id)) { + return false; + } + reject(mms, s, &id, REJECT_CANCEL_REQUEST, INVALID_INVOKE_ID); + return true; + case INITIATE_REQUEST: + return false; + default: + /* Responses, errors, rejects, unconfirmed: nothing to answer. */ + return true; + } + if (!mms_next(&p, end, &top)) { + return false; + } + p = top.v; + end = top.v + top.len; + if (!mms_next(&p, end, &id) || id.tag != 0x02 || id.len == 0 || id.len > 5 || p == end) { + return false; + } + switch (p[0]) { + case STATUS: + case IDENTIFY: + vmd(mms, s, &id, p[0]); + return true; + case GET_NAME_LIST: + case READ: + case WRITE: + case GET_VARIABLE_ACCESS_ATTRIBUTES: + case GET_NAMED_VARIABLE_LIST_ATTRIBUTES: + break; + default: + reject(mms, s, &id, REJECT_CONFIRMED_REQUEST, UNRECOGNIZED_SERVICE); + return true; + } + if (!mms_next(&p, end, &req)) { + return false; + } + switch (req.tag) { + case GET_NAME_LIST: + get_name_list(mms, s, &id, &req); + break; + case READ: + read_variables(mms, s, &id, &req); + break; + case WRITE: + write_variables(mms, s, &id, &req); + break; + case GET_VARIABLE_ACCESS_ATTRIBUTES: + get_variable_access_attributes(mms, s, &id, &req); + break; + default: + get_named_variable_list_attributes(mms, s, &id, &req); + break; + } + return true; +} diff --git a/lib/mms/zephyr/mms.c b/lib/mms/zephyr/mms.c new file mode 100644 index 0000000..529ccf0 --- /dev/null +++ b/lib/mms/zephyr/mms.c @@ -0,0 +1,255 @@ +/* + * MMS server on Zephyr sockets: one thread polls the TCP listener and the + * client sockets, below every CAN protocol's priority, and drives the core. + * A socket that does not take a TPKT within SEND_WAIT_MS closes: a client that + * stops reading holds the other up that long, once. The wait is kept here: a + * blocking send waits CONFIG_NET_SOCKET_MAX_SEND_WAIT, 10 s, unless + * CONFIG_NET_CONTEXT_SNDTIMEO is built in and SO_SNDTIMEO set. TCP keepalive + * probes a silent client every 5 s and closes one that does not answer three + * probes a second apart. zelos_mms_poke() is served within POLL_MS. + */ + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +LOG_MODULE_REGISTER(zelos_mms, LOG_LEVEL_INF); + +/* The core's deepest path holds about 1.5 KB; the socket calls go below it. */ +#define STACK_SIZE 4096 +/* With the rest of the network stack (snippets/ethernet), below UDS on CAN (6). */ +#define PRIORITY 7 +/* Poll at least this often: a poke, the link. */ +#define POLL_MS 10 +#define SEND_WAIT_MS 500 +#define SEND_RETRY_MS 2 +/* Keepalive: probes after KEEP_IDLE_S of silence, KEEP_COUNT of them a second apart. */ +#define KEEP_IDLE_S 5 +#define KEEP_INTERVAL_S 1 +#define KEEP_COUNT 3 +/* Before a reboot: the FINs, acknowledged on a LAN. */ +#define RESET_DRAIN_MS 100 +/* Listener and client sockets: CONFIG_ZVFS_POLL_MAX at least. */ +#define FDS (1 + ZELOS_MMS_SOCKETS) +BUILD_ASSERT(CONFIG_ZVFS_POLL_MAX >= FDS, "one poll() takes every MMS socket"); + +static struct zelos_mms_core core; +static int fd[ZELOS_MMS_SOCKETS] = {[0 ... ZELOS_MMS_SOCKETS - 1] = -1}; +static uint8_t rx[512]; +static atomic_t poked; +/* Set by the reboot hook: the MMS thread touches no socket after. */ +static atomic_t rebooting; + +void zelos_mms_poke(void) +{ + atomic_set(&poked, 1); +} + +static bool send_all(void *ctx, int s, const uint8_t *data, size_t len) +{ + ARG_UNUSED(ctx); + + const k_timepoint_t end = sys_timepoint_calc(K_MSEC(SEND_WAIT_MS)); + + while (len > 0) { + ssize_t n = zsock_send(fd[s], data, len, ZSOCK_MSG_DONTWAIT); + + if (n > 0) { + data += n; + len -= n; + continue; + } + if ((errno != EAGAIN && errno != ENOBUFS && errno != ENOMEM) || + sys_timepoint_expired(end)) { + LOG_WRN("client socket %d: send failed (%d), closing", s, errno); + return false; + } + /* Its window or the transmit buffers are full: the TCP threads run meanwhile. */ + k_msleep(SEND_RETRY_MS); + } + return true; +} + +static void close_socket(void *ctx, int s) +{ + ARG_UNUSED(ctx); + + LOG_INF("client socket %d closed", s); + zsock_close(fd[s]); + fd[s] = -1; +} + +static const struct zelos_mms_ops ops = { + .send = send_all, + .close = close_socket, +}; + +static int open_listener(void) +{ + struct net_sockaddr_in addr = { + .sin_family = NET_AF_INET, + .sin_port = net_htons(ZELOS_MMS_PORT), + }; + int s = zsock_socket(NET_AF_INET, NET_SOCK_STREAM, NET_IPPROTO_TCP); + + if (s < 0 || zsock_bind(s, (struct net_sockaddr *)&addr, sizeof(addr)) < 0 || + zsock_listen(s, ZELOS_MMS_SOCKETS) < 0) { + LOG_ERR("TCP %d: %d", ZELOS_MMS_PORT, errno); + if (s >= 0) { + zsock_close(s); + } + return -1; + } + return s; +} + +static void accept_one(int listener) +{ + const int one = 1; + const int idle = KEEP_IDLE_S; + const int interval = KEEP_INTERVAL_S; + const int count = KEEP_COUNT; + struct net_sockaddr_in from = {0}; + net_socklen_t from_len = sizeof(from); + int c = zsock_accept(listener, (struct net_sockaddr *)&from, &from_len); + int s; + + if (c < 0) { + return; + } + /* The address is Owner, and who a held buffered block is kept for. */ + s = zelos_mms_core_accept(&core, (const uint8_t *)&from.sin_addr, sizeof(from.sin_addr), + k_uptime_get()); + if (s < 0) { + /* Every socket taken, the refusing one too. */ + zsock_close(c); + return; + } + (void)zsock_setsockopt(c, NET_IPPROTO_TCP, ZSOCK_TCP_NODELAY, &one, sizeof(one)); + if (zsock_setsockopt(c, ZSOCK_SOL_SOCKET, ZSOCK_SO_KEEPALIVE, &one, sizeof(one)) < 0 || + zsock_setsockopt(c, NET_IPPROTO_TCP, ZSOCK_TCP_KEEPIDLE, &idle, sizeof(idle)) < 0 || + zsock_setsockopt(c, NET_IPPROTO_TCP, ZSOCK_TCP_KEEPINTVL, &interval, + sizeof(interval)) < 0 || + zsock_setsockopt(c, NET_IPPROTO_TCP, ZSOCK_TCP_KEEPCNT, &count, sizeof(count)) < 0) { + LOG_WRN("client socket %d: no keepalive (%d)", s, errno); + } + fd[s] = c; +} + +static void receive(int s) +{ + ssize_t n = zsock_recv(fd[s], rx, sizeof(rx), ZSOCK_MSG_DONTWAIT); + + if (n > 0) { + zelos_mms_core_receive(&core, s, rx, n, k_uptime_get()); + } else if (n == 0 || errno != EAGAIN) { + zelos_mms_core_close(&core, s, k_uptime_get()); + } +} + +static void run(void *p1, void *p2, void *p3) +{ + struct zsock_pollfd fds[FDS]; + bool up = false; + int listener = -1; + + ARG_UNUSED(p1); + ARG_UNUSED(p2); + ARG_UNUSED(p3); + + for (;;) { + int64_t now = k_uptime_get(); + const bool was_up = up; + int64_t next; + int ready; + + if (atomic_get(&rebooting)) { + k_sleep(K_FOREVER); + } + up = zelos_eth_ipv4_usable(zelos_eth_ipv4()); + if (up && listener < 0) { + listener = open_listener(); + } else if (!up && was_up) { + /* The link went: every client with it. Buffered blocks keep filling. */ + for (int s = 0; s < ZELOS_MMS_SOCKETS; s++) { + zelos_mms_core_close(&core, s, now); + } + } + next = atomic_clear(&poked) ? zelos_mms_core_poke(&core, now) + : zelos_mms_core_tick(&core, now); + if (listener < 0) { + k_msleep(POLL_MS); + continue; + } + if (next <= now) { + /* More to send at once: the TCP threads at this priority first. */ + k_yield(); + } + + fds[0] = (struct zsock_pollfd){.fd = listener, .events = ZSOCK_POLLIN}; + for (int s = 0; s < ZELOS_MMS_SOCKETS; s++) { + fds[1 + s] = (struct zsock_pollfd){.fd = fd[s], .events = ZSOCK_POLLIN}; + } + ready = zsock_poll(fds, FDS, (int)CLAMP(next - now, 0, POLL_MS)); + if (ready < 0) { + /* Never spin on a failing poll. */ + LOG_ERR("poll: %d", errno); + k_msleep(POLL_MS); + } + if (ready <= 0 || atomic_get(&rebooting)) { + continue; + } + if (fds[0].revents & ZSOCK_POLLIN) { + accept_one(listener); + } + for (int s = 0; s < ZELOS_MMS_SOCKETS; s++) { + if (fd[s] >= 0 && fds[1 + s].fd == fd[s] && fds[1 + s].revents != 0) { + receive(s); + } + } + } +} + +K_THREAD_DEFINE(mms_tid, STACK_SIZE, run, NULL, NULL, NULL, PRIORITY, 0, SYS_FOREVER_MS); + +/* zelos_reboot()'s hook, in the rebooting thread: every client learns of it at once (FIN). */ +static void close_clients(void) +{ + bool closed = false; + + /* The MMS thread leaves the sockets alone from here (run()). */ + atomic_set(&rebooting, 1); + for (int s = 0; s < ZELOS_MMS_SOCKETS; s++) { + if (fd[s] >= 0) { + zsock_close(fd[s]); + fd[s] = -1; + closed = true; + } + } + if (closed) { + k_msleep(RESET_DRAIN_MS); + } +} + +int zelos_mms_start(const struct zelos_mms_model *model) +{ + /* A number per boot: an EntryID of an earlier boot is refused, not resumed. */ + int err = zelos_mms_core_init(&core, model, sys_rand32_get(), &ops, NULL); + + if (err != 0) { + LOG_ERR("model refused: %d", err); + return err; + } + zelos_reboot_on(close_clients); + k_thread_start(mms_tid); + LOG_INF("MMS server %s on TCP %d", model->ld, ZELOS_MMS_PORT); + return 0; +} diff --git a/nodes/full/CMakeLists.txt b/nodes/full/CMakeLists.txt index e63db41..d692a65 100644 --- a/nodes/full/CMakeLists.txt +++ b/nodes/full/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.20.0) -# XCP, UDS, AUTOSAR, Ethernet and GOOSE are part of this image, so their snippets apply without -S. -set(SNIPPET xcp uds autosar ethernet goose CACHE STRING "Snippets every build of this image takes") +# XCP, UDS, AUTOSAR, Ethernet, GOOSE and MMS are part of this image, so their snippets apply without -S. +set(SNIPPET xcp uds autosar ethernet goose mms CACHE STRING "Snippets every build of this image takes") find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) project(full) @@ -17,5 +17,7 @@ target_sources(app PRIVATE ) target_sources_ifdef(CONFIG_ZELOS_SOMEIP app PRIVATE ${nodes}/dcdc/src/someip.c) target_sources_ifdef(CONFIG_ZELOS_GOOSE app PRIVATE src/goose.c) +# Serves what GOOSE publishes: built with it. +target_sources_ifdef(CONFIG_ZELOS_MMS app PRIVATE src/mms.c) # zephyr/dcdc.a2l, the DC-DC's A2L with this image's addresses. zelos_xcp_a2l(${nodes}/dcdc/dcdc.a2l) diff --git a/nodes/full/sample.yaml b/nodes/full/sample.yaml index 7882b46..9119c1f 100644 --- a/nodes/full/sample.yaml +++ b/nodes/full/sample.yaml @@ -1,5 +1,5 @@ sample: - name: Combined bench image (DC-DC + XCP + UDS + AUTOSAR + Ethernet + GOOSE, genset J1939, PDU CANopen) + name: Combined bench image (DC-DC + XCP + UDS + AUTOSAR + Ethernet + GOOSE + MMS, genset J1939, PDU CANopen) common: platform_allow: nucleo_h753zi integration_platforms: @@ -12,3 +12,4 @@ tests: - autosar - ethernet - goose + - mms diff --git a/nodes/full/src/main.c b/nodes/full/src/main.c index 7502509..48e50a3 100644 --- a/nodes/full/src/main.c +++ b/nodes/full/src/main.c @@ -4,7 +4,8 @@ * brings the bus up once; each node then starts its own threads. A signal * generator (nodes/full/src/waveform.c) adds a chirped Waveform frame for plots. * Ethernet (lib/eth) comes up beside them, at 10.1.1.75 by default, with - * GOOSE (lib/goose, nodes/full/src/goose.c) on it. + * GOOSE (lib/goose, nodes/full/src/goose.c) and the MMS server (lib/mms, + * nodes/full/src/mms.c) on it. * * The UDS server is the DC-DC's: CommunicationControl and ControlDTCSetting * act on the DC-DC alone. ECUReset reboots the MCU, so every node restarts. @@ -19,6 +20,7 @@ #include "../../genset/src/genset_node.h" #include "../../pdu/src/pdu_node.h" #include "goose.h" +#include "mms.h" #include "waveform.h" LOG_MODULE_REGISTER(full, LOG_LEVEL_INF); @@ -41,6 +43,9 @@ int main(void) #if defined(CONFIG_ZELOS_GOOSE) (void)full_goose_start(); #endif +#if defined(CONFIG_ZELOS_MMS) + (void)full_mms_start(); +#endif return 0; } diff --git a/nodes/full/src/mms.c b/nodes/full/src/mms.c new file mode 100644 index 0000000..a96a7ba --- /dev/null +++ b/nodes/full/src/mms.c @@ -0,0 +1,123 @@ +/* + * The image's MMS server (lib/mms): the logical device its GOOSE publishes + * from, ZELOSFULL, as zelosfull.cid describes it. Every data object has its + * value, q and t. + * + * LLN0: Beh (on); the data sets ds_pdu and ds_dcdc, GOOSE's own, members in + * the same order; report control blocks brcb_pdu01 (buffered, ds_pdu) and + * urcb_dcdc01 (unbuffered, ds_dcdc). + * XSWI1-8 Pos (Dbpos), PTRC1-8 Tr, EmcyGGIO1 IntIn1: the PDU's channels + * powered, their trip latches, overcurrent EMCYs since boot. Read when the + * PDU says they changed. + * OutMMDC1 Vol and Amp, InMMDC1 Amp, STMP1 Tmp, CycGGIO1 CntVal1: the + * DC-DC's output V and A, input A, temperature degC and 50 ms cycles since + * start. Read every 100 ms, GOOSE's period for them. + */ + +#include "mms.h" + +#include + +#include + +#include "../../dcdc/src/dcdc_node.h" +#include "../../pdu/src/pdu_node.h" + +#define CHANNELS 8 +#define SCAN_MS 100 + +enum { + V_BEH, + V_XSWI, + V_PTRC = V_XSWI + CHANNELS, + V_EMCY = V_PTRC + CHANNELS, + V_OUT_VOL, + V_OUT_AMP, + V_IN_AMP, + V_TMP, + V_CYC, + V_COUNT, +}; + +/* A data object: its value, then q and t. */ +#define DO(ln, fc, object, attribute, type, value) \ + {ln, fc, object "$" attribute, type, value}, \ + {ln, fc, object "$q", ZELOS_MMS_QUALITY, ZELOS_MMS_NO_VALUE}, \ + {ln, fc, object "$t", ZELOS_MMS_TIME, ZELOS_MMS_NO_VALUE} +#define XSWI(n) DO("XSWI" #n, "ST", "Pos", "stVal", ZELOS_MMS_DBPOS, V_XSWI + n - 1) +#define PTRC(n) DO("PTRC" #n, "ST", "Tr", "general", ZELOS_MMS_BOOLEAN, V_PTRC + n - 1) + +static const struct zelos_mms_leaf leaves[] = { + DO("LLN0", "ST", "Beh", "stVal", ZELOS_MMS_ENUM, V_BEH), + XSWI(1), XSWI(2), XSWI(3), XSWI(4), XSWI(5), XSWI(6), XSWI(7), XSWI(8), + PTRC(1), PTRC(2), PTRC(3), PTRC(4), PTRC(5), PTRC(6), PTRC(7), PTRC(8), + DO("EmcyGGIO1", "ST", "IntIn1", "stVal", ZELOS_MMS_INT32, V_EMCY), + DO("OutMMDC1", "MX", "Vol", "mag$f", ZELOS_MMS_FLOAT32, V_OUT_VOL), + DO("OutMMDC1", "MX", "Amp", "mag$f", ZELOS_MMS_FLOAT32, V_OUT_AMP), + DO("InMMDC1", "MX", "Amp", "mag$f", ZELOS_MMS_FLOAT32, V_IN_AMP), + DO("STMP1", "MX", "Tmp", "mag$f", ZELOS_MMS_FLOAT32, V_TMP), + DO("CycGGIO1", "ST", "CntVal1", "actVal", ZELOS_MMS_UINT32, V_CYC), +}; + +/* The value leaf of the nth data object above: three leaves each. */ +#define LEAF(object) (3 * (object)) +static const uint8_t ds_pdu[] = { + LEAF(1), LEAF(2), LEAF(3), LEAF(4), LEAF(5), LEAF(6), LEAF(7), LEAF(8), LEAF(9), + LEAF(10), LEAF(11), LEAF(12), LEAF(13), LEAF(14), LEAF(15), LEAF(16), LEAF(17), +}; +static const uint8_t ds_dcdc[] = {LEAF(18), LEAF(19), LEAF(20), LEAF(21), LEAF(22)}; + +static const struct zelos_mms_data_set data_sets[] = { + {"LLN0$ds_pdu", ds_pdu, ARRAY_SIZE(ds_pdu)}, + {"LLN0$ds_dcdc", ds_dcdc, ARRAY_SIZE(ds_dcdc)}, +}; + +static const struct zelos_mms_rcb rcbs[] = { + {"LLN0", "brcb_pdu01", true, 0, 1}, + {"LLN0", "urcb_dcdc01", false, 1, 1}, +}; + +static void read_values(union zelos_mms_value *v) +{ + struct dcdc_sample s; + uint8_t powered; + uint8_t tripped; + int32_t emcy; + + pdu_status(&powered, &tripped, &emcy); + dcdc_latest(&s); + /* Beh: on. */ + v[V_BEH].i32 = 1; + for (int ch = 0; ch < CHANNELS; ch++) { + /* Dbpos: on 2 (closed), off 1 (open). */ + v[V_XSWI + ch].dbpos = (powered & BIT(ch)) != 0U ? 2 : 1; + v[V_PTRC + ch].boolean = (tripped & BIT(ch)) != 0U; + } + v[V_EMCY].i32 = emcy; + v[V_OUT_VOL].f32 = s.output_v; + v[V_OUT_AMP].f32 = s.output_a; + v[V_IN_AMP].f32 = s.input_a; + v[V_TMP].f32 = s.temperature_c; + v[V_CYC].u32 = s.cycles; +} + +static const struct zelos_mms_model model = { + .ld = "ZELOSFULL", + .vendor = "Zelos", + .name = "full", + .revision = "1", + .leaves = leaves, + .leaf_count = ARRAY_SIZE(leaves), + .data_sets = data_sets, + .data_set_count = ARRAY_SIZE(data_sets), + .rcbs = rcbs, + .rcb_count = ARRAY_SIZE(rcbs), + .value_count = V_COUNT, + .read = read_values, + .scan_ms = SCAN_MS, +}; + +int full_mms_start(void) +{ + return zelos_mms_start(&model); +} diff --git a/nodes/full/src/mms.h b/nodes/full/src/mms.h new file mode 100644 index 0000000..57212c9 --- /dev/null +++ b/nodes/full/src/mms.h @@ -0,0 +1,7 @@ +#ifndef FULL_MMS_H_ +#define FULL_MMS_H_ + +/** Start the image's MMS server (lib/mms). 0, or negative errno. */ +int full_mms_start(void); + +#endif /* FULL_MMS_H_ */ diff --git a/nodes/full/zelosfull.cid b/nodes/full/zelosfull.cid new file mode 100644 index 0000000..943565b --- /dev/null +++ b/nodes/full/zelosfull.cid @@ -0,0 +1,83 @@ + + + +
+ + + + +
+

01-0C-CD-01-00-01

+

0001

+

4

+

000

+
+ 4 + 1000 +
+ +
+

01-0C-CD-01-00-02

+

0002

+

4

+

000

+
+ 100 + 100 +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nodes/pdu/src/pdu.c b/nodes/pdu/src/pdu.c index 14bce3a..a8b60bc 100644 --- a/nodes/pdu/src/pdu.c +++ b/nodes/pdu/src/pdu.c @@ -48,6 +48,9 @@ #if defined(CONFIG_ZELOS_GOOSE) #include #endif +#if defined(CONFIG_ZELOS_MMS) +#include +#endif LOG_MODULE_REGISTER(pdu, LOG_LEVEL_INF); @@ -127,10 +130,13 @@ static void tick(void) } OD_readInput8Bit.input1To8 = powered; - /* A change wakes the GOOSE publisher, where there is one. */ + /* A change wakes the GOOSE publisher and the MMS server, where there is one. */ if (atomic_set(&status, powered | tripped << 8) != (powered | tripped << 8)) { #if defined(CONFIG_ZELOS_GOOSE) zelos_goose_poke(); +#endif +#if defined(CONFIG_ZELOS_MMS) + zelos_mms_poke(); #endif } diff --git a/snippets/mms/mms.conf b/snippets/mms/mms.conf new file mode 100644 index 0000000..49d09f1 --- /dev/null +++ b/snippets/mms/mms.conf @@ -0,0 +1,9 @@ +# The IEC 61850 MMS server (lib/mms) on TCP 102: `-S mms`, after the ethernet +# snippet, whose socket counts it raises. +CONFIG_ZELOS_MMS=y +# A client that went without closing is found by its silence. +CONFIG_NET_TCP_KEEPALIVE=y +# Its listener and three connections, on top of the ethernet snippet's. +CONFIG_NET_MAX_CONTEXTS=16 +CONFIG_NET_MAX_CONN=16 +CONFIG_ZVFS_OPEN_MAX=20 diff --git a/snippets/mms/snippet.yml b/snippets/mms/snippet.yml new file mode 100644 index 0000000..a7460c0 --- /dev/null +++ b/snippets/mms/snippet.yml @@ -0,0 +1,3 @@ +name: mms +append: + EXTRA_CONF_FILE: mms.conf diff --git a/testing/pyproject.toml b/testing/pyproject.toml index 6035e68..713bd76 100644 --- a/testing/pyproject.toml +++ b/testing/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "canopen==2.4.1", "cantools==41.3.1", "cryptography==46.0.3", + "open61850==0.9.15", "pytest==9.1.1", "python-can==4.6.1", "pyxcp==0.29.19", diff --git a/testing/suites/mms/test_server.py b/testing/suites/mms/test_server.py new file mode 100644 index 0000000..8d78b42 --- /dev/null +++ b/testing/suites/mms/test_server.py @@ -0,0 +1,214 @@ +"""The combined image's IEC 61850 MMS server (lib/mms, nodes/full/src/mms.c) at +--eth-host, TCP 102, with an MMS client on the host. + +What is tested, one visible behaviour per test: the model is the station file's +(nodes/full/zelosfull.cid), a data object reads with its quality and time, the +unbuffered block reports the DC-DC as it moves, and the buffered block replays +a PDU change made while no client was connected. + +The last test switches a PDU channel over CANopen, so it takes the node from a +bench's own CANopen manager, as testing/suites/canopen does. On Renode, from +the repository root: + + just test-bench mms can-full/build/full.elf +""" + +import dataclasses +import queue +import socket +import time +import xml.etree.ElementTree as ET +from pathlib import Path + +import canopen +import pytest +from open61850.mms import MmsClient, ObjectName, decode_report, is_report, rcb +from open61850.mms.report import TrgOps + +from zelos_testing.bench_plugin import eth_link +from zelos_testing.frames import bound + +ROOT = Path(__file__).resolve().parents[3] +CID = ROOT / "nodes" / "full" / "zelosfull.cid" +EDS = ROOT / "nodes" / "pdu" / "od" / "pdu.eds" +SCL = {"scl": "http://www.iec.ch/61850/2003/SCL"} +PORT = 102 +LD = "ZELOSFULL" +BRCB = ObjectName("LLN0$BR$brcb_pdu01", LD) +URCB = ObjectName("LLN0$RP$urcb_dcdc01", LD) +# Reports on a change and on general interrogation, one asked for when enabling; no integrity +# period. The same settings every time: changing them empties a buffered block. +SETTINGS = rcb.RcbSettings(trg_ops=TrgOps(data_change=True, quality_change=True, general_interrogation=True), intg_pd_ms=0) +# The DC-DC's values are read every 100 ms (nodes/full/src/mms.c). +SCAN_S = 0.1 +# Link up and the address probed after a boot, before the listener opens. +UP_S = 10.0 +# The PDU's CANopen node, and channel 2's bit in its outputs (0x6200). +PDU_NODE = 0x20 +CHANNEL_2 = 0b0000_0010 +# ds_pdu's member for channel 2: XSWI2.Pos.stVal, a Dbpos. +XSWI2 = 1 +DBPOS_OFF, DBPOS_ON = 0b01, 0b10 + + +def item(*parts: str) -> ObjectName: + return ObjectName("$".join(parts), LD) + + +def station() -> ET.Element: + """The logical node LLN0 of the station file.""" + return ET.parse(CID).getroot().find(".//scl:LDevice/scl:LN0", SCL) + + +class Reports: + """An association, its reports queued as they arrive.""" + + def __init__(self, host: str): + self.queue: queue.Queue = queue.Queue() + self.client = MmsClient.connect(host, PORT, timeout=bound(5.0), on_information_report=self._on_message) + + def _on_message(self, message) -> None: + if is_report(message): + self.queue.put(decode_report(message)) + + def next(self, node_s: float = 2.0): + try: + return self.queue.get(timeout=bound(node_s)) + except queue.Empty: + pytest.fail(f"no report within {node_s} s") + + def until(self, done, node_s: float = 5.0): + """Reports up to the first one done() accepts.""" + end = time.monotonic() + bound(node_s) + got = [] + while not got or not done(got[-1]): + assert time.monotonic() < end, f"not done within {node_s} s: {got}" + got.append(self.next(node_s)) + return got + + +def is_gi(report) -> bool: + return all(e.reason.general_interrogation for e in report.entries) + + +def dbpos(value) -> int: + """A Dbpos bit string's two bits.""" + return value.value[0] >> 6 + + +@pytest.fixture(scope="session") +def host(pytestconfig) -> str: + link = eth_link(pytestconfig) + if link is None: + pytest.skip(f"no host interface on {pytestconfig.getoption('eth_host')}'s subnet (--eth-iface)") + end = time.monotonic() + bound(UP_S) + while True: + try: + socket.create_connection((link[1], PORT), timeout=1.0).close() + return link[1] + except OSError: + assert time.monotonic() < end, f"nothing listens on {link[1]}:{PORT}" + time.sleep(0.2) + + +@pytest.fixture +def reports(host): + r = Reports(host) + yield r + r.client.close() + + +@pytest.fixture +def pdu(bus, canopen_takeover): + """The PDU's outputs over SDO: all off before and after.""" + network = canopen.Network(bus) + node = network.add_node(PDU_NODE, str(EDS)) + node.sdo.RESPONSE_TIMEOUT = bound(node.sdo.RESPONSE_TIMEOUT) + network.connect() + outputs = node.sdo[0x6200][1] + outputs.raw = 0 + try: + yield outputs + finally: + outputs.raw = 0 + # The bus belongs to its fixture; only stop listening on it. + network.notifier.stop() + + +def test_model_is_the_station_file(reports): + client = reports.client + ln0 = station() + for data_set in ln0.findall("scl:DataSet", SCL): + want = [ + item(f"{m.get('prefix')}{m.get('lnClass')}{m.get('lnInst')}", m.get("fc"), m.get("doName"), *m.get("daName").split(".")) + for m in data_set.findall("scl:FCDA", SCL) + ] + assert client.get_data_set_members(item("LLN0", data_set.get("name"))) == want + for block in ln0.findall("scl:ReportControl", SCL): + # One instance each (RptEnabled max 1): the name, then 01. + name = item("LLN0", "BR" if block.get("buffered") == "true" else "RP", f"{block.get('name')}01") + status = rcb.read_status(client, name) + assert (status.rpt_id, status.dat_set) == (block.get("rptID"), f"{LD}/LLN0${block.get('datSet')}") + assert not status.rpt_ena + + +def test_data_object_reads_with_quality_and_time(reports): + client = reports.client + # A measured value: mag.f, then q (good) and t. + mag, q, t = client.read(item("OutMMDC1", "MX", "Vol")).members + (f,) = mag.members + assert 0.0 <= f.value < 100.0, f + assert not any(q.value), q + # No clock on the node: time since boot, flagged "clock not synchronized". + assert t.quality & 0x20, t + assert dbpos(client.read(item("XSWI1", "ST", "Pos", "stVal"))) in (DBPOS_OFF, DBPOS_ON) + # Beh: on. + assert client.read(item("LLN0", "ST", "Beh", "stVal")).value == 1 + + +def test_unbuffered_block_reports_the_dcdc(reports): + rcb.enable(reports.client, URCB, SETTINGS) + try: + # The general interrogation's every member, then the members that moved, each scan. + first = reports.until(is_gi)[-1] + assert (first.data_set, len(first.entries)) == (f"{LD}/LLN0$ds_dcdc", 5) + started = time.monotonic() + changes = [reports.next() for _ in range(10)] + took = time.monotonic() - started + finally: + rcb.disable(reports.client, URCB) + assert all(e.reason.data_change for r in changes for e in r.entries) + assert [r.seq_num for r in changes] == [(first.seq_num + 1 + k) % 256 for k in range(10)] + # The cycle counter (member 4) moves every scan. + assert all(any(e.index == 4 for e in r.entries) for r in changes) + assert took < bound(10 * SCAN_S * 2), took + + +def test_buffered_block_replays_a_change_made_while_away(host, pdu): + # Channel 2 on: a report of that one member, with an entry identifier. + first = Reports(host) + try: + rcb.enable(first.client, BRCB, dataclasses.replace(SETTINGS, purge_buf=True)) + first.until(is_gi) + pdu.raw = CHANNEL_2 + on = first.until(lambda r: any(e.reason.data_change for e in r.entries))[-1] + assert [(e.index, dbpos(e.value), e.reason.data_change) for e in on.entries] == [(XSWI2, DBPOS_ON, True)] + finally: + # Gone without disabling the block, as a client that lost its link. + first.client.close() + + # Off again while no client is connected. + pdu.raw = 0 + time.sleep(bound(0.5)) + + # Resumed after the last entry received: the missed change, as it was made, then the present state. + second = Reports(host) + try: + rcb.enable(second.client, BRCB, dataclasses.replace(SETTINGS, entry_id=on.entry_id)) + replayed, *_, now = second.until(is_gi) + assert [(e.index, dbpos(e.value), e.reason.data_change) for e in replayed.entries] == [(XSWI2, DBPOS_OFF, True)] + assert replayed.entry_id != on.entry_id and replayed.time_of_entry > on.time_of_entry + assert dbpos(now.entries[XSWI2].value) == DBPOS_OFF + finally: + rcb.disable(second.client, BRCB) + second.client.close() diff --git a/testing/uv.lock b/testing/uv.lock index 3e2648a..04ed11e 100644 --- a/testing/uv.lock +++ b/testing/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.12" [[package]] @@ -512,6 +512,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/0b/b12a2df5d1b774bd9007a6fdff9381145b6223d37f11afc9c37ab0efd9a1/numpy-2.5.3-cp315-cp315t-win_arm64.whl", hash = "sha256:befa1ae5bd6030b3f512b43ff3fa5290bbed6b84411a44244b14adf835f5b89d", size = 10850807, upload-time = "2026-09-06T16:27:43.868Z" }, ] +[[package]] +name = "open61850" +version = "0.9.15" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/a2/b84b15ccaadb5de83d78e79249ab0533b6474b2b9e2da41939ade52a4676/open61850-0.9.15.tar.gz", hash = "sha256:d838d46d92a913d718d5866d7648396fd3e8b45dcb35cae8dd87230342ed731a", size = 221580, upload-time = "2026-10-28T17:59:17.312Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/8d/ac2cc1901162f23dccf88157065a4d8e6c9cf6d3482a72f97ddb9b84174d/open61850-0.9.15-py3-none-any.whl", hash = "sha256:7cfe14953f810856f45a325178572a486a36892d517556fce0941e85cc4a987d", size = 172256, upload-time = "2026-10-28T17:59:12.129Z" }, +] + [[package]] name = "packaging" version = "26.3" @@ -1047,6 +1056,7 @@ dependencies = [ { name = "canopen" }, { name = "cantools" }, { name = "cryptography" }, + { name = "open61850" }, { name = "pytest" }, { name = "python-can" }, { name = "pyxcp" }, @@ -1062,6 +1072,7 @@ requires-dist = [ { name = "canopen", specifier = "==2.4.1" }, { name = "cantools", specifier = "==41.3.1" }, { name = "cryptography", specifier = "==46.0.3" }, + { name = "open61850", specifier = "==0.9.15" }, { name = "pytest", specifier = "==9.1.1" }, { name = "python-can", specifier = "==4.6.1" }, { name = "pyxcp", specifier = "==0.29.19" }, diff --git a/tests/lib/mms/CMakeLists.txt b/tests/lib/mms/CMakeLists.txt new file mode 100644 index 0000000..7e22c9d --- /dev/null +++ b/tests/lib/mms/CMakeLists.txt @@ -0,0 +1,5 @@ +cmake_minimum_required(VERSION 3.20.0) +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) +project(mms_test) + +target_sources(app PRIVATE src/main.c) diff --git a/tests/lib/mms/prj.conf b/tests/lib/mms/prj.conf new file mode 100644 index 0000000..2f90f4a --- /dev/null +++ b/tests/lib/mms/prj.conf @@ -0,0 +1,3 @@ +CONFIG_ZTEST=y +# The sans-IO core alone: no network needed. +CONFIG_ZELOS_MMS_CORE=y diff --git a/tests/lib/mms/src/main.c b/tests/lib/mms/src/main.c new file mode 100644 index 0000000..6e3d72a --- /dev/null +++ b/tests/lib/mms/src/main.c @@ -0,0 +1,1011 @@ +/* + * The MMS core driven by hand: bytes in, TPKTs out, time injected. The + * transport and association requests are a client's, as captured; the other + * vectors are the layouts of ISO 9506-2 and IEC 61850-8-1. + */ + +#include + +#include +#include + +#include + +/* The values read() fills. */ +enum { + BEH, + IND, + IND_Q, + VOL, + VALUES, +}; + +static union zelos_mms_value values[VALUES]; + +static void read_values(union zelos_mms_value *out) +{ + memcpy(out, values, sizeof(values)); +} + +static const struct zelos_mms_leaf leaves[] = { + {"LLN0", "ST", "Beh$stVal", ZELOS_MMS_ENUM, BEH}, + {"LLN0", "ST", "Beh$q", ZELOS_MMS_QUALITY, ZELOS_MMS_NO_VALUE}, + {"LLN0", "ST", "Beh$t", ZELOS_MMS_TIME, ZELOS_MMS_NO_VALUE}, + {"GGIO1", "ST", "Ind1$stVal", ZELOS_MMS_BOOLEAN, IND}, + {"GGIO1", "ST", "Ind1$q", ZELOS_MMS_QUALITY, IND_Q}, + {"GGIO1", "ST", "Ind1$t", ZELOS_MMS_TIME, ZELOS_MMS_NO_VALUE}, + {"MMXU1", "MX", "Vol$mag$f", ZELOS_MMS_FLOAT32, VOL}, + {"MMXU1", "MX", "Vol$q", ZELOS_MMS_QUALITY, ZELOS_MMS_NO_VALUE}, + {"MMXU1", "MX", "Vol$t", ZELOS_MMS_TIME, ZELOS_MMS_NO_VALUE}, +}; + +/* Ind1.stVal, Ind1.q, Vol.mag.f. */ +static const uint8_t members[] = {3, 4, 6}; +static const struct zelos_mms_data_set data_sets[] = {{"LLN0$ds", members, 3}}; + +enum { + BRCB, + URCB, +}; + +static const struct zelos_mms_rcb rcbs[] = { + {"LLN0", "brcb01", true, 0, 1}, + {"LLN0", "urcb01", false, 0, 1}, +}; + +static const struct zelos_mms_model model = { + .ld = "IED", + .vendor = "V", + .name = "M", + .revision = "1", + .leaves = leaves, + .leaf_count = ARRAY_SIZE(leaves), + .data_sets = data_sets, + .data_set_count = ARRAY_SIZE(data_sets), + .rcbs = rcbs, + .rcb_count = ARRAY_SIZE(rcbs), + .value_count = VALUES, + .read = read_values, +}; + +/* What the core did: per socket, each session message whole, and whether it closed. */ +#define MESSAGES 48 +static uint8_t sent[ZELOS_MMS_SOCKETS][MESSAGES][ZELOS_MMS_FRAME_MAX]; +static size_t sent_len[ZELOS_MMS_SOCKETS][MESSAGES]; +static int sends[ZELOS_MMS_SOCKETS]; +static int tpkts[ZELOS_MMS_SOCKETS]; +static size_t partial[ZELOS_MMS_SOCKETS]; +static bool closed[ZELOS_MMS_SOCKETS]; + +/* Joins the data TPDUs of a message; any other TPDU is a message as it is. */ +static bool fake_send(void *ctx, int s, const uint8_t *data, size_t len) +{ + uint8_t *m = sent[s][sends[s]]; + const bool dt = data[5] == 0xF0; + const size_t skip = dt ? 7 : 0; + + ARG_UNUSED(ctx); + zassert_true(sends[s] < MESSAGES && len >= 7 && data[0] == 3); + zassert_equal((size_t)data[2] << 8 | data[3], len, "TPKT length"); + tpkts[s]++; + memcpy(&m[partial[s]], data + skip, len - skip); + partial[s] += len - skip; + if (!dt || (data[6] & 0x80) != 0) { + sent_len[s][sends[s]++] = partial[s]; + partial[s] = 0; + } + return true; +} + +static void fake_close(void *ctx, int s) +{ + ARG_UNUSED(ctx); + closed[s] = true; +} + +static const struct zelos_mms_ops ops = {fake_send, fake_close}; +static struct zelos_mms_core mms; +static int64_t now; +static uint8_t invoke_id; + +static const uint8_t peer[] = {10, 0, 0, 1}; +static const uint8_t other[] = {10, 0, 0, 2}; + +/* A client's connection request: TPDU size 1024, TSAPs 0001. */ +static const uint8_t cr[] = {0x03, 0x00, 0x00, 0x16, 0x11, 0xE0, 0x00, 0x00, 0x00, 0x01, 0x00, + 0xC0, 0x01, 0x0A, 0xC2, 0x02, 0x00, 0x01, 0xC1, 0x02, 0x00, 0x01}; + +/* + * Its association: session CONNECT, presentation CP (ACSE as context 1, MMS as + * context 3), AARQ, MMS initiate-Request proposing a PDU of 65000. + */ +static const uint8_t association[] = { + 0x03, 0x00, 0x00, 0xBB, 0x02, 0xF0, 0x80, 0x0D, 0xB2, 0x05, 0x06, 0x13, 0x01, 0x00, 0x16, + 0x01, 0x02, 0x14, 0x02, 0x00, 0x02, 0x33, 0x02, 0x00, 0x01, 0x34, 0x02, 0x00, 0x01, 0xC1, + 0x9C, 0x31, 0x81, 0x99, 0xA0, 0x03, 0x80, 0x01, 0x01, 0xA2, 0x81, 0x91, 0x81, 0x04, 0x00, + 0x00, 0x00, 0x01, 0x82, 0x04, 0x00, 0x00, 0x00, 0x01, 0xA4, 0x23, 0x30, 0x0F, 0x02, 0x01, + 0x01, 0x06, 0x04, 0x52, 0x01, 0x00, 0x01, 0x30, 0x04, 0x06, 0x02, 0x51, 0x01, 0x30, 0x10, + 0x02, 0x01, 0x03, 0x06, 0x05, 0x28, 0xCA, 0x22, 0x02, 0x01, 0x30, 0x04, 0x06, 0x02, 0x51, + 0x01, 0x61, 0x5E, 0x30, 0x5C, 0x02, 0x01, 0x01, 0xA0, 0x57, 0x60, 0x55, 0xA1, 0x07, 0x06, + 0x05, 0x28, 0xCA, 0x22, 0x02, 0x03, 0xA2, 0x07, 0x06, 0x05, 0x29, 0x01, 0x87, 0x67, 0x01, + 0xA3, 0x03, 0x02, 0x01, 0x0C, 0xA6, 0x06, 0x06, 0x04, 0x29, 0x01, 0x87, 0x67, 0xA7, 0x03, + 0x02, 0x01, 0x0C, 0xBE, 0x2F, 0x28, 0x2D, 0x02, 0x01, 0x03, 0xA0, 0x28, 0xA8, 0x26, 0x80, + 0x03, 0x00, 0xFD, 0xE8, 0x81, 0x01, 0x05, 0x82, 0x01, 0x05, 0x83, 0x01, 0x0A, 0xA4, 0x16, + 0x80, 0x01, 0x01, 0x81, 0x03, 0x05, 0xF1, 0x00, 0x82, 0x0C, 0x03, 0xEE, 0x1C, 0x00, 0x00, + 0x04, 0x08, 0x00, 0x00, 0x79, 0xEF, 0x18, +}; +/* Where the proposed PDU size is in it. */ +#define ASSOCIATION_PDU_SIZE 152 + +/* Header size of the BER TLV at p, its content length in *len. */ +static size_t tl(const uint8_t *p, size_t *len) +{ + if (p[1] < 0x80) { + *len = p[1]; + return 2; + } + if (p[1] == 0x81) { + *len = p[2]; + return 3; + } + *len = (size_t)p[2] << 8 | p[3]; + return 4; +} + +/* The MMS PDU of the i-th message sent on socket s: under data transfer, context 3. */ +static const uint8_t *pdu(int s, int i, size_t *len) +{ + static const uint8_t data_transfer[] = {0x01, 0x00, 0x01, 0x00}; + const uint8_t *p = sent[s][i]; + + zassert_true(i < sends[s], "message %d of %d", i, sends[s]); + zassert_mem_equal(p, data_transfer, 4); + p += 4; + zassert_equal(p[0], 0x61); + p += tl(p, len); + zassert_equal(p[0], 0x30); + p += tl(p, len); + zassert_mem_equal(p, ((uint8_t[]){0x02, 0x01, 0x03, 0xA0}), 4); + p += 3; + p += tl(p, len); + zassert_equal_ptr(p + *len, &sent[s][i][sent_len[s][i]], "PDU ends with the message"); + return p; +} + +/* Into the PDU: the content of the TLVs with these tags, each inside the one before. */ +static const uint8_t *inside(const uint8_t *p, size_t *len, const uint8_t *tags, size_t n) +{ + for (size_t i = 0; i < n; i++) { + const uint8_t *end = p + *len; + + while (p < end && p[0] != tags[i]) { + size_t skip; + + p += tl(p, &skip); + p += skip; + } + zassert_true(p < end, "no tag 0x%02x", tags[i]); + p += tl(p, len); + } + return p; +} + +/* The last PDU sent on s is exactly these bytes. */ +#define PDU(s, ...) \ + do { \ + const uint8_t want_[] = {__VA_ARGS__}; \ + size_t len_; \ + const uint8_t *got_ = pdu(s, sends[s] - 1, &len_); \ + zassert_equal(len_, sizeof(want_), "length %zu", len_); \ + zassert_mem_equal(got_, want_, sizeof(want_)); \ + } while (0) + +/* The access results of message i on s, a report: unconfirmed, informationReport on RPT. */ +static const uint8_t *report(int s, int i, size_t *len) +{ + const uint8_t *p = pdu(s, i, len); + size_t n = *len; + + zassert_mem_equal(inside(p, &n, (uint8_t[]){0xA3, 0xA0, 0xA1}, 3), + ((uint8_t[]){0x80, 0x03, 'R', 'P', 'T'}), 5); + return inside(p, len, (uint8_t[]){0xA3, 0xA0, 0xA0}, 3); +} + +#define REPORT(s, i, ...) \ + do { \ + const uint8_t want_[] = {__VA_ARGS__}; \ + size_t len_; \ + const uint8_t *got_ = report(s, i, &len_); \ + zassert_equal(len_, sizeof(want_), "length %zu", len_); \ + zassert_mem_equal(got_, want_, sizeof(want_)); \ + } while (0) + +/* Message i on s, the response to a read or a write, has exactly these results. */ +#define RESULTS_AT(s, i, service, ...) \ + do { \ + const uint8_t want_[] = {__VA_ARGS__}; \ + size_t len_; \ + const uint8_t *got_ = pdu(s, i, &len_); \ + got_ = (service) == 0xA4 ? inside(got_, &len_, (uint8_t[]){0xA1, 0xA4, 0xA1}, 3) \ + : inside(got_, &len_, (uint8_t[]){0xA1, 0xA5}, 2); \ + zassert_equal(len_, sizeof(want_), "length %zu", len_); \ + zassert_mem_equal(got_, want_, sizeof(want_)); \ + } while (0) +#define RESULTS(s, service, ...) RESULTS_AT(s, sends[s] - 1, service, __VA_ARGS__) + +/* Bytes from the client, feed_step at a time. */ +static size_t feed_step = SIZE_MAX; + +static void feed(int s, const uint8_t *data, size_t len) +{ + while (len > 0) { + const size_t n = MIN(len, feed_step); + + zelos_mms_core_receive(&mms, s, data, n, now); + data += n; + len -= n; + } +} + +/* A session message from the client, as data TPDUs of at most chunk bytes. */ +static void tsdu(int s, const uint8_t *data, size_t len, size_t chunk) +{ + while (len > 0) { + const size_t n = MIN(len, chunk); + const uint8_t tpkt[7] = {0x03, 0x00, (uint8_t)((7 + n) >> 8), (uint8_t)(7 + n), + 0x02, 0xF0, n == len ? 0x80 : 0x00}; + + feed(s, tpkt, sizeof(tpkt)); + feed(s, data, n); + data += n; + len -= n; + } +} + +static size_t put(uint8_t *out, uint8_t tag, const void *v, size_t n) +{ + zassert_true(n < 0x80); + out[0] = tag; + out[1] = (uint8_t)n; + memcpy(&out[2], v, n); + return 2 + n; +} + +/* An MMS PDU from the client: data transfer, presentation context 3. */ +static void request(int s, const uint8_t *req, size_t len) +{ + uint8_t m[256] = {0x01, + 0x00, + 0x01, + 0x00, + 0x61, + 0x81, + (uint8_t)(len + 9), + 0x30, + 0x81, + (uint8_t)(len + 6), + 0x02, + 0x01, + 0x03, + 0xA0, + 0x81, + (uint8_t)len}; + + zassert_true(len + 16 <= sizeof(m)); + memcpy(&m[16], req, len); + tsdu(s, m, 16 + len, SIZE_MAX); +} + +#define REQUEST(s, ...) \ + do { \ + const uint8_t req_[] = {__VA_ARGS__}; \ + request(s, req_, sizeof(req_)); \ + } while (0) + +/* A confirmed request of one service, with the next invokeID. */ +static void confirmed(int s, uint8_t service, const uint8_t *arg, size_t len) +{ + uint8_t req[200] = {0xA0, (uint8_t)(3 + 2 + len), 0x02, 0x01, ++invoke_id}; + + (void)put(&req[5], service, arg, len); + request(s, req, 7 + len); +} + +/* ObjectName, domain-specific: IED, item. */ +static size_t object_name(uint8_t *out, const char *item) +{ + uint8_t name[80]; + size_t n = put(name, 0x1A, "IED", 3); + + n += put(&name[n], 0x1A, item, strlen(item)); + return put(out, 0xA1, name, n); +} + +/* A variable list of one: SEQUENCE { name [0] ObjectName }. */ +static size_t variable(uint8_t *out, const char *item) +{ + uint8_t name[90]; + uint8_t spec[90]; + size_t n = object_name(name, item); + + n = put(spec, 0xA0, name, n); + return put(out, 0x30, spec, n); +} + +static void read_items(int s, const char *const *items, size_t count) +{ + uint8_t list[160]; + uint8_t spec[170]; + uint8_t arg[180]; + size_t n = 0; + + for (size_t i = 0; i < count; i++) { + n += variable(&list[n], items[i]); + } + n = put(spec, 0xA0, list, n); + n = put(arg, 0xA1, spec, n); + confirmed(s, 0xA4, arg, n); +} + +static void read_item(int s, const char *item) +{ + read_items(s, &item, 1); +} + +static void write_item(int s, const char *item, const uint8_t *data, size_t len) +{ + uint8_t list[100]; + uint8_t arg[150]; + size_t n = variable(list, item); + + n = put(arg, 0xA0, list, n); + n += put(&arg[n], 0xA0, data, len); + confirmed(s, 0xA5, arg, n); +} + +/* + * Write an attribute and expect success, or the DataAccessError code. The + * response comes first; reports the write set going follow it. + */ +#define WRITE_ATTR(s, item, code, ...) \ + do { \ + const uint8_t data_[] = {__VA_ARGS__}; \ + const int at_ = sends[s]; \ + write_item(s, item, data_, sizeof(data_)); \ + if ((code) < 0) { \ + RESULTS_AT(s, at_, 0xA5, 0x81, 0x00); \ + } else { \ + RESULTS_AT(s, at_, 0xA5, 0x80, 0x01, (uint8_t)(code)); \ + } \ + } while (0) + +#define WRITTEN -1 +#define TEMPORARILY_UNAVAILABLE 2 +#define ACCESS_DENIED 3 +#define NON_EXISTENT 10 +#define VALUE_INVALID 11 +#define B_TRUE 0x83, 0x01, 0xFF +#define B_FALSE 0x83, 0x01, 0x00 + +/* A client from address `from`, associated; pdu_size 0 leaves its proposal at 65000. */ +static int associate(const uint8_t *from, uint16_t pdu_size) +{ + uint8_t m[sizeof(association)]; + const int s = zelos_mms_core_accept(&mms, from, 4, now); + + zassert_true(s >= 0); + sends[s] = 0; + tpkts[s] = 0; + partial[s] = 0; + closed[s] = false; + memcpy(m, association, sizeof(m)); + if (pdu_size != 0) { + m[ASSOCIATION_PDU_SIZE] = (uint8_t)(pdu_size >> 8); + m[ASSOCIATION_PDU_SIZE + 1] = (uint8_t)pdu_size; + } + zelos_mms_core_receive(&mms, s, cr, sizeof(cr), now); + zelos_mms_core_receive(&mms, s, m, sizeof(m), now); + zassert_equal(mms.conn[s].state, ZELOS_MMS_ASSOCIATED); + sends[s] = 0; + return s; +} + +static void before(void *fixture) +{ + ARG_UNUSED(fixture); + memset(values, 0, sizeof(values)); + memset(sends, 0, sizeof(sends)); + memset(partial, 0, sizeof(partial)); + memset(closed, 0, sizeof(closed)); + feed_step = SIZE_MAX; + now = 1000; + invoke_id = 0; + zassert_ok(zelos_mms_core_init(&mms, &model, 0, &ops, NULL)); +} + +ZTEST(mms, test_association) +{ + const int s = zelos_mms_core_accept(&mms, peer, sizeof(peer), now); + + /* Connection confirm: the peer's reference, ours, the size and TSAPs back. */ + zelos_mms_core_receive(&mms, s, cr, sizeof(cr), now); + zassert_equal(sent_len[s][0], 22); + zassert_mem_equal(sent[s][0], ((uint8_t[]){0x03, 0x00, 0x00, 0x16, 0x11, 0xD0, 0x00, 0x01, + 0x00, 0x01, 0x00, 0xC0, 0x01, 0x0A, 0xC2, 0x02, + 0x00, 0x01, 0xC1, 0x02, 0x00, 0x01}), + 22); + + /* + * The association, split anywhere. ACCEPT: CPA with both contexts + * accepted in BER, AARE accepted, initiate-Response: PDU 1024, one + * request outstanding each way, nesting 10, version 1, CBB str2 vnam + * vlis, the services of the header. + */ + zelos_mms_core_receive(&mms, s, association, 100, now); + zassert_equal(sends[s], 1); + zelos_mms_core_receive(&mms, s, &association[100], sizeof(association) - 100, now); + static const uint8_t accept[] = { + 0x0E, 0x81, 0x05, 0x06, 0x13, 0x01, 0x00, 0x16, 0x01, 0x02, 0x14, 0x02, 0x00, 0x02, + 0xC1, 0x73, 0x31, 0x71, 0xA0, 0x03, 0x80, 0x01, 0x01, 0xA2, 0x6A, 0x83, 0x04, 0x00, + 0x00, 0x00, 0x01, 0xA5, 0x12, 0x30, 0x07, 0x80, 0x01, 0x00, 0x81, 0x02, 0x51, 0x01, + 0x30, 0x07, 0x80, 0x01, 0x00, 0x81, 0x02, 0x51, 0x01, 0x61, 0x4E, 0x30, 0x4C, 0x02, + 0x01, 0x01, 0xA0, 0x47, 0x61, 0x45, 0xA1, 0x07, 0x06, 0x05, 0x28, 0xCA, 0x22, 0x02, + 0x03, 0xA2, 0x03, 0x02, 0x01, 0x00, 0xA3, 0x05, 0xA1, 0x03, 0x02, 0x01, 0x00, 0xBE, + 0x2E, 0x28, 0x2C, 0x02, 0x01, 0x03, 0xA0, 0x27, 0xA9, 0x25, 0x80, 0x02, 0x04, 0x00, + 0x81, 0x01, 0x01, 0x82, 0x01, 0x01, 0x83, 0x01, 0x0A, 0xA4, 0x16, 0x80, 0x01, 0x01, + 0x81, 0x03, 0x05, 0x61, 0x00, 0x82, 0x0C, 0x03, 0x4E, 0x08, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x10, + }; + + zassert_equal(sent_len[s][1], sizeof(accept), "length %zu", sent_len[s][1]); + zassert_mem_equal(sent[s][1], accept, sizeof(accept)); + zassert_equal(zelos_mms_core_clients(&mms), 1); + zassert_equal(mms.conn[s].pdu_size, 1024); + + /* Conclude, then the session's FINISH: DISCONNECT with the release response, closed. */ + REQUEST(s, 0x8B, 0x00); + PDU(s, 0x8C, 0x00); + tsdu(s, (uint8_t[]){0x09, 0x00}, 2, SIZE_MAX); + zassert_mem_equal(sent[s][3], + ((uint8_t[]){0x0A, 0x10, 0xC1, 0x0E, 0x61, 0x0C, 0x30, 0x0A, 0x02, 0x01, + 0x01, 0xA0, 0x05, 0x63, 0x03, 0x80, 0x01, 0x00}), + 18); + zassert_true(closed[s]); + zassert_equal(zelos_mms_core_clients(&mms), 0); +} + +ZTEST(mms, test_read) +{ + const int s = associate(peer, 0); + static const char *const three[] = {"MMXU1$MX$Vol$mag$f", "GGIO1$ST$Nope", "MMXU1"}; + + /* A data object, IED/GGIO1$ST$Ind1: a structure of stVal, q (good) and t (not changed). */ + REQUEST(s, 0xA0, 0x23, 0x02, 0x01, 0x01, 0xA4, 0x1E, 0xA1, 0x1C, 0xA0, 0x1A, 0x30, 0x18, + 0xA0, 0x16, 0xA1, 0x14, 0x1A, 0x03, 'I', 'E', 'D', 0x1A, 0x0D, 'G', 'G', 'I', 'O', + '1', '$', 'S', 'T', '$', 'I', 'n', 'd', '1'); + PDU(s, 0xA1, 0x1B, 0x02, 0x01, 0x01, 0xA4, 0x16, 0xA1, 0x14, 0xA2, 0x12, B_FALSE, 0x84, + 0x03, 0x03, 0x00, 0x00, 0x91, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F); + + /* It changes 1.5 s after boot, its quality to invalid: t is then, clock not synchronized. + */ + now = 1500; + values[IND].boolean = true; + values[IND_Q].quality = 0x4000; + read_item(s, "GGIO1$ST$Ind1"); + RESULTS(s, 0xA4, 0xA2, 0x12, B_TRUE, 0x84, 0x03, 0x03, 0x40, 0x00, 0x91, 0x08, 0x00, 0x00, + 0x00, 0x01, 0x80, 0x00, 0x00, 0x3F); + + /* Several: a leaf, a name that does not exist, a logical node down to its leaves. */ + values[VOL].f32 = 12.5f; + read_items(s, three, ARRAY_SIZE(three)); + RESULTS(s, 0xA4, 0x87, 0x05, 0x08, 0x41, 0x48, 0x00, 0x00, 0x80, 0x01, NON_EXISTENT, 0xA2, + 0x1C, 0xA2, 0x1A, 0xA2, 0x18, 0xA2, 0x07, 0x87, 0x05, 0x08, 0x41, 0x48, 0x00, 0x00, + 0x84, 0x03, 0x03, 0x00, 0x00, 0x91, 0x08, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, + 0x3F); + + /* The data set as a named variable list: its members in order. */ + REQUEST(s, 0xA0, 0x19, 0x02, 0x01, 0x09, 0xA4, 0x14, 0xA1, 0x12, 0xA1, 0x10, 0xA1, 0x0E, + 0x1A, 0x03, 'I', 'E', 'D', 0x1A, 0x07, 'L', 'L', 'N', '0', '$', 'd', 's'); + RESULTS(s, 0xA4, B_TRUE, 0x84, 0x03, 0x03, 0x40, 0x00, 0x87, 0x05, 0x08, 0x41, 0x48, 0x00, + 0x00); + + /* The object's type: named components, a quality of up to 13 bits, a UTC time. */ + REQUEST(s, 0xA0, 0x1D, 0x02, 0x01, 0x0A, 0xA6, 0x18, 0xA0, 0x16, 0xA1, 0x14, 0x1A, 0x03, + 'I', 'E', 'D', 0x1A, 0x0D, 'G', 'G', 'I', 'O', '1', '$', 'S', 'T', '$', 'I', 'n', + 'd', '1'); + PDU(s, 0xA1, 0x2E, 0x02, 0x01, 0x0A, 0xA6, 0x29, 0x80, 0x01, 0x00, 0xA2, 0x24, 0xA2, 0x22, + 0xA1, 0x20, 0x30, 0x0B, 0x80, 0x05, 's', 't', 'V', 'a', 'l', 0xA1, 0x02, 0x83, 0x00, + 0x30, 0x08, 0x80, 0x01, 'q', 0xA1, 0x03, 0x84, 0x01, 0xF3, 0x30, 0x07, 0x80, 0x01, 't', + 0xA1, 0x02, 0x91, 0x00); + + /* The data set's members: getNamedVariableListAttributes, not deletable. */ + REQUEST(s, 0xA0, 0x15, 0x02, 0x01, 0x0B, 0xAC, 0x10, 0xA1, 0x0E, 0x1A, 0x03, 'I', 'E', 'D', + 0x1A, 0x07, 'L', 'L', 'N', '0', '$', 'd', 's'); + PDU(s, 0xA1, 0x65, 0x02, 0x01, 0x0B, 0xAC, 0x60, 0x80, 0x01, 0x00, 0xA1, 0x5B, 0x30, 0x1E, + 0xA0, 0x1C, 0xA1, 0x1A, 0x1A, 0x03, 'I', 'E', 'D', 0x1A, 0x13, 'G', 'G', 'I', 'O', '1', + '$', 'S', 'T', '$', 'I', 'n', 'd', '1', '$', 's', 't', 'V', 'a', 'l', 0x30, 0x1A, 0xA0, + 0x18, 0xA1, 0x16, 0x1A, 0x03, 'I', 'E', 'D', 0x1A, 0x0F, 'G', 'G', 'I', 'O', '1', '$', + 'S', 'T', '$', 'I', 'n', 'd', '1', '$', 'q', 0x30, 0x1D, 0xA0, 0x1B, 0xA1, 0x19, 0x1A, + 0x03, 'I', 'E', 'D', 0x1A, 0x12, 'M', 'M', 'X', 'U', '1', '$', 'M', 'X', '$', 'V', 'o', + 'l', '$', 'm', 'a', 'g', '$', 'f'); +} + +/* getNameList of the domain's named variables after `after`; the names' TLVs, more in *more. */ +static const uint8_t *name_list(int s, const char *after, size_t *len, bool *more) +{ + uint8_t arg[100] = {0xA0, 0x03, 0x80, 0x01, 0x00, 0xA1, 0x05, 0x81, 0x03, 'I', 'E', 'D'}; + size_t n = 12; + const uint8_t *p; + const uint8_t *flag; + size_t flag_len; + + if (after != NULL) { + n += put(&arg[n], 0x82, after, strlen(after)); + } + confirmed(s, 0xA1, arg, n); + p = pdu(s, sends[s] - 1, len); + flag_len = *len; + flag = inside(p, &flag_len, (uint8_t[]){0xA1, 0xA1, 0x81}, 3); + *more = flag[0] != 0; + return inside(p, len, (uint8_t[]){0xA1, 0xA1, 0xA0}, 3); +} + +ZTEST(mms, test_name_list) +{ + /* A PDU of 256: the list takes several pages. */ + const int s = associate(peer, 256); + /* The first: every level once, in the model's order, as far as 256 bytes go. */ + static const char *const first[] = { + "LLN0", + "LLN0$ST", + "LLN0$ST$Beh", + "LLN0$ST$Beh$stVal", + "LLN0$ST$Beh$q", + "LLN0$ST$Beh$t", + "LLN0$RP", + "LLN0$RP$urcb01", + "LLN0$RP$urcb01$RptID", + "LLN0$RP$urcb01$RptEna", + "LLN0$RP$urcb01$Resv", + "LLN0$RP$urcb01$DatSet", + "LLN0$RP$urcb01$ConfRev", + }; + char after[ZELOS_MMS_NAME_MAX + 1] = ""; + uint8_t name[20]; + uint8_t arg[22]; + const uint8_t *p; + size_t len; + size_t n; + bool more; + int names = 0; + int pages = 1; + + zassert_equal(mms.conn[s].pdu_size, 256); + /* + * Request: class named variable, domain IED. Response: 215 bytes of + * names, then moreFollows. + */ + REQUEST(s, 0xA0, 0x11, 0x02, 0x01, 0x01, 0xA1, 0x0C, 0xA0, 0x03, 0x80, 0x01, 0x00, 0xA1, + 0x05, 0x81, 0x03, 'I', 'E', 'D'); + p = pdu(s, 0, &len); + zassert_equal(len, 230); + zassert_mem_equal(p, + ((uint8_t[]){0xA1, 0x81, 0xE3, 0x02, 0x01, 0x01, 0xA1, 0x81, 0xDD, 0xA0, + 0x81, 0xD7}), + 12); + for (p += 12; names < (int)ARRAY_SIZE(first); p += 2 + p[1], names++) { + zassert_equal(p[0], 0x1A); + zassert_equal(p[1], strlen(first[names])); + zassert_mem_equal(&p[2], first[names], p[1]); + } + zassert_mem_equal(p, ((uint8_t[]){0x81, 0x01, 0xFF}), 3); + + /* The pages after it, each continuing after the last name of the one before. */ + invoke_id = 1; + strcpy(after, first[ARRAY_SIZE(first) - 1]); + for (more = true; more; pages++) { + const uint8_t *end; + + p = name_list(s, after, &len, &more); + zassert_true(sent_len[s][sends[s] - 1] <= 256 + 19, "a page fits the PDU"); + for (end = p + len; p < end; p += 2 + p[1], names++) { + memcpy(after, &p[2], p[1]); + after[p[1]] = 0; + } + } + /* + * LLN0 6, its unbuffered block 2 + 12 and buffered block 2 + 15, GGIO1 6, + * MMXU1 7; the last is the last leaf. + */ + zassert_equal(names, 50); + zassert_true(pages >= 4); + zassert_ok(strcmp(after, "MMXU1$MX$Vol$t")); + + /* An unknown continueAfter: service error, continuation-invalid. */ + (void)confirmed(s, 0xA1, + (uint8_t[]){0xA0, 0x03, 0x80, 0x01, 0x00, 0xA1, 0x05, 0x81, 0x03, 'I', 'E', + 'D', 0x82, 0x01, 'X'}, + 15); + PDU(s, 0xA2, 0x0A, 0x80, 0x01, invoke_id, 0xA2, 0x05, 0xA0, 0x03, 0x84, 0x01, 0x04); + + /* An answer larger than the PDU agreed, the type of LLN0: service error, pdu-size. */ + n = object_name(name, "LLN0"); + n = put(arg, 0xA0, name, n); + confirmed(s, 0xA6, arg, n); + PDU(s, 0xA2, 0x0A, 0x80, 0x01, invoke_id, 0xA2, 0x05, 0xA0, 0x03, 0x84, 0x01, 0x03); + + /* The VMD's domains, the domain's named variable lists, another domain. */ + confirmed(s, 0xA1, (uint8_t[]){0xA0, 0x03, 0x80, 0x01, 0x09, 0xA1, 0x02, 0x80, 0x00}, 9); + PDU(s, 0xA1, 0x0F, 0x02, 0x01, invoke_id, 0xA1, 0x0A, 0xA0, 0x05, 0x1A, 0x03, 'I', 'E', 'D', + 0x81, 0x01, 0x00); + confirmed(s, 0xA1, + (uint8_t[]){0xA0, 0x03, 0x80, 0x01, 0x02, 0xA1, 0x05, 0x81, 0x03, 'I', 'E', 'D'}, + 12); + PDU(s, 0xA1, 0x13, 0x02, 0x01, invoke_id, 0xA1, 0x0E, 0xA0, 0x09, 0x1A, 0x07, 'L', 'L', 'N', + '0', '$', 'd', 's', 0x81, 0x01, 0x00); + confirmed(s, 0xA1, + (uint8_t[]){0xA0, 0x03, 0x80, 0x01, 0x00, 0xA1, 0x05, 0x81, 0x03, 'X', 'E', 'D'}, + 12); + PDU(s, 0xA2, 0x0A, 0x80, 0x01, invoke_id, 0xA2, 0x05, 0xA0, 0x03, 0x82, 0x01, 0x01); +} + +/* What every report of the unbuffered block starts with: RptID, then OptFlds as reported. */ +#define URCB_ID \ + 0x8A, 0x12, 'I', 'E', 'D', '/', 'L', 'L', 'N', '0', '$', 'R', 'P', '$', 'u', 'r', 'c', \ + 'b', '0', '1' +#define BRCB_ID \ + 0x8A, 0x12, 'I', 'E', 'D', '/', 'L', 'L', 'N', '0', '$', 'B', 'R', '$', 'b', 'r', 'c', \ + 'b', '0', '1' +#define DAT_SET 0x8A, 0x0B, 'I', 'E', 'D', '/', 'L', 'L', 'N', '0', '$', 'd', 's' +/* Reasons for inclusion. */ +#define DCHG 0x84, 0x02, 0x01, 0x40 +#define QCHG 0x84, 0x02, 0x01, 0x20 +#define INTEGRITY 0x84, 0x02, 0x01, 0x08 +#define GI 0x84, 0x02, 0x01, 0x04 +#define UNSIGNED(v) 0x86, 0x01, v + +ZTEST(mms, test_unbuffered_reports) +{ + const int s = associate(peer, 0); + + /* + * Reserve; OptFlds sequence number, time stamp, reason, data set name, + * data reference, and the two a block without a buffer does not report; + * TrgOps all; integrity every second; enable; interrogate. + */ + WRITE_ATTR(s, "LLN0$RP$urcb01$Resv", WRITTEN, B_TRUE); + WRITE_ATTR(s, "LLN0$RP$urcb01$OptFlds", WRITTEN, 0x84, 0x03, 0x06, 0x7F, 0x00); + WRITE_ATTR(s, "LLN0$RP$urcb01$TrgOps", WRITTEN, 0x84, 0x02, 0x02, 0x6C); + WRITE_ATTR(s, "LLN0$RP$urcb01$IntgPd", WRITTEN, 0x86, 0x02, 0x03, 0xE8); + WRITE_ATTR(s, "LLN0$RP$urcb01$RptEna", WRITTEN, B_TRUE); + sends[s] = 0; + WRITE_ATTR(s, "LLN0$RP$urcb01$GI", WRITTEN, B_TRUE); + zassert_equal(sends[s], 2); + /* Every member: SqNum 0, the time 1 s into 1984-01-01, 3 inclusion bits. */ + REPORT(s, 1, URCB_ID, 0x84, 0x03, 0x06, 0x7C, 0x00, UNSIGNED(0), 0x8C, 0x06, 0x00, 0x00, + 0x03, 0xE8, 0x00, 0x00, DAT_SET, 0x84, 0x02, 0x05, 0xE0, 0x8A, 0x17, 'I', 'E', 'D', + '/', 'G', 'G', 'I', 'O', '1', '$', 'S', 'T', '$', 'I', 'n', 'd', '1', '$', 's', 't', + 'V', 'a', 'l', 0x8A, 0x13, 'I', 'E', 'D', '/', 'G', 'G', 'I', 'O', '1', '$', 'S', + 'T', '$', 'I', 'n', 'd', '1', '$', 'q', 0x8A, 0x16, 'I', 'E', 'D', '/', 'M', 'M', + 'X', 'U', '1', '$', 'M', 'X', '$', 'V', 'o', 'l', '$', 'm', 'a', 'g', '$', 'f', + B_FALSE, 0x84, 0x03, 0x03, 0x00, 0x00, 0x87, 0x05, 0x08, 0x00, 0x00, 0x00, 0x00, GI, + GI, GI); + + /* The data references off: shorter reports from here. */ + WRITE_ATTR(s, "LLN0$RP$urcb01$RptEna", WRITTEN, B_FALSE); + WRITE_ATTR(s, "LLN0$RP$urcb01$OptFlds", WRITTEN, 0x84, 0x03, 0x06, 0x78, 0x00); + WRITE_ATTR(s, "LLN0$RP$urcb01$RptEna", WRITTEN, B_TRUE); + sends[s] = 0; + + /* A value changes: that member alone, data change. SqNum starts over. */ + now = 1200; + values[IND].boolean = true; + zelos_mms_core_poke(&mms, now); + zassert_equal(sends[s], 1); + REPORT(s, 0, URCB_ID, 0x84, 0x03, 0x06, 0x78, 0x00, UNSIGNED(0), 0x8C, 0x06, 0x00, 0x00, + 0x04, 0xB0, 0x00, 0x00, DAT_SET, 0x84, 0x02, 0x05, 0x80, B_TRUE, DCHG); + + /* A quality changes: quality change. */ + values[IND_Q].quality = 0xC000; + zelos_mms_core_poke(&mms, now); + REPORT(s, 1, URCB_ID, 0x84, 0x03, 0x06, 0x78, 0x00, UNSIGNED(1), 0x8C, 0x06, 0x00, 0x00, + 0x04, 0xB0, 0x00, 0x00, DAT_SET, 0x84, 0x02, 0x05, 0x40, 0x84, 0x03, 0x03, 0xC0, + 0x00, QCHG); + + /* Integrity: a period after enabling, not before; every member. */ + zassert_equal(zelos_mms_core_tick(&mms, 1999), 2000); + zassert_equal(sends[s], 2); + now = 2000; + zassert_equal(zelos_mms_core_tick(&mms, now), 3000); + REPORT(s, 2, URCB_ID, 0x84, 0x03, 0x06, 0x78, 0x00, UNSIGNED(2), 0x8C, 0x06, 0x00, 0x00, + 0x07, 0xD0, 0x00, 0x00, DAT_SET, 0x84, 0x02, 0x05, 0xE0, B_TRUE, 0x84, 0x03, 0x03, + 0xC0, 0x00, 0x87, 0x05, 0x08, 0x00, 0x00, 0x00, 0x00, INTEGRITY, INTEGRITY, + INTEGRITY); + + /* A trigger that is off reports nothing: quality change without its bit. */ + WRITE_ATTR(s, "LLN0$RP$urcb01$RptEna", WRITTEN, B_FALSE); + WRITE_ATTR(s, "LLN0$RP$urcb01$TrgOps", WRITTEN, 0x84, 0x02, 0x02, 0x40); + /* BufTm 100: changes within it go in one report, stamped with the first. */ + WRITE_ATTR(s, "LLN0$RP$urcb01$BufTm", WRITTEN, 0x86, 0x01, 0x64); + WRITE_ATTR(s, "LLN0$RP$urcb01$RptEna", WRITTEN, B_TRUE); + sends[s] = 0; + values[IND_Q].quality = 0; + values[IND].boolean = false; + zassert_equal(zelos_mms_core_poke(&mms, now), 2100); + now = 2050; + values[VOL].f32 = 1.0f; + zelos_mms_core_poke(&mms, now); + zelos_mms_core_tick(&mms, 2099); + zassert_equal(sends[s], 0); + now = 2100; + zelos_mms_core_tick(&mms, now); + zassert_equal(sends[s], 1); + REPORT(s, 0, URCB_ID, 0x84, 0x03, 0x06, 0x78, 0x00, UNSIGNED(0), 0x8C, 0x06, 0x00, 0x00, + 0x07, 0xD0, 0x00, 0x00, DAT_SET, 0x84, 0x02, 0x05, 0xA0, B_FALSE, 0x87, 0x05, 0x08, + 0x3F, 0x80, 0x00, 0x00, DCHG, DCHG); + /* A member changing again within BufTm: the report waiting goes at once. */ + values[VOL].f32 = 2.0f; + zelos_mms_core_poke(&mms, now); + values[VOL].f32 = 3.0f; + zelos_mms_core_poke(&mms, now); + zassert_equal(sends[s], 2); +} + +/* OptFlds as the buffered block reports them here: sequence number, BufOvfl, EntryID. */ +#define BRCB_HEAD(sq) BRCB_ID, 0x84, 0x03, 0x06, 0x43, 0x00, UNSIGNED(sq) +#define ENTRY_ID(n) 0x89, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, n +#define EVERY 0x84, 0x02, 0x05, 0xE0 +#define FIRST_ONLY 0x84, 0x02, 0x05, 0x80 +#define BRCB_ITEM "LLN0$BR$brcb01$" + +ZTEST(mms, test_buffered_resume) +{ + int a = associate(peer, 0); + int b; + + WRITE_ATTR(a, BRCB_ITEM "ResvTms", WRITTEN, 0x85, 0x01, 0x05); + WRITE_ATTR(a, BRCB_ITEM "OptFlds", WRITTEN, 0x84, 0x03, 0x06, 0x43, 0x00); + WRITE_ATTR(a, BRCB_ITEM "RptEna", WRITTEN, B_TRUE); + WRITE_ATTR(a, BRCB_ITEM "GI", WRITTEN, B_TRUE); + sends[a] = 0; + /* Entry 2 (the interrogation took EntryID 1): received. */ + values[IND].boolean = true; + zelos_mms_core_poke(&mms, now); + REPORT(a, 0, BRCB_HEAD(1), B_FALSE, ENTRY_ID(2), FIRST_ONLY, B_TRUE); + + /* The link drops; entries 3 and 4 are made with no client. */ + zelos_mms_core_close(&mms, a, now); + zassert_true(closed[a]); + values[IND].boolean = false; + zelos_mms_core_poke(&mms, now); + values[IND].boolean = true; + zelos_mms_core_poke(&mms, now); + + /* Reserved 5 s for its owner's address: another address is refused meanwhile. */ + b = associate(other, 0); + WRITE_ATTR(b, BRCB_ITEM "RptEna", TEMPORARILY_UNAVAILABLE, B_TRUE); + a = associate(peer, 0); + /* Owner, as the client reads it. */ + read_item(a, BRCB_ITEM "Owner"); + RESULTS(a, 0xA4, 0x89, 0x04, 10, 0, 0, 1); + /* An EntryID never given is refused on that attribute, and changes nothing. */ + WRITE_ATTR(a, BRCB_ITEM "EntryID", VALUE_INVALID, ENTRY_ID(9)); + /* The last one received: exactly what was missed follows, in order, then the interrogation. + */ + WRITE_ATTR(a, BRCB_ITEM "EntryID", WRITTEN, ENTRY_ID(2)); + sends[a] = 0; + WRITE_ATTR(a, BRCB_ITEM "RptEna", WRITTEN, B_TRUE); + WRITE_ATTR(a, BRCB_ITEM "GI", WRITTEN, B_TRUE); + zassert_equal(sends[a], 5, "two responses, three reports"); + REPORT(a, 1, BRCB_HEAD(0), B_FALSE, ENTRY_ID(3), FIRST_ONLY, B_FALSE); + REPORT(a, 2, BRCB_HEAD(1), B_FALSE, ENTRY_ID(4), FIRST_ONLY, B_TRUE); + REPORT(a, 4, BRCB_HEAD(2), B_FALSE, ENTRY_ID(5), EVERY, B_TRUE, 0x84, 0x03, 0x03, 0x00, + 0x00, 0x87, 0x05, 0x08, 0x00, 0x00, 0x00, 0x00); + /* The interrogation's own EntryID resumes too: nothing was missed after it. */ + WRITE_ATTR(a, BRCB_ITEM "RptEna", WRITTEN, B_FALSE); + WRITE_ATTR(a, BRCB_ITEM "EntryID", WRITTEN, ENTRY_ID(5)); + WRITE_ATTR(a, BRCB_ITEM "RptEna", WRITTEN, B_TRUE); + sends[a] = 0; + zelos_mms_core_tick(&mms, now); + zassert_equal(sends[a], 0); + + /* Writing a setting its own value keeps the buffer; a new value purges it. */ + WRITE_ATTR(a, BRCB_ITEM "RptEna", WRITTEN, B_FALSE); + WRITE_ATTR(a, BRCB_ITEM "TrgOps", WRITTEN, 0x84, 0x02, 0x02, 0x64); + WRITE_ATTR(a, BRCB_ITEM "EntryID", WRITTEN, ENTRY_ID(2)); + WRITE_ATTR(a, BRCB_ITEM "IntgPd", WRITTEN, 0x86, 0x02, 0x03, 0xE8); + WRITE_ATTR(a, BRCB_ITEM "EntryID", VALUE_INVALID, ENTRY_ID(2)); + WRITE_ATTR(a, BRCB_ITEM "IntgPd", WRITTEN, 0x86, 0x01, 0x00); + + /* More changes than the ring holds while disabled: the oldest go, BufOvfl says so once. */ + for (int i = 0; i < ZELOS_MMS_ENTRIES + 2; i++) { + values[IND].boolean = !values[IND].boolean; + zelos_mms_core_poke(&mms, now); + } + sends[a] = 0; + WRITE_ATTR(a, BRCB_ITEM "RptEna", WRITTEN, B_TRUE); + /* ZELOS_MMS_BURST entries at a time: after the response, then per tick. */ + zassert_equal(sends[a], 1 + ZELOS_MMS_BURST); + REPORT(a, 1, BRCB_HEAD(0), B_TRUE, ENTRY_ID(8), FIRST_ONLY, B_FALSE); + REPORT(a, 2, BRCB_HEAD(1), B_FALSE, ENTRY_ID(9), FIRST_ONLY, B_TRUE); + sends[a] = 0; + zassert_equal(zelos_mms_core_tick(&mms, now), now, "more to send: again at once"); + zassert_equal(sends[a], ZELOS_MMS_BURST); + while (zelos_mms_core_tick(&mms, now) == now) { + } + zassert_equal(sends[a], ZELOS_MMS_ENTRIES - ZELOS_MMS_BURST); + + /* Its client gone for good: free for anyone once ResvTms has passed. */ + WRITE_ATTR(a, BRCB_ITEM "ResvTms", TEMPORARILY_UNAVAILABLE, 0x85, 0x01, 0x05); + WRITE_ATTR(a, BRCB_ITEM "RptEna", WRITTEN, B_FALSE); + WRITE_ATTR(a, BRCB_ITEM "ResvTms", WRITTEN, 0x85, 0x01, 0x05); + zelos_mms_core_close(&mms, a, now); + zassert_equal(zelos_mms_core_tick(&mms, now), now + 5000); + now += 4999; + zelos_mms_core_tick(&mms, now); + WRITE_ATTR(b, BRCB_ITEM "ResvTms", TEMPORARILY_UNAVAILABLE, 0x85, 0x01, 0x05); + now += 1; + zelos_mms_core_tick(&mms, now); + WRITE_ATTR(b, BRCB_ITEM "ResvTms", WRITTEN, 0x85, 0x01, 0x05); +} + +ZTEST(mms, test_refusals) +{ + const int a = associate(peer, 0); + const int b = associate(other, 0); + const int c = zelos_mms_core_accept(&mms, other, sizeof(other), now); + + /* A third client: transport connected, then the session refused (congestion), closed. */ + sends[c] = 0; + closed[c] = false; + zelos_mms_core_receive(&mms, c, cr, sizeof(cr), now); + zelos_mms_core_receive(&mms, c, association, sizeof(association), now); + zassert_equal(sent_len[c][1], 5); + zassert_mem_equal(sent[c][1], ((uint8_t[]){0x0C, 0x03, 0x32, 0x01, 0x83}), 5); + zassert_true(closed[c]); + zassert_equal(zelos_mms_core_clients(&mms), 2); + + /* A block another client reserved or enabled: temporarily-unavailable, then free. */ + WRITE_ATTR(a, "LLN0$RP$urcb01$Resv", WRITTEN, B_TRUE); + WRITE_ATTR(b, "LLN0$RP$urcb01$Resv", TEMPORARILY_UNAVAILABLE, B_TRUE); + WRITE_ATTR(b, "LLN0$RP$urcb01$RptEna", TEMPORARILY_UNAVAILABLE, B_TRUE); + WRITE_ATTR(a, "LLN0$RP$urcb01$RptEna", WRITTEN, B_TRUE); + /* Enabled: its settings are refused to its own client too; some are never written. */ + WRITE_ATTR(a, "LLN0$RP$urcb01$IntgPd", TEMPORARILY_UNAVAILABLE, 0x86, 0x01, 0x64); + WRITE_ATTR(a, "LLN0$RP$urcb01$SqNum", ACCESS_DENIED, 0x86, 0x01, 0x01); + zelos_mms_core_close(&mms, a, now); + WRITE_ATTR(b, "LLN0$RP$urcb01$RptEna", WRITTEN, B_TRUE); + + /* Only block attributes are written: a value is denied, a name unknown does not exist. */ + WRITE_ATTR(b, "GGIO1$ST$Ind1$stVal", ACCESS_DENIED, B_TRUE); + WRITE_ATTR(b, "GGIO1$ST$Ind1", ACCESS_DENIED, B_TRUE); + WRITE_ATTR(b, "GGIO1$ST$Nope", NON_EXISTENT, B_TRUE); + WRITE_ATTR(b, "LLN0$RP$urcb01$RptEna", 7, 0x86, 0x01, 0x01); + + /* identify and status answer. */ + REQUEST(b, 0xA0, 0x05, 0x02, 0x01, 0x07, 0x82, 0x00); + PDU(b, 0xA1, 0x0E, 0x02, 0x01, 0x07, 0xA2, 0x09, 0x80, 0x01, 'V', 0x81, 0x01, 'M', 0x82, 0x01, + '1'); + REQUEST(b, 0xA0, 0x06, 0x02, 0x01, 0x07, 0x80, 0x01, 0x00); + PDU(b, 0xA1, 0x0B, 0x02, 0x01, 0x07, 0xA0, 0x06, 0x80, 0x01, 0x00, 0x81, 0x01, 0x00); + /* Any other confirmed service (deleteNamedVariableList): rejected. A cancel too. */ + REQUEST(b, 0xA0, 0x05, 0x02, 0x01, 0x07, 0xAD, 0x00); + PDU(b, 0xA4, 0x06, 0x80, 0x01, 0x07, 0x81, 0x01, 0x01); + REQUEST(b, 0x85, 0x01, 0x07); + PDU(b, 0xA4, 0x06, 0x80, 0x01, 0x07, 0x87, 0x01, 0x01); +} + +ZTEST(mms, test_any_split_and_bad_input) +{ + /* A connection request for TPDUs of 128, no TSAPs. */ + static const uint8_t small_cr[] = {0x03, 0x00, 0x00, 0x0E, 0x09, 0xE0, 0x00, + 0x00, 0x00, 0x07, 0x00, 0xC0, 0x01, 0x07}; + const int a = associate(peer, 0); + int b = zelos_mms_core_accept(&mms, other, sizeof(other), now); + int c; + uint8_t whole[ZELOS_MMS_FRAME_MAX]; + size_t whole_len; + + /* The logical node LLN0 with both blocks: one data TPDU at 1024. */ + read_item(a, "LLN0"); + whole_len = sent_len[a][sends[a] - 1]; + memcpy(whole, sent[a][sends[a] - 1], whole_len); + zassert_true(whole_len > 128); + zassert_equal(tpkts[a], 3, "confirm, accept, one response"); + + /* + * A client at 128, every byte on its own: its association in three + * data TPDUs, the same request, the same answer in TPDUs of at most 128. + */ + sends[b] = 0; + tpkts[b] = 0; + closed[b] = false; + feed_step = 1; + zelos_mms_core_receive(&mms, b, small_cr, sizeof(small_cr), now); + zassert_mem_equal(sent[b][0], + ((uint8_t[]){0x03, 0x00, 0x00, 0x0E, 0x09, 0xD0, 0x00, 0x07, 0x00, + (uint8_t)(b + 1), 0x00, 0xC0, 0x01, 0x07}), + 14); + tsdu(b, &association[7], sizeof(association) - 7, 80); + zassert_equal(mms.conn[b].state, ZELOS_MMS_ASSOCIATED); + zassert_equal(sent_len[b][1], 131); + zassert_equal(tpkts[b], 3, "confirm, accept in two"); + invoke_id = 0; + tpkts[b] = 0; + read_item(b, "LLN0"); + zassert_equal(sent_len[b][2], whole_len); + zassert_mem_equal(sent[b][2], whole, whole_len); + zassert_equal((size_t)tpkts[b], (whole_len + 124) / 125); + feed_step = SIZE_MAX; + + /* A length that passes the end of its PDU: that connection closes, the other serves. */ + REQUEST(b, 0xA0, 0x10, 0x02, 0x01, 0x01, 0xA4, 0x7F); + zassert_true(closed[b]); + zassert_false(closed[a]); + /* Not a TPKT at all. */ + b = zelos_mms_core_accept(&mms, other, sizeof(other), now); + closed[b] = false; + zelos_mms_core_receive(&mms, b, (const uint8_t *)"GET / HTTP/1.1\r\n", 16, now); + zassert_true(closed[b]); + /* A session message larger than any taken: closed before it is stored. */ + b = associate(other, 0); + zelos_mms_core_receive(&mms, b, (uint8_t[]){0x03, 0x00, 0x10, 0x00, 0x02, 0xF0, 0x80}, 7, + now); + zassert_true(closed[b]); + read_item(a, "GGIO1$ST$Ind1$stVal"); + RESULTS(a, 0xA4, B_FALSE); + + /* Three sockets, no fourth. One that does not associate within 5 s is closed. */ + b = zelos_mms_core_accept(&mms, other, sizeof(other), now); + c = zelos_mms_core_accept(&mms, other, sizeof(other), now); + zassert_equal(zelos_mms_core_accept(&mms, other, sizeof(other), now), -1); + closed[b] = false; + zelos_mms_core_receive(&mms, b, cr, sizeof(cr), now); + zassert_equal(zelos_mms_core_tick(&mms, now + 4999), now + 5000); + zassert_false(closed[b]); + zelos_mms_core_tick(&mms, now + 5000); + zassert_true(closed[b] && closed[c]); + zassert_false(closed[a]); +} + +ZTEST(mms, test_scan_period) +{ + struct zelos_mms_model scanned = model; + int s; + + /* Without a poke the values are read every scan_ms, the first tick at once. */ + scanned.scan_ms = 100; + zassert_ok(zelos_mms_core_init(&mms, &scanned, 0, &ops, NULL)); + s = associate(peer, 0); + WRITE_ATTR(s, "LLN0$RP$urcb01$RptEna", WRITTEN, B_TRUE); + zassert_equal(zelos_mms_core_tick(&mms, now), now + 100); + sends[s] = 0; + values[VOL].f32 = 5.0f; + zelos_mms_core_tick(&mms, now + 99); + zassert_equal(sends[s], 0); + zelos_mms_core_tick(&mms, now + 100); + zassert_equal(sends[s], 1); +} + +ZTEST(mms, test_model_is_checked) +{ + /* Leaves of one logical node apart: not depth first. */ + static const struct zelos_mms_leaf apart[] = { + {"GGIO1", "ST", "Ind1$stVal", ZELOS_MMS_BOOLEAN, IND}, + {"LLN0", "ST", "Beh$stVal", ZELOS_MMS_ENUM, BEH}, + {"GGIO1", "ST", "Ind2$stVal", ZELOS_MMS_BOOLEAN, IND}, + }; + struct zelos_mms_model bad = model; + + bad.leaves = apart; + bad.leaf_count = ARRAY_SIZE(apart); + bad.data_set_count = 0; + bad.rcb_count = 0; + zassert_equal(zelos_mms_core_init(&mms, &bad, 0, &ops, NULL), -EINVAL); + /* A value index past the values. */ + bad = model; + bad.value_count = VOL; + zassert_equal(zelos_mms_core_init(&mms, &bad, 0, &ops, NULL), -EINVAL); +} + +ZTEST_SUITE(mms, NULL, NULL, before, NULL, NULL); diff --git a/tests/lib/mms/testcase.yaml b/tests/lib/mms/testcase.yaml new file mode 100644 index 0000000..bebcba8 --- /dev/null +++ b/tests/lib/mms/testcase.yaml @@ -0,0 +1,5 @@ +tests: + zelos.lib.mms: + platform_allow: native_sim/native/64 + integration_platforms: + - native_sim/native/64 From d35bb074c5d4dd4703292592c82e9d9046e592f1 Mon Sep 17 00:00:00 2001 From: tkeairns Date: Mon, 30 Nov 2026 21:30:58 -0800 Subject: [PATCH 2/2] goose suite: joins its multicast addresses; simulation off after a failure A network card drops multicast nobody asked it for: on hardware the suite saw gcb_pdu and not gcb_dcdc. A test that failed with simulation on left it on until a reset. --- testing/suites/goose/test_publisher.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/testing/suites/goose/test_publisher.py b/testing/suites/goose/test_publisher.py index 87a1c32..19dfbb0 100644 --- a/testing/suites/goose/test_publisher.py +++ b/testing/suites/goose/test_publisher.py @@ -42,6 +42,8 @@ ROUTINE, SIMULATION, CONF_REV = 0x6185, 0x01, 0x03 # Linux's, which Python's socket module does not export: a struct timespec per frame. SO_TIMESTAMPNS = 35 +# Linux's packet(7): join a multicast address on one interface, as a subscriber does. +SOL_PACKET, PACKET_ADD_MEMBERSHIP, PACKET_MR_MULTICAST = 263, 1, 0 def tlv(b: bytes, i: int) -> tuple[int, int, int]: @@ -86,6 +88,10 @@ def goose_socket(iface: str) -> Iterator[socket.socket]: pytest.skip("capturing needs CAP_NET_RAW") with s: s.bind((iface, ETHERTYPE)) + # A network card drops multicast nobody asked it for. + for dst in DST.values(): + mreq = struct.pack("iHH8s", socket.if_nametoindex(iface), PACKET_MR_MULTICAST, len(dst), dst) + s.setsockopt(SOL_PACKET, PACKET_ADD_MEMBERSHIP, mreq) s.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1) s.settimeout(1.0) yield s @@ -171,6 +177,9 @@ def knob(option: int) -> bytes: read_until(s, got, lambda g, n=n, want=want: {p["appid"] for _, p in g[n:] if p["simulation"] == want} == set(CBS), 2.0) finally: with contextlib.suppress(Exception): + # Left on by a failure above: any other option only reads the knobs. + if knob(0x00)[:1] == b"\x01": + knob(SIMULATION) ecu.client.change_session(DEFAULT) old = pdu(rev - 1)[-1][1]