sip, engine: the SMS over IP transactions as reducers

TS 24.341 has a submission travel as a MESSAGE with the RP-DATA, answered
with a final and then with the submit report in a MESSAGE of the
IP-SM-GW's own, and a delivery arrive as a MESSAGE with the RP-DATA to be
answered and acknowledged with an RP-ACK in a MESSAGE of ours. Two
pure reducers carry that, in the shape CallMachine has: SmsOutbound takes
one message of ours segment by segment — the MESSAGE, its final (a 32 s
wait, which a provisional starts over), the RP-ACK or RP-ERROR matched by
In-Reply-To, else by RP-MR (within 40 s of the final, a length TR1M may
have),
then the next segment with the next RP-MR and TP-MR — and ends it
as sent or failed, its State action carrying the reason; OnSmsMessage turns an
inbound MESSAGE into its final, the message or status report it carried
and the delivery report to send, 488 for a
submit report In-Reply-To no MESSAGE of ours in flight — one that is not
ours (5.3.1.2), or ours once the message has ended (its report's wait
run out, judged by the reducer's caller; a failure; sent) or its segment
was superseded by the next, which gets the same answer — an RP-ERROR for
a TPDU that is
unusable (a delivery or a status report that does not parse, or one of
the submit-report type), and a 200 with a log line for what it makes
nothing of: a MESSAGE whose Content-Type does not contain the SMS one, a
body that is no RP message, a submit report without In-Reply-To for no
message in flight. Imsd:Sip gains
HeaderUri, the URI of a header's first element, a quoted display name
before it passed over (none when that URI holds an ASCII control
character, a space, `<`, `>` or `"`: it goes into a request line), and
Body, moved out of CallMachine (its four call sites and the shell's
NOTIFY/MESSAGE branch follow).

No retransmission (TS 23.040 9.2.3.6's repeat with TP-RD is not done):
an unanswered MESSAGE or a report that never comes fails the message.
RecentTransactions, the reducer, keys a request by Call-ID, CSeq and Via
branch — the value of the first `branch=` of its first Via line; a
request with none or an empty one is not remembered — and gives back the
final remembered for it within 32 s (TimerJ, on every transport) — what
a caller needs to answer a retransmitted request again and not handle
it again (RFC 3261 17.2.2); without it a repeated RP-DATA would be
handled again: a second delivery report where the first got one and, of
a text in one segment, a second Received.

Every final OnSmsMessage gives an inbound MESSAGE — the 200, the 488 —
goes through BuildResponse: each Via: line echoed, the To echoed with a
tag minted for the request unless it holds `tag=` (RFC 3261 8.2.6.2).

tests/Engine drives both reducers through the dialogs above and the
retransmission table; tests/Sip pins the two helpers.

OnSmsMessage's header reads — the delivery report's target
(P-Asserted-Identity, else From) among them — go through the text
layer, which ends at the header section: a body line may spell a header
name (a text, or UCS-2 bytes that do) and must pick nothing. Pinned with
an 8-bit SMS-DELIVER whose data spells a P-Asserted-Identity line.

A UCS-2 surrogate pair a sender split across two segments comes out
whole in the Received action OnSmsMessage returns (the codec decodes a
set from its joined units); pinned.

Pinned as well: a submit report that arrives before the MESSAGE's own
final is taken (the message sent, or the next segment out under its own
Call-ID, and the late final nobody's), a text past 255 segments fails at
once naming the fit, and a delivery with no P-Asserted-Identity and no
From URI is handed over with no delivery report to send. A submit report
whose In-Reply-To lists Call-IDs (RFC 3261 20.21) is ours when ours is
among them, and a delivered MESSAGE's Call-ID with an ASCII control
character or a space in it is not written into the delivery report's
In-Reply-To.
This commit is contained in:
Jorijn van der Graaf 2026-10-16 23:20:56 +02:00
commit 4de5f0be45
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
6 changed files with 917 additions and 23 deletions

View file

@ -39,13 +39,13 @@ PipeWire. The verified device/carrier combinations are in the README.
| `project.cpp` | The canonical build description, for [Crafter Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build). Chooses the product by `--product=`. | | `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 nine 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-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 (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped), status codes, the granted lifetime, `ResponseOf` transaction matching. Not a full RFC 3261 parser, deliberately. | | `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), 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-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-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-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-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; `tests/Messages` is their suite, which calls every builder but `BuildInviteResponse` (`tests/Engine` checks the responses `CallMachine` builds with it). Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, a final for an inbound request outside a call — each `Via:` line echoed in order (the text layer reads long header names only, not RFC 3261 7.3.3's compact forms) and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); the 488 and a 200 pinned — and `ScPsi`, the service centre's PSI from its international number, never a dialled-number guess. | | `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; `tests/Messages` is their suite, which calls every builder but `BuildInviteResponse` (`tests/Engine` checks the responses `CallMachine` builds with it). Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final `OnSmsMessage` builds for the MESSAGE it is handed (the 200, the 488): each `Via:` line echoed in order (the text layer reads long header names only, not RFC 3261 7.3.3's compact forms) and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. |
| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell) and `RegRecovery` (the registration recovery policy, §7.4). | | `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (TS 24.341): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (the final remembered for an inbound request by Call-ID, CSeq and Via branch — the value of the first `branch=` of its first `Via:` line; nothing is remembered for a request with none or an empty one — for 32 s (`TimerJ`), for a caller to answer a retransmission with it and not handle it again). |
| `interfaces/Imsd-Qmi.cppm` | `imsd::qmi` — the QMI WDS request bytes `imsd-pcscf` sends (Bind Mux Data Port, Set IP Family, Get Packet Service Status, Get Current Settings, Get Profile Settings), the message/TLV parser, the P-CSCF list readers (0x22 flag, 0x23 IPv4, 0x24 FQDN, 0x2E IPv6 — the last one libqmi does not model). | | `interfaces/Imsd-Qmi.cppm` | `imsd::qmi` — the QMI WDS request bytes `imsd-pcscf` sends (Bind Mux Data Port, Set IP Family, Get Packet Service Status, Get Current Settings, Get Profile Settings), the message/TLV parser, the P-CSCF list readers (0x22 flag, 0x23 IPv4, 0x24 FQDN, 0x2E IPv6 — the last one libqmi does not model). |
| `interfaces/ImsdBus.cppm` | `imsd::bus` — the polkit gate in front of call control, shared by imsd and imsd-ofonod. GLib, so outside `imsd-core`. | | `interfaces/ImsdBus.cppm` | `imsd::bus` — the polkit gate in front of call control, shared by imsd and imsd-ofonod. GLib, so outside `imsd-core`. |
| `implementations/main.cpp` | The `imsd` daemon shell: GLib main loop, GDBus service, sockets, subprocesses, the registration sequence and the run loop that pumps the core. | | `implementations/main.cpp` | The `imsd` daemon shell: GLib main loop, GDBus service, sockets, subprocesses, the registration sequence and the run loop that pumps the core. |
@ -289,8 +289,8 @@ What the suites pin:
keepalive discards, a header read that stops at the first empty line — a keepalive discards, a header read that stops at the first empty line — a
body line spelling a header name picks nothing, leading empty lines are body line spelling a header name picks nothing, leading empty lines are
skipped), `ResponseOf`, refused finals with reason headers, skipped), `ResponseOf`, refused finals with reason headers,
reginfo documents. A change that flips one of those tests is a behaviour reginfo documents, `HeaderUri` and `Body`. A change that flips one of
change, not a cleanup. those tests is a behaviour change, not a cleanup.
- `Sdp` — the offer's exact bytes, the parser (the telephone-event payload - `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 type at the chosen codec's clock among it), `BuildAnswer` at the offer's
own payload types and octet-align mode, the `CODECS` override. own payload types and octet-align mode, the `CODECS` override.
@ -327,7 +327,28 @@ What the suites pin:
`RegRecovery` (thresholds, backoffs, the throttle `RegRecovery` (thresholds, backoffs, the throttle
schedule, Retry-After, which waits a Dial may cut short, when the old schedule, Retry-After, which waits a Dial may cut short, when the old
registration counts as gone, the holds a restart takes over, a binding the registration counts as gone, the holds a restart takes over, a binding the
network terminated). network terminated); and SMS over IP (TS 24.341): `SmsOutbound` through a
submission — the MESSAGE with the RP-DATA to the SC's PSI, its 202, the
RP-ACK ending it as sent with the SC's time stamp; a refused final; an
RP-ERROR with its cause and TP-FCS; the final's wait and the report's running out; a
failed send; two segments with consecutive RP-MR/TP-MR, the second sent
on the first's RP-ACK; a destination that is no number; no service
centre — and `OnSmsMessage`: a delivered message to the bus and its
RP-ACK to the IP-SM-GW with In-Reply-To, a concatenated pair handed over
once whole and each segment acknowledged, a status report, a submit
report routed to the message in flight (by In-Reply-To, else RP-MR), 488
for one In-Reply-To no MESSAGE of ours in flight (a stranger's; ours once
ended; ours once its segment was superseded), 200 for one without
In-Reply-To for no message, an unusable TPDU acknowledged with an
RP-ERROR, a body that is no RP message, a page-mode text 200'd and
logged;
a submit report before the MESSAGE's own final taken — the message sent
and the late final nobody's; with two segments the second goes out under
its own Call-ID — a text past 255 segments failed at once naming the fit,
a delivery with no gateway for its report handed over with the absence
logged;
and `RecentTransactions`: a retransmitted request gets its final again,
for 32 s (`TimerJ`); no branch, no match.
Rules: Rules:

View file

@ -2448,10 +2448,7 @@ private:
// journal is the only place the payload survives until real SMSoIP // journal is the only place the payload survives until real SMSoIP
// handling exists. // handling exists.
if (method == "NOTIFY" || method == "MESSAGE") { if (method == "NOTIFY" || method == "MESSAGE") {
std::size_t at = msg.find("\r\n\r\n"); std::string_view body = imsd::sip::Body(msg);
std::string_view body = at == std::string::npos
? std::string_view{}
: std::string_view(msg).substr(at + 4);
if (method == "MESSAGE") Log(std::format("MESSAGE from {} ({} bytes):\n{}", imsd::sip::CallerId(msg), body.size(), body)); if (method == "MESSAGE") Log(std::format("MESSAGE from {} ({} bytes):\n{}", imsd::sip::CallerId(msg), body.size(), body));
else if (auto ev = imsd::sip::Header(msg, "Event"); ev && ev->starts_with("reg")) { else if (auto ev = imsd::sip::Header(msg, "Event"); ev && ev->starts_with("reg")) {
Log(std::format("reg-event NOTIFY ({} bytes):\n{}", body.size(), body)); Log(std::format("reg-event NOTIFY ({} bytes):\n{}", body.size(), body));

View file

@ -4,8 +4,8 @@
// lint-disable-file fixed-width-types // lint-disable-file fixed-width-types
/* /*
Imsd:Engine — the daemon's decisions as pure reducers: the call state Imsd:Engine — the daemon's decisions as pure reducers: the call state
machine (CallMachine) and the registration recovery policy (RegRecovery, machine (CallMachine), the registration recovery policy (RegRecovery,
its own section below). its own section below) and SMS over IP's (the last paragraph here).
A CallMachine owns one call's SIP dialog, outgoing or incoming. It never A CallMachine owns one call's SIP dialog, outgoing or incoming. It never
touches a socket, a clock, or a subprocess: each event (the INVITE's touches a socket, a clock, or a subprocess: each event (the INVITE's
@ -26,7 +26,17 @@ unit-testable against recorded network dialogs with no I/O (tests/Engine).
State/reason strings are the frozen D-Bus vocabulary the dialer maps on State/reason strings are the frozen D-Bus vocabulary the dialer maps on
(dialing/ringing/incoming/active/terminated; outgoing/incoming/accepted/ (dialing/ringing/incoming/active/terminated; outgoing/incoming/accepted/
local-hangup/remote-hangup/refused-or-busy/error). Pure std C++. local-hangup/remote-hangup/refused-or-busy/error).
SMS over IP (TS 24.341) has its own reducers at the end: SmsOutbound, one
short message of ours on its way to the service centre segment by segment
(the MESSAGE with the RP-DATA, its final, the submit report that comes
back in a MESSAGE of its own), and OnSmsMessage, what an inbound
MESSAGE outside a call's dialog leads to (the final for it, the message or
status report it delivered, the delivery report to send), with
RecentTransactions (a retransmitted request within 32 s gets its final
again and is not handled again; one whose first Via line has no
`branch=`, or an empty one, is never taken for a copy). Pure std C++.
*/ */
export module Imsd:Engine; export module Imsd:Engine;
@ -34,6 +44,7 @@ import std;
import :Util; import :Util;
import :Sip; import :Sip;
import :Sdp; import :Sdp;
import :Sms;
import :Messages; import :Messages;
export namespace imsd::engine { export namespace imsd::engine {
@ -375,7 +386,7 @@ export namespace imsd::engine {
auto rr = imsd::sip::Headers(invite_, "Record-Route"); auto rr = imsd::sip::Headers(invite_, "Record-Route");
for (std::size_t i = rr.size(); i-- > 0;) for (std::size_t i = rr.size(); i-- > 0;)
d_.recordRoute.emplace_back(rr[i]); d_.recordRoute.emplace_back(rr[i]);
answerSdp_ = std::string(Body(invite_)); // the caller's offer answerSdp_ = std::string(imsd::sip::Body(invite_)); // the caller's offer
nextCseq_ = 0; // our first in-dialog request gets CSeq 1 nextCseq_ = 0; // our first in-dialog request gets CSeq 1
} }
@ -544,7 +555,7 @@ export namespace imsd::engine {
std::string_view method = Method(msg); std::string_view method = Method(msg);
if (method == "ACK") if (method == "ACK")
return a; // ACK is never responded to (RFC 3261 17.1.1.2) return a; // ACK is never responded to (RFC 3261 17.1.1.2)
std::string_view body = Body(msg); std::string_view body = imsd::sip::Body(msg);
if (body.contains("m=audio")) answerSdp_ = std::string(body); if (body.contains("m=audio")) answerSdp_ = std::string(body);
if (direction_ == Direction::Incoming && state_ == CallState::Incoming) { if (direction_ == Direction::Incoming && state_ == CallState::Incoming) {
if (method == "CANCEL") { if (method == "CANCEL") {
@ -782,7 +793,7 @@ export namespace imsd::engine {
std::optional<bool> FallbackTo(int code, std::string_view msg) const { std::optional<bool> FallbackTo(int code, std::string_view msg) const {
if (userCancelled_) return std::nullopt; if (userCancelled_) return std::nullopt;
if (attemptSos_) return plainTried_ ? std::nullopt : std::optional(false); if (attemptSos_) return plainTried_ ? std::nullopt : std::optional(false);
if (code == 380 && !sosTried_ && Body(msg).contains("emergency")) return true; if (code == 380 && !sosTried_ && imsd::sip::Body(msg).contains("emergency")) return true;
return std::nullopt; return std::nullopt;
} }
@ -799,11 +810,6 @@ export namespace imsd::engine {
return a; return a;
} }
static std::string_view Body(std::string_view msg) {
std::size_t at = msg.find("\r\n\r\n");
return at == std::string_view::npos ? std::string_view{}
: msg.substr(at + 4);
}
static std::string_view Method(std::string_view msg) { static std::string_view Method(std::string_view msg) {
std::size_t sp = msg.find(' '); std::size_t sp = msg.find(' ');
return sp == std::string_view::npos ? msg : msg.substr(0, sp); return sp == std::string_view::npos ? msg : msg.substr(0, sp);
@ -827,7 +833,7 @@ export namespace imsd::engine {
d_.recordRoute.emplace_back(v); d_.recordRoute.emplace_back(v);
} }
if (auto ct = imsd::sip::Header(msg, "Contact")) d_.remoteTarget = AngleUri(*ct); if (auto ct = imsd::sip::Header(msg, "Contact")) d_.remoteTarget = AngleUri(*ct);
std::string_view body = Body(msg); std::string_view body = imsd::sip::Body(msg);
if (body.contains("m=audio")) answerSdp_ = std::string(body); if (body.contains("m=audio")) answerSdp_ = std::string(body);
} }
@ -905,4 +911,429 @@ export namespace imsd::engine {
into.push_back(std::move(m)); into.push_back(std::move(m));
} }
}; };
// ---- SMS over IP (TS 24.341) -----------------------------------------
//
// A short message rides a SIP MESSAGE with an RP message of TS 24.011
// as its body. Submitting one (5.3.1.2): a MESSAGE with the RP-DATA to
// the service centre's PSI, answered with a final (after a 2xx the
// submit report is awaited), then the submit report — an RP-ACK or RP-ERROR
// — in a MESSAGE of its own, In-Reply-To naming ours, which
// we answer 200. Receiving one (5.3.2.3, 5.3.2.4): a MESSAGE with the
// RP-DATA, which we answer 200 at once, then our delivery report — an RP-ACK
// with the SMS-DELIVER-REPORT — in a MESSAGE of our own to the
// IP-SM-GW (the delivered MESSAGE's P-Asserted-Identity), In-Reply-To
// naming it (a Call-ID with an ASCII control character or a space in
// it is not written). The same bytes as over NAS; the SIP legs are the
// reducers' here, the sockets and the clock the shell's.
// A short message the network delivered, as the bus reports it.
struct SmsReceived {
std::string from; // the sender: a number ("+316…", a short code) or an alphanumeric name
std::string text; // the text, UTF-8 (empty for 8-bit data)
std::vector<std::uint8_t> data; // 8-bit data (an application-port message)
std::string scts; // the service centre's time stamp (ScTimeStamp's text)
std::string sc; // the service centre (RP-Originator Address)
std::optional<int> msgClass; // 0: a flash message; 2: meant for the (U)SIM
std::optional<std::uint16_t> portDst; // application port addressing
std::optional<std::uint16_t> portSrc;
bool messageWaiting = false; // a message-waiting indication group, of any type, set or cleared (`dcs` has which)
std::uint8_t pid = 0;
std::uint8_t dcs = 0;
int segments = 1; // the segments a concatenated message came in
std::vector<std::uint8_t> tpdu; // the SMS-DELIVER as received — of a concatenated message, the segment that completed the set (the last to arrive)
};
struct SmsAction {
enum class Type {
SendClient, // send `text` on the client flow (a MESSAGE of ours)
SendResponse, // answer the inbound MESSAGE being handled with `text`
Received, // hand `received` to the bus
StatusReport, // `report`: the SC's word on a message we sent (matched by TP-MR by the shell)
State, // emit StateChanged(id, `state`, `reason`) for a message of ours
Log,
};
Type type;
std::string text;
std::string id, state, reason;
SmsReceived received;
imsd::sms::StatusReport report;
};
// The waits (TS 24.011 10: TR1M; TS 24.341 5.3.1.1 NOTE 1 has it
// exceed SIP timer F): a MESSAGE's final within 32 s
// of the MESSAGE or of its latest provisional, which starts the wait
// over; the submit report within 40 s of the final — a length TR1M may
// have, though 6.3.1 sets TR1M when the RP-DATA is transferred.
inline constexpr double SmsSendTimeout = 32.0;
inline constexpr double SmsReportTimeout = 40.0;
// What the bus hears: `sent` once every segment's submit report is
// in, `failed` with the reason otherwise.
inline constexpr std::string_view SmsStateSent = "sent";
inline constexpr std::string_view SmsStateFailed = "failed";
// One short message of ours on its way to the service centre, segment
// by segment: the MESSAGE with the segment's RP-DATA, its final, the
// submit report, then the next segment. RP-MR and TP-MR count up from
// the values the shell hands over (TS 23.040 9.2.3.6, 9.2.3.24.1; the
// shell keeps the counters across messages). No retransmission: an
// unanswered MESSAGE or a report that never comes fails the message
// (TS 23.040 9.2.3.6's automatic repeat with TP-RD is not done) and
// the bus hears why.
class SmsOutbound {
public:
struct Params {
std::string number; // the destination as typed
std::string text;
std::string scTarget; // the SC's PSI as a SIP URI (the Request-URI and To)
std::vector<std::uint8_t> scAddress; // the SC as the RP-DATA's destination: [octets][toa][digits]
std::uint8_t tpMr = 0; // the first segment's TP-MR
std::uint8_t rpMr = 0; // the first segment's RP-MR
std::uint8_t concatRef = 0; // the concatenation reference when the text needs segments
std::optional<std::uint8_t> validity; // TP-VP, relative (EF_SMSP's)
bool statusReport = false; // ask the SC for a status report (TP-SRR)
};
enum class Phase { Idle, Sending, AwaitingReport, Done };
SmsOutbound(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string id, Params p)
: ctx_(ctx), rng_(rng), id_(std::move(id)), p_(std::move(p)) {}
const std::string& Id() const { return id_; }
Phase State() const { return phase_; }
bool Done() const { return phase_ == Phase::Done; }
// the engine's clock reading at which OnDeadline is due (0: none)
double Deadline() const { return deadline_; }
// the TP-MRs the segments went out with, for the shell to match a
// later status report to this message
const std::vector<std::uint8_t>& TpMrs() const { return tpMrs_; }
std::size_t Segments() const { return tpdus_.size(); }
// Builds the segments and sends the first. A destination that is
// no number, or a text past 255 segments, fails the message at once.
std::vector<SmsAction> Start(double now) {
std::vector<SmsAction> out;
imsd::sms::Submit s{p_.number, p_.tpMr, p_.validity, p_.statusReport};
tpdus_ = imsd::sms::BuildSubmits(s, p_.text, p_.concatRef);
if (tpdus_.empty()) {
phase_ = Phase::Done;
out.push_back(Fail(imsd::sms::Address::ForNumber(p_.number) ? "the text does not fit 255 segments" : std::format("'{}' is not a number", p_.number)));
return out;
}
if (p_.scAddress.empty() || p_.scTarget.empty()) {
phase_ = Phase::Done;
tpdus_.clear();
out.push_back(Fail("no service centre (none from SMSC= or EF_SMSP)"));
return out;
}
for (std::size_t i = 0; i < tpdus_.size(); i++) tpMrs_.push_back(static_cast<std::uint8_t>((p_.tpMr + i) & 0xFF));
SendSegment(out, now);
return out;
}
// The segment in flight's MESSAGE: its final is matched by Call-ID
// and CSeq.
bool OwnsResponse(std::string_view msg) const {
return phase_ == Phase::Sending && imsd::sip::ResponseOf(msg, callid_, "1 MESSAGE");
}
std::vector<SmsAction> OnResponse(std::string_view msg, int status, double now) {
std::vector<SmsAction> out;
if (phase_ != Phase::Sending) return out;
if (status < 200) {
deadline_ = now + SmsSendTimeout;
return out;
}
if (status >= 300) {
phase_ = Phase::Done;
out.push_back(Fail(std::format("segment {}/{} refused: {}", seg_ + 1, tpdus_.size(), imsd::sip::RefusalSummary(msg))));
return out;
}
phase_ = Phase::AwaitingReport;
deadline_ = now + SmsReportTimeout;
out.push_back(LogAct(std::format("sms {}: segment {}/{} -> {}; awaiting the submit report", id_, seg_ + 1, tpdus_.size(), status)));
return out;
}
// Whether an RP-ACK/RP-ERROR the IP-SM-GW sent is this segment's:
// In-Reply-To names our MESSAGE (TS 24.341 5.3.1.2), or — from an
// IP-SM-GW that sends none — the RP-MR is the one in flight. A
// report arriving before the MESSAGE's own final (the IP-SM-GW's
// order is its own) is taken as well.
bool OwnsReport(std::string_view inReplyTo, std::optional<std::uint8_t> rpMr) const {
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return false;
if (!inReplyTo.empty()) { // a list of Call-IDs (RFC 3261 20.21): ours among them
for (auto part : std::views::split(inReplyTo, ','))
if (imsd::sip::Trim(std::string_view(part.begin(), part.end())) == callid_) return true;
return false;
}
return rpMr && *rpMr == CurrentRpMr();
}
// The submit report for the segment in flight: an RP-ACK moves to
// the next segment, or ends the message as sent; an RP-ERROR fails
// it with its cause. The shell answers the report's MESSAGE
// itself.
std::vector<SmsAction> OnReport(const imsd::sms::Rp& rp, double now) {
std::vector<SmsAction> out;
if (phase_ != Phase::AwaitingReport && phase_ != Phase::Sending) return out;
if (rp.type == imsd::sms::RpType::ErrorMt) {
phase_ = Phase::Done;
std::string why = std::format("segment {}/{} refused by the SC: RP cause {} ({})", seg_ + 1, tpdus_.size(), rp.cause.value_or(0), imsd::sms::RpCauseText(rp.cause.value_or(0)));
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, true); r && r->failureCause)
why += std::format(", TP-FCS 0x{:02x} ({})", *r->failureCause, imsd::sms::FailureCauseText(*r->failureCause));
out.push_back(Fail(why));
return out;
}
if (rp.type != imsd::sms::RpType::AckMt) return out;
if (auto r = imsd::sms::ParseSubmitReport(rp.tpdu, false); r && !r->scts.empty()) scts_ = r->scts;
seg_++;
if (seg_ < tpdus_.size()) { SendSegment(out, now); return out; }
phase_ = Phase::Done;
deadline_ = 0;
out.push_back(StateAct(SmsStateSent, scts_.empty() ? std::format("{} segment(s) accepted by the SC", tpdus_.size()) : std::format("{} segment(s) accepted by the SC at {}", tpdus_.size(), scts_)));
return out;
}
// The wait ran out: no final to the MESSAGE, or no submit report.
std::vector<SmsAction> OnDeadline() {
std::vector<SmsAction> out;
if (phase_ == Phase::Sending) {
phase_ = Phase::Done;
out.push_back(Fail(std::format("no answer to the MESSAGE of segment {}/{} within {:.0f} s", seg_ + 1, tpdus_.size(), SmsSendTimeout)));
} else if (phase_ == Phase::AwaitingReport) {
phase_ = Phase::Done;
out.push_back(Fail(std::format("no submit report for segment {}/{} within {:.0f} s of the final", seg_ + 1, tpdus_.size(), SmsReportTimeout)));
}
deadline_ = 0;
return out;
}
// The MESSAGE could not be sent (the flow is down).
std::vector<SmsAction> OnSendFailed() {
std::vector<SmsAction> out;
phase_ = Phase::Done;
deadline_ = 0;
out.push_back(Fail(std::format("segment {}/{} not sent: the flow to the P-CSCF is down", seg_ + 1, tpdus_.size())));
return out;
}
private:
std::uint8_t CurrentRpMr() const { return static_cast<std::uint8_t>((p_.rpMr + seg_) & 0xFF); }
void SendSegment(std::vector<SmsAction>& out, double now) {
callid_ = std::format("{}@{}", rng_.Token(16), ctx_.local);
std::vector<std::uint8_t> rp = imsd::sms::BuildRpData(CurrentRpMr(), p_.scAddress, tpdus_[seg_]);
out.push_back(SmsAction{SmsAction::Type::SendClient, imsd::msg::BuildMessageSms(ctx_, p_.scTarget, callid_, rng_.Token(8), rng_.Token(16), rp)});
out.push_back(LogAct(std::format("sms {}: segment {}/{} to {} via {}: MESSAGE sent (RP-MR {}, TP-MR {}, {} bytes)", id_, seg_ + 1, tpdus_.size(), p_.number, p_.scTarget, CurrentRpMr(), tpMrs_[seg_], tpdus_[seg_].size())));
phase_ = Phase::Sending;
deadline_ = now + SmsSendTimeout;
}
SmsAction Fail(std::string why) {
deadline_ = 0;
return StateAct(SmsStateFailed, std::move(why));
}
SmsAction StateAct(std::string_view state, std::string reason) {
SmsAction a{SmsAction::Type::State};
a.id = id_;
a.state = std::string(state);
a.reason = std::move(reason);
return a;
}
static SmsAction LogAct(std::string text) { return SmsAction{SmsAction::Type::Log, std::move(text)}; }
const imsd::msg::Context& ctx_;
imsd::util::Rng& rng_;
std::string id_;
Params p_;
std::vector<std::vector<std::uint8_t>> tpdus_;
std::vector<std::uint8_t> tpMrs_;
std::size_t seg_ = 0;
std::string callid_; // the segment in flight's MESSAGE
std::string scts_; // the SC's time stamp from the last RP-ACK's submit report
Phase phase_ = Phase::Idle;
double deadline_ = 0;
};
// ---- retransmitted requests (RFC 3261 17.2.2) ------------------------
// A request whose Via branch (the value of the first `branch=` of its
// first Via line), Call-ID and CSeq match one we already answered is
// taken for a retransmission — a key of imsd's own, where 17.2.3 matches
// by branch, sent-by and method: the server transaction gives the same
// final again and does nothing else, for 32 s after the final (Timer J
// on an unreliable transport; here on every transport). Used for
// MESSAGE (TS 24.341): a delivery came twice within a second (KPN,
// 2026-10-17 01:23) and the copy became a second text and a second
// delivery report; one of the two was refused with 488.
class RecentTransactions {
public:
static constexpr double TimerJ = 32.0;
// "<Call-ID>|<CSeq>|<branch>" of a request, the branch what follows the
// first `branch=` of its first Via line up to a `;`, a `,` or white
// space; empty when that is nothing (then nothing is remembered or matched).
static std::string Key(std::string_view request) {
auto via = imsd::sip::Header(request, "Via");
if (!via) return {};
const std::size_t b = via->find("branch=");
if (b == std::string_view::npos) return {};
std::string_view branch = via->substr(b + 7);
branch = branch.substr(0, branch.find_first_of(";, \t"));
if (branch.empty()) return {};
return std::format("{}|{}|{}", imsd::sip::Header(request, "Call-ID").value_or(""), imsd::sip::Header(request, "CSeq").value_or(""), branch);
}
// The final we gave this request before, when it is a retransmission.
std::optional<std::string> Repeat(std::string_view key, double now) {
Purge(now);
if (key.empty()) return std::nullopt;
auto it = seen_.find(std::string(key));
if (it == seen_.end()) return std::nullopt;
return it->second.response;
}
void Remember(std::string key, std::string response, double now) {
if (key.empty()) return;
seen_[std::move(key)] = Entry{std::move(response), now};
}
void Purge(double now) {
for (auto it = seen_.begin(); it != seen_.end();) {
if (now - it->second.at > TimerJ) it = seen_.erase(it);
else ++it;
}
}
std::size_t Size() const { return seen_.size(); }
private:
struct Entry { std::string response; double at; };
std::map<std::string, Entry> seen_;
};
// What an inbound MESSAGE leads to.
struct SmsInbound {
std::string response; // the final for it (always set)
std::vector<SmsAction> actions; // what it delivered, and the delivery report to send
std::string reportCallId; // the delivery report MESSAGE's Call-ID (empty: none sent)
std::optional<imsd::sms::Rp> rp; // the RP message it carried
};
// An inbound MESSAGE (TS 24.341 5.3.2.3, 5.3.1.2, 5.3.1.3). An RP-DATA
// with an SMS-DELIVER is answered 200, handed to the reassembler and,
// whole, to the bus, and acknowledged with an RP-ACK carrying the
// SMS-DELIVER-REPORT in a MESSAGE to the IP-SM-GW; one with an
// SMS-STATUS-REPORT is acknowledged the same way and the report handed
// over for the shell to match; one whose TPDU is unusable is
// acknowledged with an RP-ERROR (cause 96, TP-FCS "TPDU not supported")
// and logged — each report to the delivered MESSAGE's P-Asserted-Identity,
// else its From; one that gives neither URI gets none, which is logged.
// An RP-ACK/RP-ERROR is a submit report: the message in
// flight (`outbound`) takes it and the MESSAGE is answered 200; one the
// message in flight does not own is answered 488 when its In-Reply-To is
// not empty, else 200 and logged. A MESSAGE whose Content-Type
// does not contain the SMS one, or whose body is no RP message, is
// answered 200 and logged (the journal keeps what the 200 acknowledged).
SmsInbound OnSmsMessage(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string_view message, imsd::sms::Reassembler& reassembler, SmsOutbound* outbound, double now) {
using imsd::sms::RpType;
SmsInbound r;
const std::string toTag = rng.Token(10); // the To tag for the finals we give this request (RFC 3261 8.2.6.2; BuildResponse adds it unless the To holds `tag=`)
r.response = imsd::msg::BuildResponse(ctx, message, 200, "OK", toTag);
std::string_view body = imsd::sip::Body(message);
std::string ctype(imsd::sip::Header(message, "Content-Type").value_or(""));
for (char& c : ctype) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
// the delivery report's In-Reply-To: a Call-ID with an ASCII control
// character or a space in it is not written into a request of ours
std::string callid(imsd::sip::Header(message, "Call-ID").value_or(""));
if (std::ranges::any_of(callid, [](unsigned char c) { return c <= 0x20 || c == 0x7F; })) callid.clear();
const std::string from = imsd::sip::CallerId(message);
if (!ctype.contains(imsd::msg::SmsContentType)) {
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("MESSAGE from {} ({}, {} bytes):\n{}", from, ctype.empty() ? "no content type" : ctype, body.size(), body)});
return r;
}
std::span<const std::uint8_t> bytes(reinterpret_cast<const std::uint8_t*>(body.data()), body.size()); // lint-disable-line no-char-pointer
r.rp = imsd::sms::ParseRp(bytes, true);
if (!r.rp) {
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("MESSAGE from {} with {} bytes that are no RP message: {}", from, body.size(), imsd::util::ToHex(bytes))});
return r;
}
const imsd::sms::Rp& rp = *r.rp;
if (rp.type == RpType::AckMt || rp.type == RpType::ErrorMt) {
std::string inReplyTo; // every In-Reply-To row: the rows are one list (RFC 3261 7.3.1)
for (std::string_view row : imsd::sip::Headers(message, "In-Reply-To")) inReplyTo.append(inReplyTo.empty() ? "" : ",").append(row);
if (outbound && outbound->OwnsReport(inReplyTo, rp.mr)) {
r.actions = outbound->OnReport(rp, now);
return r;
}
if (!inReplyTo.empty()) {
r.response = imsd::msg::BuildResponse(ctx, message, 488, "Not Acceptable Here", toTag);
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}) In-Reply-To {}: no MESSAGE of ours in flight; 488", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", inReplyTo)});
return r;
}
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("submit report ({}, RP-MR {}) for no message in flight; 200", rp.type == RpType::AckMt ? "RP-ACK" : "RP-ERROR", rp.mr)});
return r;
}
// what is left is an RP-DATA: ParseRp gave one of the network's three
// types, and the two reports have returned above
// the delivery report goes where the delivered MESSAGE came from:
// its P-Asserted-Identity (5.3.2.4 NOTE 1), else its From
std::string gateway = imsd::sip::HeaderUri(message, "P-Asserted-Identity").value_or(imsd::sip::HeaderUri(message, "From").value_or(""));
auto report = [&](std::vector<std::uint8_t> body, std::string_view what) {
if (gateway.empty()) {
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("no P-Asserted-Identity or From URI on the delivered MESSAGE: no {} sent", what)});
return;
}
r.reportCallId = std::format("{}@{}", rng.Token(16), ctx.local);
r.actions.push_back(SmsAction{SmsAction::Type::SendClient, imsd::msg::BuildMessageSms(ctx, gateway, r.reportCallId, rng.Token(8), rng.Token(16), body, callid)});
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("{} (RP-MR {}) -> {}", what, rp.mr, gateway)});
};
const std::string sc = rp.sc ? rp.sc->Number() : std::string();
switch (imsd::sms::KindOfTpdu(rp.tpdu)) {
case imsd::sms::TpduKind::StatusReport: {
auto sr = imsd::sms::ParseStatusReport(rp.tpdu);
if (!sr) break;
SmsAction a{SmsAction::Type::StatusReport};
a.report = *sr;
r.actions.push_back(a);
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("status report from {}: TP-MR {} to {}: {} (discharged {})", sc, sr->mr, sr->recipient.Number(), imsd::sms::StatusText(sr->status), sr->dischargeTime)});
report(imsd::sms::BuildRpAck(rp.mr, imsd::sms::DeliverReportAck()), "delivery report RP-ACK");
return r;
}
case imsd::sms::TpduKind::Deliver:
case imsd::sms::TpduKind::Reserved: {
auto d = imsd::sms::ParseDeliver(rp.tpdu);
if (!d) break;
const bool concat = d->ud.header.concat.has_value();
const int total = concat ? d->ud.header.concat->total : 1;
const int seq = concat ? d->ud.header.concat->seq : 1;
std::string segment = concat ? std::format(", segment {}/{} of set {}", seq, total, d->ud.header.concat->ref) : std::string();
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("short message from {} via {} at {}{}: {} ({} bytes)", d->from.Number(), sc, d->scts, segment, d->ud.alphabet == imsd::sms::Alphabet::Octet ? "8-bit data" : "text", rp.tpdu.size())});
if (auto whole = reassembler.Add(*d, now)) {
SmsAction a{SmsAction::Type::Received};
a.received.from = whole->from.Number();
a.received.text = whole->ud.text;
a.received.data = whole->ud.data;
a.received.scts = whole->scts;
a.received.sc = sc;
a.received.msgClass = whole->coding.msgClass;
a.received.portDst = whole->ud.header.portDst;
a.received.portSrc = whole->ud.header.portSrc;
a.received.messageWaiting = whole->coding.messageWaiting;
a.received.pid = whole->pid;
a.received.dcs = whole->dcs;
a.received.segments = total;
a.received.tpdu = rp.tpdu;
r.actions.push_back(std::move(a));
}
report(imsd::sms::BuildRpAck(rp.mr, imsd::sms::DeliverReportAck()), "delivery report RP-ACK");
return r;
}
case imsd::sms::TpduKind::SubmitReport:
break;
}
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("RP-DATA from {} whose TPDU is unusable ({} bytes: {}): RP-ERROR", sc, rp.tpdu.size(), imsd::util::ToHex(rp.tpdu))});
report(imsd::sms::BuildRpError(rp.mr, imsd::sms::RpCauseInvalidMandatoryInformation, imsd::sms::DeliverReportError(imsd::sms::FcsTpduNotSupported)), "delivery report RP-ERROR");
return r;
}
} }

View file

@ -300,6 +300,44 @@ export namespace imsd::sip {
return ""; return "";
} }
// The URI of the party a header names — of the first element of the
// first `name:` header's value: what stands in its angle brackets, a
// quoted display name before them passed over, or a bare URI up to its
// first parameter or the next element —
// the Request-URI of a request to that party (the IP-SM-GW of a
// delivered short message, TS 24.341 5.3.2.4: its P-Asserted-Identity).
// nullopt when the header is absent or that element gives no URI — a
// URI with an ASCII control character, a space, `<`, `>` or `"` in it
// is none: it would stand in a request line as it is.
std::optional<std::string> HeaderUri(std::string_view msg, std::string_view name) {
auto v = Header(msg, name);
if (!v) return std::nullopt;
std::string_view uri = *v;
std::size_t at = 0;
if (uri.starts_with('"')) // a quoted display name: its `<`, `,` and `;` are not the value's
for (at = 1; at < uri.size() && uri[at] != '"'; at++)
if (uri[at] == '\\') at++;
const std::size_t stop = uri.find_first_of("<,;", at);
if (stop != std::string_view::npos && uri[stop] == '<') {
const std::size_t gt = uri.find('>', stop);
if (gt == std::string_view::npos) return std::nullopt;
uri = uri.substr(stop + 1, gt - stop - 1);
} else {
uri = Trim(uri.substr(0, stop)); // a bare URI; a value that begins with a quote is none below
}
if (uri.empty() || !uri.contains(':')) return std::nullopt;
for (unsigned char c : uri)
if (c <= 0x20 || c == 0x7F || c == '<' || c == '>' || c == '"') return std::nullopt;
return std::string(uri);
}
// The body of a message: what follows the header terminator, empty
// without one.
std::string_view Body(std::string_view msg) {
std::size_t at = msg.find("\r\n\r\n");
return at == std::string_view::npos ? std::string_view{} : msg.substr(at + 4);
}
// SIP-over-TCP stream framing, transport-free: feed received bytes into // SIP-over-TCP stream framing, transport-free: feed received bytes into
// Append(), pull complete messages (headers + Content-Length body) out // Append(), pull complete messages (headers + Content-Length body) out
// of TryExtract(). Leading CRLFs (RFC 5626 keepalive pongs) are // of TryExtract(). Leading CRLFs (RFC 5626 keepalive pongs) are

View file

@ -19,7 +19,21 @@
// fresh backoffs, the throttle schedule, Retry-After, which waits a Dial // fresh backoffs, the throttle schedule, Retry-After, which waits a Dial
// may cut short, when the old registration counts as gone, the holds a // may cut short, when the old registration counts as gone, the holds a
// restart takes over (Holds/Restore), and a binding the network terminated // restart takes over (Holds/Restore), and a binding the network terminated
// (OnBindingTerminated). Pure reducers, no I/O. // (OnBindingTerminated). Then SMS over IP: SmsOutbound through a
// submission (the MESSAGE with the RP-DATA, its 202, the RP-ACK -> sent; a
// refused final, an RP-ERROR with its cause, the final's wait and the
// report's running out, a failed send, two segments with consecutive
// RP-MR/TP-MR, a
// destination that is no number, no service centre, a submit report before
// the MESSAGE's own final, a text past 255 segments) and OnSmsMessage (a
// delivery with no gateway for its report, a
// delivered message to the bus and its RP-ACK to the IP-SM-GW with
// In-Reply-To, a concatenated pair whole once, a status report, a submit
// report routed to the message in flight, 488 for one that is not ours, an
// unusable TPDU acknowledged with an RP-ERROR, a body that is no RP
// message, a page-mode text 200'd and logged), and RecentTransactions (a
// retransmitted request gets its final again, for 32 s; no branch, no
// match). Pure reducers, no I/O.
import std; import std;
import Imsd; import Imsd;
@ -1224,6 +1238,364 @@ int main() {
} }
} }
// ---- SMS over IP: SmsOutbound and OnSmsMessage (TS 24.341) ----------
{
using namespace imsd::sms;
auto hasSms = [](const std::vector<SmsAction>& a, SmsAction::Type t) { for (const auto& x : a) if (x.type == t) return true; return false; };
auto findSms = [](const std::vector<SmsAction>& a, SmsAction::Type t) -> const SmsAction* { for (const auto& x : a) if (x.type == t) return &x; return nullptr; };
auto bodyRp = [](std::string_view msg) {
std::string_view body = imsd::sip::Body(msg);
return ParseRp(std::span<const std::uint8_t>(reinterpret_cast<const std::uint8_t*>(body.data()), body.size()), false); // lint-disable-line no-char-pointer
};
auto final = [](std::string_view callid, int code, std::string_view text) { return std::format("SIP/2.0 {} {}\r\nCall-ID: {}\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n", code, text, callid); };
const auto kpnSc = *imsd::util::FromHex("07911356131313f3");
Context c = MakeCtx();
c.aor = "sip:+31611111111@ims.mnc001.mcc001.3gppnetwork.org";
const SmsOutbound::Params p{"+31612345678", "Hello", "sip:+31653131313@ims.mnc001.mcc001.3gppnetwork.org;user=phone", kpnSc, 10, 20, 0x2A, 0xA9, false};
// a one-segment message: MESSAGE, 202, RP-ACK -> sent
{
imsd::util::Rng rng(71);
SmsOutbound m(c, rng, "ims-sms-1", p);
auto a = m.Start(100.0);
const auto* sent = findSms(a, SmsAction::Type::SendClient);
Check(sent && sent->text.starts_with("MESSAGE sip:+31653131313@ims.mnc001.mcc001.3gppnetwork.org;user=phone SIP/2.0\r\n"), "outbound: the MESSAGE goes to the SC's PSI");
Check(m.State() == SmsOutbound::Phase::Sending && m.Deadline() == 100.0 + SmsSendTimeout, "outbound: sending, the 32 s wait for the final armed");
if (!sent) return 1;
const std::string callid(imsd::sip::Header(sent->text, "Call-ID").value_or(""));
auto rp = bodyRp(sent->text);
Check(rp && rp->type == RpType::DataMo && rp->mr == 20 && rp->sc && rp->sc->Number() == "+31653131313", "outbound: the body is an RP-DATA to the SC with RP-MR 20");
Check(rp && rp->tpdu.size() > 2 && rp->tpdu[1] == 10 && (rp->tpdu[0] & 0x03) == 1 && (rp->tpdu[0] & 0x10), "outbound: an SMS-SUBMIT with TP-MR 10 and a TP-VP");
Check(m.TpMrs() == std::vector<std::uint8_t>{10} && m.Segments() == 1, "outbound: one segment");
Check(m.OwnsResponse(final(callid, 202, "Accepted")) && !m.OwnsResponse(final("other", 202, "Accepted")), "outbound: owns its own MESSAGE's final only");
auto b = m.OnResponse(final(callid, 202, "Accepted"), 202, 101.0);
Check(m.State() == SmsOutbound::Phase::AwaitingReport && m.Deadline() == 101.0 + SmsReportTimeout && !hasSms(b, SmsAction::Type::State), "outbound: 202 -> awaiting the submit report, its 40 s wait armed");
Check(SmsSendTimeout == 32.0 && SmsReportTimeout == 40.0, "outbound: the wait for the final is 32 s, the one for the submit report 40 s");
Check(m.OwnsReport(callid, std::nullopt) && !m.OwnsReport("x@y", 20) && m.OwnsReport("", 20) && !m.OwnsReport("", 21), "outbound: a report is matched by In-Reply-To, else by RP-MR");
Check(m.OwnsReport(std::format("x@y, {}", callid), std::nullopt) && m.OwnsReport(std::format("{},x@y", callid), 21) && m.OwnsReport(std::format("z@w , {} ,x@y", callid), 21) && m.OwnsReport(std::format("z@w\t,\t{}", callid), 21) && !m.OwnsReport("x@y, z@w", 20) && !m.OwnsReport(callid + "x", 20) && !m.OwnsReport("x" + callid, 20), "outbound: of an In-Reply-To that lists Call-IDs, ours among them is ours");
Rp ack{RpType::AckMt, 20, std::nullopt, *imsd::util::FromHex("010062016122050080"), std::nullopt, std::nullopt};
auto d = m.OnReport(ack, 102.0);
const auto* st = findSms(d, SmsAction::Type::State);
Check(st && st->state == "sent" && st->id == "ims-sms-1" && st->reason.contains("22:50:00+02:00") && m.Done() && m.Deadline() == 0, "outbound: the RP-ACK ends the message as sent, with the SC's time stamp");
}
// the final refuses it
{
imsd::util::Rng rng(72);
SmsOutbound m(c, rng, "ims-sms-2", p);
auto a = m.Start(0.0);
const std::string callid(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
auto b = m.OnResponse(std::format("SIP/2.0 403 Forbidden\r\nCall-ID: {}\r\nCSeq: 1 MESSAGE\r\nWarning: 399 x \"no\"\r\nContent-Length: 0\r\n\r\n", callid), 403, 1.0);
const auto* st = findSms(b, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("403 Forbidden") && st->reason.contains("Warning") && m.Done(), "outbound: a refused MESSAGE fails the message with the refusal");
}
// a provisional keeps it waiting; the RP-ERROR fails it with the cause
{
imsd::util::Rng rng(73);
SmsOutbound m(c, rng, "ims-sms-3", p);
auto a = m.Start(0.0);
const std::string callid(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
m.OnResponse(final(callid, 100, "Trying"), 100, 5.0);
Check(m.State() == SmsOutbound::Phase::Sending && m.Deadline() == 5.0 + SmsSendTimeout, "outbound: a provisional starts the 32 s wait over");
m.OnResponse(final(callid, 200, "OK"), 200, 6.0);
Rp err{RpType::ErrorMt, 20, std::nullopt, *imsd::util::FromHex("01c30062016122050080"), 28, std::nullopt};
auto b = m.OnReport(err, 7.0);
const auto* st = findSms(b, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("RP cause 28 (unidentified subscriber)") && st->reason.contains("TP-FCS 0xc3 (invalid SME address)"), "outbound: an RP-ERROR fails the message with its cause and TP-FCS");
}
// timeouts and a failed send
{
imsd::util::Rng rng(74);
SmsOutbound m(c, rng, "ims-sms-4", p);
m.Start(0.0);
auto a = m.OnDeadline();
const auto* st = findSms(a, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("no answer to the MESSAGE"), "outbound: no final within the wait fails it");
imsd::util::Rng rng2(75);
SmsOutbound m2(c, rng2, "ims-sms-5", p);
auto b = m2.Start(0.0);
const std::string callid(imsd::sip::Header(findSms(b, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
m2.OnResponse(final(callid, 202, "Accepted"), 202, 1.0);
auto d = m2.OnDeadline();
st = findSms(d, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("no submit report"), "outbound: no submit report within its wait fails it");
imsd::util::Rng rng3(76);
SmsOutbound m3(c, rng3, "ims-sms-6", p);
m3.Start(0.0);
auto e = m3.OnSendFailed();
st = findSms(e, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("flow to the P-CSCF is down"), "outbound: a failed send fails it");
}
// two segments: the second goes after the first's RP-ACK, with the next RP-MR and TP-MR
{
imsd::util::Rng rng(77);
SmsOutbound::Params pl = p;
pl.text = std::string(200, 'x');
SmsOutbound m(c, rng, "ims-sms-7", pl);
auto a = m.Start(0.0);
Check(m.Segments() == 2 && m.TpMrs() == std::vector<std::uint8_t>{10, 11}, "outbound: 200 characters are two segments with consecutive TP-MRs");
const std::string callid(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
m.OnResponse(final(callid, 202, "Accepted"), 202, 1.0);
auto b = m.OnReport(Rp{RpType::AckMt, 20, std::nullopt, {}, std::nullopt, std::nullopt}, 2.0);
const auto* second = findSms(b, SmsAction::Type::SendClient);
Check(second && !hasSms(b, SmsAction::Type::State) && m.State() == SmsOutbound::Phase::Sending, "outbound: the first RP-ACK sends the second segment");
if (!second) return 1;
const std::string callid2(imsd::sip::Header(second->text, "Call-ID").value_or(""));
Check(callid2 != callid, "outbound: a Call-ID of its own per segment");
auto rp = bodyRp(second->text);
Check(rp && rp->mr == 21 && rp->tpdu[1] == 11 && (rp->tpdu[0] & 0x40), "outbound: segment 2 has RP-MR 21, TP-MR 11 and a user-data header");
Check(m.OwnsReport("", 21) && !m.OwnsReport("", 20), "outbound: the report in flight is the second segment's");
m.OnResponse(final(callid2, 202, "Accepted"), 202, 3.0);
auto d = m.OnReport(Rp{RpType::AckMt, 21, std::nullopt, {}, std::nullopt, std::nullopt}, 4.0);
const auto* st = findSms(d, SmsAction::Type::State);
Check(st && st->state == "sent" && st->reason.contains("2 segment(s)") && m.Done(), "outbound: the second RP-ACK ends the message as sent");
}
// unsendable
{
imsd::util::Rng rng(78);
SmsOutbound::Params bad = p;
bad.number = "nobody";
SmsOutbound m(c, rng, "ims-sms-8", bad);
auto a = m.Start(0.0);
const auto* st = findSms(a, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason == "'nobody' is not a number" && m.Done() && !hasSms(a, SmsAction::Type::SendClient), "outbound: a destination that is no number fails at once");
SmsOutbound::Params longNumber = p;
longNumber.number = "+" + std::string(21, '3');
imsd::util::Rng rngL(80);
SmsOutbound mL(c, rngL, "ims-sms-10", longNumber);
auto l = mL.Start(0.0);
st = findSms(l, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("is not a number") && !hasSms(l, SmsAction::Type::SendClient), "outbound: a destination of more than 20 digits is no number, not a text that does not fit");
SmsOutbound::Params noSc = p;
noSc.scAddress.clear();
imsd::util::Rng rng2(79);
SmsOutbound m2(c, rng2, "ims-sms-9", noSc);
auto b = m2.Start(0.0);
st = findSms(b, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("no service centre"), "outbound: no service centre fails at once");
}
// inbound MESSAGEs, as the IP-SM-GW sends them
auto inbound = [](std::string_view bodyHex, std::string_view extraHeaders = "") {
auto b = *imsd::util::FromHex(bodyHex);
return std::format("MESSAGE sip:+31611111111@ims.mnc001.mcc001.3gppnetwork.org SIP/2.0\r\nVia: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn1\r\nFrom: <sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org>;tag=N1\r\nTo: <sip:+31611111111@ims.mnc001.mcc001.3gppnetwork.org>\r\nCall-ID: in-{}@net\r\nCSeq: 1 MESSAGE\r\nP-Asserted-Identity: <sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org>\r\n{}Content-Type: application/vnd.3gpp.sms\r\nContent-Length: {}\r\n\r\n{}", bodyHex.substr(0, 6), extraHeaders, b.size(), std::string(b.begin(), b.end()));
};
// a delivered short message: 200, the bus, the RP-ACK to the IP-SM-GW
{
imsd::util::Rng rng(80);
Reassembler re;
auto r = OnSmsMessage(c, rng, inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07"), re, nullptr, 50.0);
Check(r.response.starts_with("SIP/2.0 200 OK\r\n") && r.response.contains("Call-ID: in-011107@net\r\n"), "inbound: the MESSAGE is answered 200");
const auto* rec = findSms(r.actions, SmsAction::Type::Received);
Check(rec && rec->received.from == "+31641600986" && rec->received.text == "How are you?" && rec->received.sc == "+31653131313" && rec->received.scts == "2002-08-26T19:37:41-00:00" && rec->received.segments == 1 && rec->received.tpdu.size() == 30, "inbound: the message reaches the bus");
Check(std::ranges::find_if(r.actions, [](const SmsAction& x) { return x.type == SmsAction::Type::Received; }) < std::ranges::find_if(r.actions, [](const SmsAction& x) { return x.type == SmsAction::Type::SendClient; }), "inbound: the message is handed over before its report leaves");
const auto* rep = findSms(r.actions, SmsAction::Type::SendClient);
Check(rep && rep->text.starts_with("MESSAGE sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org SIP/2.0\r\n") && rep->text.contains("\r\nIn-Reply-To: in-011107@net\r\n"), "inbound: the delivery report goes to the P-Asserted-Identity, In-Reply-To the delivered MESSAGE");
Check(rep && imsd::sip::Body(rep->text) == std::string("\x02\x11\x41\x02\x00\x00", 6) && imsd::sip::Header(rep->text, "Call-ID") == r.reportCallId, "inbound: the report is an RP-ACK with the SMS-DELIVER-REPORT, RP-MR echoed");
std::string other = inbound("011207911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07");
other.replace(other.find("From: <sip:ipsmgw@"), 18, "From: <sip:someone@");
auto ro = OnSmsMessage(c, rng, other, re, nullptr, 51.0);
const auto* repo = findSms(ro.actions, SmsAction::Type::SendClient);
Check(repo && repo->text.starts_with("MESSAGE sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org SIP/2.0\r\n"), "inbound: with a From that names another, the report still goes to the P-Asserted-Identity");
}
// a Call-ID the delivery report cannot carry — a byte up to 0x20 in it (but an LF, which ends the line) or a DEL: no In-Reply-To, the message and its report as ever
for (int b = 0; b <= 0x7F; b++) {
if ((b > 0x20 && b != 0x7F) || b == 0x0A) continue;
imsd::util::Rng rng(80);
Reassembler re;
std::string req = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07");
req.replace(req.find("in-011107@net"), 13, std::string("in-0111") + static_cast<char>(b) + "Route:x@net");
auto r = OnSmsMessage(c, rng, req, re, nullptr, 52.0);
const auto* rep = findSms(r.actions, SmsAction::Type::SendClient);
Check(rep && hasSms(r.actions, SmsAction::Type::Received) && !rep->text.contains("In-Reply-To") && !rep->text.contains("Route:x") && imsd::sip::Body(rep->text) == std::string("\x02\x11\x41\x02\x00\x00", 6), std::format("inbound: a Call-ID with the byte 0x{:02x} in it is not written into the delivery report's In-Reply-To", b));
}
// a submit report whose In-Reply-To comes in two rows, ours in the first or in the second: the rows are one list
for (bool first : {true, false}) {
imsd::util::Rng rng(92);
Reassembler re;
SmsOutbound m(c, rng, "ims-sms-19", p);
auto a = m.Start(0.0);
const std::string callid(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
m.OnResponse(final(callid, 202, "Accepted"), 202, 1.0);
auto r = OnSmsMessage(c, rng, inbound("0314", first ? std::format("In-Reply-To: {}\r\nIn-Reply-To: x@y\r\n", callid) : std::format("In-Reply-To: x@y\r\nIn-Reply-To: {}\r\n", callid)), re, &m, 2.0);
const auto* st = findSms(r.actions, SmsAction::Type::State);
Check(r.response.starts_with("SIP/2.0 200 OK") && st && st->state == "sent" && m.Done(), std::format("inbound: a submit report whose In-Reply-To rows list ours in the {} reaches the message in flight", first ? "first" : "second"));
}
// a header name spelled inside the body (8-bit data): the report goes to the header's From, not there
{
imsd::util::Rng rng(83);
Reassembler re;
std::string req = inbound("011107911356131313F30035040B911346610089F6000420806291731408220A502D41737365727465642D4964656E746974793A203C7369703A6576696C40783E");
const auto pai = req.find("P-Asserted-Identity:"); // without the header, a body line would be the first match
if (pai != std::string::npos) req.erase(pai, req.find("\r\n", pai) + 2 - pai);
auto r = OnSmsMessage(c, rng, req, re, nullptr, 52.0);
const auto* rec = findSms(r.actions, SmsAction::Type::Received);
const auto* rep = findSms(r.actions, SmsAction::Type::SendClient);
Check(rec && rec->received.data.size() == 34 && rep && rep->text.starts_with("MESSAGE sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org SIP/2.0\r\n") && !rep->text.contains("evil"), "inbound: a header name in the body picks neither the report's target nor anything else");
}
// two segments: the message only once whole, each segment acknowledged
{
imsd::util::Rng rng(81);
Reassembler re;
auto r2 = OnSmsMessage(c, rng, inbound("011207911356131313F3001E440B911316325476F80000620161220500800C0500037B02028442A15008"), re, nullptr, 60.0);
Check(!hasSms(r2.actions, SmsAction::Type::Received) && hasSms(r2.actions, SmsAction::Type::SendClient) && re.Pending() == 1, "inbound: segment 2/2 first: acknowledged, nothing to the bus yet");
const std::string seg1 = "440B911316325476F8000062016122050080A00500037B020182C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683C16030180C0683";
auto r1 = OnSmsMessage(c, rng, inbound(std::format("011307911356131313F300{:02X}{}", seg1.size() / 2, seg1)), re, nullptr, 61.0);
const auto* rec = findSms(r1.actions, SmsAction::Type::Received);
Check(rec && rec->received.text == std::string(153, 'A') + "BBBBB" && rec->received.segments == 2 && re.Pending() == 0, "inbound: segment 1/2 completes the message");
Check(hasSms(r1.actions, SmsAction::Type::SendClient), "inbound: segment 1/2 acknowledged too");
}
// a UCS-2 surrogate pair split across the two segments: the bus text is whole
{
auto rep = [](std::string_view x, int n) { std::string o; for (int i = 0; i < n; i++) o += x; return o; };
imsd::util::Rng rng(82);
Reassembler re;
const std::string u1 = "440B911316325476F80008620161220500808C0500032A0201" + rep("00FC", 66) + "D83D";
const std::string u2 = "440B911316325476F8000862016122050080100500032A0202DE00" + rep("0078", 4);
auto a1 = OnSmsMessage(c, rng, inbound(std::format("011407911356131313F300{:02X}{}", u1.size() / 2, u1)), re, nullptr, 62.0);
auto a2 = OnSmsMessage(c, rng, inbound(std::format("011507911356131313F300{:02X}{}", u2.size() / 2, u2)), re, nullptr, 63.0);
const auto* w = findSms(a2.actions, SmsAction::Type::Received);
Check(!hasSms(a1.actions, SmsAction::Type::Received) && w && w->received.text == rep("ü", 66) + "😀xxxx" && w->received.segments == 2 && re.Pending() == 0, "inbound: a surrogate pair split across segments reaches the bus whole");
}
// a status report
{
imsd::util::Rng rng(82);
Reassembler re;
auto r = OnSmsMessage(c, rng, inbound("011207911356131313F30019062A0B911316325476F8620161220500806201612205708000"), re, nullptr, 70.0);
const auto* sr = findSms(r.actions, SmsAction::Type::StatusReport);
Check(sr && sr->report.mr == 0x2A && sr->report.status == 0 && !hasSms(r.actions, SmsAction::Type::Received) && hasSms(r.actions, SmsAction::Type::SendClient), "inbound: a status report is handed over and acknowledged");
}
// a submit report before the MESSAGE's own final (the IP-SM-GW's order is its own): taken, the message sent, the late final nobody's
{
imsd::util::Rng rng(84);
Reassembler re;
SmsOutbound m(c, rng, "ims-sms-11", p);
auto a = m.Start(0.0);
const std::string callid(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
Check(m.State() == SmsOutbound::Phase::Sending && m.OwnsReport(callid, std::nullopt), "outbound: a report is owned while the MESSAGE's final is still due");
auto r = OnSmsMessage(c, rng, inbound("0314", std::format("In-Reply-To: {}\r\n", callid)), re, &m, 1.0);
const auto* st = findSms(r.actions, SmsAction::Type::State);
Check(r.response.starts_with("SIP/2.0 200 OK") && st && st->state == "sent" && m.Done() && !m.OwnsResponse(final(callid, 202, "Accepted")), "outbound: the early RP-ACK ends the message as sent; the late 202 is nobody's");
}
// the same with two segments: segment 1's early RP-ACK sends segment 2 under its own Call-ID
{
imsd::util::Rng rng(85);
Reassembler re;
SmsOutbound::Params two = p; two.text = std::string(200, 'A');
SmsOutbound m(c, rng, "ims-sms-12", two);
auto a = m.Start(0.0);
const std::string callid1(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
auto r = OnSmsMessage(c, rng, inbound("0314", std::format("In-Reply-To: {}\r\n", callid1)), re, &m, 1.0);
const auto* seg2 = findSms(r.actions, SmsAction::Type::SendClient);
const std::string callid2 = seg2 ? std::string(imsd::sip::Header(seg2->text, "Call-ID").value_or("")) : std::string();
Check(seg2 && !callid2.empty() && callid2 != callid1 && m.State() == SmsOutbound::Phase::Sending && !m.OwnsResponse(final(callid1, 202, "Accepted")) && m.OwnsResponse(final(callid2, 202, "Accepted")), "outbound: segment 1's early RP-ACK sends segment 2 under its own Call-ID; segment 1's late 202 is nobody's");
// a second report for segment 1 once segment 2 is out: 488, the message untouched
auto rs = OnSmsMessage(c, rng, inbound("0314", std::format("In-Reply-To: {}\r\n", callid1)), re, &m, 2.0);
Check(rs.response.starts_with("SIP/2.0 488 Not Acceptable Here\r\n") && m.State() == SmsOutbound::Phase::Sending && m.OwnsResponse(final(callid2, 202, "Accepted")), "inbound: a report for segment 1 after segment 2 went out: 488, the message untouched");
}
// a text past 255 segments to a valid number: failed at once, naming the fit
{
imsd::util::Rng rng(86);
SmsOutbound::Params big = p; big.text = std::string(255 * 153 + 1, 'A');
SmsOutbound m(c, rng, "ims-sms-13", big);
auto a = m.Start(0.0);
const auto* st = findSms(a, SmsAction::Type::State);
Check(st && st->state == "failed" && st->reason.contains("does not fit 255 segments") && m.Done() && !hasSms(a, SmsAction::Type::SendClient), "outbound: a text past 255 segments fails at once, naming the fit");
}
// a delivery with no P-Asserted-Identity and a From without a URI: handed over, no delivery report can go anywhere
{
imsd::util::Rng rng(87);
Reassembler re;
std::string msg = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07");
const std::string pai = "P-Asserted-Identity: <sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org>\r\n", from = "From: <sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org>;tag=N1";
const auto i = msg.find(pai), j = msg.find(from);
Check(i != std::string::npos && j != std::string::npos, "inbound: the fixture carries the PAI and the From");
if (i == std::string::npos || j == std::string::npos) return 1;
msg.erase(i, pai.size());
msg.replace(msg.find(from), from.size(), "From: anonymous;tag=N1");
auto r = OnSmsMessage(c, rng, msg, re, nullptr, 51.0);
bool said = false;
for (const auto& x : r.actions) if (x.type == SmsAction::Type::Log && x.text.contains("no P-Asserted-Identity or From URI")) said = true;
Check(r.response.starts_with("SIP/2.0 200 OK") && hasSms(r.actions, SmsAction::Type::Received) && !hasSms(r.actions, SmsAction::Type::SendClient) && r.reportCallId.empty() && said, "inbound: no gateway for the delivery report — the message handed over, the absence logged");
}
// a submit report without In-Reply-To: matched by RP-MR to the message in flight
{
imsd::util::Rng rng(88);
Reassembler re;
SmsOutbound m(c, rng, "ims-sms-14", p);
auto a = m.Start(0.0);
const std::string callid(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
m.OnResponse(final(callid, 202, "Accepted"), 202, 1.0);
auto r = OnSmsMessage(c, rng, inbound("0314"), re, &m, 2.0);
const auto* st = findSms(r.actions, SmsAction::Type::State);
Check(r.response.starts_with("SIP/2.0 200 OK") && st && st->state == "sent" && m.Done() && r.reportCallId.empty(), "inbound: a submit report without In-Reply-To reaches the message in flight by RP-MR");
}
// a submit report for the message in flight; one for nobody
{
imsd::util::Rng rng(83);
Reassembler re;
SmsOutbound m(c, rng, "ims-sms-10", p);
auto a = m.Start(0.0);
const std::string callid(imsd::sip::Header(findSms(a, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
m.OnResponse(final(callid, 202, "Accepted"), 202, 1.0);
auto r = OnSmsMessage(c, rng, inbound("0314", std::format("In-Reply-To: {}\r\n", callid)), re, &m, 2.0);
const auto* st = findSms(r.actions, SmsAction::Type::State);
Check(r.response.starts_with("SIP/2.0 200 OK") && st && st->state == "sent" && m.Done() && r.reportCallId.empty(), "inbound: the submit report reaches the message in flight and is answered 200");
auto r2 = OnSmsMessage(c, rng, inbound("0314", "In-Reply-To: nobody@x\r\n"), re, &m, 3.0);
Check(r2.response.starts_with("SIP/2.0 488 Not Acceptable Here\r\n") && hasSms(r2.actions, SmsAction::Type::Log), "inbound: a report In-Reply-To a MESSAGE that is not ours: 488");
// a report for our own MESSAGE once the message has ended (here: sent): 488, as for a stranger's
auto r4 = OnSmsMessage(c, rng, inbound("0314", std::format("In-Reply-To: {}\r\n", callid)), re, &m, 3.5);
Check(r4.response.starts_with("SIP/2.0 488 Not Acceptable Here\r\n") && hasSms(r4.actions, SmsAction::Type::Log), "inbound: a report for our own MESSAGE after the message ended: 488");
// and once the report's wait ended it (OnDeadline): 488 too
SmsOutbound m3(c, rng, "ims-sms-13", p);
auto a3 = m3.Start(10.0);
const std::string callid3(imsd::sip::Header(findSms(a3, SmsAction::Type::SendClient)->text, "Call-ID").value_or(""));
m3.OnResponse(final(callid3, 202, "Accepted"), 202, 11.0);
m3.OnDeadline();
auto r5 = OnSmsMessage(c, rng, inbound("0314", std::format("In-Reply-To: {}\r\n", callid3)), re, &m3, 60.0);
Check(m3.Done() && r5.response.starts_with("SIP/2.0 488 Not Acceptable Here\r\n"), "inbound: a report for our own MESSAGE after its wait ended it: 488");
auto r3 = OnSmsMessage(c, rng, inbound("0314"), re, nullptr, 4.0);
Check(r3.response.starts_with("SIP/2.0 200 OK") && hasSms(r3.actions, SmsAction::Type::Log) && !hasSms(r3.actions, SmsAction::Type::SendClient), "inbound: a report without In-Reply-To for no message: 200 and the log");
}
// an unusable TPDU, a body that is no RP message, another content type
{
imsd::util::Rng rng(84);
Reassembler re;
auto r = OnSmsMessage(c, rng, inbound("011507911356131313F30002FFFF"), re, nullptr, 5.0);
const auto* rep = findSms(r.actions, SmsAction::Type::SendClient);
Check(r.response.starts_with("SIP/2.0 200 OK") && rep && imsd::sip::Body(rep->text) == std::string("\x04\x15\x01\x60\x41\x03\x00\xB0\x00", 9) && !hasSms(r.actions, SmsAction::Type::Received), "inbound: an unusable TPDU is acknowledged with an RP-ERROR (cause 96, TP-FCS B0)");
auto rs = OnSmsMessage(c, rng, inbound("011607911356131313F3000102"), re, nullptr, 5.2);
const auto* reps = findSms(rs.actions, SmsAction::Type::SendClient);
Check(rs.response.starts_with("SIP/2.0 200 OK") && reps && imsd::sip::Body(reps->text) == std::string("\x04\x16\x01\x60\x41\x03\x00\xB0\x00", 9) && !hasSms(rs.actions, SmsAction::Type::StatusReport), "inbound: a status report that does not parse gets the same RP-ERROR");
auto rt = OnSmsMessage(c, rng, inbound("011707911356131313F300020100"), re, nullptr, 5.4);
const auto* rept = findSms(rt.actions, SmsAction::Type::SendClient);
Check(rt.response.starts_with("SIP/2.0 200 OK") && rept && imsd::sip::Body(rept->text) == std::string("\x04\x17\x01\x60\x41\x03\x00\xB0\x00", 9) && !hasSms(rt.actions, SmsAction::Type::Received), "inbound: a TPDU of the submit-report type gets the same RP-ERROR");
auto r2 = OnSmsMessage(c, rng, inbound("07"), re, nullptr, 6.0);
Check(r2.response.starts_with("SIP/2.0 200 OK") && !r2.rp && hasSms(r2.actions, SmsAction::Type::Log) && !hasSms(r2.actions, SmsAction::Type::SendClient), "inbound: a body that is no RP message: 200 and the log");
const std::string plain = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn2\r\nFrom: <sip:x@ims>;tag=1\r\nTo: <sip:me@ims>\r\nCall-ID: t1@net\r\nCSeq: 1 MESSAGE\r\nContent-Type: text/plain\r\nContent-Length: 2\r\n\r\nhi";
auto r3 = OnSmsMessage(c, rng, plain, re, nullptr, 7.0);
Check(r3.response.starts_with("SIP/2.0 200 OK") && !r3.rp && hasSms(r3.actions, SmsAction::Type::Log) && findSms(r3.actions, SmsAction::Type::Log)->text.contains("hi"), "inbound: a page-mode text is 200'd and logged with its body");
}
// a retransmitted MESSAGE: the same final again, nothing else, for 32 s (TimerJ)
{
RecentTransactions recent;
const std::string first = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07");
const std::string key = RecentTransactions::Key(first);
Check(key == "in-011107@net|1 MESSAGE|z9hG4bKn1", "recent: the key is Call-ID, CSeq and the Via line's branch");
Check(!recent.Repeat(key, 10.0), "recent: a new request is no retransmission");
recent.Remember(key, "SIP/2.0 200 OK\r\n\r\n", 10.0);
Check(recent.Repeat(key, 10.4) == std::optional<std::string>("SIP/2.0 200 OK\r\n\r\n") && recent.Size() == 1, "recent: the copy gets the same final");
Check(!recent.Repeat("other|1 MESSAGE|z9hG4bKn1", 10.5), "recent: another Call-ID is another request");
Check(RecentTransactions::TimerJ == 32.0 && recent.Repeat(key, 10.0 + 31.5) == std::optional<std::string>("SIP/2.0 200 OK\r\n\r\n"), "recent: TimerJ is 32 s, and a copy half a second before its end still gets the final");
Check(!recent.Repeat(key, 10.0 + RecentTransactions::TimerJ + 0.5) && recent.Size() == 0, "recent: forgotten after TimerJ's 32 s");
const std::string noBranch = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000\r\nCall-ID: nb@net\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n";
Check(RecentTransactions::Key(noBranch).empty(), "recent: no branch, no key");
recent.Remember(RecentTransactions::Key(noBranch), "x", 50.0);
Check(!recent.Repeat("", 50.1) && recent.Size() == 0, "recent: an empty key is never remembered");
const std::string branchWithParams = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKabc;_aluscr_\r\nCall-ID: c@net\r\nCSeq: 7 MESSAGE\r\nContent-Length: 0\r\n\r\n";
Check(RecentTransactions::Key(branchWithParams) == "c@net|7 MESSAGE|z9hG4bKabc", "recent: the branch ends at the next parameter");
}
}
if (Failures == 0) std::println("Engine: all tests passed"); if (Failures == 0) std::println("Engine: all tests passed");
return Failures != 0; // not the count: an exit status keeps 8 bits, and this suite has more checks than that return Failures != 0; // not the count: an exit status keeps 8 bits, and this suite has more checks than that
} }

View file

@ -299,6 +299,41 @@ int main() {
Check(RegInfoContactState("<contact state=\"terminated\" event=\"expired\"><uri>sip:" + me + "@h</uri>", me).state == S::Terminated, "an unterminated element still parses"); Check(RegInfoContactState("<contact state=\"terminated\" event=\"expired\"><uri>sip:" + me + "@h</uri>", me).state == S::Terminated, "an unterminated element still parses");
} }
// ---- HeaderUri / Body: the party a header names, a message's body
{
const std::string m =
"MESSAGE sip:me@ims SIP/2.0\r\n"
"P-Asserted-Identity: \"IP-SM-GW\" <sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org>\r\n"
"P-Asserted-Identity: <tel:+31653131313>\r\n"
"From: sip:bare@ims;tag=x\r\n"
"To: <>\r\n"
"Call-ID: c1\r\n"
"Content-Length: 3\r\n"
"\r\n"
"abc";
Check(imsd::sip::HeaderUri(m, "P-Asserted-Identity") == "sip:ipsmgw@ims.mnc001.mcc001.3gppnetwork.org", "HeaderUri: the first header's bracketed URI, display name dropped");
Check(imsd::sip::HeaderUri(m, "From") == "sip:bare@ims", "HeaderUri: a bare value up to its parameters");
Check(!imsd::sip::HeaderUri(m, "To"), "HeaderUri: empty brackets hold no URI");
Check(!imsd::sip::HeaderUri(m, "Contact"), "HeaderUri: an absent header");
const std::string crafted = "MESSAGE sip:u@h SIP/2.0\r\nP-Asserted-Identity: <sip:a\rRoute:x@h>\r\nFrom: <sip:b c@h>\r\nReply-To: sip:e\rRoute:x@h\r\nReferred-By: sip:g h@h\r\nTo: <sip:ok@h>\r\n\r\n";
Check(!imsd::sip::HeaderUri(crafted, "P-Asserted-Identity") && !imsd::sip::HeaderUri(crafted, "From") && !imsd::sip::HeaderUri(crafted, "Reply-To") && !imsd::sip::HeaderUri(crafted, "Referred-By") && imsd::sip::HeaderUri(crafted, "To") == "sip:ok@h", "HeaderUri: a URI with a bare CR or a space in it is none, in brackets or bare");
bool none = true;
for (int b = 0; b <= 0x7F; b++) {
if (b > 0x20 && b != 0x7F) continue;
if (imsd::sip::HeaderUri(std::string("MESSAGE sip:u@h SIP/2.0\r\nFrom: <sip:a") + static_cast<char>(b) + "c@h>\r\n\r\n", "From")) none = false;
}
Check(none, "HeaderUri: a URI with a byte up to 0x20 or a DEL in it is none");
// the value's first element: a list in one row, a quoted display name, a value that holds no URI
auto one = [](std::string_view pai) { return imsd::sip::HeaderUri(std::format("MESSAGE sip:u@h SIP/2.0\r\nP-Asserted-Identity: {}\r\n\r\n", pai), "P-Asserted-Identity"); };
Check(one("sip:ipsmgw.home2.net,tel:+31653085001") == "sip:ipsmgw.home2.net" && one("sip:ipsmgw.home2.net, tel:+31653085001") == "sip:ipsmgw.home2.net" && one("sip:ipsmgw.home2.net\t ,tel:+31653085001") == "sip:ipsmgw.home2.net" && one("sip:ipsmgw.home2.net,<tel:+31653085001>") == "sip:ipsmgw.home2.net" && one("<sip:ipsmgw.home2.net>,<tel:+31653085001>") == "sip:ipsmgw.home2.net" && one("sip:ipsmgw.home2.net;x=1,tel:+31653085001") == "sip:ipsmgw.home2.net", "HeaderUri: of a list in one row, the first element's URI");
Check(one("\"Doe, John\" <sip:j@h>") == "sip:j@h" && one("\"a<b\" <sip:gw@h>") == "sip:gw@h" && one("\"a\\\"<b\" <sip:gw@h>") == "sip:gw@h" && one("\"a\\\\\" <sip:gw@h>") == "sip:gw@h" && one("\"\"<sip:gw@h>") == "sip:gw@h" && one("\"<sip:x@y>\" <sip:gw@h>;tag=1") == "sip:gw@h", "HeaderUri: a quoted display name is passed over — a `<`, a `,`, an escaped quote or an escaped backslash in it too, and an empty one");
Check(!one("\"open<sip:x@h>") && !one("\"x\"sip:a@h") && !one("\"x\\"), "HeaderUri: a quote that does not close, or a display name with no bracketed URI after it, gives none");
Check(one("sip:gw@h;tag=1;x=\"<a:b>\"") == "sip:gw@h", "HeaderUri: a bare URI ends at its first parameter, also when a later one holds a `<`");
Check(!one("<sip:a@h,<tel:+1>") && !one("sip:a>b@h") && !one("<sip:a\"b@h>"), "HeaderUri: a URI with `<`, `>` or `\"` in it is none");
Check(imsd::sip::Body(m) == "abc", "Body: what follows the header terminator");
Check(imsd::sip::Body("OPTIONS sip:x SIP/2.0\r\nCSeq: 1 OPTIONS\r\n").empty(), "Body: none without a terminator");
}
if (Failures == 0) std::println("Sip: all tests passed"); if (Failures == 0) std::println("Sip: 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 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
} }