From c88de31a0aa2229c7155ff453a9e9ef847ad3ff6 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 16 Oct 2026 23:11:24 +0200 Subject: [PATCH] sms: the short message codecs of TS 23.038, 23.040 and 24.011, and EF_SMSP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SMS over IP (TS 24.341) carries the bytes a 2G/3G phone puts in an RP-DATA inside a SIP MESSAGE body of type application/vnd.3gpp.sms, so imsd needs the whole stack below SIP once it owns SMS on a carrier whose modem IMS is off: the GSM 7-bit default alphabet with its extension table and the septet packing, UCS-2 for everything else (TS 23.038); SMS-SUBMIT built per segment with the concatenation header, SMS-DELIVER, SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed, the SMS-DELIVER-REPORT that acknowledges a delivery, the user-data header and the reassembly of a concatenated message (TS 23.040); RP-DATA, RP-ACK and RP-ERROR in both directions with their causes (TS 24.011); and EF_SMSP, where the (U)SIM names the service centre the RP-DATA is addressed to (TS 31.102 4.2.27, the KPN SIM's record read on the dev phone on 2026-10-16: +31653131313). A new partition, Imsd:Sms, pure std with no SIP, clock or I/O; tests/Sms checks it against the classic public PDU vectors ("hellohello", the "How are you?" SMS-DELIVER) and vectors cross-generated by an independent Python reference. A concatenated set with one alphabet throughout is decoded from its segments' joined units — the septets, or the UTF-16BE octets — not from the segments' texts, so a surrogate pair or an escape pair a sender cut at a segment boundary comes out whole; a U+0000 in UCS-2 decodes as U+FFFD, since no text means it and a D-Bus string cannot carry it. A status report's TP-ST is read as TS 23.040 9.2.3.15 has the MS read it: a reserved value, any with bit 7 set among them, as "Service Rejected" — a temporary error after which the SC is not making any more transfer attempts (StatusAsRead, pinned over all 256 values; StatusText has the clause's four classes in words). Three more readings follow their clauses the same way, each pinned: a time stamp semi-octet that is no digit reads as 0 (9.2.3.11); `1111` before an address's last semi-octet is skipped, not taken for its end (9.1.2.3); an SMS-SUBMIT-REPORT for RP-ERROR with an unused bit of its first octet set gives TP-FCS 0xFF, unspecified, with nothing else examined (9.2.2.2a). --- AGENTS.md | 35 +- interfaces/Imsd-Sms.cppm | 1072 ++++++++++++++++++++++++++++++++++++++ interfaces/Imsd.cppm | 1 + project.cpp | 6 +- tests/Sms/main.cpp | 369 +++++++++++++ 5 files changed, 1474 insertions(+), 9 deletions(-) create mode 100644 interfaces/Imsd-Sms.cppm create mode 100644 tests/Sms/main.cpp diff --git a/AGENTS.md b/AGENTS.md index a01b265..1675cf0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,10 +37,11 @@ PipeWire. The verified device/carrier combinations are in the README. | Path | What it is | |---|---| | `project.cpp` | The canonical build description, for [Crafter Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build). Chooses the product by `--product=`. | -| `interfaces/Imsd.cppm` | The primary module interface of `imsd-core`: `export import`s the eight partitions below. | +| `interfaces/Imsd.cppm` | The primary module interface of `imsd-core`: `export import`s the nine partitions below. | | `interfaces/Imsd-Util.cppm` | `imsd::util` — SIP tokens, IPv6 host/port formatting, the RFC 5952 §4 IPv6 text (`CanonicalIp6`/`CanonicalAddr`; an IPv4-mapped address spelled in hex stays hex, where §5 and `inet_ntop` write it dotted) and the comma-separated address-list parser (`ParseAddressList`), hex/base64, MD5 (RFC 1321), the fixed protected ports `PortUc`/`PortUs` (45061/45062). | | `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction, status codes, the granted lifetime, `ResponseOf` transaction matching. Not a full RFC 3261 parser, deliberately. | | `interfaces/Imsd-Sdp.cppm` | `imsd::sdp` — SDP offer/answer: the AMR-WB + AMR + telephone-event offer (optional IR.92 preconditions; `OfferedTelephoneEventPt` names its telephone-event numbers), the parser the media plane needs (the codec, its payload type and mode, and the telephone-event payload type the m-line lists at that codec's clock), `BuildAnswer` for the terminating side, the `CODECS` override. | +| `interfaces/Imsd-Sms.cppm` | `imsd::sms` — the short message codecs SMS over IP rides on (TS 24.341 carries the bytes a 2G/3G phone puts in an RP-DATA, in a SIP MESSAGE body): the GSM 7-bit default alphabet with its extension table and the septet packing, UCS-2 (TS 23.038); the SM-TL PDUs (TS 23.040: SMS-SUBMIT built, one per segment with the concatenation header when the text needs more than one; SMS-DELIVER, SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed; the SMS-DELIVER-REPORT that acknowledges a delivery; the user-data header — concatenation, application ports — and the `Reassembler` of a concatenated message); the SM-RL messages (TS 24.011: RP-DATA, RP-ACK, RP-ERROR in both directions, the cause values); EF_SMSP (TS 31.102 §4.2.27), where the (U)SIM names the service centre, and qmicli's hex dump of it. Byte-level only: no SIP, no clock, no I/O. | | `interfaces/Imsd-Aka.cppm` | `imsd::aka` — USIM AKA glue: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response. | | `interfaces/Imsd-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the Security-Server mechanism selection, and the reader that reconstructs SPIs/ports from `ip xfrm state`/`policy` text for a warm resume, and (1.0.0) `SaPeer`, the P-CSCF the kernel's pair is to, read from the `dir out` policies that carry imsd's fingerprint, `OwnXfrmDeleteCommands`, the deletes by exact key of what two rules select — the policies carrying imsd's fingerprint and the reqid-1/2 transport-mode ESP states in their direction or on the UE's ims-PDN address, whoever installed them (§12), and `FileNamesAnotherPair`, whether a state file's `spi_uc`/`spi_us` name the kernel's pair (unknown on either side decides nothing). | | `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; byte-pinned by `tests/Messages`. Also `IsEmergency`. | @@ -52,7 +53,7 @@ PipeWire. The verified device/carrier combinations are in the README. | `implementations/pcscf.cpp` | `imsd-pcscf`, the P-CSCF reader: the AF_QIPCRTR socket, the WDS service lookup and the Bind Mux Data Port / Set IP Family / Get Current Settings sequence around `Imsd:Qmi` (plus Get Profile Settings with `--profile`, Get Packet Service Status with `-v`). std + POSIX + the Linux QRTR UAPI (``), no GLib; never Start/Stop Network. | | `implementations/dialerd.cpp` | `imsd-dialerd`, the Plasma Mobile session-bus backend (`org.kde.telephony.*`). | | `implementations/ofonod.cpp` | `imsd-ofonod`, the GNOME Calls system-bus backend (`org.ofono`). | -| `tests//main.cpp` | The eight unit-test suites: `Util`, `Aka`, `Ipsec`, `Qmi`, `Messages`, `Engine`, `Sip`, `Sdp`. | +| `tests//main.cpp` | The nine unit-test suites: `Util`, `Aka`, `Ipsec`, `Qmi`, `Messages`, `Engine`, `Sip`, `Sdp`, `Sms`. | | `packaging/` | systemd units, the bring-up and upgrade scripts, D-Bus and polkit policies, presets, the gschema override, `APKBUILD.binary` and the CI helpers (§9). | | `.forgejo/workflows/package.yml` | CI: builds the aarch64 apks on every push to `main` and publishes them to the Forgejo Alpine registry (§9.4). | | `bin/`, `build/` | crafter-build's outputs and intermediates. Ignored. | @@ -68,7 +69,7 @@ in every source but the re-exporting `Imsd.cppm`, clang + libc++ + lld. | Product | Kind | Built from | Links | Notes | |---|---|---|---|---| -| `imsd-core` | static library | the `Imsd` module and its eight partitions | — | Pure `import std` C++, no GLib, no I/O side effects: every message, digest, SA command and call-state decision is here and unit-testable on any dev box without a bus, a modem or a phone. | +| `imsd-core` | static library | the `Imsd` module and its nine partitions | — | Pure `import std` C++, no GLib, no I/O side effects: every message, digest, SA command and call-state decision is here and unit-testable on any dev box without a bus, a modem or a phone. | | `imsd` | executable | `implementations/main.cpp` | `imsd-core`, `imsd-bus`, gio-2.0, pthread | The daemon. Default product. | | `imsd-bus` | static library | `interfaces/ImsdBus.cppm` | gio-2.0 | The polkit gate (`net.catcrafts.IMS1.Voice`) imsd and imsd-ofonod both link. A translation daemon that runs as root on the system bus reaches imsd as root, which polkit always allows, so it gates its own callers through this or it is a bypass. | | `imsd-media` | executable | `implementations/media.cpp` | `-ldl -lpthread` | The RTP/AMR data plane, spawned once per call. No GLib, no core. A separate process for crash isolation and for the far-end-hangup exit-code contract (§7.6). `-- --product=media`. | @@ -165,7 +166,7 @@ crafter-build -- --product=media # bin/imsd-media-…/imsd-media crafter-build -- --product=dialerd # bin/imsd-dialerd-…/imsd-dialerd crafter-build -- --product=ofonod # bin/imsd-ofonod-…/imsd-ofonod crafter-build -- --product=pcscf # bin/imsd-pcscf-…/imsd-pcscf -crafter-build test # the eight unit-test suites +crafter-build test # the nine unit-test suites crafter-build lint # the house-style rules (§4.2, §6) ``` @@ -237,11 +238,11 @@ releases. This is the flow CI runs (§9.4). ## 5. Tests -`crafter-build test` runs the eight suites. Each suite +`crafter-build test` runs the nine suites. Each suite is a plain `main()` with a `Check(bool, message)` counter: failures print `FAIL: …`, success prints `: all tests passed`, and the exit status is the failure count for seven suites — non-zero short of a multiple of 256 — and -1 for `Engine`. `crafter-build test` ending in `8 passed`, on every +1 for `Engine` and `Sms`. `crafter-build test` ending in `9 passed`, on every commit of a range (§11), is the project's definition of green. What the suites pin: @@ -285,6 +286,26 @@ What the suites pin: - `Sdp` — the offer's exact bytes, the parser (the telephone-event payload type at the chosen codec's clock among it), `BuildAnswer` at the offer's own payload types and octet-align mode, the `CODECS` override. +- `Sms` — the short message codecs byte for byte: the GSM 7-bit alphabet, + its extension table and the septet packing (the classic "hellohello" + vector), UCS-2 with surrogate pairs (and U+0000 as U+FFFD), the address fields (international, + a short code, `*`/`#`, an alphanumeric sender), SMS-SUBMIT (the classic + tutorial PDU, UCS-2, the concatenated pair for a 161-character text, an + escape pair and a surrogate pair kept whole at a segment boundary, the + 160/70-character fits), SMS-DELIVER (the classic "How are you?" PDU; a + header with fill bits, a 16-bit concatenation reference, class 0, + port-addressed 8-bit data, a negative time zone — the vectors + cross-generated by the fp6 journal's Python reference, + `utilities/smsref.py` — and short user data, the 'Test' vector with its + TP-UDL raised by hand), the DCS groups, SMS-STATUS-REPORT (its TP-ST as + TS 23.040 9.2.3.15 has the MS read it: every reserved value, bit 7 set + among them, as "Service Rejected") and + SMS-SUBMIT-REPORT, RP-DATA / RP-ACK / RP-ERROR both ways (a type read + against its direction refused), EF_SMSP on the KPN SIM's record (dev + phone, 2026-10-16) straight from qmicli's dump, and the `Reassembler` + (segments out of order, a lone message, a set dropped by `Purge`, a + surrogate pair and an escape pair split across two segments whole + again). - `Engine` — the call state machine driven through recorded network dialogs (reliable 18x/PRACK, 2xx ACK + media start, far-end hangup, CANCEL/answer races, busy/error finals, the terminating side's 100/180/200/486/487/488, @@ -1574,7 +1595,7 @@ only the imsd side of its bus choice. not override the identity from the environment. - **One change, one commit; a fix goes into the commit that introduced the problem** while a range is unpublished (rebase), never as a follow-up on - top. Every commit of a range builds and passes the eight suites on its own. + top. Every commit of a range builds and passes the nine suites on its own. - **Keep `make-bin-tarball.sh`'s file list and `APKBUILD.binary`'s `package()` in sync** when a packaged file is added. - **The README and this file follow the code in the same commit.** A new diff --git a/interfaces/Imsd-Sms.cppm b/interfaces/Imsd-Sms.cppm new file mode 100644 index 0000000..9fceaab --- /dev/null +++ b/interfaces/Imsd-Sms.cppm @@ -0,0 +1,1072 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file fixed-width-types +/* +Imsd:Sms — the short message codecs SMS over IP rides on (TS 24.341 carries +the same bytes a 2G/3G phone puts in an RP-DATA, inside a SIP MESSAGE body of +type application/vnd.3gpp.sms): + +- TS 23.038: the GSM 7-bit default alphabet with its extension table, the + septet packing, and UCS-2 (UTF-16BE on the wire) for everything else; +- TS 23.040: the SM-TL PDUs — SMS-SUBMIT built (one per segment, with the + concatenation header when the text needs more than one), SMS-DELIVER, + SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed, the SMS-DELIVER-REPORT + that acknowledges a delivery, the user-data header (concatenation, the + application ports) and the reassembly of a concatenated message; +- TS 24.011: the SM-RL messages — RP-DATA, RP-ACK, RP-ERROR — in both + directions, and their cause values; +- TS 31.102 §4.2.27: EF_SMSP, where the (U)SIM names the service centre the + RP-DATA is addressed to. + +Byte-level only: no SIP, no clock, no I/O. tests/Sms checks it +against the classic public PDU vectors ("hellohello", the "How are you?" +SMS-DELIVER) and vectors cross-generated by an independent reference. +*/ + +export module Imsd:Sms; +import std; + +namespace imsd::sms { + + using Bytes = std::vector; + + // TS 23.038 6.2.1, the GSM 7-bit default alphabet; 0x1B is the escape + // to the extension table (its own entry is a placeholder — the ESC + // character itself is not encodable). + constexpr std::array Gsm7Table = { + u'@', u'£', u'$', u'¥', u'è', u'é', u'ù', u'ì', u'ò', u'Ç', u'\n', u'Ø', u'ø', u'\r', u'Å', u'å', + u'Δ', u'_', u'Φ', u'Γ', u'Λ', u'Ω', u'Π', u'Ψ', u'Σ', u'Θ', u'Ξ', u'\u001B', u'Æ', u'æ', u'ß', u'É', + u' ', u'!', u'"', u'#', u'¤', u'%', u'&', u'\'', u'(', u')', u'*', u'+', u',', u'-', u'.', u'/', + u'0', u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8', u'9', u':', u';', u'<', u'=', u'>', u'?', + u'¡', u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'H', u'I', u'J', u'K', u'L', u'M', u'N', u'O', + u'P', u'Q', u'R', u'S', u'T', u'U', u'V', u'W', u'X', u'Y', u'Z', u'Ä', u'Ö', u'Ñ', u'Ü', u'§', + u'¿', u'a', u'b', u'c', u'd', u'e', u'f', u'g', u'h', u'i', u'j', u'k', u'l', u'm', u'n', u'o', + u'p', u'q', u'r', u's', u't', u'u', u'v', u'w', u'x', u'y', u'z', u'ä', u'ö', u'ñ', u'ü', u'à', + }; + constexpr std::uint8_t Gsm7Escape = 0x1B; + + // TS 23.038 6.2.1.1, the extension table: pairs. + constexpr std::array, 10> Gsm7Ext = {{ + {0x0A, u'\u000C'}, {0x14, u'^'}, {0x28, u'{'}, {0x29, u'}'}, {0x2F, u'\\'}, + {0x3C, u'['}, {0x3D, u'~'}, {0x3E, u']'}, {0x40, u'|'}, {0x65, u'€'}, + }}; + + // UTF-8 → code points; a byte that starts no sequence, or starts one cut + // short or with a byte that does not continue it, yields U+FFFD and is + // passed over alone. The value is not checked: an overlong form, a + // surrogate or one past U+10FFFF is taken as it is. + std::vector Utf8Decode(std::string_view s) { + std::vector out; + std::size_t i = 0; + while (i < s.size()) { + const std::uint8_t b = static_cast(s[i]); + std::size_t n = 0; + char32_t cp = 0; + if (b < 0x80) { cp = b; n = 1; } + else if ((b & 0xE0) == 0xC0) { cp = b & 0x1F; n = 2; } + else if ((b & 0xF0) == 0xE0) { cp = b & 0x0F; n = 3; } + else if ((b & 0xF8) == 0xF0) { cp = b & 0x07; n = 4; } + else { out.push_back(0xFFFD); i++; continue; } + if (i + n > s.size()) { out.push_back(0xFFFD); i++; continue; } + bool ok = true; + for (std::size_t k = 1; k < n; k++) { + const std::uint8_t c = static_cast(s[i + k]); + if ((c & 0xC0) != 0x80) { ok = false; break; } + cp = (cp << 6) | (c & 0x3F); + } + if (!ok) { out.push_back(0xFFFD); i++; continue; } + out.push_back(cp); + i += n; + } + return out; + } + + void Utf8Append(std::string& s, char32_t cp) { + if (cp < 0x80) { s.push_back(static_cast(cp)); return; } + if (cp < 0x800) { + s.push_back(static_cast(0xC0 | (cp >> 6))); + s.push_back(static_cast(0x80 | (cp & 0x3F))); + return; + } + if (cp < 0x10000) { + s.push_back(static_cast(0xE0 | (cp >> 12))); + s.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + s.push_back(static_cast(0x80 | (cp & 0x3F))); + return; + } + s.push_back(static_cast(0xF0 | (cp >> 18))); + s.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + s.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + s.push_back(static_cast(0x80 | (cp & 0x3F))); + } + + // Called Party BCD digits (TS 24.008 10.5.4.7): 0-9, then * # a b c as + // 0xA..0xE; 0xF ends an odd-length value. + constexpr std::string_view BcdDigits = "0123456789*#abc"; + + std::optional BcdOf(char c) { + const std::size_t i = BcdDigits.find(c); + if (i == std::string_view::npos) return std::nullopt; + return static_cast(i); + } + + std::uint8_t Byte(std::span b, std::size_t i) { return i < b.size() ? b[i] : 0; } +} + +export namespace imsd::sms { + + using Bytes = std::vector; + + // ---- TS 23.038: alphabets ------------------------------------------- + + enum class Alphabet { Gsm7, Octet, Ucs2 }; + + // The text as GSM 7-bit septets (an extension character as the ESC + // pair); nullopt when a character is outside the alphabet and its + // extension — the caller then sends UCS-2. + std::optional Gsm7Septets(std::string_view utf8) { + Bytes out; + for (char32_t cp : Utf8Decode(utf8)) { + bool found = false; + for (std::size_t i = 0; i < Gsm7Table.size(); i++) + if (i != Gsm7Escape && static_cast(Gsm7Table[i]) == cp) { out.push_back(static_cast(i)); found = true; break; } + if (found) continue; + for (const auto& [code, u] : Gsm7Ext) + if (static_cast(u) == cp) { out.push_back(Gsm7Escape); out.push_back(code); found = true; break; } + if (!found) return std::nullopt; + } + return out; + } + + // Septets → UTF-8. An escape to a code the extension table does not + // define shows the main table's character (TS 23.038 6.2.1.1); an escape + // to another extension table (ESC ESC) a space (6.2.1.1 NOTE 1), and so + // does a trailing escape. + std::string Gsm7Text(std::span septets) { + std::string s; + for (std::size_t i = 0; i < septets.size(); i++) { + const std::uint8_t c = septets[i] & 0x7F; + if (c != Gsm7Escape) { Utf8Append(s, Gsm7Table[c]); continue; } + if (i + 1 >= septets.size()) { s.push_back(' '); break; } + const std::uint8_t n = septets[++i] & 0x7F; + if (n == Gsm7Escape) { s.push_back(' '); continue; } + bool hit = false; + for (const auto& [code, u] : Gsm7Ext) + if (code == n) { Utf8Append(s, u); hit = true; break; } + if (!hit) Utf8Append(s, Gsm7Table[n]); + } + return s; + } + + // TS 23.038 6.1.2.1.1: septets packed LSB first into octets, `fill` + // zero bits before the first septet (the padding that brings a + // user-data header to a septet boundary, TS 23.040 9.2.3.24). + Bytes PackSeptets(std::span septets, int fill = 0) { + const std::size_t bits = static_cast(fill) + septets.size() * 7; + Bytes out((bits + 7) / 8, 0); + std::size_t p = static_cast(fill); + for (std::uint8_t s : septets) { + for (int i = 0; i < 7; i++, p++) + if ((s >> i) & 1) out[p / 8] |= static_cast(1u << (p % 8)); + } + return out; + } + + // `count` septets out of `octets`, skipping `fill` bits first; stops + // short when the octets run out. + Bytes UnpackSeptets(std::span octets, std::size_t count, int fill = 0) { + Bytes out; + const std::size_t total = octets.size() * 8; + std::size_t p = static_cast(fill); + for (std::size_t n = 0; n < count && p + 7 <= total; n++) { + std::uint8_t v = 0; + for (int i = 0; i < 7; i++, p++) + if ((octets[p / 8] >> (p % 8)) & 1) v |= static_cast(1u << i); + out.push_back(v); + } + return out; + } + + // UTF-8 → UTF-16BE units (a code point beyond the BMP as a surrogate + // pair). + std::vector Utf16Units(std::string_view utf8) { + std::vector out; + for (char32_t cp : Utf8Decode(utf8)) { + if (cp < 0x10000) { out.push_back(static_cast(cp)); continue; } + cp -= 0x10000; + out.push_back(static_cast(0xD800 + (cp >> 10))); + out.push_back(static_cast(0xDC00 + (cp & 0x3FF))); + } + return out; + } + + Bytes Ucs2Bytes(std::span units) { + Bytes out; + for (char16_t u : units) { + out.push_back(static_cast(u >> 8)); + out.push_back(static_cast(u & 0xFF)); + } + return out; + } + + Bytes Ucs2Encode(std::string_view utf8) { return Ucs2Bytes(Utf16Units(utf8)); } + + // UTF-16BE bytes → UTF-8; a lone surrogate, a trailing odd byte or a + // U+0000 (no text means it, and a D-Bus string cannot carry it) yields + // U+FFFD. + std::string Ucs2Decode(std::span b) { + std::string s; + for (std::size_t i = 0; i + 1 < b.size(); i += 2) { + char32_t u = static_cast((b[i] << 8) | b[i + 1]); + if (u >= 0xD800 && u < 0xDC00 && i + 3 < b.size()) { + const char32_t lo = static_cast((b[i + 2] << 8) | b[i + 3]); + if (lo >= 0xDC00 && lo < 0xE000) { u = 0x10000 + ((u - 0xD800) << 10) + (lo - 0xDC00); i += 2; } + else u = 0xFFFD; + } else if (u >= 0xD800 && u < 0xE000) u = 0xFFFD; + if (u == 0) u = 0xFFFD; + Utf8Append(s, u); + } + if (b.size() % 2) Utf8Append(s, 0xFFFD); + return s; + } + + // ---- TS 23.040 9.1.2.5 / TS 24.011 8.2.5: addresses ------------------ + + // Type-of-address octets: bit 7 set, type of number in bits 6-4, + // numbering plan in bits 3-0. + constexpr std::uint8_t ToaInternational = 0x91; // E.164, international + constexpr std::uint8_t ToaUnknown = 0x81; // E.164, as dialled (a short code, a national number) + constexpr std::uint8_t ToaAlphanumeric = 0xD0; // GSM 7-bit text, no numbering plan + + struct Address { + std::uint8_t toa = ToaUnknown; + std::string digits; // the digits (0-9 * # a b c), or the text of an alphanumeric sender + + bool International() const { return (toa & 0x70) == 0x10; } + bool Alphanumeric() const { return (toa & 0x70) == 0x50; } + // "+" for an international number, the digits or the text otherwise. + std::string Number() const { return International() ? "+" + digits : digits; } + + // A number as a user types it: "+…" is international; anything else + // (a short code, a national number) goes as dialled with the type + // "unknown", which the network reads by its own dialling plan. + // Spaces, dashes and dots are dropped. Digits, `*` and `#` only: the + // BCD table's a, b and c are decoded, never dialled. At most 20 + // digits, what an address field holds (9.1.2.5) — so a number this + // accepts is one the encoders accept. + static std::optional
ForNumber(std::string_view number) { + Address a; + std::string n; + for (char c : number) + if (c != ' ' && c != '-' && c != '.') n.push_back(c); + if (n.starts_with('+')) { a.toa = ToaInternational; n.erase(0, 1); } + if (n.empty() || n.size() > 20) return std::nullopt; + for (char c : n) + if (!(std::isdigit(static_cast(c)) || c == '*' || c == '#')) return std::nullopt; + a.digits = n; + return a; + } + }; + + // Semi-octet digits, the first digit in the low nibble, 0xF closing an + // odd count; nullopt for a character that is no BCD digit. + std::optional EncodeBcd(std::string_view digits) { + Bytes out; + for (std::size_t i = 0; i < digits.size(); i += 2) { + auto lo = BcdOf(digits[i]); + if (!lo) return std::nullopt; + std::uint8_t hi = 0xF; + if (i + 1 < digits.size()) { + auto h = BcdOf(digits[i + 1]); + if (!h) return std::nullopt; + hi = *h; + } + out.push_back(static_cast(*lo | (hi << 4))); + } + return out; + } + + // Up to `nDigits` digits out of semi-octets. A 0xF is fill and is + // skipped wherever it stands: one before the last semi-octet does not + // end the value (9.1.2.3). + std::string DecodeBcd(std::span b, std::size_t nDigits) { + std::string s; + for (std::size_t i = 0; i < nDigits; i++) { + const std::uint8_t n = i % 2 ? Byte(b, i / 2) >> 4 : Byte(b, i / 2) & 0xF; + if (n == 0xF) continue; + s.push_back(BcdDigits[n]); + } + return s; + } + + // The SM-TL address field: [digits][type-of-address][value] — the length + // counts semi-octets (TS 23.040 9.1.2.5); an alphanumeric value is 7-bit + // packed text and its length the useful semi-octets, ceil(7n/4). + std::optional EncodeTpAddress(const Address& a) { + Bytes out; + if (a.Alphanumeric()) { + auto sep = Gsm7Septets(a.digits); + if (!sep) return std::nullopt; + Bytes packed = PackSeptets(*sep); + out.push_back(static_cast((sep->size() * 7 + 3) / 4)); + out.push_back(a.toa); + out.insert(out.end(), packed.begin(), packed.end()); + return out; + } + auto bcd = EncodeBcd(a.digits); + if (!bcd || a.digits.empty() || a.digits.size() > 20) return std::nullopt; + out.push_back(static_cast(a.digits.size())); + out.push_back(a.toa); + out.insert(out.end(), bcd->begin(), bcd->end()); + return out; + } + + // Reads an SM-TL address field at `pos`, advancing it; nullopt when the + // bytes run out. + std::optional
DecodeTpAddress(std::span b, std::size_t& pos) { + if (pos + 2 > b.size()) return std::nullopt; + const std::size_t len = b[pos]; + const std::size_t octets = (len + 1) / 2; + if (pos + 2 + octets > b.size()) return std::nullopt; + Address a; + a.toa = b[pos + 1]; + auto value = b.subspan(pos + 2, octets); + if (a.Alphanumeric()) a.digits = Gsm7Text(UnpackSeptets(value, len * 4 / 7)); + else a.digits = DecodeBcd(value, len); + pos += 2 + octets; + return a; + } + + // The SM-RL address (TS 24.011 8.2.5.1/8.2.5.2) as the LV it travels + // as: [octets][type-of-address][digits] — the length counts octets. + std::optional EncodeRpAddress(const Address& a) { + auto bcd = EncodeBcd(a.digits); + if (!bcd || a.digits.empty() || a.digits.size() > 20) return std::nullopt; + Bytes out; + out.push_back(static_cast(1 + bcd->size())); + out.push_back(a.toa); + out.insert(out.end(), bcd->begin(), bcd->end()); + return out; + } + + // The value of an SM-RL address (what follows its length): the + // type-of-address octet and the digits. + std::optional
DecodeRpAddressValue(std::span v) { + if (v.empty()) return std::nullopt; + Address a; + a.toa = v[0]; + a.digits = DecodeBcd(v.subspan(1), (v.size() - 1) * 2); + return a; + } + + // ---- TS 23.040 9.2.3.11: TP-Service-Centre-Time-Stamp ----------------- + + // Seven semi-octet pairs (year, month, day, hour, minute, second, zone + // in quarter hours with its sign in bit 3 of the first semi-octet) as + // "2026-10-16T22:50:00+02:00", with the sender's offset. + // A semi-octet that is no digit reads as 0 (9.2.3.11). + std::string ScTimeStamp(std::span b) { + if (b.size() < 7) return {}; + auto semi = [](int v) { return v > 9 ? 0 : v; }; + auto digit = [&](std::size_t i) { return semi(Byte(b, i) & 0xF) * 10 + semi(Byte(b, i) >> 4); }; + const int tzOctet = Byte(b, 6); + const int quarters = (tzOctet & 0x7) * 10 + semi(tzOctet >> 4); + const char sign = (tzOctet & 0x08) ? '-' : '+'; + return std::format("20{:02}-{:02}-{:02}T{:02}:{:02}:{:02}{}{:02}:{:02}", + digit(0), digit(1), digit(2), digit(3), digit(4), digit(5), sign, quarters / 4, (quarters % 4) * 15); + } + + // ---- TS 23.040 9.2.3.10 / TS 23.038 4: TP-Data-Coding-Scheme ---------- + + struct Coding { + Alphabet alphabet = Alphabet::Gsm7; + std::optional msgClass; // 0-3 when the scheme carries a class + bool compressed = false; // TS 23.042 compression (not decoded) + bool messageWaiting = false; // a message-waiting indication group (the text, if any, is still shown) + }; + + Coding DecodeDcs(std::uint8_t dcs) { + Coding c; + const std::uint8_t group = dcs >> 4; + if (group <= 0x7) { // general data coding (00xx), marked for automatic deletion (01xx) + c.compressed = dcs & 0x20; + if (dcs & 0x10) c.msgClass = dcs & 0x03; + switch ((dcs >> 2) & 0x3) { + case 1: c.alphabet = Alphabet::Octet; break; + case 2: c.alphabet = Alphabet::Ucs2; break; + default: c.alphabet = Alphabet::Gsm7; break; // 0, and the reserved 3 (TS 23.038 4: as 00000000) + } + } else if (group >= 0xC && group <= 0xE) { // message waiting indication: discard / store 7-bit / store UCS-2 + c.messageWaiting = true; + c.alphabet = group == 0xE ? Alphabet::Ucs2 : Alphabet::Gsm7; + } else if (group == 0xF) { // data coding / message class + c.alphabet = (dcs & 0x04) ? Alphabet::Octet : Alphabet::Gsm7; + c.msgClass = dcs & 0x03; + } + return c; // 1000..1011 reserved: as 00000000 + } + + constexpr std::uint8_t DcsGsm7 = 0x00; + constexpr std::uint8_t DcsUcs2 = 0x08; + + // ---- TS 23.040 9.2.3.24: the user-data header ------------------------- + + struct Concat { + std::uint16_t ref = 0; + std::uint8_t total = 0; + std::uint8_t seq = 0; + }; + + struct UserDataHeader { + std::optional concat; // IE 00 (8-bit reference) or 08 (16-bit) + std::optional portDst; // IE 04/05: application port addressing + std::optional portSrc; + bool valid = true; // false: an element overran the header (the whole header is ignored, 9.2.3.24) + }; + + // The elements of a header (its contents after the UDHL octet). A later + // occurrence of a non-repeatable element wins (9.2.3.24); a + // concatenation element with a zero total, a zero sequence or one past + // the total is ignored (9.2.3.24.1). + UserDataHeader ParseUserDataHeader(std::span h) { + UserDataHeader out; + std::size_t p = 0; + while (p < h.size()) { + if (p + 2 > h.size()) { out.valid = false; break; } + const std::uint8_t iei = h[p]; + const std::size_t len = h[p + 1]; + if (p + 2 + len > h.size()) { out.valid = false; break; } + auto d = h.subspan(p + 2, len); + if (iei == 0x00 && len == 3) { + if (d[1] != 0 && d[2] != 0 && d[2] <= d[1]) out.concat = Concat{d[0], d[1], d[2]}; + } else if (iei == 0x08 && len == 4) { + if (d[2] != 0 && d[3] != 0 && d[3] <= d[2]) out.concat = Concat{static_cast((d[0] << 8) | d[1]), d[2], d[3]}; + } else if (iei == 0x04 && len == 2) { + out.portDst = d[0]; out.portSrc = d[1]; + } else if (iei == 0x05 && len == 4) { + out.portDst = static_cast((d[0] << 8) | d[1]); + out.portSrc = static_cast((d[2] << 8) | d[3]); + } + p += 2 + len; + } + if (!out.valid) out = UserDataHeader{std::nullopt, std::nullopt, std::nullopt, false}; + return out; + } + + // The concatenation element with an 8-bit reference, as the header's + // contents (UDHL excluded): 00 03 . + Bytes ConcatHeader(std::uint8_t ref, std::uint8_t total, std::uint8_t seq) { return {0x00, 0x03, ref, total, seq}; } + + // ---- TS 23.040 9.2.2: the TPDUs --------------------------------------- + + // The user data as the TPDU carries it: the header (if any), then the + // text or the octets. + struct UserData { + Alphabet alphabet = Alphabet::Gsm7; + UserDataHeader header; + bool hasHeader = false; + std::string text; // GSM 7-bit or UCS-2 decoded to UTF-8; empty for 8-bit data + Bytes units; // the text's undecoded units — septets for GSM 7-bit, UTF-16BE octets for UCS-2 — so a set's segments decode as one stream (Reassembler) + Bytes data; // 8-bit data after the header + }; + + // Decodes TP-UD given TP-UDL and TP-UDHI (9.2.3.16, 9.2.3.24): with a + // header and the 7-bit alphabet the text starts at the next septet + // boundary after it and the length counts the header's septets too; + // with UCS-2 or 8-bit data the length counts octets, header included. + // Short user data decodes as far as it goes. + UserData DecodeUserData(std::span ud, std::size_t udl, bool udhi, Alphabet alphabet) { + UserData out; + out.alphabet = alphabet; + std::size_t headerOctets = 0; + if (udhi && !ud.empty()) { + const std::size_t udhl = ud[0]; + headerOctets = std::min(ud.size(), 1 + udhl); + out.hasHeader = true; + out.header = ParseUserDataHeader(ud.subspan(1, headerOctets - 1)); + } + if (alphabet == Alphabet::Gsm7) { + const std::size_t headerSeptets = (headerOctets * 8 + 6) / 7; + const int fill = static_cast(headerSeptets * 7 - headerOctets * 8); + const std::size_t count = udl > headerSeptets ? udl - headerSeptets : 0; + out.units = UnpackSeptets(ud.subspan(headerOctets), count, fill); + out.text = Gsm7Text(out.units); + return out; + } + const std::size_t count = udl > headerOctets ? std::min(udl - headerOctets, ud.size() - headerOctets) : 0; + auto payload = ud.subspan(headerOctets, count); + if (alphabet == Alphabet::Ucs2) { out.units.assign(payload.begin(), payload.end()); out.text = Ucs2Decode(payload); } + else out.data.assign(payload.begin(), payload.end()); + return out; + } + + // What a TPDU from the service centre is (9.2.3.1, the SC → MS reading + // of TP-MTI). + enum class TpduKind { Deliver, SubmitReport, StatusReport, Reserved }; + TpduKind KindOfTpdu(std::span tpdu) { + switch (Byte(tpdu, 0) & 0x3) { + case 0: return TpduKind::Deliver; + case 1: return TpduKind::SubmitReport; + case 2: return TpduKind::StatusReport; + default: return TpduKind::Reserved; // processed as an SMS-DELIVER (9.2.3.1) + } + } + + struct Deliver { + Address from; + std::uint8_t pid = 0; + std::uint8_t dcs = 0; + Coding coding; + std::string scts; // the service centre's time stamp (ScTimeStamp's text) + bool moreMessages = false; // TP-MMS: more are waiting at the SC + bool statusReportIndication = false; + bool replyPath = false; + UserData ud; + }; + + // An SMS-DELIVER (9.2.2.1). nullopt when the mandatory fields run out; + // a TP-MTI of reserved value is read as a DELIVER (9.2.3.1). + std::optional ParseDeliver(std::span b) { + if (b.empty()) return std::nullopt; + Deliver d; + const std::uint8_t first = b[0]; + d.moreMessages = !(first & 0x04); + d.statusReportIndication = first & 0x20; + d.replyPath = first & 0x80; + const bool udhi = first & 0x40; + std::size_t pos = 1; + auto from = DecodeTpAddress(b, pos); + if (!from) return std::nullopt; + d.from = *from; + if (pos + 2 + 7 + 1 > b.size()) return std::nullopt; + d.pid = b[pos++]; + d.dcs = b[pos++]; + d.coding = DecodeDcs(d.dcs); + d.scts = ScTimeStamp(b.subspan(pos, 7)); + pos += 7; + const std::size_t udl = b[pos++]; + d.ud = DecodeUserData(b.subspan(pos), udl, udhi, d.coding.alphabet); + return d; + } + + struct StatusReport { + std::uint8_t mr = 0; // the TP-MR of the SMS-SUBMIT it reports on + Address recipient; + std::string scts; // when the SC took the SMS-SUBMIT + std::string dischargeTime; // when the outcome happened + std::uint8_t status = 0; // TP-ST (9.2.3.15) + bool moreMessages = false; + }; + + // An SMS-STATUS-REPORT (9.2.2.3); the optional tail (TP-PI onwards) is + // not read. + std::optional ParseStatusReport(std::span b) { + if (b.size() < 2) return std::nullopt; + StatusReport r; + r.moreMessages = !(b[0] & 0x04); + r.mr = b[1]; + std::size_t pos = 2; + auto ra = DecodeTpAddress(b, pos); + if (!ra) return std::nullopt; + r.recipient = *ra; + if (pos + 15 > b.size()) return std::nullopt; + r.scts = ScTimeStamp(b.subspan(pos, 7)); + r.dischargeTime = ScTimeStamp(b.subspan(pos + 7, 7)); + r.status = b[pos + 14]; + return r; + } + + // TP-ST (9.2.3.15) as the MS is to read it. The octet's low seven bits + // make four classes of 32 values: the transaction completed (from + // 0x00), a temporary error with the SC still trying (0x20), and a + // permanent (0x40) and a temporary (0x60) error with the SC not making + // any more transfer attempts. Each names its first values, reserves the + // rest of its first sixteen and leaves the other sixteen to each SC. A + // reserved value — any with bit 7 set among them — is read as "Service + // Rejected" (0x63), as the clause has it. + constexpr std::uint8_t StatusAsRead(std::uint8_t st) { + constexpr std::uint8_t lastNamed[] = {0x02, 0x05, 0x09, 0x05}; // of each class, counted from its first value + if (st & 0x80) return 0x63; + const std::uint8_t within = st & 0x1F; + return (within >= 0x10 || within <= lastNamed[st >> 5]) ? st : 0x63; + } + + // The same in words: a named value by its name, an SC's own by its + // class and number, a reserved one as the rejection it is read as, + // with the number that came. + std::string StatusText(std::uint8_t st) { + const std::uint8_t read = StatusAsRead(st); + if (read != st) return std::format("service rejected, the SC has stopped trying (reserved status 0x{:02x})", st); + switch (read) { + case 0x00: return "delivered"; + case 0x01: return "forwarded, delivery unconfirmed"; + case 0x02: return "replaced by the SC"; + case 0x20: return "congestion, the SC is retrying"; + case 0x21: return "recipient busy, the SC is retrying"; + case 0x22: return "no response from the recipient, the SC is retrying"; + case 0x23: return "service rejected, the SC is retrying"; + case 0x24: return "quality of service not available, the SC is retrying"; + case 0x25: return "error in the recipient, the SC is retrying"; + case 0x40: return "remote procedure error"; + case 0x41: return "incompatible destination"; + case 0x42: return "connection rejected by the recipient"; + case 0x43: return "not obtainable"; + case 0x44: return "quality of service not available"; + case 0x45: return "no interworking available"; + case 0x46: return "validity period expired"; + case 0x47: return "deleted by the originator"; + case 0x48: return "deleted by the SC"; + case 0x49: return "no longer exists"; + case 0x60: return "congestion, the SC has stopped trying"; + case 0x61: return "recipient busy, the SC has stopped trying"; + case 0x62: return "no response from the recipient, the SC has stopped trying"; + case 0x63: return "service rejected, the SC has stopped trying"; + case 0x64: return "quality of service not available, the SC has stopped trying"; + case 0x65: return "error in the recipient, the SC has stopped trying"; + default: break; + } + if (read < 0x20) return std::format("completed, status 0x{:02x}", st); + if (read < 0x40) return std::format("temporary error 0x{:02x}, the SC is retrying", st); + if (read < 0x60) return std::format("permanent error 0x{:02x}", st); + return std::format("temporary error 0x{:02x}, the SC has stopped trying", st); + } + + struct SubmitReport { + std::optional failureCause; // TP-FCS, in the RP-ERROR shape only + std::string scts; + }; + + // An SMS-SUBMIT-REPORT (9.2.2.2a) — in an RP-ACK (the SC's time stamp) + // or an RP-ERROR (`ofError`: the failure cause first). + std::optional ParseSubmitReport(std::span b, bool ofError) { + SubmitReport r; + std::size_t pos = 1; + if (ofError) { + // bits 7 and 5-2 of the first octet are unused: with one of them set + // nothing else is examined and the cause is "unspecified" (9.2.2.2a) + if (!b.empty() && (b[0] & 0xBC)) { r.failureCause = 0xFF; return r; } + if (b.size() < 2) return std::nullopt; + r.failureCause = b[1]; pos = 2; + } + if (pos + 1 + 7 > b.size()) return std::nullopt; + r.scts = ScTimeStamp(b.subspan(pos + 1, 7)); + return r; + } + + // TP-FCS (9.2.3.22) in words. + std::string FailureCauseText(std::uint8_t fcs) { + switch (fcs) { + case 0x80: return "telematic interworking not supported"; + case 0x81: return "short message type 0 not supported"; + case 0x82: return "cannot replace short message"; + case 0x8F: return "unspecified TP-PID error"; + case 0x90: return "data coding scheme not supported"; + case 0x91: return "message class not supported"; + case 0x9F: return "unspecified TP-DCS error"; + case 0xB0: return "TPDU not supported"; + case 0xC0: return "SC busy"; + case 0xC1: return "no SC subscription"; + case 0xC2: return "SC system failure"; + case 0xC3: return "invalid SME address"; + case 0xC4: return "destination SME barred"; + case 0xC5: return "duplicate short message rejected"; + case 0xC6: return "TP-VPF not supported"; + case 0xC7: return "TP-VP not supported"; + case 0xD0: return "(U)SIM SMS storage full"; + case 0xD1: return "no SMS storage capability in (U)SIM"; + case 0xD2: return "error in MS"; + case 0xD3: return "memory capacity exceeded"; + case 0xFF: return "unspecified error"; + default: return std::format("failure cause 0x{:02x}", fcs); + } + } + + // The SMS-DELIVER-REPORT a delivery is acknowledged with (9.2.2.1a): + // for the RP-ACK the type octet and an empty parameter indicator; for + // the RP-ERROR the failure cause between them. + Bytes DeliverReportAck() { return {0x00, 0x00}; } + Bytes DeliverReportError(std::uint8_t fcs) { return {0x00, fcs, 0x00}; } + constexpr std::uint8_t FcsUnspecified = 0xFF; + constexpr std::uint8_t FcsTpduNotSupported = 0xB0; + + // Segment capacities (9.2.3.24.1): a lone message, and one with the + // 8-bit-reference concatenation header (six octets: UDHL + 00 03 r t s). + constexpr std::size_t Gsm7Max = 160; + constexpr std::size_t Gsm7SegmentMax = 153; + constexpr std::size_t Ucs2Max = 70; // UTF-16 units + constexpr std::size_t Ucs2SegmentMax = 67; + constexpr std::size_t SegmentsMax = 255; + + struct Submit { + std::string to; + std::uint8_t mr = 0; // TP-MR of the first segment; each further one takes the next (9.2.3.24.1) + std::optional validity; // TP-VP, relative format (9.2.3.12.1); none: no TP-VP + bool statusReport = false; // TP-SRR + bool rejectDuplicates = false; // TP-RD + std::uint8_t pid = 0; + }; + + // The text split into segments of septets (7-bit) or UTF-16 units + // (UCS-2): one when it fits a lone message, else as many as the + // concatenated capacity needs; an escape pair or a surrogate pair is + // never split (9.2.3.24.1). nullopt when more than SegmentsMax would + // be needed. + std::optional>> SplitText(std::string_view text, Alphabet& alphabet) { + std::vector> segments; + std::vector units; + std::size_t lone = 0; + std::size_t per = 0; + auto isPairLead = [&](std::uint16_t u) { + return alphabet == Alphabet::Gsm7 ? u == Gsm7Escape : (u >= 0xD800 && u < 0xDC00); + }; + if (auto sep = Gsm7Septets(text)) { + alphabet = Alphabet::Gsm7; + units.assign(sep->begin(), sep->end()); + lone = Gsm7Max; per = Gsm7SegmentMax; + } else { + alphabet = Alphabet::Ucs2; + for (char16_t u : Utf16Units(text)) units.push_back(u); + lone = Ucs2Max; per = Ucs2SegmentMax; + } + if (units.size() <= lone) { segments.push_back(units); return segments; } + std::size_t i = 0; + while (i < units.size()) { + std::size_t n = std::min(per, units.size() - i); + if (n > 1 && i + n < units.size() && isPairLead(units[i + n - 1])) n--; + segments.emplace_back(units.begin() + static_cast(i), units.begin() + static_cast(i + n)); + i += n; + if (segments.size() > SegmentsMax) return std::nullopt; + } + return segments; + } + + // The SMS-SUBMIT TPDUs (9.2.2.2) for `text`: one per segment, the + // concatenation header on each when there are several (`concatRef` + // names the set), TP-MR counting up from `s.mr`. Empty when the + // destination is no number or the text needs too many segments. + std::vector BuildSubmits(const Submit& s, std::string_view text, std::uint8_t concatRef) { + std::vector out; + auto to = Address::ForNumber(s.to); + if (!to) return out; + auto da = EncodeTpAddress(*to); + if (!da) return out; + Alphabet alphabet = Alphabet::Gsm7; + auto segments = SplitText(text, alphabet); + if (!segments) return out; + const bool concat = segments->size() > 1; + for (std::size_t i = 0; i < segments->size(); i++) { + const auto& units = (*segments)[i]; + std::uint8_t first = 0x01; // SMS-SUBMIT + if (s.rejectDuplicates) first |= 0x04; + if (s.validity) first |= 0x10; // TP-VPF relative + if (s.statusReport) first |= 0x20; + if (concat) first |= 0x40; + Bytes tpdu = {first, static_cast((s.mr + i) & 0xFF)}; + tpdu.insert(tpdu.end(), da->begin(), da->end()); + tpdu.push_back(s.pid); + tpdu.push_back(alphabet == Alphabet::Gsm7 ? DcsGsm7 : DcsUcs2); + if (s.validity) tpdu.push_back(*s.validity); + Bytes header; + if (concat) { + Bytes ie = ConcatHeader(concatRef, static_cast(segments->size()), static_cast(i + 1)); + header.push_back(static_cast(ie.size())); + header.insert(header.end(), ie.begin(), ie.end()); + } + if (alphabet == Alphabet::Gsm7) { + Bytes septets(units.begin(), units.end()); + const std::size_t headerSeptets = (header.size() * 8 + 6) / 7; + const int fill = static_cast(headerSeptets * 7 - header.size() * 8); + Bytes packed = PackSeptets(septets, header.empty() ? 0 : fill); + tpdu.push_back(static_cast(headerSeptets + septets.size())); + tpdu.insert(tpdu.end(), header.begin(), header.end()); + tpdu.insert(tpdu.end(), packed.begin(), packed.end()); + } else { + std::vector u16(units.begin(), units.end()); + Bytes body = Ucs2Bytes(u16); + tpdu.push_back(static_cast(header.size() + body.size())); + tpdu.insert(tpdu.end(), header.begin(), header.end()); + tpdu.insert(tpdu.end(), body.begin(), body.end()); + } + out.push_back(std::move(tpdu)); + } + return out; + } + + // ---- TS 24.011 7.3 / 8.2: the SM-RL messages -------------------------- + + enum class RpType : std::uint8_t { + DataMo = 0, // RP-DATA, MS → network + DataMt = 1, // RP-DATA, network → MS + AckMo = 2, // RP-ACK, MS → network + AckMt = 3, // RP-ACK, network → MS + ErrorMo = 4, // RP-ERROR, MS → network + ErrorMt = 5, // RP-ERROR, network → MS + Smma = 6, // RP-SMMA, MS → network + }; + + constexpr std::uint8_t RpUserDataIei = 0x41; + + struct Rp { + RpType type = RpType::DataMt; + std::uint8_t mr = 0; // RP-Message Reference: links an ACK/ERROR to its DATA + std::optional
sc; // RP-Originator (MT) or RP-Destination (MO): the service centre + Bytes tpdu; // RP-User Data + std::optional cause; // RP-ERROR + std::optional diagnostic; + }; + + // RP-DATA MS → network (7.3.1.2): an empty originator, the service + // centre as destination — `scAddress` as EF_SMSP holds it and + // EncodeRpAddress builds it: [octets][toa][digits] —, the TPDU. + Bytes BuildRpData(std::uint8_t mr, std::span scAddress, std::span tpdu) { + Bytes out = {static_cast(RpType::DataMo), mr, 0x00}; + out.insert(out.end(), scAddress.begin(), scAddress.end()); + out.push_back(static_cast(tpdu.size())); + out.insert(out.end(), tpdu.begin(), tpdu.end()); + return out; + } + + // RP-ACK MS → network (7.3.3), the SMS-DELIVER-REPORT as its user data + // when given. + Bytes BuildRpAck(std::uint8_t mr, std::span tpdu = {}) { + Bytes out = {static_cast(RpType::AckMo), mr}; + if (!tpdu.empty()) { + out.push_back(RpUserDataIei); + out.push_back(static_cast(tpdu.size())); + out.insert(out.end(), tpdu.begin(), tpdu.end()); + } + return out; + } + + // RP-ERROR MS → network (7.3.4): the cause (8.2.5.4, no diagnostic), + // the SMS-DELIVER-REPORT as its user data when given. + Bytes BuildRpError(std::uint8_t mr, std::uint8_t cause, std::span tpdu = {}) { + Bytes out = {static_cast(RpType::ErrorMo), mr, 0x01, static_cast(cause & 0x7F)}; + if (!tpdu.empty()) { + out.push_back(RpUserDataIei); + out.push_back(static_cast(tpdu.size())); + out.insert(out.end(), tpdu.begin(), tpdu.end()); + } + return out; + } + + // RP-Cause values (table 8.4) in words — the MO ones a submission may + // be refused with and the MT ones we send. + std::string RpCauseText(std::uint8_t cause) { + switch (cause & 0x7F) { + case 1: return "unassigned number"; + case 8: return "operator determined barring"; + case 10: return "call barred"; + case 21: return "short message transfer rejected"; + case 22: return "memory capacity exceeded"; + case 27: return "destination out of order"; + case 28: return "unidentified subscriber"; + case 29: return "facility rejected"; + case 30: return "unknown subscriber"; + case 38: return "network out of order"; + case 41: return "temporary failure"; + case 42: return "congestion"; + case 47: return "resources unavailable"; + case 50: return "requested facility not subscribed"; + case 69: return "requested facility not implemented"; + case 81: return "invalid short message transfer reference value"; + case 95: return "semantically incorrect message"; + case 96: return "invalid mandatory information"; + case 97: return "message type non-existent or not implemented"; + case 98: return "message not compatible with the short message protocol state"; + case 99: return "information element non-existent or not implemented"; + case 111: return "protocol error, unspecified"; + case 127: return "interworking, unspecified"; + default: return std::format("cause {}", cause & 0x7F); + } + } + constexpr std::uint8_t RpCauseMemoryCapacityExceeded = 22; + constexpr std::uint8_t RpCauseInvalidMandatoryInformation = 96; + constexpr std::uint8_t RpCauseProtocolError = 111; + + // An RP message as received — from the network (the MT types) or, for + // a round trip of our own, from a mobile. nullopt when the type does + // not fit the direction or a mandatory element runs out; the optional + // RP-User Data of an ACK or ERROR is read when its IEI is there. + std::optional ParseRp(std::span b, bool fromNetwork = true) { + if (b.size() < 2) return std::nullopt; + Rp rp; + const std::uint8_t mti = b[0] & 0x07; + if (mti > 6 || (fromNetwork ? mti % 2 == 0 : mti % 2 == 1)) return std::nullopt; + rp.type = static_cast(mti); + rp.mr = b[1]; + std::size_t pos = 2; + auto lv = [&](Bytes& out) -> bool { + if (pos >= b.size()) return false; + const std::size_t len = b[pos++]; + if (pos + len > b.size()) return false; + out.assign(b.begin() + static_cast(pos), b.begin() + static_cast(pos + len)); + pos += len; + return true; + }; + auto userDataTlv = [&]() { + if (pos < b.size() && b[pos] == RpUserDataIei) { pos++; lv(rp.tpdu); } + }; + switch (rp.type) { + case RpType::DataMo: + case RpType::DataMt: { + Bytes oa, da; + if (!lv(oa) || !lv(da) || !lv(rp.tpdu)) return std::nullopt; + const Bytes& scv = rp.type == RpType::DataMt ? oa : da; + if (!scv.empty()) rp.sc = DecodeRpAddressValue(scv); + return rp; + } + case RpType::AckMo: + case RpType::AckMt: + userDataTlv(); + return rp; + case RpType::ErrorMo: + case RpType::ErrorMt: { + Bytes cause; + if (!lv(cause) || cause.empty()) return std::nullopt; + rp.cause = cause[0] & 0x7F; + if (cause.size() > 1) rp.diagnostic = cause[1]; + userDataTlv(); + return rp; + } + case RpType::Smma: + return rp; + } + return std::nullopt; + } + + // ---- TS 31.102 4.2.27: EF_SMSP ---------------------------------------- + + struct SmsParameters { + std::string alpha; // the parameter set's name + Bytes scAddress; // TS-Service-Centre-Address as the RP-DATA destination takes it: [octets][toa][digits] + std::string scNumber; // the same as a number + std::optional validity; // TP-Validity-Period, relative format + }; + + // One record of EF_SMSP: the alpha identifier (the record's length less + // the 28 fixed octets), the parameter indicators (a 0 bit = present), + // TP-Destination-Address (12), TP-Service-Centre-Address (12 — the first + // octet counts the octets that follow, 0xFF when unused), TP-PID, + // TP-DCS, TP-Validity-Period. nullopt for a record too short or without + // a service centre. + std::optional ParseSmsp(std::span record) { + if (record.size() < 28) return std::nullopt; + const std::size_t base = record.size() - 28; + SmsParameters p; + for (std::size_t i = 0; i < base; i++) { + if (record[i] == 0xFF) break; + Utf8Append(p.alpha, Gsm7Table[record[i] & 0x7F]); + } + const std::uint8_t pi = record[base]; + if (pi & 0x02) return std::nullopt; // TP-SCA absent + auto sca = record.subspan(base + 13, 12); + const std::size_t len = sca[0]; + if (len == 0 || len > 11 || len == 0xFF) return std::nullopt; + p.scAddress.assign(sca.begin(), sca.begin() + static_cast(1 + len)); + auto addr = DecodeRpAddressValue(std::span(p.scAddress).subspan(1)); + if (!addr || addr->digits.empty()) return std::nullopt; + p.scNumber = addr->Number(); + if (!(pi & 0x10)) p.validity = record[base + 27]; + return p; + } + + // The bytes `qmicli --uim-read-record` / `--uim-read-transparent` + // print under "Read result:" — colon-separated hex pairs, wrapped over + // lines. Empty when the marker is missing. + Bytes ParseQmicliReadResult(std::string_view text) { + Bytes out; + const std::size_t at = text.find("Read result:"); + if (at == std::string_view::npos) return out; + std::string_view rest = text.substr(at + 12); + std::size_t i = 0; + auto hex = [](char c) -> int { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; + }; + while (i < rest.size()) { + const char c = rest[i]; + if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == ':') { i++; continue; } + if (i + 1 >= rest.size()) break; + const int hi = hex(c); + const int lo = hex(rest[i + 1]); + if (hi < 0 || lo < 0) break; + out.push_back(static_cast(hi * 16 + lo)); + i += 2; + } + return out; + } + + // ---- reassembly of a concatenated message ------------------------------ + + // Collects the segments of concatenated SMS-DELIVERs — keyed by the + // sender, the reference and the total (9.2.3.24.1) — and hands the + // whole message back once every segment is in, in sequence order. A + // set to which no segment comes for `maxAge` seconds on the caller's + // clock is dropped by Purge, and named to the caller: its segments go + // nowhere. + class Reassembler { + public: + struct Dropped { std::string from; std::uint16_t ref = 0; std::uint8_t total = 0; std::uint8_t held = 0; }; + // A segment in; the complete message when it was the last one + // missing: the highest-numbered segment's fields; the text decoded from the + // segments' units joined in order when one alphabet runs through + // the set, so a surrogate pair or an escape pair a sender cut at a + // segment boundary comes out whole (the segments' texts joined + // otherwise); the data joined. A DELIVER without a concatenation + // header is complete as it is. + std::optional Add(Deliver part, double now) { + if (!part.ud.header.concat) return part; + const Concat c = *part.ud.header.concat; + Key key{part.from.Number(), c.ref, c.total}; + Set& set = sets_[key]; + set.at = now; + set.parts[c.seq] = std::move(part); + if (set.parts.size() < c.total) return std::nullopt; + Deliver whole = set.parts.rbegin()->second; + whole.ud.text.clear(); + whole.ud.units.clear(); + whole.ud.data.clear(); + bool oneAlphabet = true; + for (auto& [seq, p] : set.parts) { + if (p.ud.alphabet != whole.ud.alphabet) oneAlphabet = false; + whole.ud.text += p.ud.text; + whole.ud.units.insert(whole.ud.units.end(), p.ud.units.begin(), p.ud.units.end()); + whole.ud.data.insert(whole.ud.data.end(), p.ud.data.begin(), p.ud.data.end()); + } + if (oneAlphabet && whole.ud.alphabet == Alphabet::Gsm7) whole.ud.text = Gsm7Text(whole.ud.units); + else if (oneAlphabet && whole.ud.alphabet == Alphabet::Ucs2) whole.ud.text = Ucs2Decode(whole.ud.units); + sets_.erase(key); + return whole; + } + + std::vector Purge(double now, double maxAge) { + std::vector dropped; + for (auto it = sets_.begin(); it != sets_.end();) { + if (now - it->second.at > maxAge) { + dropped.push_back({it->first.from, it->first.ref, it->first.total, static_cast(it->second.parts.size())}); + it = sets_.erase(it); + } else ++it; + } + return dropped; + } + + std::size_t Pending() const { return sets_.size(); } + + private: + struct Key { + std::string from; + std::uint16_t ref; + std::uint8_t total; + auto operator<=>(const Key&) const = default; + }; + struct Set { + std::map parts; + double at = 0; + }; + std::map sets_; + }; +} diff --git a/interfaces/Imsd.cppm b/interfaces/Imsd.cppm index 588b20b..3baad7e 100644 --- a/interfaces/Imsd.cppm +++ b/interfaces/Imsd.cppm @@ -12,5 +12,6 @@ export import :Ipsec; export import :Qmi; export import :Sip; export import :Sdp; +export import :Sms; export import :Messages; export import :Engine; diff --git a/project.cpp b/project.cpp index e9e89b9..870fd3c 100644 --- a/project.cpp +++ b/project.cpp @@ -158,7 +158,7 @@ extern "C" Configuration CrafterBuildProject(std::span a } // imsd-core — the engine as a static library of pure C++ modules (SIP, - // SDP, later AKA/IPsec/media/engine). Deliberately GLib-free so every + // SDP, SMS, AKA/IPsec/QMI/engine). Deliberately GLib-free so every // piece is unit-testable without a bus or a phone. static auto Core = std::make_unique(); Core->path = "./"; @@ -167,7 +167,7 @@ extern "C" Configuration CrafterBuildProject(std::span a ApplyStandardArgs(*Core, args); Core->type = ConfigurationType::LibraryStatic; { - std::array ifaces = { + std::array ifaces = { "interfaces/Imsd", "interfaces/Imsd-Util", "interfaces/Imsd-Aka", @@ -175,6 +175,7 @@ extern "C" Configuration CrafterBuildProject(std::span a "interfaces/Imsd-Qmi", "interfaces/Imsd-Sip", "interfaces/Imsd-Sdp", + "interfaces/Imsd-Sms", "interfaces/Imsd-Messages", "interfaces/Imsd-Engine", }; @@ -226,6 +227,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("Engine").Dependencies({ Core.get() }); cfg.AddTest("Sip").Dependencies({ Core.get() }); cfg.AddTest("Sdp").Dependencies({ Core.get() }); + cfg.AddTest("Sms").Dependencies({ Core.get() }); LintRules::AddRules(cfg); diff --git a/tests/Sms/main.cpp b/tests/Sms/main.cpp new file mode 100644 index 0000000..5c98d77 --- /dev/null +++ b/tests/Sms/main.cpp @@ -0,0 +1,369 @@ +// SPDX-License-Identifier: GPL-3.0-only +// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® + +// lint-disable-file fixed-width-types +// Imsd:Sms unit tests — the short message codecs byte for byte: the GSM +// 7-bit alphabet, its extension table and the septet packing (the classic +// "hellohello" vector), UCS-2, the address fields, SMS-SUBMIT (the classic +// tutorial PDU, UCS-2, the concatenated pair, the escape and surrogate pairs +// kept whole at a segment boundary), SMS-DELIVER (the classic "How are +// you?" PDU and vectors cross-generated by the fp6 journal's Python +// reference: a header with fill bits, a 16-bit concatenation reference, a +// class-0 message, port-addressed 8-bit data, an alphanumeric sender, a +// negative time zone), SMS-STATUS-REPORT and SMS-SUBMIT-REPORT, the +// RP-DATA / RP-ACK / RP-ERROR messages both ways, EF_SMSP with the KPN +// SIM's record, qmicli's hex dump, and the reassembly of a concatenated +// message. +import std; +import Imsd; + +using namespace imsd::sms; + +namespace { + int Failures = 0; + void Check(bool cond, std::string_view msg) { + if (!cond) { + std::println(std::cerr, "FAIL: {}", msg); + ++Failures; + } + } + + Bytes Hex(std::string_view hex) { + auto b = imsd::util::FromHex(hex); + return b ? *b : Bytes{}; + } + std::string Hex(std::span b) { + std::string s = imsd::util::ToHex(b); + for (char& c : s) c = static_cast(std::toupper(static_cast(c))); + return s; + } + void Eq(std::span got, std::string_view wantHex, std::string_view msg) { + if (Hex(got) != wantHex) { + std::println(std::cerr, "FAIL: {}\n--- got ---\n{}\n--- want ---\n{}", msg, Hex(got), wantHex); + ++Failures; + } + } + std::string Rep(std::string_view s, std::size_t n) { + std::string out; + for (std::size_t i = 0; i < n; i++) out += s; + return out; + } + void EqS(std::string_view got, std::string_view want, std::string_view msg) { + if (got != want) { + std::println(std::cerr, "FAIL: {}\n--- got ---\n{}\n--- want ---\n{}", msg, got, want); + ++Failures; + } + } + + // the KPN SIM's service centre, as EF_SMSP holds it (dev phone, 2026-10-16) + constexpr std::string_view KpnSc = "07911356131313F3"; + + void TestAlphabet() { + auto hello = Gsm7Septets("hellohello"); + Check(hello.has_value() && hello->size() == 10, "hellohello: 10 septets"); + Eq(PackSeptets(*hello), "E8329BFD4697D9EC37", "hellohello packed (the classic vector)"); + EqS(Gsm7Text(UnpackSeptets(Hex("E8329BFD4697D9EC37"), 10)), "hellohello", "hellohello unpacked"); + Eq(PackSeptets(*Gsm7Septets("AAAAAAA"), 1), "82C16030180C02", "seven septets after one fill bit"); + EqS(Gsm7Text(UnpackSeptets(Hex("82C16030180C02"), 7, 1)), "AAAAAAA", "unpacked after one fill bit"); + Eq(PackSeptets(*Gsm7Septets("Test")), "D4F29C0E", "Test packed"); + + auto ext = Gsm7Septets("€[x]{~}\\|^\f"); + Check(ext.has_value() && ext->size() == 21, "extension characters: ESC pairs"); + EqS(Gsm7Text(*ext), "€[x]{~}\\|^\f", "extension characters round trip"); + EqS(Gsm7Text(Bytes{0x00, 0x01, 0x10, 0x1B, 0x1B, 0x1B, 0x41, 0x1B}), "@£Δ A ", "ESC ESC and a trailing ESC show a space, an undefined extension code the main table's character"); + Check(!Gsm7Septets("❤"), "a character outside the alphabet: no septets"); + Check(!Gsm7Septets("a\x1b" "b"), "the ESC character itself is not encodable"); + Check(Gsm7Septets("@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà")->size() == 127, "the whole default table encodes"); + + Eq(Ucs2Encode("Grüße ❤"), "0047007200FC00DF006500202764", "UCS-2 encode"); + EqS(Ucs2Decode(Hex("0047007200FC00DF006500202764")), "Grüße ❤", "UCS-2 decode"); + Eq(Ucs2Encode("😀"), "D83DDE00", "beyond the BMP: a surrogate pair"); + EqS(Ucs2Decode(Hex("D83DDE00")), "😀", "a surrogate pair decodes"); + EqS(Ucs2Decode(Hex("D83D0041")), "�" "A", "a lone high surrogate: U+FFFD"); + EqS(Ucs2Decode(Hex("004100")), "A�", "an odd trailing byte: U+FFFD"); + EqS(Ucs2Decode(Hex("0048006900000021")), "Hi�!", "U+0000: U+FFFD (no text means it; a D-Bus string cannot carry it)"); + } + + void TestAddresses() { + auto a = Address::ForNumber("+31 6-1234.5678"); + Check(a && a->International() && a->digits == "31612345678", "ForNumber: international, separators dropped"); + EqS(a->Number(), "+31612345678", "Number() restores the +"); + Eq(*EncodeTpAddress(*a), "0B911316325476F8", "TP address, 11 digits"); + auto s = Address::ForNumber("112"); + Check(s && !s->International() && s->toa == ToaUnknown, "a short code: type unknown"); + Eq(*EncodeTpAddress(*s), "038111F2", "TP address, 3 digits"); + Eq(*EncodeRpAddress(*Address::ForNumber("+3161234567")), "06911316325476", "RP address, 10 digits: the length counts octets"); + Eq(*EncodeRpAddress(Address{ToaInternational, "31653131313"}), KpnSc, "RP address of KPN's SC = the EF_SMSP bytes"); + Check(!Address::ForNumber("+31x"), "a letter that is no BCD digit: no address"); + Check(!Address::ForNumber("+"), "no digits: no address"); + Check(Address::ForNumber("*21#")->digits == "*21#", "* and # are digits"); + Check(!Address::ForNumber("abc") && !Address::ForNumber("+31c"), "ForNumber: the BCD table's a, b, c are not dialled digits"); + Check(!Address::ForNumber(std::string(21, '1')) && Address::ForNumber(std::string(20, '1')), "ForNumber: at most 20 digits, the address field's cap"); + Eq(*EncodeTpAddress(*Address::ForNumber("*21#")), "04812AB1", "TP address with * and #"); + std::size_t pos = 0; + auto d = DecodeTpAddress(Hex("0B911316325476F8FF"), pos); + Check(d && d->Number() == "+31612345678" && pos == 8, "DecodeTpAddress: 11 digits, 8 octets consumed"); + pos = 0; + Check(!DecodeTpAddress(Hex("0B9113"), pos), "DecodeTpAddress: short"); + pos = 0; + auto inner = DecodeTpAddress(Hex("0481F132"), pos); + Check(inner && inner->Number() == "123" && pos == 4, "DecodeTpAddress: 1111 before the last semi-octet is skipped, not the value's end (9.1.2.3)"); + auto rp = DecodeRpAddressValue(Hex("911356131313F3")); + Check(rp && rp->Number() == "+31653131313", "DecodeRpAddressValue: KPN's SC"); + pos = 0; + auto alnum = DecodeTpAddress(Hex("06D04BA813"), pos); + Check(alnum && alnum->Alphanumeric() && alnum->Number() == "KPN", "an alphanumeric sender decodes as text"); + Eq(*EncodeTpAddress(Address{ToaAlphanumeric, "KPN"}), "06D04BA813", "an alphanumeric address encodes 7-bit"); + } + + void TestSubmit() { + Submit s{"+46708251358", 0, 0xAA}; + auto t = BuildSubmits(s, "hellohello", 0); + Check(t.size() == 1, "classic SUBMIT: one segment"); + if (!t.empty()) Eq(t[0], "11000B916407281553F80000AA0AE8329BFD4697D9EC37", "the classic tutorial SMS-SUBMIT"); + + Submit u{"+31612345678", 7}; + auto tu = BuildSubmits(u, "Grüße ❤", 0); + Check(tu.size() == 1, "UCS-2 SUBMIT: one segment"); + if (!tu.empty()) Eq(tu[0], "01070B911316325476F800080E0047007200FC00DF006500202764", "SMS-SUBMIT in UCS-2, no TP-VP"); + + Submit e{"112", 3}; + auto te = BuildSubmits(e, "€[x]{~}", 0); + Check(te.size() == 1, "SUBMIT with extension characters: one segment"); + if (!te.empty()) Eq(te[0], "0103038111F200000D9BF28687DFF836A84D6F9302", "SMS-SUBMIT with extension characters: 13 septets for 7 characters"); + + Submit o{"+3161234567", 1, 0xA9, true}; + auto to = BuildSubmits(o, "Hi", 0); + Check(to.size() == 1, "SUBMIT with a status report requested: one segment"); + if (!to.empty()) Eq(to[0], "31010A9113163254760000A902C834", "SMS-SUBMIT: status report requested, TP-VP A9, an even number of digits"); + + Submit c{"+31612345678", 10}; + std::string longText(153, 'A'); + longText += std::string(8, 'B'); + auto tc = BuildSubmits(c, longText, 0x2A); + Check(tc.size() == 2, "161 characters: two segments"); + if (tc.size() == 2) { + Eq(tc[0], "410A0B911316325476F80000A00500032A020182C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683", "segment 1/2: UDHI, the concatenation header, 153 septets after one fill bit, TP-MR 10"); + Eq(tc[1], "410B0B911316325476F800000F0500032A02028442A15028140A01", "segment 2/2: TP-MR 11, 8 septets"); + } + Check(BuildSubmits(c, std::string(160, 'A'), 1).size() == 1, "160 characters fit one message"); + Check(BuildSubmits(c, std::string(161, 'A'), 1).size() == 2, "161 characters need two"); + Check(BuildSubmits(c, Rep("ü", 70) + "❤", 1).size() == 2, "71 UCS-2 characters need two"); + Check(BuildSubmits(c, std::string(69, 'x') + "❤", 1).size() == 1, "70 UCS-2 characters fit one"); + Check(BuildSubmits(c, "", 1).size() == 1 && BuildSubmits(c, "", 1)[0].back() == 0, "an empty text: one TPDU with TP-UDL 0"); + Check(BuildSubmits(Submit{"+31x", 1}, "a", 1).empty(), "no number: no TPDU"); + Check(BuildSubmits(c, std::string(153 * 255 + 1, 'A'), 1).empty(), "more than 255 segments: refused"); + + Alphabet alphabet; + auto seg = SplitText(std::string(152, 'A') + "€" + std::string(10, 'B'), alphabet); + Check(seg && seg->size() == 2 && (*seg)[0].size() == 152 && (*seg)[1].size() == 12 && (*seg)[1][0] == 0x1B, "an escape pair is not split at the segment boundary"); + seg = SplitText(Rep("ü", 66) + "😀xxxx", alphabet); + Check(seg && alphabet == Alphabet::Ucs2 && seg->size() == 2 && (*seg)[0].size() == 66 && (*seg)[1].size() == 6, "a surrogate pair is not split at the segment boundary"); + seg = SplitText(std::string(306, 'A'), alphabet); + Check(seg && seg->size() == 2 && (*seg)[1].size() == 153, "306 characters: two full segments"); + } + + void TestDeliver() { + auto classic = ParseDeliver(Hex("040B911346610089F60000208062917314080CC8F71D14969741F977FD07")); + Check(classic.has_value(), "the classic SMS-DELIVER parses"); + if (classic) { + EqS(classic->from.Number(), "+31641600986", "classic: sender"); + EqS(classic->ud.text, "How are you?", "classic: text"); + EqS(classic->scts, "2002-08-26T19:37:41-00:00", "classic: time stamp as the bytes say (its zone octet 08 reads as a negative zero)"); + Check(!classic->moreMessages && !classic->ud.hasHeader && classic->coding.alphabet == Alphabet::Gsm7 && !classic->coding.msgClass, "classic: flags"); + } + auto t = ParseDeliver(Hex("040B911316325476F800006201612205008004D4F29C0E")); + Check(t && t->ud.text == "Test" && t->scts == "2026-10-16T22:50:00+02:00" && t->from.Number() == "+31612345678", "DELIVER 'Test' at +02:00"); + + auto u = ParseDeliver(Hex("040B911316325476F80008620161220500800E0047007200FC00DF006500202764")); + Check(u && u->coding.alphabet == Alphabet::Ucs2 && u->ud.text == "Grüße ❤", "DELIVER in UCS-2"); + + auto k = ParseDeliver(Hex("440B911316325476F80000620161220500800D060804123403029576F91C06")); + Check(k && k->ud.hasHeader && k->ud.header.concat && k->ud.header.concat->ref == 0x1234 && k->ud.header.concat->total == 3 && k->ud.header.concat->seq == 2 && k->ud.text == "Ωmega", "DELIVER with a 16-bit concatenation reference: header of eight septets, no fill"); + + auto f = ParseDeliver(Hex("04048121430010620161220500800546767" "88E06")); + Check(f && f->coding.msgClass == 0 && f->ud.text == "Flash" && f->from.Number() == "1234", "DELIVER class 0 from a short code"); + + auto p = ParseDeliver(Hex("440B911316325476F8000462016122050080090605040B8423F0DEAD")); + Check(p && p->coding.alphabet == Alphabet::Octet && p->ud.header.portDst == 0x0B84 && p->ud.header.portSrc == 0x23F0 && p->ud.text.empty() && Hex(p->ud.data) == "DEAD", "DELIVER of 8-bit data to an application port"); + + auto a = ParseDeliver(Hex("0406D04BA81300006201612205008002C834")); + Check(a && a->from.Alphanumeric() && a->from.Number() == "KPN" && a->ud.text == "Hi", "DELIVER from an alphanumeric sender"); + + auto n = ParseDeliver(Hex("04049121430000621020304050890178")); + Check(n && n->scts == "2026-01-02T03:04:05-04:30" && n->ud.text == "x", "DELIVER with a negative zone"); + + Check(!ParseDeliver(Hex("040B91")), "a truncated DELIVER: nullopt"); + auto shortUd = ParseDeliver(Hex("040B911316325476F8000062016122050080" "0AD4F29C0E")); + Check(shortUd && shortUd->ud.text == "Test", "user data shorter than TP-UDL decodes as far as it goes"); + auto mms = ParseDeliver(Hex("000B911316325476F800006201612205008004D4F29C0E")); + Check(mms && mms->moreMessages, "TP-MMS 0: more messages waiting"); + } + + void TestReassembly() { + Reassembler r; + auto p1 = ParseDeliver(Hex("440B911316325476F8000062016122050080A00500037B020182C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683")); + auto p2 = ParseDeliver(Hex("440B911316325476F80000620161220500800C0500037B02028442A15008")); + Check(p1 && p2 && p1->ud.header.concat && p2->ud.header.concat, "both segments parse with their headers"); + if (!p1 || !p2) return; + Check(p1->ud.text == std::string(153, 'A') && p2->ud.text == "BBBBB", "the segments' texts"); + Check(!r.Add(*p2, 10.0) && r.Pending() == 1, "the second segment first: nothing yet"); + auto whole = r.Add(*p1, 11.0); + Check(whole && whole->ud.text == std::string(153, 'A') + "BBBBB" && r.Pending() == 0, "the first segment completes the message in order"); + auto lone = ParseDeliver(Hex("040B911316325476F800006201612205008004D4F29C0E")); + Check(r.Add(*lone, 12.0).has_value() && r.Pending() == 0, "a message without a header is complete as it is"); + auto k = ParseDeliver(Hex("440B911316325476F80000620161220500800D060804123403029576F91C06")); + Check(!r.Add(*k, 100.0) && r.Pending() == 1, "one of three: pending"); + auto dropped = r.Purge(701.0, 600.0); + Check(r.Pending() == 0 && dropped.size() == 1 && dropped[0].from == "+31612345678" && dropped[0].ref == 0x1234 && dropped[0].total == 3 && dropped[0].held == 1, "a set older than maxAge is dropped and named: sender, reference, total, segments held"); + // a UCS-2 surrogate pair a sender split at the segment boundary (cut at 67 units blindly): whole again, in either arrival order + auto s1 = ParseDeliver(Hex("440B911316325476F80008620161220500808C0500032A0201" + Rep("00FC", 66) + "D83D")); + auto s2 = ParseDeliver(Hex("440B911316325476F8000862016122050080100500032A0202DE00" + Rep("0078", 4))); + Check(s1 && s2 && s1->ud.text == Rep("ü", 66) + "�" && s2->ud.text == "�xxxx", "the split pair: each segment alone decodes its half as U+FFFD"); + if (!s1 || !s2) return; + Check(!r.Add(*s1, 20.0) && r.Pending() == 1, "the split pair: segment 1 alone, nothing yet"); + auto w12 = r.Add(*s2, 21.0); + Check(w12 && w12->ud.text == Rep("ü", 66) + "😀xxxx" && r.Pending() == 0, "the split pair: whole again from the joined units (1 then 2)"); + Check(!r.Add(*s2, 22.0), "the split pair: segment 2 alone, nothing yet"); + auto w21 = r.Add(*s1, 23.0); + Check(w21 && w21->ud.text == Rep("ü", 66) + "😀xxxx" && r.Pending() == 0, "the split pair: whole again (2 then 1)"); + // a GSM 7-bit escape pair split the same way: ESC ends segment 1, the extension code starts segment 2 + auto g1 = ParseDeliver(Hex("440B911316325476F8000062016122050080090500032B0201" + Hex(PackSeptets(Bytes{0x41, 0x1B}, 1)))); + auto g2 = ParseDeliver(Hex("440B911316325476F8000062016122050080090500032B0202" + Hex(PackSeptets(Bytes{0x65, 0x42}, 1)))); + Check(g1 && g2 && g1->ud.text == "A " && g2->ud.text == "eB", "the split escape pair: a space and a stray e, segment by segment"); + if (!g1 || !g2) return; + Check(!r.Add(*g1, 30.0), "the split escape pair: segment 1 alone, nothing yet"); + auto wg = r.Add(*g2, 31.0); + Check(wg && wg->ud.text == "A€B" && r.Pending() == 0, "the split escape pair: whole again from the joined septets"); + } + + void TestHeaderAndDcs() { + auto h = ParseUserDataHeader(Hex("0003010201")); + Check(h.valid && h.concat && h.concat->ref == 1 && h.concat->total == 2 && h.concat->seq == 1, "concatenation IE"); + Check(!ParseUserDataHeader(Hex("0003010001")).concat, "a zero total is ignored"); + Check(!ParseUserDataHeader(Hex("0003010203")).concat, "a sequence past the total is ignored"); + Check(!ParseUserDataHeader(Hex("00030102")).valid, "an element overrunning the header: the whole header is ignored"); + Check(ParseUserDataHeader(Hex("7F02AABB0003050201")).concat.has_value(), "an unknown element is skipped"); + + Check(DecodeDcs(0x00).alphabet == Alphabet::Gsm7 && !DecodeDcs(0x00).msgClass, "DCS 00"); + Check(DecodeDcs(0x08).alphabet == Alphabet::Ucs2, "DCS 08: UCS-2"); + Check(DecodeDcs(0x11).alphabet == Alphabet::Gsm7 && DecodeDcs(0x11).msgClass == 1, "DCS 11: class 1"); + Check(DecodeDcs(0xF6).alphabet == Alphabet::Octet && DecodeDcs(0xF6).msgClass == 2, "DCS F6: 8-bit class 2"); + Check(DecodeDcs(0xD8).messageWaiting && DecodeDcs(0xD8).alphabet == Alphabet::Gsm7, "DCS D8: message waiting, 7-bit"); + Check(DecodeDcs(0xE0).messageWaiting && DecodeDcs(0xE0).alphabet == Alphabet::Ucs2, "DCS E0: message waiting, UCS-2"); + Check(DecodeDcs(0x24).compressed && DecodeDcs(0x24).alphabet == Alphabet::Octet, "DCS 24: compressed 8-bit"); + Check(DecodeDcs(0x0C).alphabet == Alphabet::Gsm7 && DecodeDcs(0x9F).alphabet == Alphabet::Gsm7, "reserved codings read as the default alphabet"); + Check(DecodeDcs(0x48).alphabet == Alphabet::Ucs2 && DecodeDcs(0x51).msgClass == 1 && !DecodeDcs(0x48).messageWaiting && DecodeDcs(0x74).compressed && DecodeDcs(0x74).alphabet == Alphabet::Octet, "DCS 48, 51, 74: the group marked for automatic deletion, read as the general one"); + Check(DecodeDcs(0xC8).messageWaiting && DecodeDcs(0xC8).alphabet == Alphabet::Gsm7 && !DecodeDcs(0xC8).msgClass, "DCS C8: message waiting, discard"); + Check(DecodeDcs(0x84).alphabet == Alphabet::Gsm7 && DecodeDcs(0xB4).alphabet == Alphabet::Gsm7 && !DecodeDcs(0xB4).compressed && !DecodeDcs(0xB4).msgClass && !DecodeDcs(0xB0).messageWaiting, "DCS 84, B0, B4: the reserved groups read as 00000000"); + } + + void TestReports() { + auto sr = ParseStatusReport(Hex("062A0B911316325476F8620161220500806201612205708000")); + Check(sr && sr->mr == 0x2A && sr->recipient.Number() == "+31612345678" && sr->scts == "2026-10-16T22:50:00+02:00" && sr->dischargeTime == "2026-10-16T22:50:07+02:00" && sr->status == 0, "SMS-STATUS-REPORT"); + Check(!ParseStatusReport(Hex("062A0B9113")), "a truncated status report"); + EqS(StatusText(0x00), "delivered", "TP-ST 0"); + EqS(StatusText(0x46), "validity period expired", "TP-ST 46"); + EqS(StatusText(0x30), "temporary error 0x30, the SC is retrying", "TP-ST 30: an SC-specific temporary value"); + EqS(StatusText(0x50), "permanent error 0x50", "TP-ST 50: an SC-specific permanent value"); + EqS(StatusText(0x62), "no response from the recipient, the SC has stopped trying", "TP-ST 62: a temporary error, the SC not trying any more"); + EqS(StatusText(0x70), "temporary error 0x70, the SC has stopped trying", "TP-ST 70: an SC-specific value of that class"); + EqS(StatusText(0x03), "service rejected, the SC has stopped trying (reserved status 0x03)", "TP-ST 03: a reserved value, in words"); + EqS(StatusText(0x80), "service rejected, the SC has stopped trying (reserved status 0x80)", "TP-ST 80: bit 7 set, in words"); + bool asRead = true; + for (int v = 0; v < 256; v++) { + const bool reserved = (v >= 0x03 && v <= 0x0F) || (v >= 0x26 && v <= 0x2F) || (v >= 0x4A && v <= 0x4F) || (v >= 0x66 && v <= 0x6F) || v >= 0x80; + if (StatusAsRead(static_cast(v)) != (reserved ? 0x63 : v)) asRead = false; + } + Check(asRead, "TP-ST: 9.2.3.15's reserved values (0x03-0x0F, 0x26-0x2F, 0x4A-0x4F, 0x66-0x6F, and bit 7 set) are read as Service Rejected (0x63), every other value as it is"); + Check(KindOfTpdu(Hex("062A")) == TpduKind::StatusReport && KindOfTpdu(Hex("04")) == TpduKind::Deliver && KindOfTpdu(Hex("01")) == TpduKind::SubmitReport && KindOfTpdu(Hex("03")) == TpduKind::Reserved, "TP-MTI, SC to MS"); + + auto ack = ParseSubmitReport(Hex("010062016122050080"), false); + Check(ack && !ack->failureCause && ack->scts == "2026-10-16T22:50:00+02:00", "SMS-SUBMIT-REPORT for RP-ACK"); + auto err = ParseSubmitReport(Hex("01C30062016122050080"), true); + Check(err && err->failureCause == 0xC3 && err->scts == "2026-10-16T22:50:00+02:00", "SMS-SUBMIT-REPORT for RP-ERROR"); + bool unusedBits = true; + for (int bit : {7, 5, 4, 3, 2}) { + auto unused = ParseSubmitReport(Hex(std::format("{:02X}C30062016122050080", 0x01 | (1 << bit))), true); + if (!unused || unused->failureCause != 0xFF || !unused->scts.empty()) unusedBits = false; + } + Check(unusedBits, "SMS-SUBMIT-REPORT for RP-ERROR with one of the unused bits of its first octet set (7, 5, 4, 3, 2): the cause is unspecified, nothing else examined (9.2.2.2a)"); + auto alone = ParseSubmitReport(Hex("81"), true); + Check(alone && alone->failureCause == 0xFF, "the same for such a first octet with nothing after it"); + auto udhi = ParseSubmitReport(Hex("41C30062016122050080"), true); + Check(udhi && udhi->failureCause == 0xC3, "TP-UDHI (bit 6) is no unused bit: the cause as sent"); + EqS(ScTimeStamp(Hex("621AF12205A0A0")), "2026-01-10T22:50:00+00:00", "SCTS: a semi-octet that is no digit reads as 0, in the zone too (9.2.3.11)"); + EqS(FailureCauseText(0xC3), "invalid SME address", "TP-FCS C3"); + Eq(DeliverReportAck(), "0000", "SMS-DELIVER-REPORT for RP-ACK"); + Eq(DeliverReportError(0xFF), "00FF00", "SMS-DELIVER-REPORT for RP-ERROR"); + } + + void TestRp() { + const Bytes classic = Hex("11000B916407281553F80000AA0AE8329BFD4697D9EC37"); + Eq(BuildRpData(0x2A, Hex(KpnSc), classic), "002A00" + std::string(KpnSc) + "1711000B916407281553F80000AA0AE8329BFD4697D9EC37", "RP-DATA MS to network"); + Eq(BuildRpAck(5, DeliverReportAck()), "020541020000", "RP-ACK MS to network with the delivery report"); + Eq(BuildRpAck(5), "0205", "RP-ACK MS to network, bare"); + Eq(BuildRpError(5, 111, DeliverReportError(0xFF)), "0405016F410300FF00", "RP-ERROR MS to network"); + + auto mo = ParseRp(BuildRpData(0x2A, Hex(KpnSc), classic), false); + Check(mo && mo->type == RpType::DataMo && mo->mr == 0x2A && mo->sc && mo->sc->Number() == "+31653131313" && mo->tpdu == classic, "our RP-DATA round-trips"); + Check(!ParseRp(BuildRpData(0x2A, Hex(KpnSc), classic), true), "an MS-to-network type read as the network's: refused"); + auto mt = ParseRp(Hex("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07")); + Check(mt && mt->type == RpType::DataMt && mt->mr == 0x11 && mt->sc && mt->sc->Number() == "+31653131313" && mt->tpdu.size() == 30 && KindOfTpdu(mt->tpdu) == TpduKind::Deliver, "RP-DATA network to MS"); + Check(!ParseRp(Hex("011107911356131313F3001E040B91")), "a truncated RP-DATA"); + auto ackMt = ParseRp(Hex("032A4109010062016122050080")); + Check(ackMt && ackMt->type == RpType::AckMt && ackMt->mr == 0x2A && ackMt->tpdu.size() == 9 && KindOfTpdu(ackMt->tpdu) == TpduKind::SubmitReport, "RP-ACK network to MS with a submit report"); + auto bare = ParseRp(Hex("032A")); + Check(bare && bare->type == RpType::AckMt && bare->tpdu.empty(), "a bare RP-ACK"); + auto errMt = ParseRp(Hex("052A011C410A01C30062016122050080")); + Check(errMt && errMt->type == RpType::ErrorMt && errMt->cause == 28 && !errMt->diagnostic && errMt->tpdu.size() == 10, "RP-ERROR network to MS with a submit report"); + EqS(RpCauseText(28), "unidentified subscriber", "RP cause 28"); + auto diag = ParseRp(Hex("0507022611")); + Check(diag && diag->cause == 38 && diag->diagnostic == 0x11 && diag->tpdu.empty(), "RP-ERROR with a diagnostic octet"); + Check(!ParseRp(Hex("05")), "one byte: nothing"); + auto sr = ParseRp(Hex("011207911356131313F30019062A0B911316325476F8620161220500806201612205708000")); + Check(sr && KindOfTpdu(sr->tpdu) == TpduKind::StatusReport, "RP-DATA carrying a status report"); + } + + void TestSmsp() { + const std::string record = std::string(30, 'F') + "ED" + std::string(24, 'F') + std::string(KpnSc) + std::string(8, 'F') + "FFFFA9"; + auto p = ParseSmsp(Hex(record)); + Check(p.has_value(), "the KPN SIM's EF_SMSP record parses"); + if (p) { + EqS(p->scNumber, "+31653131313", "EF_SMSP: the service centre"); + Eq(p->scAddress, KpnSc, "EF_SMSP: the RP-DA bytes"); + Check(p->validity == 0xA9 && p->alpha.empty(), "EF_SMSP: validity A9, no alpha identifier"); + } + const std::string named = "4B504EFF" + std::string(22, 'F') + "ED" + std::string(24, 'F') + std::string(KpnSc) + std::string(8, 'F') + "FFFFFF"; + auto n = ParseSmsp(Hex(named)); + Check(n && n->alpha == "KPN" && n->validity == 0xFF, "EF_SMSP with an alpha identifier"); + Check(!ParseSmsp(Hex("FFFF")), "a short record"); + Check(!ParseSmsp(Hex(std::string(30, 'F') + "EF" + std::string(24, 'F') + std::string(KpnSc) + std::string(8, 'F') + "FFFFA9")), "TP-SCA marked absent"); + Check(!ParseSmsp(Hex(std::string(30, 'F') + "ED" + std::string(24, 'F') + "FF911356131313F3" + std::string(8, 'F') + "FFFFA9")), "an unused TP-SCA"); + + const std::string qmicli = + "[qrtr://0] Successfully read information from the UIM:\n" + "Card result:\n\tSW1: '0x90'\n\tSW2: '0x00'\n" + "Read result:\n\tFF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:ED:FF:FF:FF:FF:FF:FF:FF:FF:FF:FF:\n" + "\tFF:FF:07:91:13:56:13:13:13:F3:FF:FF:FF:FF:FF:FF:A9\n"; + auto b = ParseQmicliReadResult(qmicli); + Check(b.size() == 43, "qmicli's hex dump: 43 bytes"); + auto q = ParseSmsp(b); + Check(q && q->scNumber == "+31653131313", "EF_SMSP straight from qmicli's output"); + Check(ParseQmicliReadResult("error: couldn't read").empty(), "no marker: no bytes"); + } +} + +int main() { + TestAlphabet(); + TestAddresses(); + TestSubmit(); + TestDeliver(); + TestReassembly(); + TestHeaderAndDcs(); + TestReports(); + TestRp(); + TestSmsp(); + if (Failures == 0) std::println("Sms: all tests passed"); + return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that +}