From a63132deb8108a2b1b6865faf52704394b0bddd6 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 01/40] tests: every suite returns 1 for a failure, not the count Six suites ended in `return Failures;`. `crafter-build test` takes an exit status of 77 for a skipped suite and then succeeds, and an exit status keeps 8 bits: 77 failing checks read as a skip, 256 as a pass. All nine now return 1 after any failure, as Engine, Sip and Sms did. Tested with 77 failing checks added to Ipsec, to Messages and to Sdp in turn (the fp6 journal's 2026-11-20-issues-2-5 capture, exit-status): before, `crafter-build test` ended `8 passed, 1 skipped` with exit status 0; now it ends `8 passed, 1 failed` with exit status 1. --- AGENTS.md | 3 +-- tests/Aka/main.cpp | 2 +- tests/Ipsec/main.cpp | 2 +- tests/Messages/main.cpp | 2 +- tests/Qmi/main.cpp | 2 +- tests/Sdp/main.cpp | 2 +- tests/Util/main.cpp | 2 +- 7 files changed, 7 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 26508cc..802dff2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -242,8 +242,7 @@ releases. This is the flow CI runs (§9.4). `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 six suites — non-zero short of a multiple of 256 — and -1 for `Engine`, `Sip` and `Sms`. `crafter-build test` ending in `9 passed`, on every +1 after any failure. `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: diff --git a/tests/Aka/main.cpp b/tests/Aka/main.cpp index e0380cb..49c8d1f 100644 --- a/tests/Aka/main.cpp +++ b/tests/Aka/main.cpp @@ -145,5 +145,5 @@ int main() { } if (Failures == 0) std::println("Aka: all tests passed"); - return Failures; + return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits } diff --git a/tests/Ipsec/main.cpp b/tests/Ipsec/main.cpp index 07f24c4..d8e3088 100644 --- a/tests/Ipsec/main.cpp +++ b/tests/Ipsec/main.cpp @@ -374,5 +374,5 @@ int main() { } if (Failures == 0) std::println("Ipsec: all tests passed"); - return Failures; + return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits } diff --git a/tests/Messages/main.cpp b/tests/Messages/main.cpp index 2dccd9a..519ed15 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -512,5 +512,5 @@ int main() { } if (Failures == 0) std::println("Messages: all tests passed"); - return Failures; + return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits } diff --git a/tests/Qmi/main.cpp b/tests/Qmi/main.cpp index 111a07d..245a116 100644 --- a/tests/Qmi/main.cpp +++ b/tests/Qmi/main.cpp @@ -90,5 +90,5 @@ int main() { } if (Failures == 0) std::println("Qmi: all tests passed"); - return Failures; + return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits } diff --git a/tests/Sdp/main.cpp b/tests/Sdp/main.cpp index a29148b..ed3fa19 100644 --- a/tests/Sdp/main.cpp +++ b/tests/Sdp/main.cpp @@ -396,5 +396,5 @@ int main() { } if (Failures == 0) std::println("Sdp: all tests passed"); - return Failures; + return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits } diff --git a/tests/Util/main.cpp b/tests/Util/main.cpp index 7b4f5f7..ae86762 100644 --- a/tests/Util/main.cpp +++ b/tests/Util/main.cpp @@ -137,5 +137,5 @@ int main() { } if (Failures == 0) std::println("Util: all tests passed"); - return Failures; + return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and an exit status keeps 8 bits } From ca825937bf1df95370dae49c231ce6ed2c1a64dd Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 02/40] tests: the Sip suite's header names its sections, and its reginfo fixture takes a documentation address and the suites' instance id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suite's header comment named five of its sections — header access, the status line, the granted lifetime, the caller's identity and the frame buffer — and left out six: ViaResponsePort, DatagramMessage, RetryAfter and RefusalSummary, ResponseOf, RegInfoContactState, HeaderUri and Body. Its reg-event fixture had a contact at [2a03:db8::1], outside the documentation prefix 2001:db8::/32, and an instance id built on a real phone model's type allocation code. The header now names every section; the fixture has [2001:db8::1] and the instance id that tests/Aka and tests/Messages use, 35999999-000000-1. No check changes. --- tests/Sip/main.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index a51d222..2844f07 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -2,9 +2,13 @@ // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // Imsd:Sip unit tests — header access, status-line parsing, granted-expires -// extraction, caller-identity extraction, and the TCP frame buffer (split -// delivery, keepalive pongs, pipelined messages). These pin the module's -// edge-case behavior; see the module header before "fixing" one. +// extraction, caller-identity extraction, the port a Via names for the +// response (ViaResponsePort), the two framers — the TCP frame buffer (split +// delivery, keepalive pongs, pipelined messages) and a datagram's +// (DatagramMessage) —, a refused final's Retry-After and summary (RetryAfter, +// RefusalSummary), transaction matching (ResponseOf), our binding in a +// reg-event document (RegInfoContactState), and HeaderUri and Body. These pin +// the module's edge-case behavior; see the module header before "fixing" one. import std; import Imsd; @@ -257,8 +261,8 @@ int main() { auto contact = [](std::string_view id, std::string_view state, std::string_view extra, std::string_view user) { return std::format( "\t\t\n" - "\t\t\tsip:{}@[2a03:db8::1]:45062\n" - "\t\t\t"<urn:gsma:imei:35901961-000000-0>" \n" + "\t\t\tsip:{}@[2001:db8::1]:45062\n" + "\t\t\t"<urn:gsma:imei:35999999-000000-1>" \n" "\t\t\n", id, state, extra, user); }; auto reginfo = [](std::string_view contacts) { From 5c1fca12b9dd7d9eb5082d9aa1eeecd07b6dcb2b Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 03/40] docs: a phone record shows `to` and `operator` in a List MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AGENTS.md §5 said no phone record shows the two keys in a `Received` or a `List`. The tip of 1.2.0 ran on the dev phone on 2026-11-20, after that sentence was written: a text sent to the own number over the bus was delivered back, and `List` gave its record with `to` and `operator` (the fp6 journal's 2026-11-20-imsd-1.2.0-frozen-on-dev-phone capture, checks.log). No capture holds a `Received` with them. --- AGENTS.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 802dff2..13c2710 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -652,8 +652,11 @@ Rules: `SMSC='abc' is not a number` (`ForNumber` dials digits, `*` and `#` only; the bench's first run, on a build outside this history that dialled a, b and c, submitted with them and got an RP-ERROR back, RP cause 28). - No phone record shows `to` or `operator` in a `Received` or a `List`; the - store's round trip with each is in `tests/Engine`. + `to` and `operator` are in a `List` record from the dev phone (2026-11-20, + the fp6 journal's `2026-11-20-imsd-1.2.0-frozen-on-dev-phone` capture, + `checks.log`: a text sent to the own number over the bus, delivered + back and listed); no capture holds a `Received` with them; the store's + round trip with each is in `tests/Engine`. - `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims bearer: the `--mux 1 --profile 2 -v` sequence, a plain run, and `OutOfCall` on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture, From 1267fe1adaccddd583bf59420816927b6e89934b Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 04/40] sip: a header is found under its compact form, and with white space before the colon MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 3261 7.3.3 lets a sender write a header name in its one-letter form at any time and has every implementation accept both forms. The text layer matched the long name only, so to every reader a header sent in compact form was absent: the TCP framer took no body length from `l:` and read the body as the start of the next message, a response with `i:` matched no transaction and a request no call, the finals imsd builds left out a Via, From, To or Call-ID that came in compact form, and a short message whose content type came as `c:` was answered 200 and logged instead of taken (issue #2). MatchHeaderLine now takes a line under the name it is asked for or under that name's compact form: the ten RFC 3261 defines, and `o` for Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two extension headers imsd reads that have one. Every reader goes through it — Header, Headers, the framer, DatagramMessage — so no reader changes for it. It also takes white space between the name and the colon, which the same grammar allows (25.1's HCOLON; 7.3.1's "Subject : lunch") and the matcher refused. A value folded onto further lines is still read by its first line. One reader is changed for the rows it is now handed. ViaResponsePort gives the port the top Via names, to which the answer to a request that came in a datagram on a server port goes (RFC 3261 18.2.2), and none where that Via carries `rport` (RFC 3581): the answer then goes back to the port the request came from. It took `rport` for present where those five letters, in lower case, stood anywhere behind the row's first semicolon. Parameter names are case-insensitive (7.3.1), and a request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over, would have been answered to the port that Via names, its `rport` not seen. ViaResponsePort now reads the Via's parameters one by one, each to the next semicolon outside a quoted string, and `rport` is one by its name, in any case: not those letters in a value or in a longer name. Read so, the last parameter of the top value would run on into the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no `rport`, and 1.2.0's search of the letters found it —, so the top value is cut from the row first, at the first comma outside a quoted string. With that cut a lower value's `rport` no longer counts for the top one's, as it did in 1.2.0 for a list on one line. Tested by the suites: tests/Sip pins each of the twelve forms through Header, in lower and in upper case, and through Headers, `l:` through the framer and DatagramMessage, 7.3.1's four spellings of the colon, and ViaResponsePort's reading of a Via row, `rport` by its name and of a list on one line the top value alone; tests/Engine drives an incoming call from an INVITE in compact form, an outgoing call from responses in compact form and a delivered MESSAGE in compact form through the reducers; tests/Messages builds BuildResponse, BuildResponse200 and BuildInviteResponse for a request in compact form. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports, at this commit and at the one before) a request on a server port whose Via row is a list on one line with `rport` on its lower value is answered from the client-port socket, the way to the port its top value names, where the commit before answered it from the socket it had come on. On the dev phone the binary of this range's last commit answered a MESSAGE the phone sent to its own protected server port from the client-port socket where its Via row was such a list, and from the socket it had come on where its one Via came as `v: …;RPORT` (the capture's phone-form6, inject-bench.log). --- AGENTS.md | 51 ++++++++++----- interfaces/Imsd-Messages.cppm | 9 ++- interfaces/Imsd-Sip.cppm | 89 ++++++++++++++++++++----- tests/Engine/main.cpp | 95 ++++++++++++++++++++++++++- tests/Messages/main.cpp | 53 ++++++++++++++- tests/Sip/main.cpp | 118 +++++++++++++++++++++++++++++++--- 6 files changed, 367 insertions(+), 48 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 13c2710..36f0854 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,13 +41,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=`. | | `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 (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-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; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `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-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; `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 for an inbound MESSAGE outside a call's dialog (the 200, the 480, 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); in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; 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), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `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` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first `Via:` line and a request with none or an empty one never matched — answered with the same final and not handled again); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | +| `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. 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 for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; 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), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `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` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | | `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 and messaging (`Gated`'s `Action` parameter names the action), 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. | @@ -280,15 +280,31 @@ What the suites pin: - `Messages` — the outgoing SIP messages: the initial and the protected REGISTER, the reg-event SUBSCRIBE and the INVITEs byte-for-byte, their variants, the in-dialog requests, the ACKs, the CANCEL and - `BuildResponse200` by their lines, `BuildInviteResponse` not there - (`tests/Engine` checks the responses `CallMachine` builds with it); the + `BuildResponse200` by their lines, `BuildInviteResponse` by the lines of + one 180 and by a 486 without a Record-Route (`tests/Engine` checks the + responses `CallMachine` builds with it); the SMS over IP shapes (the `+g.3gpp.smsip` tag, the MESSAGE with an RP-DATA, the delivery report - with In-Reply-To, a 488) pinned against TS 24.341's clauses. + with In-Reply-To, a 488) pinned against TS 24.341's clauses; `BuildResponse`, + `BuildResponse200` and `BuildInviteResponse` on a request whose header + names come in compact form. - `Sip` — the text layer's edge cases (empty header values, line anchoring, 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 - skipped), `ResponseOf`, refused finals with reason headers, + skipped), the twelve compact forms (each through `Header`, in lower and + in upper case, and through `Headers`; no other letter taken for a + header name the suite lists; `l:` through the framer and + `DatagramMessage`), `ViaResponsePort`'s reading of a Via row — `rport` by its name (in + another case, with white space around it, with a value; those letters + in a value, in a longer name or in a quoted string not; a quoted string + ended by its closing quote — not by a quoted pair in it, and by the + quote behind an escaped backslash —), and of a row that holds a list + the top value alone (its port, a later value's `rport` and port not + counted, its own `rport` counted, last before the comma too; a comma + in a quoted string no end of it, the comma behind the closing quote + its end) —, white space before the colon (RFC 3261 7.3.1's four + spellings), + `ResponseOf`, refused finals with reason headers, reginfo documents, `HeaderUri` and `Body`. A change that flips one of those tests is a behaviour change, not a cleanup. - `Sdp` — the offer's exact bytes, the parser (the telephone-event payload @@ -323,7 +339,8 @@ What the suites pin: call, without the negotiation, for a character that is no tone or for a string past `DtmfMaxTones`; the receive payload type: our offer's on a renumbered answer, the answer's when the audio took ours, the echoed - offer's on an incoming call) and + offer's on an incoming call; an incoming call from an INVITE, and an + outgoing call from responses, whose header names come in compact form) and `RegRecovery` (thresholds, backoffs, the throttle 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 @@ -342,6 +359,10 @@ What the suites pin: 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 short message while SMS over IP is off refused with 480; + a delivered MESSAGE whose header names come in compact form — the 200 and + the delivery report of its long form, its retransmission key, the 480 + while SMS over IP is off — and a final in compact form taken by the + message in flight; 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, @@ -1561,15 +1582,15 @@ unmeasured. A MESSAGE outside a call's dialog whose `Content-Type` does not contain `application/vnd.3gpp.sms`, letter case ignored — a page-mode MESSAGE — is still answered 200 and logged with its body: the 200 is `BuildResponse`'s -now and the line names the content type (§7.8). Every header of a MESSAGE -is read by its long name, on one line with the colon straight after the -name: a compact form (RFC 3261 7.3.3) is not seen, so -a `c:` line is no `Content-Type`, an `i:` line no Call-ID and a `v:` line -no `Via`; nor is a name with white space before its colon, and of a value -folded onto further lines the first is read (7.3.1 allows both). +now and the line names the content type (§7.8). A header imsd reads is +found under its long name or, where it has one, its compact form (RFC +3261 7.3.3: a `c:` line is a `Content-Type`, an `i:` line a Call-ID, a +`v:` line a Via), with or without white space before the colon; of a +value folded onto further lines the first line is read (7.3.1 allows the +fold). - **A retransmitted MESSAGE** (the same Call-ID, CSeq and Via branch — the - value of the first `branch=` of its first `Via:` line; a MESSAGE with none + value of the first `branch=` of its first Via row; a MESSAGE with none or an empty one is never taken for a copy — within 32 s of our final: `RecentTransactions`, standing in for RFC 3261 17.2.2's server transaction) gets that final again and is not diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index 3fe5969..b31c72e 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -16,8 +16,8 @@ Covers: the unprotected + protected REGISTER and the refresh re-REGISTER an AMR-WB SDP offer and IMS MMTEL feature tags; the in-dialog PRACK/BYE and 2xx/non-2xx ACK; CANCEL (reusing the INVITE branch); the 200 OK that echoes an inbound request's dialog headers; the finals of the inbound MESSAGE -path, each `Via:` line echoed and the To tagged unless it holds `tag=` -(RFC 3261 8.2.6.2; long header names only); the UAS responses to an +path, each Via row echoed and the To tagged unless it holds `tag=` +(RFC 3261 8.2.6.2); the UAS responses to an inbound INVITE (100/180/200 and rejection finals); and the SIP MESSAGE that carries a short message's RP-DATA to the service centre, or its RP-ACK/RP-ERROR back to the IP-SM-GW @@ -522,9 +522,8 @@ export namespace imsd::msg { } // The final for an inbound MESSAGE outside a call's dialog — the 200 to one we took, the 480 or - // 488 to one we did not: each `Via:` line echoed in order (the response - // travels the proxy chain back, RFC 3261 8.2.6.2; long header names only, - // not the compact forms), From, To with + // 488 to one we did not: each Via row echoed in order (RFC 3261 + // 8.2.6.2), From, To with // `toTag` added unless the request's To holds `tag=` (8.2.6.2 again), // Call-ID and CSeq; no body. The shell's answers to any other request // outside a call but an INVITE (an OPTIONS, a NOTIFY, a method it does diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index 925cd3f..006c56b 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -7,9 +7,11 @@ Imsd:Sip — SIP message text layer + TCP framing. Deliberately a text layer, not a full RFC 3261 parser: the engine works on whole messages as strings and pulls out exactly what it needs (headers, status codes, the granted registration lifetime), which keeps every message -loggable and testable verbatim. Edge-case behavior (empty header values, -line anchoring, keepalive discards) is pinned by tests/Sip — a change that -flips one of those tests is a behavior change, not a cleanup. +loggable and testable verbatim. A header is asked for by its long name and +found under that or its compact form (RFC 3261 7.3.3). Edge-case behavior +(empty header values, line anchoring, white space before the colon, +keepalive discards) is pinned by tests/Sip — a change that flips one of +those tests is a behavior change, not a cleanup. Pure std C++ (no GLib). */ @@ -39,6 +41,19 @@ namespace imsd::sip { return s; } + // Where the piece of `s` that begins at `from` ends: at the first `sep` + // outside a quoted string (RFC 3261 25.1: in one, a backslash takes the + // next character with it), or at the end of `s`. + constexpr std::size_t PieceEnd(std::string_view s, std::size_t from, char sep) { + bool quoted = false; + for (std::size_t i = from; i < s.size(); i++) { + if (quoted && s[i] == '\\') i++; + else if (s[i] == '"') quoted = !quoted; + else if (!quoted && s[i] == sep) return i; + } + return s.size(); + } + // Iterate the \n-separated lines of the header section (any trailing CR // stays on the line and is stripped by Trim when a value is extracted). // The first empty line after a line of text ends the headers (RFC 3261 @@ -64,22 +79,52 @@ namespace imsd::sip { } } - // One "Name: value" match: name anchored at line start (case-insensitive, - // per RFC 3261 header names), immediately followed by the colon — no - // whitespace before it — and at least one character (even just the CR) - // after it. A bare "Name:\r" line matches with value ""; a "Name:" that - // ends the buffer does not match. Matching never crosses the line - // boundary: an empty-valued header yields "", NOT the next line's - // content (a regex-based implementation whose whitespace class eats the - // CRLF gets that wrong — pinned by the "bare header" test). - std::optional MatchHeaderLine(std::string_view line, std::string_view name) { + // The one-letter form a header name may be written in (RFC 3261 7.3.3: + // "Implementations MUST accept both the long and short forms of each + // header name"): the ten RFC 3261 defines (its section 20), and those + // of the two extension headers imsd reads that have one — Event (RFC + // 6665 7.3) and Session-Expires (RFC 4028 4). 0 for any other name: + // whoever starts reading another extension header adds its form here. + constexpr char CompactForm(std::string_view name) { + constexpr std::pair Forms[] = { + {"Call-ID", 'i'}, {"Contact", 'm'}, {"Content-Encoding", 'e'}, {"Content-Length", 'l'}, + {"Content-Type", 'c'}, {"From", 'f'}, {"Subject", 's'}, {"Supported", 'k'}, {"To", 't'}, + {"Via", 'v'}, {"Event", 'o'}, {"Session-Expires", 'x'}, + }; + for (const auto& [longForm, letter] : Forms) + if (name.size() == longForm.size() && IEqualsPrefix(name, longForm)) return letter; + return 0; + } + + // The value of a line that begins with the field name `name`: the name + // anchored at line start (case-insensitive, per RFC 3261 header names), + // then spaces or tabs, or none, then the colon (RFC 3261 25.1's HCOLON: + // "Subject : lunch" is 7.3.1's example) and at least one + // character (even just the CR) after it. A bare "Name:\r" line matches + // with value ""; a "Name:" that ends the buffer does not match. + // Matching never crosses the line boundary: an empty-valued header + // yields "", NOT the next line's content (a regex-based implementation + // whose whitespace class eats the CRLF gets that wrong — pinned by the + // "bare header" test), so of a value folded onto further lines (7.3.1) + // the first line is read. + std::optional ValueOfField(std::string_view line, std::string_view name) { if (!IEqualsPrefix(line, name)) return std::nullopt; - if (line.size() <= name.size() || line[name.size()] != ':') return std::nullopt; - std::string_view rest = line.substr(name.size() + 1); + std::size_t colon = name.size(); + while (colon < line.size() && (line[colon] == ' ' || line[colon] == '\t')) colon++; + if (colon >= line.size() || line[colon] != ':') return std::nullopt; + std::string_view rest = line.substr(colon + 1); if (rest.empty()) return std::nullopt; return Trim(rest); } + // One header line's match to `name`, the long form a reader asks by: + // the line carries that name, or its compact form. + std::optional MatchHeaderLine(std::string_view line, std::string_view name) { + if (auto v = ValueOfField(line, name)) return v; + if (const char letter = CompactForm(name)) return ValueOfField(line, std::string_view(&letter, 1)); + return std::nullopt; + } + // First run of ASCII digits starting at `s`; nullopt if none. std::optional LeadingDigits(std::string_view s) { std::size_t n = 0; @@ -223,13 +268,23 @@ export namespace imsd::sip { // the caller should reply to the request's source port instead // (nullopt). Also nullopt when the Via has no explicit port (5060 is // the default, but our P-CSCF flows always carry one). Handles - // "[v6]:port" and "host:port" sent-by forms. + // "[v6]:port" and "host:port" sent-by forms. rport (RFC 3581) is a + // parameter by its name, in any case (7.3.1): not those letters in a + // value or in a longer name. The top Via is the first value of the + // first Via row: a row may hold a list (7.3.1), and what follows its + // first comma outside a quoted string is another hop's. std::optional ViaResponsePort(std::string_view msg) { auto via = Header(msg, "Via"); if (!via) return std::nullopt; - std::string_view v = *via; + std::string_view v = via->substr(0, PieceEnd(*via, 0, ',')); if (std::size_t sc = v.find(';'); sc != std::string_view::npos) { - if (v.substr(sc).find("rport") != std::string_view::npos) return std::nullopt; + for (std::size_t at = sc; at < v.size();) { // each parameter, from its semicolon to the next + const std::size_t next = PieceEnd(v, at + 1, ';'); + std::string_view name = v.substr(at + 1, next - at - 1); + name = Trim(name.substr(0, name.find('='))); + if (name.size() == 5 && IEqualsPrefix(name, "rport")) return std::nullopt; + at = next; + } v = v.substr(0, sc); } std::size_t colon; diff --git a/tests/Engine/main.cpp b/tests/Engine/main.cpp index c9052b3..3615e0c 100644 --- a/tests/Engine/main.cpp +++ b/tests/Engine/main.cpp @@ -10,7 +10,9 @@ // reject -> 486, remote CANCEL -> 200+487, unusable offer -> 488 (naming // what was offered), a landline gateway's G.711-only and AMR-NB offers // ring and are answered at the offer's own payload types, ring timeout -> -// 480, BYE both ways. DTMF: the tones reach the media leg on an active +// 480, BYE both ways; an incoming call from an INVITE, and an outgoing +// call from responses, whose header names come in compact form (RFC 3261 +// 7.3.3). DTMF: the tones reach the media leg on an active // call that negotiated telephone-event, and are dropped — with the reason // — before the answer, after the call, without the negotiation or with a // character that is no tone. Then RegRecovery, the registration recovery policy: @@ -38,7 +40,8 @@ // 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, a short message while SMS -// over IP is off refused with 480), and the store's record codec +// over IP is off refused with 480, a delivered MESSAGE and a final whose +// header names come in compact form), and the store's record codec // (FormatStoredSms/ParseStoredSms: a full record round trip, defaults // for absent keys, a value that does not parse or a missing id refused) and order // (StoredSmsBefore: the arrival second, then within a run the sequence @@ -199,6 +202,20 @@ namespace { "Content-Length: {}\r\n\r\n{}", extraHeaders, sdp.size(), sdp); } + + // The same message with the header names that have a compact form + // written in it (RFC 3261 7.3.3: Via, From, To, Call-ID, Contact, + // Content-Type, Content-Length, Supported; Event, Session-Expires) — + // in the header section only, the start line and the body as they are. + std::string Compact(std::string_view msg) { + const std::size_t end = msg.find("\r\n\r\n"); + std::string head(msg.substr(0, end)); + for (auto [name, letter] : std::initializer_list>{ + {"\r\nVia:", "\r\nv:"}, {"\r\nFrom:", "\r\nf:"}, {"\r\nTo:", "\r\nt:"}, {"\r\nCall-ID:", "\r\ni:"}, {"\r\nContact:", "\r\nm:"}, + {"\r\nContent-Type:", "\r\nc:"}, {"\r\nContent-Length:", "\r\nl:"}, {"\r\nSupported:", "\r\nk:"}, {"\r\nEvent:", "\r\no:"}, {"\r\nSession-Expires:", "\r\nx:"}}) + for (std::size_t at = 0; (at = head.find(name, at)) != std::string::npos; at += letter.size()) head.replace(at, name.size(), letter); + return end == std::string_view::npos ? head : head + std::string(msg.substr(end)); + } } int main() { @@ -754,6 +771,56 @@ int main() { Check(t && t->reason == "local-hangup", "active hangup -> local-hangup"); } + // ---- an incoming call whose INVITE carries its header names in compact + // form (RFC 3261 7.3.3: "MUST accept both the long and short forms"): + // the same dialog as from the long names + { + const std::string invite = Compact(MtInvite()); + Check(!invite.contains("Via:") && !invite.contains("From:") && !invite.contains("\r\nTo:") && !invite.contains("Call-ID:") && !invite.contains("Contact:") && !invite.contains("Session-Expires:") && !invite.contains("Content-Type:") && !invite.contains("Content-Length:"), "the compact INVITE carries none of the eight long names"); + Check(invite.contains("\r\nv: SIP/2.0/UDP [2001:db8::9]:5060;branch=z9hG4bKscscf1\r\n") && invite.contains("\r\ni: mt-call-abc123\r\n") && invite.contains("\r\nx: 1800\r\n") && invite.ends_with("a=ptime:20\r\na=sendrecv\r\n"), "...their compact forms instead, the body untouched"); + imsd::util::Rng rng(33); + CallMachine m(c, rng, "ims-call-70", IncomingInvite{invite}, 50004); + Check(m.CallId() == "mt-call-abc123" && m.Number() == "+31612345678", "compact INVITE: the Call-ID from `i:`"); + auto ai = m.OnInvite(); + const Action* ringing = Responded(ai, "SIP/2.0 180 Ringing"); + Check(ringing && ringing->text.contains("\r\nVia: SIP/2.0/UDP [2001:db8::105]:5100;branch=z9hG4bKpcscf1\r\nVia: SIP/2.0/UDP [2001:db8::9]:5060;branch=z9hG4bKscscf1\r\n"), "compact INVITE: the 180 echoes both `v:` rows, in order, as Via"); + Check(ringing && ringing->text.contains("\r\nFrom: ;tag=caller1\r\n") && ringing->text.contains("\r\nTo: ;tag=") && ringing->text.contains("\r\nCall-ID: mt-call-abc123\r\n"), "compact INVITE: the 180 echoes the `f:`, the `t:` with our tag and the `i:`"); + auto aa = m.OnAccept(); + const Action* ok = Responded(aa, "SIP/2.0 200 OK"); + const Action* media = Find(aa, Action::Type::StartMedia); + Check(ok && ok->text.contains("Session-Expires: 1800;refresher=uac\r\n") && media && media->media.remotePort == 27864 && m.State() == CallState::Active, "compact INVITE: the 200 echoes the `x:` session timer, the offer is answered"); + // a refresh whose Session-Expires comes as `x:` + const std::string upd = Compact(std::format( + "UPDATE sip:me SIP/2.0\r\nVia: SIP/2.0/UDP [x]:1;branch=z9hG4bKu2\r\n" + "From: ;tag=caller1\r\n" + "To: ;tag=x\r\n" + "Min-SE: 90\r\nSession-Expires: 1800;refresher=uac\r\n" + "Call-ID: {}\r\nCSeq: 3 UPDATE\r\nContent-Length: 0\r\n\r\n", m.CallId())); + auto au = m.OnRequest(upd); + const Action* se200 = Responded(au, "SIP/2.0 200 OK"); + Check(upd.contains("\r\nx: 1800;refresher=uac\r\n") && se200 && se200->text.contains("Session-Expires: 1800;refresher=uac\r\n") && se200->text.contains("\r\nVia: SIP/2.0/UDP [x]:1;branch=z9hG4bKu2\r\n") && se200->text.contains(std::format("\r\nCall-ID: {}\r\n", m.CallId())), "compact UPDATE: the 200 echoes the `x:` timer and the `v:`, `i:` rows"); + // our BYE: to the caller's `m:` Contact, the `f:` From as its To, the `t:` To's URI as its From + auto ah = m.OnHangup(); + const Action* bye = Sent(ah, "BYE "); + Check(bye && bye->text.starts_with("BYE sip:origgw@[2001:db8::9]:5060 SIP/2.0\r\n") && bye->text.contains("\r\nTo: ;tag=caller1\r\n") && bye->text.contains("\r\nFrom: ;tag=") && bye->text.contains("\r\nCall-ID: mt-call-abc123\r\n"), "compact INVITE: our BYE goes to the `m:` Contact with the dialog the `f:`, `t:` and `i:` rows made"); + } + + // ---- an outgoing call whose responses carry compact names: the dialog + // from `t:` and `m:` + { + imsd::util::Rng rng(42); + CallMachine m(c, rng, "ims-call-71", "1233", 50004, false); + m.Start(); + const std::string r183 = Compact(R183(m.CallId())), r200 = Compact(R200(m.CallId())); + Check(!r183.contains("\r\nTo:") && !r183.contains("Contact:") && r183.contains("\r\nt: ;tag=remote7\r\n") && r200.contains("\r\nm: \r\n"), "the compact responses carry `t:` and `m:`"); + auto a183 = m.OnInviteResponse(r183); + const Action* prack = Sent(a183, "PRACK "); + Check(prack && prack->text.starts_with("PRACK sip:termgw@[2001:db8::9]:5060 SIP/2.0\r\n") && prack->text.contains("\r\nTo: ;tag=remote7\r\n"), "compact 183: the PRACK targets the `m:` Contact and carries the `t:` To"); + auto a200 = m.OnInviteResponse(r200); + const Action* ack = Sent(a200, "ACK "); + Check(ack && ack->text.starts_with("ACK sip:termgw@[2001:db8::9]:5060 SIP/2.0\r\n") && ack->text.contains("\r\nTo: ;tag=remote7\r\n") && Has(a200, Action::Type::StartMedia) && m.State() == CallState::Active, "compact 200: the ACK to the `m:` Contact with the `t:` To, the call active"); + } + // ---- media death after accept releases the call { imsd::util::Rng rng(35); @@ -1490,6 +1557,28 @@ int main() { 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"); } + // the same delivery with its header names in compact form (RFC 3261 7.3.3): `c:` is the content type, `i:` the Call-ID, `v:` the Via + { + const std::string longForm = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07"); + const std::string compact = Compact(longForm); + Check(!compact.contains("Content-Type:") && !compact.contains("Call-ID:") && !compact.contains("Via:") && compact.contains("\r\nc: application/vnd.3gpp.sms\r\n") && compact.contains("\r\ni: in-011107@net\r\n") && compact.contains("\r\nv: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn1\r\n") && compact.contains(std::format("\r\nl: {}\r\n", imsd::sip::Body(longForm).size())) && imsd::sip::Body(longForm).size() == 42 && imsd::sip::Body(compact) == imsd::sip::Body(longForm), "the compact MESSAGE carries `c:`, `i:`, `v:` and `l:`, the body of 42 bytes as it was"); + imsd::util::Rng rng(80), rngLong(80); + Reassembler re, reLong; + auto r = OnSmsMessage(c, rng, compact, re, nullptr, 50.0); + auto want = OnSmsMessage(c, rngLong, longForm, reLong, nullptr, 50.0); + const auto* rec = findSms(r.actions, SmsAction::Type::Received); + const auto* rep = findSms(r.actions, SmsAction::Type::SendClient); + const auto* wantRep = findSms(want.actions, SmsAction::Type::SendClient); + Check(r.response == want.response && r.response.starts_with("SIP/2.0 200 OK\r\nVia: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn1\r\n") && r.response.contains("\r\nCall-ID: in-011107@net\r\n"), "compact MESSAGE: the 200 of the long form, the `v:` and the `i:` echoed as Via and Call-ID"); + Check(rec && rec->received.text == "How are you?" && rep && wantRep && rep->text == wantRep->text && rep->text.contains("\r\nIn-Reply-To: in-011107@net\r\n"), "compact MESSAGE: taken for a short message, and its delivery report names the `i:` Call-ID in In-Reply-To"); + Check(RecentTransactions::Key(compact) == "in-011107@net|1 MESSAGE|z9hG4bKn1" && RecentTransactions::Key(compact) == RecentTransactions::Key(longForm), "compact MESSAGE: the retransmission key from `i:` and `v:`"); + // the final to a MESSAGE of ours, its Call-ID as `i:` + imsd::util::Rng rngOut(81); + SmsOutbound m(c, rngOut, "ims-sms-20", p); + const std::string callid(imsd::sip::Header(findSms(m.Start(0.0), SmsAction::Type::SendClient)->text, "Call-ID").value_or("")); + const std::string final202 = Compact(final(callid, 202, "Accepted")); + Check(final202.contains(std::format("\r\ni: {}\r\n", callid)) && !final202.contains("Call-ID:") && m.OwnsResponse(final202), "outbound: a final whose Call-ID comes as `i:` is the message in flight's"); + } // 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; @@ -1735,6 +1824,8 @@ int main() { const std::string plain = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn3\r\nFrom: ;tag=1\r\nTo: \r\nCall-ID: t2@net\r\nCSeq: 1 MESSAGE\r\nContent-Type: text/plain\r\nContent-Length: 2\r\n\r\nhi"; auto r2 = OnSmsMessage(off, rng, plain, re, nullptr, 9.0); Check(r2.response.starts_with("SIP/2.0 200 OK") && hasSms(r2.actions, SmsAction::Type::Log), "off: a page-mode text is still 200'd and logged"); + auto r3 = OnSmsMessage(off, rng, Compact(offered), re, nullptr, 9.5); + Check(r3.response.starts_with("SIP/2.0 480 Temporarily Unavailable\r\n") && r3.response.contains("\r\nCall-ID: in-011107@net\r\n") && !r3.rp, "off: a short message whose content type comes as `c:` is refused with 480 too"); } } diff --git a/tests/Messages/main.cpp b/tests/Messages/main.cpp index 519ed15..974507b 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -5,7 +5,8 @@ // compared byte-for-byte against a reference message cross-generated from the // Python VoLTE stack with pinned tags/branches/SPIs; their variants and the other // builders against a message written here or by their lines (BuildInviteResponse -// is not called). A divergence here is a wire-format change, i.e. a +// by the lines of one 180 and by its answers to an INVITE in long and in +// compact form). A divergence here is a wire-format change, i.e. a // registration or call that the commercial IMS core may reject; these are the // hardest pins in the project. Two deliberate post-parity divergences: // the REGISTER Contact carries +sip.instance and the MMTEL ICSI feature tag @@ -501,6 +502,56 @@ int main() { "Content-Length: 0\r\n\r\n", "a 488 for an inbound MESSAGE echoes every Via and tags To"); const std::string tagged = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet2\r\nFrom: ;tag=N2\r\nTo: ;tag=had\r\nCall-ID: in2@net\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n"; Check(BuildResponse(c, tagged, 200, "OK", "unused").contains("\r\nTo: ;tag=had\r\n"), "a To that already carries a tag is echoed as it is"); + // a request whose header names come in compact form (RFC 3261 7.3.3): the finals echo them under the long names + const std::string compact = + "MESSAGE sip:me@[2001:db8::db43]:45062 SIP/2.0\r\n" + "v: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n" + "V: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n" + "f: ;tag=N1\r\n" + "t: \r\n" + "i: in1@net\r\n" + "CSeq: 9 MESSAGE\r\n" + "l: 0\r\n\r\n"; + Eq(BuildResponse(c, compact, 488, "Not Acceptable Here", "T488"), BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"), "a 488 for a MESSAGE in compact form is the one for its long form"); + Eq(BuildResponse200(c, compact), BuildResponse200(c, inbound), "the hop-by-hop 200 for a request in compact form is the one for its long form"); + Check(BuildResponse200(c, compact).contains("\r\nFrom: ;tag=N1\r\nTo: \r\nCall-ID: in1@net\r\nCSeq: 9 MESSAGE\r\n"), "with its `f:`, `t:` and `i:` under the long names"); + // BuildInviteResponse reads the same names: an INVITE in compact form gets the responses of its long form + const std::string invite = + "INVITE sip:me@[2001:db8::db43]:45062 SIP/2.0\r\n" + "Via: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n" + "Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n" + "Record-Route: \r\n" + "From: ;tag=N3\r\n" + "To: \r\n" + "Call-ID: call3@net\r\n" + "CSeq: 1 INVITE\r\n" + "Content-Length: 0\r\n\r\n"; + const std::string compactInvite = + "INVITE sip:me@[2001:db8::db43]:45062 SIP/2.0\r\n" + "v: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n" + "V: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n" + "Record-Route: \r\n" + "f: ;tag=N3\r\n" + "t: \r\n" + "i: call3@net\r\n" + "CSeq: 1 INVITE\r\n" + "l: 0\r\n\r\n"; + const std::string ringing = BuildInviteResponse(c, invite, 180, "Ringing", "T180"); + Eq(ringing, + "SIP/2.0 180 Ringing\r\n" + "Via: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKnet3\r\n" + "Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw3\r\n" + "Record-Route: \r\n" + "From: ;tag=N3\r\n" + "To: ;tag=T180\r\n" + "Call-ID: call3@net\r\n" + "CSeq: 1 INVITE\r\n" + "Contact: \r\n" + "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER\r\n" + "Content-Length: 0\r\n\r\n", "a 180 for an INVITE echoes every Via and the Record-Route, tags To and carries our Contact and Allow"); + Eq(BuildInviteResponse(c, compactInvite, 180, "Ringing", "T180"), ringing, "a 180 for an INVITE in compact form is the one for its long form"); + Eq(BuildInviteResponse(c, compactInvite, 486, "Busy Here", "T486"), BuildInviteResponse(c, invite, 486, "Busy Here", "T486"), "and so is a 486"); + Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("\r\nTo: ;tag=T486\r\n") && !BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("Record-Route"), "a 486 tags To and returns no Record-Route"); { const std::string body = "hi\r\nVia: SIP/2.0/UDP 192.0.2.66;branch=z9hG4bKx"; const std::string tail = "Content-Length: 0\r\n\r\n"; diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 2844f07..77fc8b8 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -1,14 +1,15 @@ // SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® -// Imsd:Sip unit tests — header access, status-line parsing, granted-expires -// extraction, caller-identity extraction, the port a Via names for the -// response (ViaResponsePort), the two framers — the TCP frame buffer (split -// delivery, keepalive pongs, pipelined messages) and a datagram's -// (DatagramMessage) —, a refused final's Retry-After and summary (RetryAfter, -// RefusalSummary), transaction matching (ResponseOf), our binding in a -// reg-event document (RegInfoContactState), and HeaderUri and Body. These pin -// the module's edge-case behavior; see the module header before "fixing" one. +// Imsd:Sip unit tests — header access (compact forms and white space before +// the colon among it), status-line parsing, granted-expires extraction, +// caller-identity extraction, the port a Via names for the response +// (ViaResponsePort), the two framers — the TCP frame buffer (split delivery, +// keepalive pongs, pipelined messages) and a datagram's (DatagramMessage) —, +// a refused final's Retry-After and summary (RetryAfter, RefusalSummary), +// transaction matching (ResponseOf), our binding in a reg-event document +// (RegInfoContactState), and HeaderUri and Body. These pin the module's +// edge-case behavior; see the module header before "fixing" one. import std; import Imsd; @@ -69,6 +70,63 @@ int main() { Check(!Header(BodyVia, "X-Body").has_value(), "Header never reads the body"); Check(Header("\r\n\r\nSIP/2.0 200 OK\r\nCall-ID: k\r\n\r\n", "Call-ID") == "k", "empty lines before the first line of text (a keepalive's CRLFs) are skipped"); + // ---- compact forms (RFC 3261 7.3.3: "MUST accept both the long and short forms of each header name") + { + // RFC 3261's ten (section 20), then Event (RFC 6665 7.3) and Session-Expires (RFC 4028 4) + const std::pair forms[] = { + {"Call-ID", 'i'}, {"Contact", 'm'}, {"Content-Encoding", 'e'}, {"Content-Length", 'l'}, {"Content-Type", 'c'}, {"From", 'f'}, + {"Subject", 's'}, {"Supported", 'k'}, {"To", 't'}, {"Via", 'v'}, {"Event", 'o'}, {"Session-Expires", 'x'}, + }; + // every letter against the header names below — those imsd reads, and the three of the RFC's ten it does not: the twelve pairs match, nothing else does + { + const std::string_view names[] = {"Call-ID", "CSeq", "To", "From", "Via", "Contact", "Record-Route", "P-Associated-URI", "Session-Expires", "Require", "P-Asserted-Identity", "Subscription-State", "Service-Route", "Security-Server", "RSeq", "Retry-After", "Reason", "Path", "In-Reply-To", "Expires", "Event", "Content-Type", "Content-Length", "Warning", "Server", "Content-Encoding", "Subject", "Supported"}; + int pairs = 0; + bool onlyThose = true; + for (char letter = 'a'; letter <= 'z'; letter++) + for (std::string_view name : names) { + const bool found = Header(std::format("OPTIONS sip:a@b SIP/2.0\r\n{}: v\r\n\r\n", letter), name).has_value(); + const bool paired = std::ranges::any_of(forms, [&](const auto& form) { return form.first == name && form.second == letter; }); + if (found) pairs++; + if (found != paired) onlyThose = false; + } + Check(pairs == 12 && onlyThose, "of the letters a to z against the header names listed, the twelve pairs are compact forms and no other letter is taken for a name"); + } + for (const auto& [name, letter] : forms) { + const std::string lower = std::format("OPTIONS sip:a@b SIP/2.0\r\n{}: value-{}\r\n\r\n", letter, letter); + const std::string upper = std::format("OPTIONS sip:a@b SIP/2.0\r\n{}: value-{}\r\n\r\n", static_cast(letter - 'a' + 'A'), letter); + const std::string expect = std::format("value-{}", letter); + Check(Header(lower, name) == expect, std::format("Header: `{}:` is read as {}", letter, name)); + Check(Header(upper, name) == expect, std::format("Header: the compact form of {} in upper case is read too", name)); + Check(Headers(lower, name) == std::vector{expect}, std::format("Headers: `{}:` is a row of {}", letter, name)); + // no other name of the twelve takes that line + for (const auto& [other, otherLetter] : forms) + if (other != name) Check(!Header(lower, other).has_value(), std::format("Header: `{}:` is no {}", letter, other)); + } + // a name with no compact form is found under its long form only + Check(!Header("NOTIFY sip:a@b SIP/2.0\r\nr: \r\ns: active\r\n\r\n", "Record-Route").has_value() && !Header("NOTIFY sip:a@b SIP/2.0\r\nr: \r\ns: active\r\n\r\n", "Subscription-State").has_value(), "Header: a name that has no compact form is not found under a letter"); + // both forms in one message, in the order they stand (7.3.3: a name MAY appear in both forms) + const std::string mixed = "MESSAGE sip:a@b SIP/2.0\r\nVia: one\r\nv: two\r\nV: three\r\nVia: four\r\ni: c1@h\r\n\r\n"; + Check(Headers(mixed, "Via") == std::vector{"one", "two", "three", "four"} && Header(mixed, "Via") == "one" && Header(mixed, "Call-ID") == "c1@h", "Headers: long and compact rows of one name are one list, in order"); + // asked for in another case, the compact form is found all the same; a longer name that begins with a long form has none + Check(Header(mixed, "call-id") == "c1@h" && Header(mixed, "CALL-ID") == "c1@h" && Headers(mixed, "VIA").size() == 4, "Header: the name asked for in lower or upper case finds its compact form"); + Check(!Header(mixed, "Via-Info").has_value() && !Header(mixed, "Call-ID-Extra").has_value(), "Header: a name that only begins with one that has a compact form has none"); + // a longer name that begins with the letter is not the compact form + Check(!Header("MESSAGE sip:a@b SIP/2.0\r\nTimestamp: 54\r\nVersion: 1\r\n\r\n", "To").has_value() && !Header("MESSAGE sip:a@b SIP/2.0\r\nTimestamp: 54\r\nVersion: 1\r\n\r\n", "Via").has_value(), "Header: a name that only begins with a compact letter is not that header"); + } + + // ---- white space before the colon (RFC 3261 7.3.1, 25.1 HCOLON) + { + // 7.3.1's four equivalent spellings + for (std::string_view line : {"Subject: lunch", "Subject : lunch", "Subject :lunch", "Subject: lunch"}) + Check(Header(std::format("MESSAGE sip:a@b SIP/2.0\r\n{}\r\n\r\n", line), "Subject") == "lunch", std::format("Header: `{}` reads as lunch", line)); + Check(Header("MESSAGE sip:a@b SIP/2.0\r\nCall-ID\t: c2@h\r\ni \t : c3@h\r\n\r\n", "Call-ID") == "c2@h" && Headers("MESSAGE sip:a@b SIP/2.0\r\nCall-ID\t: c2@h\r\ni \t : c3@h\r\n\r\n", "Call-ID").size() == 2, "Header: a tab or spaces before the colon, after the long or the compact form"); + Check(!Header("MESSAGE sip:a@b SIP/2.0\r\nTo be: or not\r\nt x: y\r\n\r\n", "To").has_value(), "Header: a word between the name and the colon is another field name"); + Check(Header("X-Empty :\r\nX-Real: v\r\n\r\n", "X-Empty") == "" && !Header("X-Last :", "X-Last").has_value(), "a bare header with a space before its colon matches with an empty value; one that ends the buffer does not"); + // a name, or a name and white space, that ends the text is no header — also where a colon stands in the bytes right after the text + Check(!Header("A: 1\r\nTo", "To").has_value() && !Header("A: 1\r\nTo \t", "To").has_value() && !Header("A: 1\r\nt", "To").has_value(), "a name that ends the text, with or without white space after it, is no header"); + Check(!Header(std::string_view("A: 1\r\nTo:v").substr(0, 8), "To").has_value() && !Header(std::string_view("A: 1\r\nTo \t:v").substr(0, 10), "To").has_value(), "nor is it where a colon follows in the bytes past the text's end"); + } + // ---- GrantedExpires Check(GrantedExpires(Resp200) == 600000, "GrantedExpires from Contact expires="); Check(GrantedExpires("SIP/2.0 200 OK\r\nExpires: 3600\r\n\r\n") == 3600, "GrantedExpires falls back to Expires"); @@ -123,6 +181,18 @@ int main() { Check(fb.TryExtract() == msg, "no Content-Length -> body length 0"); Check(fb.Size() == 8, "trailing bytes stay buffered"); } + { + // the body's length under the compact name (RFC 3261 7.3.3), and with a space before the colon (7.3.1) + const std::string compact = "MESSAGE sip:a@b SIP/2.0\r\ni: c1@h\r\nl: 5\r\n\r\nhello"; + const std::string spaced = "MESSAGE sip:a@b SIP/2.0\r\nCall-ID: c2@h\r\nContent-Length : 3\r\n\r\nabc"; + FrameBuffer fb; + fb.Append(compact + spaced + Resp200); + Check(fb.TryExtract() == compact, "`l: 5` frames a body of five bytes"); + Check(fb.TryExtract() == spaced, "`Content-Length : 3` frames a body of three"); + Check(fb.TryExtract() == Resp200 && !fb.TryExtract().has_value(), "the message after them starts where their bodies end"); + fb.Append(compact.substr(0, compact.size() - 2)); + Check(!fb.TryExtract().has_value(), "a body shorter than `l:` says is waited for"); + } // ---- CallerId: P-Asserted-Identity preferred, From fallback { @@ -163,6 +233,14 @@ int main() { Check(CallerId("INVITE sip:me SIP/2.0\r\nContent-Length: 0\r\n\r\n").empty(), "no identity headers -> empty"); } + // ---- the readers above under compact names + { + Check(CallerId("INVITE sip:me SIP/2.0\r\nf: ;tag=f\r\nl: 0\r\n\r\n") == "+31687654321", "CallerId: a From that comes as `f:`"); + Check(HeaderUri("MESSAGE sip:me SIP/2.0\r\nf: \"GW\" ;tag=f\r\nl: 0\r\n\r\n", "From") == "sip:ipsmgw@ims.example", "HeaderUri: a From that comes as `f:`"); + Check(GrantedExpires("SIP/2.0 200 OK\r\nm: ;expires=7200\r\n\r\n") == 7200, "GrantedExpires: a Contact that comes as `m:`"); + Check(ViaResponsePort("UPDATE sip:me SIP/2.0\r\nv: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKx\r\nl: 0\r\n\r\n") == 6000, "ViaResponsePort: a Via that comes as `v:`"); + } + // ---- ViaResponsePort: RFC 3261 18.2.2 UDP response routing { std::string upd = @@ -186,6 +264,25 @@ int main() { "Content-Length: 0\r\n\r\n"; Check(!ViaResponsePort(np).has_value(), "portless v6 sent-by -> nullopt"); Check(!ViaResponsePort("UPDATE sip:me SIP/2.0\r\n\r\n").has_value(), "no Via -> nullopt"); + // rport is a parameter by its name (RFC 3581), in any case (RFC 3261 7.3.1) + const std::string top = "SIP/2.0/UDP [2001:db8::105]:6000"; + auto row = [](std::string_view value) { return std::format("BYE sip:me SIP/2.0\r\nVia: {}\r\nContent-Length: 0\r\n\r\n", value); }; + Check(!ViaResponsePort(row(top + ";RPort;branch=z9hG4bKp")).has_value(), "rport in another case"); + Check(!ViaResponsePort(row(top + " ; rport ;branch=z9hG4bKp")).has_value(), "rport with white space around it"); + Check(!ViaResponsePort(row(top + ";rport=6001;branch=z9hG4bKp")).has_value(), "rport that came with a value"); + Check(ViaResponsePort(row(top + ";branch=z9hG4bKrport;xrport;rportx=1")) == 6000, "those letters in a value or in a longer name are no rport"); + Check(ViaResponsePort(row(top + ";x=\"a;rport;b\";branch=z9hG4bKp")) == 6000, "nor between semicolons in a quoted string"); + Check(!ViaResponsePort(row(top + ";x=\"a;b\";rport")).has_value(), "a quoted string ends at its closing quote"); + Check(ViaResponsePort(row(top + ";x=\"a\\\";rport;b\"")) == 6000, "and a quoted pair in it does not close it"); + Check(!ViaResponsePort(row(top + ";x=\"a\\\\\";rport")).has_value(), "the quote behind an escaped backslash does"); + // a row that holds a list (RFC 3261 7.3.1): the top value alone speaks + const std::string next = "SIP/2.0/UDP [2001:db8::9]:5060"; + Check(ViaResponsePort(row(top + ";branch=z9hG4bKp, " + next + ";branch=z9hG4bKs;rport=5060")) == 6000, "a list on one line: the top value's port, a later value's rport not counted"); + Check(!ViaResponsePort(row(top + ";rport;branch=z9hG4bKp, " + next + ";branch=z9hG4bKs")).has_value(), "the top value's own rport counts"); + Check(!ViaResponsePort(row(top + ";branch=z9hG4bKp;rport, " + next + ";branch=z9hG4bKs")).has_value(), "also where it stands last before the comma"); + Check(ViaResponsePort(row(top + ", " + next + ";branch=z9hG4bKs")) == 6000, "a top value without parameters: its own port, not the next value's"); + Check(!ViaResponsePort(row(top + ";x=\"a,b\";rport, " + next)).has_value(), "a comma in a quoted string does not end the top value"); + Check(ViaResponsePort(row(top + ";x=\"a,b\";branch=z9hG4bKp, " + next + ";rport=5060")) == 6000, "the comma behind that string's closing quote does"); } // ---- DatagramMessage (one UDP datagram = one message, RFC 3261 18.3) @@ -208,6 +305,10 @@ int main() { Check(m3 && *m3 == hdr + "X-Note: Content-Length: 99\r\n\r\nv=0\n", "a header name inside a value does not match"); auto m4 = DatagramMessage(hdr + "Content-Length: 99999999999999999999\r\n\r\nv=0\n", &why); Check(!m4.has_value(), "absurd Content-Length: discarded, no overflow"); + auto m5 = DatagramMessage(hdr + "l: 4\r\n\r\nv=0\nJUNK"); + Check(m5 && *m5 == hdr + "l: 4\r\n\r\nv=0\n", "`l:` that fits truncates the body like Content-Length"); + why.clear(); + Check(!DatagramMessage(hdr + "L : 40\r\n\r\nv=0\n", &why).has_value() && why.contains("truncated"), "`L :` larger than the datagram: discarded, problem set"); } // ---- RetryAfter / RefusalSummary (what a refused final is logged as) @@ -253,6 +354,7 @@ int main() { Check(ResponseOf(stale, "earlier@[2001:db8::db43]", "1 REGISTER"), "matched by Call-ID and CSeq"); Check(!ResponseOf("NOTIFY sip:x SIP/2.0\r\nCall-ID: 12345@host\r\nCSeq: 2 REGISTER\r\n\r\n", "12345@host", "2 REGISTER"), "a request is never a response"); Check(!ResponseOf("", "12345@host", "2 REGISTER"), "nothing is not it"); + Check(ResponseOf("SIP/2.0 202 Accepted\r\nv: SIP/2.0/TCP [2001:db8::db43]:45062;branch=z9hG4bKx\r\ni: 12345@host\r\nCSeq: 1 MESSAGE\r\nl: 0\r\n\r\n", "12345@host", "1 MESSAGE"), "a final whose Call-ID comes as `i:` is the transaction's"); } // ---- RegInfoContactState: our binding in a reg-event NOTIFY (RFC 3680) From 78c702546af8468e77be47245b0790305b526f48 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 05/40] sip: ResponseOf compares a response's CSeq as its number and its method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ResponseOf matched a response to a request by its Call-ID and by its CSeq compared as text. RFC 3261 25.1 writes the CSeq as 1*DIGIT LWS Method, so a response may part the two by a tab or by more than one space, and one written so was no transaction's: a REGISTER's wait ran out without a reply. CSeqParts takes a CSeq value as its number and its method: the digits it begins with, the spaces or tabs after them, the method to the value's end. ResponseOf compares the two as 20.16 has two CSeqs equal, "if the sequence number and the request method are identical": the number as a number — zeros before it do not make it another — and the method to the letter. A value of another shape matches nothing. Tested by tests/Sip: a final whose CSeq has two spaces, a tab or both between its parts, or zeros before its number, is the transaction's, and so is its 100 Trying; another number, another method, a method in other letter case, and a CSeq without its number, its method or the white space between them are not. --- AGENTS.md | 9 +++++++-- interfaces/Imsd-Sip.cppm | 26 ++++++++++++++++++++++++-- tests/Sip/main.cpp | 19 +++++++++++++++++++ 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 36f0854..720f6fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,7 @@ 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=`. | | `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 (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `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-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; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number). 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. | @@ -304,7 +304,12 @@ What the suites pin: in a quoted string no end of it, the comma behind the closing quote its end) —, white space before the colon (RFC 3261 7.3.1's four spellings), - `ResponseOf`, refused finals with reason headers, + `ResponseOf` (the transaction's own 100 Trying; a final whose CSeq parts + its number and its method by two spaces, by a tab or by both, or has + zeros before its number: the + transaction's; another number, another method, a method in other letter + case, a CSeq without one of the two: not), refused finals with reason + headers, reginfo documents, `HeaderUri` and `Body`. A change that flips one of those tests is a behaviour change, not a cleanup. - `Sdp` — the offer's exact bytes, the parser (the telephone-event payload diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index 006c56b..c91a332 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -136,6 +136,21 @@ namespace imsd::sip { if (ec != std::errc{}) return std::nullopt; return v; } + + // A CSeq value as its sequence number and its method (RFC 3261 25.1: + // 1*DIGIT LWS Method): the digits the trimmed value begins with, less + // the zeros before the number, the spaces or tabs after them, then the + // method to the value's end. nullopt where no space or tab follows the + // digits. + std::optional> CSeqParts(std::string_view v) { + v = Trim(v); + const std::size_t digits = v.find_first_not_of("0123456789"); + const std::size_t method = v.find_first_not_of(" \t", digits); + if (method == digits) return std::nullopt; + std::string_view number = v.substr(0, digits); + while (number.starts_with('0')) number.remove_prefix(1); + return std::pair{number, v.substr(method)}; + } } export namespace imsd::sip { @@ -178,9 +193,16 @@ export namespace imsd::sip { // True for a response of the transaction (callid, cseq) — the reply a // wait for that request may judge. A request, another transaction's - // response or anything else a socket delivers is not. + // response or anything else a socket delivers is not. Two CSeqs are + // equal "if the sequence number and the request method are identical" + // (RFC 3261 20.16): they are compared so, whatever spaces or tabs part + // the two and whatever zeros stand before the number. bool ResponseOf(std::string_view msg, std::string_view callid, std::string_view cseq) { - return Status(msg).has_value() && Header(msg, "Call-ID") == callid && Header(msg, "CSeq") == cseq; + if (!Status(msg).has_value() || Header(msg, "Call-ID") != callid) return false; + const auto theirs = Header(msg, "CSeq"); + if (!theirs) return false; + const auto a = CSeqParts(*theirs), b = CSeqParts(cseq); + return a && b && *a == *b; } // Retry-After of a response (RFC 3261 20.33), in seconds; nullopt when diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 77fc8b8..62ce946 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -355,6 +355,25 @@ int main() { Check(!ResponseOf("NOTIFY sip:x SIP/2.0\r\nCall-ID: 12345@host\r\nCSeq: 2 REGISTER\r\n\r\n", "12345@host", "2 REGISTER"), "a request is never a response"); Check(!ResponseOf("", "12345@host", "2 REGISTER"), "nothing is not it"); Check(ResponseOf("SIP/2.0 202 Accepted\r\nv: SIP/2.0/TCP [2001:db8::db43]:45062;branch=z9hG4bKx\r\ni: 12345@host\r\nCSeq: 1 MESSAGE\r\nl: 0\r\n\r\n", "12345@host", "1 MESSAGE"), "a final whose Call-ID comes as `i:` is the transaction's"); + // a provisional of the transaction is its response too: both REGISTER waits start over on one + Check(ResponseOf("SIP/2.0 100 Trying\r\nCall-ID: 12345@host\r\nCSeq: 2 REGISTER\r\nContent-Length: 0\r\n\r\n", "12345@host", "2 REGISTER"), "the transaction's 100 Trying is its response"); + // the CSeq as its number and its method (RFC 3261 20.16: equal "if the sequence number and the request method are identical"; 25.1: 1*DIGIT LWS Method), whatever spaces or tabs part them + auto finalWith = [](std::string_view cseq) { return std::format("SIP/2.0 202 Accepted\r\nCall-ID: 12345@host\r\nCSeq: {}\r\nContent-Length: 0\r\n\r\n", cseq); }; + Check(ResponseOf(finalWith("1 MESSAGE"), "12345@host", "1 MESSAGE"), "two spaces between the CSeq's number and its method: the transaction's"); + Check(ResponseOf(finalWith("1\tMESSAGE"), "12345@host", "1 MESSAGE"), "a tab between them: the transaction's"); + Check(ResponseOf(finalWith("1 \t MESSAGE"), "12345@host", "1 MESSAGE"), "spaces and a tab between them: the transaction's"); + Check(ResponseOf(finalWith("01 MESSAGE"), "12345@host", "1 MESSAGE") && ResponseOf(finalWith("1 MESSAGE"), "12345@host", "001 MESSAGE"), "zeros before the number do not make it another"); + Check(ResponseOf(finalWith("0 MESSAGE"), "12345@host", "00 MESSAGE") && !ResponseOf(finalWith("10 MESSAGE"), "12345@host", "1 MESSAGE"), "zero is zero however long, and a zero after the number counts"); + Check(ResponseOf(finalWith("1 MESSAGE"), "12345@host", " 1 MESSAGE "), "white space around the CSeq asked for is no part of it"); + Check(!ResponseOf(finalWith("11 MESSAGE"), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith("1 MESSAGE"), "12345@host", "11 MESSAGE"), "another number that begins alike is not it"); + Check(!ResponseOf(finalWith("1 MESSAGES"), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith("1 MESSAG"), "12345@host", "1 MESSAGE"), "another method that begins alike is not it"); + Check(!ResponseOf(finalWith("1 message"), "12345@host", "1 MESSAGE"), "a method is a case-sensitive token"); + Check(!ResponseOf(finalWith("1MESSAGE"), "12345@host", "1 MESSAGE"), "no white space between number and method: not a CSeq"); + Check(!ResponseOf(finalWith("1 "), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith("1"), "12345@host", "1 MESSAGE"), "a CSeq without a method is not it"); + Check(!ResponseOf(finalWith("MESSAGE"), "12345@host", "1 MESSAGE") && !ResponseOf(finalWith(" MESSAGE"), "12345@host", "1 MESSAGE"), "a CSeq without a number is not it"); + Check(!ResponseOf("SIP/2.0 202 Accepted\r\nCall-ID: 12345@host\r\nContent-Length: 0\r\n\r\n", "12345@host", "1 MESSAGE"), "a final without a CSeq is not it"); + Check(!ResponseOf(finalWith("1 MESSAGE"), "12345@host", "MESSAGE"), "asked with a CSeq of another shape: nothing is it"); + Check(!ResponseOf(finalWith("MESSAGE"), "12345@host", "MESSAGE") && !ResponseOf(finalWith("1MESSAGE"), "12345@host", "1MESSAGE"), "two CSeqs of another shape are no match, alike or not"); } // ---- RegInfoContactState: our binding in a reg-event NOTIFY (RFC 3680) From c81dd3d2678fc225600f4ace79b0a1758ea2399b Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 06/40] sip: both framers read a Content-Length as a number DatagramMessage read the first nine characters of a Content-Length, the zeros before its number among them: a length written 0000000005 came out as 0, and the body after it was cut off as bytes past the message. FrameBuffer read the value into a long, and one too long for that counted as no Content-Length: the body was framed as the start of the next message. RFC 3261 25.1 writes the value as 1*DIGIT. LengthOf reads it for both: the number its leading digits spell, zeros before it aside; of a number of more than nine digits the first nine, more than a datagram holds and enough that a stream waits. A value that begins with no digit is no length, as before. Tested by tests/Sip through both framers: a length of one digit written with ten zeros before it frames that many bytes; a twenty-digit length that wraps to zero in 64 bits is a datagram cut short and a stream's body waited for; a value without a leading digit leaves a datagram's body the rest of it and a stream's empty. --- AGENTS.md | 4 +++- interfaces/Imsd-Sip.cppm | 21 +++++++++++++++++---- tests/Sip/main.cpp | 25 ++++++++++++++++++++----- 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 720f6fe..23f6b4f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -291,7 +291,9 @@ What the suites pin: - `Sip` — the text layer's edge cases (empty header values, line anchoring, 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 - skipped), the twelve compact forms (each through `Header`, in lower and + skipped), the Content-Length the two framers read (zeros before its + number no part of it; a number past any that fits not read as zero; a + value that begins with no digit read as none), the twelve compact forms (each through `Header`, in lower and in upper case, and through `Headers`; no other letter taken for a header name the suite lists; `l:` through the framer and `DatagramMessage`), `ViaResponsePort`'s reading of a Via row — `rport` by its name (in diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index c91a332..f0d97c6 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -137,6 +137,20 @@ namespace imsd::sip { return v; } + // The length a Content-Length value names: the number its leading + // digits spell (RFC 3261 25.1: 1*DIGIT), zeros before it aside; nullopt + // where the value begins with no digit. Of a number of more than nine + // digits the first nine are read — more than a datagram holds, and + // enough that a stream waits for a body that does not come. + std::optional LengthOf(std::string_view v) { + std::string_view digits = v.substr(0, v.find_first_not_of("0123456789")); + if (digits.empty()) return std::nullopt; + while (digits.starts_with('0')) digits.remove_prefix(1); + std::size_t n = 0; + for (char c : digits.substr(0, 9)) n = n * 10 + static_cast(c - '0'); + return n; + } + // A CSeq value as its sequence number and its method (RFC 3261 25.1: // 1*DIGIT LWS Method): the digits the trimmed value begins with, less // the zeros before the number, the spaces or tabs after them, then the @@ -432,7 +446,7 @@ export namespace imsd::sip { if (idx == std::string::npos) return std::nullopt; std::string_view head = std::string_view(buf_).substr(0, idx); long clen = 0; - if (auto v = Header(head, "Content-Length")) clen = LeadingDigits(*v).value_or(0); + if (auto v = Header(head, "Content-Length")) clen = static_cast(LengthOf(*v).value_or(0)); std::size_t total = idx + 4 + static_cast(clen); if (buf_.size() < total) return std::nullopt; std::string msg = buf_.substr(0, total); @@ -465,9 +479,8 @@ export namespace imsd::sip { std::size_t bodyStart = idx + 4; std::size_t body = d.size() - bodyStart; if (auto v = Header(d.substr(0, idx), "Content-Length")) { - std::size_t clen = 0; int digits = 0; - for (char c : *v) { if (c < '0' || c > '9' || digits == 9) break; clen = clen * 10 + static_cast(c - '0'); digits++; } - if (digits) { + if (const auto length = LengthOf(*v)) { + const std::size_t clen = *length; if (clen > body) { if (problem) *problem = std::format("datagram truncated (Content-Length {} > {} body bytes)", clen, body); return std::nullopt; diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 62ce946..6c45f4f 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -5,11 +5,12 @@ // the colon among it), status-line parsing, granted-expires extraction, // caller-identity extraction, the port a Via names for the response // (ViaResponsePort), the two framers — the TCP frame buffer (split delivery, -// keepalive pongs, pipelined messages) and a datagram's (DatagramMessage) —, -// a refused final's Retry-After and summary (RetryAfter, RefusalSummary), -// transaction matching (ResponseOf), our binding in a reg-event document -// (RegInfoContactState), and HeaderUri and Body. These pin the module's -// edge-case behavior; see the module header before "fixing" one. +// keepalive pongs, pipelined messages) and a datagram's (DatagramMessage), +// with the Content-Length they read —, a refused final's Retry-After and +// summary (RetryAfter, RefusalSummary), transaction matching (ResponseOf), +// our binding in a reg-event document (RegInfoContactState), and HeaderUri +// and Body. These pin the module's edge-case behavior; see the module header +// before "fixing" one. import std; import Imsd; @@ -181,6 +182,16 @@ int main() { Check(fb.TryExtract() == msg, "no Content-Length -> body length 0"); Check(fb.Size() == 8, "trailing bytes stay buffered"); } + { + // the Content-Length is read as a number: zeros before it do not count, and one too long to be a length is no zero + const std::string head = "SIP/2.0 200 OK\r\nCall-ID: x\r\n"; + FrameBuffer fb; + fb.Append(head + "Content-Length: 00000000005\r\n\r\nhello" + head + "Content-Length: 000\r\n\r\n" + head + "Content-Length: x\r\n\r\n"); + Check(fb.TryExtract() == head + "Content-Length: 00000000005\r\n\r\nhello", "a Content-Length of 5 written with ten zeros before it frames a body of five bytes"); + Check(fb.TryExtract() == head + "Content-Length: 000\r\n\r\n" && fb.TryExtract() == head + "Content-Length: x\r\n\r\n" && fb.Size() == 0, "zero in three digits is zero, and a value without a digit counts as none"); + fb.Append(head + "Content-Length: 18446744073709551616\r\n\r\nhello"); + Check(!fb.TryExtract().has_value() && fb.Size() > 0, "a Content-Length past any number that fits is not read as zero: the body is waited for"); + } { // the body's length under the compact name (RFC 3261 7.3.3), and with a space before the colon (7.3.1) const std::string compact = "MESSAGE sip:a@b SIP/2.0\r\ni: c1@h\r\nl: 5\r\n\r\nhello"; @@ -305,6 +316,10 @@ int main() { Check(m3 && *m3 == hdr + "X-Note: Content-Length: 99\r\n\r\nv=0\n", "a header name inside a value does not match"); auto m4 = DatagramMessage(hdr + "Content-Length: 99999999999999999999\r\n\r\nv=0\n", &why); Check(!m4.has_value(), "absurd Content-Length: discarded, no overflow"); + why.clear(); + Check(!DatagramMessage(hdr + "Content-Length: 18446744073709551616\r\n\r\nv=0\n", &why).has_value() && why.contains("truncated"), "nor is one that would wrap to zero: discarded as truncated"); + Check(DatagramMessage(hdr + "Content-Length: 00000000004\r\n\r\nv=0\nJUNK") == hdr + "Content-Length: 00000000004\r\n\r\nv=0\n", "a Content-Length of 4 written with ten zeros before it cuts the body at four bytes"); + Check(DatagramMessage(hdr + "Content-Length: x4\r\n\r\nv=0\nJUNK") == hdr + "Content-Length: x4\r\n\r\nv=0\nJUNK", "a Content-Length that begins with no digit: the body is the rest of the datagram"); auto m5 = DatagramMessage(hdr + "l: 4\r\n\r\nv=0\nJUNK"); Check(m5 && *m5 == hdr + "l: 4\r\n\r\nv=0\n", "`l:` that fits truncates the body like Content-Length"); why.clear(); From 7cae603c0cfba5624ff70fe77fb04970c52e2fe0 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 07/40] sip, messages, imsd: the client flow answers a request datagram cut short of the Content-Length it reads with a 400, unless an ACK or a CANCEL MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 3261 18.3 on a datagram that ends before its message's body does: "If the message is a response, it MUST be discarded. If the message is a request, the element SHOULD generate a 400 (Bad Request) response." The client flow's datagram read ignored either, where the Content-Length it read said more bytes than came, with one line, `UDP: datagram truncated (…) — ignored`. CutShortRequest gives the header section of a request whose datagram has fewer body bytes than the Content-Length read from it says, and BuildBadRequest the 400 for it, in the shape of BuildResponse's finals: every Via row echoed, the To tagged unless it holds a tag. The client flow sends that 400 and its line ends `— answered 400`. Such a request is known by its first line, which ends with the SIP version where a status line begins with it (7.1, 7.2), in upper or in lower case: a response cut short so, bytes that are no SIP cut short so and a datagram without an end of headers are ignored as before. imsd keeps nothing of a request it answers so, and follows 8.2.7 for an element that answers without state: a To tag it adds is made from the request's header section and a secret drawn once for the run, "in a manner that will generate the same tag for the same request consistently", and an ACK or a CANCEL cut short so gets no answer. The server ports and the init port hand a datagram on as it came, as before this commit. Tested by tests/Sip (CutShortRequest: the header section of a request cut short, with line breaks before it, under a compact Content-Length and with its version in lower case; nothing for a body that is all there, no Content-Length, no end of headers, a response in either letter case, bytes that are no SIP, an ACK, a CANCEL) and by tests/Messages (the 400 by its lines, its tag against Python's hashlib; the same request, the same 400; another request or another secret, another tag). On the workstation's loopback, SipFlow built around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture, cut-short, at this commit and at the one before): a MESSAGE with five body bytes of nine draws the 400, and the same one when it is sent again, where the commit before ignored it; a response cut short the same way, in upper and in lower case, an ACK, a CANCEL, bytes that are no SIP and a request without an end of headers draw nothing at either commit; the MESSAGE with its Content-Length folded is handed on at either commit, a folded value being read by its first line; a whole request sent after them is returned by the flow. --- AGENTS.md | 45 +++++++++++++++++++++++++++++++---- implementations/main.cpp | 20 ++++++++++++++-- interfaces/Imsd-Messages.cppm | 13 ++++++++++ interfaces/Imsd-Sip.cppm | 31 ++++++++++++++++++++++++ tests/Messages/main.cpp | 30 +++++++++++++++++++++++ tests/Sip/main.cpp | 36 ++++++++++++++++++++++++---- 6 files changed, 164 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 23f6b4f..d860264 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,12 +41,12 @@ 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=`. | | `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 (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number). 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; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number), `CutShortRequest`: the header section of a request — any but an ACK or a CANCEL — whose datagram has fewer body bytes than the Content-Length read from it says, which its 400 is built from. 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; `tests/Messages` is their suite. 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 for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; 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. 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 for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); since 1.2.1 `BuildBadRequest`, the 400 to a request cut short of the Content-Length read from it — any but an ACK or a CANCEL, in a call's dialog or not —, in that shape, a To tag it adds made from the request's header section and a secret of the run (RFC 3261 8.2.7); of requests that came whole, in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; 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), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `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` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | | `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 and messaging (`Gated`'s `Action` parameter names the action), shared by imsd and imsd-ofonod. GLib, so outside `imsd-core`. | @@ -287,13 +287,25 @@ What the suites pin: `+g.3gpp.smsip` tag, the MESSAGE with an RP-DATA, the delivery report with In-Reply-To, a 488) pinned against TS 24.341's clauses; `BuildResponse`, `BuildResponse200` and `BuildInviteResponse` on a request whose header - names come in compact form. + names come in compact form; `BuildBadRequest` by the lines of one 400 + (every Via row echoed; the To tag sixteen hex digits of the MD5 of a + secret and the header section, the expected one from Python's hashlib; + the same request, the same 400; another request, another tag; another + secret, another tag; a To's own tag kept). - `Sip` — the text layer's edge cases (empty header values, line anchoring, 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 skipped), the Content-Length the two framers read (zeros before its number no part of it; a number past any that fits not read as zero; a - value that begins with no digit read as none), the twelve compact forms (each through `Header`, in lower and + value that begins with no digit read as none), `CutShortRequest` (the + header section of a request with fewer body bytes than the + Content-Length read from it says, its version in upper or in lower case; none for a + body that is all there, for no Content-Length, no end of headers, a + response in either letter case, a status line whose phrase ends like a + version, a first line that ends in another version, in seven other + bytes or in more than the version, bytes that are no SIP, an ACK or a + CANCEL; for a MESSAGE, a header section exactly where + `DatagramMessage` calls the datagram truncated), the twelve compact forms (each through `Header`, in lower and in upper case, and through `Headers`; no other letter taken for a header name the suite lists; `l:` through the framer and `DatagramMessage`), `ViaResponsePort`'s reading of a Via row — `rport` by its name (in @@ -685,6 +697,18 @@ Rules: `checks.log`: a text sent to the own number over the bus, delivered back and listed); no capture holds a `Received` with them; the store's round trip with each is in `tests/Engine`. +- A request cut short of its Content-Length on the client flow ran on the + workstation's loopback (2026-11-22, the fp6 journal's + `2026-11-20-issues-2-5` capture, `cut-short`: `SipFlow` built around a + bench `main`, a peer on ::1 sending datagrams to the flow): a MESSAGE + with five body bytes of nine, its Content-Length on one line, drew a + 400 with its Via, From, Call-ID and CSeq echoed and its To tagged, and + the same 400 when it was sent again; a response, an ACK and a CANCEL + cut short the same way, and a request without an end of headers, were + ignored with their lines and drew nothing; a whole request sent after + them was returned by the flow; at the commit before, the cut-short + request was ignored as they were. Not in that bench: a 400 the flow + cannot send. - `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims bearer: the `--mux 1 --profile 2 -v` sequence, a plain run, and `OutOfCall` on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture, @@ -1594,7 +1618,18 @@ found under its long name or, where it has one, its compact form (RFC 3261 7.3.3: a `c:` line is a `Content-Type`, an `i:` line a Call-ID, a `v:` line a Via), with or without white space before the colon; of a value folded onto further lines the first line is read (7.3.1 allows the -fold). +fold). A request that reaches the client flow in a datagram with fewer body +bytes than the Content-Length read from it says is answered 400 (RFC 3261 18.3: the element "SHOULD generate a 400 (Bad +Request) response"; the journal has `UDP: datagram truncated (…) — +answered 400`). Such a request is known by its first line, which ends with +the SIP version where a status line begins with it (7.1, 7.2), whatever +the version's letter case: a datagram cut short so that begins with a +status line, or with no line of SIP, is ignored, its line ending `— +ignored`. imsd keeps nothing of a request it answers so: a To tag +it adds is made from the request and a secret of the run, the same for the +same request (`BuildBadRequest`), and an ACK or a CANCEL cut short so draws +nothing — what RFC 3261 8.2.7 has an element do that answers without +state. - **A retransmitted MESSAGE** (the same Call-ID, CSeq and Via branch — the value of the first `branch=` of its first Via row; a MESSAGE with none diff --git a/implementations/main.cpp b/implementations/main.cpp index 2901c34..2c64d82 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -370,6 +370,14 @@ struct RefusedError : std::runtime_error { // 1280-byte MTU (40 IPv6 + 8 ESP + 16 IV + 8 UDP + padding + 12 ICV). constexpr std::size_t UdpSinglePacketBudget = 1190; +// The secret in the To tag of a 400 to a request cut short +// (imsd::msg::BuildBadRequest): drawn at the first such request, the same +// until imsd stops. +const std::string& BadRequestSecret() { + static const std::string secret = imsd::util::Rng().Token(16); + return secret; +} + class SipFlow { public: // TCP: connect up to `tries` times (12-s timeout each, 10 s apart). An @@ -527,9 +535,17 @@ public: alive_ = false; return std::nullopt; } if (n == 0) continue; + const std::string_view d(buf, static_cast(n)); std::string why; - if (auto m = imsd::sip::DatagramMessage(std::string_view(buf, static_cast(n)), &why)) return m; - if (!why.empty()) Log(std::format("UDP: {} — ignored", why)); + if (auto m = imsd::sip::DatagramMessage(d, &why)) return m; + if (!why.empty()) { + // A request cut short of its Content-Length is answered 400 + // (RFC 3261 18.3; CutShortRequest says which); whatever else + // DatagramMessage refuses is ignored. + const auto head = imsd::sip::CutShortRequest(d); + Log(std::format("UDP: {} — {}", why, head ? "answered 400" : "ignored")); + if (head && !Send(imsd::msg::BuildBadRequest(*head, BadRequestSecret()))) return std::nullopt; + } continue; } // EOF/RST is not a timeout: mark the flow dead so the engine's diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index b31c72e..5bf0c23 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -542,6 +542,19 @@ export namespace imsd::msg { return std::format("{}\r\n", detail::Join(l)); } + // The 400 to a request whose datagram ended before its body did (RFC + // 3261 18.3), from the request's header section + // (imsd::sip::CutShortRequest), as BuildResponse makes a final. imsd + // keeps nothing of such a request, so the To tag is made from the + // request itself, "in a manner that will generate the same tag for the + // same request consistently" (8.2.7), and from `secret`, which the + // caller draws once for the run: the randomness 19.3 asks of a tag. It + // is the first sixteen hex digits of the MD5 of the secret and that + // header section. + std::string BuildBadRequest(std::string_view head, std::string_view secret) { + return BuildResponse({}, head, 400, "Bad Request", imsd::util::Md5::HexDigest(std::format("{}{}", secret, head)).substr(0, 16)); + } + // A 200 OK for an inbound request: echo Via/From/To/Call-ID/CSeq in order, // then either an SDP answer (with our Contact) or an empty body. // `extra` appends headers (Session-Expires echo for refreshes...). diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index f0d97c6..0779cf8 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -490,4 +490,35 @@ export namespace imsd::sip { } return std::string(d); } + + // RFC 3261 18.3 of a datagram that ends before its message's body does: + // "If the message is a response, it MUST be discarded. If the message + // is a request, the element SHOULD generate a 400 (Bad Request) + // response." The header section of such a request, with the empty line + // that ends it and no body — what the 400 is built from — or nullopt + // for every other datagram: one whose body is all there, by its + // Content-Length or for want of one; one without an end of headers; + // one whose first line is no request's; an ACK or a CANCEL. A request's + // first line ends with the SIP version (7.1: "Request-Line = Method SP + // Request-URI SP SIP-Version CRLF") and a status line begins with it + // (7.2), in whatever letter case ("The SIP-Version string is + // case-insensitive"): a response is none, and neither are bytes that + // are no SIP. imsd keeps nothing of a request it answers so, and of an + // element that keeps nothing 8.2.7 says: "A stateless UAS MUST ignore + // ACK requests." "A stateless UAS MUST ignore CANCEL requests." + std::optional CutShortRequest(std::string_view d) { + const std::size_t start = d.find_first_not_of("\r\n"); + if (start == std::string_view::npos) return std::nullopt; + d.remove_prefix(start); + const std::size_t idx = d.find("\r\n\r\n"); + if (idx == std::string_view::npos) return std::nullopt; + const std::string_view head = d.substr(0, idx); + const auto length = Header(head, "Content-Length").and_then(LengthOf); + if (!length || *length <= d.size() - (idx + 4)) return std::nullopt; + const std::string_view line = head.substr(0, head.find("\r\n")); + const std::string_view last = line.substr(line.rfind(' ') + 1); // of a line without a space, the line + if (last.size() != 7 || !IEqualsPrefix(last, "SIP/2.0") || IEqualsPrefix(line, "SIP/")) return std::nullopt; + if (line.starts_with("ACK ") || line.starts_with("CANCEL ")) return std::nullopt; + return std::string(head) + "\r\n\r\n"; + } } diff --git a/tests/Messages/main.cpp b/tests/Messages/main.cpp index 974507b..e8f6c6f 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -502,6 +502,36 @@ int main() { "Content-Length: 0\r\n\r\n", "a 488 for an inbound MESSAGE echoes every Via and tags To"); const std::string tagged = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet2\r\nFrom: ;tag=N2\r\nTo: ;tag=had\r\nCall-ID: in2@net\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n"; Check(BuildResponse(c, tagged, 200, "OK", "unused").contains("\r\nTo: ;tag=had\r\n"), "a To that already carries a tag is echoed as it is"); + // the 400 to a request whose datagram ended before its body did (RFC 3261 18.3), built from what imsd::sip::CutShortRequest gives of it + { + std::string cut = inbound; + cut.replace(cut.find("Content-Length: 0"), 17, "Content-Length: 12"); + const std::string head = imsd::sip::CutShortRequest(cut + "seven b").value_or(""); + Check(!head.empty(), "an inbound MESSAGE with seven body bytes of twelve is a request cut short"); + // the To tag below was made apart from imsd's MD5: Python's hashlib over the secret and the header section with its empty line, the first sixteen digits + const std::string_view secret = "run-secret-of-16"; + Eq(BuildBadRequest(head, secret), + "SIP/2.0 400 Bad Request\r\n" + "Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n" + "Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n" + "From: ;tag=N1\r\n" + "To: ;tag=d930d9cad06d5cba\r\n" + "Call-ID: in1@net\r\n" + "CSeq: 9 MESSAGE\r\n" + "Content-Length: 0\r\n\r\n", "its 400 echoes every Via and tags To with sixteen hex digits of the MD5 of the secret and the header section"); + Eq(BuildBadRequest(imsd::sip::CutShortRequest(cut + "s").value_or(""), secret), BuildBadRequest(head, secret), "the same request cut short elsewhere draws the same 400, tag and all"); + const auto toTag = [](std::string_view r) { const std::size_t at = r.find(";tag=", r.find("\r\nTo: ")); return r.substr(at, r.find("\r\n", at) - at); }; + const std::string r1 = BuildBadRequest(head, secret); + std::string other = cut; + other.replace(other.find("in1@net"), 7, "in2@net"); + const std::string r2 = BuildBadRequest(imsd::sip::CutShortRequest(other + "seven b").value_or(""), secret); + Check(r2.contains("\r\nCall-ID: in2@net\r\n") && toTag(r2).size() == 5 + 16 && toTag(r2) != toTag(r1), "another request draws another tag, of sixteen digits too"); + const std::string r3 = BuildBadRequest(head, "another-secret-16"); + Check(toTag(r3).size() == 5 + 16 && toTag(r3) != toTag(r1), "and the same request under another secret draws another tag"); + std::string had = tagged; + had.replace(had.find("Content-Length: 0"), 17, "Content-Length: 12"); + Check(BuildBadRequest(imsd::sip::CutShortRequest(had + "seven b").value_or(""), secret).contains("\r\nTo: ;tag=had\r\n"), "and the 400 echoes a To that already carries a tag as it is"); + } // a request whose header names come in compact form (RFC 3261 7.3.3): the finals echo them under the long names const std::string compact = "MESSAGE sip:me@[2001:db8::db43]:45062 SIP/2.0\r\n" diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 6c45f4f..2db5339 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -6,10 +6,11 @@ // caller-identity extraction, the port a Via names for the response // (ViaResponsePort), the two framers — the TCP frame buffer (split delivery, // keepalive pongs, pipelined messages) and a datagram's (DatagramMessage), -// with the Content-Length they read —, a refused final's Retry-After and -// summary (RetryAfter, RefusalSummary), transaction matching (ResponseOf), -// our binding in a reg-event document (RegInfoContactState), and HeaderUri -// and Body. These pin the module's edge-case behavior; see the module header +// with the Content-Length they read —, a request whose datagram ends before +// its body does (CutShortRequest), a refused final's Retry-After and summary +// (RetryAfter, RefusalSummary), transaction matching (ResponseOf), our +// binding in a reg-event document (RegInfoContactState), and HeaderUri and +// Body. These pin the module's edge-case behavior; see the module header // before "fixing" one. import std; import Imsd; @@ -326,6 +327,33 @@ int main() { Check(!DatagramMessage(hdr + "L : 40\r\n\r\nv=0\n", &why).has_value() && why.contains("truncated"), "`L :` larger than the datagram: discarded, problem set"); } + // ---- CutShortRequest (a request whose datagram ends before its body does: the header section its 400 is built from, RFC 3261 18.3) + { + const std::string req = "MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::2]:6000;branch=z9hG4bK1\r\nCall-ID: c\r\nCSeq: 7 MESSAGE\r\n"; + Check(CutShortRequest(req + "Content-Length: 9\r\n\r\nhello") == req + "Content-Length: 9\r\n\r\n", "a request with five body bytes of nine: its header section and the empty line, no body"); + Check(CutShortRequest("\r\n\r\n" + req + "l: 6\r\n\r\nhello") == req + "l: 6\r\n\r\n", "line breaks before it are no part of it, and the length is found under its compact form"); + Check(CutShortRequest(req + "Content-Length: 0006\r\n\r\nhello").has_value(), "zeros before the length are no part of the number"); + Check(!CutShortRequest(req + "Content-Length: 5\r\n\r\nhello") && !CutShortRequest(req + "Content-Length: 4\r\n\r\nhello"), "a body that is all there, with or without bytes after it: none"); + Check(!CutShortRequest(req + "\r\nhello") && !CutShortRequest(req + "Content-Length: x9\r\n\r\nhello"), "no Content-Length, or one that begins with no digit: none (the body is the rest of the datagram)"); + Check(!CutShortRequest(req + "Content-Length: 9\r\n") && !CutShortRequest("\r\n\r\n") && !CutShortRequest(""), "no end of headers, line breaks alone, no bytes: none"); + Check(!CutShortRequest("SIP/2.0 200 OK\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello") && !CutShortRequest("sip/2.0 200 OK\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello"), "a response cut short: none (it is discarded), its version in upper or in lower case"); + Check(!CutShortRequest("SIP/2.0 200 SIP/2.0\r\nContent-Length: 9\r\n\r\nhello") && !CutShortRequest("sip/2.0 200 sip/2.0\r\nContent-Length: 9\r\n\r\nhello"), "nor is a status line a request's first line because its phrase ends like a version"); + Check(CutShortRequest("MESSAGE sip:a@example.net sip/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value(), "a request whose version is in lower case is a request"); + Check(!CutShortRequest("MESSAGE sip:a@example.net SIP/2.01\r\nContent-Length: 9\r\n\r\nhello"), "a first line that ends in more than the version: none"); + Check(!CutShortRequest("MESSAGE sip:a@example.net SIP/3.0\r\nContent-Length: 9\r\n\r\nhello") && !CutShortRequest("MESSAGE sip:a@example.net bar1234\r\nContent-Length: 9\r\n\r\nhello"), "nor one that ends in another version, or in seven other bytes"); + Check(!CutShortRequest("l:9\r\n\r\n") && !CutShortRequest("HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nhello"), "bytes that are no SIP, a Content-Length larger than what follows among them: none"); + Check(!CutShortRequest("ACK sip:a@example.net SIP/2.0\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello"), "an ACK cut short: none"); + Check(!CutShortRequest("CANCEL sip:a@example.net SIP/2.0\r\nCall-ID: c\r\nContent-Length: 9\r\n\r\nhello"), "a CANCEL cut short: none"); + Check(CutShortRequest("ACKNOWLEDGE sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value() && CutShortRequest("ack sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value(), "a method that begins with ACK, or spells it in other letter case, is no ACK"); + Check(CutShortRequest("CANCELLED sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value() && CutShortRequest("cancel sip:a@example.net SIP/2.0\r\nContent-Length: 9\r\n\r\nhello").has_value(), "nor is one that begins with CANCEL, or spells it in other letter case, a CANCEL"); + // the two agree on what is cut short: the same bytes skipped, the same length read, the same count of body bytes + for (std::string_view tail : {"Content-Length: 9\r\n\r\nhello", "Content-Length: 5\r\n\r\nhello", "Content-Length: 4\r\n\r\nhello", "\r\nhello", "Content-Length: 9\r\n"}) { + std::string why; + const bool truncated = !DatagramMessage(req + std::string(tail), &why).has_value() && why.contains("truncated"); + Check(CutShortRequest(req + std::string(tail)).has_value() == truncated, std::format("a MESSAGE's header section comes exactly where DatagramMessage calls its datagram truncated ({:?})", tail)); + } + } + // ---- RetryAfter / RefusalSummary (what a refused final is logged as) { std::string r503 = From 5f01b46909c9f6b797aff992b78d334cf5aca5c0 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:11 +0100 Subject: [PATCH 08/40] imsd: a datagram on a server port or the init port is framed as one on the client flow is MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SipFlow passes a datagram of the client flow through DatagramMessage: one datagram is one message, the bytes past the Content-Length read from it are no part of it and one whose body is shorter than that length is no message (RFC 3261 18.3), nor is one that has no end of headers. The two other places that read a datagram handed it on as it came: the protected server ports, where the network's requests arrive, and the init port, where the 401 to the unprotected REGISTER does. Bytes after a body so reached its readers: behind an RP-ACK or an RP-ERROR without user data, bytes shaped like that element (0x41, a length and at least as many bytes) would be read as its submit report. Both go through DatagramMessage now. On a server port a request cut short of the Content-Length read from it is answered 400 as on the client flow (Jorijn's decision of 2026-11-22, asked of him for this port), by the way any answer from that port goes, and its line reads `UDP: … on server socket — answered 400`; whatever else DatagramMessage refuses there is ignored with that line's `— ignored`. The init port answers no request, whole or cut short: what DatagramMessage refuses there is ignored with `UDP: … on the init port, from port — ignored`. A datagram of line breaks alone is passed over on all three, and so is one of no bytes: on the init port it ended the wait for the 401, and on a server port that pass's read of the socket, with whatever stood behind it left for the next pass. The server ports pass over one of other white space alone, as before. Tested on the workstation's loopback with stand-ins for the network (the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and server-ports; each at this commit and at the one before). The init port, with the daemon in dev mode: an empty datagram and one of line breaks are passed over, a 401 cut short of its Content-Length is ignored with its line, and the 401 after each is taken, where the commit before ended its wait at the empty one and took the cut-short one for the reply; a request, cut short or whole, draws no answer at either. The server ports, their class built around a bench main: a request with bytes after its body comes out without them; one with a short body is answered 400 on either port; a response, an ACK and a CANCEL cut short so and a request without an end of headers are ignored with their lines; a request behind a datagram of no bytes comes out in the same pass. The commit before handed each of those requests on as it came and stopped its pass at the datagram of no bytes. A request whose Content-Length is folded is handed on at either commit, with a body shorter than that length or with the bytes past it, a folded value being read by its first line. On the dev phone the binary of this range's last commit registered fresh through the init port after a reboot; the submit report and the delivery of each of two texts came to the server port as datagrams, by a packet counter; and a MESSAGE with a Content-Length larger than its body, sent from the phone to its own server port, was answered 400 (the capture's phone-form6: fresh-check.log, checks.log, inject-bench.log). --- AGENTS.md | 76 ++++++++++++++++++++++++++++++---------- implementations/main.cpp | 62 +++++++++++++++++++++++++------- 2 files changed, 107 insertions(+), 31 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d860264..b07eb7e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -485,8 +485,8 @@ Rules: and `detached` not counted, `connecting` with `unknown` counted), its other states, ModemManager not answering and its second site (a refresh unanswered over a reconnected flow) not at all, and `tests/Engine` pin - nothing of it; the REGISTER wait's diverting arms — a datagram skipped on - the init port, a response to another transaction ignored, a provisional + nothing of it; the REGISTER wait's diverting arms — a response to + another transaction ignored, a provisional restarting the wait, a request (an INVITE among them) dispatched and answered under the wait; an incoming call answered from a session's dialer since the polkit gate — imsd-dialerd's `Accept` by the active @@ -638,19 +638,19 @@ Rules: same-second retransmission was answered again and absorbed, the delivery report answered 202. No capture of the benches on hardware holds a journal line of one of these arms (each arm's line is searched in them in the - fp6 journal's `2026-11-19-imsd-1.2.0-r32-cut` capture, `searches/arms.out`): a refused final to a submission's MESSAGE, an RP-ERROR this + fp6 journal's `2026-11-19-imsd-1.2.0-r32-cut` capture, `searches/arms.out`, and for the phone's + visits of 2026-11-20 to 2026-11-22 in its `2026-11-20-issues-2-5` + capture, `phone/arms.out` and `phone-form6/arms.out`): a refused final to a submission's MESSAGE, an RP-ERROR this code sends (the cause-96 unusable-TPDU path; an RP-ERROR that came in was reached: `smsc-override-2026-10-18-0217`, 02:19:41, RP cause 28 + TP-FCS - 0xc1, through `OnReport`), the final's wait and the report's - running out, a dead flow under a `Send`, a status report (one requested + 0xc1, through `OnReport`), the final's wait running out, the report's wait ending a message as `failed`, a dead flow under a `Send`, a status report (one requested at 01:33 with TP-SRR; none came in the following 11 minutes — the unfiltered journal of 01:33:30–01:45:00, `r23-phone-journal-2026-10-17-precise-and-modem-sms`; whether KPN's SC sends them over this path is unknown), 8-bit data (an MMS notification), a message while SMS over IP is off (the 480), a submit report In-Reply-To no MESSAGE of ours in flight (the 488) or one without - In-Reply-To for no message in flight (the 200), a page-mode MESSAGE, a - body that is no RP message, a delivery that names no gateway, a text + In-Reply-To for no message in flight (the 200), a page-mode MESSAGE, a body that is no RP message, a text past 255 segments, an EF_SMSP record 1 that cannot be read or holds no service centre, or one whose service centre is not an international number, a @@ -709,6 +709,35 @@ Rules: them was returned by the flow; at the commit before, the cut-short request was ignored as they were. Not in that bench: a 400 the flow cannot send. +- The daemon reads SIP from a socket in four places — the client flow, + the server ports' datagrams, their connections, the init port — and + each goes through a framer of `Imsd:Sip`. The two datagram reads 1.2.1 put behind `DatagramMessage` ran on the workstation's loopback + (2026-11-22, the fp6 journal's `2026-11-20-issues-2-5` capture). The + init port (`init-port`: the daemon in dev mode, its card and modem + reads answered by stand-ins, a stand-in P-CSCF answering the + unprotected REGISTER): a datagram of no bytes and one of line + breaks alone passed over, a 401 cut short of its Content-Length ignored + with its `UDP: datagram truncated … on the init port` line, and the 401 + after each taken; at the commit before, the empty datagram ended the + wait (`no 401 to unprotected REGISTER`) and the cut-short 401 was taken + for the reply. A request sent there, cut short or whole, drew a line + and no answer at either commit. The server ports (`server-ports`: + `ServerPorts` built around a bench `main`): a request with bytes after + its body handed on without them; one whose body is shorter than its + Content-Length answered 400 on either port, its Via, From, Call-ID and + CSeq echoed and its To tagged — the Content-Length of each on one line; a response, an ACK and a CANCEL cut + short so, and a request without an end of headers, ignored with their + lines; a datagram of line breaks alone passed over, and one of no bytes + with the request behind it handed on in the same pass; at the commit + before, those requests were handed on as they came, and the datagram of no + bytes ended the pass, the request behind it handed on in the next. On + the dev phone (2026-11-22, the capture's `phone-form6`, the binary of + 1.2.1) the 401 of a fresh registration after a reboot + came through the init port's read, and the submit report and the + delivery of each of two texts through the server ports' as datagrams (two per + text by a packet counter, none over TCP: `checks.log`); a MESSAGE the + phone sent to its own server port with a Content-Length larger than + its body was answered 400 (`inject-bench.log`). - `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims bearer: the `--mux 1 --profile 2 -v` sequence, a plain run, and `OutOfCall` on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture, @@ -1618,18 +1647,27 @@ found under its long name or, where it has one, its compact form (RFC 3261 7.3.3: a `c:` line is a `Content-Type`, an `i:` line a Call-ID, a `v:` line a Via), with or without white space before the colon; of a value folded onto further lines the first line is read (7.3.1 allows the -fold). A request that reaches the client flow in a datagram with fewer body -bytes than the Content-Length read from it says is answered 400 (RFC 3261 18.3: the element "SHOULD generate a 400 (Bad -Request) response"; the journal has `UDP: datagram truncated (…) — -answered 400`). Such a request is known by its first line, which ends with -the SIP version where a status line begins with it (7.1, 7.2), whatever -the version's letter case: a datagram cut short so that begins with a -status line, or with no line of SIP, is ignored, its line ending `— -ignored`. imsd keeps nothing of a request it answers so: a To tag -it adds is made from the request and a secret of the run, the same for the -same request (`BuildBadRequest`), and an ACK or a CANCEL cut short so draws -nothing — what RFC 3261 8.2.7 has an element do that answers without -state. +fold). A datagram on a server port or on the init port is +framed as one on the client flow is (RFC 3261 18.3): bytes past the +Content-Length read from it are discarded, and one that has no end of headers is +ignored with a line (`UDP: … on server socket — ignored`, `UDP: … +on the init port, from port — ignored`); one of no bytes or of line +breaks alone is passed over without a line, and so is one of other white +space alone on a server port. A request that reaches the client flow or a +server port in a datagram with fewer body bytes than the Content-Length +read from it says is answered 400 (RFC 3261 +18.3: the element "SHOULD generate a 400 (Bad Request) response"; the +journal has `UDP: datagram truncated (…) — answered 400`, with the +server port named before the dash). Such a request is known by its first +line, which ends with the SIP version where a status line begins with +it (7.1, 7.2), whatever the version's letter case: a datagram cut short +so that begins with a status line, or with no line of SIP, is ignored, +its line ending `— ignored`, and so is a request cut short so on the init +port, which answers no request. imsd keeps nothing of a request it +answers so: a To tag it adds is made from the request and a secret of +the run, the same for the same request (`BuildBadRequest`), and an ACK +or a CANCEL cut short so draws nothing — what RFC 3261 8.2.7 has an element +do that answers without state. - **A retransmitted MESSAGE** (the same Call-ID, CSeq and Via branch — the value of the first `branch=` of its first Via row; a MESSAGE with none diff --git a/implementations/main.cpp b/implementations/main.cpp index 2c64d82..a5b5a33 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -341,6 +341,11 @@ socklen_t MakeAddr(std::string_view ip, int port, sockaddr_storage& ss) { return sizeof(sockaddr_in); } +// The port a socket address names. +int PortOf(const sockaddr_storage& ss) { + return ss.ss_family == AF_INET6 ? ntohs(reinterpret_cast(&ss)->sin6_port) : ntohs(reinterpret_cast(&ss)->sin_port); +} + // ---- SIP over the protected TCP flow -------------------------------------- enum class Transport { Tcp, Udp }; constexpr std::string_view TransportName(Transport t) { return t == Transport::Udp ? "UDP" : "TCP"; } @@ -624,17 +629,35 @@ public: char buf[65535]; sockaddr_storage src; socklen_t sl = sizeof src; ssize_t n = recvfrom(us, buf, sizeof buf, 0, reinterpret_cast(&src), &sl); - if (n <= 0) break; + if (n < 0) break; std::string_view sv(buf, static_cast(n)); bool blank = sv.find_first_not_of("\r\n \t") == std::string_view::npos; if (blank) continue; - std::string msg(sv); + // One datagram = one message, framed as on the client flow + // (RFC 3261 18.3): bytes past its Content-Length are + // discarded; a request whose body is shorter than its + // Content-Length is answered 400 (CutShortRequest says + // which), the way any answer goes from here (below); + // whatever else DatagramMessage refuses is ignored with a + // line. One of white space alone, or of no bytes, was + // passed over above. + std::string why; + auto framed = imsd::sip::DatagramMessage(sv, &why); + bool cutShort = false; + if (!framed) { + framed = imsd::sip::CutShortRequest(sv); + cutShort = framed.has_value(); + } + if (!framed) { + if (!why.empty()) Log(std::format("UDP: {} on server socket {} — ignored", why, us == udpUc_ ? PortUc : PortUs)); + continue; + } + std::string msg = std::move(*framed); if (imsd::sip::Status(msg).has_value()) { // A response here means the P-CSCF answered to the Via port // instead of the source port of our request (rport) — it // never reaches the client flow. Say so. - int sp = src.ss_family == AF_INET6 ? ntohs(reinterpret_cast(&src)->sin6_port) : ntohs(reinterpret_cast(&src)->sin_port); - Log(std::format("UDP response on server socket {} from port {} ignored: {}", us == udpUc_ ? PortUc : PortUs, sp, sv.substr(0, sv.find("\r\n")))); + Log(std::format("UDP response on server socket {} from port {} ignored: {}", us == udpUc_ ? PortUc : PortUs, PortOf(src), std::string_view(msg).substr(0, msg.find("\r\n")))); continue; } if (!imsd::sip::Status(msg).has_value()) { // request only @@ -658,9 +681,15 @@ public: htons(static_cast(*vp)); if (udpUc_ >= 0) rs = udpUc_; } - out.push_back({std::move(msg), [rs, s, sll](const std::string& r) mutable { + auto reply = [rs, s, sll](const std::string& r) mutable { sendto(rs, r.data(), r.size(), 0, reinterpret_cast(&s), sll); - }}); + }; + if (cutShort) { + Log(std::format("UDP: {} on server socket {} — answered 400", why, us == udpUc_ ? PortUc : PortUs)); + reply(imsd::msg::BuildBadRequest(msg, BadRequestSecret())); + continue; + } + out.push_back({std::move(msg), std::move(reply)}); } } } @@ -2069,9 +2098,12 @@ private: // The final of the unprotected REGISTER (callid, CSeq 1) on the init // socket, within 8 s of the send or of its last provisional. The socket // is bound to the init port, not connected: what else it delivers — a - // late final of an earlier attempt, a stray datagram — is logged with - // its source port and skipped, never judged as the reply. Closes the - // socket; throws when nothing answers. + // late final of an earlier attempt, a stray datagram — is skipped, + // never judged as the reply, and logged with its source port unless it + // holds nothing but line breaks. A datagram is framed as on the other + // sockets (RFC 3261 18.3; DatagramMessage), but a request gets no + // answer here, whole or cut short: the socket is that REGISTER's own. + // Closes the socket; throws when nothing answers. std::string AwaitInitialFinal(int us, const std::string& callid) { double deadline = Mono() + 8.0; char buf[65535]; @@ -2085,10 +2117,16 @@ private: setsockopt(us, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); sockaddr_storage src; socklen_t sl = sizeof src; ssize_t n = recvfrom(us, buf, sizeof buf, 0, reinterpret_cast(&src), &sl); - if (n <= 0) break; - std::string m(buf, static_cast(n)); + if (n < 0) break; + const int sp = PortOf(src); + std::string why; + auto framed = imsd::sip::DatagramMessage(std::string_view(buf, static_cast(n)), &why); + if (!framed) { + if (!why.empty()) Log(std::format("UDP: {} on the init port, from port {} — ignored", why, sp)); + continue; + } + std::string m = std::move(*framed); if (!imsd::sip::ResponseOf(m, callid, "1 REGISTER")) { - int sp = src.ss_family == AF_INET6 ? ntohs(reinterpret_cast(&src)->sin6_port) : ntohs(reinterpret_cast(&src)->sin_port); std::string_view sv = m; Log(std::format("ignoring a datagram on the init port from port {} that is not the unprotected REGISTER's reply: {}", sp, sv.substr(0, sv.find("\r\n")))); continue; From 9333621c66b5873671ff72ca6b57f9e640d72a75 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:12 +0100 Subject: [PATCH 09/40] sip: a received message's header section is unfolded where it is framed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RFC 3261 7.3.1 lets a header value go on over further lines, each begun with a space or a tab: "The line break and the whitespace at the beginning of the next line are treated as a single SP character." The text layer read a header from one line, so of a folded value it had the first line only. Networks fold: KPN's 401 to the unprotected REGISTER of 2026-07-18 and Odido's of 2026-07-13 had the WWW-Authenticate over four lines (AGENTS.md §13; imsd finds a 401's nonce by a search of the whole message, on a continuation line as on any other). A Security-Server folded the same way would be read by its first line alone, without the SPIs and ports on the further lines, and the bring-up deferred; a short message whose Content-Type stands on a continuation line would be taken for a page-mode text, answered 200 and never shown; a folded Content-Length on a connection would frame no body, and the body's bytes begin the next message. Unfolded takes the folds out of a header section, and the two framers — FrameBuffer::TryExtract for a stream, DatagramMessage for a datagram — hand a message on with its header section unfolded and its body as it came; the Content-Length that frames the body is read from the unfolded section. CutShortRequest reads its Content-Length so too, and the header section it gives for the 400 is unfolded. Every socket imsd reads SIP from goes through one of the two framers, so each reader of a header still reads one line. A DUMP_SIP dump of a received message holds it as framed. Jorijn's decision of 2026-11-21 ("Unfold now"). Tested by tests/Sip — Unfolded on 7.3.1's own example, a tab, a bare LF, a value begun on the next line and a line break that nothing follows; both framers on a 401 whose WWW-Authenticate goes over four lines and whose Content-Length is folded; CutShortRequest on a request cut short of a folded Content-Length; ViaResponsePort on a Via list folded after its comma, through the datagram framer — and by tests/Engine, a delivered MESSAGE whose Content-Type came folded. On the workstation's loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, init-port, server-ports and cut-short, at this commit and at the one before): a stand-in's 401 with its Security-Server over three lines gives the whole value, where the commit before deferred the bring-up for want of SPIs; a request with its Content-Type and Content-Length on continuation lines comes out of the server ports unfolded and framed by that length, as a datagram and over a connection; a request cut short of a folded Content-Length, its Via on a continuation line, is answered 400 with its Via whole, on a server port and on the client flow, where the commit before did not read the folded length and handed the request on as it came; a request on a server port whose Via row is a list folded after its comma, `rport` on its lower value, is answered from the client-port socket, the way to the port its top value names, as at the commit before. On the dev phone the binary of this range's last commit registered fresh on KPN after a reboot; the 401 was not dumped, so whether it came folded that time is not on record. A MESSAGE the phone sent to its own protected server port, its Via row a list folded after its comma with `rport` on the lower value, was answered from the client-port socket (the capture's phone-form6, fresh-check.log and inject-bench.log). --- AGENTS.md | 46 +++++++++++++++++---- README.md | 2 +- implementations/main.cpp | 10 +++-- interfaces/Imsd-Sip.cppm | 87 +++++++++++++++++++++++++++------------- tests/Engine/main.cpp | 17 +++++++- tests/Sip/main.cpp | 63 ++++++++++++++++++++++++++--- 6 files changed, 178 insertions(+), 47 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b07eb7e..de49c6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,7 @@ 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=`. | | `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 (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number), `CutShortRequest`: the header section of a request — any but an ACK or a CANCEL — whose datagram has fewer body bytes than the Content-Length read from it says, which its 400 is built from. 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; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `Unfolded`, by which the framers hand a message on with its folded header lines — 7.3.1 — joined; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number), `CutShortRequest`: the header section of a request — any but an ACK or a CANCEL — whose datagram has fewer body bytes than the Content-Length read from it says, which its 400 is built from. 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. | @@ -298,7 +298,7 @@ What the suites pin: skipped), the Content-Length the two framers read (zeros before its number no part of it; a number past any that fits not read as zero; a value that begins with no digit read as none), `CutShortRequest` (the - header section of a request with fewer body bytes than the + header section, unfolded, of a request with fewer body bytes than the Content-Length read from it says, its version in upper or in lower case; none for a body that is all there, for no Content-Length, no end of headers, a response in either letter case, a status line whose phrase ends like a @@ -317,7 +317,12 @@ What the suites pin: counted, its own `rport` counted, last before the comma too; a comma in a quoted string no end of it, the comma behind the closing quote its end) —, white space before the colon (RFC 3261 7.3.1's four - spellings), + spellings), `Unfolded` (7.3.1's own example, a tab, a bare LF, a value + begun on the next line, a line break that nothing follows kept) and both + framers on a 401 whose WWW-Authenticate goes over four lines — the + header section unfolded, a folded Content-Length framing the body, the + body as it came —, and `ViaResponsePort` on a Via list folded after its + comma, as the datagram framer hands it on, `ResponseOf` (the transaction's own 100 Trying; a final whose CSeq parts its number and its method by two spaces, by a tab or by both, or has zeros before its number: the @@ -381,7 +386,8 @@ What the suites pin: a delivered MESSAGE whose header names come in compact form — the 200 and the delivery report of its long form, its retransmission key, the 480 while SMS over IP is off — and a final in compact form taken by the - message in flight; + message in flight; a delivered MESSAGE whose Content-Type came folded, + taken for a short message once the datagram framer has unfolded it; 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, @@ -738,6 +744,24 @@ Rules: text by a packet counter, none over TCP: `checks.log`); a MESSAGE the phone sent to its own server port with a Content-Length larger than its body was answered 400 (`inject-bench.log`). + The unfolding ran in the same benches: the stand-in's 401 with its + WWW-Authenticate over four lines and its Security-Server over three + gave the Security-Server whole (at the commit before, its first line, + and the bring-up deferred: `Security-Server carries no + spi-c/spi-s/port-c/port-s`); a request whose Content-Type and + Content-Length stood on continuation lines came out of the server + ports unfolded and framed by that length, as a datagram and over a + connection (at the commit before, the datagram kept the bytes after + its body); a request cut short of a folded Content-Length, its Via on a continuation + line, was answered 400 with its Via whole, on a server port and, in + `cut-short`, on the client flow (at the commit before, its folded + length was not read and it was handed on as it came); a request on a + server port whose Via row held a list folded after its comma, `rport` + on its lower value, was answered by the way to the port its top value + names, as at the commit before. On the + phone the 401 of the fresh registration came from KPN, whose 401 of + 2026-07-18 had its WWW-Authenticate over four lines (§13; the fresh one was not + dumped). - `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims bearer: the `--mux 1 --profile 2 -v` sequence, a plain run, and `OutOfCall` on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture, @@ -1645,9 +1669,10 @@ still answered 200 and logged with its body: the 200 is `BuildResponse`'s now and the line names the content type (§7.8). A header imsd reads is found under its long name or, where it has one, its compact form (RFC 3261 7.3.3: a `c:` line is a `Content-Type`, an `i:` line a Call-ID, a -`v:` line a Via), with or without white space before the colon; of a -value folded onto further lines the first line is read (7.3.1 allows the -fold). A datagram on a server port or on the init port is +`v:` line a Via), with or without white space before the colon, and a +value folded onto further lines (7.3.1) whole: a received message's +header section is unfolded where it is framed (`Unfolded`), each line +break in it that a space or a tab follows becoming, with the white space after it, one space. A datagram on a server port or on the init port is framed as one on the client flow is (RFC 3261 18.3): bytes past the Content-Length read from it are discarded, and one that has no end of headers is ignored with a line (`UDP: … on server socket — ignored`, `UDP: … @@ -2383,3 +2408,10 @@ the related code. 01:17:41–45, 28–36 min after their SC time stamps; what held them is unknown. The registrar echoes `+g.3gpp.smsip` in the reg-event reginfo (``) on both AORs. +- **A folded `WWW-Authenticate`** — the 401 to the unprotected REGISTER + came with its `WWW-Authenticate` over four lines on KPN (2026-07-18) + and on Odido (2026-07-13), the nonce on the second (RFC 3261 7.3.1; one + 401 of each: the fp6 journal's `2026-11-20-issues-2-5` capture, + `folded-401`); the `Security-Server` of both was one line. imsd finds the nonce by a search + of the whole message, and unfolds every received message where it is + framed (§7.9). diff --git a/README.md b/README.md index 22a83cf..b072e38 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ Configuration is environment variables in `/etc/imsd.env`, none are required. | `RTP_PORT` | `50004` | local RTP port advertised in SDP | | `PRECOND` | `0` | `1` offers SDP QoS preconditions | | `CODECS` | *(empty — defaults)* | comma-separated codec preference list over `AMR-WB`, `AMR` (or `AMR-NB`), `PCMA`, `PCMU`: restricts and orders both the codecs offered on an outgoing call and those accepted from an inbound offer (default: offer AMR-WB + AMR, accept all four in that order). A bench knob — a network whose gateway transcodes every caller up to AMR-WB otherwise never lets the narrowband path run | -| `DUMP_SIP` | `0` | `1` writes raw REGISTER-200/SUBSCRIBE-200 dumps, the last refused REGISTER or SUBSCRIBE final (`imsd-register-fail.raw`, `imsd-subscribe-fail.raw`), the last incoming call's INVITE (`imsd-invite-in.raw`), the last outgoing INVITE (`imsd-invite-out.raw`), the last inbound MESSAGE outside a call's dialog (`imsd-message-in.raw`) and the last MESSAGE a submission started with (`imsd-message-out.raw`), mode 0600, for debugging — they contain your IMSI/MSISDN and addresses, and the two MESSAGE dumps the text of a short message. A refused REGISTER or SUBSCRIBE is logged with its status line and any Retry-After / Warning / Reason / Server headers | +| `DUMP_SIP` | `0` | `1` writes dumps of a fresh registration's REGISTER 200 and of the SUBSCRIBE 200s, the last refused REGISTER or SUBSCRIBE final (`imsd-register-fail.raw`, `imsd-subscribe-fail.raw`), the last incoming call's INVITE (`imsd-invite-in.raw`), the last outgoing INVITE (`imsd-invite-out.raw`), the last inbound MESSAGE outside a call's dialog (`imsd-message-in.raw`) and the last MESSAGE a submission started with (`imsd-message-out.raw`), mode 0600, for debugging; a received message is dumped as imsd reads it, its folded header lines joined — they contain your IMSI/MSISDN and addresses, and the two MESSAGE dumps the text of a short message. A refused REGISTER or SUBSCRIBE is logged with its status line and any Retry-After / Warning / Reason / Server headers | | `DUMP_DIR`, `OUT_DIR` | state dir | where dumps / per-call media stats land | | `IMSD_MEDIA` | *(auto)* | path to `imsd-media` (default: next to `imsd`, else `/usr/libexec/imsd-media`) | | `IMSD_ENV` | `/etc/imsd.env` | the configuration file's path — a bench seam for manual runs of `ims-pdn-up.sh` (the packaged unit reads `/etc/imsd.env` through `EnvironmentFile=`). The file's existence changes nothing | diff --git a/implementations/main.cpp b/implementations/main.cpp index a5b5a33..5f8b078 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -810,10 +810,12 @@ void PersistState(const RegState& r, const std::string& route, const std::string } } -// Raw dump of a received message for offline diffing against the stock-modem -// oracle (rung-5b registration-parity work). One file per message kind, -// overwritten on every registration cycle. The dumps carry the subscriber's -// IMSI/MSISDN and addresses, so they are opt-in (DUMP_SIP=1) and mode 0600. +// A dump of a SIP message for offline reading (the README's DUMP_SIP row +// lists the dumps): one imsd received, as its framer hands it on — bytes +// past its body gone, its folded header lines joined — or one of its own, +// dumped before the send is tried. One file per kind, overwritten by the +// next dump of its kind. The dumps carry the subscriber's IMSI/MSISDN and +// addresses, so they are opt-in (DUMP_SIP=1) and mode 0600. void DumpRaw(std::string_view name, std::string_view msg) { if (EnvOr("DUMP_SIP", "0") != "1") return; std::string path = std::format("{}/{}", EnvOr("DUMP_DIR", StateDir()), name); diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index 0779cf8..0f5a07a 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -7,7 +7,7 @@ Imsd:Sip — SIP message text layer + TCP framing. Deliberately a text layer, not a full RFC 3261 parser: the engine works on whole messages as strings and pulls out exactly what it needs (headers, status codes, the granted registration lifetime), which keeps every message -loggable and testable verbatim. A header is asked for by its long name and +loggable and testable as text. A header is asked for by its long name and found under that or its compact form (RFC 3261 7.3.3). Edge-case behavior (empty header values, line anchoring, white space before the colon, keepalive discards) is pinned by tests/Sip — a change that flips one of @@ -105,8 +105,9 @@ namespace imsd::sip { // Matching never crosses the line boundary: an empty-valued header // yields "", NOT the next line's content (a regex-based implementation // whose whitespace class eats the CRLF gets that wrong — pinned by the - // "bare header" test), so of a value folded onto further lines (7.3.1) - // the first line is read. + // "bare header" test). A value folded onto further lines (7.3.1) is + // one line by the time a received message is read here: the framers + // unfold its header section (Unfolded). std::optional ValueOfField(std::string_view line, std::string_view name) { if (!IEqualsPrefix(line, name)) return std::nullopt; std::size_t colon = name.size(); @@ -421,6 +422,29 @@ export namespace imsd::sip { return std::string(uri); } + // A header section with its folds taken out. RFC 3261 7.3.1: "Header + // fields can be extended over multiple lines by preceding each extra + // line with at least one SP or horizontal tab (HT). The line break and + // the whitespace at the beginning of the next line are treated as a + // single SP character." So a line break that a space or a tab follows + // becomes, with that white space, one space; every other byte is kept. + std::string Unfolded(std::string_view head) { + std::string out; + out.reserve(head.size()); + for (std::size_t i = 0; i < head.size();) { + const std::string_view next = head.substr(i + 1); + if (head[i] == '\n' && (next.starts_with(' ') || next.starts_with('\t'))) { + if (out.ends_with('\r')) out.pop_back(); + out.push_back(' '); + const std::size_t text = next.find_first_not_of(" \t"); + i = text == std::string_view::npos ? head.size() : i + 1 + text; + } else { + out.push_back(head[i++]); + } + } + return out; + } + // The body of a message: what follows the header terminator, empty // without one. std::string_view Body(std::string_view msg) { @@ -431,25 +455,27 @@ export namespace imsd::sip { // SIP-over-TCP stream framing, transport-free: feed received bytes into // Append(), pull complete messages (headers + Content-Length body) out // of TryExtract(). Leading CRLFs (RFC 5626 keepalive pongs) are - // discarded. + // discarded. A message comes out with its header section unfolded + // (Unfolded) and its body as it came. class FrameBuffer { public: void Append(std::string_view data) { buf_.append(data); } // One complete SIP message off the front of the buffer, or nullopt // if more bytes are needed. Content-Length is located with the same - // line-anchored matching rules as Header(). + // line-anchored matching rules as Header(), in the unfolded header + // section. std::optional TryExtract() { std::size_t keep = buf_.find_first_not_of("\r\n"); buf_.erase(0, keep == std::string::npos ? buf_.size() : keep); std::size_t idx = buf_.find("\r\n\r\n"); if (idx == std::string::npos) return std::nullopt; - std::string_view head = std::string_view(buf_).substr(0, idx); + std::string msg = Unfolded(std::string_view(buf_).substr(0, idx)); long clen = 0; - if (auto v = Header(head, "Content-Length")) clen = static_cast(LengthOf(*v).value_or(0)); + if (auto v = Header(msg, "Content-Length")) clen = static_cast(LengthOf(*v).value_or(0)); std::size_t total = idx + 4 + static_cast(clen); if (buf_.size() < total) return std::nullopt; - std::string msg = buf_.substr(0, total); + msg.append(buf_, idx, total - idx); buf_.erase(0, total); return msg; } @@ -467,6 +493,8 @@ export namespace imsd::sip { // fit is a truncated datagram → nullopt with `problem` set; no // Content-Length means the body is the rest of the datagram. A datagram // without a header terminator is malformed → nullopt with `problem`. + // The message comes out with its header section unfolded (Unfolded), + // where the Content-Length is read, and its body as it came. std::optional DatagramMessage(std::string_view d, std::string* problem = nullptr) { std::size_t start = d.find_first_not_of("\r\n"); if (start == std::string_view::npos) return std::nullopt; @@ -476,49 +504,52 @@ export namespace imsd::sip { if (problem) *problem = std::format("datagram without a header terminator ({} bytes)", d.size()); return std::nullopt; } - std::size_t bodyStart = idx + 4; - std::size_t body = d.size() - bodyStart; - if (auto v = Header(d.substr(0, idx), "Content-Length")) { + std::size_t body = d.size() - (idx + 4); + std::string msg = Unfolded(d.substr(0, idx)); + if (auto v = Header(msg, "Content-Length")) { if (const auto length = LengthOf(*v)) { const std::size_t clen = *length; if (clen > body) { if (problem) *problem = std::format("datagram truncated (Content-Length {} > {} body bytes)", clen, body); return std::nullopt; } - return std::string(d.substr(0, bodyStart + clen)); + body = clen; } } - return std::string(d); + msg.append(d.substr(idx, 4 + body)); + return msg; } // RFC 3261 18.3 of a datagram that ends before its message's body does: // "If the message is a response, it MUST be discarded. If the message // is a request, the element SHOULD generate a 400 (Bad Request) - // response." The header section of such a request, with the empty line - // that ends it and no body — what the 400 is built from — or nullopt - // for every other datagram: one whose body is all there, by its - // Content-Length or for want of one; one without an end of headers; - // one whose first line is no request's; an ACK or a CANCEL. A request's - // first line ends with the SIP version (7.1: "Request-Line = Method SP - // Request-URI SP SIP-Version CRLF") and a status line begins with it - // (7.2), in whatever letter case ("The SIP-Version string is - // case-insensitive"): a response is none, and neither are bytes that - // are no SIP. imsd keeps nothing of a request it answers so, and of an - // element that keeps nothing 8.2.7 says: "A stateless UAS MUST ignore - // ACK requests." "A stateless UAS MUST ignore CANCEL requests." + // response." The header section of such a request, unfolded (Unfolded), + // with the empty line that ends it and no body — what the 400 is built + // from — or nullopt for every other datagram: one whose body is all + // there, by its Content-Length or for want of one; one without an end + // of headers; one whose first line is no request's; an ACK or a CANCEL. + // A request's first line ends with the SIP version (7.1: "Request-Line + // = Method SP Request-URI SP SIP-Version CRLF") and a status line + // begins with it (7.2), in whatever letter case ("The SIP-Version + // string is case-insensitive"): a response is none, and neither are + // bytes that are no SIP. imsd keeps nothing of a request it answers so, + // and of an element that keeps nothing 8.2.7 says: "A stateless UAS + // MUST ignore ACK requests." "A stateless UAS MUST ignore CANCEL + // requests." std::optional CutShortRequest(std::string_view d) { const std::size_t start = d.find_first_not_of("\r\n"); if (start == std::string_view::npos) return std::nullopt; d.remove_prefix(start); const std::size_t idx = d.find("\r\n\r\n"); if (idx == std::string_view::npos) return std::nullopt; - const std::string_view head = d.substr(0, idx); + std::string head = Unfolded(d.substr(0, idx)); const auto length = Header(head, "Content-Length").and_then(LengthOf); if (!length || *length <= d.size() - (idx + 4)) return std::nullopt; - const std::string_view line = head.substr(0, head.find("\r\n")); + const std::string_view line = std::string_view(head).substr(0, head.find("\r\n")); const std::string_view last = line.substr(line.rfind(' ') + 1); // of a line without a space, the line if (last.size() != 7 || !IEqualsPrefix(last, "SIP/2.0") || IEqualsPrefix(line, "SIP/")) return std::nullopt; if (line.starts_with("ACK ") || line.starts_with("CANCEL ")) return std::nullopt; - return std::string(head) + "\r\n\r\n"; + head.append("\r\n\r\n"); + return head; } } diff --git a/tests/Engine/main.cpp b/tests/Engine/main.cpp index 3615e0c..6dbc3fb 100644 --- a/tests/Engine/main.cpp +++ b/tests/Engine/main.cpp @@ -41,7 +41,8 @@ // unusable TPDU acknowledged with an RP-ERROR, a body that is no RP // message, a page-mode text 200'd and logged, a short message while SMS // over IP is off refused with 480, a delivered MESSAGE and a final whose -// header names come in compact form), and the store's record codec +// header names come in compact form, a delivered MESSAGE whose +// Content-Type came folded), and the store's record codec // (FormatStoredSms/ParseStoredSms: a full record round trip, defaults // for absent keys, a value that does not parse or a missing id refused) and order // (StoredSmsBefore: the arrival second, then within a run the sequence @@ -1557,6 +1558,20 @@ int main() { 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"); } + // the same delivery with its Content-Type folded onto a second line (RFC 3261 7.3.1), as a framer hands it on + { + const std::string longForm = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07"); + std::string folded = longForm; + folded.replace(folded.find("Content-Type: "), 14, "Content-Type:\r\n\t"); + const auto framed = imsd::sip::DatagramMessage(folded); + Check(folded.contains("\r\nContent-Type:\r\n\tapplication/vnd.3gpp.sms\r\n") && framed == longForm, "folded MESSAGE: the datagram framer hands the long form's message on"); + imsd::util::Rng rng(80), rngLong(80); + Reassembler re, reLong; + auto r = OnSmsMessage(c, rng, framed.value_or(""), re, nullptr, 50.0); + auto want = OnSmsMessage(c, rngLong, longForm, reLong, nullptr, 50.0); + const auto* rec = findSms(r.actions, SmsAction::Type::Received); + Check(rec && rec->received.text == "How are you?" && r.response == want.response && hasSms(r.actions, SmsAction::Type::SendClient), "folded MESSAGE: taken for a short message, answered and reported on as its long form"); + } // the same delivery with its header names in compact form (RFC 3261 7.3.3): `c:` is the content type, `i:` the Call-ID, `v:` the Via { const std::string longForm = inbound("011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07"); diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 2db5339..d4471a7 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -6,12 +6,12 @@ // caller-identity extraction, the port a Via names for the response // (ViaResponsePort), the two framers — the TCP frame buffer (split delivery, // keepalive pongs, pipelined messages) and a datagram's (DatagramMessage), -// with the Content-Length they read —, a request whose datagram ends before -// its body does (CutShortRequest), a refused final's Retry-After and summary -// (RetryAfter, RefusalSummary), transaction matching (ResponseOf), our -// binding in a reg-event document (RegInfoContactState), and HeaderUri and -// Body. These pin the module's edge-case behavior; see the module header -// before "fixing" one. +// with the Content-Length they read and the unfolding of a folded header +// section (Unfolded) —, a request whose datagram ends before its body does +// (CutShortRequest), a refused final's Retry-After and summary (RetryAfter, +// RefusalSummary), transaction matching (ResponseOf), our binding in a +// reg-event document (RegInfoContactState), and HeaderUri and Body. These pin +// the module's edge-case behavior; see the module header before "fixing" one. import std; import Imsd; @@ -290,6 +290,8 @@ int main() { // a row that holds a list (RFC 3261 7.3.1): the top value alone speaks const std::string next = "SIP/2.0/UDP [2001:db8::9]:5060"; Check(ViaResponsePort(row(top + ";branch=z9hG4bKp, " + next + ";branch=z9hG4bKs;rport=5060")) == 6000, "a list on one line: the top value's port, a later value's rport not counted"); + auto folded = DatagramMessage(row(top + ";branch=z9hG4bKp,\r\n " + next + ";branch=z9hG4bKs;rport=5060")); + Check(folded && ViaResponsePort(*folded) == 6000, "the same list folded after its comma, as the datagram framer hands it on"); Check(!ViaResponsePort(row(top + ";rport;branch=z9hG4bKp, " + next + ";branch=z9hG4bKs")).has_value(), "the top value's own rport counts"); Check(!ViaResponsePort(row(top + ";branch=z9hG4bKp;rport, " + next + ";branch=z9hG4bKs")).has_value(), "also where it stands last before the comma"); Check(ViaResponsePort(row(top + ", " + next + ";branch=z9hG4bKs")) == 6000, "a top value without parameters: its own port, not the next value's"); @@ -354,6 +356,55 @@ int main() { } } + // ---- Unfolded, and the framers that use it (RFC 3261 7.3.1: a line begun with a space or a tab goes on with the line before it) + { + Check(Unfolded("Subject: I know you're there,\r\n pick up the phone\r\n and talk to me!") == "Subject: I know you're there, pick up the phone and talk to me!", "7.3.1's own example: each line break and the white space after it are one space"); + Check(Unfolded("A: 1\r\n\t2") == "A: 1 2" && Unfolded("A: 1\r\n \t 2") == "A: 1 2", "a tab begins a continuation as a space does, and a run of them is one space"); + Check(Unfolded("A:\r\n 1") == "A: 1", "a value that begins on the next line"); + Check(Unfolded("A: 1 \r\n 2") == "A: 1 2", "white space before the line break is kept"); + Check(Unfolded("A: 1\n 2") == "A: 1 2", "a bare LF folds as a CRLF does"); + Check(Unfolded("A: 1\r\nB: 2\r\n") == "A: 1\r\nB: 2\r\n", "a line break that no white space follows is kept"); + Check(Unfolded("A: 1\r\n") == "A: 1\r\n" && Unfolded("A: 1\n") == "A: 1\n" && Unfolded("\n") == "\n" && Unfolded("").empty(), "a line break that ends the text is kept"); + Check(Unfolded("A: 1\r\n \r\n 2") == "A: 1 2", "a continuation line of white space alone"); + Check(Unfolded("A: 1\r 2") == "A: 1\r 2", "a CR alone is no line break"); + Check(Unfolded("A: 1\r\n ") == "A: 1 " && Unfolded("A: 1\r\n \t") == "A: 1 ", "white space after a line break that ends the text is that one space"); + Check(Unfolded("\n 1") == " 1" && Unfolded("\r\n\t1") == " 1", "a text that begins with a fold"); + // a 401 whose WWW-Authenticate goes over four lines, its nonce on the second + const std::string folded401 = + "SIP/2.0 401 Unauthorized\r\n" + "Call-ID: f1@host\r\n" + "CSeq: 1\r\n REGISTER\r\n" + "WWW-Authenticate: Digest realm=\"ims.example\",\r\n" + " nonce=\"bm9uY2U=\",\r\n" + " algorithm=AKAv1-MD5,\r\n" + " qop=\"auth\"\r\n" + "Content-Length:\r\n" + "\t5\r\n\r\n"; + const std::string body = "a\r\n b"; // a body line that begins with a space is no fold + const std::string unfolded401 = + "SIP/2.0 401 Unauthorized\r\n" + "Call-ID: f1@host\r\n" + "CSeq: 1 REGISTER\r\n" + "WWW-Authenticate: Digest realm=\"ims.example\", nonce=\"bm9uY2U=\", algorithm=AKAv1-MD5, qop=\"auth\"\r\n" + "Content-Length: 5\r\n\r\n"; + FrameBuffer fb; + fb.Append(folded401 + body + Resp200); + auto m = fb.TryExtract(); + Check(m == unfolded401 + body, "the stream framer hands a message out with its header section unfolded and its body as it came"); + Check(m && Header(*m, "WWW-Authenticate") == "Digest realm=\"ims.example\", nonce=\"bm9uY2U=\", algorithm=AKAv1-MD5, qop=\"auth\"", "a folded WWW-Authenticate is read whole"); + Check(m && ResponseOf(*m, "f1@host", "1 REGISTER"), "a CSeq folded between its number and its method is the transaction's"); + Check(fb.TryExtract() == Resp200 && !fb.TryExtract().has_value(), "a folded Content-Length frames the body: the next message starts after it"); + fb.Append(folded401 + body.substr(0, 3)); + Check(!fb.TryExtract().has_value(), "a body shorter than a folded Content-Length says is waited for"); + fb.Append(body.substr(3)); + Check(fb.TryExtract() == unfolded401 + body, "and taken once it is whole"); + std::string why; + Check(DatagramMessage(folded401 + body + "JUNK", &why) == unfolded401 + body && why.empty(), "the datagram framer does the same, and cuts at a folded Content-Length"); + Check(!DatagramMessage(folded401 + "a\r\n ", &why).has_value() && why.contains("truncated"), "a datagram shorter than its folded Content-Length: discarded, problem set"); + Check(DatagramMessage("SIP/2.0 200 OK\r\nCall-ID:\r\n a\r\n\r\nv=0\r\n b") == "SIP/2.0 200 OK\r\nCall-ID: a\r\n\r\nv=0\r\n b", "no Content-Length: the header section unfolded, the rest of the datagram the body as it came"); + Check(CutShortRequest("MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP\r\n [2001:db8::2]:6000\r\nContent-Length:\r\n\t9\r\n\r\nhello") == "MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::2]:6000\r\nContent-Length: 9\r\n\r\n", "a request cut short of a folded Content-Length: its header section unfolded, for the 400"); + } + // ---- RetryAfter / RefusalSummary (what a refused final is logged as) { std::string r503 = From 710f884575af6a925243897d557c5b9d95b10cfe Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:12 +0100 Subject: [PATCH 10/40] imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LoadStoredSms had no way to report a failure. A store directory that could not be opened read as an empty store, and a record that could not be opened read as a corrupt file and was skipped: Messaging.List answered success with texts missing. A consumer that forgets a deleted text's id once List no longer carries it forgets it too early then, and imports the text again when a later List has it; and a text that arrived while no app ran stays unseen until another List (issue #5). The scans also walked the directory with the iterator's throwing increment and tested each entry with is_regular_file() in its throwing form, and nothing catches that at the start's sweep, in List's handler or in the run loop: a read error there ended the process — in the run loop from the count for the `stored` journal line, with a text stored and its delivery report unsent. The three scans now go through opendir, readdir, stat and read. What a scan cannot read is a StoreFault, logged by the scan that met it; List's read and the count hand theirs back as well. List answers org.freedesktop.DBus.Error.IOError with the system's reason, the error Delete gives for a removal that failed: no list, so a consumer takes nothing for deleted and asks again. A store directory that does not exist is still an empty list, and a file that reads and is no record is still skipped with its line. The sweep logs the fault and lets the daemon start; the `stored` line goes without its count. The journal names what could not be read: `sms store: cannot read : `. The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no member, signature, key, state word or error name changes; List gains a failure answer under an error name the interface has. Tested in dev mode on a private session bus, on the workstation's build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture, list-io): IOError with "Permission denied" for the store directory at mode 000 and at mode 400 and for a record at mode 000, and with "Not a directory" for a file in the directory's place; an empty list with no directory; both records listed beside a file that is no record, a directory and a dangling link named like records; a start with the directory at mode 000 logs the sweep's fault and the daemon answers. On the dev phone, with the binary of this range's last commit (the capture's phone-form6): an empty list with the store directory moved away, IOError with "Not a directory" with a file in its place, the fault in the journal for each call it refused. Not benched: a read that fails part-way, a file removed between the directory's read and its own, a process out of descriptors, the `stored` line without its count. --- AGENTS.md | 44 ++++++++++- README.md | 6 +- implementations/main.cpp | 167 +++++++++++++++++++++++++++++++++------ 3 files changed, 187 insertions(+), 30 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index de49c6f..9f42bf4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -162,7 +162,8 @@ that asked for one `SameRecipient` and `StatusReportBook`, all with tests. The received-message store (§7.9) keeps in the shell, among others, the `link(2)` publish and its retry with the next id, the sweep of `.tmp` files at the engine's start, `Delete`'s id check and its -answers by the removal's outcome, `List`'s skip of a file that is no record and the delivery +answers by the removal's outcome, `List`'s skip of a file that is no record, its `IOError` +for a store it could not read, the count the `stored` line loses for one, and the delivery report a store failure leaves unchanged; the record codec and `List`'s order are the core's, with tests. @@ -692,6 +693,25 @@ Rules: `IOError` for a record in a store directory made unwritable, the record still listed; the removal once it was writable; `FileNotFound` for an id with no record. + A store that cannot be read ran there too (2026-11-20 to 2026-11-22, the fp6 journal's + `2026-11-20-issues-2-5` capture, `list-io`): `List` answered `IOError` + with `Permission denied` for a store directory of mode 000, for one of + mode 400 (its names read, its first record's `stat` refused) and for a + record of mode 000, and with `Not a directory` for a file where the + directory should be; it answered an empty list with no store directory, + and the two records beside a file that is no record, a directory and a + dangling symbolic link named like records; a start with the directory + at mode 000 wrote the sweep's `cannot read` line and the daemon + answered afterwards. On the dev phone (2026-11-22, the + same capture, `phone-form6`, `checks.log`, the binary of 1.2.1) + `List` answered an empty list with the store directory + moved away and `IOError` with `Not a directory` with a file in its + place, with the journal's `cannot read` line for each of the two calls + it refused. Not reached by any bench: a directory or a file + whose read fails part-way, a file removed between the directory's read + and its own, a process out of descriptors, and the `stored` line + without its count, which takes a text received, and dev mode receives + none. Reached from 2026-10-18 02:17 (`smsc-override-2026-10-18-0217`): the `SMSC=` override — `SMSC=+31653131313` gives `service centre +31653131313 (SMSC=)` and a `Send` through it reaches `sent`; `SMSC=abc` gives @@ -1613,7 +1633,13 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: temporary file(s) removed` (at the engine's start); `sms : NOT stored — ; the bus signal is its only delivery`; `sms : deleted from the store`; `sms : not deleted from the store: `; `sms - store: is no record; skipped`. + store: is no record; skipped`; `sms store: cannot read : + ` — the first thing a scan of the store cannot read, for + another reason than that nothing is there: the store directory, opened + or read to its end, at any scan; a `.tmp` name's `stat` at the engine's + start (the sweep); a `.msg` name's `stat`, `open` or `read` at a `List` + (which answers `IOError`, §8.4) and at the count for the `stored` line, + which is then `sms : stored` alone. - `idle: no SIM — nothing to do; systemctl start imsd when that changes` (or `idle: no ims PDN from the network — …` from `IMSD_IDLE`; `idle: no P-CSCF — none configured (PCSCF=), none discovered (see the ims-pdn-up @@ -1721,7 +1747,17 @@ do that answers without state. record's second name — is removed when the engine next starts (`sms store: N stale temporary file(s) removed`; a start that exits before the engine runs leaves it, and one the sweep cannot unlink stays unreported); `Delete` - leaves `.tmp` names alone. `received` is that wall clock: before a boot's first time + leaves `.tmp` names alone. A store that cannot be read — its directory, + or the file of a `.msg` or a `.tmp` name in it — is logged (`sms + store: cannot read …`) by the scan that meets it and ends no process: + the start's sweep lets the daemon start, the `stored` line goes + without its count, and `List` answers `IOError` (§8.4), never a shorter + list — every `List` while the fault lasts, the readable records beside + an unreadable one with it: the line names the path. No fault, and passed over without a line: a store directory that + does not exist, which holds nothing, and a name behind which stat(2) + finds no regular file — a directory — or nothing (`ENOENT`: a dangling + link, a file removed since the directory was read). A file that reads and is no record is + skipped with its line, the rest listed. `received` is that wall clock: before a boot's first time sync it reads 1970, and `List`'s oldest-first order follows it, so an app that cares orders by the SC's `timestamp`. A store failure is logged, the signal still goes out, and the delivery report stays an RP-ACK — @@ -2002,7 +2038,7 @@ when it does not know it. | `Send(number, text, options)` | `ssa{sv} → s` (the message's id, `ims-sms---`: this run's token — eight hex digits drawn at the daemon's start —, its start second and a counter; a later run gives the same id only if it draws the same token and starts in the same second, and a received id (`ims-sms-in---`) only with the same token, arrival second and counter; a client keys `StateChanged` by id); options: `status-report` (b). `org.freedesktop.DBus.Error.NotSupported` while `SMS_OVER_IMS` is off | | `GetStatus()` | `→ a{sv}`: `enabled` (b, the daemon's configuration — answered before the first registration too), `smsc` (s, the service centre as of the daemon's last status snapshot, the one the frozen `GetStatus` answers from — so empty before a run's first, and when none is known), `ppi` (s, the own number in that snapshot — the frozen interface's `ppi`, made valid UTF-8 as `to` is, so a consumer needs no second call — empty while the snapshot holds none), `operator` (s, the SIM's operator id — MCC then MNC, as ModemManager gives it, and never the IMSI — empty until the first status after the SIM is read), `registered` (b), `subscribers` (u). No count of the store: `GetStatus` is the open read, and a count would tell any local account when a text arrived; `List`'s length is behind the gate | | `Subscribe()` | `→` nothing: the caller's connection receives the two signals below from now on, until it closes. It succeeds while SMS over IP is off too (only `Send` is refused then); a consumer reads `enabled` for that state | -| `List()` | `→ a(sa{sv})`: the stored messages it can read, by the arrival second on the phone's wall clock, then within a run the sequence number — oldest first on a synced clock (a 1970 second before the first time sync sorts first; the SC's `timestamp` is the chronology, §7.9) — each the id and the same dictionary `Received` carries (its `received` the arrival time) | +| `List()` | `→ a(sa{sv})`: the stored messages, by the arrival second on the phone's wall clock, then within a run the sequence number — oldest first on a synced clock (a 1970 second before the first time sync sorts first; the SC's `timestamp` is the chronology, §7.9) — each the id and the same dictionary `Received` carries (its `received` the arrival time); a file in the store that reads and is no record is left out, as is a name behind which stat(2) finds no regular file or nothing (`ENOENT`), and a store directory that does not exist is an empty list. `org.freedesktop.DBus.Error.IOError`, with the system's reason, when the store directory or a record's file could not be read: no list comes then, and none while the fault lasts, so a consumer asks again later and takes no message for deleted | | `Delete(id)` | `s`: removes a stored message; `org.freedesktop.DBus.Error.InvalidArgs` for an empty string, one over 64 bytes or one with a character other than an ASCII letter, an ASCII digit or `-`; `org.freedesktop.DBus.Error.FileNotFound` for any other string when the removal found no file; `org.freedesktop.DBus.Error.IOError`, with the system's reason, when the removal failed — a record that is there is kept | | `Received` | `s a{sv}` — unicast to each subscriber (id `ims-sms-in---`; `from` s, `text` s, `timestamp` s (the SC's, with its offset: `2026-10-16T22:50:00+02:00`), `received` x (epoch), `sc` s, `to` s when the daemon held an own number at receipt (the first tel: P-Associated-URI of this run's latest answer to a fresh registration, a resume or a reconnect that carried one — a periodic refresh's answer is not read for it — and, until the first such, the state file's once a resume attempt has taken it up): the subscriber the text arrived for, which a later SIM's status cannot tell, `operator` s when the SIM's operator id was known at receipt: the subscription's country and operator, by which a consumer reads a sender in national form or a short code, `class` i (-1: none), `pid` y, `dcs` y, `segments` i, `message-waiting` b, `port-dst`/`port-src` u when the header addresses a port, `data` ay for 8-bit data, `pdu` ay — the SMS-DELIVER as received; of a concatenated message, the segment that completed the set, the last to arrive) | | `StateChanged` | `s s s` — unicast to each subscriber, and the submission's `sent` / `failed` also to the connection that called `Send` (id, state, reason): `sent` / `failed` for the submission, `delivered` / `delivery-pending` / `delivery-failed` from a status report — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once; `delivered` only when every segment's report is in the completed class (§7.9; the reason carries the SC's status word). The words of one message come in this order: the submission's first — `sent`, or `failed`, after which nothing follows — and a status report's only after `sent` (a report the SC sends while a later segment is still on its way is held until the submission ends; a submission whose every segment the SC reported delivered before its last submit report came ends as `sent` then `delivered`), so a consumer applies each word as it comes. Every string of the two signals is valid UTF-8: a `failed` reason can hold the network's text (a refused final's, `RefusalSummary`), so the emission makes it valid — bytes that are not UTF-8 become U+FFFD, and a NUL byte ends the string (the `Received` strings are the codecs' own; `to` is made valid the same way, and `operator` is digits) | diff --git a/README.md b/README.md index b072e38..a0a4c38 100644 --- a/README.md +++ b/README.md @@ -147,15 +147,15 @@ A new desktop needs a new translation daemon, not changes here. A second interface on the same object, for short messages over IMS (`SMS_OVER_IMS=1`). Additive: the interface above is unchanged. Frozen as of -1.2.0: what the table lists stays as it is, and a dictionary imsd gives may -gain a key. +1.2.0: its members and their signatures stay as they are, and a dictionary +imsd gives may gain a key. | Member | Signature | |---|---| | `Send(number, text, options)` | `ssa{sv} → s` (id); options: `status-report` (b, ask the SC to report delivery). Refused with `NotSupported` while SMS over IMS is off | | `GetStatus()` | `→ a{sv}`: `enabled` (b), `smsc` (s), `ppi` (s, the own number in the daemon's last status, e.g. `tel:+31612345678`), `operator` (s, the SIM's operator id in that status), `registered` (b), `subscribers` (u) | | `Subscribe()` | `→` nothing: the calling connection receives `Received` and `StateChanged` from now on (unicast, never broadcast: to subscribers, and a submission's `sent` / `failed` also to its `Send` caller); subscribe again when imsd's name reappears on the bus | -| `List()` | `→ a(sa{sv})`: the stored messages it can read, by the arrival second on the phone's wall clock, then within a run the sequence number (a 1970 clock before the first time sync sorts first; the SC's `timestamp` is the real chronology), each the id and the dictionary `Received` carries | +| `List()` | `→ a(sa{sv})`: the stored messages, by the arrival second on the phone's wall clock, then within a run the sequence number (a 1970 clock before the first time sync sorts first; the SC's `timestamp` is the real chronology), each the id and the dictionary `Received` carries; `IOError` when a store that is there cannot be read | | `Delete(id)` | `s`: removes a stored message | | `Received` | `s a{sv}` (id, message: `from`, `text`, `timestamp` (the SC's, as `2026-10-16T22:50:00+02:00`), `received` (x), `sc`, `to` (when the daemon held an own number at receipt: that number, e.g. `tel:+31612345678`), `operator` (the SIM's operator id at receipt), `class` (i, -1 none), `pid` (y), `dcs` (y), `segments` (i), `message-waiting` (b), `port-dst`/`port-src` (u, when addressed to a port), `data` (ay, 8-bit data), `pdu` (ay, the SMS-DELIVER as received; of a concatenated message, the segment that completed it)) | | `StateChanged` | `s s s` (id, state, reason): `sent` (every segment accepted by the SC), `failed` (why), and with a status report `delivered` (every segment), `delivery-pending`, `delivery-failed` — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once | diff --git a/implementations/main.cpp b/implementations/main.cpp index 5f8b078..1a29618 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -29,6 +29,7 @@ its subscriber set on the main thread too. */ #include +#include #include #include #include @@ -40,6 +41,7 @@ its subscriber set on the main thread too. #include #include #include +#include #include #include #include @@ -1033,7 +1035,12 @@ void EmitSignalTo(const std::string& destination, const char* name, GVariant* pa // A record is written whole to a .tmp beside it, fsynced, linked to its // name with link(2) — which refuses a name already taken — and the .tmp // removed, the directory fsynced after it, so a listing never sees a -// half-written one and nothing is replaced. +// half-written one and nothing is replaced. The three scans — the start's +// sweep, List's read and the count for the journal — go through +// opendir(3), readdir(3), stat(2) and read(2), whose errors come back as +// values. What a scan cannot read is a StoreFault, logged by the scan that +// met it; +// List's read and the count hand theirs back as well. std::string SmsStoreDir() { return std::format("{}/sms", StateDir()); } bool ValidSmsId(std::string_view id) { @@ -1045,18 +1052,104 @@ bool ValidSmsId(std::string_view id) { std::string SmsRecordPath(std::string_view id) { return std::format("{}/{}.msg", SmsStoreDir(), id); } +// What kept a scan of the store from reading it whole: where it stopped +// and the system's error. Empty when nothing did. +struct StoreFault { + std::string path; + int err = 0; + explicit operator bool() const { return err != 0; } + std::string Reason() const { return std::generic_category().message(err); } +}; + +void LogStoreFault(const StoreFault& f) { Log(std::format("sms store: cannot read {}: {}", f.path, f.Reason())); } + +// The names in the store directory. A directory that is not there holds +// none and is no fault: the first record stored makes it. Any other +// failure to open it, or to read it to its end, is — and the names read +// until then are not handed over. +StoreFault SmsStoreNames(std::vector& names) { + const std::string dir = SmsStoreDir(); + DIR* d = opendir(dir.c_str()); + if (!d) { + const int err = errno; // read before the fault copies the path: an allocation may change it + return err == ENOENT ? StoreFault{} : StoreFault{dir, err}; + } + StoreFault fault; + for (;;) { + errno = 0; // readdir(3): a null with errno unchanged is the end + const dirent* e = readdir(d); + if (!e) { + if (const int err = errno; err != 0) fault = {dir, err}; + break; + } + names.emplace_back(e->d_name); + } + closedir(d); + if (fault) names.clear(); + return fault; +} + +// A store file's name by its ending: `.msg` a record, +// `.tmp` a writer's temporary file. +bool HasStoreSuffix(std::string_view name, std::string_view suffix) { return name.size() > suffix.size() && name.ends_with(suffix); } + +// Whether `path` is a regular file, a symbolic link to one included. One +// that is gone since the directory was read is not, and no fault; any +// other failure of stat(2) is the fault. +bool IsStoreFile(const std::string& path, StoreFault& fault) { + struct stat st {}; + if (stat(path.c_str(), &st) != 0) { + if (const int err = errno; err != ENOENT) fault = {path, err}; + return false; + } + return S_ISREG(st.st_mode); +} + +// A store file's whole content into `text`. False when the file is gone +// since the directory was read (no fault) or could not be opened or read +// to its end (the fault). +bool ReadStoreFile(const std::string& path, std::string& text, StoreFault& fault) { + const int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + if (const int err = errno; err != ENOENT) fault = {path, err}; + return false; + } + bool whole = false; + char buf[4096]; + for (;;) { + const ssize_t n = read(fd, buf, sizeof buf); + if (n > 0) { text.append(buf, static_cast(n)); continue; } + const int err = n < 0 ? errno : 0; + if (err == EINTR) continue; + if (err != 0) fault = {path, err}; + else whole = true; + break; + } + close(fd); + return whole; +} + // The .tmp files a crash left (between the open and the link, or between // the link and the unlink, when one is a record's second name): unlinked // at the engine's start, before it takes its first message; the count is // of those the unlink removed. A record whose second name goes keeps its -// inode. +// inode. A store that cannot be read is logged and left: the daemon +// starts all the same. int SweepSmsStore() { - std::error_code ec; + std::vector names; + StoreFault fault = SmsStoreNames(names); int n = 0; - for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) { - if (!e.is_regular_file() || e.path().extension() != ".tmp") continue; - if (unlink(e.path().c_str()) == 0) n++; + for (const std::string& name : names) { + if (!HasStoreSuffix(name, ".tmp")) continue; + const std::string path = std::format("{}/{}", SmsStoreDir(), name); + StoreFault here; + if (!IsStoreFile(path, here)) { + if (here && !fault) fault = here; + continue; + } + if (unlink(path.c_str()) == 0) n++; } + if (fault) LogStoreFault(fault); return n; } @@ -1107,25 +1200,42 @@ StoreResult StoreReceivedSms(const imsd::engine::StoredSms& r, std::string& why) return StoreResult::Stored; } -// The stored messages, oldest first: the `.msg` files, one that is no -// record skipped (logged when `log`). -std::vector LoadStoredSms(bool log = true) { - std::vector out; - std::error_code ec; - for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) { - if (!e.is_regular_file() || e.path().extension() != ".msg") continue; - std::ifstream in(e.path(), std::ios::binary); - std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); +// The stored messages, oldest first: the `.msg` files, one that reads and +// is no record skipped (logged when `log`) — one corrupt file does not +// close the store. The scan stops at the first thing it cannot read — the +// directory, a file's type, a file — with that as `fault`, logged: the +// records are then not the store's, and a caller must not hand them over +// as if they were. +struct StoreRead { + std::vector records; + StoreFault fault; +}; +StoreRead LoadStoredSms(bool log = true) { + StoreRead out; + std::vector names; + out.fault = SmsStoreNames(names); + for (const std::string& name : names) { + if (out.fault) break; + if (!HasStoreSuffix(name, ".msg")) continue; + const std::string path = std::format("{}/{}", SmsStoreDir(), name); + std::string text; + if (!IsStoreFile(path, out.fault) || !ReadStoreFile(path, text, out.fault)) continue; auto r = imsd::engine::ParseStoredSms(text); - if (!r) { if (log) Log(std::format("sms store: {} is no record; skipped", e.path().string())); continue; } - out.push_back(std::move(*r)); + if (!r) { if (log) Log(std::format("sms store: {} is no record; skipped", path)); continue; } + out.records.push_back(std::move(*r)); } - std::sort(out.begin(), out.end(), imsd::engine::StoredSmsBefore); + if (out.fault) LogStoreFault(out.fault); + std::sort(out.records.begin(), out.records.end(), imsd::engine::StoredSmsBefore); return out; } -// The records in the store (what List would hand over), not the files. -std::size_t StoredSmsCount() { return LoadStoredSms(false).size(); } +// The records in the store (what List would hand over), not the files; +// none when the store could not be read. +std::optional StoredSmsCount() { + const StoreRead store = LoadStoredSms(false); + if (store.fault) return std::nullopt; + return store.records.size(); +} // a received short message as the Messaging interface's a{sv} (§8.4) GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt, const std::string& to, const std::string& simOperator) { @@ -2975,8 +3085,13 @@ private: } Log(std::format("sms {}: from {} via {}, {}{}", ev->uni, m.from, m.sc, m.data.empty() ? std::format("{} bytes of text", m.text.size()) : std::format("{} bytes of 8-bit data", m.data.size()), m.segments > 1 ? std::format(" in {} segments", m.segments) : std::string())); - if (stored == StoreResult::Stored) Log(std::format("sms {}: stored ({} kept until an app deletes them)", ev->uni, StoredSmsCount())); - else Log(std::format("sms {}: NOT stored — {}; the bus signal is its only delivery", ev->uni, stored == StoreResult::Exists ? "a thousand names taken" : why)); + if (stored == StoreResult::Stored) { + // a store that cannot be read back costs this line its count (the scan has logged why), never the signal or the delivery report + const auto kept = StoredSmsCount(); + Log(kept ? std::format("sms {}: stored ({} kept until an app deletes them)", ev->uni, *kept) : std::format("sms {}: stored", ev->uni)); + } else { + Log(std::format("sms {}: NOT stored — {}; the bus signal is its only delivery", ev->uni, stored == StoreResult::Exists ? "a thousand names taken" : why)); + } PostEvent(std::move(ev)); } void PostSmsState(const std::string& id, std::string_view state, std::string_view reason) { @@ -3374,9 +3489,15 @@ void HandleMessagingMethod(GDBusConnection* conn, const gchar*, const gchar*, co return; } if (m == "List") { + const StoreRead store = LoadStoredSms(); + if (store.fault) { + // not a shorter list: a consumer takes a record List leaves out for one it may forget + g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.IOError", store.fault.Reason().c_str()); + return; + } GVariantBuilder b; g_variant_builder_init(&b, G_VARIANT_TYPE("a(sa{sv})")); - for (const auto& r : LoadStoredSms()) g_variant_builder_add(&b, "(s@a{sv})", r.id.c_str(), SmsVariant(r.sms, r.receivedAt, r.to, r.simOperator)); + for (const auto& r : store.records) g_variant_builder_add(&b, "(s@a{sv})", r.id.c_str(), SmsVariant(r.sms, r.receivedAt, r.to, r.simOperator)); g_dbus_method_invocation_return_value(inv, g_variant_new("(a(sa{sv}))", &b)); return; } From ef04b473a77d82250d626518a35b9fff3eaaa3bc Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Sun, 22 Nov 2026 17:35:12 +0100 Subject: [PATCH 11/40] engine, imsd: a submit report for a MESSAGE no longer in flight that this run sent in the last hour is answered 200 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TS 24.341 5.3.1.2 has a submit report answered 200 when its In-Reply-To "indicates that the request corresponds to a short message submitted by the SM-over-IP sender" and 488 when it does not, and its NOTE 3 has the sender store the Call-ID for that. imsd knew only the Call-ID of the segment in flight (OwnsReport): a report that came once its message had ended — the 40 s wait run out — or once its segment was followed by the next was answered 488 like a stranger's, and its line said only "no MESSAGE of ours in flight" (issue #3, the first of its three cases). RecentSubmissions keeps the Call-ID of every MESSAGE a submission goes out in for an hour, with the message's id and the segment. A report In-Reply-To one of them that the message in flight does not take is answered 200, and the journal has `submit report (RP-ACK) In-Reply-To …: sms 's segment i/n, no longer in flight; 200`, an RP-ERROR's with its cause. The 488 is left for an In-Reply-To that names no MESSAGE of ours on record, and its line says so ("on record" for "in flight"). A report without In-Reply-To that no message in flight takes by its RP-MR is answered 200 as before; its line ends `that no message in flight owns; 200` where it ended `for no message in flight; 200`. The bus is told nothing of a late report: the Messaging interface is frozen with `failed` as a message's last word (AGENTS.md §8.4), so a text the service centre took after its wait had run out stays `failed` there; the journal's line is the record of it. Tested by tests/Engine: the table (a Call-ID on record for 3600 s, the first of a list that is ours, each segment's MESSAGE put on record as it goes out) and OnSmsMessage (200 and the line for a report on a segment that was followed by the next, on a message that was sent and, with an RP-ERROR's cause, on one its wait had ended; 488 and its line for a stranger's). On the dev phone, with the binary of this range's last commit, no report came for a MESSAGE no longer in flight (the fp6 journal's 2026-11-20-issues-2-5 capture, phone-form6), so the 200 for one and its line have run in the suite alone. --- AGENTS.md | 52 ++++++++----- implementations/main.cpp | 5 +- interfaces/Imsd-Engine.cppm | 96 +++++++++++++++++++----- tests/Engine/main.cpp | 144 +++++++++++++++++++++--------------- 4 files changed, 203 insertions(+), 94 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9f42bf4..4a1a256 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,7 +47,7 @@ PipeWire. The verified device/carrier combinations are in the README. | `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; `tests/Messages` is their suite. 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 for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); since 1.2.1 `BuildBadRequest`, the 400 to a request cut short of the Content-Length read from it — any but an ACK or a CANCEL, in a call's dialog or not —, in that shape, a To tag it adds made from the request's header section and a secret of the run (RFC 3261 8.2.7); of requests that came whole, in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; 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), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `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` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | +| `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 (§7.9): `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` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first Via row and a request with none or an empty one never matched — answered with the same final and not handled again) and, since 1.2.1, `RecentSubmissions` (the Call-IDs of the MESSAGEs our submissions went out in, an hour each, by which a submit report for one that is no longer in flight is known for ours — TS 24.341 5.3.1.2); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. | | `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 and messaging (`Gated`'s `Action` parameter names the action), 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. | @@ -157,7 +157,7 @@ judgement of the final's wait and of the report's after the server ports' drain, failure attributed by Call-ID, and the forwarding of a status report's word to the bus — the transactions themselves are `SmsOutbound` and `OnSmsMessage` (a submit report's routing to the message in flight, by -In-Reply-To, else RP-MR, is theirs), and the report's match to the message +In-Reply-To, else RP-MR, and past that to a MESSAGE of ours on record, is theirs), and the report's match to the message that asked for one `SameRecipient` and `StatusReportBook`, all with tests. The received-message store (§7.9) keeps in the shell, among others, the `link(2)` publish and its retry with the next id, @@ -378,10 +378,13 @@ What the suites pin: 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 + report routed to the message in flight (by In-Reply-To, else RP-MR), 200 + and the journal's line for one In-Reply-To a MESSAGE of ours no longer + in flight (ours once ended, an RP-ERROR's cause in the line; ours once + its segment was followed by the next), 488 for a stranger's, 200 for one + without In-Reply-To that no message in flight owns; `RecentSubmissions`: a Call-ID on + record for 3600 s, the first of a list that is ours, each segment's + MESSAGE put on record as it goes out; an unusable TPDU acknowledged with an RP-ERROR, a body that is no RP message, a page-mode text 200'd and logged, a short message while SMS over IP is off refused with 480; a delivered MESSAGE whose header names come in compact form — the 200 and @@ -656,8 +659,10 @@ Rules: `r23-phone-journal-2026-10-17-precise-and-modem-sms`; whether KPN's SC sends them over this path is unknown), 8-bit data (an MMS notification), a message while SMS over IP is off (the 480), a submit - report In-Reply-To no MESSAGE of ours in flight (the 488) or one without - In-Reply-To for no message in flight (the 200), a page-mode MESSAGE, a body that is no RP message, a text + report In-Reply-To no MESSAGE of ours in flight (1.2.0's 488: since then + the 200 for one of ours on record and the 488 for one that names none, + each with a line of its own that no bench on hardware has written) or one without + In-Reply-To that no message in flight owns (the 200), a page-mode MESSAGE, a body that is no RP message, a text past 255 segments, an EF_SMSP record 1 that cannot be read or holds no service centre, or one whose service centre is not an international number, a @@ -1264,8 +1269,8 @@ emptied, never unlinked. The recovery policy's waits and the holds are measured on the boot clock (`CLOCK_BOOTTIME`), so a suspend counts; the keepalive refresh gate, the CRLF keepalive, the reg-event retry and renewal timers and the times SMS over IP measures (§7.9: its two waits, -the 30-minute age-out, the retransmission table's 32 s) run on the steady -clock and count awake seconds only. +the 30-minute age-out, the retransmission table's 32 s, the submissions +table's hour) run on the steady clock and count awake seconds only. The **reg-event subscription** (RFC 3680; the network's own view of the binding) is one live dialog per registration, subscribed anew ahead of the @@ -1601,8 +1606,11 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: the delivered MESSAGE: no delivery report RP-ACK|RP-ERROR sent`; `status report from : TP-MR n to : … (discharged