From e3b94a8415d280cf0a9744561eff30f39e4ce681 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Tue, 1 Dec 2026 14:22:05 +0100 Subject: [PATCH 1/7] AGENTS.md, imsd: an ISIM's identity has registered on a network MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AGENTS.md §5 said that this daemon had sent no network a REGISTER with names it read from an ISIM and no real ISIM an AUTHENTICATE, §13 that it had not sent the US card's network the card's own names, and a comment of the shell that no AKA in a real ISIM had run on this code. A reporter's journal of 2026-11-25 has imsd read that card's ISIM and register under its names on AT&T's network, without the line an application that gives no result for the challenge leaves (imsd 1.2.4 by the reporter's word; the fp6 journal's 2026-12-01-min-se-retry capture, evidence/). §13 has what the journal shows. --- AGENTS.md | 20 +++++++++++++++----- implementations/main.cpp | 3 +-- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 63e58cf..0e2a42c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -625,9 +625,10 @@ Rules: under the standing registration's names) and fresh registrations before which an ISIM that gave none at the bring-up is read again: giving its identity at the first, or none again at the first and its identity at - the second. The reads' commands ran on two reporters' cards in the - journal's probe, §13; this daemon has sent no network a REGISTER with - names it read from an ISIM, and no real ISIM an AUTHENTICATE); a + the second. On real cards: the reads' commands ran on two reporters' + cards in the journal's probe, and a reporter's journal has this daemon + read the US card's ISIM, register under its names on AT&T's network + and refresh that registration, with no `AKA:` line (§13)); a Security-Server list `PersistState` writes empty (one with a quote, a backslash or a newline — neither KPN's nor O2's list has one; the resume of such a file ran with a hand-edited empty key, @@ -3629,8 +3630,17 @@ the related code. (2026-11-09: a journal has the answer in the second the REGISTER was sent, a dump of such an answer has no Reason, Warning or Retry-After) — what TS 24.229 5.3.1.3 has an I-CSCF answer - when the HSS lookup "cannot be completed"; this daemon has not sent - that network the card's own names. + when the HSS lookup "cannot be completed". Under the card's own names + imsd registered on that network (the reporter's phone, 2026-11-25, imsd + 1.2.4 by the reporter's word; the fp6 journal's `2026-12-01-min-se-retry` + capture): the `identity:` line with the three names above; a + `Security-Server` of one `ipsec-3gpp` mechanism (`hmac-sha-1-96`, + `aes-cbc`) to the two-cipher offer; `REGISTERED (fresh)` in the second + after `FRESH registration`, and no `AKA:` line; a 200 without a + Service-Route, with a `tel:` P-Associated-URI and a `sip:` one at + `one.att.net`, and a binding of `expires=2112`; two refreshes within + the hour. Each of the five calls placed in that boot ended `INVITE + final 422`. - **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 diff --git a/implementations/main.cpp b/implementations/main.cpp index 605f932..455a8e9 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -2875,8 +2875,7 @@ private: // 7.1.2) and the IMS AKA context of an ISIM (TS 31.103 7.1.2), and both // answer RES, CK and IK under tag DB. // An ISIM that gives no result is not the end of the attempt: the same - // card's USIM is asked, where 1.2.2 sent every challenge — - // no AKA in a real ISIM has run on this code (AGENTS.md §5). + // card's USIM is asked, where 1.2.2 sent every challenge. std::optional Authenticate(std::span rand16, std::span autn16) { std::string what; auto result = AkaIn(reg_.aid, rand16, autn16, what); From 3d702ec1f1c20f53d8eec1f3fdf4bf81bea90b3c Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Tue, 1 Dec 2026 15:51:21 +0100 Subject: [PATCH 2/7] messages, engine: the INVITE's sequence number, session interval and Min-SE are the dialog's BuildInvite wrote "CSeq: 1 INVITE", "Session-Expires: 1800;refresher=uac" and "Min-SE: 90" as fixed text, and the INVITE's CANCEL, its two ACKs and a PRACK's RAck wrote the 1 again. The three values are fields of the Dialog now, with those defaults, and nothing in the daemon sets them otherwise yet: every message it sends is byte for byte what it was. Tested: the suites (tests/Messages has an INVITE, its CANCEL and its ACKs for a dialog with other values). --- AGENTS.md | 4 +++- interfaces/Imsd-Engine.cppm | 2 +- interfaces/Imsd-Messages.cppm | 25 ++++++++++++++++--------- tests/Messages/main.cpp | 18 +++++++++++++++++- 4 files changed, 37 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 0e2a42c..4c7fadc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -358,7 +358,9 @@ What the suites pin: variants (a Security-Client for another offer among them; the two REGISTERs of an identity an ISIM holds, byte for byte the pinned ones with the card's names for the derived ones, and `RuriFor` at an - ISIM's home domain), the in-dialog + ISIM's home domain; the INVITE, its CANCEL and its two ACKs for a dialog + whose sequence number, session interval and `Min-SE` are not 1, 1800 + and 90), the in-dialog requests, the ACKs, the CANCEL and `BuildResponse200` by their lines, `BuildInviteResponse` by the lines of one 180 and by a 486 without a Record-Route (`tests/Engine` checks the diff --git a/interfaces/Imsd-Engine.cppm b/interfaces/Imsd-Engine.cppm index 17ff177..9c6aad1 100644 --- a/interfaces/Imsd-Engine.cppm +++ b/interfaces/Imsd-Engine.cppm @@ -617,7 +617,7 @@ export namespace imsd::engine { if (rseq && require.contains("100rel") && !pracked_.contains(std::string(*rseq))) { pracked_.insert(std::string(*rseq)); std::array extra = { - std::format("RAck: {} 1 INVITE", *rseq)}; + std::format("RAck: {} {} INVITE", *rseq, d_.invCseq)}; a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "PRACK", nextCseq_, rng_.Token(20), extra))); nextCseq_++; } diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index 5500ed1..a9d1285 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -5,7 +5,7 @@ Imsd:Messages — the SIP request/response text the engine puts on the wire. Every VoLTE message the daemon sends is assembled here from an explicit -context and the per-request variables (tags, branches, CSeq) so the builders +context and the per-request variables so the builders are pure functions with no hidden state: the engine owns the dialog bookkeeping and the transport owns the socket, this module only formats bytes. That makes each message byte-pinnable — tests/Messages compares a REGISTER pair and an INVITE @@ -333,7 +333,7 @@ export namespace imsd::msg { // ---- call dialog ---------------------------------------------------- - // The dialog identity + routing the engine accumulates for one call. + // A dialog as the engine keeps it. // For an outgoing call itag is our From tag and dialogTo is learned from // the responses; for an incoming call itag is the To tag we mint, // dialogTo is the caller's From, and both feed BuildInDialog identically @@ -348,6 +348,12 @@ export namespace imsd::msg { std::optional remoteTarget; // remote Contact URI std::string localUri; // our URI in this dialog: the UAS takes the // INVITE's To URI; empty = CallerId(c) (UAC) + int invCseq = 1; // our INVITE's sequence number: its CANCEL + // and its ACK carry it, a PRACK's RAck + // names it + int sessionExpires = 1800; // the session interval our INVITE asks for + // (RFC 4028 4), in seconds + int minSe = 90; // the Min-SE our INVITE carries (RFC 4028 5) }; // The identity we sign our own requests with: the registered public @@ -382,7 +388,8 @@ export namespace imsd::msg { } // INVITE with an AMR-WB SDP offer (passed in, built by Imsd:Sdp). MMTEL - // ICSI feature tags + sec-agree + session timers, exactly as imsd._send_invite. + // ICSI feature tags + sec-agree + session timers, as imsd._send_invite; the + // sequence number, the session interval and its minimum are the dialog's. std::string BuildInvite(const Context& c, const Dialog& d, std::string_view sdp, bool precond) { std::string supported = precond ? "100rel, timer, precondition" : "100rel, timer"; @@ -394,7 +401,7 @@ export namespace imsd::msg { std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("To: <{}>", d.ruri), std::format("Call-ID: {}", d.callid), - "CSeq: 1 INVITE", + std::format("CSeq: {} INVITE", d.invCseq), std::format("Contact: ;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)), "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER", std::format("Supported: {}", supported), @@ -406,8 +413,8 @@ export namespace imsd::msg { l.push_back(std::format("Security-Verify: {}", c.securityServer)); l.push_back("Proxy-Require: sec-agree"); l.push_back("Require: sec-agree"); - l.push_back("Session-Expires: 1800;refresher=uac"); - l.push_back("Min-SE: 90"); + l.push_back(std::format("Session-Expires: {};refresher=uac", d.sessionExpires)); + l.push_back(std::format("Min-SE: {}", d.minSe)); l.push_back("Content-Type: application/sdp"); l.push_back(std::format("Content-Length: {}", sdp.size())); l.push_back(""); @@ -454,7 +461,7 @@ export namespace imsd::msg { std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("To: {}", to), std::format("Call-ID: {}", d.callid), - "CSeq: 1 ACK", + std::format("CSeq: {} ACK", d.invCseq), "Content-Length: 0", }; return std::format("{}\r\n", detail::Join(l)); @@ -471,7 +478,7 @@ export namespace imsd::msg { std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("To: {}", toHeader), std::format("Call-ID: {}", d.callid), - "CSeq: 1 ACK", + std::format("CSeq: {} ACK", d.invCseq), "Content-Length: 0", }; return std::format("{}\r\n", detail::Join(l)); @@ -487,7 +494,7 @@ export namespace imsd::msg { std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("To: <{}>", d.ruri), std::format("Call-ID: {}", d.callid), - "CSeq: 1 CANCEL", + std::format("CSeq: {} CANCEL", d.invCseq), "Content-Length: 0", }; return std::format("{}\r\n", detail::Join(l)); diff --git a/tests/Messages/main.cpp b/tests/Messages/main.cpp index 36103f4..2916c7a 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -19,7 +19,9 @@ // CS fallback (observed live 2026-07-20); and the REGISTERs' Security-Client // carries the default offer's two mechanisms, where the Python stack offered // one cipher. The two REGISTERs once more on an identity an ISIM holds: the -// pinned ones with the card's names in place of the derived ones. Then the +// pinned ones with the card's names in place of the derived ones. The INVITE, +// its CANCEL and its ACKs once more for a dialog with another sequence number, +// session interval and Min-SE than the pinned 1, 1800 and 90. Then the // SMS over IP shapes: the // +g.3gpp.smsip Contact tag behind Context::smsOverIp, the MESSAGE carrying // an RP-DATA to the service centre and the one carrying an RP-ACK to the @@ -446,6 +448,20 @@ int main() { Check(ack.contains(std::format("Route: {}\r\n", c.route)), "non-2xx ACK registration route"); Check(ack.contains("To: ;tag=z\r\n"), "non-2xx ACK echoes response To"); } + { + // The INVITE's sequence number, session interval and Min-SE are the + // dialog's (1, 1800 and 90 in the pinned INVITE above), and its CANCEL + // and both ACKs carry the INVITE's number. + Dialog d; + d.ruri = "sip:x@y"; d.callid = "CID"; d.itag = "it"; d.invBranch = "ib9"; + d.invCseq = 2; d.sessionExpires = 3600; d.minSe = 2400; + std::string inv = BuildInvite(c, d, "v=0\r\n", false); + Check(inv.contains("\r\nCSeq: 2 INVITE\r\n"), "INVITE carries the dialog's sequence number"); + Check(inv.contains("\r\nSession-Expires: 3600;refresher=uac\r\nMin-SE: 2400\r\n"), "INVITE carries the dialog's session interval and Min-SE"); + Check(BuildCancel(c, d).contains("\r\nCSeq: 2 CANCEL\r\n"), "CANCEL copies the INVITE's number"); + Check(BuildAckNon2xx(c, d, ";tag=z").contains("\r\nCSeq: 2 ACK\r\n"), "non-2xx ACK copies the INVITE's number"); + Check(BuildAck2xx(c, d, "ab", ";tag=z").contains("\r\nCSeq: 2 ACK\r\n"), "2xx ACK copies the INVITE's number"); + } // ---- 200 OK response echoes the request's dialog headers, in order { From 00262130733496ae5d0085c2ec57d35d7d9c939d Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Tue, 1 Dec 2026 15:51:21 +0100 Subject: [PATCH 3/7] sip, engine: the retry of an INVITE refused 422 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit imsd asks for a session interval of 1800 s in a call's first INVITE. A 422 (Session Interval Too Small) is a server's answer to an interval below its minimum and carries that minimum in a Min-SE (RFC 4028 6); TS 24.229 5.1.2A.1.1 has a UE that supports RFC 4028 retry an INVITE so refused in accordance with RFC 4028 7.4. imsd announces "timer" and took a 422 for any other refusal: on a reporter's phone on AT&T's network each of the five calls of one boot ended "INVITE final 422" (AGENTS.md §13). The call machine now sends the INVITE again in the same call: a new transaction under the Call-ID, with the next sequence number, the 422's Min-SE and a session interval no smaller. AGENTS.md §7.6 has when it does not, and what becomes of an answer to an INVITE it has replaced. Tested: the suites, and the daemon of this commit on the workstation against a stand-in network that answers 422 (the fp6 journal's 2026-12-01-min-se-retry capture, bench/). --- AGENTS.md | 69 +++++++-- implementations/main.cpp | 5 +- interfaces/Imsd-Engine.cppm | 110 +++++++++++--- interfaces/Imsd-Sip.cppm | 16 ++- tests/Engine/main.cpp | 279 +++++++++++++++++++++++++++++++++++- tests/Sip/main.cpp | 19 ++- 6 files changed, 459 insertions(+), 39 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4c7fadc..b0912f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,7 +44,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`), the count of seconds a setting names (`WholeSeconds`), 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; `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-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, `MinSe` (the interval a `Min-SE` names), `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) and `RpCauseIsTemporary`, the causes of a submission after which imsd sends the segment again; 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` — the card's side of a registration: 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; since 1.2.3 the ISIM: the application of the slot in use out of the card status (`ParseIsimApp`, in whatever state the modem lists it), the SELECT and the two READ commands its identity files are read with, a card's answer (`ApduAnswer`: `90 00`, `91 XX` and `92 XX` are its normal endings; `HoldsRead` takes a read's data under `62 82` as well) and the command it asks for next (`ApduFollowUp`, for an answer without data: GET RESPONSE for `61 XX`, a command without data again for `6C XX`), the value a file holds (`ParseIsimValue`: the data object with tag `80`, the `FF` bytes at the end of its length cut, no blank and no byte outside printable ASCII) and `IsimIdentity`, the check of the three values — an `@` between two parts, a domain of labels of letters, digits and inner hyphens, 63 characters a label and 253 in all at most, a `sip:` at the start and more after it, the two identities 255 characters at most, no blank, no byte outside printable ASCII and no `"`, `\`, `<` or `>` — before they replace the derived names. | @@ -168,7 +168,7 @@ answers' reading, the follow-up, the value of a file and the check of the identity are `Imsd:Aka`'s, with tests; the shell's part ran against stand-ins on the workstation (§5). A call whose client flow is found dead before any response to its INVITE (1.2.4, §7.6) has its decisions in -`CallMachine`, with tests: which attempt is sent again, with which bytes, +`CallMachine`, with tests: which INVITE is sent again, with which bytes, and when the call ends instead. The shell's part (`MaybeResendInvite`: the dead flow closed without a FIN's exchange, the one connect, the policy's word on whether the old registration may be reconnected over) ran against a stand-in network on @@ -410,7 +410,9 @@ What the suites pin: 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, + headers, `MinSe` (the number a `Min-SE` begins with, zeros before it + aside, whatever parameter follows; none for no such header, for a value + that begins with no digit and for a number of more than nine digits), 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 @@ -442,9 +444,22 @@ What the suites pin: (reliable 18x/PRACK, 2xx ACK + media start, far-end hangup, CANCEL/answer races, busy/error finals, the terminating side's 100/180/200/486/487/488, G.711-only and AMR-NB gateway offers, ring timeout, BYE both ways, the - emergency chain, an attempt's INVITE with no response and no CANCEL yet - sent again over a flow the shell reopened, byte for byte and once per - attempt, and its call ended where the flow is lost (an emergency call's + emergency chain, an INVITE refused 422 sent again in the same call (the + Call-ID, the From and the To kept, the number after the refused + INVITE's or after a PRACK's sent since, a branch of its own, the + refusal's `Min-SE` as its `Min-SE` and a session interval no smaller; + an answer with the replaced INVITE's number dropped; the PRACK numbered + after the second INVITE and naming it, the ACKs with its number; the + second INVITE starting without the first's ringing state, PRACKed 18x, + early answer, route and target, and with a resend of its own; the + journal's line with the minimum and the refusal's `Reason`; not sent + again for a `Min-SE` no larger than the one sent, for none that is + read, after three, after a hang-up's CANCEL or after the answer, nor + for a refusal that is no 422; an emergency attempt's INVITE sent again + like any other, and its fallback counting anew), an INVITE with no + response and no CANCEL yet sent again over a flow the shell reopened, + byte for byte and once per INVITE, and its call ended where the flow is + lost (an emergency call's first attempt too), DTMF — sent to the leg on an active call that negotiated telephone-event, dropped with the reason before the answer, after the call, without the negotiation, for a character that is no tone or for a @@ -1982,12 +1997,14 @@ sent, emit this D-Bus state change, arm this deadline). States and reasons are t - Outgoing: INVITE with the SDP offer (AMR-WB + AMR + telephone-event by default; `CODECS` restricts and orders; `PRECOND=1` adds IR.92 preconditions), reliable 18x with PRACK, 2xx ACK and media start, CANCEL - before answer, BYE after. Busy and error finals end the call with - `refused-or-busy` or `error`. Where the client flow is found dead after + before answer, BYE after. Busy and error finals end the call, unless + the emergency chain or the session timer (both below) has another + INVITE follow. Where the client flow is found dead after an attempt's INVITE was sent and before any response to it (a 100 included) or a CANCEL of it, the shell closes the dead socket without a FIN's exchange, reopens the flow with one connect and the same INVITE - goes out again, once per attempt of the emergency chain, the setup + goes out again, once for each INVITE a call sends (an attempt of the + emergency chain's, or one sent again for a 422, below), the setup deadline running from then (`MaybeResendInvite`). No REGISTER goes first: the registration and its SAs stand (where a reg-event NOTIFY has ended the binding, §7.4, nothing is reopened), and TS 33.203 7.1 has a @@ -2054,6 +2071,33 @@ sent, emit this D-Bus state change, arm this deadline). States and reasons are t a plain INVITE answered `380 Alternative Service` with an emergency body is re-attempted as `urn:service:sos`. An attempt whose client flow is lost (above) ends the call there: no fallback follows it. +- Session timer (RFC 4028): the first INVITE of a dialog announces + `timer` and asks for a session interval of 1800 s with `refresher=uac` + and a `Min-SE` of 90. The shell hands a call every response on the + client flow to an INVITE under its Call-ID; of a call imsd places the + machine takes those whose sequence number is its current INVITE's + (`ResponseOf`) and drops the others. Where the current INVITE awaits + its final (no CANCEL of it out, no answer taken) and is answered `422` + with a `Min-SE` (what `imsd::sip::MinSe` reads of it: a number of up to + nine digits, zeros before it aside) above the one it carried, the + INVITE goes out again in the same call (TS 24.229 5.1.2A.1.1; RFC 4028 + 7.3, 7.4), at most three times under one Call-ID (`MinSeAgainMax`, + imsd's own bound): the Call-ID, the From with its tag and the To as + they were, a new branch and the 422's `Min-SE` as its `Min-SE` + (`CallMachine::AgainWithMinSe`). The session interval it asks for is + the one asked for before, or that `Min-SE` where the interval was + smaller. Its sequence number is the next the Call-ID has not carried: + RFC 4028 7.3 has "one higher than the previous", which imsd takes as + the one after the refused INVITE's; where a PRACK followed that INVITE + imsd takes the one after the last PRACK's instead. The setup deadline + runs anew from each INVITE. Any other 422 to the current INVITE is a + refusal like any other, to a call and to an attempt of the emergency + chain, whose fallback is a new dialog and starts at 1800 and 90 again. + What answers an INVITE the call has replaced is dropped with the + others: its 422 coming a second time is not acknowledged again. In a + call it places imsd asks to be the refresher and sends no session + refresh of its own (the call machine sends no UPDATE and no re-INVITE; + one from the far side is answered). - DTMF (`SendDtmf`): the tones go out as RFC 4733 telephone-event packets on the call's RTP stream, at the payload type the SDP negotiated for the codec's clock (`MediaLeg::dtmfPt`: the answer's for an outgoing call, the @@ -2246,6 +2290,11 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: - `call X: the client flow died before any response to the INVITE; reopening it` and, when the connect succeeded, `call X: the INVITE again over the reopened flow` (§7.6); `call X ended: error — the client flow died before any response to the INVITE` where the call ends instead. +- `call X: INVITE final 422, Min-SE N — the INVITE again with Session-Expires S` when an INVITE goes out again + for a 422 (§7.6). A 422 that is a refusal like any other has what was read of it in the line it leaves, as + `INVITE final 422, Min-SE N` or `INVITE final 422, no Min-SE read`: the call's `ended:` line, or an + emergency attempt's `— retrying as plain INVITE of the digits`. In each of the three a `Reason` header of + the 422 follows the `Min-SE` part (`…, Reason: …`). - `sleep is held off while the call lasts (logind's inhibitor)` when the calls table's first call has its lock and `sleep is no longer held off (no call)` when that lock is released, the table's last call gone @@ -3642,7 +3691,7 @@ the related code. Service-Route, with a `tel:` P-Associated-URI and a `sip:` one at `one.att.net`, and a binding of `expires=2112`; two refreshes within the hour. Each of the five calls placed in that boot ended `INVITE - final 422`. + final 422` (§7.6). - **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 diff --git a/implementations/main.cpp b/implementations/main.cpp index 455a8e9..e8bb4ba 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -2957,8 +2957,9 @@ private: } // A client flow found dead under an outgoing call whose INVITE has had - // no response and no CANCEL (CallMachine::Unanswered) is reopened once - // per attempt and the INVITE sent again: a flow the network had + // no response and no CANCEL (CallMachine::Unanswered) is reopened, once + // for each INVITE the call sends, and that INVITE sent again: a flow the + // network had // forgotten is reset at the first bytes sent on it, and those may be a // call's. No REGISTER goes first: the registration and its SAs stand // (not where the network has ended the binding: RegRecovery's diff --git a/interfaces/Imsd-Engine.cppm b/interfaces/Imsd-Engine.cppm index 9c6aad1..07b8394 100644 --- a/interfaces/Imsd-Engine.cppm +++ b/interfaces/Imsd-Engine.cppm @@ -17,7 +17,8 @@ That keeps the whole call FSM — PRACK on reliable 18x, ACK of 2xx vs non-2xx finals, CANCEL/answer races, remote BYE, media-plane far-end-hangup, the emergency attempt chain (urn:service:sos first for a classified number, one fallback to a plain INVITE of the digits; a 380 Alternative Service upgrade -the other way), the terminating (UAS) side: 100/180 on an inbound INVITE, +the other way), an INVITE refused 422 sent again with the Min-SE the 422 +names (RFC 4028 7.3, 7.4), the terminating (UAS) side: 100/180 on an inbound INVITE, 200-with-answer on Accept, 486 reject, the remote-CANCEL 200+487 pair — and DTMF, which reaches the media leg only on an active call whose SDP negotiated telephone-event, as the tones a keypad has — @@ -417,6 +418,10 @@ export namespace imsd::engine { // imsd.py INVITE_TIMEOUT / CANCEL_487_TIMEOUT constants. inline constexpr double InviteTimeout = 90.0; inline constexpr double Cancel487Timeout = 10.0; + // How often an INVITE goes out again for a 422 under one Call-ID + // (CallMachine::OnInviteResponse). RFC 4028 sets no number: this is + // imsd's bound for a path that names a larger minimum every time. + inline constexpr int MinSeAgainMax = 3; // How long an unanswered incoming call may ring before we 480 it — a // safety net behind the network's own CANCEL, so generous. inline constexpr double IncomingRingTimeout = 120.0; @@ -494,22 +499,23 @@ export namespace imsd::engine { return a; } - // The current outgoing attempt has sent its INVITE and has had no - // response to it, not a 100 either, and no CANCEL has followed it. + // An outgoing call's current INVITE has been sent and has had no + // response, not a 100 either, and no CANCEL has followed it. // The shell asks when it finds the client flow dead under a call: a // flow the network had forgotten is reset at the first bytes sent // on it, and those may be this INVITE. bool Unanswered() const { return state_ == CallState::Dialing && !inviteOut_.empty() && !answered_ && !cancelled_; } - // … and the attempt has not been sent again yet. + // … and that INVITE has not gone out a second time over a reopened + // flow. bool ResendDue() const { return Unanswered() && !resent_; } - // The shell reopened the flow under an attempt whose resend is due: + // The shell reopened the flow under an INVITE whose resend is due: // the same INVITE again, byte for byte (the same branch: RFC 3261 // 17.2.3 has a server that did receive the first match this one to // its transaction), and the setup deadline from now. Once per - // attempt. + // INVITE: one that AgainWithMinSe sends has a resend of its own. std::vector OnFlowReopened() { std::vector a; if (!ResendDue()) return a; @@ -520,7 +526,7 @@ export namespace imsd::engine { return a; } - // The flow under an unanswered attempt is dead and stays so (it + // The flow under an unanswered INVITE is dead and stays so (it // could not be reopened, or died again after the resend): the call // ends here, an emergency call's first attempt too, with nothing to // send a CANCEL on and no flow for a fallback attempt. @@ -597,11 +603,17 @@ export namespace imsd::engine { return a; } - // A response to our INVITE (the shell already matched Call-ID + CSeq). + // A response to an INVITE of ours (the shell has matched the Call-ID + // and the method). std::vector OnInviteResponse(std::string_view msg) { std::vector a; if (direction_ == Direction::Incoming) return a; // a UAS has no INVITE transaction of its own + // An answer to an INVITE this call has since sent again under + // its Call-ID (AgainWithMinSe) is the replaced transaction's: + // the shell matches the Call-ID and the method, the sequence + // number is told apart here. + if (!imsd::sip::ResponseOf(msg, d_.callid, std::format("{} INVITE", d_.invCseq))) return a; AbsorbDialog(msg); auto st = imsd::sip::Status(msg); if (!st) return a; @@ -650,7 +662,24 @@ export namespace imsd::engine { } // non-2xx final a.push_back(Send(imsd::msg::BuildAckNon2xx(ctx_, d_, std::string(imsd::sip::Header(msg, "To").value_or(""))))); - std::string fin = WithReason(std::format("INVITE final {}", code), msg); + std::string fin = std::format("INVITE final {}", code); + if (code == 422) { + // Session Interval Too Small: by RFC 4028 6 it carries the + // server's minimum in a Min-SE, and TS 24.229 5.1.2A.1.1 has + // a UE retry an INVITE so refused by RFC 4028 7.4. Only an + // INVITE that awaits its final (no CANCEL out, no answer + // taken), not for a Min-SE no larger than the one the + // refused INVITE carried, and not more than MinSeAgainMax + // times under one Call-ID. + const auto minSe = imsd::sip::MinSe(msg); + fin += minSe ? std::format(", Min-SE {}", *minSe) : std::string(", no Min-SE read"); + const bool awaited = !cancelled_ && (state_ == CallState::Dialing || state_ == CallState::Ringing); + if (minSe && awaited && *minSe > d_.minSe && minSeAgain_ < MinSeAgainMax) { + Append(a, AgainWithMinSe(*minSe, WithReason(fin, msg))); + return a; + } + } + fin = WithReason(fin, msg); if (auto sos = FallbackTo(code, msg)) { Append(a, Retry(*sos, fin)); return a; @@ -868,12 +897,13 @@ export namespace imsd::engine { bool sosTried_ = false; bool plainTried_ = false; bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline - // The current outgoing attempt's INVITE as sent, whether any response - // to it has come, and whether it went out a second time over a - // reopened flow (OnFlowReopened). + // The current INVITE as sent, whether any response to it has come, + // and whether it went out a second time over a reopened flow + // (OnFlowReopened). std::string inviteOut_; bool answered_ = false; bool resent_ = false; + int minSeAgain_ = 0; // INVITEs sent again for a 422 under this Call-ID std::set pracked_; std::string answerSdp_; std::optional dtmfPt_; // the running leg's telephone-event pt, set at media start @@ -889,23 +919,65 @@ export namespace imsd::engine { d_.callid = std::format("{}@{}", rng_.Token(20), ctx_.local); d_.itag = rng_.Token(10); d_.invBranch = rng_.Token(20); - nextCseq_ = 2; - pracked_.clear(); - answerSdp_.clear(); + NewTransaction(); cancelled_ = false; userCancelled_ = false; + minSeAgain_ = 0; + } + + // What each INVITE of an outgoing call starts from, a dialog's first + // (ResetDialog) and one sent again in it (AgainWithMinSe): the + // requests within the dialog numbered after it, no 18x PRACKed, no + // answer, no response to it and no resend of it. + void NewTransaction() { + nextCseq_ = d_.invCseq + 1; + pracked_.clear(); + answerSdp_.clear(); answered_ = false; resent_ = false; } + // The INVITE a 422 refused, again (RFC 4028 7.3, 7.4): a new + // transaction of the same call. Its dialog keeps the request-URI, + // the Call-ID and our tag, takes the next sequence number the + // Call-ID has not carried (7.3 has "one higher than the previous": + // the one after the refused INVITE's, or, which is ours, the one + // after the last PRACK's where a PRACK followed that INVITE), a + // branch of its own and `minSe` as its Min-SE. Its session interval + // is the refused INVITE's, or `minSe` where that was smaller. What + // the refused transaction left (the refusal's To tag, a route, a + // target, and what NewTransaction clears) is not the new one's. + // Whether it is sent is the caller's (OnInviteResponse). + std::vector AgainWithMinSe(int minSe, std::string_view why) { + imsd::msg::Dialog next; + next.ruri = d_.ruri; + next.callid = d_.callid; + next.itag = d_.itag; + next.invBranch = rng_.Token(20); + next.invCseq = nextCseq_; + next.minSe = minSe; + next.sessionExpires = std::max(d_.sessionExpires, minSe); + d_ = std::move(next); + NewTransaction(); + minSeAgain_++; + std::vector a; + a.push_back(LogAct(std::format("call {}: {} — the INVITE again with Session-Expires {}", uni_, why, d_.sessionExpires))); + if (state_ != CallState::Dialing) { + state_ = CallState::Dialing; + a.push_back(StateAct("outgoing")); + } + Append(a, Start()); + return a; + } + // The emergency fallback chain — where the next attempt (if any) // points. `msg` may be empty (deadline paths). - // - a sos INVITE that fails for any reason other than the user - // hanging up, its own send failing at the Dial (Fail) or the - // client flow lost under it (OnFlowLost: there is nothing to send - // on) is re-attempted as a plain INVITE of the dialled digits: the + // - asked after a sos attempt, it answers the dialled digits as a + // plain INVITE, unless the user hung up or the digits were tried + // before that attempt (the 380's upgrade below): the // pre-emergency-support behavior, so classification can only improve // on the status quo, never block a call the old code would have placed. + // An end of a sos attempt that does not ask here brings no fallback. // - a plain INVITE answered 380 Alternative Service whose body // names emergency (TS 24.229 5.1.6: the network classified a // number we didn't) is re-attempted as urn:service:sos. A 380 diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index 0f5a07a..c672693 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -6,8 +6,8 @@ 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 as text. A header is asked for by its long name and +status codes, the granted registration lifetime, the interval a Min-SE +names), which keeps every message 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 @@ -228,6 +228,18 @@ export namespace imsd::sip { return LeadingDigits(*v); } + // The interval a message's Min-SE names (RFC 4028 5: delta-seconds, + // then parameters), in seconds: the number its value's leading digits + // spell, zeros before it aside. nullopt when the header is absent, its + // value begins with no digit, or the number has more than nine digits. + std::optional MinSe(std::string_view msg) { + auto v = Header(msg, "Min-SE"); + if (!v) return std::nullopt; + const auto n = LeadingDigits(*v); + if (!n || *n > 999'999'999) return std::nullopt; + return static_cast(*n); + } + // A refused final for the journal: its status line, then the headers // that say who refused and for how long — Retry-After (RFC 3261 20.33), // Warning (20.43: the node's own words), Reason (RFC 3326), Server diff --git a/tests/Engine/main.cpp b/tests/Engine/main.cpp index 1ee15da..c98ee31 100644 --- a/tests/Engine/main.cpp +++ b/tests/Engine/main.cpp @@ -4,7 +4,9 @@ // Imsd:Engine unit tests — the call state machine driven through recorded // network dialogs. Outgoing: reliable-18x PRACK, 2xx ACK + media start, // media-plane far-end hangup, local hang-up (CANCEL before answer, BYE -// after), the CANCEL/answer race, and busy/error finals. Incoming: 100+180 +// after), the CANCEL/answer race, busy/error finals, and an INVITE refused +// 422 sent again with the Min-SE the refusal names (the same call, the next +// sequence number; when it is not sent again). Incoming: 100+180 // on the INVITE (reliable when the caller requires 100rel), Accept -> 200 // with the SDP answer at the offer's payload types + media, ACK silence, // reject -> 486, remote CANCEL -> 200+487, unusable offer -> 488 (naming @@ -96,8 +98,9 @@ namespace { return nullptr; } - // Build a response with the machine's own Call-ID (so dialog matching in a - // real shell would hold; the reducer itself doesn't re-check). + // Build a response with the machine's own Call-ID and its INVITE's first + // sequence number: the shell matches the Call-ID and the method, the + // reducer the transaction (Cseq below gives a response another number). std::string R183(std::string_view callid) { return std::format( "SIP/2.0 183 Session Progress\r\n" @@ -154,6 +157,30 @@ namespace { code, text, callid); } + // A 422 to the INVITE numbered `cseq`; `minSe` is its Min-SE header's + // value, empty for a 422 without the header. + std::string R422(std::string_view callid, int cseq, std::string_view minSe) { + return std::format( + "SIP/2.0 422 Session Interval Too Small\r\n" + "Via: SIP/2.0/TCP [2001:db8::db43]:45061;branch=z9hG4bKx\r\n" + "From: ;tag=it\r\n" + "To: ;tag=refused1\r\n" + "Call-ID: {}\r\nCSeq: {} INVITE\r\n{}Content-Length: 0\r\n\r\n", + callid, cseq, minSe.empty() ? std::string() : std::format("Min-SE: {}\r\n", minSe)); + } + // One of the responses above as an answer to the INVITE numbered `n`. + std::string Cseq(std::string msg, int n) { + const std::string_view one = "CSeq: 1 INVITE\r\n"; + msg.replace(msg.find(one), one.size(), std::format("CSeq: {} INVITE\r\n", n)); + return msg; + } + // The Log action whose text holds `part`. + const Action* Logged(const std::vector& a, std::string_view part) { + for (const auto& x : a) + if (x.type == Action::Type::Log && x.text.contains(part)) return &x; + return nullptr; + } + // First SendResponse whose text starts with `prefix`. const Action* Responded(const std::vector& a, std::string_view prefix) { for (const auto& x : a) @@ -473,7 +500,7 @@ int main() { } // ---- the client flow dies before any response to the INVITE: the shell - // reopens it and the same INVITE goes out again, once per attempt + // reopens it and the same INVITE goes out again, once per INVITE { imsd::util::Rng rng(16); CallMachine m(c, rng, "ims-call-6b", "1233", 50004, false); @@ -487,7 +514,7 @@ int main() { const Action* dl = Find(again, Action::Type::SetDeadline); Check(dl && dl->seconds == imsd::engine::InviteTimeout, "the resend arms the setup deadline anew"); Check(m.State() == CallState::Dialing && !m.Terminated(), "still dialing after the resend"); - Check(m.Unanswered() && !m.ResendDue(), "one resend per attempt"); + Check(m.Unanswered() && !m.ResendDue(), "one resend per INVITE"); Check(m.OnFlowReopened().empty(), "a second reopen sends nothing"); auto lost = m.OnFlowLost(); const Action* t = Find(lost, Action::Type::State); @@ -969,6 +996,248 @@ int main() { Check(m.Terminated(), "terminated when the chain is exhausted"); } + // ---- a 422 that names a larger Min-SE: the INVITE again in the same + // call (RFC 4028 7.3, 7.4; TS 24.229 5.1.2A.1.1), then answered + { + imsd::util::Rng rng(61); + CallMachine m(c, rng, "ims-call-40", "1233", 50004, false); + auto start = m.Start(); + const Action* inv1 = Sent(start, "INVITE "); + Check(inv1 && inv1->text.contains("\r\nCSeq: 1 INVITE\r\n") && inv1->text.contains("\r\nSession-Expires: 1800;refresher=uac\r\nMin-SE: 90\r\n"), "the first INVITE asks for 1800 s with a Min-SE of 90"); + const std::string id = m.CallId(); + m.OnInviteResponse(Final(id, 100, "Trying")); + auto a = m.OnInviteResponse(R422(id, 1, "3600")); + const Action* ack = Sent(a, "ACK "); + Check(ack && ack->text.contains("\r\nCSeq: 1 ACK\r\n") && ack->text.contains("\r\nTo: ;tag=refused1\r\n"), "the 422 is ACKed in its own transaction, with its To"); + Check(ack && inv1 && imsd::sip::Header(ack->text, "Via") == imsd::sip::Header(inv1->text, "Via"), "... over the refused INVITE's branch"); + const Action* inv2 = Sent(a, "INVITE "); + Check(inv2 && m.CallId() == id && inv2->text.contains(std::format("\r\nCall-ID: {}\r\n", id)), "the INVITE goes out again under the same Call-ID"); + Check(inv2 && inv2->text.contains("\r\nCSeq: 2 INVITE\r\n"), "... with the next sequence number"); + Check(inv2 && inv1 && inv2->text.substr(0, inv2->text.find("\r\n")) == inv1->text.substr(0, inv1->text.find("\r\n")), "... the same request line"); + Check(inv2 && inv1 && imsd::sip::Header(inv2->text, "From") == imsd::sip::Header(inv1->text, "From"), "... the same From and tag"); + Check(inv2 && inv1 && imsd::sip::Header(inv2->text, "To") == imsd::sip::Header(inv1->text, "To"), "... the same To"); + Check(inv2 && inv1 && imsd::sip::Header(inv2->text, "Via") != imsd::sip::Header(inv1->text, "Via"), "... a branch of its own"); + Check(inv2 && inv2->text.contains("\r\nSession-Expires: 3600;refresher=uac\r\nMin-SE: 3600\r\n"), "... the 422's Min-SE as its Min-SE and as its session interval"); + const Action* log = Find(a, Action::Type::Log); + Check(log && log->text == "call ims-call-40: INVITE final 422, Min-SE 3600 — the INVITE again with Session-Expires 3600", "the journal names the minimum and the interval sent"); + Check(Has(a, Action::Type::SetDeadline) && !Has(a, Action::Type::State) && m.State() == CallState::Dialing && !m.Terminated(), "the call goes on dialing, its timeout armed again, no state announced"); + Check(m.Unanswered() && m.ResendDue(), "the INVITE sent again has had no response and has a resend of its own"); + // an answer of the replaced transaction is not this one's + Check(m.OnInviteResponse(R422(id, 1, "7200")).empty() && m.OnInviteResponse(R200(id)).empty() && m.OnInviteResponse(R183(id)).empty() && m.State() == CallState::Dialing && m.Unanswered(), "an answer with the replaced INVITE's number is dropped"); + // the second INVITE's own answers + auto a183 = m.OnInviteResponse(Cseq(R183(id), 2)); + const Action* prack = Sent(a183, "PRACK "); + Check(prack && prack->text.contains("RAck: 1 2 INVITE\r\n") && prack->text.contains("CSeq: 3 PRACK\r\n"), "the PRACK names the second INVITE and takes the number after it"); + Check(prack && prack->text.contains("\r\nTo: ;tag=remote7\r\n"), "... in the dialog the second INVITE's 183 made"); + auto a200 = m.OnInviteResponse(Cseq(R200(id), 2)); + const Action* ack2 = Sent(a200, "ACK "); + Check(ack2 && ack2->text.contains("\r\nCSeq: 2 ACK\r\n") && Has(a200, Action::Type::StartMedia) && m.State() == CallState::Active, "the second INVITE's 200 is ACKed with its number and the call is active"); + } + + // ---- the flow dies under the INVITE sent again: the shell reopens it + // and that INVITE goes out once more, byte for byte; a flow that + // dies again ends the call + { + imsd::util::Rng rng(79); + CallMachine m(c, rng, "ims-call-53", "1233", 50004, false); + auto start = m.Start(); + const Action* inv1 = Sent(start, "INVITE "); + auto a = m.OnInviteResponse(R422(m.CallId(), 1, "3600")); + const Action* inv2 = Sent(a, "INVITE "); + auto again = m.OnFlowReopened(); + const Action* resent = Sent(again, "INVITE "); + Check(inv1 && inv2 && resent && resent->text == inv2->text && resent->text != inv1->text, "the INVITE sent again for a 422 is the one resent over a reopened flow, byte for byte"); + Check(m.Unanswered() && !m.ResendDue() && m.OnFlowReopened().empty(), "... once"); + auto lost = m.OnFlowLost(); + const Action* t = Find(lost, Action::Type::State); + Check(t && t->reason == "error" && m.Terminated() && Sent(lost, "INVITE ") == nullptr, "... and a flow that dies again ends its call with error"); + } + + // ---- a hang-up while the INVITE sent again awaits its final cancels + // that INVITE + { + imsd::util::Rng rng(80); + CallMachine m(c, rng, "ims-call-54", "1233", 50004, false); + m.Start(); + const std::string id = m.CallId(); + auto a = m.OnInviteResponse(R422(id, 1, "3600")); + const Action* inv2 = Sent(a, "INVITE "); + auto h = m.OnHangup(); + const Action* cancel = Sent(h, "CANCEL "); + Check(inv2 && cancel && cancel->text.contains("\r\nCSeq: 2 CANCEL\r\n") && imsd::sip::Header(cancel->text, "Via") == imsd::sip::Header(inv2->text, "Via"), "a hang-up after the INVITE was sent again: a CANCEL with the second INVITE's number and branch"); + auto e = m.OnInviteResponse(Cseq(Final(id, 487, "Request Terminated"), 2)); + const Action* t = Find(e, Action::Type::State); + Check(Sent(e, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "local-hangup", "... and its 487 ends the call as a hang-up"); + } + + // ---- what the refused transaction left is not the second INVITE's: a + // 183 before the 422 (the ringing state, a PRACKed RSeq, an early + // answer), the refusal's Record-Route and Contact, a resend used + { + auto refused = [&](CallMachine& m) { + m.Start(); + m.OnFlowReopened(); // the first INVITE's one resend + m.OnInviteResponse(R183(m.CallId())); // ringing; RSeq 1 PRACKed; an answer on port 6004 + std::string r = R422(m.CallId(), 1, "3600"); + r.replace(r.find("Content-Length"), 0, "Record-Route: \r\nContact: \r\nReason: Q.850;cause=31\r\n"); + return m.OnInviteResponse(r); + }; + imsd::util::Rng rng(74); + CallMachine m(c, rng, "ims-call-48", "1233", 50004, false); + auto a = refused(m); + const std::string id = m.CallId(); + const Action* st = Find(a, Action::Type::State); + Check(Sent(a, "INVITE ") != nullptr && m.State() == CallState::Dialing && st && st->state == "dialing" && st->reason == "outgoing", "a 422 after a 183: the INVITE again, and the call announced as dialing again"); + Check(Logged(a, "call ims-call-48: INVITE final 422, Min-SE 3600, Reason: Q.850;cause=31 — the INVITE again with Session-Expires 3600") != nullptr, "the refusal's Reason is in the line of the INVITE sent again"); + Check(m.Unanswered() && m.ResendDue(), "the second INVITE has a resend of its own although the first used one"); + const Action* inv = Sent(a, "INVITE "); + Check(inv && inv->text.contains("\r\nCSeq: 3 INVITE\r\n"), "after a PRACK numbered 2 the second INVITE takes 3"); + auto b183 = m.OnInviteResponse(Cseq(R183(id), 3)); + const Action* prack = Sent(b183, "PRACK "); + Check(prack && prack->text.contains("RAck: 1 3 INVITE\r\n") && prack->text.contains("CSeq: 4 PRACK\r\n"), "the second INVITE's 183 is PRACKed although the first's had the same RSeq"); + Check(prack && prack->text.starts_with("PRACK sip:termgw@[2001:db8::9]:5060 SIP/2.0"), "... to that 183's Contact"); + // a 200 that brings no route, no Contact and no answer finds none left over + imsd::util::Rng rng2(75); + CallMachine n(c, rng2, "ims-call-49", "1233", 50004, false); + refused(n); + auto a200 = n.OnInviteResponse(Cseq(Final(n.CallId(), 200, "OK"), 3)); + const Action* ack = Sent(a200, "ACK "); + Check(ack && ack->text.starts_with("ACK sip:1233;") && !ack->text.contains("2001:db8::bad") && !ack->text.contains("termgw"), "the ACK of a 200 without a Contact or a Record-Route goes to the request-URI: not to the refusal's Contact or the first 183's, not over the refusal's Record-Route"); + const Action* media = Find(a200, Action::Type::StartMedia); + Check(media && media->media.remotePort != 6004 && media->media.remoteIp.empty(), "the first INVITE's early answer is not the second's"); + } + + // ---- a Min-SE below the interval asked for: sent again with that + // Min-SE, the interval kept + { + imsd::util::Rng rng(62); + CallMachine m(c, rng, "ims-call-41", "1233", 50004, false); + m.Start(); + auto a = m.OnInviteResponse(R422(m.CallId(), 1, "900;x=y")); + const Action* inv2 = Sent(a, "INVITE "); + Check(inv2 && inv2->text.contains("\r\nSession-Expires: 1800;refresher=uac\r\nMin-SE: 900\r\n"), "a smaller Min-SE is carried and the interval of 1800 kept"); + Check(Logged(a, "INVITE final 422, Min-SE 900 — the INVITE again with Session-Expires 1800") != nullptr, "... and the journal says so"); + } + + // ---- a 422 the INVITE is not sent again for: the call ends, and the + // journal has what the refusal named + { + // the Min-SE the refused INVITE carried, named again + imsd::util::Rng rng(63); + CallMachine m(c, rng, "ims-call-42", "1233", 50004, false); + m.Start(); + const std::string id = m.CallId(); + m.OnInviteResponse(R422(id, 1, "3600")); + auto a = m.OnInviteResponse(R422(id, 2, "3600")); + const Action* ack = Sent(a, "ACK "); + Check(ack && ack->text.contains("\r\nCSeq: 2 ACK\r\n"), "the second 422 is ACKed with the second INVITE's number"); + const Action* t = Find(a, Action::Type::State); + Check(Sent(a, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "error", "a 422 that names the Min-SE just sent ends the call"); + Check(Logged(a, "call ims-call-42 ended: error — INVITE final 422, Min-SE 3600") != nullptr, "... with the minimum in the journal"); + // none, one that begins with no digit, one of ten digits, the default, zero + int n = 0; + for (std::string_view v : {"", "soon", "1000000000", "90", "0"}) { + imsd::util::Rng r2(64 + n); + CallMachine k(c, r2, "ims-call-43", "1233", 50004, false); + k.Start(); + auto b = k.OnInviteResponse(R422(k.CallId(), 1, v)); + const std::string what = v.empty() ? std::string("a 422 without a Min-SE") : std::format("a 422 with Min-SE '{}'", v); + Check(Sent(b, "ACK ") != nullptr && Sent(b, "INVITE ") == nullptr && k.Terminated(), what + " ends the call"); + const bool read = v == "90" || v == "0"; + Check(Logged(b, read ? std::format("INVITE final 422, Min-SE {}", v) : std::string("INVITE final 422, no Min-SE read")) != nullptr, what + ": the journal has what was read"); + n++; + } + // a Reason on the refusal follows the Min-SE part + imsd::util::Rng r3(70); + CallMachine q(c, r3, "ims-call-44", "1233", 50004, false); + q.Start(); + std::string r = R422(q.CallId(), 1, ""); + r.replace(r.find("Content-Length"), 0, "Reason: Q.850;cause=31\r\n"); + Check(Logged(q.OnInviteResponse(r), "INVITE final 422, no Min-SE read, Reason: Q.850;cause=31") != nullptr, "a 422's Reason is kept in the journal line"); + } + + // ---- a network that names a larger minimum each time: three INVITEs + // sent again, then the call ends (MinSeAgainMax) + { + imsd::util::Rng rng(71); + CallMachine m(c, rng, "ims-call-45", "1233", 50004, false); + m.Start(); + const std::string id = m.CallId(); + int sent = 0; + for (int i = 1; i <= 3; i++) { + auto a = m.OnInviteResponse(R422(id, i, std::to_string(3600 * i))); + const Action* inv = Sent(a, "INVITE "); + if (inv && inv->text.contains(std::format("\r\nCSeq: {} INVITE\r\n", i + 1)) && inv->text.contains(std::format("\r\nSession-Expires: {};refresher=uac\r\nMin-SE: {}\r\n", 3600 * i, 3600 * i))) sent++; + } + Check(sent == 3 && !m.Terminated(), "three larger minimums in a row: the INVITE again each time, numbered 2, 3 and 4"); + auto last = m.OnInviteResponse(R422(id, 4, "14400")); + Check(Sent(last, "INVITE ") == nullptr && m.Terminated() && Logged(last, "INVITE final 422, Min-SE 14400") != nullptr, "the fourth ends the call"); + } + + // ---- a 422 after the answer: no INVITE again; the call ends + { + imsd::util::Rng rng(77); + CallMachine m(c, rng, "ims-call-51", "1233", 50004, false); + m.Start(); + m.OnInviteResponse(R200(m.CallId())); + auto a = m.OnInviteResponse(R422(m.CallId(), 1, "3600")); + const Action* t = Find(a, Action::Type::State); + Check(Sent(a, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "error" && Has(a, Action::Type::StopMedia), "a 422 after the answer: no INVITE again; the call ends and its media stops"); + } + + // ---- a 486 that carries a Min-SE is no 422: not sent again + { + imsd::util::Rng rng(78); + CallMachine m(c, rng, "ims-call-52", "1233", 50004, false); + m.Start(); + std::string busy = Final(m.CallId(), 486, "Busy Here"); + busy.replace(busy.find("Content-Length"), 0, "Min-SE: 3600\r\n"); + auto a = m.OnInviteResponse(busy); + Check(Sent(a, "INVITE ") == nullptr && Logged(a, "call ims-call-52 ended: refused-or-busy — INVITE final 486") != nullptr && Logged(a, "Min-SE") == nullptr, "a 486 that carries a Min-SE is no 422: no INVITE again, no Min-SE in its line"); + } + + // ---- a 422 after the call was cancelled ends it as a hang-up + { + imsd::util::Rng rng(72); + CallMachine m(c, rng, "ims-call-46", "1233", 50004, false); + m.Start(); + m.OnHangup(); + auto a = m.OnInviteResponse(R422(m.CallId(), 1, "3600")); + const Action* t = Find(a, Action::Type::State); + Check(Sent(a, "INVITE ") == nullptr && m.Terminated() && t && t->reason == "local-hangup", "a 422 that crosses the user's CANCEL: no INVITE again, a local hang-up"); + } + + // ---- an emergency call: the 422 is answered on the same attempt; a 422 + // the INVITE is not sent again for falls back like any other final + { + imsd::util::Rng rng(73); + CallMachine m(c, rng, "ims-call-47", "112", 50004, false, true); + m.Start(); + const std::string id = m.CallId(); + auto a = m.OnInviteResponse(R422(id, 1, "3600")); + const Action* sos2 = Sent(a, "INVITE "); + Check(sos2 && sos2->text.starts_with("INVITE urn:service:sos ") && sos2->text.contains("\r\nCSeq: 2 INVITE\r\n") && sos2->text.contains("\r\nMin-SE: 3600\r\n") && m.CallId() == id, "the emergency INVITE again with the Min-SE, still to urn:service:sos"); + auto b = m.OnInviteResponse(R422(id, 2, "3600")); + const Action* plain = Sent(b, "INVITE "); + Check(plain && plain->text.starts_with("INVITE sip:112;phone-context=") && m.CallId() != id && plain->text.contains("\r\nCSeq: 1 INVITE\r\n") && plain->text.contains("\r\nSession-Expires: 1800;refresher=uac\r\nMin-SE: 90\r\n"), "a 422 that ends the emergency attempt falls back to the digits: a new dialog, numbered and timed afresh"); + auto c2 = m.OnInviteResponse(R422(m.CallId(), 1, "3600")); + const Action* plain2 = Sent(c2, "INVITE "); + Check(plain2 && plain2->text.starts_with("INVITE sip:112;phone-context=") && plain2->text.contains("\r\nCSeq: 2 INVITE\r\n") && plain2->text.contains("\r\nMin-SE: 3600\r\n"), "... and the fallback's own 422 is answered in its turn"); + } + { + // the count of INVITEs sent again is the Call-ID's: after an emergency + // attempt that used all three, the fallback's starts at none + imsd::util::Rng rng(76); + CallMachine m(c, rng, "ims-call-50", "112", 50004, false, true); + m.Start(); + const std::string id = m.CallId(); + for (int i = 1; i <= 3; i++) m.OnInviteResponse(R422(id, i, std::to_string(3600 * i))); + auto b = m.OnInviteResponse(R422(id, 4, "14400")); + Check(m.CallId() != id && Sent(b, "INVITE ") != nullptr && Sent(b, "INVITE ")->text.starts_with("INVITE sip:112;phone-context="), "the fourth 422 of the emergency attempt: the fallback"); + auto d = m.OnInviteResponse(R422(m.CallId(), 1, "3600")); + Check(Sent(d, "INVITE ") != nullptr && Sent(d, "INVITE ")->text.contains("\r\nCSeq: 2 INVITE\r\n") && !m.Terminated(), "the fallback's first 422 is answered: its count starts at none"); + } + // ---- user hangup during the sos attempt kills the chain: 487 ends it { imsd::util::Rng rng(47); diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index d4471a7..9df0cee 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -9,7 +9,8 @@ // 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 +// RefusalSummary), the interval a 422's Min-SE names (MinSe), 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; @@ -405,6 +406,22 @@ int main() { 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"); } + // ---- MinSe (the smallest session interval a 422 names, RFC 4028 5, 6) + { + auto r422 = [](std::string_view line) { + return std::format("SIP/2.0 422 Session Interval Too Small\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;branch=z9hG4bKx\r\n{}Content-Length: 0\r\n\r\n", line); + }; + Check(MinSe(r422("Min-SE: 3600\r\n")) == 3600, "Min-SE read"); + Check(MinSe(r422("min-se: 0090 ;x=1\r\n")) == 90, "Min-SE: any case of the name, spaces, zeros before the number, a parameter after it"); + Check(MinSe(r422("Min-SE: 999999999\r\n")) == 999999999, "Min-SE of nine digits read"); + Check(MinSe(r422("Min-SE: 0000000090\r\n")) == 90, "zeros before the number are no digits of it: ten characters, the number 90"); + Check(MinSe(r422("Min-SE: 0\r\n")) == 0, "Min-SE of zero read as zero"); + Check(!MinSe(r422("")), "no Min-SE header: none"); + Check(!MinSe(r422("Min-SE: soon\r\n")) && !MinSe(r422("Min-SE: -90\r\n")) && !MinSe(r422("Min-SE:\r\n")), "Min-SE that begins with no digit: none"); + Check(!MinSe(r422("Min-SE: 1000000000\r\n")) && !MinSe(r422("Min-SE: 99999999999999999999\r\n")), "Min-SE of more than nine digits: none"); + Check(!MinSe(r422("Session-Expires: 3600\r\n")), "a Session-Expires is no Min-SE"); + } + // ---- RetryAfter / RefusalSummary (what a refused final is logged as) { std::string r503 = From 1eee41f0ed537b05c3709c6bc48074270b29530f Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Tue, 1 Dec 2026 14:39:57 +0100 Subject: [PATCH 4/7] imsd 1.2.6 --- implementations/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/implementations/main.cpp b/implementations/main.cpp index e8bb4ba..5a10859 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -56,7 +56,7 @@ import ImsdBus; namespace { // ---- static config (env-overridable, same knobs as imsd.py) --------------- -constexpr const char* Version = "1.2.5"; +constexpr const char* Version = "1.2.6"; constexpr const char* BusName = "net.catcrafts.IMS1"; constexpr const char* ObjPath = "/net/catcrafts/IMS1"; constexpr const char* Iface = "net.catcrafts.IMS1"; From 6d05aaed0dbc95ad0b35187bae6c91eb592705f1 Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 4 Dec 2026 23:20:38 +0100 Subject: [PATCH 5/7] imsd: a server port's answer finds its connection or socket when it is sent A request that came in on a server port (the protected ports' TCP listeners and UDP sockets) was answered through a closure that kept a descriptor's number: its connection's over TCP, a socket's over UDP. The daemon closes a connection's descriptor when the peer has ended the connection, and the kernel gives a closed descriptor's number out again. A call's later answers go through the closure of the call's latest request when the user answers or refuses or the ringing ends (the 200 of an Accept, a 486, a 480): they were written to that number, whatever had it by then, the connection of whoever had connected since among them. A closure now keeps the port its request came in on and the peer it came from, or which of the two UDP ports its answer leaves by. Over TCP an answer is written to the newest connection the daemon holds from that peer to that port, and is not sent where it holds none: the journal says so once in a run. Over UDP it leaves from the socket its port has at that moment, if it has one. Tested: the daemon of this commit on the workstation against a stand-in network that closes the connection its INVITE came on while the call rings and then connects from another host, from another port, from the same port to the daemon's other port or from the same port to the same one, and one that resets the connection right behind its INVITE and makes it again (the fp6 journal's 2026-12-04-pani-in-dialog capture, bench/); and on the dev phone on KPN, where it answered a call that came in and the two requests that a text to the phone's own number brings (the journal's 2026-12-04-imsd-1.2.7-range-on-dev-phone capture). --- AGENTS.md | 61 ++++++++++++++++++++++++++++- implementations/main.cpp | 83 ++++++++++++++++++++++++++++++++++------ 2 files changed, 132 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b0912f1..a0504b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -180,7 +180,11 @@ sleep (1.2.5, §7.10) is the shell's but for when the phone has to be awake (`WakeAt`) and the policy's wake after a local wait (`RegRecovery::WakeTime`), which are `Imsd:Engine`'s, with tests; §7.10 has what the shell does for it, and §5 what of that ran against -stand-ins on the workstation and what on the dev phone. SMS over IP +stand-ins on the workstation and what on the dev phone. Where an answer +goes that the server ports send (§12: the connection found by its port +and its peer, an answer that is not sent, the socket a datagram leaves +from) is the shell's (`ServerPorts`); §5 has what of it ran against a +stand-in network on the workstation and what on the dev phone. SMS over IP (1.2.0, §7.9) keeps in the shell, among others, the service centre's source (`SMSC=` over EF_SMSP, `LoadSmsParameters`), the three counters (TP-MR, RP-MR, the concatenation reference), their @@ -1309,6 +1313,46 @@ Rules: through a step's wait while a text is in flight, which is read from the code; the reg-event subscription's renewal on a network. +- Where an answer goes that the server ports send (§12) is the shell's + (`ServerPorts`), and no suite reaches it. On the workstation the daemon + ran against a stand-in network that sends it requests over TCP and UDP + and can close or reset a connection behind one (the fp6 journal's + `2026-12-04-pani-in-dialog` capture, `bench/bench-pani.sh`: the daemon + in dev mode, its card and modem reads answered by stand-ins, an + incoming call accepted on its bus). Where the network closed the + connection its INVITE had come on while the call rang, the 200 of the + Accept arrived on the connection the same peer had made again to the + same port, also where the network had reset the first right behind its + INVITE (that call's 100 and 180 did not arrive: the connection they + were written to had been reset); it was not sent, with the journal's + line, where the only new connection was another host's, another port's + of the same host, or the same peer's to the daemon's other port (the + release before, 1.2.6, wrote it on the other host's connection and on + the one to the other port; with another port of the same host it was + not run); and it arrived on the INVITE's own connection where the peer + made a second one to the other port while the call rang. Two requests + whose connections the network closed right behind them were not + answered, with one line. Over UDP five OPTIONS requests were answered + from the ports the release before answered them from; two of the five + had no `rport` in their Via and were answered at the port that Via + names. On the dev phone on KPN (2026-12-04; the fp6 journal's + `2026-12-04-imsd-1.2.7-range-on-dev-phone` capture: the daemon in the + packaged one's place, resuming its registration, and the SA pair's + packets read on the phone) the two requests that a text to the phone's + own number brings came in over UDP, and each 200 left from 45061 for + the P-CSCF's protected server port, which their Via names; the text + was delivered, and the network sent neither request again. A call + came in there over TCP, on a connection the P-CSCF had made to 45062 + and had sent two NOTIFYs on: the 200s to those, the call's 100, its + 180 and the 200 of the Accept left on that connection, and the 200 to + its BYE, which came over UDP, from 45061. Of what ran against the + stand-in network nothing else has been seen on a real one (a + connection closed or reset behind a request and an answer that is not + sent among it). + Not run: an answer given after the daemon has moved to another + address; a peer on a link-local or an IPv4 address; a connection that + ends in an error and is made again within one turn of the daemon's + loop. - `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, @@ -2295,6 +2339,9 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: `INVITE final 422, Min-SE N` or `INVITE final 422, no Min-SE read`: the call's `ended:` line, or an emergency attempt's `— retrying as plain INVITE of the digits`. In each of the three a `Reason` header of the 422 follows the `Min-SE` part (`…, Reason: …`). +- `an answer from port N to [address]:port is not sent: no connection from that peer to that port is held + (said once)` the first time in a run that an answer is given to the channel of a request that came in over + TCP and `ServerPorts` holds no connection from that request's peer to that port (§12). - `sleep is held off while the call lasts (logind's inhibitor)` when the calls table's first call has its lock and `sleep is no longer held off (no call)` when that lock is released, the table's last call gone @@ -3346,6 +3393,18 @@ only the imsd side of its bus choice. kernel drops an ESP packet no SA matches, and what an SA decapsulates passes the chain again, under the same rules as a packet that came without ESP. +- `ServerPorts` (the protected ports' TCP listeners and UDP sockets) + takes a request from whatever reaches it on the ims PDN (the entry on + short messages below). The channel of a request that came in there + over TCP is the newest connection `ServerPorts` holds from that + request's peer to the port it came in on; where it holds none, an + answer given to the channel is not sent (§7.8). A connection that has + ended in an error is held until `Poll` has read its end, and what is + written to it meanwhile is lost. Over UDP the channel is the socket + that the port the answer leaves by has when the answer is sent, if it + has one. A channel keeps no descriptor: the kernel gives a closed + descriptor's number out again, to a pipe, a file or the connection of + whoever connects next. - Short messages (§7.9): `Send` is behind `net.catcrafts.IMS1.Messaging` (an ungated `Send` would let any local account text from the subscriber's number); the journal names a delivered message's sender, size and diff --git a/implementations/main.cpp b/implementations/main.cpp index 5a10859..95e8e0d 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -435,6 +435,30 @@ int PortOf(const sockaddr_storage& ss) { return ss.ss_family == AF_INET6 ? ntohs(reinterpret_cast(&ss)->sin6_port) : ntohs(reinterpret_cast(&ss)->sin_port); } +// The host a socket address names, as text. +std::string HostOf(const sockaddr_storage& ss) { + char buf[INET6_ADDRSTRLEN] = {}; + if (ss.ss_family == AF_INET6) inet_ntop(AF_INET6, &reinterpret_cast(&ss)->sin6_addr, buf, sizeof buf); + else inet_ntop(AF_INET, &reinterpret_cast(&ss)->sin_addr, buf, sizeof buf); + return buf; +} + +// Whether two socket addresses name the same host and port: for IPv6 the +// scope too (a link-local address is a host of one link). One that names +// none is the same as nothing, another such one included. +bool SameEnd(const sockaddr_storage& a, const sockaddr_storage& b) { + if (a.ss_family == AF_UNSPEC || a.ss_family != b.ss_family || PortOf(a) != PortOf(b) || HostOf(a) != HostOf(b)) return false; + return a.ss_family != AF_INET6 || + reinterpret_cast(&a)->sin6_scope_id == reinterpret_cast(&b)->sin6_scope_id; +} + +// A socket's own name (getsockname); all zeros where that fails. +sockaddr_storage NameOf(int fd) { + sockaddr_storage ss{}; socklen_t l = sizeof ss; + if (getsockname(fd, reinterpret_cast(&ss), &l) != 0) ss = {}; + return ss; +} + // ---- SIP over the protected TCP flow -------------------------------------- enum class Transport { Tcp, Udp }; constexpr std::string_view TransportName(Transport t) { return t == Transport::Udp ? "UDP" : "TCP"; } @@ -753,7 +777,7 @@ public: if (bind(us, reinterpret_cast(&a), l) == 0) { fcntl(us, F_SETFL, O_NONBLOCK); udp_.push_back(us); - if (port == PortUc) udpUc_ = us; + (port == PortUc ? udpUc_ : udpUs_) = us; } else { close(us); } } Log(std::format("listening on protected port {} (TCP+UDP)", port)); @@ -764,10 +788,11 @@ public: std::vector out; for (int ls : listeners_) { for (;;) { - int c = accept(ls, nullptr, nullptr); + sockaddr_storage peer{}; socklen_t pl = sizeof peer; + int c = accept(ls, reinterpret_cast(&peer), &pl); if (c < 0) break; fcntl(c, F_SETFL, O_NONBLOCK); - conns_.push_back({c, {}}); + conns_.push_back({c, {}, PortOf(NameOf(c)), peer}); } } for (int us : udp_) { @@ -827,8 +852,14 @@ public: htons(static_cast(*vp)); if (udpUc_ >= 0) rs = udpUc_; } - auto reply = [rs, s, sll](const std::string& r) mutable { - sendto(rs, r.data(), r.size(), 0, reinterpret_cast(&s), sll); + // The closure keeps which of the two ports the answer + // leaves by, not the socket's descriptor: CloseAll closes + // that, and the kernel gives a closed descriptor's number + // out again. + auto reply = [this, uc = rs == udpUc_, s, sll](const std::string& r) mutable { + const int from = uc ? udpUc_ : udpUs_; + if (from < 0) return; + sendto(from, 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)); @@ -850,9 +881,18 @@ public: } while (auto m = it->fb.TryExtract()) { if (!imsd::sip::Status(*m).has_value()) { - int fd = it->fd; - out.push_back({*m, [fd](const std::string& r) { - (void)!write(fd, r.data(), r.size()); + // What is sent through this closure is written to the + // newest connection held from this request's peer to the + // port the request came in on, and is not sent where none + // is held. The closure keeps the port and the peer, not + // the descriptor: Poll closes that when the peer has ended + // the connection, and the kernel gives a closed + // descriptor's number out again, to a pipe, a file or the + // connection of whoever connects next. + out.push_back({*m, [this, port = it->port, peer = it->peer](const std::string& r) { + const Conn* c = Find(port, peer); + if (!c) { Gone(port, peer); return; } + (void)!write(c->fd, r.data(), r.size()); }}); } } @@ -866,11 +906,32 @@ public: for (int f : udp_) close(f); for (auto& c : conns_) close(c.fd); listeners_.clear(); udp_.clear(); conns_.clear(); - udpUc_ = -1; + udpUc_ = udpUs_ = -1; } private: - struct Conn { int fd; imsd::sip::FrameBuffer fb; }; - int udpUc_ = -1; + // An accepted connection: the port of ours it came in on and the peer + // accept named. + struct Conn { int fd; imsd::sip::FrameBuffer fb; int port; sockaddr_storage peer; }; + + // The connection held from `peer` to our port `port`: the newest, where + // an older one that ended in an error stands until Poll reads its end; + // none where none is held. + const Conn* Find(int port, const sockaddr_storage& peer) const { + const Conn* found = nullptr; + for (const Conn& c : conns_) + if (c.port == port && SameEnd(c.peer, peer)) found = &c; + return found; + } + + // An answer with no connection to go out on. + void Gone(int port, const sockaddr_storage& peer) { + if (!saidClosed_) Log(std::format("an answer from port {} to {} is not sent: no connection from that peer to that port is held (said once)", port, + imsd::util::HostPort(HostOf(peer), PortOf(peer)))); + saidClosed_ = true; + } + + bool saidClosed_ = false; + int udpUc_ = -1, udpUs_ = -1; std::vector listeners_, udp_; std::vector conns_; }; From a65724a25286eb6b1390602d2ed16e3db452fa8c Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 4 Dec 2026 23:20:38 +0100 Subject: [PATCH 6/7] messages, imsd: P-Access-Network-Info in responses and in requests within a dialog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit imsd named the serving cell in its REGISTERs, the reg-event SUBSCRIBE, an INVITE and a MESSAGE. TS 24.229 5.1.2A.1.1 and 5.1.2A.2 have a UE insert the header into a request within a dialog as well, and into a response within a dialog, to a request for a dialog and to a standalone method: not into a CANCEL nor into a response to one, and into an ACK at its choice. A PRACK and a BYE carry it now, and every response imsd builds but a 100 Trying, the 200 to a CANCEL and the transport's 400 to a request cut short. The server ports (the protected ports' TCP listeners and UDP sockets) take a request from any source (AGENTS.md §12), and the header is the phone's cell. What they send in answer keeps it only on the two paths of the SA pair the shell has on record, and loses it anywhere else. Tested: the suites, and the daemon of this commit on the workstation against a stand-in network that asks it from both sides of those paths (the fp6 journal's 2026-12-04-pani-in-dialog capture, bench/), and on the dev phone on KPN, where its answers to a text's two requests and a call's 180 and 200 carried the header inside the SA pair (the journal's 2026-12-04-imsd-1.2.7-range-on-dev-phone capture). --- AGENTS.md | 154 ++++++++++++++++++++++++++++++++-- implementations/main.cpp | 47 ++++++++++- interfaces/Imsd-Aka.cppm | 3 +- interfaces/Imsd-Ipsec.cppm | 26 +++++- interfaces/Imsd-Messages.cppm | 56 ++++++++++--- interfaces/Imsd-Sip.cppm | 20 +++++ tests/Aka/main.cpp | 3 +- tests/Engine/main.cpp | 67 ++++++++++++++- tests/Ipsec/main.cpp | 19 ++++- tests/Messages/main.cpp | 69 +++++++++++++-- tests/Sip/main.cpp | 34 +++++++- 11 files changed, 460 insertions(+), 38 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a0504b2..1f99bc7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,12 +44,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`), the count of seconds a setting names (`WholeSeconds`), 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; `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, `MinSe` (the interval a `Min-SE` names), `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, `MinSe` (the interval a `Min-SE` names), `WithoutHeader` (a message less every line on which one header is found, under its long name or its compact form), `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) and `RpCauseIsTemporary`, the causes of a submission after which imsd sends the segment again; 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` — the card's side of a registration: 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; since 1.2.3 the ISIM: the application of the slot in use out of the card status (`ParseIsimApp`, in whatever state the modem lists it), the SELECT and the two READ commands its identity files are read with, a card's answer (`ApduAnswer`: `90 00`, `91 XX` and `92 XX` are its normal endings; `HoldsRead` takes a read's data under `62 82` as well) and the command it asks for next (`ApduFollowUp`, for an answer without data: GET RESPONSE for `61 XX`, a command without data again for `6C XX`), the value a file holds (`ParseIsimValue`: the data object with tag `80`, the `FF` bytes at the end of its length cut, no blank and no byte outside printable ASCII) and `IsimIdentity`, the check of the three values — an `@` between two parts, a domain of labels of letters, digits and inner hyphens, 63 characters a label and 253 in all at most, a `sip:` at the start and more after it, the two identities 255 characters at most, no blank, no byte outside printable ASCII and no `"`, `\`, `<` or `>` — before they replace the derived names. | -| `interfaces/Imsd-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the ESP ciphers offered (`ParseEalgOffer`, `DefaultEalgOffer`), 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-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the ESP ciphers offered (`ParseEalgOffer`, `DefaultEalgOffer`), 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); `SaPaths` and `OnSaPath`, whether a packet runs on one of the two paths the outbound policies of an SA pair select. | +| `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` (an empty one for `BuildBadRequest`'s 400) and per-request variables so the builders are pure functions (the shell takes one line, `P-Access-Network-Info`, out of an answer its server ports send on neither path of the SA pair on record: §12); `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, since 1.2.1 a segment that gets no answer, or an RP-ERROR with cause 41, sent once more with TP-RD set — TS 23.040 9.2.3.6 —, 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. Since 1.2.5 also `WakeAt`: when the phone has to be awake for imsd (§7.10). | | `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`. | @@ -184,7 +184,14 @@ stand-ins on the workstation and what on the dev phone. Where an answer goes that the server ports send (§12: the connection found by its port and its peer, an answer that is not sent, the socket a datagram leaves from) is the shell's (`ServerPorts`); §5 has what of it ran against a -stand-in network on the workstation and what on the dev phone. SMS over IP +stand-in network on the workstation and what on the dev phone. What such +an answer keeps of `P-Access-Network-Info` (§12) is decided by +`imsd::ipsec::OnSaPath` and done by `imsd::sip::WithoutHeader`, both with +tests; the shell's part is the record of the SA pair (`saPaths_`: when a +pair goes on it and when it is emptied), the two ends it has an answer +judged by (`Leaving`'s callers) and the journal's line for a header taken +out (`Leaving`), and §5 has what of it ran against that network and what +on the dev phone. SMS over IP (1.2.0, §7.9) keeps in the shell, among others, the service centre's source (`SMSC=` over EF_SMSP, `LoadSmsParameters`), the three counters (TP-MR, RP-MR, the concatenation reference), their @@ -345,7 +352,14 @@ What the suites pin: untouched, another transport-mode user's pair on other ports and addresses untouched — its reqid-1 ESP state on the UE's address deleted, its AH state left —, a policy-less state on the UE's address deleted, one between - other addresses left). + other addresses left), and `OnSaPath` (our client port to the P-CSCF's + server port and our server port to its client port are the pair's + paths; our client port to its client port, our server port to its + server port, another port or another host for the P-CSCF, another + address or another port of ours are not, nor is anything while no pair + is on record; an IPv6 address in another spelling, the packet's or the + record's, is the same address; over IPv4 a path of the pair, and not + another host on its port). - `Qmi` — the request bytes `imsd-pcscf` sends (four of the five the probe's, byte for byte; Get Profile Settings is the helper's own, answered by the modem on the dev phone in the probe capture's `--profile 2 -v` run and on the dev phone's bring-up @@ -377,11 +391,25 @@ What the suites pin: (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). + secret, another tag; a To's own tag kept); `P-Access-Network-Info` + where the cell is known — after the RAck of a PRACK and the CSeq of a + BYE, in the 200 of `BuildResponse200` (before the Contact of one with an + answer), in the 488 of `BuildResponse`, in a 180 plain and reliable, a + 486 and a 200 of `BuildInviteResponse` — and in none of these where it + is not (the 488 and the plain 180 are pinned whole in both forms); where + the cell is known, in no 200 to a CANCEL, no 100 Trying, neither ACK and + no CANCEL; in no 400 of `BuildBadRequest`, which is built without the + context; and the 180 to an INVITE whose Allow names CANCEL is the 180 + to any other. - `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 + skipped), `WithoutHeader` (a message less every line on which + one header is found: one such line, two, the last before the + empty line, a last line without its line end, the name in + another letter case, a compact form; the body, a message + without the header and a name that is part of a longer one left + as they are), 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, unfolded, of a request with fewer body bytes than the @@ -470,7 +498,11 @@ What the suites pin: 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; an incoming call from an INVITE, and an - outgoing call from responses, whose header names come in compact form) and + outgoing call from responses, whose header names come in compact form; + `P-Access-Network-Info` through a call where the cell is known: in the + 180, the 200s, the 486 and the 487 of a call that comes in, in the PRACK + of a call imsd places and in a BYE either way, in no 100 Trying, no 200 + to a CANCEL, no ACK and no CANCEL) 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 @@ -1353,6 +1385,46 @@ Rules: address; a peer on a link-local or an IPv4 address; a connection that ends in an error and is made again within one turn of the daemon's loop. +- What an answer of the server ports keeps of `P-Access-Network-Info` + (§7.6, §12): the rule of the two paths is pinned in `tests/Ipsec` and + the line's removal in `tests/Sip`; the shell's part (the record of the + SA pair, the two ends an answer is judged by, the journal's line) ran + on the workstation against the same stand-in network (the same capture + and script; the bench installs no SA, its `ip` being a stand-in, and + the network tells the paths by the addresses and the ports, as the + record does). Eight OPTIONS requests (five over UDP, three over TCP) + were answered with the header to the P-CSCF's protected client port + from 45062, over UDP and over TCP, and to its protected server port + from 45061 by the request's Via, and without it to another port of the + P-CSCF's host, to another host and to a Via port that is not the + protected server port, with one line in the journal; the same after a + restart that resumed the registration with another P-CSCF configured + than the pair's; none of the eight answers carried it where one policy + add of the SA setup had failed, nor where the modem named no cell. Of + an incoming call, over TCP and over UDP by the Via, the reliable 180, + the 200s to its PRACK and its UPDATE, the 200 that answered it and the + 200 to its BYE carried the header and the 100 Trying did not; over TCP + a 486 and a 487 carried it and the 200 to the CANCEL did not; a call + from another host got its 180 and its 486 without it. The daemon's own + PRACK and BYE carried it, its ACKs and its CANCEL did not, and a + request on the client flow was answered there with it. On the dev + phone on KPN (2026-12-04, the capture of the entry above), with the + record of the pair made by a resume, these left with the header + inside the SA pair: the 200s to the two NOTIFYs that follow the + reg-event SUBSCRIBE and to a text's two requests; of a call that came + in the 180, the 200 that answered it and the 200 to its UPDATE; and + the daemon's own BYE, of that call and of one it placed. The call's + 100 Trying and the daemon's ACK left without it. After a boot, where + the record is made by the fresh registration's setup: the 200s to the + NOTIFY and to a text's two requests, a call's 180, its 200 and the + 200 to its BYE, and the BYE of a call the daemon placed, with the + header; the 100 Trying and the ACK without. The journal has no line + of an answer that went without it. Of what ran against the stand-in + network nothing else has been seen on a real one (an answer off the + pair's two paths, a PRACK either way, a 486, a 487 and a CANCEL among + it). Not run: a fresh registration whose setup fails while a pair is + on record; a bring-up that finds a dead pair; a fresh attempt to + another P-CSCF that fails before its SA setup; an address move. - `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, @@ -2142,6 +2214,29 @@ sent, emit this D-Bus state change, arm this deadline). States and reasons are t call it places imsd asks to be the refresher and sends no session refresh of its own (the call machine sends no UPDATE and no re-INVITE; one from the far side is answered). +- Access information: `P-Access-Network-Info` names the serving cell + (`ParsePani` of `mmcli --location-get`: no header before a read has + named a cell, and a read that names none leaves the last one). TS 24.229 + 5.1.2A.1.1 has a UE insert it "into any request for a dialog, any + subsequent request (except CANCEL requests) or response (except CANCEL + responses) within a dialog or any request for a standalone method", the + ACK at its choice, and 5.1.2A.2 into "any response to a request for a + dialog" and "any response to a standalone method" as well; RFC 7315 5.7 + has it appear in no ACK and no CANCEL. imsd writes it into its + REGISTERs, the reg-event SUBSCRIBE, an INVITE, a MESSAGE, a PRACK and a + BYE, and into every response it builds but three, the last two by its + own choice: the 200 to a CANCEL; a 100 Trying, which a stateful proxy + never forwards (RFC 3261 21.1.1) and for which the log of the stock + modem's capture has no value either (§13); and the 400 to a request cut + short (§7.9), which the transport answers without the registration's + context. The value is the one + `RefreshPani` last took — it reads at the bring-up and after a wait + there, before a refresh's, a reconnect's and a recovery's REGISTER and + before a dial — and not the cell of the moment a later message leaves at + (NOTE 13 of 5.1.2A.1.1 has the current one in a request or response + within a dialog): an incoming call's answers name the cell of the last + of those reads. What the server ports send in answer keeps the header on + the two paths of the SA pair on record and loses it anywhere else (§12). - DTMF (`SendDtmf`): the tones go out as RFC 4733 telephone-event packets on the call's RTP stream, at the payload type the SDP negotiated for the codec's clock (`MediaLeg::dtmfPt`: the answer's for an outgoing call, the @@ -2342,6 +2437,9 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: - `an answer from port N to [address]:port is not sent: no connection from that peer to that port is held (said once)` the first time in a run that an answer is given to the channel of a request that came in over TCP and `ServerPorts` holds no connection from that request's peer to that port (§12). +- `an answer from port N to [address]:port is on neither path of the SA pair on record: it goes without + P-Access-Network-Info, as every such answer does (said once)` the first time in a run that the header is + taken out of an answer the server ports send (§12). - `sleep is held off while the call lasts (logind's inhibitor)` when the calls table's first call has its lock and `sleep is no longer held off (no call)` when that lock is released, the table's last call gone @@ -3405,6 +3503,28 @@ only the imsd side of its bus choice. has one. A channel keeps no descriptor: the kernel gives a closed descriptor's number out again, to a pipe, a file or the connection of whoever connects next. + `P-Access-Network-Info` names the serving cell, so what `ServerPorts` + sends in answer keeps it only on the two paths of the SA pair on record + — from the client port to the P-CSCF's protected server port, from the + server port to its protected client port, between the pair's two + addresses (`imsd::ipsec::OnSaPath`) — and loses it anywhere else + (`Leaving`, `imsd::sip::WithoutHeader`), the journal saying so once in a + run (§7.8). The record is the shell's (`saPaths_`): the pair this run + set up without an error from `ip`, or read back from the kernel's + tables at a resume, and none from the moment the shell takes that pair + out of the kernel; the shell does not ask the kernel again. The client + flow is not judged by the record: what imsd sends there, its own + requests and its answers to what comes in on that flow, leaves as it + was built. It is the first of the two paths; where a command of the SA + setup failed and the registration went on all the same, it may run in + the clear. The first REGISTER of a fresh registration goes from the + init port to the P-CSCF's unprotected port and, where a cell has been + read, carries the header in the clear: RFC 7315 6.4 keeps it out of an + initial request that is unauthenticated and unprotected, as this one + is, and TS 24.229 5.1.1.2.1 has it in an unprotected REGISTER only + where a security association or TLS session exists (§13 has what the + stock modem's log shows of the REGISTER that begins its own + registration). - Short messages (§7.9): `Send` is behind `net.catcrafts.IMS1.Messaging` (an ungated `Send` would let any local account text from the subscriber's number); the journal names a delivered message's sender, size and @@ -3758,3 +3878,21 @@ the related code. `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). +- **The stock modem's `P-Access-Network-Info`** — on KPN the stock + Fairphone 6's own IMS client (2026-07-21, a de-registration, a + registration and an incoming call it took: the fp6 journal's + `2026-12-04-pani-in-dialog` capture, `evidence/`) puts the header into + its reg-event SUBSCRIBE and + into its 200s to a NOTIFY, to a PRACK, to an INVITE it answers after + the call's ACK and to a BYE: its log has the value for each. It has + the value for each of the capture's three REGISTERs too; for the one + that begins the registration, unprotected, it also has, after the + value, the stack's line that a `P-Access-Network-Info` "to be Removed" + was "NOT Found", the only line of the log with the header's name: it + does not say whether that REGISTER carried the header. + The log has no value for its two 100 Tryings nor for the 200 with + which it answers the call's INVITE, and too little of its 180 to say; + it is a diagnostic stream that loses lines, so a value it lacks was + not added or its line was lost. imsd leaves a 100 Trying without the + header by its own choice (§7.6); into the 200 that answers an INVITE + it writes it, as TS 24.229 5.1.2A.2 has it. diff --git a/implementations/main.cpp b/implementations/main.cpp index 95e8e0d..4f2be52 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -753,6 +753,15 @@ struct Inbound { class ServerPorts { public: + // Whether a packet from `own` to `peer` runs on a path of the SA pair: + // the shell answers, from its record of the pair (Engine::InsideSa). + // These ports take a request from any source (AGENTS.md §12); an + // answer they send that runs on neither path goes without + // P-Access-Network-Info, which names the serving cell (RFC 7315 4.4.2: + // a UA inserts it into what "is going to be securely sent" to its + // proxy). + void SetInsideSa(std::function f) { insideSa_ = std::move(f); } + void Open(const std::string& local) { int fam = Is6(local) ? AF_INET6 : AF_INET; for (int port : {PortUc, PortUs}) { @@ -859,7 +868,8 @@ public: auto reply = [this, uc = rs == udpUc_, s, sll](const std::string& r) mutable { const int from = uc ? udpUc_ : udpUs_; if (from < 0) return; - sendto(from, r.data(), r.size(), 0, reinterpret_cast(&s), sll); + const std::string o = Leaving(r, NameOf(from), s); + sendto(from, o.data(), o.size(), 0, reinterpret_cast(&s), sll); }; if (cutShort) { Log(std::format("UDP: {} on server socket {} — answered 400", why, us == udpUc_ ? PortUc : PortUs)); @@ -892,7 +902,8 @@ public: out.push_back({*m, [this, port = it->port, peer = it->peer](const std::string& r) { const Conn* c = Find(port, peer); if (!c) { Gone(port, peer); return; } - (void)!write(c->fd, r.data(), r.size()); + const std::string o = Leaving(r, NameOf(c->fd), c->peer); + (void)!write(c->fd, o.data(), o.size()); }}); } } @@ -923,6 +934,18 @@ private: return found; } + // `r` as it leaves from `own` to `peer` (SetInsideSa). + std::string Leaving(const std::string& r, const sockaddr_storage& own, const sockaddr_storage& peer) { + if (insideSa_ && insideSa_(own, peer)) return r; + std::string bare = imsd::sip::WithoutHeader(r, "P-Access-Network-Info"); + if (bare.size() != r.size() && !saidOutside_) { + saidOutside_ = true; + Log(std::format("an answer from port {} to {} is on neither path of the SA pair on record: it goes without P-Access-Network-Info, as every such answer does (said once)", PortOf(own), + imsd::util::HostPort(HostOf(peer), PortOf(peer)))); + } + return bare; + } + // An answer with no connection to go out on. void Gone(int port, const sockaddr_storage& peer) { if (!saidClosed_) Log(std::format("an answer from port {} to {} is not sent: no connection from that peer to that port is held (said once)", port, @@ -930,6 +953,8 @@ private: saidClosed_ = true; } + std::function insideSa_; + bool saidOutside_ = false; bool saidClosed_ = false; int udpUc_ = -1, udpUs_ = -1; std::vector listeners_, udp_; @@ -1817,6 +1842,7 @@ public: return; } } + server_.SetInsideSa([this](const sockaddr_storage& own, const sockaddr_storage& peer) { return InsideSa(own, peer); }); try { server_.Open(local_); } catch (...) { Log("server ports unavailable; remote hangup/incoming not seen"); } OnRegistered(); @@ -2019,6 +2045,7 @@ private: double subRenewAt_ = 0; // the live subscription is subscribed anew at this time on the boot clock, ahead of its granted expiry (0: none) double subRetryDelay_ = 60; // 60 s doubling to 10 min between failed SUBSCRIBEs int portPs_ = 0; // P-CSCF protected server port (reconnect target) + imsd::ipsec::SaPaths saPaths_; // the SA pair this run set up without an error or resumed, until it takes that pair out of the kernel: what InsideSa judges by imsd::engine::RegRecovery recovery_; // what to do when the registration stops working bool saReplaced_ = false; // the running fresh attempt got past the SA setup (the old registration's SAs are gone) @@ -2220,6 +2247,14 @@ private: return "/usr/libexec/imsd-media"; } + // Whether a packet from `own` to `peer` runs on one of the two paths of + // the SA pair on record (imsd::ipsec::OnSaPath). The record is the + // shell's own: of the pair it set up without an error or read back from + // the kernel's tables at a resume. It does not ask the kernel again. + bool InsideSa(const sockaddr_storage& own, const sockaddr_storage& peer) const { + return imsd::ipsec::OnSaPath(saPaths_, HostOf(own), PortOf(own), HostOf(peer), PortOf(peer)); + } + // Refresh P-Access-Network-Info from the live serving cell (mmcli 3GPP // location). Serving cell changes as the phone moves, so this runs // before every REGISTER/INVITE-carrying step; on failure the previous @@ -2355,7 +2390,7 @@ private: // P-CSCF and nothing is configured, a fact until a boot or a // start. A discovery that FAILED (the reader did not answer) is // no fact: the fatal, and the restart runs it again. - if (outcome == ResumeOutcome::Dead) { recovery_.OldGone(); RemoveDeadPair(pdnLocal_); } + if (outcome == ResumeOutcome::Dead) { recovery_.OldGone(); RemoveDeadPair(pdnLocal_); saPaths_ = {}; } KeepHolds(); if (outcome == ResumeOutcome::Failed || DiscoveryFailed()) throw std::runtime_error(std::string(NoFreshPcscf)); RequestIdle(std::string(NoPcscfIdleText)); throw Stopping{}; @@ -2501,6 +2536,7 @@ private: Log(std::format("RESUME via existing SA (cseq {})", ps->cseq.value_or(1))); portPs_ = sa->portPs; + saPaths_ = {local_, pcscf_, sa->portPs, sa->portPc}; SetTransport(t); // Local refusals (TIME_WAIT after a restart) keep retrying; two // silences mean the flow is not coming back — fresh instead. @@ -2668,16 +2704,19 @@ private: sp.ealg = ealg; // imsd's previous pair out first, each entry by its key — not `ip xfrm … // flush`: another IPsec user's entries (a policy-based VPN's) stay (§12) + saPaths_ = {}; { auto state = RunCapture({"ip", "xfrm", "state"}); auto policy = RunCapture({"ip", "xfrm", "policy"}); RunOwnXfrmDeletes(imsd::ipsec::OwnXfrmDeleteCommands(state.out, policy.out, local_)); } saReplaced_ = true; // from here on the old registration's SAs are gone + bool installed = true; for (auto& cmd : imsd::ipsec::BuildSetupCommands(sp)) { int rc = RunCmd(cmd); - if (rc != 0) Log(std::format("{} -> rc {}", RedactKeys(cmd), rc)); + if (rc != 0) { Log(std::format("{} -> rc {}", RedactKeys(cmd), rc)); installed = false; } } + if (installed) saPaths_ = {local_, pcscf_, portPs, portPc}; ctx_.securityServer = ss_; portPs_ = portPs; diff --git a/interfaces/Imsd-Aka.cppm b/interfaces/Imsd-Aka.cppm index e470a07..935e736 100644 --- a/interfaces/Imsd-Aka.cppm +++ b/interfaces/Imsd-Aka.cppm @@ -283,8 +283,7 @@ export namespace imsd::aka { // "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=" // (TS 24.229 7.2A.4: E-UTRAN cell id = MCC + MNC as broadcast + 16-bit // TAC + 28-bit ECI; mmcli prints both hex fields zero-padded wider, so - // take the low digits). The stock modem sends exactly this shape in - // every REGISTER/INVITE — the TAS reads it to see which access the UE + // take the low digits). The TAS reads it to see which access the UE // is reachable on. FDD is a constant: every KPN LTE band in use is FDD // and MM does not expose the duplex mode. nullopt when the fields are // missing or zero (no serving cell) — callers then omit the header diff --git a/interfaces/Imsd-Ipsec.cppm b/interfaces/Imsd-Ipsec.cppm index 2960187..e4f8903 100644 --- a/interfaces/Imsd-Ipsec.cppm +++ b/interfaces/Imsd-Ipsec.cppm @@ -25,7 +25,8 @@ 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 pair the kernel holds (unknown on either side -decides nothing). +decides nothing). And `SaPaths` with `OnSaPath`: whether a packet runs on one +of the two paths the outbound policies of an SA pair select (§12). Pure std C++ (the shell runs the commands and captures the text). Command shapes and the parser are pinned by tests/Ipsec. @@ -180,6 +181,29 @@ export namespace imsd::ipsec { return cmds; } + // The two paths the outbound policies of an SA pair select + // (BuildSetupCommands: reqid 1 from the UE's protected client port to + // the P-CSCF's server port, reqid 2 from its protected server port to the + // P-CSCF's client port), between the pair's two addresses. The shell + // keeps one of the pair it set up without an error or resumed; with no + // ports, none. + struct SaPaths { + std::string local; // the UE's address the pair is on + std::string pcscf; // the P-CSCF's + int portPs = 0; + int portPc = 0; + }; + + // Whether a packet from [fromHost]:fromPort to [toHost]:toPort runs on + // one of the two paths of `p`. Addresses are compared as + // imsd::util::CanonicalAddr writes them (an IPv6 address in its RFC 5952 + // form). + inline bool OnSaPath(const SaPaths& p, std::string_view fromHost, int fromPort, std::string_view toHost, int toPort) { + const int theirs = fromPort == imsd::util::PortUc ? p.portPs : fromPort == imsd::util::PortUs ? p.portPc : 0; + return theirs != 0 && toPort == theirs && imsd::util::CanonicalAddr(fromHost) == imsd::util::CanonicalAddr(p.local) && + imsd::util::CanonicalAddr(toHost) == imsd::util::CanonicalAddr(p.pcscf); + } + // ---- Security-Server (RFC 3329 §2.2) ----------------------------------- // // The P-CSCF answers the challenge with the mechanisms it supports, each diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index a9d1285..92ef390 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -7,7 +7,9 @@ Imsd:Messages — the SIP request/response text the engine puts on the wire. Every VoLTE message the daemon sends is assembled here from an explicit context and the per-request variables so the builders are pure functions with no hidden state: the engine owns the dialog bookkeeping -and the transport owns the socket, this module only formats bytes. That makes +and the transport owns the socket (and takes the P-Access-Network-Info line +out of an answer the server ports send on neither path of the SA pair on +record), this module only formats bytes. That makes each message byte-pinnable — tests/Messages compares a REGISTER pair and an INVITE with strings cross-generated from the Python reference stack, header for header but for the divergences that suite's header names. @@ -77,7 +79,13 @@ export namespace imsd::msg { // P-Access-Network-Info value (imsd::aka::ParsePani from live mmcli // location: real MCC/MNC/TAC/ECI, FDD). Empty omits the header — // never fabricate one: the network reads it to learn which access - // the UE is reachable on (stock sends it in every REGISTER/INVITE). + // the UE is reachable on. + // It rides in every request but the ACKs and the CANCEL and in every + // response but a 100 Trying, a CANCEL's and BuildBadRequest's 400: + // by TS 24.229 5.1.2A.1.1 and 5.1.2A.2 for a request within a + // dialog and for the three kinds of response detail::AccessInfo + // names (the 100 and the 400 are left out by imsd's choice), by RFC + // 7315 5.7 for the ACKs and the CANCEL. std::string panInfo; // Advertise SMS over IP in the REGISTER Contact (+g.3gpp.smsip, TS // 24.341 5.3.2.2): the network then delivers terminating short @@ -224,6 +232,18 @@ export namespace imsd::msg { } return s; } + + // The P-Access-Network-Info line of a response with status `code` + // to `request`, where the serving cell is known: TS 24.229 + // 5.1.2A.1.1 and 5.1.2A.2 have a UE insert the header into every + // response it sends within a dialog, to a request for a dialog and + // to a standalone method, those to a CANCEL excepted. A 100 Trying + // gets none, by imsd's choice: a stateful proxy never forwards it + // (RFC 3261 21.1.1; AGENTS.md §7.6). + inline void AccessInfo(std::vector& l, const Context& c, std::string_view request, int code) { + if (c.panInfo.empty() || code == 100 || request.starts_with("CANCEL ")) return; + l.push_back(std::format("P-Access-Network-Info: {}", c.panInfo)); + } } // ---- REGISTER ------------------------------------------------------- @@ -423,6 +443,9 @@ export namespace imsd::msg { // An in-dialog request (PRACK, BYE, UPDATE...) over the dialog route set. // `extra` lines go after CSeq; an optional body sets Content-Type/Length. + // P-Access-Network-Info as in the INVITE (TS 24.229 5.1.2A.1.1, + // 5.1.2A.2); the ACKs and the CANCEL, built below, carry none (RFC 7315 + // 5.7: the header appears in no ACK and no CANCEL). std::string BuildInDialog(const Context& c, const Dialog& d, std::string_view method, int cseq, std::string_view viaBranch, std::span extra = {}, std::string_view body = {}, std::string_view ctype = {}) { std::string target = d.remoteTarget.value_or(d.ruri); std::string to = d.dialogTo.value_or(std::format("<{}>", d.ruri)); @@ -438,6 +461,7 @@ export namespace imsd::msg { }; for (const std::string& e : extra) l.push_back(e); + if (!c.panInfo.empty()) l.push_back(std::format("P-Access-Network-Info: {}", c.panInfo)); if (!body.empty()) { l.push_back(std::format("Content-Type: {}", ctype)); l.push_back(std::format("Content-Length: {}", body.size())); @@ -508,7 +532,8 @@ export namespace imsd::msg { // half by tagging To (all but 100 Trying, which is hop-by-hop and // tagless). 1xx/2xx carry our Contact (the dialog's remote target for the // caller) and Allow; `extra` appends headers (RSeq, Session-Expires...); - // `sdp` turns a 200 into the answer. + // P-Access-Network-Info follows them where the cell is known, in all + // but a 100; `sdp` turns a 200 into the answer. std::string BuildInviteResponse(const Context& c, std::string_view invite, int code, std::string_view text, std::string_view toTag, std::optional sdp = std::nullopt, std::span extra = {}) { std::vector l = {std::format("SIP/2.0 {} {}", code, text)}; for (auto v : imsd::sip::Headers(invite, "Via")) @@ -530,6 +555,7 @@ export namespace imsd::msg { } for (const std::string& e : extra) l.push_back(e); + detail::AccessInfo(l, c, invite, code); if (sdp) { l.push_back("Content-Type: application/sdp"); l.push_back(std::format("Content-Length: {}", sdp->size())); @@ -544,10 +570,12 @@ export namespace imsd::msg { // 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 + // Call-ID and CSeq, then P-Access-Network-Info where the cell is known; + // no body. The shell's answers to any other request // outside a call but an INVITE (an OPTIONS, a NOTIFY, a method it does - // not handle) keep BuildResponse200's hop-by-hop shape, as before. - std::string BuildResponse(const Context&, std::string_view request, int code, std::string_view text, std::string_view toTag) { + // not handle) keep BuildResponse200's hop-by-hop shape, as before, + // unless the request is cut short: BuildBadRequest's 400 has this one. + std::string BuildResponse(const Context& c, std::string_view request, int code, std::string_view text, std::string_view toTag) { std::vector l = {std::format("SIP/2.0 {} {}", code, text)}; for (auto v : imsd::sip::Headers(request, "Via")) l.push_back(std::format("Via: {}", v)); if (auto f = imsd::sip::Header(request, "From")) l.push_back(std::format("From: {}", *f)); @@ -557,6 +585,7 @@ export namespace imsd::msg { } if (auto ci = imsd::sip::Header(request, "Call-ID")) l.push_back(std::format("Call-ID: {}", *ci)); if (auto cs = imsd::sip::Header(request, "CSeq")) l.push_back(std::format("CSeq: {}", *cs)); + detail::AccessInfo(l, c, request, code); l.push_back("Content-Length: 0"); return std::format("{}\r\n", detail::Join(l)); } @@ -564,25 +593,30 @@ export namespace imsd::msg { // 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 + // keeps nothing of such a request, so the tag it adds to a To that holds + // none 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. + // header section. The transport answers with it, without the + // registration's context: it carries no P-Access-Network-Info. 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...). + // `extra` appends headers (Session-Expires echo for refreshes...), and + // P-Access-Network-Info follows them where the cell is known, unless + // the request is a CANCEL. std::string BuildResponse200(const Context& c, std::string_view request, std::optional sdp = std::nullopt, std::span extra = {}) { std::vector l = {"SIP/2.0 200 OK"}; for (std::string_view h : {"Via", "From", "To", "Call-ID", "CSeq"}) if (auto v = imsd::sip::Header(request, h)) l.push_back(std::format("{}: {}", h, *v)); for (const auto& e : extra) l.push_back(e); + detail::AccessInfo(l, c, request, 200); if (sdp) { l.push_back(std::format("Contact: ", ContactUser(c), imsd::util::HostPort(c.local, c.portUs))); l.push_back("Content-Type: application/sdp"); diff --git a/interfaces/Imsd-Sip.cppm b/interfaces/Imsd-Sip.cppm index c672693..18ca65f 100644 --- a/interfaces/Imsd-Sip.cppm +++ b/interfaces/Imsd-Sip.cppm @@ -193,6 +193,26 @@ export namespace imsd::sip { return out; } + // `msg` without its `name:` header lines: every line of the header + // section on which Headers would find the name, long or compact + // (MatchHeaderLine), is left out, and the other lines and the body stay + // as they are. For P-Access-Network-Info as the builders write it, one + // line with its value, that is the header whole. + std::string WithoutHeader(std::string_view msg, std::string_view name) { + std::string out; + std::size_t kept = 0; + ForEachLine(msg, [&](std::string_view line) { + if (MatchHeaderLine(line, name)) { + const auto at = static_cast(line.data() - msg.data()); + out += msg.substr(kept, at - kept); + kept = std::min(at + line.size() + 1, msg.size()); + } + return true; + }); + out += msg.substr(kept); + return out; + } + // The 3-digit code of a "SIP/2.0 NNN ..." response start-line; nullopt // for requests / anything else. Only matches at the start of the message. std::optional Status(std::string_view msg) { diff --git a/tests/Aka/main.cpp b/tests/Aka/main.cpp index 7cdad57..f75c92c 100644 --- a/tests/Aka/main.cpp +++ b/tests/Aka/main.cpp @@ -215,8 +215,7 @@ int main() { { // P-Access-Network-Info from `mmcli --location-get` (real-device // output shape; TAC/CI zero-padded wider than the 4/7 hex digits - // PANI uses). The mcc+mnc+TAC+ECI concatenation was validated - // against a stock modem's on-wire PANI; values here are synthetic. + // PANI uses). Values here are synthetic. constexpr std::string_view Loc = " --------------------------\n" " 3GPP | operator mcc: 001\n" diff --git a/tests/Engine/main.cpp b/tests/Engine/main.cpp index c98ee31..4a7c514 100644 --- a/tests/Engine/main.cpp +++ b/tests/Engine/main.cpp @@ -14,7 +14,11 @@ // ring and are answered at the offer's own payload types, ring timeout -> // 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 +// 7.3.3); which of a call's messages carry P-Access-Network-Info where +// the cell is known (its 180, its 200s but the one to a CANCEL, a 486 +// and a 487, PRACK and BYE) and which do not (the 100 Trying, the 200 to +// a CANCEL, the ACKs, the CANCEL). 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: @@ -917,6 +921,67 @@ int main() { Check(m.Terminated(), "terminated"); } + // ---- P-Access-Network-Info through a call's life, where the cell is + // known: in the 180, the 200s but a CANCEL's, a 486 and a 487, and + // in PRACK and BYE; in no 100 Trying, no ACK and no CANCEL + { + Context k = MakeCtx(); + k.panInfo = "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0"; + const auto with = [](const Action* a) { return a && a->text.contains("\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n"); }; + const auto without = [](const Action* a) { return a && !a->text.contains("P-Access-Network-Info"); }; + const auto inDialog = [](std::string_view method, std::string_view callid, std::string_view extra = "") { + return std::format( + "{} sip:001010123456789@[2001:db8::db43]:45061 SIP/2.0\r\n" + "Via: SIP/2.0/UDP [2001:db8::105]:5100;branch=z9hG4bKpcscf9\r\n" + "From: ;tag=caller1\r\n" + "To: ;tag=ours\r\n" + "Call-ID: {}\r\nCSeq: 2 {}\r\n{}Content-Length: 0\r\n\r\n", method, callid, method, extra); + }; + { + // an incoming call its caller cancels + imsd::util::Rng rng(71); + CallMachine m(k, rng, "ims-call-80", IncomingInvite{MtInvite("Require: 100rel\r\n")}, 50004); + auto ai = m.OnInvite(); + Check(with(Responded(ai, "SIP/2.0 180 Ringing")) && without(Responded(ai, "SIP/2.0 100 Trying")), "a cell known: the 180 to an incoming INVITE carries P-Access-Network-Info, its 100 Trying does not"); + Check(with(Responded(m.OnRequest(inDialog("PRACK", m.CallId(), "RAck: 1 1 INVITE\r\n")), "SIP/2.0 200 OK")), "... and the 200 to the PRACK of that 180"); + auto ac = m.OnRequest(inDialog("CANCEL", m.CallId())); + Check(without(Responded(ac, "SIP/2.0 200 OK")) && with(Responded(ac, "SIP/2.0 487 Request Terminated")), "... the 200 to a CANCEL does not, the INVITE's 487 does"); + } + { + // an incoming call answered, then refreshed and ended from the far side + imsd::util::Rng rng(72); + CallMachine m(k, rng, "ims-call-81", IncomingInvite{MtInvite()}, 50004); + m.OnInvite(); + Check(with(Responded(m.OnAccept(), "SIP/2.0 200 OK")), "... the 200 that answers the call"); + Check(with(Responded(m.OnRequest(inDialog("UPDATE", m.CallId(), "Session-Expires: 1800;refresher=uac\r\n")), "SIP/2.0 200 OK")), "... the 200 to a session refresh"); + Check(with(Responded(m.OnRequest(inDialog("BYE", m.CallId())), "SIP/2.0 200 OK")), "... and the 200 to the far side's BYE"); + } + { + // an incoming call refused, and one answered and ended here + imsd::util::Rng rng(73); + CallMachine m(k, rng, "ims-call-82", IncomingInvite{MtInvite()}, 50004); + m.OnInvite(); + Check(with(Responded(m.OnHangup(), "SIP/2.0 486 Busy Here")), "... a 486"); + CallMachine n(k, rng, "ims-call-83", IncomingInvite{MtInvite()}, 50004); + n.OnInvite(); + n.OnAccept(); + Check(with(Sent(n.OnHangup(), "BYE ")), "... our BYE on a call that came in"); + } + { + // a call we place: its PRACK and its BYE carry it, its ACKs and its CANCEL do not + imsd::util::Rng rng(74); + CallMachine m(k, rng, "ims-call-84", "1233", 50004, false); + m.Start(); + Check(with(Sent(m.OnInviteResponse(R183(m.CallId())), "PRACK ")), "... the PRACK of a call we place"); + Check(without(Sent(m.OnInviteResponse(R200(m.CallId())), "ACK ")), "... not the ACK of its 200"); + Check(with(Sent(m.OnHangup(), "BYE ")), "... its BYE"); + CallMachine n(k, rng, "ims-call-85", "1233", 50004, false); + n.Start(); + Check(without(Sent(n.OnHangup(), "CANCEL ")), "... not a CANCEL"); + Check(without(Sent(n.OnInviteResponse(Final(n.CallId(), 487, "Request Terminated")), "ACK ")), "... and not the ACK of a refusal"); + } + } + // ================= emergency (stage 1) ================================ // ---- emergency dial: the INVITE targets the sos URN over the normal diff --git a/tests/Ipsec/main.cpp b/tests/Ipsec/main.cpp index 5bdf223..6512087 100644 --- a/tests/Ipsec/main.cpp +++ b/tests/Ipsec/main.cpp @@ -8,7 +8,8 @@ // prints, with its line for each algorithm imsd installs, and // the Security-Server parser, fed the operator lines as captured (O2 UK's // six-mechanism Mavenir shape verbatim, under a null and under an aes-cbc -// offer; KPN's single mechanism; Odido's), and the EALG list. +// offer; KPN's single mechanism; Odido's), the EALG list, and the two +// paths an SA pair's outbound policies select (OnSaPath). import std; import Imsd; @@ -476,6 +477,22 @@ int main() { Check(NormalizeEalg("") == "null" && NormalizeEalg("3des") == "des-ede3-cbc" && NormalizeEalg("aes-cbc") == "aes-cbc", "NormalizeEalg"); } + // ---- OnSaPath: the two paths an SA pair's outbound policies select + { + const SaPaths p{"2001:db8::db43", "2001:db8::105", 6000, 33421}; + Check(OnSaPath(p, "2001:db8::db43", 45061, "2001:db8::105", 6000), "OnSaPath: the client port to the P-CSCF's server port"); + Check(OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 33421), "OnSaPath: the server port to the P-CSCF's client port"); + Check(!OnSaPath(p, "2001:db8::db43", 45061, "2001:db8::105", 33421) && !OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 6000), "OnSaPath: not the client port to its client port, nor the server port to its server port"); + Check(!OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::105", 33422), "OnSaPath: not another port of the P-CSCF"); + Check(!OnSaPath(p, "2001:db8::db43", 45062, "2001:db8::106", 33421), "OnSaPath: not another host on the P-CSCF's port"); + Check(!OnSaPath(p, "2001:db8::db44", 45062, "2001:db8::105", 33421), "OnSaPath: not from another address of ours"); + Check(!OnSaPath(p, "2001:db8::db43", 5060, "2001:db8::105", 6000) && !OnSaPath(p, "2001:db8::db43", 5060, "2001:db8::105", 33421), "OnSaPath: not from a port that is neither protected port"); + Check(OnSaPath(p, "2001:DB8:0:0:0:0:0:DB43", 45061, "2001:0db8::0105", 6000) && OnSaPath(SaPaths{"2001:DB8:0:0:0:0:0:DB43", "2001:0db8::0105", 6000, 33421}, "2001:db8::db43", 45061, "2001:db8::105", 6000), "OnSaPath: an IPv6 address in another spelling is the same address, the packet's or the record's"); + Check(!OnSaPath(SaPaths{}, "2001:db8::db43", 45061, "2001:db8::105", 6000) && !OnSaPath(SaPaths{}, "", 45061, "", 0), "OnSaPath: no pair on record, no path"); + const SaPaths four{"192.0.2.2", "192.0.2.1", 6000, 33421}; + Check(OnSaPath(four, "192.0.2.2", 45062, "192.0.2.1", 33421) && !OnSaPath(four, "192.0.2.2", 45062, "192.0.2.3", 33421), "OnSaPath: over IPv4 a path of the pair, and not another host on its port"); + } + if (Failures == 0) std::println("Ipsec: all tests passed"); 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 2916c7a..ec2994e 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -21,7 +21,10 @@ // one cipher. The two REGISTERs once more on an identity an ISIM holds: the // pinned ones with the card's names in place of the derived ones. The INVITE, // its CANCEL and its ACKs once more for a dialog with another sequence number, -// session interval and Min-SE than the pinned 1, 1800 and 90. Then the +// session interval and Min-SE than the pinned 1, 1800 and 90. Which +// messages carry P-Access-Network-Info where the cell is known, and that the +// PRACK, the BYE and the responses that carry it carry none where it is not. +// Then the // SMS over IP shapes: the // +g.3gpp.smsip Contact tag behind Context::smsOverIp, the MESSAGE carrying // an RP-DATA to the service centre and the one carrying an RP-ACK to the @@ -423,11 +426,11 @@ int main() { Check(prack.contains("To: ;tag=remote99\r\n"), "PRACK To has remote tag"); Check(prack.contains("CSeq: 2 PRACK\r\n"), "PRACK CSeq"); Check(prack.contains("RAck: 42 1 INVITE\r\n"), "PRACK RAck"); - Check(prack.ends_with("Content-Length: 0\r\n\r\n"), "PRACK empty body"); + Check(prack.ends_with("RAck: 42 1 INVITE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "PRACK: P-Access-Network-Info after its RAck, an empty body"); std::string bye = BuildInDialog(c, d, "BYE", 3, "byebranch"); Check(bye.starts_with("BYE sip:termgw@2001:db8::9 SIP/2.0\r\n"), "BYE line"); - Check(bye.contains("CSeq: 3 BYE\r\n"), "BYE CSeq"); + Check(bye.ends_with("CSeq: 3 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "BYE: its CSeq, then P-Access-Network-Info"); std::string ack = BuildAck2xx(c, d, "ackbranch", ""); Check(ack.starts_with("ACK sip:termgw@2001:db8::9 SIP/2.0\r\n"), "ACK 2xx target"); @@ -438,6 +441,12 @@ int main() { Check(cancel.starts_with(std::format("CANCEL {} SIP/2.0\r\n", d.ruri)), "CANCEL request-URI = ruri"); Check(cancel.contains("branch=z9hG4bKib;rport\r\n"), "CANCEL reuses INVITE branch"); Check(cancel.contains("CSeq: 1 CANCEL\r\n"), "CANCEL CSeq copies INVITE"); + // RFC 7315 5.7: the header appears in no ACK and no CANCEL + Check(!ack.contains("P-Access-Network-Info") && !cancel.contains("P-Access-Network-Info") && !BuildAckNon2xx(c, d, ";tag=z").contains("P-Access-Network-Info"), "neither ACK nor the CANCEL carries P-Access-Network-Info"); + // where the cell is not known the in-dialog requests carry none either + Context n = MakeCtx(); + n.panInfo.clear(); + Check(BuildInDialog(n, d, "PRACK", 2, "prbranch", rack).ends_with("RAck: 42 1 INVITE\r\nContent-Length: 0\r\n\r\n") && BuildInDialog(n, d, "BYE", 3, "byebranch").ends_with("CSeq: 3 BYE\r\nContent-Length: 0\r\n\r\n"), "no cell known: PRACK and BYE without the header"); } { // non-2xx ACK uses the INVITE branch + registration route + resp To @@ -478,12 +487,21 @@ int main() { Check(r.contains("Via: SIP/2.0/TCP [a::1]:45061;branch=z9hG4bKother\r\n"), "200 echoes Via"); Check(r.contains("Call-ID: xyz@far\r\n"), "200 echoes Call-ID"); Check(r.contains("CSeq: 7 BYE\r\n"), "200 echoes CSeq"); - Check(r.ends_with("Content-Length: 0\r\n\r\n"), "200 empty body"); + Check(r.ends_with("CSeq: 7 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "200 to a BYE: P-Access-Network-Info after the echoed five, an empty body"); // with an SDP answer: our Contact + application/sdp appear std::string r2 = BuildResponse200(c, req, Sdp); Check(r2.contains("Content-Type: application/sdp\r\n"), "200 w/ SDP content-type"); Check(r2.contains("Contact: \r\n"), "200 w/ SDP includes our Contact"); Check(r2.ends_with(Sdp), "200 w/ SDP body"); + Check(r2.contains("CSeq: 7 BYE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContact: "), "200 w/ SDP: P-Access-Network-Info before our Contact"); + // TS 24.229 5.1.2A.1.1, 5.1.2A.2: "(except CANCEL responses)" + std::string cancelReq = req; + cancelReq.replace(0, 3, "CANCEL"); + cancelReq.replace(cancelReq.find("CSeq: 7 BYE"), 11, "CSeq: 7 CANCEL"); + Check(BuildResponse200(c, cancelReq).ends_with("CSeq: 7 CANCEL\r\nContent-Length: 0\r\n\r\n"), "200 to a CANCEL: no P-Access-Network-Info"); + Context n = MakeCtx(); + n.panInfo.clear(); + Check(BuildResponse200(n, req).ends_with("CSeq: 7 BYE\r\nContent-Length: 0\r\n\r\n") && !BuildResponse200(n, req, Sdp).contains("P-Access-Network-Info"), "no cell known: the 200 without the header"); } // ---- s53 oracle diff: UUID Contact user-part + User-Agent ------------ @@ -569,7 +587,9 @@ int main() { "Call-ID: in1@net\r\n" "CSeq: 9 MESSAGE\r\n" "Content-Length: 0\r\n\r\n"; - Eq(BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"), + Context noCell = MakeCtx(); + noCell.panInfo.clear(); + Eq(BuildResponse(noCell, inbound, 488, "Not Acceptable Here", "T488"), "SIP/2.0 488 Not Acceptable Here\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" @@ -578,6 +598,16 @@ int main() { "Call-ID: in1@net\r\n" "CSeq: 9 MESSAGE\r\n" "Content-Length: 0\r\n\r\n", "a 488 for an inbound MESSAGE echoes every Via and tags To"); + Eq(BuildResponse(c, inbound, 488, "Not Acceptable Here", "T488"), + "SIP/2.0 488 Not Acceptable Here\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=T488\r\n" + "Call-ID: in1@net\r\n" + "CSeq: 9 MESSAGE\r\n" + "P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n" + "Content-Length: 0\r\n\r\n", "and where the cell is known, P-Access-Network-Info after its CSeq"); 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 @@ -598,6 +628,7 @@ int main() { "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"); + Check(!BuildBadRequest(head, secret).contains("P-Access-Network-Info"), "the 400 is built without the registration's context: no P-Access-Network-Info"); 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; @@ -644,6 +675,18 @@ int main() { "i: call3@net\r\n" "CSeq: 1 INVITE\r\n" "l: 0\r\n\r\n"; + Eq(BuildInviteResponse(noCell, invite, 180, "Ringing", "T180"), + "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"); const std::string ringing = BuildInviteResponse(c, invite, 180, "Ringing", "T180"); Eq(ringing, "SIP/2.0 180 Ringing\r\n" @@ -656,7 +699,21 @@ int main() { "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"); + "P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n" + "Content-Length: 0\r\n\r\n", "and where the cell is known, P-Access-Network-Info after them"); + { + const std::array reliable = {"Require: 100rel", "RSeq: 1"}; + Check(BuildInviteResponse(c, invite, 180, "Ringing", "T180", std::nullopt, reliable).ends_with("Require: 100rel\r\nRSeq: 1\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "a reliable 180: P-Access-Network-Info after its Require and RSeq"); + Check(BuildInviteResponse(c, invite, 100, "Trying", "unused").ends_with("CSeq: 1 INVITE\r\nContent-Length: 0\r\n\r\n"), "a 100 Trying carries none"); + Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").ends_with("CSeq: 1 INVITE\r\nP-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Length: 0\r\n\r\n"), "and a 486"); + Check(BuildInviteResponse(c, invite, 200, "OK", "T200", "v=0\r\n").ends_with("P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\nContent-Type: application/sdp\r\nContent-Length: 5\r\n\r\nv=0\r\n"), "and a 200 with its answer, before the Content-Type"); + Check(!BuildInviteResponse(noCell, invite, 100, "Trying", "unused").contains("P-Access-Network-Info") && !BuildInviteResponse(noCell, invite, 200, "OK", "T200", "v=0\r\n").contains("P-Access-Network-Info"), "no cell known: a 100 and a 200 without the header"); + Check(BuildInviteResponse(noCell, invite, 180, "Ringing", "T180", std::nullopt, reliable).ends_with("Require: 100rel\r\nRSeq: 1\r\nContent-Length: 0\r\n\r\n") && BuildInviteResponse(noCell, invite, 486, "Busy Here", "T486").ends_with("CSeq: 1 INVITE\r\nContent-Length: 0\r\n\r\n"), "no cell known: a reliable 180 and a 486 without it"); + // the exception is for a response to a CANCEL, not for one to a request that names the method + std::string allowing = invite; + allowing.insert(allowing.find("Content-Length:"), "Allow: INVITE, ACK, CANCEL, BYE\r\n"); + Check(BuildInviteResponse(c, allowing, 180, "Ringing", "T180") == ringing, "an INVITE whose Allow names CANCEL is answered like any other"); + } 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"); diff --git a/tests/Sip/main.cpp b/tests/Sip/main.cpp index 9df0cee..4d3784a 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -11,8 +11,10 @@ // (CutShortRequest), a refused final's Retry-After and summary (RetryAfter, // RefusalSummary), the interval a 422's Min-SE names (MinSe), 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. +// reg-event document (RegInfoContactState), HeaderUri and Body, and a +// message less every line on which one header is found (WithoutHeader). +// These pin the module's edge-case behavior; see the module header before +// "fixing" one. import std; import Imsd; @@ -569,6 +571,34 @@ int main() { Check(imsd::sip::Body("OPTIONS sip:x SIP/2.0\r\nCSeq: 1 OPTIONS\r\n").empty(), "Body: none without a terminator"); } + // ---- WithoutHeader: a message less every line on which one header is + // found + { + const std::string r = + "SIP/2.0 200 OK\r\n" + "Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n" + "P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: 31\r\n" + "\r\n" + "P-Access-Network-Info: a body\r\n"; + const std::string bare = + "SIP/2.0 200 OK\r\n" + "Via: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKnet1\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: 31\r\n" + "\r\n" + "P-Access-Network-Info: a body\r\n"; + Check(WithoutHeader(r, "P-Access-Network-Info") == bare, "WithoutHeader: the header's line is gone, the other lines and a body line that spells its name stay"); + Check(WithoutHeader(bare, "P-Access-Network-Info") == bare, "WithoutHeader: a message without the header comes back as it is"); + Check(WithoutHeader(r, "p-access-network-info") == bare, "WithoutHeader: the name in another letter case"); + Check(WithoutHeader(r, "P-Access-Network") == r && WithoutHeader(r, "Access-Network-Info") == r, "WithoutHeader: a name that is only part of a header's name takes nothing"); + const std::string twice = "BYE sip:a@b SIP/2.0\r\nP-Access-Network-Info: one\r\nCSeq: 2 BYE\r\nP-Access-Network-Info: two\r\n\r\n"; + Check(WithoutHeader(twice, "P-Access-Network-Info") == "BYE sip:a@b SIP/2.0\r\nCSeq: 2 BYE\r\n\r\n", "WithoutHeader: every line of the name, the last before the empty line too"); + Check(WithoutHeader("SIP/2.0 200 OK\r\nVia: x\r\nP-Access-Network-Info: v", "P-Access-Network-Info") == "SIP/2.0 200 OK\r\nVia: x\r\n", "WithoutHeader: a last line without its line end"); + Check(WithoutHeader("SIP/2.0 200 OK\r\nv: x\r\nTo: y\r\nVia: z\r\n\r\n", "Via") == "SIP/2.0 200 OK\r\nTo: y\r\n\r\n", "WithoutHeader: a header under its compact form goes as under its long one"); + } + if (Failures == 0) std::println("Sip: all tests passed"); return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that } From c3b7d01d433b5aca7e50cc5468dc11cd5646c44c Mon Sep 17 00:00:00 2001 From: Jorijn van der Graaf Date: Fri, 4 Dec 2026 23:20:38 +0100 Subject: [PATCH 7/7] imsd 1.2.7 --- implementations/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/implementations/main.cpp b/implementations/main.cpp index 4f2be52..19187b9 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -56,7 +56,7 @@ import ImsdBus; namespace { // ---- static config (env-overridable, same knobs as imsd.py) --------------- -constexpr const char* Version = "1.2.6"; +constexpr const char* Version = "1.2.7"; constexpr const char* BusName = "net.catcrafts.IMS1"; constexpr const char* ObjPath = "/net/catcrafts/IMS1"; constexpr const char* Iface = "net.catcrafts.IMS1";