diff --git a/AGENTS.md b/AGENTS.md index 0f4bd93..1f99bc7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,8 +15,10 @@ bug — fix it in the same change. imsd is a userspace IMS/VoLTE client for mainline Linux phones. The modem firmware on such phones brings up the IMS PDN but cannot carry call audio, so -imsd does the whole IMS client itself: SIP registration with USIM AKA -authentication over kernel IPsec (ESP), call signalling for outgoing and +imsd does the whole IMS client itself: SIP registration — by default under +the identity the card's ISIM holds, else the one derived from the IMSI, with +AKA authentication in that ISIM, else in the USIM (§7.2) — over +kernel IPsec (ESP), call signalling for outgoing and incoming calls, and the RTP media plane (AMR-WB, AMR, G.711) wired into PipeWire, and since 1.2.0 short messages over IMS (TS 24.341: the SIP MESSAGE carrying an RP-DATA, a store, the Messaging interface — @@ -25,7 +27,8 @@ and GNOME Mobile — places and receives real VoLTE calls on a commercial network through it. It talks to the modem through ModemManager (`mmcli`) and `qmicli` over QRTR -(the USIM AKA run goes through a UIM logical channel) and, for the P-CSCF list +(the AKA run and the read of an ISIM's identity files go through UIM logical +channels) and, for the P-CSCF list the network put in the ims PDN's PCO, through its own QMI WDS client (`imsd-pcscf`, a raw QRTR socket bound to the bearer's mux data port — §13), installs its security @@ -40,14 +43,14 @@ PipeWire. The verified device/carrier combinations are in the README. |---|---| | `project.cpp` | The canonical build description, for [Crafter Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build). Chooses the product by `--product=`. | | `interfaces/Imsd.cppm` | The primary module interface of `imsd-core`: `export import`s the nine partitions below. | -| `interfaces/Imsd-Util.cppm` | `imsd::util` — SIP tokens, IPv6 host/port formatting, the RFC 5952 §4 IPv6 text (`CanonicalIp6`/`CanonicalAddr`; an IPv4-mapped address spelled in hex stays hex, where §5 and `inet_ntop` write it dotted) and the comma-separated address-list parser (`ParseAddressList`), hex/base64, MD5 (RFC 1321), the fixed protected ports `PortUc`/`PortUs` (45061/45062). | -| `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `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-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), `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` — USIM AKA glue: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response. | -| `interfaces/Imsd-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the Security-Server mechanism selection, and the reader that reconstructs SPIs/ports from `ip xfrm state`/`policy` text for a warm resume, and (1.0.0) `SaPeer`, the P-CSCF the kernel's pair is to, read from the `dir out` policies that carry imsd's fingerprint, `OwnXfrmDeleteCommands`, the deletes by exact key of what two rules select — the policies carrying imsd's fingerprint and the reqid-1/2 transport-mode ESP states in their direction or on the UE's ims-PDN address, whoever installed them (§12), and `FileNamesAnotherPair`, whether a state file's `spi_uc`/`spi_us` name the kernel's pair (unknown on either side decides nothing). | -| `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; `tests/Messages` is their suite. Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each Via row echoed in order and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); since 1.2.1 `BuildBadRequest`, the 400 to a request cut short of the Content-Length read from it — any but an ACK or a CANCEL, in a call's dialog or not —, in that shape, a To tag it adds made from the request's header section and a secret of the run (RFC 3261 8.2.7); of requests that came whole, in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. | -| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (§7.9): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, 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. | +| `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); `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`. | | `implementations/main.cpp` | The `imsd` daemon shell: GLib main loop, GDBus service, sockets, subprocesses, the registration sequence and the run loop that pumps the core. | @@ -98,7 +101,9 @@ meanwhile and the routing of our reg-event SUBSCRIBE's final read there, the 12 s wait restarted on a provisional); the reregistration's headers and its answer to a challenge (`Reregister`: the stored challenge answer, or the empty digest for a pre-0.3.11 state file, the new SPIs, `PortUcNext`; a 401 thrown -as a refusal carrying its status); the state-file round trip +as a refusal carrying its status; and, since 1.2.5, the number it takes, +used and written to the state file once the REGISTER is sent, §7.2 +step 5 and §5); the state-file round trip (`PersistState`/`LoadState`: the `security_server` key, written empty for a value with a quote, a backslash or a newline — the choice between that list and the entry rebuilt from the SA is `Imsd:Ipsec`'s, with a test); the @@ -116,8 +121,14 @@ the second refusal, the count travelling in the holds (`Reconnectable()` and `Fresh()`, decided once after both catch arms) — and taken out of the kernel, §7.2 step 1), the `OnLink` read that writes the old registration off when its address has left the netdev (`FreshRecover` after a failed move, -`AddressGone`), and `PacketServiceUp`'s read of -ModemManager before a silent cycle is counted; the no-target reads and +`AddressGone`), `PacketServiceUp`'s read of +ModemManager before a silent cycle is counted and, since 1.2.5, before +every reconnect cycle and every fresh registration of the recovery +(`NoService`; a bring-up's registrations and the connect for a call's +resend do not ask), and the shell's word that the network has answered, +which starts a coverage gap's counts over (`OnNetworkAnswered`: an +answered TCP connect of the resume or of a reconnect, a response to a +REGISTER); the no-target reads and reactions (1.0.0): the kernel text behind `SaPeer`, the holds' `old_gone` and the script's `PCSCF_DISCOVERY=` — whether a pair is resumable (`SaPeer` finds one and the holds' `old_gone` does not write it off: `!peer || @@ -139,7 +150,49 @@ both sides (1.0.0) is unbenched: no capture stages a holds file whose `pdn` is spelled unlike `LOCAL`). For the schedule, a reducer next to `RegRecovery`, with a Subscription-State parser in `Imsd:Sip` pinned by `tests/Sip`, is the follow-up that moves it; a pure format/parse pair in -`Imsd:Engine` is the holds file's. SMS over IP (1.2.0, §7.9) keeps in the +`Imsd:Engine` is the holds file's. The card's side (1.2.3, §7.2 step 2) +keeps in the shell the choice of the identity (`BringUp`: `ISIM=0`, no ISIM +application in the USIM's slot, an ISIM that gave none, and `FreshRecover`'s +asking of such an ISIM again), the read itself +(`ReadIsimIdentity`: the three files and their order, record 1 of EF_IMPU, +a SELECT's `61 XX` taken for the file selected, what its `why` says), the +channel (`UimChannel`: the open, the exchanges, the two follow-ups at most, +the close), the application the challenge goes to with its +fall-back to the USIM and the journal's words for an answer that is no +result (`Authenticate`, `AkaIn`), and which identity a +registration carries: the card's at a fresh registration, the one it was +made under at a resume (`TryResume`: the state file's three names, the +derived ones for a file that has none; `FreshRegister`'s restore after a +failed attempt) — the commands, the +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 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 +the workstation and on the dev phone (§5). The sleep inhibitor for a call +(1.2.5, §7.6) is all in the shell (`HoldSleepOff` and its callers); +what of it ran against a stand-in logind on the workstation and what on +the dev phone is in §5. The registration through a +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. 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. 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 seeding and the TP-MR file, the routing of an inbound MESSAGE @@ -251,11 +304,43 @@ What the suites pin: - `Util` — tokens, IPv6 detection and host/port formatting, the RFC 5952 §4 form (the RFC's §4.1–4.2.3 examples, idempotence on `inet_ntop`-shaped - text, what is refused), the address-list parser, hex/base64, MD5. + text, what is refused), the address-list parser, the count of seconds + a setting names (`WholeSeconds`: digits and nothing else; a sign, a + unit, a fraction, a blank, `0x1e`, `1e2`, `nan`, `inf` and a number too + large are refused), hex/base64, MD5. - `Aka` — the AKAv1-MD5 digest, identity derivation, the `qmicli`/`mmcli` - text parsers, the AUTHENTICATE APDU and its response parser. -- `Ipsec` — the exact `ip xfrm` argv lists for the SA pairs, the - Security-Server mechanism selection, the SA reader, the SA peer + text parsers, the AUTHENTICATE APDU and its response parser, the class + byte of a command on a logical channel (the channel itself for 0 to 3, + `4X` for 4 to 19 — TS 102 221 10.1.1; AUTHENTICATE on channels 3 and + 4, GET RESPONSE on channel 7); the ISIM application of a slot (a card with a `ready` USIM and + a `detected` ISIM in one slot, in either order — the applications, states + and AIDs the fp6 journal's probe read off a reporter's card, 2026-11-23, + in the lines qmicli prints for an application —; another slot's ISIM not + taken, a twelve-byte AID, a CSIM, a missing state line) and the slot of + a line whose number does not parse, the SELECT and the READ + commands byte for byte on standard and extended channels, a card's answer + and its follow-up (`61 XX`, `6C XX` to a read and to a command with + data, an error, data with `61 XX`; `91 XX` and `92 XX` normal endings, + `90 01` and `93 00` none; a read's data + taken under `62 82`, not under `62 81` or `63 82`), `ParseIsimValue` (the + three length forms, the padding after the object and `FF` at the end of + its length, an unused record, another tag, a length past the data, a + blank, a line break, a NUL, an `FF` before the value's end, a byte above + ASCII) and `IsimIdentity` (names unlike the derived ones, the derived + ones themselves, and what is refused: a private identity without an `@` + between two parts, a domain that is not labels of letters, digits and + inner hyphens or that has a label of 64 characters or 254 characters in + all, a public identity that does not begin `sip:` or + is that alone, a private or a public identity of 256 characters, a + quote, a backslash, an angle bracket, a blank or a line break in one of + the three). +- `Ipsec` — the exact `ip xfrm` argv lists for the SA pairs, the `EALG` + setting, the Security-Server mechanism selection against one offered + cipher and against two (KPN's entry and Odido's, O2's six with the SPIs + on the null entry and on the aes-cbc one, a list whose every entry + carries them), the SA reader (the entry it + rebuilds names the pair's integrity algorithm and cipher, read from the + lines the kernel prints for them), the SA peer (`SaPeer`: the one address a reqid-1 and a reqid-2 `dir out` transport policy both name with imsd's protected port as the selector's sport — the fingerprint —, the pair kept beside a VPN's policies; @@ -267,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 @@ -281,7 +373,13 @@ What the suites pin: TLVs) and the error names (OutOfCall, NoEffect, an unknown code as `?`). - `Messages` — the outgoing SIP messages: the initial and the protected REGISTER, the reg-event SUBSCRIBE and the INVITEs byte-for-byte, their - variants, the in-dialog requests, the ACKs, the CANCEL and + 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 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 responses `CallMachine` builds with it); the @@ -293,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 @@ -330,7 +442,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 @@ -362,17 +476,54 @@ 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, DTMF — sent to the leg on an active call that negotiated + 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 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 - network terminated); and SMS over IP (TS 24.341): `SmsOutbound` through a + network terminated; the look after a local wait: 5 s after the + refusal is reported, and the time a sleeping phone is to be woken for + it, 10 s to 15 min by value, counted for no packet service from the + modem's first such word since the network's last answer and for the + kernel's refusals (the kind of a refusal that names none) from the + first since the modem was last without service or the network last + answered, where what starts a count over is the shell's word of an + answer, a refused reconnect, a refused or throttled fresh attempt or + a terminated binding, and not a silent cycle or attempt (a success + starts everything over); a step that + follows no local wait, and a + registration written off meanwhile, at the policy's own time) and + `WakeAt` (when the phone has to be awake for imsd: now while a call + or a text is in flight; with a registration on a live flow the + refresh's due time or the subscription's renewal, whichever comes + first; with a dead flow under a registration the recovery's word, + a due step as now; never where nothing waits); + and SMS over IP (TS 24.341): `SmsOutbound` through a submission — the MESSAGE with the RP-DATA to the SC's PSI, its 202, the RP-ACK ending it as sent with the SC's time stamp; a refused final; an RP-ERROR with its cause and TP-FCS; the final's wait and the report's @@ -460,19 +611,17 @@ Rules: named here. The known gaps: the reg-event subscription schedule (the arming and KPN's `noresource` closure have run on hardware, the 60 s retry only on a - pre-fix build that renewed that closure; the retry on this code, the - renewal firing, Timer F, the doubling, a SUBSCRIBE `Retry-After`, the + pre-fix build that renewed that closure, and the renewal firing on + the workstation, with the boot clock set ahead, 1.2.5's record below; + the retry on this code, Timer F, the doubling, a SUBSCRIBE + `Retry-After`, the renew arm and the back-off's survival across a refresh have run nowhere — - §3, §7.4); a `Retry-After` on a REGISTER has run in the field (one - report, a screenshot of 2026-10-08, O2, 0.3.10: a refresh's Retry-After - set the next step's time — `in 7 min`, then `in 13 min` — and the - refusals counted; the wait's length went unmeasured, the journal lines - on the screenshot carry no timestamps; KPN's refusals, all 403, carry - none) and a `Dial` bringing a recovery step + §3, §7.4); a `Dial` bringing a recovery step forward (imsd-ofonod refuses the `Dial` itself and imsd-dialerd forwards - it) is pinned in `tests/Engine` only; a 401 to a reregistration (the - refreshes KPN accepted were never challenged — consecutive CSeqs on every - bench — and O2 has not run this shape) and + it) has run on the workstation in a coverage gap, where the step it + brought forward was the look at the modem (1.2.5's record below); one + that brings a reconnect, or a fresh attempt that is due, forward is + pinned in `tests/Engine` only; the escalation by one refused refresh that carries a `Retry-After` — the escalation to a fresh registration is pinned in `tests/Engine` only; a resume echoing a multi-mechanism Security-Server list on the wire (the @@ -480,34 +629,77 @@ Rules: list; KPN's has one mechanism, so on the bench the stored value and the rebuilt one are the same bytes; O2's six-entry list has not resumed on this code, and the state-file round trip is shell code no test - reaches); a Security-Server list `PersistState` writes empty (one with + reaches); a resume whose rebuilt entry names another algorithm than + `hmac-sha-1-96` or another cipher than `aes-cbc` (pinned in `tests/Ipsec` + on the lines `ip xfrm state` prints; no such pair has been resumed on a + network); a list that marks one of two offered ciphers (pinned in + `tests/Ipsec` with two of O2's recorded lists, each its answer to an + offer of one cipher, and run against a stand-in P-CSCF that marks the + lower-q of the two as far as the `SA:` line; no capture holds O2's + answer to imsd offering two); the default offer's null cipher taken + by a network (KPN named `aes-cbc` to the two-cipher offer at a fresh + registration and answered a reregistration that carried it 200: the dev + phone, 2026-11-22, an earlier build of this change, on 1.2.0; the + selection of a null entry is pinned in `tests/Ipsec` with Odido's answer + of 2026-07-13 to the Python stack's offer of the null cipher and ran + against a stand-in P-CSCF on the workstation as far as the `SA:` line; + no capture holds a registration of imsd's over a null SA pair); an + ISIM's identity and an AKA in an ISIM (1.2.3; the dev phone's card has no + ISIM: the daemon ran its registration on the workstation against a + stand-in for qmicli and a stand-in network that answers a first REGISTER + of any other names than its subscriber's 480 and tells the two + applications' answers to the challenge apart — the fp6 journal's + `2026-11-23-isim-identity` capture, 46 scenarios: a card without an + ISIM, an ISIM that holds names of the operator's own and one that holds + the derived names, `ISIM=0`, another slot's ISIM, an ISIM listed `ready` + or with no state; an ISIM that gives no identity (no channel, no answer + to a SELECT, to a read or to the GET RESPONSE after one, no EF_DOMAIN, + a refused read, an + unused or a `tel:` first record of EF_IMPU, a private identity without + a realm); reads answered `6C XX` or `61 XX` first, one after the other, + or `61 XX` to every GET RESPONSE (two are sent, then the read counts as + failed), reads that end `91 XX` or `62 82`, and a length that counts + the padding in; channels 4 and 5; an ISIM that refuses the AUTHENTICATE + or answers a + synchronisation failure, the USIM asked after it; no application giving + a result (both refusing; a USIM with no channel, with an answer of one + byte, of bytes that are no result, with no answer to the AUTHENTICATE + or to the GET RESPONSE after it); the registration + made again over UDP; a second bring-up in one run at which the ISIM + gives none; resumes — of a registration of a card without an ISIM, of + one made under the ISIM's names, with and without `ISIM=0` at the + restart, of one 1.2.2 made under the derived names on a card whose ISIM + holds others (kept under the derived names; refused by a network that + knows the card's names only, and registered fresh under those), of a + state file whose identity fails the check, with a fresh target and + without (also under a forced `SIP_TRANSPORT` that is not the file's), or + lacks one of the three names — and, in a run that resumed, a + fresh registration the network refuses (the reconnect after it goes out + 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. 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, 2026-10-11); a state write of a standing registration after a fresh - attempt that aborted before its SA setup (`RegState::securityServer`, - not the attempt's `ss_` — on KPN the old SA's retry after a throttled - attempt is refused 403, the throttled-attempt chain below, so no such - write follows here); the window that leaves a state file naming another + attempt that had its 401 and aborted before its SA setup + (`RegState::securityServer`, + not the attempt's `ss_`: since 1.2.5 the write is made when a + re-REGISTER is sent, so on KPN it follows the old SA's first retry + after a throttled attempt, which KPN has answered 403, 2026-10-03, and + 480, 2026-11-25; no daemon that writes at the send has had a throttled + attempt); the window that leaves a state file naming another SA pair than the kernel's (a stop or a crash between a fresh attempt's SA setup and its 200's state write — the check is pinned in `tests/Ipsec` and ran on a hand-edited list, 2026-10-11; the window itself is not - staged); a - refused initial or fresh - REGISTER (403, 5xx) at bring-up or in recovery (KPN has only throttled or - stayed silent — pinned in `tests/Engine` only); the write-off of the old + staged); the write-off of the old registration by a recovery's fresh attempt that fails past the SA setup (such attempts are on record only as a bring-up's fatal exit, which does - not pass that arm — pinned in `tests/Engine` only); the escalation by - two refused refreshes that carry no `Retry-After` (KPN refuses a refresh - only with the 403 that says the registration is gone — pinned in - `tests/Engine` only); of the throttled-attempt chain in recovery (a - throttled fresh attempt, the old SA retried once meanwhile with the stored - binding's Contact and refused 403, the deferred attempt accepted at the - hold's end — run 2026-10-03 on the series as it then stood) the deferred - attempt made by the - same process, since a restart inside the hold made it from the holds file - instead (the same process made it on 2026-09-24, on the build before the - policy's rework); the address moves + not pass that arm — pinned in `tests/Engine` only); the address moves writing `old_gone` to the holds file (the move benches predate that field); a SUBSCRIBE final read inside a REGISTER wait (KPN answers within the second); the shell's handling of a NOTIFY that terminates our own @@ -517,11 +709,17 @@ Rules: error, a bind() refused while the address is still on the link — which no bench reaches without fault injection (§3); a coverage gap on the air (no bench stages a radio gap without an RF shield) — the packet-service - read's rule has run through a fake `mmcli` only (2026-10-03: `searching` - and `detached` not counted, `connecting` with `unknown` counted), its - other states, ModemManager not answering and its second site (a refresh - unanswered over a reconnected flow) not at all, and `tests/Engine` pin - nothing of it; the REGISTER wait's diverting arms — a response to + read's rule has run through a fake `mmcli` (2026-10-03: `searching` + and `detached` not counted, `connecting` with `unknown` counted; the + bench of 1.2.5's record below: `searching` with `detached`, + `registered` with `attached`) and against the dev phone's own + ModemManager (2026-10-03: `connected` with `attached`, two silent + cycles counted); the read that follows a refresh unanswered over a + reconnected flow has found no packet service on no run (`refresh + unanswered while the modem reports no packet service`); and + `tests/Engine` + pin what the policy does with the modem's word, nothing + of the read; the REGISTER wait's diverting arms — a response to another transaction ignored, a provisional restarting the wait, a request (an INVITE among them) dispatched and answered under the wait; an incoming call answered from a session's @@ -529,7 +727,9 @@ Rules: session, or GNOME Calls' `Answer` through imsd-ofonod's gate (imsd's own `Accept` gate has run: refused for an account without a seat session and for nobody, accepted for root, 2026-10-04); a refused - final carrying reason headers (KPN's 403s carry none — the rendering is pinned + final carrying a `Warning`, a `Reason` or a `Server` header (KPN's 403s + and 482s carried none, its 480s of 2026-11-25 a `Retry-After` and no + other — the rendering of the three is pinned in `tests/Sip` only); an `AUDIO_USER` pin in imsd's own environment that names no account (the logind fallback) or an account without a PipeWire socket (a silent call) — a pin naming an account with one ran, 2026-10-04. @@ -844,6 +1044,387 @@ Rules: phone the 401 of the fresh registration came from KPN, whose 401 of 2026-07-18 had its WWW-Authenticate over four lines (§13; the fresh one was not dumped). +- A call whose client flow is found dead before any response to its + INVITE (§7.6, 1.2.4). + The machine's side is pinned in `tests/Engine`; the shell's + (`MaybeResendInvite`) ran on the workstation against a stand-in network + (2026-11-24, the fp6 journal's `2026-11-24-crlf-keepalive` capture, + `bench/bench-dial.sh`: the daemon in dev mode, its card and modem reads + answered by stand-ins, a Dial put on its bus 25 s after the + registration, a network that answers a delivered INVITE 486 and can + drop a flow in several ways). On a flow the network had forgotten, + which it reset at the INVITE's bytes, the flow was reopened and the + INVITE delivered in the same second, the call ending `refused-or-busy` + as on a live flow; 1.2.3's call there ended `error` 100 s after the + Dial. The same outcome where the network closed the flow at the INVITE + and no acknowledgement of the daemon's own close reached it (what the + close without a FIN's exchange is for). Where the flow died on the + daemon's side at the kernel's retransmission limit, the first INVITE + never delivered, the second went out about 2 s after the death was + found and the call ended the same way. Where the network took no new + connection (it refused the reopen's connect), where it reset the + reopened flow at the second INVITE, and where a reg-event NOTIFY had + ended the binding before the reset, the call ended `error` within a + second of the Dial. Over UDP an ICMP port unreachable ended the flow: + the INVITE went out once more and the call ended `error` at the second + ICMP. On the dev phone (KPN, the same day, the capture's `phone3/`, the + binary of 1.2.4): a call to voicemail answered and hung up; and one + whose flow was made to die under the INVITE before the INVITE left the + phone (every segment of the flow dropped on the phone, five in all, and + the kernel's retransmission limit lowered for the moment; nothing of + the old connection's end went to the P-CSCF): the flow was reopened + from the same port, the INVITE went out again 2.1 s after the death was + found, and the call was answered 0.2 s after that. Not met by a call: + a P-CSCF that had dropped a flow's state, and one that had received + the first INVITE before the flow died; a reopen's connect that gets no + answer at all; the emergency chain on a network. +- The firewall's rule for ESP (§7.3, §13; 1.2.4) is the bring-up script's, + which no suite reaches. The script's firewall block ran by itself on the + workstation against nftables (2026-11-24 and -25, the fp6 journal's + `2026-11-24-incoming-dropped-without-ping` capture, + `bench/bench-esp-rule.sh`: two network namespaces, an ESP transport-mode + SA pair between them, the dev phone's ruleset as read from it loaded in + the one that stands for the phone, the connection tracker's generic + timeout at 8 s, plain TCP both ways and no imsd). 1.2.3's block left the + ruleset as it was, and a connection the network's side opened to port + 45062 11 s after the phone's last packet got no answer: its three ESP + packets were new to the tracker and none passed the chain. This script's + block inserted the rule (`nftables: accepting ESP on qmapmux*`; a second + run inserted nothing), and the same connection, 11 s after the last + packet, was accepted. An ESP packet whose SPI no SA has passed the chain + and was dropped by the kernel (`XfrmInNoStates`); a connection through + the SA to another port got no answer, its SYNs dropped by the chain + after decapsulation. On that ruleset without imsd's rules the block + inserted all three above the chain's own; with no `inet filter` table it + did nothing. After the ruleset was loaded again from its file the + script's rule was gone and the connection unanswered again; a file that + carries the rule kept it. ESP on another interface was not accepted and + neither was an AH packet; ESP over IPv4 on `qmapmux0.0` was accepted, + and ESP on a second `qmapmux` interface. On that ruleset without imsd's + rules, as the block left it, connections to both ports were accepted. + Eleven faults put into the block one at a time, ten in its rule for ESP, + that rule's check and its journal lines and one in a port rule, were + each caught by a step (`bench/run-mutations-esp.sh`). + `bench/bench-esp-pinhole.sh` there has the gap without the script: the + network's connection accepted a second after the phone's own exchange + and under a packet of the phone's every 3 s, and unanswered 11 s after + the last packet. On the dev phone (KPN, the capture's `phone/`), under a + daemon that sends no ping (the binary of 1.2.4, no `CRLF_KEEPALIVE`): + the tracker's entry for the P-CSCF's ESP was read counting down after a + refresh (575 s left 23 s after it, 15 s left 9 min 43 s after it) and + was gone 10 min 29 s after it (2026-11-24); the script, run at imsd's + start, inserted the rule above the two port rules it found, and the + daemon resumed its registration (2026-11-25). Then a text was sent to + the phone's own number with the tracker's timeout at 0 for the test, so + that every ESP packet from the network came without an entry: with the + rule, six such packets came, and the answer to the MESSAGE, the submit + report and the text's delivery reached the daemon within a second; with + the rule taken out, 23 came in 20 s and none of the three reached the + daemon in those 20 s. Not met: a request the network starts after the + entry has lapsed of itself, 600 s after the phone's last ESP packet (a + call to the phone from another line). +- The idle flow (§7.2 step 5; no CRLF keepalive unless `CRLF_KEEPALIVE` + names an interval, 1.2.4) is shell code no suite reaches; how the + setting's value is read is `WholeSeconds`, pinned in `tests/Util`. The + loop ran on the workstation against a stand-in network that prints + every ping and can close a flow it has heard nothing on, or forget it + and answer the next bytes on it with a reset (2026-11-24, the fp6 + journal's `2026-11-24-crlf-keepalive` capture, + `bench/bench-keepalive.sh`: the daemon in dev mode, its card and modem + reads answered by stand-ins). Left alone for 100 s after its + registration the daemon sent no ping, 1.2.3's three, and with + `CRLF_KEEPALIVE=10` nine, behind its start line (§7.8); over UDP with + that setting it sent none and no empty datagram; with + `CRLF_KEEPALIVE=0` and with an empty value it sent none and logged + nothing of the setting; with `CRLF_KEEPALIVE=30s` it logged the value + as not understood and sent none. A network that closes a flow after + 45 s of silence closed two in 130 s, each reconnected and re-registered + in the same second; it closed none under 1.2.3's pings or under + `CRLF_KEEPALIVE=30`, and one that closes after 60 s none under a refresh + every 40 s. A network that forgets a flow after 45 s of silence reset + the refresh that came at 60 s, twice in 140 s: `keepalive re-REGISTER + failed: no reply to re-REGISTER`, then the reconnect and the + registration in the same second; under `CRLF_KEEPALIVE=30`, as under + 1.2.3's pings, it forgot none and answered both refreshes; one that + forgets after 20 s reset each of 1.2.3's three pings, and each was + followed by the reconnect. Under a call the daemon had placed and + hung up 30 s later, a network that forgets a flow after 20 s of + silence reset the BYE's bytes, and one that closes it after 20 s had + closed it: in both the BYE was not delivered, the call ended + `local-hangup — HangUp; BYE sent`, and the recovery reconnected as + soon as the call was gone; 1.2.3's BYE was lost the same way on the + forgetting network (the fp6 journal's `2026-11-24-bye-resend` + capture, `bench/bench-hangup.sh`, the scenarios named `-not-resent` + and `hangup-forgotten-before`; §7.6). + On the dev phone (KPN, the same day; its + ModemManager has the WDS event reports off while the phone sleeps, + §13), with the binary of 1.2.4 (the capture's `phone3/`): no packet on + the ims netdev in two idle minutes, where 1.2.3 put one each way every + 30 s (`phone/`); with `CRLF_KEEPALIVE=30` the start line and a packet + each way every 30 s; with `CRLF_KEEPALIVE=30s` the line for a value not + understood and no packet. With builds of this change from before the + call's resend (two bullets above) was put under it (`phone2/`, + `phone/`): the netdev's counters stood still for the 1800 awake seconds + to the refresh, which the P-CSCF answered on the flow, silent until + then (no reconnect), twice; and two loops of deep suspends with a 150-s + alarm had no packet on the netdev, of seven sleeps (five ended by the + alarm, one after 9 s by the ADSP's battery manager, one after 98 s by a + file-system request of the modem's that no packet had preceded) and of + six (five ended by the alarm, one after 99 s by the ADSP's battery + manager). Not met: a real network that closes or forgets an idle flow; + a flow that dies with neither a close nor a reset; a reg-event + SUBSCRIBE as the first bytes on a forgotten flow; an incoming call + whose BYE is the first bytes on such a flow; an incoming text whose + delivery report is the first bytes on such a flow. A text's MESSAGE as + the first bytes on a flow the network had dropped was met once, in the + firewall's test above (2026-11-25): the phone had dropped the P-CSCF's + packets for 20 s, a text's first MESSAGE had gone unanswered for that, + and its repeat, 128 s on, was the first thing imsd sent on the flow + since. The flow was found dead 0.3 s after the repeat went out, the + recovery reconnected and re-registered 0.2 s after that, and the text + ended `failed`, its repeat lost with the flow. +- The CSeq of a re-REGISTER (§7.2 step 5) is the shell's, and no suite + reaches it. On the workstation the daemon ran against a stand-in network + that keeps the highest CSeq of the protected REGISTERs it has taken + per Call-ID, answers a protected REGISTER + that is not higher `482 Loop Detected`, and can take one refresh + without answering it or refuse one (the fp6 journal's + `2026-11-25-refresh-answer-lost` + capture, `bench/bench-cseq.sh`): after a refresh whose answer is lost + the reconnect's re-REGISTER carries the next number and is answered + 200, where 1.2.4's carried the lost one's, was refused twice and + registered fresh; a daemon killed under the wait resumes with the next + number, the state file having it, where 1.2.4's resume was refused and + registered fresh; after a refresh the stand-in refused (503) the + reconnect's re-REGISTER carries the next number, where 1.2.4's carried + the refused one's again (the stand-in keeps no number for a REGISTER + it refuses, and answered both 200). On the dev phone (KPN, + 2026-11-25, this commit's + daemon; the fp6 journal's `2026-11-25-through-sleep` capture, + `phone/cseqtest-2-a`), with the firewall's rule for ESP taken out and + the connection tracker's generic timeout at 0 around a refresh, so that + its answer was dropped: `keepalive re-REGISTER failed: no reply to + re-REGISTER`, and `reconnected + re-registered` 10 s later. Not run: the + number after a re-REGISTER whose send failed; a re-REGISTER's answer + lost over UDP; a restart after a daemon was told to stop (SIGTERM) + under the wait, where the bench kills it; a resume whose REGISTER gets + no answer; a state file torn by a kill during its write; and what a + network makes of a number that skips one, as a REGISTER that was sent + and never arrived leaves it (the stand-in took one; no phone run tells + whether its network saw one). +- The call's sleep inhibitor (§7.6) is the main thread's code, and no suite + reaches it. On the workstation the daemon ran with a stand-in logind + on the bench's bus, which prints every `Inhibit` and every lock's + release and refuses every `Inhibit`, with logind's + `OperationInProgress` error, while a file says a sleep's + operation runs (the fp6 journal's `2026-11-25-through-sleep` capture, + `bench/bench-sleep.sh`): one lock per call, taken within 1.5 s of the + `Dial` and released within 1.5 s after the call's end, for a call + answered and hung up, a call the network refused and two calls in a + row; a call placed while the stand-in refused had its lock within + 0.5 s of the stand-in's `PrepareForSleep(false)`; with no logind on + the bus the call ran as with one; 1.2.4 asked for no lock. On the dev + phone (KPN, systemd 262.2, Plasma Mobile, the sleep targets unmasked + for the test; `phone/` there), under a + call to the carrier's voicemail placed on the bus: imsd's lock the + only block inhibitor for sleep in `systemd-inhibit --list`, none in + the list of PowerDevil's policy agent, `systemctl + suspend` answered `Operation denied due to active block inhibitor` and + no suspend counted, the lock gone after the hang-up; and for a call + placed from a sleep hook at a resume, with logind's operation still + running: the refusal's line, and the lock when logind had said the + sleep was over. Not run: a suspend under a call without the lock; an + incoming call that wakes a sleeping phone; a call announced before + the bus connection is there; a request at a second row's addition or + removal (a Dial refused under a call that has no lock); a second + refusal before a lock is given, which prints no line; an answer of + logind's without a descriptor; a `PrepareForSleep` whose argument is + not one boolean; a Dial refused under a call that has its lock, which + asks nothing, and what logind signals after a suspend told to ignore + inhibitors under a call (the next entry has such a suspend; its run's + log has the lock listed before and after it, and no line of logind's + for the signal); a desktop's own request for a suspend under the lock. +- The registration through a sleep (§7.10) is shell code but for + `WakeAt` and the recovery policy's wake after a local wait, which + `tests/Engine` pins. On the workstation + (`bench/bench-sleep.sh` of the capture above) the bench's sleep is a + preloaded `clock_gettime` under which the boot clock runs ahead of the + steady clock by the seconds a file names: with the boot clock 50 s + ahead a refresh set for 60 s went out 20 s into the registration, and + 1.2.4's did not; with it 599500 s ahead the reg-event subscription was + renewed, and 1.2.4's was not; with no jump the refresh came at its + awake time and not before. The second lock was taken and released + around a refresh, asked for again at the stand-in logind's + `PrepareForSleep(false)` where that had refused it at a refresh's + start, and held from a text's sending to its `failed` where the + stand-in network answered no MESSAGE (256 s). In a gap of 40 s + (the stand-in modem without packet service, no SYN let through, the + flow closed by the network) no connect was tried and no lock taken, + the modem was asked every 5 s, the daemon's own processor time + stayed under a second (an earlier build, which kept the dead flow's + socket through the gap, used 33.9 s of it), and the reconnect came + 3 to 5 s after the gap's end; a `Dial` inside such a gap ended at + once, with nothing reopened under it, and the reconnect then came + 0.5 to 1.5 s after the gap's end. In a gap of 70 s that let no + segment through, the daemon had no socket of the old flow at the + gap's end, and the reconnect came 3 to 5 s after it, 0.5 to 1.5 s + where a `Dial` had been tried inside the gap. A + daemon started inside a hold of 60 s held no lock for + it. With `WAKE_TRACE=1`, a test seam, the daemon writes a line + whenever the time the alarm is armed for changes (by the second; one + line for a run of times less than two seconds ahead), with a timer + or without: in a gap + that a refresh ran into, with the boot clock put 1000 s ahead inside + it, the alarm named 900 s ahead; after the gap's end, where the old + flow's socket had two connects refused, it named no more than 30 s + ahead, and the reconnect came 15 to 16 s after the gap's end; and + where the stand-in modem reported service twice inside such a gap, + the alarm named 900 s ahead again after each. Where the modem still + reported service when the refresh failed, where the network stayed + silent for 80 s after the modem's return (two silent cycles, then a + fresh registration) and over UDP, the alarm named no more than 30 s + ahead from the modem's return to the recovery. While a step waited + for the network (a refresh's 12 s without a reply, a connect's 12 s + without an answer and the 10 s before the next try, a fresh + registration's two waits with the stand-in network holding its + answers back) the alarm was named a new time every second, and + through the connect for a call's resend it was named no time 2 s or + more ahead. Stopped 1.5 s into a fresh registration's wait for its + first 401 and continued 2 s later (a stop and a continue end a + datagram receive under a timeout as a suspend's freeze does, §13), + the daemon + registered when the stand-in's held-back 401 came, five runs of five; + an earlier build and 1.2.4 gave the wait up at the continue, five of + five each. The bench's + namespace gives no `CAP_WAKE_ALARM`: every life of this daemon there + says `no wake + alarm (Operation not permitted)` and runs on. The alarm is the dev + phone's (KPN, a 7.3 kernel, this commit's code under the next + commit's version string, `phone/` there, 2026-11-28), with + `REFRESH_INTERVAL=120` and deep suspends asked of logind: every + refresh that fell due under a sleep went out within 3 s of its due + time, after a resume whose first interrupt was the RTC's alarm + (1.2.4, in three sleeps of that script as it was on 2026-11-25, on + the same kernel build, sent no refresh in seven minutes); seven + recovery steps that fell due under a sleep ran 1.5 to 3 s after + their time (an earlier build, 2026-11-25); under a call a suspend + told to ignore inhibitors was refused by the kernel (`alarmtimer`, + -16), twice, systemd-sleep having tried its second state; and under + a refresh whose REGISTER the phone itself dropped, such a suspend a + second into the wait was ended by imsd's alarm (the RTC's the first + interrupt, 30.6 s in), after which imsd's timer, zero at the test's + first look, read 29 to 30 s ahead at each of its 32 looks from 0.2 s + later to the wait's end, which the test saw about 10 s after that + first look (an earlier build, which set the alarm once + for the wait, read zero at every reading until the wait had ended; + in another run, with two more such suspends in that wait, it slept + to the test's own alarm of 75 s both times). The re-registration + after that refresh came 71 s after its `no reply`, the kernel + refusing nine connects over a minute first (the old flow's socket, + §7.10). Not run: a + suspend under a fresh registration's first wait with the daemon on a + phone (the receive's `EINTR` at a resume was seen there with a test + program, §13); an alarm clock with no RTC behind it (`no RTC that + can wake the phone`), and a `timerfd_settime` that fails (`wake + alarm not set`); the alarm's disarming and `wake trace: none`, + which nothing reaches once the loop runs; a second suspend told to + ignore + inhibitors under one wait with this daemon on a phone (the dev + phone is not to be suspended within ten seconds of a resume: the + earlier build's run with three did so, and its wifi firmware + crashed; and the wait the test stages, an unanswered refresh's + 12 s, is over at about that time); the 1.9 s through a connect for + a call's resend that waits (the bench's is answered at once); a + fresh registration's look at the modem finding no packet service + (the reconnect's has run); a bring-up the network defers or refuses, + and a stop during a bring-up's hold; the work's lock asked for at + the bus connection's coming (no record tells that request from the + step's own); a coverage gap on a + phone, and the wake for its slower look; on a phone, a sleep longer + than a refresh interval of 1800 s; the alarm at most 30 s ahead + 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. +- 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, @@ -923,7 +1504,9 @@ the status snapshot live (main thread only). The Messaging interface's `Subscribe` keeps its subscriber set on the main thread as well, and `List` and `Delete` read and unlink the received-message store there while the engine thread writes it — safe through the `.tmp` + `link(2)` publish -(§7.9). +(§7.9). On the same bus imsd is a client of logind's +(`org.freedesktop.login1`): the main thread takes its sleep inhibitors +there and listens for its `PrepareForSleep` (§7.6, §7.10). Per answered call imsd forks `imsd-media` (`IMSD_MEDIA`, default next to the `imsd` binary, else `/usr/libexec/imsd-media`) with the addresses, ports and @@ -983,7 +1566,7 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): registration is due or a binding a NOTIFY terminated under the attempt write the registration off — either way the pair counts as one nothing can resume. A pair nothing can resume (its UE address left the link, no - state file, a file another attempt left behind, written off before this start or + state file, a file another attempt left behind or whose identity fails the check, written off before this start or given up by the engine during the attempt) is written off (`old_gone` in the holds — written as well for a pair `RESUME=0` leaves untried) and taken out of the kernel first (`the SA pair to … is nothing to resume: removing @@ -992,7 +1575,37 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): 2. `qmicli -d qrtr://0 --uim-get-card-status` finds the ready USIM (slot, AID); `mmcli -m any` gives the primary SIM path and the IMEI (for the `+sip.instance` URN); `mmcli -i ` gives IMSI and MCC/MNC, from which - the IMPI/IMPU/realm are derived; with SMS over IP on and `SMSC=` unset, + the IMPI/IMPU/realm are derived (TS 23.003 13.2 to 13.4B) — the names + of a UE without an ISIM (TS 24.229 5.1.1.1A). Since 1.2.3, unless + `ISIM=0` is set, a card with an ISIM application in the USIM's slot + (`ParseIsimApp`, in whatever state the modem lists it) is asked for the + identity that ISIM holds: over a logical channel on the application imsd + reads EF_IMPI (the private identity), EF_DOMAIN (the home domain) and + record 1 of EF_IMPU (the public identity to register, GSMA IR.92 2.2.1), + each with a SELECT by file identifier and a read, and takes the three + when `IsimIdentity` accepts them (`identity: the ISIM's (application + state …): …`, with whether they are the names the IMSI gives). Then the + ISIM is asked for the answer to the challenge (step 4). When the card + has no ISIM, when `ISIM=0` is set, or when the ISIM gave no identity, + the derived identity and the USIM stand, as in 1.2.2, + and the `identity: derived from the IMSI …` line says which of the three + and, for the last, what was missing (§7.8). The read is made at every + bring-up of such a card, a resume's too, and at each recovery by a + fresh registration later in the same run (`FreshRecover`) while no read + since the bring-up has given one. That is the card's identity, and a fresh + registration is made under it. A resumed registration keeps the one it + was made under until its next fresh registration, as it keeps its + P-CSCF and its address (step 3): the state file records the three names + since 1.2.3, and a file without them is taken for one made under the + derived ones (`identity: the registration to + resume was made under …; it keeps them until the next fresh + registration, which takes the card's` when they are not the card's; + `identity: the fresh registration takes the card's: …` when that + registration comes under other names, and after an attempt that fails + the names are back that stood before it). The registration's home + domain is also what `RuriFor` and `ScPsi` take, for an outgoing call's + Request-URI and for the service centre's address of an SMS submission + (§12). With SMS over IP on and `SMSC=` unset, `qmicli --uim-read-record` of EF_SMSP record 1 names the service centre (§7.9). `mmcli --location-get` fills `P-Access-Network-Info`. @@ -1050,14 +1663,65 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): route (imsd's own `ip -6 route replace`; step 3 says which target), an unprotected REGISTER on `PCSCF_PORT` (UDP, always), the 401 with the AKA challenge and the `Security-Server` list, the AKA run over a UIM logical channel - (`--uim-open-logical-channel`, `--uim-send-apdu`), the SA pair installed + (`--uim-open-logical-channel`, `--uim-send-apdu`) — in the ISIM when the + card's identity was read from it, else in the USIM; the command is the + same (AUTHENTICATE with P2 `81`: the 3G context of TS 31.102 7.1.2, the + IMS AKA context of TS 31.103 7.1.2), and an ISIM that gives no result + is followed by the same challenge to the card's USIM (`AKA: the ISIM + application gave no result (…); asking the USIM`). TS 24.229 5.1.1.1A + has the ISIM used for authentication whenever the card has one: with + `ISIM=0`, with an ISIM that gave no identity and behind one that gives + no result imsd asks the USIM —, the SA pair installed with `ip xfrm`, the protected REGISTER over the negotiated transport (§10.1, `SIP_TRANSPORT`), `REGISTERED (fresh)`. Then the reg-event SUBSCRIBE (§7.4). -5. A keepalive re-REGISTER refresh at half the granted lifetime, within - 120–1800 s (`REFRESH_INTERVAL`), only while idle. The refresh of a +5. A keepalive re-REGISTER refresh at half the granted lifetime (of + 3600 s where none was granted), within + 120–1800 s (`REFRESH_INTERVAL`), only while idle; the time runs + through a suspend, and a sleeping phone is woken for it where imsd + has its wake alarm (§7.10). + Besides it an idle + phone whose registration stands sends what its reg-event subscription + needs (§7.4). The CRLF keepalive (RFC 5626 4.4.1) imsd sent every 30 s + until 1.2.3 is off unless `CRLF_KEEPALIVE` names an interval in whole + seconds (a TCP flow's only; an empty value is as none, any other that + is no whole number is reported and sends none; §13 has what a ping + costs a phone). No registration of imsd's negotiates keep-alives: its + REGISTER has no `outbound` in `Supported` and no `reg-id` (RFC 5626 + 4.2.1), and no `keep` in the Via (RFC 6223), which TS 24.229 5.1.1.2.1 + d) has a UE offer unless it is configured not to send keep-alives or + is directly connected to an IP-CAN for which usage of NAT is not + defined. What a ping does for a flow, outside a call (none is sent in + one): sent more often than a P-CSCF's timer for a flow it hears + nothing on, it keeps that P-CSCF from dropping the flow, and it draws + the reset of a P-CSCF that has lost the flow. On the phone it also + kept the connection tracker's entry for the P-CSCF's ESP, which the + firewall's rule for ESP makes needless (§13). Without the ping: a + close by the network is answered, outside a call, with a reconnect + and a refresh (`client flow dead; reconnecting`, §7.4); the reconnect's + first connect can be refused, the closed flow's socket still in the + kernel's table (`connect failed; retry in 10s (TIME_WAIT?)`: a user's + log on O2, 2026-09-24), and its second follows 10 s later. A flow the + network has dropped without closing, where it answers the next bytes + on it with a reset, is found at those bytes: where they are this + refresh's, it fails (`keepalive re-REGISTER failed: …`) and the same + reconnect follows; where they are a call's INVITE, the shell reopens + the flow for the call (§7.6); where they are a call's BYE, the BYE + is lost (§7.6); where they are a text's MESSAGE, it is lost with the + flow and the text's wait decides (§7.9); where they are the delivery + report of a text that came in, the report is lost with the flow and + not sent again. A flow that died with no close and no + reset reaching the phone is noticed when this refresh's re-REGISTER + gets no answer, or sooner where TCP gives up on bytes imsd sent on it + before that (924.6 s or more after them by the kernel's default + `tcp_retries2` of 15); until 1.2.3 a ping's were among those bytes + every 30 s outside a call. The refresh of a registration this process made fresh is a reregistration as TS 24.229 - 5.1.1.4.2 has it: the same Call-ID and Contact, CSeq+1, the + 5.1.1.4.2 has it: the same Call-ID and Contact, the CSeq one above the + last REGISTER sent on that Call-ID, answered or not (RFC 3261 10.2; + the number is used, and in the state file, once the REGISTER is sent: + §13 has KPN's 482 to re-REGISTERs that, by 1.2.4's code, carried an + unanswered one's number), the Authorization of the last successful authentication verbatim (the 401's nonce, our cnonce and response, kept in the state file), a Security-Client with new SPIs and a new client port (`PortUcNext`, @@ -1074,7 +1738,7 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): `spi_uc`/`spi_us` are not the pair's, step 3), it sends — on the resume's re-REGISTER, the keepalive re-REGISTERs, the reg-event SUBSCRIBE and INVITEs, until its next fresh registration — the one - entry rebuilt from the SA + entry rebuilt from the SA, with the algorithms the kernel prints for it (`Imsd:Ipsec`, which makes the choice): KPN's one-entry answer to the default offer in the same bytes, not a list such as O2's six, which RFC 3329 §2.3.1 has the server answer with a 494 when it does not mirror its own; a refused resume registers fresh (with @@ -1087,7 +1751,12 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`): in-use SPIs) was refused with 503 (§13). The state file is JSON: `callid`, `ftag`, `cseq`, `spi_uc`, `spi_us`, -`expiry`, `route`, `ppi`, `aor`, `contact_user`, `transport`, since 1.0.0 +`expiry`, `route`, `ppi`, `aor`, `contact_user`, `transport`, since 1.2.3 +`impi`, `domain` and `impu` (the identity the registration was made under, +which a resume keeps — step 2; all three absent in an older file: the +derived identity; a file that holds one or two of them, or three that are +no identity `IsimIdentity` accepts, is not resumed: `the state file's +identity is not one imsd can register; …`), since 1.0.0 `pcscf` (the P-CSCF the registration was made to; named in the line that reports a file another attempt left behind — the check is the SPIs', `FileNamesAnotherPair`), since 0.3.12 @@ -1234,7 +1903,12 @@ configures the muxed netdev. Idempotent; a non-zero exit fails the unit. - Opens imsd's protected ports 45061–45062 (TCP and UDP) on `qmapmux*` in nftables when a `inet filter` table exists (pmOS's default INPUT chain drops inbound on `qmapmux*`, which silently killed every network-initiated - request after ESP decapsulation). Best-effort. + request after ESP decapsulation), and accepts ESP itself on `qmapmux*` + (the packet passes the chain before it is decapsulated too; §13). Each + under its own comment in the chain, `imsd-protected-ports` and `imsd-esp`, + and only where the chain has no rule under that comment. Best-effort, + and in the running ruleset only: what the script inserted is gone when + the ruleset is next loaded from its files (§13). - Writes `/run/imsd.env`: `DEV=`, `LOCAL=`, `PCSCF_DISCOVERED=` (comma-separated in the modem's order; empty when nothing was discovered or `PCSCF` is set) and `PCSCF_DISCOVERY=found|none|failed|skipped` @@ -1259,7 +1933,9 @@ configuration file's path — the bench's seam too). ### 7.4 Registration recovery (`RegRecovery`, `Imsd-Engine.cppm`) What the daemon does when the registration stops working after bring-up, as -a pure reducer the shell feeds with the clock and the network's answers. Two +a pure reducer the shell feeds with the clock, the network's answers and its +local waits (a connect the kernel refused, the modem without packet +service). Two kinds of failure reach it: a **refusal** (the network answered a refresh with a final other than 200 — a 401, re-authentication, included — or a fresh registration's REGISTER with a final other than the expected one: from 300 @@ -1278,11 +1954,12 @@ The policy, with its constants: |---|---| | Reconnect | Through the existing SA, then refresh. Back-off 5 s → 5 min (`ReconnectDelayMin`/`Max`). | | Escalate to a fresh registration | After one refused refresh whose `Retry-After` is at least a second (the network's considered answer; a `Retry-After` of 0 or one that does not parse counts as none; O2 2026-10-08: the refresh refused 503 with Retry-After 414 s, the refresh after that wait 503 with Retry-After 772 s) or a 401 (re-authentication, which imsd answers with a fresh registration rather than over temporary SAs), after two refused refreshes without one (`RefusalsBeforeFresh`), or two reconnect cycles that end without an answer (`SilentCyclesBeforeFresh`) while the modem reports packet service (`PacketServiceUp`: ModemManager's registration and packet-service state, as `ims-pdn-up.sh` reads them). A cycle that fails during a coverage gap is the phone's silence, not the network's: not counted, retried on the local-refusal pace, so a radio gap across a refresh does not escalate into a fresh registration, which KPN refuses while the registration is live and drops it for (§13). New Call-ID, new challenge, new SA pair (`registering fresh (recovery attempt N)`; with no fresh target the daemon restarts instead, §7.2 step 3). | +| No packet service | While the modem reports none (`PacketServiceUp`) the recovery tries no reconnect and no fresh attempt and holds no sleep off (§7.10; a bring-up does not ask the modem): the modem is asked again 5 s after each look while the phone is awake and no call is up (`LocalRetry`, the pause after a connect the kernel refuses locally as well), and where imsd has its wake alarm a sleeping phone is woken for the next look after as long again as that kind of wait has lasted, within 10 s and 15 min (`LocalWakeMin`/`Max`): where the modem has no service, since its first such word since the network last answered (an answered TCP connect of the resume or of a reconnect, a response to a REGISTER, a terminated binding, a success); where the kernel refuses the connect, since its first refusal since the modem was last without service or the network last answered, whichever came later. A report of service from the modem starts neither count over. A step that follows no local wait (the rows above and below) is woken for at its own time. A `Dial` on the dead flow meanwhile ends at once: nothing is reopened under it (§7.10). | | A refused or throttled fresh attempt | Waits on the **throttle schedule**: 21 min, growing ×1.5 to 60 (`ThrottleMinutesMin`/`Max`). KPN refuses a fresh SA pair on an address whose registration is live (§13), and drops that registration the moment an initial REGISTER arrives. | | A silent fresh attempt | Backs off 30 s → 10 min (`FreshDelayMin`/`Max`). | | `Retry-After` | Always wins over a shorter wait, honoured up to an hour (`RetryAfterMax`, the schedule's longest wait); a longer one is cut to an hour and the refusal heard again then. On a refused fresh attempt it replaces the schedule's wait, shorter or longer, never below 30 s (`FreshDelayMin`). | | A 403 | A refusal like the others: never hammered (the schedule), never abandoned (a SIM that is unbarred registers within the hour). | -| The old registration is gone | A 403 once a fresh registration is due, a fresh attempt that got past the SA setup, a binding the network terminated (reg-event), an older address that left the netdev, or a bring-up whose resume failed while a fresh registration follows (with no fresh target a resumable pair whose attempt failed is kept for the restart; a pair nothing can resume — given up or written off by the engine, its address off the link, no state file, a file another attempt left behind, left untried by `RESUME=0` — is written off and taken out of the kernel, §7.2 step 1): no reconnect over the old SA from then on. Otherwise the existing SA is still retried on the reconnect back-off while a fresh registration is deferred. | +| The old registration is gone | A 403 once a fresh registration is due, a fresh attempt that got past the SA setup, a binding the network terminated (reg-event), an older address that left the netdev, or a bring-up whose resume failed while a fresh registration follows (with no fresh target a resumable pair whose attempt failed is kept for the restart; a pair nothing can resume — given up or written off by the engine, its address off the link, no state file, a file another attempt left behind or whose identity fails the check, left untried by `RESUME=0` — is written off and taken out of the kernel, §7.2 step 1): no reconnect over the old SA from then on. Otherwise the existing SA is still retried on the reconnect back-off while a fresh registration is deferred. | | A `Dial` while unregistered | Brings the next recovery step forward (the reconnect, or the fresh attempt once it is due) — never a wait the network imposed (a `Retry-After`, or the schedule after a refused or throttled fresh attempt). imsd-ofonod refuses a `Dial` then and imsd-dialerd lists no modem. | | Success | Resets everything. | @@ -1296,7 +1973,8 @@ the SA setup, a binding the network terminated, an older address that left the netdev, and every bring-up that goes on to register fresh — its resume failed or there was nothing to resume; a bring-up with no fresh target writes `old_gone` when nothing can be resumed — a pair nothing can resume: its UE -address left the link, no state file, a file another attempt left behind, written +address left the link, no state file, a file another attempt left behind or whose +identity fails the check, written off before this start, given up or written off by the engine during the attempt, left untried by `RESUME=0` — never for a pair kept for the restart, §7.2 step 1); the reducer's refusal count travels too (`refusals`): a resume @@ -1323,11 +2001,16 @@ even after the holds run out, so a restart does not start it over at 21 min. When nothing is held the file is removed — when it is a regular file; `/dev/null` switches the knob off and anything that is not a regular file is emptied, never unlinked. The recovery policy's waits and the holds are -measured on the boot clock (`CLOCK_BOOTTIME`), so a suspend counts; the -keepalive refresh gate, the CRLF keepalive, the reg-event retry and -renewal timers and the times SMS over IP measures (§7.9: its two waits, -the 30-minute age-out, the retransmission table's 32 s, the submissions -table's hour) run on the steady clock and count awake seconds only. +measured on the boot clock (`CLOCK_BOOTTIME`), so a suspend counts, and +so are the keepalive refresh's gate and the reg-event subscription's +renewal ahead of its granted lifetime's end (§7.10; awake seconds in +the releases up to 1.2.4); the CRLF keepalive (where `CRLF_KEEPALIVE` +sets one), the reg-event subscription's Timer F, its retries (after a +refusal, an unanswered SUBSCRIBE, a send that failed) and its renewal +after the S-CSCF has ended it, and the times SMS over IP measures +(§7.9: its two waits, the 30-minute age-out, the retransmission table's +32 s, the submissions table's hour) run on the steady clock and count +awake seconds only. The **reg-event subscription** (RFC 3680; the network's own view of the binding) is one live dialog per registration, subscribed anew ahead of the @@ -1430,8 +2113,27 @@ 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`. + 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 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 + UE that has no TCP connection towards the P-CSCF set one up before it + sends a request. Where nothing is reopened, the connect fails (one that + gets no answer, after 12 s) or the flow dies again before a response, + the call ends with `error`. Under a call, a flow that died with no + reset and no close reaching the phone is found dead only when the + kernel gives up on bytes sent on it that were never acknowledged + (924.6 s or more after them by its default `tcp_retries2` of 15): an + attempt whose own INVITE is the first such bytes gets no response and + is cancelled at its setup deadline, long before that. A flow found dead + after a response to the INVITE is not reopened. - Incoming: an INVITE on a protected-port listener is validated before it is announced to the UI; 100 and 180 (reliable when the caller requires 100rel); `Accept` sends the 200 with the SDP answer at the offer's own @@ -1440,11 +2142,101 @@ sent, emit this D-Bus state change, arm this deadline). States and reasons are t unusable offer 488 naming what was offered; ring timeout 480. A landline gateway's G.711-only or AMR-NB offer rings and is answered at its own payload types. +- Hang-up: a BYE of imsd's goes out on the client flow, an incoming + call's too, and the call is over for imsd as the BYE is sent: the + media leg is stopped (RFC 3261 15.1.1 has the session terminated as + soon as the BYE is passed to the client transaction) and no response + to the BYE is waited for. The BYE is not kept and not sent again: on a + flow the network has closed or dropped it is lost, and the call's line + in the journal still ends `BYE sent`. A network that closes or drops a + TCP flow it hears nothing on (§7.2 step 5) can have done so by then: + under a call no ping goes out (with `CRLF_KEEPALIVE` neither), the + refresh waits for the call's end and the recovery does not reconnect. + That network's timer runs from the flow's last bytes. A call the + daemon placed restarts it with its own requests; an incoming call + sends none before its BYE, and where until 1.2.3 a ping went out every + 30 s outside a call, without the ping the flow can have been silent, + or dropped without a close, long before the call came. Shown on the + workstation for a call the daemon placed (§5); not met on a network. +- Sleep: nothing of imsd runs while the phone is suspended, so a + suspend under a call stops the daemon and the call's media leg for as + long as the phone sleeps; on the dev phone (Plasma Mobile, the sleep + targets unmasked for the test, a call placed on the bus) logind + listed one block inhibitor for sleep under a call, imsd's, and + PowerDevil's policy agent none of its own (§5). While the + calls table holds a call imsd holds logind's block inhibitor for + sleep (`Inhibit` with `sleep`, `imsd`, `a call`, `block`; + `systemd-inhibit --list` shows it): from the call's addition to the + table, which is an incoming call's announcement and for a `Dial` + follows the recovery's try on a dead flow (§7.4) and the refresh of + the `P-Access-Network-Info`, to its removal. Under it logind refused + a plain `systemctl suspend` on the dev phone (§5); a request can tell + logind to ignore inhibitors (`systemctl suspend -i`). Where it was + asked for during a suspend's operation logind refused this lock + (§13): a lock that was not given and is still wanted is asked for + again when logind + sends `PrepareForSleep` with false, and one + wanted before the bus connection was there when the connection + comes. Where logind gives none at all (`--session`: the session bus + has no logind) calls go on without one. For a suspend that is told to + ignore inhibitors there is the wake alarm: what it holds under a call + and what it does not is in §7.10. - Emergency: a number `IsEmergency` classifies (112, 911, plus `EMERGENCY_NUMBERS`; SIM `EF_ECC` is not read yet) is tried as `urn:service:sos` first, with one fallback to a plain INVITE of the digits; a plain INVITE answered `380 Alternative Service` with an emergency body is - re-attempted as `urn:service:sos`. + 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). +- 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 @@ -1544,7 +2336,35 @@ account `user`, its old default. Lines the operator (and the scripts) look for, all prefixed `imsd: `: -- `LOCAL=… P-CSCF=…`, `SIP transport: …`, `SIM slot=… IMSI=… domain=…` at start. +- `LOCAL=… P-CSCF=…`, `SIP transport: …` (behind it `CRLF keepalive: every N s on an idle TCP flow + (CRLF_KEEPALIVE)` where that setting names an interval), `ESP ciphers offered: …`, `SIM slot=… IMSI=… domain=…` at start + (the home domain of the card's identity, which the line before names); + `EALG entry '…' is not a cipher imsd can install; ignored` for a name in `EALG` that imsd cannot install, + `CRLF_KEEPALIVE=… is not a whole number of seconds; no CRLF keepalive` for a value of that setting, other than an empty one, that is no whole number. +- Before the `SIM slot=…` line, at every bring-up, where the identity is from (§7.2 step 2): `identity: the + ISIM's (application state S): private identity P, home domain D, public identity U; the names the IMSI gives` + or `…; not the names the IMSI gives (home domain D')`, `identity: derived from the IMSI (the card has no + ISIM application)`, `identity: derived from the IMSI (ISIM=0)`, `identity: derived from the IMSI: the ISIM + application (state S) gave none — …` with what was missing: `no logical channel opened on it`, `EF_X: the + SELECT answered `, `EF_X: the read answered `, `EF_X: no answer with a status + word to the SELECT`, `EF_X: an exchange of the read brought no answer with a status word` (the read or a + command the card asked for after it), `EF_X: no value in the N bytes read`, or `EF_IMPI '…', EF_DOMAIN + '…' and EF_IMPU record 1 '…' are no identity imsd can register`. At a resume whose + registration was made under other names than the card gives now: `identity: the registration to resume was + made under private identity P, home domain D, public identity U; it keeps them until the next fresh + registration, which takes the card's`; at a fresh registration under other names than the ones in use + before it: `identity: the fresh registration takes the card's: private identity P, home domain D, public + identity U`; + `the state file's identity is not one imsd can register; resume falls back to fresh` (with no fresh target + `…; nothing can resume it: the pair is removed`) for a file whose three names fail the check or that + holds one or two of them. At a recovery by a fresh registration, while the ISIM has given none since the + bring-up, it is read again and the line of that read follows: `identity: the ISIM's …` or + `… gave none — …`. +- `AKA: the ISIM application gave no result (…); asking the USIM` and, when no application gave one, `AKA: no + result (…)` before `USIM AKA failed`: `no logical channel opened`, `an exchange brought no answer with a + status word` (the AUTHENTICATE or a GET RESPONSE after it), + `status word `, `a synchronisation failure, tag DC`, or `N bytes that are no AKA result, + status word `. - `RESUME via existing SA (cseq N)`, `REGISTERED (resumed + true-refreshed)`, `FRESH registration`, `Security-Server: …`, `REGISTERED (fresh)`. - `bring-up deferred: …; next: fresh registration in N s` — one line; `in N @@ -1554,8 +2374,9 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: `the refusal schedule stands at N min from before this start: …`. - `…; next: fresh registration in N s` (`in N min` from a minute, `now`), `registering fresh (recovery attempt N)`, - `fresh registration deferred/refused/failed: …`, `reconnected + re-registered`, - `recovered by a fresh registration`. + `fresh registration deferred/refused/failed: …`, `client flow dead; reconnecting` + (a reconnect over the registration's SAs begins, §7.4) and its + `reconnected + re-registered`, `recovered by a fresh registration`. - `the registration's SAs are on X, not the PDN's own address Y: resuming there until the next fresh registration`, `the fresh registration moves from X to the PDN's own address Y`, `back on X: the old registration stands @@ -1605,6 +2426,39 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `: failed: … — the resume is given up (the engine's rule): the pair is removed`). - `audio session: …` at start and at each call's media start; `CODECS override active: …`. +- `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: …`). +- `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 + (§7.6): where no lock was held, no such line; `no sleep inhibitor from + logind (…): asked again when it says a sleep is over` where logind gave + none, once until a call's lock is next given. +- `wake alarm: a sleeping phone is woken when the registration's refresh + is due` when the alarm is first armed, `no wake alarm (…): a sleeping + phone is not woken for the registration's refresh` where the kernel + gives no such timer (its error) or has no RTC behind it (`no RTC that + can wake the phone`), `wake alarm not set: …` where setting it fails + (§7.10). +- `the modem reports no packet service: the reconnect waits until it has + it again` (or `the fresh registration waits …`) where a recovery step + finds the modem without packet service: once, and again after a look + that found it with service (§7.10). A cycle that was tried and went + unanswered, the modem then reporting none, has the line it had: `… + while the modem reports no packet service: not counted; next: …` + (§7.4). `wake trace: …` only with `WAKE_TRACE=1`, a test seam (§5). - `media pt=N octet=true|false -> [X]:P, telephone-event pt N|none` at a call's media start (`… pt N (theirs M)` when `DTMF_RX_PT` differs from the one we send with); `call X: DTMF '…' -> media leg (telephone-event pt @@ -1741,7 +2595,9 @@ imsd to try again`, `wrote (not usable on the IPv6-only ims PDN)`, `P-CSCF discovery: nothing usable (…)`, `P-CSCF X configured: discovery skipped`, `host route to P-CSCF X dev Y` (the configured address or the first discovered), `wrote -/run/imsd.env: DEV=… LOCAL=… PCSCF_DISCOVERED=… PCSCF_DISCOVERY=…` —, +/run/imsd.env: DEV=… LOCAL=… PCSCF_DISCOVERED=… PCSCF_DISCOVERY=…`, +`nftables: opened protected ports 45061-45062 on qmapmux*` and `nftables: +accepting ESP on qmapmux*` where the script inserted the rule —, `imsd-handover: …`, `imsd-ofono-restart-calls: …`. ### 7.9 SMS over IP (TS 24.341) @@ -2095,6 +2951,140 @@ do that answers without state. — its flatpak on the `flatpak.catcrafts.net` remote accompanies this release. +### 7.10 A phone that sleeps + +Nothing of imsd runs while the phone is suspended. What it has to do at +a certain time the phone has to be awake for, and what it waits for +must not be cut off by a suspend. This is what sees to that. + +- **The refresh, and the subscription's renewal ahead of its expiry, run + on the boot clock.** + The network counts + a registration's lifetime while the phone sleeps. The refresh (§7.2 + step 5) is due on `CLOCK_BOOTTIME`, as the recovery policy's waits are + (§7.4), and so is the renewal of the reg-event subscription ahead of + its granted lifetime's end. In the releases up to 1.2.4 both counted + awake seconds, and a registration lapsed on a phone that slept most + of its two hours (§13). +- **A wake alarm.** A timer on `CLOCK_BOOTTIME_ALARM` (the kernel's alarm + timer, which sets the RTC's alarm for a suspend; it takes + `CAP_WAKE_ALARM`, which the service has) is armed at the end of every + turn of the loop that takes no command off the queue (a turn that + takes one handles it and goes straight to the next turn) for the time + `WakeAt` names (`Imsd:Engine`): now while a call or a text is in + flight (the hold of the next entry); else, with a + registration on a live flow the refresh's due time, or the reg-event + subscription's renewal where that comes first; with a dead flow under + a registration the recovery policy's word (`RegRecovery::WakeTime`: its + next step, and the slower look after a local wait, below); and none + where nothing waits to be done. A bring-up's wait for the policy arms + the policy's time itself. The timer is never read: the waking is the + whole of it, and the loop's own clock checks act once the phone is + awake. Where the kernel gives no such timer, or has no RTC behind it, + the journal says so once, and nothing wakes the phone for imsd. A + resume by itself sends nothing: a refresh that is not due does not go + out. +- **Work in flight has a lock and the alarm.** Beside the call's lock + (§7.6) the main thread asks for a second block inhibitor of + logind's, in the way it asks for the call's + (its reason `a registration step or a text in flight`), while a step + of the + registration exchanges with the network (the refresh, a reconnect, a + fresh registration, the bring-up: `Engine::Step`) and while a text is + being sent, whose two waits count awake seconds (§7.9); not while a + bring-up waits out a hold the network set, which can be an hour + (§7.4). For a suspend that begins all the same (logind refused such + a lock where a suspend's operation was already running, §13; a request + can tell it to ignore inhibitors) there is the alarm. Under a call + and under a text in + flight, and where a step is due that the next turn runs (but for the + look after a local wait, below, which has its own slower time), it + is set 1.9 s ahead at every such turn, and the kernel refuses a + suspend under an alarm less than two seconds ahead (§13); that holds + where there is + an alarm and while the loop turns or a call's resend waits for its + connect, not through a turn that takes longer otherwise (a media leg + being stopped, a helper program) and not through a registration + step; and the suspend has to come to the kernel's check before the + alarm set last has fired, after its sync and its freeze of the + processes (§13). A step keeps the + alarm at most 30 s ahead while it waits for + the network, whatever else is in flight: where imsd has its wake + alarm, a sleep that begins under such a wait ends there, and the + step goes on (this section's last paragraph has what is left). The + alarm fires once + (§13), and a wait can outlast the sleep it ended, so it is set anew + before every second of a wait for the network (a connect's answer, + the pause before the next try, a REGISTER's answer): where the wait + goes on after a wake, it stands again within a second. One of those + waits, for the fresh registration's first answer, is a receive with a + timeout, which a suspend's freeze ends with `EINTR` (§13): it is + taken up again for the rest of its time. A wait for a helper program + keeps the alarm that stood when it began. +- **A coverage gap costs little sleep.** While the modem reports no + packet service the recovery tries no reconnect and no fresh + registration, and no lock is taken for one: either would wait for + answers that cannot come. A dead flow's socket that is still open at + that look is closed there without the FIN's exchange (`Abort`): over + TCP, + left open it is readable at every turn of the loop, which would + spin instead of waiting, and closed with a FIN it would hold the + address pair against the reconnect after the gap, as the socket of + a flow does that a step closed after a wait without an answer (the + kernel's refusals, below). (The refresh that + runs into the gap waits its 12 s under the lock, once. A bring-up + does not ask the modem: one that meets a gap makes its attempts + under the lock. A `Dial` that finds the flow dead in the gap ends + at once: the recovery's immediate try for it tries nothing either, + and the INVITE fails on a flow that is gone.) Awake and with no call + up, the modem is + asked again every 5 s; a sleeping phone is woken for the next look + after as long again as the modem has been without service, 10 s at + the least and 15 min at the most (§7.4's table). That time is + counted from the modem's first word of no service since the network + last answered (§7.4's table has what counts as its answer): the + modem's word for its + service starts no count over, and where it alternates at the edge + of coverage an attempt made on it costs its wait under the lock + (a TCP reconnect's 34 s where nothing answers) while the looks keep + their pace. Every + step that follows no local wait is woken for at the policy's own + time (§7.4's table): a reconnect cycle the network was silent to is + no local wait where the modem has service, a fresh attempt it was + silent to never is. + The kernel refuses a connect locally for as long as the + old flow's socket holds the address pair, which clears in awake + seconds (TIME_WAIT's 60, an unanswered FIN's retransmissions): two + tries 10 s apart under the lock at each look. That is the other + local wait: awake and with no call up, the next look comes 5 s after + each; a sleeping phone is woken for it after as long again as the + kernel's refusals have lasted, 10 s at the least and 15 min at the + most, counted from its first refusal since the + modem's last word of no service or the network's last answer, + whichever came later. The slower look does not know + the registration's lifetime: a gap that ends shortly before the + lifetime does can cost the registration. + +What of the registration's schedule and of the texts' times still +counts awake seconds is in §7.4's paragraph on the clocks; a step's own +waits for the network (a connect's answer, the pause before the next +try, a REGISTER's answer) count them too, under the step's lock. +Nothing holds a sleep off under the bring-up script, which runs before +the daemon (§7.3), nor in the wait before a restart after a failure: a +phone suspended there does not register until it is awake again. And +from the +moment the alarm has woken the phone to the step it woke it for, the +loop's next turn (up to a second where a bring-up waited out a hold), +there is neither alarm nor lock: a desktop that asked for a suspend +again within that time would have the phone sleep through the step +until something else woke it. For up to a second after the alarm has +ended a sleep under a step's wait it is not set again yet either +(where the freeze has ended the receive of the fresh registration's +first wait with time left, §13, it is set at once), and a helper +program the step goes on to from a wait in that second has none until +the step's next wait for the network: a suspend told to ignore +inhibitors that began there would not be ended by imsd. + ## 8. D-Bus ABI and desktop integration ### 8.1 `net.catcrafts.IMS1` (frozen) @@ -2363,7 +3353,8 @@ line, having a fresh target decides what a refused or failed resume leads to — the fresh registration (a refusal without a Retry-After is not counted) or, with none, the pair kept for the restart, removed, or the idle (§7.2 step 1) — and a comma-separated `PCSCF=` stops the bring-up before the -resume. +resume. `WAKE_TRACE=1` is a test seam of the wake alarm's (§5, §7.8), no +configuration, and in none of the README's tables. ### 10.2 imsd-media (per call, set through imsd's environment) @@ -2452,10 +3443,37 @@ only the imsd side of its bus choice. or paired, between any addresses — goes, with the reqid-1/2 transport-mode ESP states in its direction, and a reqid-1/2 transport-mode ESP state on the UE's ims-PDN address goes whoever made it (`tests/Ipsec` pins both). +- Whether the signalling is encrypted inside the SAs is the P-CSCF's + choice (TS 33.203 5.1.3): the default offer names `aes-cbc` and the null + cipher, and with the null cipher selected the SAs protect the + signalling's integrity and do not encrypt it. `EALG=aes-cbc` offers + encryption only; a P-CSCF that answers it with the null cipher alone is + followed all the same (README, `EALG`: when no entry matches). The + protected REGISTER repeats the Security-Client for the P-CSCF to compare + with the first one's (TS 33.203 Annex H). - The bus policies deliberately let any local account *reach* both names; authorization is polkit's, not the policy file's. Keep it that way: a policy that names an account breaks the moment the account is called something else. +- What an ISIM's identity files hold goes into the requests of a + registration made under it. Its REGISTERs: the home domain as the + Request-URI's host and in the digest's quoted `realm` and `uri`, the + private identity inside the quoted `username`, the public identity + between the angle brackets of From and To. Beyond them: the home domain + in the address `RuriFor` makes of a dialled number, an outgoing call's + Request-URI and To (its host, and its phone-context where `RuriFor` + writes one), and as the host of the service centre's address of an SMS + submission (`ScPsi`: the MESSAGE's Request-URI and To); the public + identity, while no + P-Associated-URI has named another, as the reg-event SUBSCRIBE's + Request-URI, From and To (`BuildSubscribeReg`) and as the identity of + imsd's own requests (`CallerId`). `ParseIsimValue` takes no blank and no + byte outside printable ASCII and `IsimIdentity` no quote, backslash or + angle bracket, and in the domain nothing but letters, digits, hyphens + and dots, so a card cannot end a header field or a request line or add + one; a card whose values fail the check registers the derived names. The + journal prints the three as it prints the IMSI, and the state file holds + them. - SIP dumps and the state file carry the IMSI, the MSISDN, SPIs and addresses, and the state file (since 0.3.11) the last challenge answer — nonce, cnonce and response — and (since 0.3.12) the P-CSCF's @@ -2469,7 +3487,44 @@ only the imsd side of its bus choice. (§7.2 step 3). Nothing else is routed over it. A change that routes anything else over it needs a reason and a bench. - The fixed protected ports (45061/45062) are opened in nftables for - `qmapmux*` only, by the bring-up script. + `qmapmux*` only, by the bring-up script, and ESP is accepted there: the + 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. + `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 @@ -2522,6 +3577,24 @@ the related code. 21 min is the wait that has never been refused, not a measured minimum; imsd resumes rather than registers fresh wherever it can, since on a live registration's address the attempt is refused and costs the registration. +- **KPN refused the two re-REGISTERs that followed an unanswered refresh + `482 Loop Detected`, before any fresh attempt, and answered 200 where + the next number was sent** (the dev phone, 2026-11-25; the fp6 + journal's `2026-11-25-refresh-answer-lost` capture). A refresh's answer + did not reach the phone, whose firewall dropped the network's packets + for 20 s in a test. The reconnect's re-REGISTER was refused 482 10 s + after the refresh had failed, and the next one that reached the + network 66 s after that. That both carried the unanswered one's number + is read from the code, not seen: it was a test build with 1.2.4's code + at that place, and the journal prints no number for a REGISTER that + fails. The fresh registration that followed met the throttle above + (`spi-s=0`), re-REGISTERs after it were answered `480 Temporarily + Unavailable` with `Retry-After: 180` (by the same reading of the code + they carried the unanswered one's number too: the 482 came only + before the throttled attempt), and the phone registered again + 25 min 55 s after the refresh had failed. With the next number, the + reconnect's re-REGISTER after a refresh whose answer was dropped the + same way was answered 200. - **O2 UK, 2026-09-24:** a refresh refused 21 × 503 over 70 min, then 33 unanswered reconnect cycles; a fresh registration was accepted in one second. The origin of `RegRecovery`. On 2026-10-08, under 0.3.10 (the @@ -2535,6 +3608,18 @@ the related code. one succeed, while the fresh registrations that followed were accepted: the origin of the 5.1.1.4.2 refresh shape. KPN accepts both shapes without a challenge. +- **The security offer.** KPN answered the two-cipher offer with one + mechanism, `hmac-sha-1-96` with `aes-cbc`, at a fresh registration, and + answered a reregistration that carried it 200 (the dev phone, 2026-11-22, + an earlier build of this change, on 1.2.0). Odido answered an offer that + named the null cipher with one mechanism naming `ealg=null`: the + Python stack's offer of that one cipher (2026-07-13) and the four + mechanisms of another Fairphone 6's own IMS client, which then + registered (2026-07-15). On KPN's ims PDN (MTU 1280) the netdev counted + one datagram fragmented in two after a boot with one fresh registration, + with one mechanism offered and with two (the dev phone, 2026-11-22): + the first REGISTER goes over UDP whatever its size, and KPN challenged + both. - **KPN closes a registration's previous reg-event subscription with `noresource`** when a new one replaces it: that end is not renewed. - **Modem attach-family forcing** (Odido, O2 UK, Swisscom): an APN-string @@ -2574,9 +3659,124 @@ the related code. first off the stream's 20 ms timestamp grid (bench 10's outgoing call) — whether that shape is the phone's or the network's interworking, nothing on disk says. +- **A packet imsd sends on the ims PDN can wake a phone that has gone + back to sleep, up to twice** (the dev phone, KPN, a mainline-based 7.3 + kernel with the fp6 journal's power lane's test patches; + `2026-11-20-modem-echo-wakes` there). The bearer comes + up for it and goes dormant 11 to 13 s later, which the modem reports to + ModemManager (WDS event reports), and 90 s after the dormancy the modem + makes a file-system request to rmtfs (what it reads or writes there is + not known). Each can wake a phone that has + gone back to sleep; a ModemManager patched to switch those reports off + for the sleep (on the dev phone since 2026-11-20, not in the fp6 image) + keeps the first back. Under the CRLF keepalive of imsd up to 1.2.3, one + every 30 s of a clock that stops in a suspend, the modem ended 29 + sleeps of 29 in a loop of suspends with a 150-s alarm, 15 with the + report and 14 with that request, and 5 of 8 with the reports off; with imsd + held still, none of 6 (2026-11-20). Without the ping (two builds of 1.2.4's + change, §5), with the reports off, the same loop ran twice with no + packet on the ims netdev: the modem ended none of six sleeps in one + and one of seven in the other, for a file-system request that no + packet had preceded (2026-11-24). What an idle phone with a standing + registration still sends is the refresh, once in 1800 s on KPN, awake or, + where imsd has its wake alarm, asleep (§7.10; three packets out, the + dormancy report 11 to 13 s and + the request 102 to 104 s after them), and what its reg-event + subscription needs (§7.4): on KPN a renewal once in 599400 s (the grant + of 600000 s less 600). Awake and idle + on a 100-mA USB port the dev phone's battery lost 140 mA under 1.2.3's + ping and 59 mA without it (its own counter over one window of 40 min + and one of 33; 2026-11-24). +- **KPN's P-CSCF leaves a flow open that carries nothing**: 44 min 9 s + lay between a registration's last packet and the refresh, which it + answered on that flow (the dev phone, 2026-11-24, six suspends in + between). Where a network's P-CSCF closes or forgets a flow it hears + nothing on, `CRLF_KEEPALIVE` is that network's setting (§7.2 step 5 + has what imsd does without it). +- **A registration counted in awake seconds lapsed on a phone that + slept most of its two hours** (the dev phone, KPN, imsd 1.1.0, + 2026-11-19; the fp6 + journal's power lane, `2026-11-19-wake-tests`): registered at 09:15:48 + with a lifetime of 7200 s, the phone in a loop of suspends from 09:26 + to 11:22, no refresh + went out; the network's NOTIFY that the binding had expired woke the + phone at 11:16:37, the fresh registration met the throttle above, and + the phone registered again at 11:37:38. +- **The kernel refuses a suspend under an alarm timer less than two + seconds ahead** (`alarmtimer_suspend`, `kernel/time/alarmtimer.c`, + read at v7.3: -EBUSY, and a wakeup event of two seconds, where an + RTC stands behind the alarm timer; without one it lets the suspend + pass). The check is in the suspend's device phase, after the kernel + has synced and frozen the processes: an alarm that has fired by then + is off the queue and refuses nothing. On the dev + phone (2026-11-25 and 2026-11-28), `systemctl suspend -i` under a call + or a text in flight: logind let it through, the kernel refused it, + systemd-sleep tried the next state of its list and was refused again, + and the phone did not suspend; each refused attempt has its line in + the kernel's log, `alarmtimer alarmtimer.0.auto: PM: failed to + suspend: error -16` (six of six in the boot of 2026-11-28 13:22). +- **A timer on an alarm clock made with `timerfd_create` and set with no + interval fires once** + (read at v7.3: `alarmtimer_fired`, `kernel/time/alarmtimer.c`, takes + the alarm off the kernel's queue and restarts nothing; + `timerfd_alarmproc`, `fs/timerfd.c`, marks the timer expired, counts + a tick and wakes whoever waits on the descriptor; an interval would + be applied only when the timer is next accessed, by a read or by + `timerfd_gettime`). imsd sets no interval and neither reads nor + queries its timer: after it has fired there is no alarm of imsd's + until the next `timerfd_settime`, which is why a wait sets it every + second (§7.10). +- **A suspend's freeze ends a datagram receive that has a timeout with + `EINTR`** + (read at v7.3: `freeze_task`, `kernel/freezer.c`, wakes a user thread + that it cannot freeze where it sleeps as a pending signal would; a + datagram receive sleeps interruptibly and not freezably and leaves + with `sock_intr_errno`, `net/core/datagram.c` and + `include/net/sock.h`, which under a finite `SO_RCVTIMEO` is `-EINTR`, + and that the kernel does not take up again as it does an interrupted + `poll`). On the dev phone (2026-11-28) a test program's `recvfrom` + under a timeout returned `EINTR` at the resume from a suspend, in + pieces of a second and in one long wait alike (the fp6 journal's + `2026-11-25-through-sleep` capture, `evidence/recv-eintr/`). A stop + and a continue (`SIGSTOP`, `SIGCONT`) end such a receive the same + way, which is how the bench stages it (§5). The daemon's wait for a + fresh registration's first answer is such a receive + (`AwaitInitialFinal`). +- **logind refused a block inhibitor for sleep where it was asked for + during a suspend's operation** + (systemd 262.2, the dev phone, 2026-11-25 and 2026-11-28): `Inhibit` + for `sleep` in `block` mode was answered + `org.freedesktop.login1.OperationInProgress` (`The operation + inhibition has been requested for is already running`) in a sleep hook + before the suspend, in one after it, and to imsd 0.1 to 0.3 s after + systemd-sleep's `System returned from sleep operation`; + logind's `Operation 'suspend' finished` came 0.03 s after that line + where the run's sleep hook did nothing after the resume, 0.1 s after + it where the hook made three bus calls then, and 2.1 s after it where + it also waited two seconds; a lock asked for after it was given. - **pmOS's default nftables** drops inbound on `qmapmux*`; without the - protected-port rule every network-initiated request (NOTIFY, MT INVITE) - dies after ESP decapsulation and MT calls fall back to CS. + protected-port rule every network-initiated request (NOTIFY, MT + INVITE) dies after ESP decapsulation and MT calls fall back to CS. The + ESP packet passes the same chain before it is decapsulated, and + without a rule for it the chain accepts it only as an answer to a + packet the phone sent (`ct state established`): the connection tracker + has no tracker for ESP, and its generic one keeps the entry for + `nf_conntrack_generic_timeout` seconds after the last packet either + way, 600 on the dev phone. A request the network starts later than + that after the phone's last ESP packet is then dropped, and its + retransmissions until the phone next sends to that P-CSCF. Until 1.2.3 + imsd's CRLF keepalive every 30 s kept the entry (over TCP and outside + a call only; since 1.2.4 none goes out unless `CRLF_KEEPALIVE` names + an interval, §7.2 step 5); the bring-up script's rule for ESP (§7.3, + 1.2.4) makes the entry needless. Shown on the workstation with the dev + phone's ruleset, and on the dev phone for a text with the tracker's + timeout at 0 (§5). A firewall without an `inet filter` table with an + `input` chain gets no rule from the script and needs its own. And the + script's rules are in the running ruleset only: a reload of the + ruleset from its files (the nftables unit's `flush ruleset`, and the + one in `/etc/nftables.nft`) removes them until imsd next starts, so a + ruleset whose files carry the port rules (fp6-img's `01_imsd.nft`) has + to carry the rule for ESP in them too. - **The kernel's temporary SLAAC address** on the ims netdev is listed first and retired after about two days; a registration bound to it dies with it. - **systemd reads `EnvironmentFile=` per spawned command** (systemd 262~rc3 @@ -2634,6 +3834,43 @@ the related code. 01:17:41–45, 28–36 min after their SC time stamps; what held them is unknown. The registrar echoes `+g.3gpp.smsip` in the reg-event reginfo (``) on both AORs. +- **Cards with an ISIM** (the fp6 journal's read-only probe on two + reporters' phones; the dev phone's card has none). A US card on AT&T's + network (operator name "Dark Star", SIM operator 310 280; 2026-11-23) and + a Norwegian one (Ice, 242 14; 2026-11-21) each list a USIM `ready` and + an ISIM `detected` in one slot of the Fairphone 6. On both a logical + channel opened on the ISIM's AID in that state and the probe read + EF_IMPI, EF_DOMAIN and EF_IMPU's record 1: it sends SELECT by file + identifier with P2 `04` and takes a `61 XX` for the file selected, sends + READ BINARY and READ RECORD with Le `00` and follows a `61 XX` or a + `6C XX` to those (which it got on the way it does not print), and cuts + `FF` bytes from the end of a value. The US card holds names of the + operator's own in all three + (the private identity `@private.att.net`, the home domain + `one.att.net`, the public identity `sip:@one.att.net`) and has no + EF_P-CSCF and no EF_IST (`6A 82` to their SELECT); the Norwegian card + holds the names TS 23.003 derives from the IMSI, an EF_P-CSCF of three + unused records and an EF_IST of seven zero bytes. On the dev phone's + USIM (a KPN eSIM, 2026-11-21, by hand) that SELECT answered `61 19` for + one file and `61 1C` for another, the + two reads data and `90 00` at once, and the SELECT of a file the + application does not have `6A 82`. The US card's network answered imsd + 1.1.0's first REGISTER, which carried the derived names + (`ims.mnc280.mcc310.3gppnetwork.org`), `480 Temporarily Unavailable` + (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". 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` (§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 @@ -2641,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/README.md b/README.md index 19d1822..26180d7 100644 --- a/README.md +++ b/README.md @@ -90,11 +90,13 @@ Configuration is environment variables in `/etc/imsd.env`, none are required. | `DEV` | `qmapmux0.0` | ims-PDN netdev; the packaged service passes the real one via `/run/imsd.env` | | `LOCAL` | *(auto)* | UE address (compared in RFC 5952 form). The packaged service gets the PDN address ModemManager assigned, via `/run/imsd.env` from `ims-pdn-up.sh`; a manual run prefers a global IPv6 on `DEV` that is neither temporary nor `dynamic` (RA-derived), then any non-temporary one, then the first (the kernel's temporary SLAAC address is listed first, and a registration bound to it is lost when the kernel retires it) | | `USER_AGENT` | `imsd/` | REGISTER User-Agent. Some networks fingerprint UAs; setting your device's stock build string reproduces the stock modem's registration exactly. Empty omits the header | +| `ISIM` | `1` | `0` registers the names derived from the IMSI and answers the challenge in the USIM, as 1.2.2 did. By default a card that has an ISIM registers the identity the ISIM holds (its private identity, home domain and first public identity) and the ISIM is asked for the answer to the challenge; a card without one, or with one imsd cannot use, registers the derived names. The journal's `identity:` line says which. A registration that stands keeps the names it was made under, so a change of the setting shows after a reboot | | `STATE_FILE` | `/var/lib/imsd/imsreg.state` (root) / `$XDG_STATE_HOME/imsd/imsreg.state` | persisted registration context for warm resume | | `HOLDS_FILE` | `/run/imsd.holds` (root) / `$XDG_RUNTIME_DIR/imsd.holds` (`/tmp/imsd.holds` without a runtime dir) | the waits the network imposed (a `Retry-After`, the refusal schedule), where that schedule stands whether the old registration is gone (`old_gone`) and the refusal count (`refusals`: a resume refused without a Retry-After at a start with no fresh target is one, the restart's the second), kept across a restart of imsd for the PDN they were set on — not across a reboot; `/dev/null` switches the file off (only a regular file is ever removed; anything else is emptied). `imsd-handover.sh` honours it too | | `RESUME` | `auto` | `0` forces a fresh registration (ignores a warm SA) where there is a fresh target; with none the untried pair is removed and the bring-up ends as AGENTS §7.2 (the daemon's own bring-up) step 1 says | | `REFRESH_INTERVAL` | *(auto)* | keepalive re-REGISTER period in s; default = half the granted expiry, clamped to [120, 1800] | -| `EALG` | `aes-cbc` | offered ESP cipher (`aes-cbc`, `des-ede3-cbc`, `null`). From the 401's `Security-Server` list imsd selects the highest-preference `ipsec-3gpp` mechanism that matches this offer (RFC 3329 §2.3.1) and takes the SPIs/ports from the entry carrying them (some cores list every mechanism they support and put the SPIs on the one they applied); when no entry matches, the P-CSCF's SPI-carrying entry is installed as listed (`hmac-md5-96`, an absent `ealg` = null) and the journal says so. The line, the selection and the SA parameters are logged at every fresh registration | +| `CRLF_KEEPALIVE` | `0` | whole seconds between CRLF keepalives (RFC 5626 §4.4.1) on an idle TCP flow to the P-CSCF; `0` or an empty value sends none (until 1.2.3 imsd sent one every 30 s; AGENTS.md §13 has what that costs a phone). For a network that drops a flow it hears nothing on (AGENTS.md §7.2, the daemon's bring-up, step 5). Any other value that is no whole number of seconds is reported in the journal and sends none | +| `EALG` | `aes-cbc,null` | the ESP ciphers offered, in order: a comma-separated list of `aes-cbc`, `null` (no encryption) and `des-ede3-cbc`; a name imsd cannot install is ignored with a journal line. From the 401's `Security-Server` list imsd selects the `ipsec-3gpp` mechanism the P-CSCF put the SPIs on when it is the only such entry and one of the offer, else the mechanism of the offer with the highest preference (the `q` of RFC 3329 §2.3.1), and takes the SPIs/ports from the entry carrying them (some cores list every mechanism they support and put the SPIs on the one they applied); when no entry matches, the P-CSCF's SPI-carrying entry is taken as listed (`hmac-md5-96`, an absent `ealg` = null) where imsd can install it, and the journal says so. The offer is logged at bring-up beside the SIP transport, the line, the selection and the SA parameters at every fresh registration | | `SIP_TRANSPORT` | `auto` | transport of the protected leg (the second REGISTER and everything after it): `tcp`, `udp`, or `auto` = TCP, falling back to a fresh registration over UDP when the P-CSCF leaves two TCP connects unanswered — but only on a phone that has never registered over TCP: once the state file records a TCP registration, a silent connect is treated as an outage, not a policy (delete the file or set `udp` to override, e.g. after a SIM change). The challenge (first REGISTER) is always UDP. Over UDP a REGISTER or INVITE larger than ~1.2 KB leaves as IPv6 fragments at the ims PDN's 1280-byte MTU (the journal says so once per flow); there are no SIP retransmission timers over UDP yet, so a lost datagram costs a timeout. The SAs, the listener and the firewall rule cover both transports | | `SMS_OVER_IMS` | `0` | `1` takes short messages over IMS (AGENTS.md §7.9): the REGISTER Contact advertises `+g.3gpp.smsip` and `net.catcrafts.IMS1.Messaging.Send` submits one; off, imsd does not advertise it and refuses `Send` (AGENTS.md §7.9 says how imsd answers a text the network sends anyway) | | `SMSC` | *(EF_SMSP)* | the service centre a submission is addressed to, in international form (`+31653131313`; spaces, dashes and dots dropped; a national or `00`-prefixed number, or a `*` or `#` in it, is refused at bring-up); unset, imsd reads the (U)SIM's EF_SMSP record 1. Without either, `Send` fails with the reason | diff --git a/implementations/main.cpp b/implementations/main.cpp index b1bd4b0..19187b9 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -5,8 +5,10 @@ imsd — the userspace IMS/VoLTE daemon (control plane). Owns net.catcrafts.IMS1 on the system bus with the project's frozen D-Bus ABI -(AGENTS.md §8.1) and drives it with the engine core: register on the IMS PDN (USIM AKA -+ IPsec sec-agree, fresh or warm-resume, with a keepalive re-REGISTER refresh), +(AGENTS.md §8.1) and drives it with the engine core: register on the IMS PDN (by default the +identity the card's ISIM holds, else the one derived from the IMSI; AKA in that +ISIM, else in the USIM; IPsec sec-agree, fresh or warm-resume, with a keepalive +re-REGISTER refresh), run outgoing and incoming calls through the Imsd:Engine call machine (inbound INVITEs on the protected-port listeners become ringing calls a dialer answers via Accept), spawn one imsd-media data-plane process per answered call, and @@ -42,6 +44,7 @@ its subscriber set on the main thread too. #include #include #include +#include #include #include #include @@ -53,7 +56,7 @@ import ImsdBus; namespace { // ---- static config (env-overridable, same knobs as imsd.py) --------------- -constexpr const char* Version = "1.2.1"; +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"; @@ -194,6 +197,90 @@ std::optional CompletedHex(std::string_view out) { return h; } +// ---- the card, through qmicli's UIM logical channels ---------------------- + +// A logical channel to one application of the card: opened on the +// application's AID, closed when the object goes. Exchange sends one command +// and returns the card's answer to it; Transmit also sends what the card asks +// for after it (imsd::aka::ApduFollowUp, for an answer without data: GET +// RESPONSE for '61 XX', a command without data again with the length a +// '6C XX' names — two follow-ups at most) and returns the last answer. +// nullopt when one of the exchanges +// brought no answer with a status word back: qmicli printed none, or fewer +// than two bytes. +class UimChannel { +public: + UimChannel(int slot, std::string_view aid) : slot_(slot) { + auto open = RunCapture({"qmicli", "-d", "qrtr://0", std::format("--uim-open-logical-channel={},{}", slot, aid)}); + if (auto ch = CompletedInt(open.out)) channel_ = static_cast(*ch); + } + UimChannel(const UimChannel&) = delete; + UimChannel& operator=(const UimChannel&) = delete; + ~UimChannel() { + if (channel_ >= 0) RunCapture({"qmicli", "-d", "qrtr://0", std::format("--uim-close-logical-channel={},{}", slot_, channel_)}); + } + bool Open() const { return channel_ >= 0; } + int Number() const { return channel_; } + std::optional Exchange(std::string_view apdu) const { + auto r = RunCapture({"qmicli", "-d", "qrtr://0", std::format("--uim-send-apdu={},{},{}", slot_, channel_, apdu)}); + auto hex = CompletedHex(r.out); + if (!hex) return std::nullopt; + auto bytes = imsd::util::FromHex(*hex); + if (!bytes) return std::nullopt; + return imsd::aka::ParseApduAnswer(*bytes); + } + std::optional Transmit(std::string apdu) const { + auto answer = Exchange(apdu); + for (int i = 0; answer && i < 2; i++) { + auto next = imsd::aka::ApduFollowUp(channel_, apdu, *answer); + if (!next) break; + apdu = std::move(*next); + answer = Exchange(apdu); + } + return answer; + } +private: + int slot_; + int channel_ = -1; +}; + +// Whether two identities are the same three names. +bool SameNames(const imsd::aka::Identity& a, const imsd::aka::Identity& b) { + return a.impi == b.impi && a.domain == b.domain && a.impu == b.impu; +} + +// The identity the card's ISIM application holds (TS 24.229 5.1.1.1A): the +// private identity of EF_IMPI, the home domain of EF_DOMAIN and the public +// identity of EF_IMPU's first record (GSMA IR.92 2.2.1), read over a logical +// channel on the application with the commands that read two reporters' +// cards (AGENTS.md §13); a SELECT's '61 XX' is taken for the file selected +// and the control parameters it offers are not fetched, as there. nullopt, +// with `why` saying what was missing, when it gives none. +std::optional ReadIsimIdentity(int slot, const imsd::aka::IsimApp& app, const imsd::aka::Identity& derived, std::string& why) { + UimChannel ch(slot, app.aid); + if (!ch.Open()) { why = "no logical channel opened on it"; return std::nullopt; } + auto read = [&](std::uint16_t file, std::string_view name, bool record) -> std::optional { + auto selected = ch.Exchange(imsd::aka::BuildSelectFileApdu(ch.Number(), file)); + if (!selected) { why = std::format("{}: no answer with a status word to the SELECT", name); return std::nullopt; } + if (!imsd::aka::Selected(*selected)) { why = std::format("{}: the SELECT answered {}", name, selected->Status()); return std::nullopt; } + auto got = ch.Transmit(record ? imsd::aka::BuildReadRecordApdu(ch.Number(), 1) : imsd::aka::BuildReadBinaryApdu(ch.Number())); + if (!got) { why = std::format("{}: an exchange of the read brought no answer with a status word", name); return std::nullopt; } + if (!imsd::aka::HoldsRead(*got)) { why = std::format("{}: the read answered {}", name, got->Status()); return std::nullopt; } + auto value = imsd::aka::ParseIsimValue(got->data); + if (!value) why = std::format("{}: no value in the {} bytes read", name, got->data.size()); + return value; + }; + auto impi = read(imsd::aka::EfImpi, "EF_IMPI", false); + if (!impi) return std::nullopt; + auto domain = read(imsd::aka::EfDomain, "EF_DOMAIN", false); + if (!domain) return std::nullopt; + auto impu = read(imsd::aka::EfImpu, "EF_IMPU record 1", true); + if (!impu) return std::nullopt; + auto id = imsd::aka::IsimIdentity(derived, *impi, *domain, *impu); + if (!id) why = std::format("EF_IMPI '{}', EF_DOMAIN '{}' and EF_IMPU record 1 '{}' are no identity imsd can register", *impi, *domain, *impu); + return id; +} + // The UE address on the ims PDN when LOCAL is not given: a global IPv6 on // that is neither temporary nor RA-derived (`dynamic`) — the one // ims-pdn-up.sh assigned from ModemManager — else the first non-temporary @@ -348,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"; } @@ -396,11 +507,17 @@ public: // datagram socket to the same peer — the kernel then delivers that peer's // datagrams here in preference to the unconnected ServerPorts socket on // the same port. A UDP connect() cannot be refused by the peer, so it is - // one attempt. - bool Connect(const std::string& local, int lport, const std::string& pcscf, int pport, Transport t, int tries = 10, int silentLimit = 0) { + // one attempt. `tick` is called before every try and then before every + // second of a try's wait for its answer and of the pause before the + // next try: what the caller must do at least that often while this + // thread waits (the wake alarm, under a registration step and under + // the connect for a call's resend). + bool Connect(const std::string& local, int lport, const std::string& pcscf, int pport, Transport t, int tries = 10, int silentLimit = 0, + const std::function& tick = {}) { transport_ = t; lastConnectLocal_ = false; int fam = Is6(local) ? AF_INET6 : AF_INET; + if (tick) tick(); if (t == Transport::Udp) { int fd = socket(fam, SOCK_DGRAM, 0); if (fd < 0) return SocketFailed(); @@ -421,6 +538,7 @@ public: } int silent = 0; for (int attempt = 0; attempt < tries; attempt++) { + if (tick && attempt > 0) tick(); int fd = socket(fam, SOCK_STREAM, 0); if (fd < 0) return SocketFailed(); int one = 1; @@ -441,7 +559,7 @@ public: int err = localRefusal ? errno : 0; if (rc < 0 && errno == EINPROGRESS) { pollfd p{fd, POLLOUT, 0}; - if (poll(&p, 1, 12000) > 0) { + if (PollTicked(p, 12000, tick) > 0) { socklen_t el = sizeof err; getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &el); connected = (err == 0); @@ -468,10 +586,24 @@ public: return false; } Log(std::format("connect failed; retry in 10s ({}) [{}/{}]", why, attempt + 1, tries)); - sleep(10); + for (int s = 0; s < 10; s++) { + if (tick) tick(); + sleep(1); + } } return false; } + // poll(2) on one descriptor for `ms`, in pieces of a second with `tick` + // called before each where there is one. Answers as poll does. + static int PollTicked(pollfd& p, int ms, const std::function& tick) { + if (!tick) return poll(&p, 1, ms); + for (;;) { + tick(); + int piece = std::min(ms, 1000); + int r = poll(&p, 1, piece); + if (r != 0 || (ms -= piece) <= 0) return r; + } + } // socket() failing is ours, not the network's: logged, and a local // refusal like a connect() the kernel turns down. bool SocketFailed() { @@ -514,7 +646,10 @@ public: if (send(fd_, "\r\n\r\n", 4, MSG_NOSIGNAL) <= 0) alive_ = false; } - std::optional RecvMsg(double timeoutSec) { + // The next whole message on the flow, within `timeoutSec`. With a + // `tick` the wait for the socket is PollTicked's (Connect has what the + // tick is for). + std::optional RecvMsg(double timeoutSec, const std::function& tick = {}) { auto deadline = std::chrono::steady_clock::now() + std::chrono::duration_cast(std::chrono::duration(timeoutSec)); for (;;) { @@ -523,7 +658,7 @@ public: if (now >= deadline) return std::nullopt; int ms = static_cast(std::chrono::duration_cast(deadline - now).count()); pollfd p{fd_, POLLIN, 0}; - int r = poll(&p, 1, ms); + int r = PollTicked(p, ms, tick); if (r <= 0) { if (r == 0) return std::nullopt; if (errno == EINTR) continue; return std::nullopt; } std::optional m; if (!ReadOnce(m)) return std::nullopt; @@ -549,6 +684,17 @@ public: // What was read and not yet dispatched goes with the flow: nothing // read from it can be answered once it is closed. void Close() { if (fd_ >= 0) { close(fd_); fd_ = -1; } alive_ = false; fb_ = {}; } + // Close without the FIN's exchange: the kernel drops the connection at + // once (after the peer's FIN with a reset in our FIN's place; where a + // reset or its own giving up has ended it, it sends nothing), so the + // same local port can connect to the same peer again in the same + // breath. A socket closed with Close() after the peer's FIN stays in the + // kernel's table until the peer has acknowledged ours, and a connect from + // its port meanwhile is refused (EADDRNOTAVAIL). For a dead flow only. + void Abort() { + if (fd_ >= 0) { linger l{1, 0}; setsockopt(fd_, SOL_SOCKET, SO_LINGER, &l, sizeof l); } + Close(); + } private: // One read of the socket once poll(2) has named it: `m` is the message a // datagram held (UDP); on TCP the bytes go to the frame buffer. False @@ -607,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}) { @@ -631,7 +786,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)); @@ -642,10 +797,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_) { @@ -705,8 +861,15 @@ 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; + 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)); @@ -728,9 +891,19 @@ 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; } + const std::string o = Leaving(r, NameOf(c->fd), c->peer); + (void)!write(c->fd, o.data(), o.size()); }}); } } @@ -744,11 +917,46 @@ 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; + } + + // `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, + imsd::util::HostPort(HostOf(peer), PortOf(peer)))); + saidClosed_ = true; + } + + std::function insideSa_; + bool saidOutside_ = false; + bool saidClosed_ = false; + int udpUc_ = -1, udpUs_ = -1; std::vector listeners_, udp_; std::vector conns_; }; @@ -760,8 +968,15 @@ struct RegState { std::uint32_t spiUc = 0; std::uint32_t spiUs = 0; long expiry = 0; + // The card application the challenge goes to, by its slot and AID: the + // ISIM when the card's identity was read from it, else the USIM. int slot = 0; std::string aid; + // The identity this registration was made under. Set on the fresh 200 + // and when a resume takes its state file's (the file's since 1.2.3; the + // derived one for an older file, as 1.2.2 wrote it for a registration + // under it); empty before the first of either. + imsd::aka::Identity id; // Contact user-part of the stored binding (UUID since the s53 oracle // diff; empty = legacy IMSI binding from an older state file). std::string contactUser; @@ -815,6 +1030,10 @@ void SaveTpMr(std::uint8_t mr) { // since 0.3.12. The file's values are quoted without escaping; a value // with a quote, a backslash or a newline in it (none RFC 3329's token // syntax produces) is written empty, and the resume falls back to the SA. +// `impi`, `domain` and `impu` (since 1.2.3) are the identity the +// registration was made under, which a resume keeps (TryResume); the three +// have passed imsd::aka::IsimIdentity or are MakeIdentity's, so none holds +// a character the quoting cannot carry. void PersistState(const RegState& r, const std::string& route, const std::string& ppi, const std::string& aor, const std::string& transport, const std::string& pcscf) { std::string ss = r.securityServer.find_first_of("\"\\\n") == std::string::npos ? r.securityServer : std::string(); std::string j = std::format( @@ -822,9 +1041,11 @@ void PersistState(const RegState& r, const std::string& route, const std::string "\"spi_us\": {}, \"expiry\": {}, \"route\": \"{}\", \"ppi\": \"{}\", " "\"aor\": \"{}\", \"contact_user\": \"{}\", \"transport\": \"{}\", " "\"auth_nonce\": \"{}\", \"auth_cnonce\": \"{}\", \"auth_response\": \"{}\", " - "\"security_server\": \"{}\", \"pcscf\": \"{}\"}}", + "\"security_server\": \"{}\", \"pcscf\": \"{}\", " + "\"impi\": \"{}\", \"domain\": \"{}\", \"impu\": \"{}\"}}", r.callid, r.ftag, r.cseq, r.spiUc, r.spiUs, r.expiry, route, ppi, aor, - r.contactUser, transport, r.authNonce, r.authCnonce, r.authResponse, ss, pcscf); + r.contactUser, transport, r.authNonce, r.authCnonce, r.authResponse, ss, pcscf, + r.id.impi, r.id.domain, r.id.impu); std::string path = StatePath(); std::error_code ec; std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec); @@ -850,7 +1071,7 @@ void DumpRaw(std::string_view name, std::string_view msg) { } struct PersistedState { - std::optional callid, ftag, route, ppi, aor, contactUser, transport, authNonce, authCnonce, authResponse, securityServer, pcscf; + std::optional callid, ftag, route, ppi, aor, contactUser, transport, authNonce, authCnonce, authResponse, securityServer, pcscf, impi, domain, impu; std::optional cseq, spiUc, spiUs, expiry; }; std::optional LoadState() { @@ -873,6 +1094,9 @@ std::optional LoadState() { ps.authResponse = QuotedAfter(s, "\"auth_response\": \""); ps.securityServer = QuotedAfter(s, "\"security_server\": \""); // absent in pre-0.3.12 files ps.pcscf = QuotedAfter(s, "\"pcscf\": \""); // absent in pre-1.0.0 files + ps.impi = QuotedAfter(s, "\"impi\": \""); // the three absent in pre-1.2.3 files + ps.domain = QuotedAfter(s, "\"domain\": \""); + ps.impu = QuotedAfter(s, "\"impu\": \""); ps.cseq = IntAfter(s, "\"cseq\": "); ps.spiUc = IntAfter(s, "\"spi_uc\": "); ps.spiUs = IntAfter(s, "\"spi_us\": "); @@ -898,7 +1122,7 @@ struct StatusSnapshot { // engine -> main-loop event struct Event { - enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState } type; + enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState, Work } type; CallInfo info; // Added std::string uni, state, reason; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id) StatusSnapshot status; // Registration/Status @@ -907,6 +1131,7 @@ struct Event { std::int64_t at = 0; // SmsReceived: when it arrived (epoch seconds) std::string to; // SmsReceived: the subscriber it arrived for (the own number the daemon held then) std::string simOperator; // SmsReceived: the operator id of the SIM it arrived under + bool on = false; // Work: a registration step or a text's sending wants the work's lock (true: at its begin, after its wait for a hold) or no longer does (at its end, for such a wait) }; GDBusConnection* DbusConn = nullptr; @@ -1283,11 +1508,90 @@ GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt return g_variant_builder_end(&b); } +// ---- logind's inhibitor for sleep (main thread only) ----------------------- +// Nothing of imsd runs while the phone is suspended: a suspend under a +// call stops this daemon and the call's media leg for as long as the +// phone sleeps. So imsd takes logind's block inhibitor for sleep while +// the calls table holds a call: from the call's addition (an incoming +// call's ringing; for a Dial after the recovery's try on a dead flow and +// the PANI refresh) to its removal. Under it logind refused a plain +// `systemctl suspend` on the dev phone; a request can tell it to ignore +// inhibitors (`systemctl suspend -i`). +// Where it was asked for during a suspend's operation logind refused this lock (systemd 262 on the +// dev phone: refused in a suspend's hooks before and after the sleep and +// to a call 0.1 to 0.3 s after the resume, given once logind had logged +// the operation's "finished"). So a lock that is wanted and not held is +// asked for again when logind sends PrepareForSleep with false; one +// wanted before the bus connection is there, when it comes. +// Where logind gives no lock at all (the session bus of --session has no +// logind) calls go on without one. The journal says so once until a +// call's lock is next given. +// A second lock is asked for, in the way the call's is, while the engine has work in flight that waits for +// the network: a step of the registration (Engine::Step) or a text being +// sent. A suspend under one would leave it where it stood until something +// wakes the phone: a text's waits count awake seconds. It is asked for where it is wanted and not +// held, released when nothing wants it any more, and the journal has no line for any of that. +struct SleepLock { + const char* why; // logind's "why": what the lock is held for + bool told; // its taking, its release and a refusal go to the journal + bool want = false; + int fd = -1; // the inhibitor's file descriptor (-1: not held) +}; +SleepLock CallLock{"a call", true}; +SleepLock WorkLock{"a registration step or a text in flight", false}; +int WorksInFlight = 0; // the engine's Work events, true less false: what wants the work's lock now (a step that waits out a hold is not in it) +bool NoSleepLockTold = false; // the journal has a refusal's line since a call's lock was last given +void HoldSleepOff(SleepLock& lock, bool want) { + lock.want = want; + if (want == (lock.fd >= 0)) return; + if (!want) { + close(lock.fd); + lock.fd = -1; + if (lock.told) Log("sleep is no longer held off (no call)"); + return; + } + if (!DbusConn) return; + GError* err = nullptr; + GUnixFDList* fds = nullptr; + GVariant* r = g_dbus_connection_call_with_unix_fd_list_sync( + DbusConn, "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "Inhibit", + g_variant_new("(ssss)", "sleep", "imsd", lock.why, "block"), G_VARIANT_TYPE("(h)"), + G_DBUS_CALL_FLAGS_NONE, 2000, nullptr, &fds, nullptr, &err); + if (r) { + gint32 handle = -1; + g_variant_get(r, "(h)", &handle); + g_variant_unref(r); + if (fds && handle >= 0) lock.fd = g_unix_fd_list_get(fds, handle, nullptr); + } + if (fds) g_object_unref(fds); + if (lock.fd >= 0) { + if (lock.told) { + Log("sleep is held off while the call lasts (logind's inhibitor)"); + NoSleepLockTold = false; + } + } else if (lock.told && !NoSleepLockTold) { + Log(std::format("no sleep inhibitor from logind ({}): asked again when it says a sleep is over", err ? err->message : "no file descriptor in its answer")); + NoSleepLockTold = true; + } + g_clear_error(&err); +} +// logind's PrepareForSleep: at one with false, a lock that is wanted and +// not held is asked for. +void OnPrepareForSleep(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer) { + if (!g_variant_is_of_type(params, G_VARIANT_TYPE("(b)"))) return; + gboolean entering = TRUE; + g_variant_get(params, "(b)", &entering); + if (entering) return; + HoldSleepOff(CallLock, CallLock.want); + HoldSleepOff(WorkLock, WorkLock.want); +} + gboolean OnIdleEvent(gpointer data) { std::unique_ptr ev(static_cast(data)); switch (ev->type) { case Event::Type::Added: { Calls[ev->info.uni] = ev->info; + HoldSleepOff(CallLock, true); EmitSignal("CallAdded", g_variant_new("(s@a{sv})", ev->info.uni.c_str(), CallVariant(ev->info))); break; } @@ -1303,6 +1607,7 @@ gboolean OnIdleEvent(gpointer data) { } case Event::Type::Deleted: Calls.erase(ev->uni); + HoldSleepOff(CallLock, !Calls.empty()); EmitSignal("CallDeleted", g_variant_new("(s)", ev->uni.c_str())); break; case Event::Type::Registration: @@ -1323,6 +1628,10 @@ gboolean OnIdleEvent(gpointer data) { Log(std::format("idle: {} — nothing to do; systemctl start imsd when that changes", ev->text)); g_main_loop_quit(MainLoop); break; + case Event::Type::Work: + WorksInFlight = std::max(0, WorksInFlight + (ev->on ? 1 : -1)); + HoldSleepOff(WorkLock, WorksInFlight > 0); + break; case Event::Type::SmsReceived: for (const std::string& to : Subscribers) EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms, ev->at, ev->to, ev->simOperator))); @@ -1380,7 +1689,15 @@ public: outDir_ = EnvOr("OUT_DIR", StateDir()); rtpPort_ = std::atoi(EnvOr("RTP_PORT", "50004").c_str()); precond_ = EnvOr("PRECOND", "0") == "1"; - ealgOffer_ = EnvOr("EALG", "aes-cbc"); + // EALG: the ESP ciphers Security-Client offers, in the order + // written (imsd::ipsec::ParseEalgOffer: with no cipher named, the + // default list). A name imsd cannot install is passed over with a + // line. + { + imsd::ipsec::EalgSetting ealg = imsd::ipsec::ParseEalgOffer(EnvOr("EALG", "")); + for (const std::string& u : ealg.unknown) Log(std::format("EALG entry '{}' is not a cipher imsd can install; ignored", u)); + ealgOffer_ = std::move(ealg.ciphers); + } // SIP_TRANSPORT: the protected leg's transport. auto (default) = TCP, // and when the P-CSCF never answers the TCP connect, a fresh // registration over UDP; tcp / udp force one. The challenge (first @@ -1391,6 +1708,16 @@ public: sipPolicy_ = "auto"; } transport_ = sipPolicy_ == "udp" ? Transport::Udp : Transport::Tcp; + // CRLF_KEEPALIVE=: an RFC 5626 4.4.1 ping that often on the + // idle TCP flow, for a P-CSCF that drops a flow it hears nothing on. + // None by default (until 1.2.3: one every 30 s): no registration of + // imsd's negotiates them, and a ping can wake a suspended phone + // afterwards (AGENTS.md §13). An empty value is as none; any other + // that is no whole number of seconds is reported and sends none. + if (std::string v = EnvOr("CRLF_KEEPALIVE", ""); !v.empty()) { + if (auto s = imsd::util::WholeSeconds(v)) crlfKeepalive_ = *s; + else Log(std::format("CRLF_KEEPALIVE={} is not a whole number of seconds; no CRLF keepalive", v)); + } mediaBin_ = ResolveMediaBin(); // CODECS: restrict + reorder the codecs we offer and accept (bench // knob — a gateway that transcodes every caller up to AMR-WB never @@ -1482,6 +1809,7 @@ public: } for (;;) { try { + Step step(*this); BringUp(); break; } catch (const Stopping&) { @@ -1514,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(); @@ -1548,12 +1877,14 @@ public: MaybeRefresh(); MaybeReconnect(); MaybeResubscribe(); - if (!call_ && sip_.Alive() && Mono() - lastKa_ > 30) { sip_.SendKeepalive(); lastKa_ = Mono(); } + MaybeResendInvite(); + if (crlfKeepalive_ > 0 && !call_ && sip_.Alive() && Mono() - lastKa_ > crlfKeepalive_) { sip_.SendKeepalive(); lastKa_ = Mono(); } ReapMedia(); if (call_ && call_->State() != imsd::engine::CallState::Active && Mono() > deadline_) { Execute(call_->OnDeadline()); MaybeDropCall(); } + ArmWake(WakeDue()); if (auto msg = sip_.RecvMsg(0.3)) OnFlowMessage(*msg); } // shutdown: release an active call, keep the SA/registration for resume @@ -1615,11 +1946,19 @@ private: // after it, not before. False when the engine is stopping. bool WaitForPolicy() { bool waited = false; + // No lock under this wait, which can be an hour: nothing is waited + // for from the network, and the alarm ends a sleep at its end. For a + // step it is called from (the bring-up's) the lock is asked for again after. + const int paused = !quit_.load() && recovery_.Next(Boot()).at > Boot() ? steps_ : 0; + for (int i = 0; i < paused; i++) PostWork(false); while (!quit_.load() && recovery_.Next(Boot()).at > Boot()) { waited = true; if (auto cmd = PopCmd()) { HandleCmd(*cmd); MaybeDropCall(); continue; } + ArmWake(recovery_.Next(Boot()).at); // a wait the phone sleeps under ends with the phone awake std::this_thread::sleep_for(std::chrono::seconds(1)); } + for (int i = 0; i < paused; i++) PostWork(true); + if (waited) netAlarm_(); // the wait's alarm has fired where the phone slept under it if (waited && !quit_.load()) RefreshPani(); return !quit_.load(); } @@ -1628,7 +1967,7 @@ private: // what follows a resume that failed: with a fresh target the fresh // registration, without one the restart's new resume attempt std::string ResumeFailedNext() const { return pcscfTarget_.empty() ? "the restart tries the resume again" : "the next registration is a fresh one"; } - // a pair nothing can resume (no state file, the file another attempt's): with a fresh target the fresh registration replaces it; with none BringUp writes it off and takes it out of the kernel + // a pair nothing can resume (no state file, the file another attempt's or its identity failing the check): with a fresh target the fresh registration replaces it; with none BringUp writes it off and takes it out of the kernel std::string ResumeDeadNext() const { return pcscfTarget_.empty() ? "nothing can resume it: the pair is removed" : "resume falls back to fresh"; } // the failed resume's line tail by the engine's verdict: a registration it // wrote off is removed (no fresh target) or replaced by the fresh one; with @@ -1650,7 +1989,9 @@ private: } // config - std::string pcscf_, dev_, outDir_, local_, ealgOffer_, mediaBin_; + std::string pcscf_, dev_, outDir_, local_, mediaBin_; + long crlfKeepalive_ = 0; // CRLF_KEEPALIVE=: seconds between pings on the idle TCP flow; 0: none + std::vector ealgOffer_; // the ESP ciphers offered, in order // The P-CSCF a fresh registration goes to (PCSCF=, else the first of // PCSCF_DISCOVERED=) and the whole discovered list. pcscf_ is the one in // use: the same, or the kernel's SA peer while a resumed registration @@ -1676,6 +2017,22 @@ private: // registration imsd::msg::Context ctx_; RegState reg_; + // The identity the card gives — its ISIM's, else the one derived from + // the IMSI — and the derived one. A fresh registration is made under the + // first. A resumed one keeps the identity it was made under (reg_.id) + // until the next fresh registration, as it keeps its P-CSCF and its + // address: the binding to refresh is the one made under those names. + imsd::aka::Identity cardId_; + imsd::aka::Identity derivedId_; + // The card's USIM: the challenge goes to it when the identity is not an + // ISIM's, and after an ISIM that gave the identity and gives no result + // for the challenge. + std::string usimAid_; + // The ISIM application that has given no identity since the bring-up: + // asked again at each recovery by a fresh registration later in the + // same run (FreshRecover), which else would go out under the derived + // names. + std::optional isimOwed_; std::string route_, ppi_, ss_; std::string simOperator_; // the SIM's operator id as read at bring-up: MCC then MNC bool registered_ = false; @@ -1685,9 +2042,10 @@ private: bool subPending_ = false; // SUBSCRIBE sent, no final yet double subSentAt_ = 0; double subRetryAt_ = 0; // a failed/ended subscription is renewed at this time (0: none due) - double subRenewAt_ = 0; // the live subscription is subscribed anew at this time, ahead of its granted expiry (0: none) + 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) @@ -1707,8 +2065,10 @@ private: std::function callReply_; // timers - double lastRefresh_ = 0; - double lastKa_ = 0; + double lastRefresh_ = 0; // on the boot clock (Boot): the registration's lifetime runs at the network while the phone sleeps + double lastKa_ = 0; // on the steady clock (Mono) + int wakeFd_ = -1; // the wake alarm, a timer on CLOCK_BOOTTIME_ALARM (-2: the kernel gave none) + double wakeAt_ = 0; // the boot-clock time it was last armed for, fired or not (0: not armed) std::atomic quit_{false}; bool devMode_ = false; @@ -1744,6 +2104,133 @@ private: return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); } + // The refresh's interval: half the granted lifetime (of 3600 s where none + // was granted), within 120-1800 s (REFRESH_INTERVAL= sets it). + double RefreshInterval() const { + if (const char* o = std::getenv("REFRESH_INTERVAL")) return std::atof(o); + long exp = reg_.expiry ? reg_.expiry : 3600; + return std::max(120.0, std::min(exp * 0.5, 1800.0)); + } + + // The wake alarm. The registration's lifetime runs at the network while + // the phone sleeps, and the steady clock does not: a refresh counted in + // awake seconds comes too late for a phone that sleeps most of the time + // (the dev phone, 2026-11-19: asleep for most of a registration's two hours, no refresh, the + // binding expired). So the refresh is due on the boot clock, and a timer + // on CLOCK_BOOTTIME_ALARM, armed by the loop for the time WakeDue names (ArmWake's other callers arm their own), makes the + // kernel wake a sleeping phone then (its RTC's alarm; CAP_WAKE_ALARM, + // which the system service has). The descriptor is never read: the + // waking is the whole of it, and the loop's own clock checks act once + // the phone is awake. Where the kernel gives no such timer the journal + // says so once and the daemon runs without: awake, nothing differs. + void ArmWake(double at) { + if (wakeTrace_) TraceWake(at); + if (wakeFd_ == -2 || at == wakeAt_) return; + if (wakeFd_ < 0) { + // the timer can be had without an RTC behind it, and then + // neither wakes the phone nor makes the kernel refuse a suspend: + // the clock's resolution is what the kernel answers only with one + timespec res{}; + if (clock_getres(CLOCK_BOOTTIME_ALARM, &res) != 0) { + Log("no wake alarm (no RTC that can wake the phone): a sleeping phone is not woken for the registration's refresh"); + wakeFd_ = -2; + return; + } + wakeFd_ = timerfd_create(CLOCK_BOOTTIME_ALARM, TFD_CLOEXEC); + if (wakeFd_ < 0) { + Log(std::format("no wake alarm ({}): a sleeping phone is not woken for the registration's refresh", std::strerror(errno))); + wakeFd_ = -2; + return; + } + Log("wake alarm: a sleeping phone is woken when the registration's refresh is due"); + } + itimerspec its{}; // all zero disarms + if (at > 0) { + its.it_value.tv_sec = static_cast(at); + its.it_value.tv_nsec = static_cast((at - std::floor(at)) * 1e9); + } + if (timerfd_settime(wakeFd_, TFD_TIMER_ABSTIME, &its, nullptr) < 0) { + Log(std::format("wake alarm not set: {}", std::strerror(errno))); + return; + } + wakeAt_ = at; + } + // What the loop arms the alarm for at the end of a turn that took no + // command off the queue (one that took a command handles it and goes + // straight to the next turn). A time that has come (a call, a text in + // flight; a step that is due, which the next turn runs) is armed + // WakeHold ahead at every such turn: the kernel refuses a suspend + // that finds an alarm less than two seconds ahead at its check (alarmtimer_suspend), + // whoever asks for it. For a step that follows a local wait (no + // packet service, a connect the kernel refused) the policy names the + // slower look's time: with no call and no text in flight nothing is + // held then. + static constexpr double WakeHold = 1.9; + // WAKE_TRACE=1, a test seam: a line whenever the time the alarm is + // armed for changes (by the second), with or without a timer to arm (a + // bench has none). A time under two seconds ahead is "held", said once + // while it lasts. + const bool wakeTrace_ = EnvOr("WAKE_TRACE", "0") == "1"; + std::string wakeTraced_; + void TraceWake(double at) { + double ahead = at - Boot(); + std::string s = at <= 0 ? "none" : ahead < 2 ? "held under 2 s ahead" : std::format("{:.0f} s on the boot clock", at); + if (s == wakeTraced_) return; + wakeTraced_ = s; + Log(at > 0 && ahead >= 2 ? std::format("wake trace: {} ({:.0f} s ahead)", s, ahead) : std::format("wake trace: {}", s)); + } + double WakeDue() const { + bool recovering = portPs_ != 0 && !reg_.callid.empty(); // MaybeReconnect's own condition + bool renewal = registered_ && !subCallid_.empty() && !subPending_; // MaybeResubscribe's own, with the live flow + double now = Boot(); + double at = imsd::engine::WakeAt(now, call_.has_value() || smsOut_.has_value(), !reg_.callid.empty() && sip_.Alive(), + lastRefresh_ + RefreshInterval(), renewal ? subRenewAt_ : 0, + recovering, recovering ? recovery_.WakeTime(now) : 0); + return at > 0 && at < now + WakeHold ? now + WakeHold : at; + } + // A step of the registration that exchanges with the network: the + // refresh, a reconnect, a fresh registration, the bring-up. The main + // thread asks for logind's sleep lock while one runs (WorkLock, which a + // text in flight wants as well; held where logind gives it), so that the step's waits run their + // awake seconds in one piece; not while the bring-up waits out a hold + // (WaitForPolicy). For a sleep that begins under a step all the same + // (logind refused such a lock on the dev phone where a suspend's operation was already running; a suspend + // told to ignore inhibitors) the alarm stands at most WakeNet ahead + // while the step waits for the network: set as it begins, and anew + // before every second of a connect's wait, of the pause before the next + // try and of a wait for a REGISTER's answer. It fires once, and a wait + // can outlast the sleep it ended: set every second, it stands again + // within a second of that wake, for the sleep that may follow. Where there is an alarm the + // sleep ends there, a lock logind had refused is asked for at its end (one held is kept), and the step goes + // on. A wait for a helper program (mmcli, qmicli, ip) has the alarm + // that stood when it began, once. After the step + // the loop's own arming takes over again (WakeDue). + static constexpr double WakeNet = 30; + struct Step { + explicit Step(Engine& engine) : e(engine) { e.steps_++; e.PostWork(true); e.netAlarm_(); } + ~Step() { e.steps_--; e.PostWork(false); } + Step(const Step&) = delete; + Step& operator=(const Step&) = delete; + Engine& e; + }; + int steps_ = 0; // the steps under way: what a hold's wait pauses (WaitForPolicy) + bool noServiceTold_ = false; // the journal has the line of the coverage gap that runs + // What a step sets the alarm to as it begins and before every second of + // its waits for the network: WakeNet ahead, also where a call or a text + // is in flight (the loop's WakeHold needs setting anew within two + // seconds, which a helper program's wait does not give: under a step + // the sleep is bounded, not refused). + const std::function netAlarm_ = [this] { ArmWake(Boot() + WakeNet); }; + // The connect for a call's resend is no step: no helper program runs + // under it, and the loop arms again at the end of the turn it runs in. + // It keeps the loop's hold through its wait, set anew every second. + const std::function holdAlarm_ = [this] { ArmWake(Boot() + WakeHold); }; + void PostWork(bool on) { + auto ev = std::make_unique(); + ev->type = Event::Type::Work; ev->on = on; + PostEvent(std::move(ev)); + } + std::optional PopCmd() { std::scoped_lock g(cmdLock_); if (cmds_.empty()) return std::nullopt; @@ -1760,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 @@ -1789,12 +2284,19 @@ private: auto siminfo = RunCapture({"mmcli", "-i", *simPath}); auto info = imsd::aka::ParseSimInfo(siminfo.out); if (!info) throw std::runtime_error("SIM IMSI/operator not found"); - ctx_.id = imsd::aka::MakeIdentity(info->imsi, info->mcc, info->mnc); + derivedId_ = imsd::aka::MakeIdentity(info->imsi, info->mcc, info->mnc); + cardId_ = derivedId_; simOperator_ = info->mcc + info->mnc; ctx_.local = local_; ctx_.ealgOffer = ealgOffer_; SetTransport(transport_); Log(std::format("SIP transport: {} ({})", TransportName(transport_), sipPolicy_)); + if (crlfKeepalive_ > 0) Log(std::format("CRLF keepalive: every {} s on an idle TCP flow (CRLF_KEEPALIVE)", crlfKeepalive_)); + { + std::string list; + for (const std::string& e : ealgOffer_) list += (list.empty() ? "" : ", ") + e; + Log(std::format("ESP ciphers offered: {}", list)); + } // USER_AGENT overrides (some networks fingerprint UAs — setting the // stock firmware's build string gives oracle parity, journal/ims.md // s53); USER_AGENT= (empty) omits the header. @@ -1802,7 +2304,26 @@ private: if (auto imei = imsd::aka::ParseEquipmentId(modem.out)) if (auto urn = imsd::aka::ImeiUrn(*imei)) ctx_.instanceId = *urn; reg_.slot = sel->slot; - reg_.aid = sel->aid; + reg_.aid = usimAid_ = sel->aid; + // The identity so far is the one TS 23.003 derives from the IMSI, + // the names of a UE without an ISIM (TS 24.229 5.1.1.1A). When the + // card's ISIM gives an identity, that one is the card's and the + // challenge goes to the ISIM. The names can be the operator's own: a US + // card on AT&T's network holds @private.att.net and + // one.att.net, and the derived names drew a 480 to the first + // REGISTER there (2026-11-09; the read of the card 2026-11-23, + // AGENTS.md §13). An ISIM that gives none leaves the derived + // identity and the USIM, what 1.2.2 registered with; ISIM=0 asks for + // that. + std::optional app; + if (EnvOr("ISIM", "1") == "0") { + Log("identity: derived from the IMSI (ISIM=0)"); + } else { + app = imsd::aka::ParseIsimApp(card.out, sel->slot); + if (!app) Log("identity: derived from the IMSI (the card has no ISIM application)"); + } + isimOwed_ = app && !TakeIsimIdentity(*app) ? app : std::nullopt; + ctx_.id = cardId_; Log(std::format("SIM slot={} IMSI={} domain={}", sel->slot, info->imsi, ctx_.id.domain)); ctx_.smsOverIp = smsOverIp_; if (smsOverIp_) LoadSmsParameters(); @@ -1860,7 +2381,8 @@ private: // binding; a 401, a refusal with a Retry-After, the second refusal — // the count travels in the holds; Dead above); a pair nothing can // resume (its UE address left the link, no - // state file, the file another attempt's, written off before this + // state file, the file another attempt's or its identity failing + // the check, written off before this // start) is written off and taken out of the kernel by exact key // — the fresh registration that would have replaced it does not // come — so the next bring-up finds nothing to resume, and the @@ -1868,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{}; @@ -1954,11 +2476,27 @@ private: sa->spiUc, sa->spiUs, pcscf_, ResumeDeadNext())); return ResumeOutcome::Dead; } + // The registration's identity is the one it was made under, whatever + // the card gives today: the file's since 1.2.3, and for an older file + // the derived one, under which 1.2.2 registered. A file whose three + // names are no identity imsd can write names a registration nothing + // can refresh, whatever else the file holds: judged before the + // transport, as the file of another attempt is. + imsd::aka::Identity made = derivedId_; + if (ps->impi || ps->domain || ps->impu) { + auto filed = imsd::aka::IsimIdentity(derivedId_, ps->impi.value_or(""), ps->domain.value_or(""), ps->impu.value_or("")); + if (!filed) { Log(std::format("the state file's identity is not one imsd can register; {}", ResumeDeadNext())); return ResumeOutcome::Dead; } + made = *filed; + } // The registration's transport is what the P-CSCF knows; a resume // must reuse it. A forced policy that disagrees means a fresh start // — decided before anything from the file is adopted. Transport t = ps->transport.value_or("TCP") == "UDP" ? Transport::Udp : Transport::Tcp; if (sipPolicy_ != "auto" && t != transport_) { Log(std::format("state file transport differs from SIP_TRANSPORT; {}", ResumeFailedNext())); return ResumeOutcome::Failed; } + if (!SameNames(made, cardId_)) + Log(std::format("identity: the registration to resume was made under private identity {}, home domain {}, public identity {}; it keeps them until the next fresh registration, which takes the card's", made.impi, made.domain, made.impu)); + ctx_.id = made; + reg_.id = made; route_ = ps->route.value_or(std::format("", imsd::util::HostPort(pcscf_, sa->portPs))); // No fallback identity: an empty ppi omits P-Preferred-Identity and @@ -1968,8 +2506,9 @@ private: // SUBSCRIBE and the INVITEs echo: the 401's whole Security-Server // list (RFC 3329 §2.3.1), from the state file since 0.3.12, or the // one-mechanism entry rebuilt from the SA — Imsd:Ipsec chooses - // (ChooseResumeSecurityVerify). The rebuilt entry is KPN's answer to - // the default offer in the same bytes, not a list such as O2's six, + // (ChooseResumeSecurityVerify). The rebuilt entry names the pair's + // own algorithms: KPN's answer to the default offer in the same + // bytes, not a list such as O2's six, // which the RFC has the server answer with a 494; a refused resume // registers fresh where there is a fresh target (§7.2 step 1 otherwise). auto rsv = imsd::ipsec::ChooseResumeSecurityVerify(ps->securityServer.value_or(""), *sa, ealgOffer_); @@ -1989,20 +2528,23 @@ private: } // The public identity our requests are signed with (From) — restored // here so a call placed before the refresh 200 re-learns it does not - // fall back to the barred temporary IMPU. + // fall back to the identity's own (for a registration made under the + // derived names, the temporary IMPU). ctx_.aor = ps->aor.value_or(""); ctx_.route = route_; ctx_.ppi = ppi_; ctx_.securityServer = ss_; ctx_.portUc = PortUc; ctx_.portUs = PortUs; 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. - if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2)) { + if (!sip_.Connect(local_, PortUc, pcscf_, sa->portPs, transport_, 10, 2, netAlarm_)) { Log(std::format("resume connect failed; {}", ResumeFailedNext())); return ResumeOutcome::Failed; } + if (transport_ == Transport::Tcp) recovery_.OnNetworkAnswered(); reg_.callid = *ps->callid; reg_.ftag = ps->ftag.value_or(""); // The refresh must carry the SAME Contact URI as the stored binding; @@ -2035,18 +2577,48 @@ private: Log(std::format("binding: {}", ct)); } + // The ISIM application's identity for the card: when the three files + // read and pass the check it is the card's, and the challenge goes to + // the ISIM. The journal's `identity:` line says which way it went. + bool TakeIsimIdentity(const imsd::aka::IsimApp& app) { + std::string state = app.state.empty() ? "unknown" : app.state; + std::string why; + auto id = ReadIsimIdentity(reg_.slot, app, derivedId_, why); + if (!id) { + Log(std::format("identity: derived from the IMSI: the ISIM application (state {}) gave none — {}", state, why)); + return false; + } + cardId_ = *id; + reg_.aid = app.aid; + Log(std::format("identity: the ISIM's (application state {}): private identity {}, home domain {}, public identity {}; {}", + state, id->impi, id->domain, id->impu, + SameNames(cardId_, derivedId_) ? "the names the IMSI gives" : std::format("not the names the IMSI gives (home domain {})", derivedId_.domain))); + return true; + } + // A fresh registration. The attempt mints its own Contact user-part into // ctx_ for its REGISTERs; on any failure the stored binding's comes back, // so requests over the existing SA meanwhile (a reconnect, a refresh) // carry the binding the network knows. reg_ takes the new one on the 200. + // The identity goes the same way: the attempt registers the card's + // (cardId_), and on a failure the one ctx_ held before it comes back — + // a resumed registration's can be another than the card's (TryResume). void FreshRegister() { saReplaced_ = false; + imsd::aka::Identity before = ctx_.id; try { FreshRegisterAttempt(); } - catch (...) { ctx_.contactUser = reg_.contactUser; throw; } + catch (...) { + ctx_.contactUser = reg_.contactUser; + ctx_.id = before; + throw; + } } void FreshRegisterAttempt() { Log("FRESH registration"); + if (!SameNames(ctx_.id, cardId_)) + Log(std::format("identity: the fresh registration takes the card's: private identity {}, home domain {}, public identity {}", cardId_.impi, cardId_.domain, cardId_.impu)); + ctx_.id = cardId_; // Oracle diff (journal/ims.md s53): stock's Contact user-part is a // fresh UUID per registration, not the IMSI. Minted before reg1 so // both REGISTERs and the stored binding carry the same URI. @@ -2085,7 +2657,7 @@ private: std::vector autn16(raw->begin() + 16, raw->begin() + 32); // Every Security-Server instance is one comma-list (RFC 3261 // §7.3.1); the joined value is what Security-Verify echoes — RFC - // 3329 §2.2 wants the whole list back, not the chosen entry. + // 3329 §2.3.1 wants the whole list back, not the chosen entry. auto ssLines = imsd::sip::Headers(resp, "Security-Server"); if (ssLines.empty()) throw std::runtime_error("no Security-Server"); ss_.clear(); @@ -2094,8 +2666,8 @@ private: ss_ += line; } Log(std::format("Security-Server: {}", ss_)); - // Algorithms from the mechanism we select against our offer (RFC - // 3329 §2.3.1), SPIs/ports from the entry carrying them (O2 lists + // Algorithms from the mechanism ParseSecurityServer selects against + // our offer, SPIs/ports from the entry carrying them (O2 lists // six and marks one; ims ledger F11). An answer we cannot use is a // deferral on the throttle schedule, not a fatal: a fatal restarts // imsd every RestartSec, an initial REGISTER each time. @@ -2132,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; @@ -2163,7 +2738,7 @@ private: } } bool autoTcp = (sipPolicy_ == "auto" && transport_ == Transport::Tcp && !tcpKnownGood); - if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0)) { + if (!sip_.Connect(local_, PortUc, pcscf_, portPs, transport_, 10, autoTcp ? 2 : 0, netAlarm_)) { if (autoTcp) { // Two unanswered TCP connects: treat the P-CSCF as UDP-only // and register again over UDP — a new challenge and a new SA @@ -2189,6 +2764,7 @@ private: } reg_.callid = callidReg; reg_.ftag = ftag; reg_.cseq = 2; reg_.contactUser = contactUser; + reg_.id = ctx_.id; reg_.spiUc = spiUc; reg_.spiUs = spiUs; reg_.authNonce = *nonceB64; reg_.authCnonce = cnonce; reg_.authResponse = response; reg_.securityServer = ss_; @@ -2231,7 +2807,8 @@ private: double deadline = Mono() + 12.0; for (;;) { double left = deadline - Mono(); - auto m = left > 0 ? sip_.RecvMsg(left) : std::nullopt; + // the alarm is set anew before every second of the wait (Step) + auto m = left > 0 ? sip_.RecvMsg(left, netAlarm_) : std::nullopt; if (!m) throw std::runtime_error(std::format("no reply to {}", what)); auto st = imsd::sip::Status(*m); if (!st) { @@ -2244,6 +2821,7 @@ private: if (!OnSubscribeResponse(*m, *st) && !OnSmsResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what)); continue; } + recovery_.OnNetworkAnswered(); // a response to our REGISTER, whatever it says: the network is in reach if (*st >= 200) return *m; Log(std::format("{} -> {} (provisional); waiting for the final", what, *st)); deadline = Mono() + 12.0; @@ -2265,6 +2843,9 @@ private: for (;;) { double left = deadline - Mono(); if (left <= 0) break; + // in pieces of a second, the alarm set anew before each (Step) + netAlarm_(); + left = std::min(left, 1.0); long sec = static_cast(left); long usec = static_cast((left - static_cast(sec)) * 1e6); if (sec == 0 && usec == 0) usec = 1000; @@ -2272,7 +2853,14 @@ private: setsockopt(us, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv); sockaddr_storage src; socklen_t sl = sizeof src; ssize_t n = recvfrom(us, buf, sizeof buf, 0, reinterpret_cast(&src), &sl); - if (n < 0) break; + if (n < 0) { + // a piece is over, or the receive was interrupted (EINTR: by + // a suspend's freeze, after which the kernel takes a poll up + // again but not a datagram receive under a timeout; by a stop and a + // continue; by a signal handled here): the deadline is looked at above + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) continue; + break; + } const int sp = PortOf(src); std::string why; auto framed = imsd::sip::DatagramMessage(std::string_view(buf, static_cast(n)), &why); @@ -2287,6 +2875,7 @@ private: continue; } int st = *imsd::sip::Status(m); + recovery_.OnNetworkAnswered(); if (st >= 200) { close(us); return m; } Log(std::format("unprotected REGISTER -> {} (provisional); waiting for the final", st)); deadline = Mono() + 8.0; @@ -2318,6 +2907,15 @@ private: do spiUs = rng_.UInt(0x10000, 0xFFFFFFF); while (spiUs == reg_.spiUc || spiUs == reg_.spiUs || spiUs == spiUc); std::string reg = imsd::msg::BuildRegisterProtected(ctx_, callid, ftag, rng_.Token(16), cseq, spiUc, spiUs, auth, PortUcNext); if (!sip_.Send(reg)) throw std::runtime_error("send re-REGISTER failed"); + // Sent, the number is used, whatever comes back: the next REGISTER + // on this Call-ID carries a higher one (RFC 3261 10.2), where a + // registrar that took this one and whose answer did not arrive + // refuses the same number (10.3 step 7; KPN answered 482 Loop + // Detected where, by 1.2.4's code, two re-REGISTERs carried an + // unanswered refresh's: the dev phone, 2026-11-25). After a restart + // too: the state file has the number before the answer is waited for. + reg_.cseq = cseq; + PersistState(reg_, route_, ppi_, ctx_.aor, ctx_.transport, pcscf_); std::string m = AwaitFinal(callid, cseq, "re-REGISTER"); auto st = imsd::sip::Status(m); if (st == 200) return {m, cseq}; @@ -2370,44 +2968,47 @@ private: Log(std::format("self AOR: {}", ctx_.aor.empty() ? ctx_.id.impu : ctx_.aor)); } - // USIM AKA via qmicli UIM logical channel. + // AKA in the card: the challenge to the application that goes with the + // card's identity (reg_.aid: the ISIM when the identity was read from it, + // else the USIM), over a UIM logical channel. The command is the same in + // both: AUTHENTICATE with P2 '81' is the 3G context of a USIM (TS 31.102 + // 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. std::optional Authenticate(std::span rand16, std::span autn16) { - auto open = RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-open-logical-channel={},{}", reg_.slot, reg_.aid)}); - auto ch = CompletedInt(open.out); - if (!ch) return std::nullopt; - int channel = static_cast(*ch); - auto closeCh = [&] { - RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-close-logical-channel={},{}", reg_.slot, channel)}); - }; - std::string apdu = imsd::aka::BuildAkaApdu(channel, rand16, autn16); - auto r1 = RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-send-apdu={},{},{}", reg_.slot, channel, apdu)}); - auto b1 = CompletedHex(r1.out); - if (!b1) { closeCh(); return std::nullopt; } - if (b1->size() >= 2 && b1->substr(0, 2) == "61") { - std::string gr = imsd::aka::BuildGetResponseApdu(channel, std::stoi(b1->substr(2, 2), nullptr, 16)); - auto r2 = RunCapture({"qmicli", "-d", "qrtr://0", - std::format("--uim-send-apdu={},{},{}", reg_.slot, channel, gr)}); - b1 = CompletedHex(r2.out); - if (!b1) { closeCh(); return std::nullopt; } + std::string what; + auto result = AkaIn(reg_.aid, rand16, autn16, what); + if (!result && reg_.aid != usimAid_) { + Log(std::format("AKA: the ISIM application gave no result ({}); asking the USIM", what)); + result = AkaIn(usimAid_, rand16, autn16, what); } - closeCh(); - auto bytes = imsd::util::FromHex(*b1); - if (!bytes) return std::nullopt; - return imsd::aka::ParseAkaResponse(*bytes); + if (!result) Log(std::format("AKA: no result ({})", what)); + return result; + } + + // One AUTHENTICATE in the application `aid` of the card in reg_.slot; + // `what` says why there is no result. + std::optional AkaIn(const std::string& aid, std::span rand16, std::span autn16, std::string& what) { + UimChannel ch(reg_.slot, aid); + if (!ch.Open()) { what = "no logical channel opened"; return std::nullopt; } + auto answer = ch.Transmit(imsd::aka::BuildAkaApdu(ch.Number(), rand16, autn16)); + if (!answer) { what = "an exchange brought no answer with a status word"; return std::nullopt; } + auto result = imsd::aka::ParseAkaResponse(*answer); + if (!result) { + what = answer->data.empty() ? std::format("status word {}", answer->Status()) + : answer->data[0] == 0xDC ? std::string("a synchronisation failure, tag DC") + : std::format("{} bytes that are no AKA result, status word {}", answer->data.size(), answer->Status()); + } + return result; } // ---- keepalive refresh (only while idle) ------------------------------ void MaybeRefresh() { if (call_ || reg_.callid.empty()) return; if (!sip_.Alive()) return; // MaybeReconnect owns dead-flow recovery - long exp = reg_.expiry ? reg_.expiry : 3600; - double interval; - if (const char* o = std::getenv("REFRESH_INTERVAL")) interval = std::atof(o); - else interval = std::max(120.0, std::min(exp * 0.5, 1800.0)); - if (Mono() - lastRefresh_ < interval) return; + if (Boot() - lastRefresh_ < RefreshInterval()) return; + Step step(*this); try { RefreshPani(); auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1); @@ -2434,13 +3035,13 @@ private: Log(std::format("keepalive re-REGISTER failed: {}", e.what())); CloseFlowAfterWait(); } - lastRefresh_ = Mono(); + lastRefresh_ = Boot(); lastKa_ = Mono(); } // The protected client flow can die under us while the SA and the - // registration stay valid — a CSFB excursion resets it, the P-CSCF drops - // idle flows — which is exactly the state a daemon restart resumes from + // registration stay valid — a CSFB excursion resets it, a P-CSCF may drop + // an idle flow — which is exactly the state a daemon restart resumes from // (s51: "restart-to-recover"). Do what the restart does, in place: // reconnect the TCP leg over the existing SA and true-refresh. When that // keeps failing — the network refuses the refresh, or nothing answers — @@ -2455,6 +3056,31 @@ private: else ReconnectCycle(); } + // A client flow found dead under an outgoing call whose INVITE has 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 + // Reconnectable, and then nothing is reopened), and TS 33.203 7.1 has a + // UE that has no TCP connection towards the P-CSCF set one up before it + // sends a request. One connect, which waits 12 s for an answer; where + // it fails, and where the flow dies again under the resent INVITE, the + // call ends (CallMachine::OnFlowLost), and the recovery policy takes + // the flow up when the call is gone (MaybeReconnect). + void MaybeResendInvite() { + if (!call_ || sip_.Alive() || !call_->Unanswered()) return; + bool ok = false; + if (recovery_.Reconnectable() && call_->ResendDue()) { + Log(std::format("call {}: the client flow died before any response to the INVITE; reopening it", call_->Uni())); + sip_.Abort(); + ok = sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/1, 0, holdAlarm_) && Execute(call_->OnFlowReopened()); + } + if (!ok && call_ && !call_->Terminated()) Execute(call_->OnFlowLost()); + MaybeDropCall(); + } + // The policy's next step, as the journal line: what, and when. std::string NextStep() { auto plan = recovery_.Next(Boot()); @@ -2498,15 +3124,48 @@ private: // refuses while the old one is live, and drops it for. void CoverageGap(std::string_view what) { if (registered_) { registered_ = false; EmitStatus(true); } - recovery_.OnLocalRefusal(Boot()); + recovery_.OnLocalRefusal(Boot(), imsd::engine::RegRecovery::Local::NoService); Log(std::format("{} while the modem reports no packet service: not counted; {}", what, NextStep())); } + // While the modem reports no packet service the recovery tries nothing + // (this is its look before a reconnect cycle and before a fresh + // registration of its own; a bring-up does not ask): a reconnect would wait for answers that cannot come (over TCP + // two connects of 12 s, over UDP the re-REGISTER's 12 s), and a fresh registration its first REGISTER's 8 s, with the sleep + // lock held. The policy looks again LocalRetry on while the phone is + // awake, and wakes a sleeping one for a look at its slower pace + // (RegRecovery::WakeTime). One line where the modem is found without + // service, and again after a look that found it with. The modem's word + // does not start the gap's count over: only the network's answer does + // (RegRecovery::OnNetworkAnswered: the shell's calls and the policy's + // own). The look asks ModemManager, which can take its time: the alarm + // stands under it. A dead flow's socket that is still open does not + // outlive the look: left open through the wait a TCP one is readable at every + // turn of the loop (its end of file, its error), which would then spin + // instead of waiting, and a Dial's INVITE would be written into it. + // Abort, as at a call's reopen: a TCP FIN sent into a gap would hold the + // address pair against the reconnect after it, as a step's own close after an unanswered wait does (CloseFlowAfterWait). (A recovery step runs + // on a dead flow only: MaybeReconnect.) + bool NoService(std::string_view what) { + netAlarm_(); + if (PacketServiceUp()) { noServiceTold_ = false; return false; } + sip_.Abort(); + if (registered_) { registered_ = false; EmitStatus(true); } + recovery_.OnLocalRefusal(Boot(), imsd::engine::RegRecovery::Local::NoService); + if (!noServiceTold_) { + Log(std::format("the modem reports no packet service: {} waits until it has it again", what)); + noServiceTold_ = true; + } + return true; + } + void ReconnectCycle() { using F = imsd::engine::RegRecovery::Failure; + if (NoService("the reconnect")) return; Log("client flow dead; reconnecting"); + Step step(*this); sip_.Close(); - if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2)) { + if (!sip_.Connect(local_, PortUc, pcscf_, portPs_, transport_, /*tries=*/2, 0, netAlarm_)) { if (AddressGone()) return; if (sip_.LastConnectLocal()) { if (registered_) { registered_ = false; EmitStatus(true); } @@ -2517,6 +3176,10 @@ private: RecoveryFailed(F::Silent, 0, "P-CSCF silent"); return; } + // a TCP connect the P-CSCF answered: the network is in reach (a + // UDP "connect" says nothing of it; there a REGISTER's response + // does, in AwaitFinal) + if (transport_ == Transport::Tcp) recovery_.OnNetworkAnswered(); try { RefreshPani(); auto [msg, used] = Reregister(reg_.callid, reg_.ftag, reg_.cseq + 1); @@ -2565,7 +3228,9 @@ private: // nothing is retried until the next fresh attempt. void FreshRecover() { using F = imsd::engine::RegRecovery::Failure; + if (NoService("the fresh registration")) return; Log(std::format("registering fresh (recovery attempt {})", recovery_.freshAttempts + 1)); + Step step(*this); sip_.Close(); saReplaced_ = false; // this attempt's, whatever fails first // the subscription dialog is the registration's and goes with the @@ -2595,6 +3260,9 @@ private: bool ok = false; try { RefreshPani(); + // an ISIM that has given no identity since the bring-up is asked + // again: its names can be the only ones the network takes + if (isimOwed_ && TakeIsimIdentity(*isimOwed_)) isimOwed_.reset(); FreshRegister(); subRetryAt_ = 0; // a new registration: its subscription starts afresh OnRegistered(); @@ -2698,7 +3366,7 @@ private: bool was = registered_; registered_ = true; EmitStatus(!was); - lastRefresh_ = Mono(); lastKa_ = Mono(); + lastRefresh_ = Boot(); lastKa_ = Mono(); // a refresh or a reconnect opens no subscription dialog while imsd // holds one for the registration or has a retry scheduled; a fresh // registration (or a start) has none yet, and a fresh attempt drops @@ -2762,7 +3430,7 @@ private: ScheduleResubscribe(0); } if (call_ || !registered_ || !sip_.Alive()) return; - if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Mono() >= subRenewAt_) { + if (!subCallid_.empty() && !subPending_ && subRenewAt_ > 0 && Boot() >= subRenewAt_) { // the granted lifetime is running out: a new dialog (the S-CSCF // closes the previous one — KPN with noresource), on the same // registration @@ -2780,8 +3448,8 @@ private: // end, or halfway through a shorter grant. void ArmSubscriptionRenewal(long expires) { double ahead = expires > 1200 ? expires - 600.0 : expires / 2.0; - subRenewAt_ = Mono() + std::max(ahead, 30.0); - Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Mono())); + subRenewAt_ = Boot() + std::max(ahead, 30.0); + Log(std::format("reg-event: subscription granted {} s; renewed in {:.0f} s", expires, subRenewAt_ - Boot())); } // The network's view of our binding (RFC 3680 reginfo), read from any @@ -2976,6 +3644,7 @@ private: const bool wantsReport = p.statusReport; const std::string destination = p.number; smsOut_.emplace(ctx_, rng_, smsSubmitted_, id, std::move(p)); + PostWork(true); // the work's lock while it is in flight: its waits count awake seconds auto actions = smsOut_->Start(Mono()); // on record from the start — the SC may deliver segment 1 and report on // it while segment 2 is still in flight — and only for a message that @@ -2999,6 +3668,7 @@ private: void EndSms() { rpMr_ = smsOut_->NextRpMr(); smsOut_.reset(); + PostWork(false); } // The message in flight ended: the next queued message starts (its @@ -3588,6 +4258,11 @@ const GDBusInterfaceVTable MessagingVtable = { imsd::bus::Gatedmessage : "?")); if (err) g_error_free(err); return; } diff --git a/interfaces/Imsd-Aka.cppm b/interfaces/Imsd-Aka.cppm index 4671984..935e736 100644 --- a/interfaces/Imsd-Aka.cppm +++ b/interfaces/Imsd-Aka.cppm @@ -2,17 +2,26 @@ // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® /* -Imsd:Aka — USIM AKA (3GPP TS 33.102) glue for IMS registration: +Imsd:Aka — the card's side of an IMS registration: AKA (3GPP TS 33.102) and +the identity to register: * the AKAv1-MD5 HTTP-digest response (RFC 3310) the protected REGISTER carries in its Authorization header — MD5 over the binary RES; - * the home-network identity (IMPI/IMPU/registration URI/realm) derived - from IMSI + MCC/MNC; - * text parsers for the SIM facts the daemon shell scrapes from qmicli - (`--uim-get-card-status`: which slot holds a ready USIM and its AID) and - ModemManager (`mmcli`: the primary SIM path, then IMSI + operator id); + * the home-network identity (IMPI/IMPU/registration URI/realm): derived + from IMSI + MCC/MNC (TS 23.003 13.2 to 13.4B, the names of a UE without + an ISIM), and since 1.2.3 the one an ISIM holds (TS 24.229 5.1.1.1A) — + the value an identity file carries (`ParseIsimValue`) and the check of + the three before they stand in a REGISTER (`IsimIdentity`); + * text parsers for the SIM facts in qmicli's output + (`--uim-get-card-status`: which slot holds a ready USIM and its AID, + and the ISIM application of a slot) and in + ModemManager's (`mmcli`: the primary SIM path, then IMSI + operator id); * the ISO 7816 APDU for the AUTHENTICATE(AKA) command and the parser for - its 0xDB success response (RES / CK / IK TLV). + its 0xDB success response (RES / CK / IK TLV), the class byte of a + command on a logical channel, the SELECT and the two READ commands the + ISIM's files are read with, and a card's answer: its status word and, + for an answer without data, the command it asks for next ('61 XX', + '6C XX'). All pure std C++: the actual card I/O (open channel, transmit APDU) is the shell's job — this module only shapes the bytes and reads the answers back. @@ -25,7 +34,9 @@ import :Util; export namespace imsd::aka { - // The home-network identity a USIM registers under. + // The home-network identity: the one derived from the IMSI + // (MakeIdentity), whose shapes the comments below give, or the one an + // ISIM holds (IsimIdentity). struct Identity { std::string imsi; std::string mcc; @@ -75,24 +86,26 @@ export namespace imsd::aka { return imsd::util::Md5::HexDigest(std::format("{}:{}:{}:{}:{}:{}", ha1, nonce, nc, cnonce, qop, ha2)); } - // Which USIM the modem should authenticate against. + // The ready USIM of a card status: its slot and its AID. struct SimSelection { int slot = 0; std::string aid; // uppercase, colons stripped }; - // Parse qmicli `--uim-get-card-status`: the first ready USIM application, - // its slot number, and its Application ID (the hex line under - // "Application ID:"). nullopt if no ready USIM is present. Mirrors the - // Python detect_sim() scan exactly. - std::optional ParseCardStatus(std::string_view text) { - int curSlot = 0; - bool inUsim = false; - bool ready = false; - std::optional out; - std::size_t pos = 0; - auto isAidLine = [](std::string_view s) { - // trimmed line is HH(:HH)+ — two-or-more colon-separated hex pairs + // The pieces of qmicli's card status both of its readers take. + namespace detail { + // A line without the blanks before it and the blanks or the CR + // after it. + inline std::string_view Trimmed(std::string_view t) { + while (!t.empty() && (t.front() == ' ' || t.front() == '\t')) + t.remove_prefix(1); + while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r')) + t.remove_suffix(1); + return t; + } + // A trimmed line that is an Application ID: HH(:HH)+, two or more + // colon-separated hex pairs. + inline bool AidLine(std::string_view s) { std::size_t i = 0; int pairs = 0; auto hex = [](char c) { @@ -108,36 +121,49 @@ export namespace imsd::aka { i++; } return pairs >= 2; - }; + } + // Such a line's AID: uppercase, colons stripped. + inline std::string AidOf(std::string_view t) { + std::string aid; + for (char c : t) + if (c != ':') aid.push_back(static_cast(std::toupper(static_cast(c)))); + return aid; + } + // The N of a "Slot [N]:" line: 0 when what stands between the + // brackets is no number, `fallback` for a line without the pair. + inline int SlotOf(std::string_view t, int fallback) { + std::size_t lb = t.find('['); + std::size_t rb = t.find(']', lb); + if (lb == std::string_view::npos || rb == std::string_view::npos) return fallback; + int v = 0; + std::from_chars(t.data() + lb + 1, t.data() + rb, v); + return v; + } + } + + // Parse qmicli `--uim-get-card-status`: the first ready USIM application, + // its slot number, and its Application ID (the hex line under + // "Application ID:"). nullopt if no ready USIM is present. Mirrors the + // Python detect_sim() scan exactly. + std::optional ParseCardStatus(std::string_view text) { + int curSlot = 0; + bool inUsim = false; + bool ready = false; + std::optional out; + std::size_t pos = 0; while (pos <= text.size()) { std::size_t nl = text.find('\n', pos); - std::string_view line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos); - std::string_view t = line; - while (!t.empty() && (t.front() == ' ' || t.front() == '\t')) - t.remove_prefix(1); - while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r')) - t.remove_suffix(1); + std::string_view t = detail::Trimmed(text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos)); if (t.starts_with("Slot [")) { - std::size_t lb = t.find('['); - std::size_t rb = t.find(']', lb); - if (lb != std::string_view::npos && rb != std::string_view::npos) { - int v = 0; - std::from_chars(t.data() + lb + 1, t.data() + rb, v); - curSlot = v; - } + curSlot = detail::SlotOf(t, curSlot); inUsim = ready = false; } else if (t.contains("Application type") && t.contains("usim")) { inUsim = true; } else if (inUsim && t.contains("Application state") && t.contains("ready")) { ready = true; - } else if (inUsim && isAidLine(t)) { - if (ready && !out) { - std::string aid; - for (char c : t) - if (c != ':') aid.push_back(static_cast(std::toupper(static_cast(c)))); - out = SimSelection{curSlot, aid}; - } + } else if (inUsim && detail::AidLine(t)) { + if (ready && !out) out = SimSelection{curSlot, detail::AidOf(t)}; inUsim = false; } if (nl == std::string_view::npos) break; @@ -146,6 +172,49 @@ export namespace imsd::aka { return out; } + // An ISIM application as the card status lists it. + struct IsimApp { + std::string aid; // uppercase, colons stripped + std::string state; // the modem's word for it: detected, ready, … + }; + + // The first ISIM application of the card in `slot`, from the same card + // status, in whatever state the modem lists it: the Fairphone 6's modem + // lists an ISIM as `detected` beside a `ready` USIM (the two cards + // with an ISIM the probe read, AGENTS.md §13), and a logical channel + // opened on each all the same. nullopt when the card in that slot lists + // none — another + // slot's ISIM belongs to another subscription. + std::optional ParseIsimApp(std::string_view text, int slot) { + int curSlot = 0; + bool inIsim = false; + std::string state; + std::size_t pos = 0; + while (pos <= text.size()) { + std::size_t nl = text.find('\n', pos); + std::string_view t = detail::Trimmed(text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos)); + + if (t.starts_with("Slot [")) { + curSlot = detail::SlotOf(t, curSlot); + inIsim = false; + } else if (t.contains("Application type")) { + inIsim = t.contains("isim"); + state.clear(); + } else if (t.contains("Application state")) { + // the word between the quotes: Application state: 'detected' + std::size_t q1 = t.find('\''); + std::size_t q2 = q1 == std::string_view::npos ? q1 : t.find('\'', q1 + 1); + if (q2 != std::string_view::npos) state = t.substr(q1 + 1, q2 - q1 - 1); + } else if (inIsim && detail::AidLine(t)) { + if (curSlot == slot) return IsimApp{detail::AidOf(t), state}; + inIsim = false; + } + if (nl == std::string_view::npos) break; + pos = nl + 1; + } + return std::nullopt; + } + // "primary sim path: " from `mmcli -m any`. std::optional ParsePrimarySimPath(std::string_view text) { std::size_t at = text.find("primary sim path:"); @@ -214,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 @@ -248,20 +316,191 @@ export namespace imsd::aka { // ---- AUTHENTICATE(AKA) APDU (ISO 7816-4 over the qmicli UIM channel) ---- + // The class byte of a command on a logical channel (ETSI TS 102 221 + // 10.1.1): '0X' with the channel in its two low bits for the standard + // channels 0 to 3, '4X' with the channel less four in its low nibble for + // the extended ones, 4 to 19. Before 1.2.3 the channel number itself was + // the class byte, which is the first form only: a command for channel 4 + // went out as '04', channel 0 with a secure-messaging bit set. + inline int ClassByte(int channel) { + return channel < 4 ? channel & 0x03 : 0x40 | ((channel - 4) & 0x0F); + } + // The command APDU (hex, no separators) for a 3G AKA authentication: - // CLA= INS=88 P1=00 P2=81 Lc [10 RAND(16) 10 AUTN(16)] - // `channel` is the logical-channel number qmicli returned; the CLA low - // nibble carries it (Python: cla = "%02x" % ch). + // CLA= INS=88 P1=00 P2=81 Lc [10 RAND(16) 10 AUTN(16)] + // `channel` is the logical-channel number qmicli returned. std::string BuildAkaApdu(int channel, std::span rand16, std::span autn16) { std::string data = std::format("10{}10{}", imsd::util::ToHex(rand16), imsd::util::ToHex(autn16)); std::size_t lc = data.size() / 2; // CLA INS=88 P1=00 P2=81 Lc - return std::format("{:02x}880081{:02x}{}", channel, lc, data); + return std::format("{:02x}880081{:02x}{}", ClassByte(channel), lc, data); } // GET RESPONSE APDU for when the card answers 61xx (xx bytes available). std::string BuildGetResponseApdu(int channel, int le) { - return std::format("{:02x}c00000{:02x}", channel, le & 0xFF); + return std::format("{:02x}c00000{:02x}", ClassByte(channel), le & 0xFF); + } + + // ---- reading a file of the selected application ------------------------- + + // The ISIM's identity files (TS 31.103 4.2.2 to 4.2.4). + constexpr std::uint16_t EfImpi = 0x6F02; // transparent: the private user identity + constexpr std::uint16_t EfDomain = 0x6F03; // transparent: the home network domain name + constexpr std::uint16_t EfImpu = 0x6F04; // linear fixed: the public user identities + + // SELECT by file identifier under the application the channel was opened + // on (TS 102 221 11.1.1.2: P1 '00', select by file id; P2 '04', return + // the FCP template). + std::string BuildSelectFileApdu(int channel, std::uint16_t fileId) { + return std::format("{:02x}a4000402{:04x}", ClassByte(channel), fileId); + } + + // READ BINARY from the start of the selected transparent file (TS 102 221 + // 11.1.3), and READ RECORD of one record of the selected linear fixed + // file by its number (11.1.5: P2 '04', absolute mode), both with Le '00': + // a '6C XX' in answer names the length (7.3.1.1.5.1). + std::string BuildReadBinaryApdu(int channel) { + return std::format("{:02x}b0000000", ClassByte(channel)); + } + std::string BuildReadRecordApdu(int channel, int record) { + return std::format("{:02x}b2{:02x}0400", ClassByte(channel), record & 0xFF); + } + + // A card's answer to one command: the data and the status word. + struct ApduAnswer { + std::vector data; + std::uint8_t sw1 = 0; + std::uint8_t sw2 = 0; + // The normal endings (TS 102 221 10.2.1.1): '90 00'; '91 XX', from + // a card that has a proactive command waiting for the terminal + // (7.4.2.1); '92 XX', with a data transfer session going on. + bool Ok() const { return (sw1 == 0x90 && sw2 == 0x00) || sw1 == 0x91 || sw1 == 0x92; } + // The status word as the specifications write it: "6a82". + std::string Status() const { return std::format("{:02x}{:02x}", sw1, sw2); } + }; + + // The answer in the bytes qmicli prints for an exchange (the data, then + // SW1 SW2); nullopt for fewer than the two status bytes. + std::optional ParseApduAnswer(std::span bytes) { + if (bytes.size() < 2) return std::nullopt; + ApduAnswer a; + a.data.assign(bytes.begin(), bytes.end() - 2); + a.sw1 = bytes[bytes.size() - 2]; + a.sw2 = bytes[bytes.size() - 1]; + return a; + } + + // The command to send after `answer` to get what `apdu` (hex) asked for, + // when the card asks for one (TS 102 221 7.3.1.1.5, the procedure bytes + // '61xx' and '6Cxx'): GET RESPONSE with the length a '61 XX' names, or, + // for a '6C XX', the command again with that length in place of its + // last byte — of a command that is a header and an Le, five bytes. + // nullopt for any other answer, which is taken for the command's last: + // data with a '61 XX' behind it, which offers more, among them. + std::optional ApduFollowUp(int channel, std::string_view apdu, const ApduAnswer& answer) { + if (!answer.data.empty()) return std::nullopt; + if (answer.sw1 == 0x61) return BuildGetResponseApdu(channel, answer.sw2); + if (answer.sw1 == 0x6C && apdu.size() == 10) return std::format("{}{:02x}", apdu.substr(0, 8), answer.sw2); + return std::nullopt; + } + + // Whether a SELECT's answer says the file is selected: a normal ending, + // or '61 XX', the card offering the file's control parameters, which + // nothing here needs. + inline bool Selected(const ApduAnswer& answer) { + return answer.Ok() || answer.sw1 == 0x61; + } + + // Whether a read's answer holds what was read: a normal ending, or + // data under the warning '62 82', the file or the record having ended + // before the Le bytes asked for (TS 102 221 10.2.1.3). + inline bool HoldsRead(const ApduAnswer& answer) { + return answer.Ok() || (answer.sw1 == 0x62 && answer.sw2 == 0x82 && !answer.data.empty()); + } + + // The value of the data object with tag '80' that an ISIM identity file, + // or a record of EF_IMPU, begins with (TS 31.103 4.2.2 to 4.2.4: the + // NAI, the domain name, a URI), as text. The bytes after the object are + // the file's padding and are not read, and 'FF' bytes at the end of its + // length are taken for padding counted into it and cut: the probe that + // read two reporters' cards cuts them (AGENTS.md §13), so its output + // does not tell such a card from another. nullopt for anything else: + // another first byte (an unused record is all 'FF'), a length in + // another form than one byte, '81' and one or '82' and two, a length + // that runs past the data, no value, or a value with a blank or a byte + // that is not printable ASCII — the three are written into SIP header + // fields. + std::optional ParseIsimValue(std::span data) { + if (data.size() < 2 || data[0] != 0x80) return std::nullopt; + std::size_t i = 1; + std::size_t n = data[i++]; + if (n == 0x81) { + if (i >= data.size()) return std::nullopt; + n = data[i++]; + } else if (n == 0x82) { + if (i + 1 >= data.size()) return std::nullopt; + n = static_cast(data[i]) << 8 | data[i + 1]; + i += 2; + } else if (n >= 0x80) { + return std::nullopt; + } + if (i + n > data.size()) return std::nullopt; + while (n > 0 && data[i + n - 1] == 0xFF) n--; + if (n == 0) return std::nullopt; + std::string value; + for (std::size_t k = 0; k < n; k++) { + std::uint8_t c = data[i + k]; + if (c < 0x21 || c > 0x7E) return std::nullopt; + value.push_back(static_cast(c)); + } + return value; + } + + // The identity an ISIM holds in place of the derived one: `derived` + // (which keeps its IMSI and operator) with the private identity, the + // home domain and the public identity the card gave, and the + // registration URI of that domain. nullopt when one of the three cannot + // stand where imsd writes it: a private identity without an `@` between + // two parts, a domain that is not labels of letters, digits and inner + // hyphens, 63 characters a label and 253 in all at most, a + // public identity that does not begin `sip:` and go on, a private or a + // public identity of more than 255 characters, or one of the two with a + // `"`, a `\`, a `<` or a `>` (the private identity is written into a + // quoted string, the public one between angle brackets), a blank or a + // byte outside printable ASCII. + std::optional IsimIdentity(Identity derived, std::string_view impi, std::string_view domain, std::string_view impu) { + auto plain = [](std::string_view s) { + if (s.empty() || s.size() > 255) return false; + for (char ch : s) { + auto c = static_cast(ch); + if (c < 0x21 || c > 0x7E || c == '"' || c == '\\' || c == '<' || c == '>') return false; + } + return true; + }; + auto host = [](std::string_view s) { + if (s.empty() || s.size() > 253) return false; + char prev = '.'; + std::size_t label = 0; + for (char c : s) { + bool alnum = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + if (!alnum && c != '-' && c != '.') return false; + if ((c == '.' || c == '-') && prev == '.') return false; // a label begins with a letter or a digit + if (c == '.' && prev == '-') return false; // and ends with one + label = c == '.' ? 0 : label + 1; + if (label > 63) return false; + prev = c; + } + return prev != '.' && prev != '-'; + }; + if (!plain(impi) || !plain(impu) || !host(domain)) return std::nullopt; + std::size_t at = impi.find('@'); + if (at == 0 || at == std::string_view::npos || at + 1 == impi.size()) return std::nullopt; + if (!impu.starts_with("sip:") || impu.size() == 4) return std::nullopt; + derived.impi = impi; + derived.domain = domain; + derived.impu = impu; + derived.regUri = std::format("sip:{}", domain); + return derived; } struct AkaResult { @@ -293,4 +532,13 @@ export namespace imsd::aka { if (!take(r.res) || !take(r.ck) || !take(r.ik)) return std::nullopt; return r; } + + // The same of an answer already parted into its data and its status + // word (ParseApduAnswer). + std::optional ParseAkaResponse(const ApduAnswer& answer) { + std::vector resp = answer.data; + resp.push_back(answer.sw1); + resp.push_back(answer.sw2); + return ParseAkaResponse(std::span(resp)); + } } diff --git a/interfaces/Imsd-Engine.cppm b/interfaces/Imsd-Engine.cppm index 8774435..07b8394 100644 --- a/interfaces/Imsd-Engine.cppm +++ b/interfaces/Imsd-Engine.cppm @@ -3,8 +3,8 @@ /* Imsd:Engine — the daemon's decisions as pure reducers: the call state -machine (CallMachine), the registration recovery policy (RegRecovery, -its own section below) and SMS over IP's (the last paragraph here). +machine (CallMachine), the registration recovery policy (RegRecovery, its own section below), when the phone has +to be awake for imsd (WakeAt, with the policy's WakeTime after a local wait) and SMS over IP's (the last paragraph here). A CallMachine owns one call's SIP dialog, outgoing or incoming. It never touches a socket, a clock, or a subprocess: each event (the INVITE's @@ -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 — @@ -76,8 +77,8 @@ export namespace imsd::engine { // ---- registration recovery policy --------------------------------- // // What the daemon does when the registration stops working after - // bring-up, as a pure reducer: the shell supplies the clock and the - // network, this decides the next step and how long to wait for it. Two + // bring-up, as a pure reducer: the shell supplies the clock, the network and (at a local wait) its kind, the + // kernel's refusal or the modem's word; this decides the next step, how long to wait for it and when a sleeping phone is woken for it. Two // kinds of failure reach it. A REFUSAL: the network answered a refresh // with a final other than 200 — a 401, re-authentication, included — or // a fresh registration's protected REGISTER with a final other than 200 @@ -131,9 +132,9 @@ export namespace imsd::engine { // refused or throttled fresh attempt, a terminated binding's probation // or its refusal schedule), which nothing cuts short — a // restart of the process neither: the shell keeps the holds (Holds) - // and hands them to the next one (Restore). The shell supplies the - // clock and the network; this holds the deadlines and names the next - // step (Next). Success resets everything. + // and hands them to the next one (Restore). The shell supplies the clock, what the network answered or did not and, + // at a local wait, its kind (the kernel's refusal, the modem's word); this holds the deadlines and each kind's count, + // and names the next step (Next) and when a sleeping phone is woken for it (WakeTime). Success resets everything. struct RegRecovery { enum class Failure { Refused, Silent, Throttled }; enum class Step { Reconnect, Fresh }; @@ -160,6 +161,21 @@ export namespace imsd::engine { // untouched. Dev phone 2026-09-24: four such refusals in 26 s read // as two silent cycles cost a fresh registration into the throttle. static constexpr double LocalRetry = 5; + // That pace is for a phone that is awake. A sleeping phone is woken + // for a look that follows such a wait after as long again as that + // kind of wait has lasted, within these bounds: seldom in a + // coverage gap of hours (counted from the modem's first word of no + // service since the network last answered: a modem that alternates + // at the edge of coverage shortens nothing), soon at first where + // the kernel refuses a connect (counted from its first refusal + // since the modem was last without service or the network last + // answered, whichever came later: a 4-tuple it still holds clears + // in awake seconds, TIME_WAIT's 60). A step that follows no + // local wait is woken for at the policy's own time, + // whatever went before. + static constexpr double LocalWakeMin = 10; + static constexpr double LocalWakeMax = 900; + enum class Local { NoService, Kernel }; int refusals = 0; int silentCycles = 0; @@ -170,10 +186,14 @@ export namespace imsd::engine { bool fresh = false; // the next registration attempt is a fresh one bool oldGone = false; // the old registration is gone: nothing to reconnect over bool terminated = false; // the network terminated our binding, and the policy has counted it - // the deadlines, on the shell's clock + // the deadlines and a local wait's state, on the shell's clock double backoffUntil = 0; // self-imposed: no step before this; a Dial clears it double holdUntil = 0; // the network's word for any attempt (a Retry-After on a refresh): nothing clears it double freshHoldUntil = 0; // no fresh attempt before this (the schedule after a refused or throttled fresh attempt, a fresh Retry-After, probation, rejected/unregistered) + bool lastLocal = false; // the step that waits follows a local wait, not a counted failure + double gapSince = 0; // the modem's first word of no service since the network last answered (0: none) + double kernelSince = 0; // the kernel's first refusal of a connect since the modem was last without service or the network last answered (0: none) + double localWakeAt = 0; // when a sleeping phone is woken for the look after a local wait bool Fresh() const { return fresh; } bool Reconnectable() const { return !oldGone; } @@ -213,7 +233,32 @@ export namespace imsd::engine { return {Step::Fresh, freshAt}; } - void OnLocalRefusal(double now) { backoffUntil = now + LocalRetry; } + void OnLocalRefusal(double now, Local kind = Local::Kernel) { + backoffUntil = now + LocalRetry; + lastLocal = true; + double since; + if (kind == Local::NoService) { + if (gapSince == 0) gapSince = now; + kernelSince = 0; + since = gapSince; + } else { + if (kernelSince == 0) kernelSince = now; + since = kernelSince; + } + localWakeAt = now + std::clamp(now - since, LocalWakeMin, LocalWakeMax); + } + bool LocalLook() const { return lastLocal; } + // The network has answered (the shell's word: an answered TCP + // connect of the resume or of a reconnect, a response to a + // REGISTER): it is in reach, and both counts start over. + void OnNetworkAnswered() { gapSince = 0; kernelSince = 0; } + // When a sleeping phone is to be awake for the next step: the + // step's own time, and after a local wait the slower look's, never + // before the step's own (a hold the network set). + double WakeTime(double now) const { + double at = Next(now).at; + return lastLocal ? std::max(at, localWakeAt) : at; + } // A refused keepalive refresh, or a failed reconnect + refresh // cycle; `status` is the refusal's. The backoff paces the next step; @@ -223,6 +268,8 @@ export namespace imsd::engine { // registration is due says the old registration is gone (KPN drops // it the moment an initial REGISTER arrives, throttled or not). void OnReconnectFailure(double now, Failure f, long retryAfter = 0, int status = 0) { + lastLocal = false; // a counted step waits now: woken for at its own time + if (f == Failure::Refused) OnNetworkAnswered(); // silence is no answer: the gap's count stands if (retryAfter > 0) holdUntil = std::max(holdUntil, now + static_cast(std::min(retryAfter, RetryAfterMax))); // A cycle over a registration already known gone — the network // terminated the binding while the cycle waited for its final — @@ -246,6 +293,8 @@ export namespace imsd::engine { // it off 30 s → 10 min. A reconnect over the old SA meanwhile waits // at least the reconnect backoff. void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) { + lastLocal = false; + if (f != Failure::Silent) OnNetworkAnswered(); freshAttempts++; fresh = true; if (saReplaced) oldGone = true; @@ -271,6 +320,8 @@ export namespace imsd::engine { // reg-event dialog of the account carries it, a NOTIFY may be // retransmitted), and never shortens a hold already running. void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) { + lastLocal = false; + OnNetworkAnswered(); bool reported = terminated; terminated = true; oldGone = true; @@ -289,7 +340,7 @@ export namespace imsd::engine { // The stored registration is not there to reconnect over (a resume // that failed at bring-up found its SAs unusable, or there are none). - void OldGone() { oldGone = true; fresh = true; } + void OldGone() { oldGone = true; fresh = true; lastLocal = false; } // A user's Dial cuts the backoff short, never the network's word. void OnDial() { backoffUntil = 0; } @@ -297,6 +348,24 @@ export namespace imsd::engine { void OnSuccess() { *this = RegRecovery{}; } }; + // When the phone has to be awake for imsd, on the shell's clock (0: + // never): what the shell arms its wake alarm from. A time that is not + // later than now says the phone is to stay awake. The shell's loop arms the alarm for the time, and WakeHold + // ahead where the time is nearer than that: under an alarm that near the kernel refuses a suspend that reaches + // its check in time (the shell has the turns that arm it and what that takes). While imsd is busy with + // what counts awake seconds in its waits (a call, a text in flight) that + // is now. With a registration on a live flow it is the refresh's due + // time, or the reg-event subscription's renewal where that comes first + // (renewalDue 0: none is due). Without one it is the recovery policy's + // word (RegRecovery::WakeTime) where the shell has a step to run, a dead + // flow under a registration: a step that is due is now, whatever the + // policy's clock value for "now". And none where nothing waits to be done. + constexpr double WakeAt(double now, bool busy, bool liveFlow, double refreshDue, double renewalDue, bool recovering, double recoveryAt) { + if (busy) return now; + if (liveFlow) return renewalDue > 0 ? std::min(refreshDue, renewalDue) : refreshDue; + return recovering ? std::max(recoveryAt, now) : 0; + } + // Parsed SDP answer needed to bring up the media leg. `codec` is one of // imsd-media's: "AMR-WB", "AMR", "PCMA", "PCMU" (empty = none we play). // `dtmfPt` is the telephone-event payload type at the codec's clock @@ -349,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; @@ -420,11 +493,50 @@ export namespace imsd::engine { offer.codecs = codecs_; std::string sdp = imsd::sdp::BuildOffer(offer); std::vector a; - a.push_back(Send(imsd::msg::BuildInvite(ctx_, d_, sdp, precond_))); + inviteOut_ = imsd::msg::BuildInvite(ctx_, d_, sdp, precond_); + a.push_back(Send(inviteOut_)); a.push_back(Deadline(InviteTimeout)); return a; } + // 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 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 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 + // INVITE: one that AgainWithMinSe sends has a resend of its own. + std::vector OnFlowReopened() { + std::vector a; + if (!ResendDue()) return a; + resent_ = true; + a.push_back(LogAct(std::format("call {}: the INVITE again over the reopened flow", uni_))); + a.push_back(Send(inviteOut_)); + a.push_back(Deadline(InviteTimeout)); + return a; + } + + // 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. + std::vector OnFlowLost() { + std::vector a; + if (!Unanswered()) return a; + Append(a, Finish("error", "the client flow died before any response to the INVITE")); + return a; + } + // UAS: answer the inbound INVITE with 100 Trying + 180 Ringing (made // reliable only when the caller Requires 100rel) and arm the ring // timeout. An offer we cannot serve — no audio line, or none of the @@ -491,14 +603,21 @@ 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; + answered_ = true; int code = *st; if (code > 100 && code < 200) { if (state_ == CallState::Dialing) { @@ -510,7 +629,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_++; } @@ -543,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; @@ -761,6 +897,13 @@ export namespace imsd::engine { bool sosTried_ = false; bool plainTried_ = false; bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline + // 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 @@ -776,20 +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 is re-attempted as a plain INVITE of the dialled - // digits: the pre-emergency-support behavior, so classification - // can only improve on the status quo, never block a call the old - // code would have placed. + // - 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-Ipsec.cppm b/interfaces/Imsd-Ipsec.cppm index 84f36a5..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. @@ -66,8 +67,8 @@ export namespace imsd::ipsec { return std::nullopt; } - // Canonical ealg name: absent is the null cipher (RFC 3329 §2.2), "3des" - // (imsd's EALG alias) is des-ede3-cbc. Used on both sides of the + // Canonical ealg name: absent is the null cipher (RFC 3329 Appendix A), + // "3des" (imsd's EALG alias) is des-ede3-cbc. Used on both sides of the // offer/answer comparison. std::string NormalizeEalg(std::string_view ealg) { if (ealg.empty()) return "null"; @@ -82,6 +83,40 @@ export namespace imsd::ipsec { return ealg == "null" || ealg == "aes-cbc" || ealg == "des-ede3-cbc"; } + // The ESP ciphers offered in Security-Client when EALG names none, in + // the order offered. The UE announces the IPsec algorithms it supports + // (TS 24.229 5.1.1.2.2 d; TS 33.203 7.2), and of the ciphers it must + // support (7.1 by TS 33.210 5.3.3: RFC 8221's NULL, AES-CBC and + // AES-GCM) these are the two EncArgs can key. Whether the signalling is + // encrypted is the P-CSCF's choice (TS 33.203 5.1.3); aes-cbc comes + // first for a P-CSCF that goes by the UE's order. + std::vector DefaultEalgOffer() { return {"aes-cbc", "null"}; } + + // An EALG setting ("aes-cbc, null") read as the ciphers to offer, in the + // order written: case-insensitive, spaces and tabs ignored, "3des" for + // des-ede3-cbc, a repeat dropped. An element that names no cipher + // KnownEalg() has goes to `unknown`, in lower case without its spaces; + // an empty element is passed over. A setting that names no cipher gives + // DefaultEalgOffer(). + struct EalgSetting { + std::vector ciphers; // the offer + std::vector unknown; // the names passed over + }; + EalgSetting ParseEalgOffer(std::string_view spec) { + EalgSetting out; + for (auto part : std::views::split(spec, ',')) { + std::string n; + for (char c : std::string_view(part)) + if (c != ' ' && c != '\t') n += static_cast(std::tolower(static_cast(c))); + if (n.empty()) continue; // not NormalizeEalg's absent-means-null: an empty element names nothing + n = NormalizeEalg(n); + std::vector& to = KnownEalg(n) ? out.ciphers : out.unknown; + if (std::ranges::find(to, n) == to.end()) to.push_back(n); + } + if (out.ciphers.empty()) out.ciphers = DefaultEalgOffer(); + return out; + } + namespace detail { // ESP cipher argv triple for `ip xfrm state add ... `, matching // imscall.setup_sa: aes-cbc keyed with CK; 3DES uses CK||CK[:8] to @@ -146,16 +181,47 @@ 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 // with a preference, plus the SPIs and ports it assigned to this - // registration. The UE takes the highest-preference mechanism that is - // in that list AND that it offered (RFC 3329 §2.3.1, TS 24.229 - // §5.1.1.5.1, TS 33.203 §7.2); imsd offers exactly one combination - // (hmac-sha-1-96 + EALG). The SPIs/ports are per registration, not per - // mechanism: they come from whichever entry carries them (O2 UK's - // Mavenir core lists six entries and puts them on the one it applied). + // registration. RFC 3329 §2.3.1 and TS 24.229 §5.1.1.5.1 have the UE + // take the most preferred mechanism it supports; TS 33.203 §7.2 has it + // take the first on the P-CSCF's list, the same entry where the list + // runs from its highest q down or carries none. imsd looks among the + // entries it offered: hmac-sha-1-96 with each cipher of its list (EALG, + // DefaultEalgOffer). The SPIs/ports are per registration, not per + // mechanism: they come from whichever entry carries them. O2 UK's + // Mavenir core lists six entries, in rising q, and puts them on the one + // it applied: the sha1 entry without a cipher for a null offer + // (2026-09-17), the sha1 entry with aes-cbc, its highest q, for an + // aes-cbc offer (2026-09-20). So an entry that alone carries them, when + // it is one imsd offered, is taken before the highest q is looked at: + // with more than one cipher offered the two can name different + // algorithms, with one a different mod or prot. // imsd ≤ 0.3.5 took the first `ealg=` anywhere in the header and // installed 3DES against a P-CSCF expecting the null cipher: every // protected packet was undecryptable to it (alyx, 2026-09-17; journal/ims @@ -255,15 +321,21 @@ export namespace imsd::ipsec { // Parse a Security-Server value and select against our offer. Names, // parameter names and alg/ealg/prot/mod values are tokens - // (case-insensitive) and come back lower-case. `selected` = the - // highest-q ipsec-3gpp mechanism whose alg (absent = the offered one) - // and ealg (absent = null) equal what we offered; when none matches, - // the highest-q ipsec-3gpp entry carrying spi-s, else port-s, else the - // first ipsec-3gpp entry, with offerMatched = false so the caller can - // say so. `carrier` = selected when it carries spi-s, else the highest-q - // ipsec-3gpp entry that does. nullopt when the value holds no ipsec-3gpp - // mechanism at all. - std::optional ParseSecurityServer(std::string_view value, std::string_view offeredAlg, std::string_view offeredEalg) { + // (case-insensitive) and come back lower-case. An entry is one we + // offered when it is ipsec-3gpp, its alg (absent = the offered one) is + // the offered one and its ealg (absent = null) is among the offered + // ciphers. `selected` = the ipsec-3gpp entry carrying spi-s when one + // entry alone carries it and it is one we offered (the entry the P-CSCF + // marked), else the highest-q entry we offered (ties: the earlier one); + // when none matches, the highest-q ipsec-3gpp entry carrying spi-s, else + // port-s, else the first ipsec-3gpp entry, with offerMatched = false so + // the caller can say so. With one cipher offered the marked entry and + // the highest-q offered one name the same algorithms; their mod and prot + // can differ, and the marked entry's are the ones taken. `carrier` = + // selected when it carries spi-s, else the highest-q ipsec-3gpp entry + // that does. nullopt when the value holds no ipsec-3gpp mechanism at + // all. + std::optional ParseSecurityServer(std::string_view value, std::string_view offeredAlg, const std::vector& offeredEalgs) { SecurityServer ss; for (std::string_view part : detail::SplitUnquoted(value, ',')) { part = detail::TrimWs(part); @@ -294,13 +366,17 @@ export namespace imsd::ipsec { auto ipsec = [](const SecurityMechanism& m) { return m.name == "ipsec-3gpp"; }; auto carries = [&](const SecurityMechanism& m) { return ipsec(m) && m.spiPs.has_value(); }; std::string wantAlg = detail::Lower(offeredAlg); - std::string wantEalg = NormalizeEalg(detail::Lower(offeredEalg)); + std::vector wantEalgs; + for (const std::string& e : offeredEalgs) wantEalgs.push_back(NormalizeEalg(detail::Lower(e))); auto offered = [&](const SecurityMechanism& m) { - return ipsec(m) && (m.alg.empty() || m.alg == wantAlg) && NormalizeEalg(m.ealg) == wantEalg; + return ipsec(m) && (m.alg.empty() || m.alg == wantAlg) && std::ranges::find(wantEalgs, NormalizeEalg(m.ealg)) != wantEalgs.end(); }; auto firstIpsec = std::ranges::find_if(ss.mechanisms, ipsec); if (firstIpsec == ss.mechanisms.end()) return std::nullopt; - if (auto i = detail::Best(ss.mechanisms, offered)) { ss.selected = *i; ss.offerMatched = true; } + std::optional marked; + if (std::ranges::count_if(ss.mechanisms, carries) == 1) marked = static_cast(std::ranges::find_if(ss.mechanisms, carries) - ss.mechanisms.begin()); + if (marked && offered(ss.mechanisms[*marked])) { ss.selected = *marked; ss.offerMatched = true; } + else if (auto i = detail::Best(ss.mechanisms, offered)) { ss.selected = *i; ss.offerMatched = true; } else if (auto i = detail::Best(ss.mechanisms, carries)) ss.selected = *i; else if (auto i = detail::Best(ss.mechanisms, [&](const SecurityMechanism& m) { return ipsec(m) && m.portPs.has_value(); })) ss.selected = *i; else ss.selected = static_cast(firstIpsec - ss.mechanisms.begin()); @@ -312,7 +388,7 @@ export namespace imsd::ipsec { // What a warm SA in the kernel tells us — enough for a refresh re-REGISTER // to re-bind without re-authenticating. struct ExistingSa { - std::string securityServer; // one-mechanism Security-Server value: the resume's Security-Verify when the state file holds no list for this pair + std::string securityServer; // one-mechanism Security-Server value, its alg and ealg the pair's own: the resume's Security-Verify when the state file holds no list for this pair int portPs = 0; int portPc = 0; std::uint32_t spiUc = 0; // our inbound client SPI (a reregistration offers a different one) @@ -384,6 +460,22 @@ export namespace imsd::ipsec { if (b.find("dir in") != std::string_view::npos) return ParseDec(TokenAfter(b, "dport ")) == port; return false; } + + // The sec-agree names of a state's algorithms, from the names `ip + // xfrm state` prints on its `auth-trunc` and `enc` lines (the + // kernel's for what KernelAuth and EncArgs install; the null cipher, + // added as cipher_null, prints as ecb(cipher_null)). A state that + // prints no such line, or another name, reads as hmac-sha-1-96 and + // aes-cbc. + inline std::string_view AlgOfState(std::string_view b) { + return TokenAfter(b, "auth-trunc ") == "hmac(md5)" ? "hmac-md5-96" : "hmac-sha-1-96"; + } + inline std::string_view EalgOfState(std::string_view b) { + std::string_view enc = TokenAfter(b, "enc "); + if (enc == "ecb(cipher_null)") return "null"; + if (enc == "cbc(des3_ede)") return "des-ede3-cbc"; + return "aes-cbc"; + } } // Reconstruct SA facts from `ip xfrm state` + `ip xfrm policy` text. @@ -391,6 +483,8 @@ export namespace imsd::ipsec { // state: (src==LOCAL,dst==P): reqid1->spiPs reqid2->spiPc // (src==P,dst==LOCAL): reqid1->spiUc reqid2->spiUs // policy: dir out, reqid1->portPs=dport, reqid2->portPc=dport + // The state that gives spiPs also gives the algorithms the rebuilt + // Security-Server entry names (detail::AlgOfState, EalgOfState). // Addresses are compared in RFC 5952 form on both sides (the kernel prints // that form; PCSCF=/LOCAL= arrive in any spelling), so the spelling in // /etc/imsd.env can no longer hide a registration's SAs. @@ -403,13 +497,15 @@ export namespace imsd::ipsec { bool havePc = false; bool havePortPs = false; bool havePortPc = false; + std::string_view alg; + std::string_view ealg; for (std::string_view b : detail::SrcBlocks(stateText)) { const std::string src = imsd::util::CanonicalAddr(detail::TokenAfter(b, "src ")); const std::string dst = imsd::util::CanonicalAddr(detail::TokenAfter(b, "dst ")); auto spi = detail::ParseHex32(detail::TokenAfter(b, "spi ")); auto reqid = detail::ParseDec(detail::TokenAfter(b, "reqid ")); if (!spi || !reqid) continue; - if (src == l && dst == p && *reqid == 1) { sa.spiPs = *spi; havePs = true; } + if (src == l && dst == p && *reqid == 1) { sa.spiPs = *spi; havePs = true; alg = detail::AlgOfState(b); ealg = detail::EalgOfState(b); } if (src == l && dst == p && *reqid == 2) { sa.spiPc = *spi; havePc = true; } if (src == p && dst == l && *reqid == 1) sa.spiUc = *spi; if (src == p && dst == l && *reqid == 2) sa.spiUs = *spi; @@ -430,7 +526,7 @@ export namespace imsd::ipsec { else if (*reqid == 2) { sa.portPc = *dport; havePortPc = true; } } if (!(havePs && havePc && havePortPs && havePortPc)) return std::nullopt; - sa.securityServer = std::format("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; " "spi-c={}; spi-s={}; port-c={}; port-s={}", sa.spiPc, sa.spiPs, sa.portPc, sa.portPs); + sa.securityServer = std::format("ipsec-3gpp; q=0.1; alg={}; ealg={}; " "spi-c={}; spi-s={}; port-c={}; port-s={}", alg, ealg, sa.spiPc, sa.spiPs, sa.portPc, sa.portPs); return sa; } @@ -438,7 +534,10 @@ export namespace imsd::ipsec { // file's list when the entry carrying its SPIs names the SA pair the // kernel holds (a file an attempt the process did not live to record // left behind names another pair), else the one-mechanism entry rebuilt - // from the SA — for an empty or unparseable value too. + // from the SA — for an empty or unparseable value too. The entry + // carrying the SPIs is ParseSecurityServer's carrier under the offer + // handed in: the offer decides only where several entries carry SPIs + // of their own. struct ResumeSecurityVerify { enum class Source { Stored, NoneStored, OtherSa }; Source source = Source::NoneStored; @@ -446,12 +545,12 @@ export namespace imsd::ipsec { std::size_t mechanisms = 0; // of the stored list, when it is used std::optional storedSpiPs; // the stored list's spi-s (OtherSa); nullopt = none parsed }; - ResumeSecurityVerify ChooseResumeSecurityVerify(std::string_view stored, const ExistingSa& sa, std::string_view offeredEalg) { + ResumeSecurityVerify ChooseResumeSecurityVerify(std::string_view stored, const ExistingSa& sa, const std::vector& offeredEalgs) { ResumeSecurityVerify r; r.value = sa.securityServer; if (stored.empty()) return r; r.source = ResumeSecurityVerify::Source::OtherSa; - if (auto parsed = ParseSecurityServer(stored, "hmac-sha-1-96", offeredEalg)) { + if (auto parsed = ParseSecurityServer(stored, "hmac-sha-1-96", offeredEalgs)) { const SecurityMechanism& c = parsed->Carrier(); r.storedSpiPs = c.spiPs; if (c.spiPc == sa.spiPc && c.spiPs == sa.spiPs && c.portPc == sa.portPc && c.portPs == sa.portPs) { diff --git a/interfaces/Imsd-Messages.cppm b/interfaces/Imsd-Messages.cppm index 5bf0c23..92ef390 100644 --- a/interfaces/Imsd-Messages.cppm +++ b/interfaces/Imsd-Messages.cppm @@ -5,11 +5,14 @@ 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 +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. +with strings cross-generated from the Python reference stack, header for header +but for the divergences that suite's header names. Covers: the unprotected + protected REGISTER and the refresh re-REGISTER (sec-agree, Security-Client/Verify, AKAv1-MD5 Authorization); the INVITE with @@ -17,7 +20,8 @@ an AMR-WB SDP offer and IMS MMTEL feature tags; the in-dialog PRACK/BYE and 2xx/non-2xx ACK; CANCEL (reusing the INVITE branch); the 200 OK that echoes an inbound request's dialog headers; the finals of the inbound MESSAGE path, each Via row echoed and the To tagged unless it holds `tag=` -(RFC 3261 8.2.6.2); the UAS responses to an +(RFC 3261 8.2.6.2); the 400 to a request whose datagram ended before its +body did (18.3); the UAS responses to an inbound INVITE (100/180/200 and rejection finals); and the SIP MESSAGE that carries a short message's RP-DATA to the service centre, or its RP-ACK/RP-ERROR back to the IP-SM-GW @@ -28,6 +32,7 @@ export module Imsd:Messages; import std; import :Util; import :Aka; +import :Ipsec; import :Sip; export namespace imsd::msg { @@ -46,7 +51,9 @@ export namespace imsd::msg { // of every request we send over it. TCP unless the engine fell back // to, or was told to use, UDP. std::string transport = "TCP"; - std::string ealgOffer = "aes-cbc"; + // The ESP ciphers Security-Client offers, in order (canonical names: + // imsd::ipsec::ParseEalgOffer). + std::vector ealgOffer = imsd::ipsec::DefaultEalgOffer(); // RFC 7254 IMEI URN for +sip.instance (e.g. urn:gsma:imei:35999999- // 000000-1); empty omits the parameter. std::string instanceId; @@ -72,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 @@ -100,12 +113,18 @@ export namespace imsd::msg { return std::format("Via: SIP/2.0/{} {};branch=z9hG4bK{};rport", transport, imsd::util::HostPort(c.local, port), branch); } - // Security-Client value: the SPIs and protected ports offered for the SA - // pairs this REGISTER may set up — the in-use ones on an initial - // registration, new SPIs and a new client port on a reregistration - // (TS 24.229 5.1.1.4.2 d; TS 33.203 7.4.0: the server port stays). + // Security-Client value: one mechanism per offered cipher, each with the + // SPIs and protected ports offered for the SA pairs this REGISTER may + // set up — the in-use ones on an initial registration, new SPIs and a + // new client port on a reregistration (TS 24.229 5.1.1.4.2 d; TS 33.203 + // 7.4.0: the server port stays). One pair of SPIs and one of ports for + // the whole list (TS 33.203 7.2 NOTE 1, NOTE 2), the mechanisms + // comma-separated in one header field (Annex H). inline std::string SecurityClient(const Context& c, std::uint32_t spiUc, std::uint32_t spiUs, int portUc, int portUs) { - return std::format("Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg={}; " "spi-c={}; spi-s={}; port-c={}; port-s={}", c.ealgOffer, spiUc, spiUs, portUc, portUs); + std::string v; + for (const std::string& ealg : c.ealgOffer) + v += std::format("{}ipsec-3gpp; alg=hmac-sha-1-96; ealg={}; " "spi-c={}; spi-s={}; port-c={}; port-s={}", v.empty() ? "" : ", ", ealg, spiUc, spiUs, portUc, portUs); + return std::format("Security-Client: {}", v); } inline std::string SecurityClient(const Context& c, std::uint32_t spiUc, std::uint32_t spiUs) { return SecurityClient(c, spiUc, spiUs, c.portUc, c.portUs); @@ -213,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 ------------------------------------------------------- @@ -322,7 +353,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 @@ -337,11 +368,18 @@ 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 // identity (P-Associated-URI sip: entry), else the tel: one, and the - // IMSI-derived temporary IMPU only before either is learned. 3GPP allows + // identity's own (an ISIM's first, or the IMSI-derived temporary IMPU) + // only before either is learned. 3GPP allows // the temporary IMPU in REGISTER alone; a P-CSCF that does not overwrite // From shows it to the callee (Telia, 2026-09-01: the reporter's IMSI on // the far phone) and a strict one may reject the request. @@ -370,7 +408,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"; @@ -382,7 +421,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), @@ -394,8 +433,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(""); @@ -404,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)); @@ -419,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())); @@ -442,7 +485,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)); @@ -459,7 +502,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)); @@ -475,7 +518,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)); @@ -489,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")) @@ -511,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())); @@ -525,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)); @@ -538,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)); } @@ -545,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 0f5a07a..18ca65f 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 @@ -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) { @@ -228,6 +248,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/interfaces/Imsd-Util.cppm b/interfaces/Imsd-Util.cppm index 4cc50a9..3578ba9 100644 --- a/interfaces/Imsd-Util.cppm +++ b/interfaces/Imsd-Util.cppm @@ -3,7 +3,8 @@ /* Imsd:Util — small self-contained primitives the rest of the engine builds on: -random SIP tokens, IPv6 detection + host/port formatting, the RFC 5952 +random SIP tokens, the whole seconds a setting names, IPv6 detection + +host/port formatting, the RFC 5952 canonical IPv6 text and the address-list parser, hex/base64 decoding, and MD5 (RFC 1321). None of the standard library ships these last three, and the IMS AKAv1-MD5 digest (Imsd:Aka) needs MD5 over raw bytes plus base64 to @@ -148,6 +149,18 @@ export namespace imsd::util { return out; } + // A setting that counts whole seconds (CRLF_KEEPALIVE=): decimal digits + // and nothing else. nullopt for anything else — a sign, a unit, a + // fraction, a blank, an empty value, a number too large for a long — so + // the caller can say the setting was not understood rather than take it + // for a number it is not. + inline std::optional WholeSeconds(std::string_view s) { + if (s.empty() || !std::all_of(s.begin(), s.end(), [](char c) { return c >= '0' && c <= '9'; })) return std::nullopt; + long v = 0; + if (std::from_chars(s.data(), s.data() + s.size(), v).ec != std::errc{}) return std::nullopt; + return v; + } + // A random token of `n` chars over [a-z0-9] — SIP branch/tag/Call-ID // material (the Python rand()). The generator is a parameter so tests can // pin output; the default constructor seeds from random_device. diff --git a/packaging/ims-pdn-up.sh b/packaging/ims-pdn-up.sh index dafc4d9..0342941 100644 --- a/packaging/ims-pdn-up.sh +++ b/packaging/ims-pdn-up.sh @@ -501,6 +501,18 @@ log "wrote /run/imsd.env: DEV=$IFACE LOCAL=$ADDR PCSCF_DISCOVERED=$DISCOVERED PC # the P-CSCF's TCP SYNs to the protected server port never reached the # listener, so terminating delivery failed and MT calls fell back to CS. # 45061/45062 = imsd's protected client/server ports (kPortUc/kPortUs). +# +# The ESP packet itself passes the chain first, before the kernel +# decapsulates it. With no rule for it, the chain lets it in only as an +# answer to a packet of ours ("ct state established": the connection +# tracker's entry for a protocol it has no tracker of its own for, 600 s by +# default), and drops a request the network starts later than that after +# our last packet. ESP that no SA of ours matches is dropped by the kernel +# behind the rule, and what an SA decapsulates passes the chain again. +# +# Each of the two has its own check: a ruleset that carries the port rules +# under their comment (fp6-img's 01_imsd.nft) can lack the ESP rule. What +# is inserted here is gone when the ruleset is next loaded from its files. # Best-effort: never fail the unit over a missing/foreign firewall. if nft list table inet filter >/dev/null 2>&1; then if ! nft list chain inet filter input | grep -q imsd-protected-ports; then @@ -509,5 +521,10 @@ if nft list table inet filter >/dev/null 2>&1; then log "nftables: opened protected ports 45061-45062 on qmapmux*" || log "nftables: rule insert failed (continuing)" fi + if ! nft list chain inet filter input | grep -q imsd-esp; then + nft insert rule inet filter input iifname "qmapmux*" meta l4proto esp accept comment '"imsd-esp"' && + log "nftables: accepting ESP on qmapmux*" || + log "nftables: rule insert failed (continuing)" + fi fi exit 0 diff --git a/tests/Aka/main.cpp b/tests/Aka/main.cpp index 49c8d1f..f75c92c 100644 --- a/tests/Aka/main.cpp +++ b/tests/Aka/main.cpp @@ -4,6 +4,10 @@ // Imsd:Aka unit tests — the AKAv1-MD5 digest against a vector cross-computed // with the Python reference, identity assembly, the qmicli/mmcli text // parsers (fed real device output), and the AUTHENTICATE APDU build/parse. +// Then the ISIM (since 1.2.3): the application of the slot in use out of a +// card status, the commands its files are read with, a card's answer and +// the command it asks for next, the value an identity file holds, and the +// check of the three values before they are an identity. import std; import Imsd; @@ -36,6 +40,69 @@ namespace { "\t\t\tA0:00:00:00:87:10:02:FF:31:F0:04:89:0E:00:00:01\n" "\t\tPIN1 state: 'disabled'\n"; + // A card with a USIM and an ISIM in one slot. The two applications, + // their states and their AIDs are those the fp6 journal's probe read off + // a reporter's card on 2026-11-23 (the modem lists the ISIM `detected` + // beside the `ready` USIM); the lines are the ones qmicli prints for an + // application, as in the fixture above: the probe prints its own listing + // of a card, not qmicli's. + constexpr std::string_view CardStatusIsim = + "[qrtr://0] Successfully got card status\n" + "Provisioning applications:\n" + "\tPrimary GW: slot '1', application '1'\n" + "Slot [1]:\n" + "\tCard state: 'present'\n" + "\tUPIN state: 'not-initialized'\n" + "\tApplication [1]:\n" + "\t\tApplication type: 'usim (2)'\n" + "\t\tApplication state: 'ready'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00\n" + "\t\tPIN1 state: 'disabled'\n" + "\tApplication [2]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:04:FF:FF:FF:FF:89:03:02:00:00\n" + "\t\tPIN1 state: 'disabled'\n" + "Slot [2]:\n" + "\tCard state: 'absent'\n"; + + // The same two applications with the ISIM listed first, and a second + // card in slot 2 that has an ISIM of its own (its AID the twelve bytes + // of the other card with an ISIM the probe read, 2026-11-21) beside a USIM + // that is not ready. + constexpr std::string_view CardStatusIsimFirst = + "Slot [1]:\n" + "\tCard state: 'present'\n" + "\tApplication [1]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:04:FF:FF:FF:FF:89:03:02:00:00\n" + "\tApplication [2]:\n" + "\t\tApplication type: 'usim (2)'\n" + "\t\tApplication state: 'ready'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:02:FF:FF:FF:FF:89:03:02:00:00\n" + "Slot [2]:\n" + "\tCard state: 'present'\n" + "\tApplication [1]:\n" + "\t\tApplication type: 'usim (2)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:02:FF:49:FF:05:89\n" + "\tApplication [2]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'ready'\n" + "\t\tApplication ID:\n" + "\t\t\ta0:00:00:00:87:10:04:ff:49:ff:05:89\n" + "\tApplication [3]:\n" + "\t\tApplication type: 'isim (5)'\n" + "\t\tApplication state: 'detected'\n" + "\t\tApplication ID:\n" + "\t\t\tA0:00:00:00:87:10:04:FF:49:FF:05:99\n"; + constexpr std::string_view MmcliSim = " Properties | active: yes\n" " | imsi: 001010123456789\n" @@ -72,6 +139,10 @@ int main() { Check(sel && sel->aid == "A0000000871002FF31F004890E000001", "AID uppercased, colons stripped"); } Check(!ParseCardStatus("Slot [1]:\n\tCard state: 'absent'\n").has_value(), "no ready USIM -> nullopt"); + { + auto odd = ParseCardStatus("Slot [2]:\n\tCard state: 'absent'\nSlot [x]:\n\tApplication [1]:\n\t\tApplication type: 'usim (2)'\n\t\tApplication state: 'ready'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:02:FF\n"); + Check(odd && odd->slot == 0, "a slot line whose number does not parse is slot 0, not the slot before it"); + } // ---- mmcli parsers Check(ParsePrimarySimPath(" SIM | primary sim path: /org/freedesktop/ModemManager1/SIM/0\n") == "/org/freedesktop/ModemManager1/SIM/0", "primary sim path"); @@ -98,6 +169,20 @@ int main() { Check(apdu == "0188008122" "10" "11111111111111111111111111111111" "10" "22222222222222222222222222222222", "APDU byte-exact"); Check(BuildGetResponseApdu(0x01, 0x2E) == "01c000002e", "GET RESPONSE APDU"); } + { + // the class byte (TS 102 221 10.1.1, tables 10.3 and 10.4a): the + // channel itself for 0 to 3, '4X' with the channel less four for 4 + // to 19 + Check(ClassByte(0) == 0x00 && ClassByte(1) == 0x01 && ClassByte(3) == 0x03, "class byte of a standard channel is the channel"); + Check(ClassByte(4) == 0x40, "class byte of channel 4 is 40"); + Check(ClassByte(5) == 0x41, "class byte of channel 5 is 41"); + Check(ClassByte(19) == 0x4F, "class byte of channel 19 is 4f"); + std::vector rnd(16, 0x11), autn(16, 0x22); + Check(BuildAkaApdu(3, rnd, autn).starts_with("0388008122"), "AUTHENTICATE on channel 3 starts 03"); + Check(BuildAkaApdu(4, rnd, autn).starts_with("4088008122"), "AUTHENTICATE on channel 4 starts 40, not 04"); + Check(BuildAkaApdu(4, rnd, autn).substr(2) == BuildAkaApdu(1, rnd, autn).substr(2), "the channel changes the class byte and nothing else"); + Check(BuildGetResponseApdu(7, 0x35) == "43c0000035", "GET RESPONSE on channel 7 starts 43"); + } { // DB | 08 RES | 10 CK | 10 IK | SW1 SW2(9000) std::vector body = {0xDB, 0x08}; @@ -112,6 +197,13 @@ int main() { Check(r && r->res.size() == 8 && r->res[0] == 0xA0, "RES extracted"); Check(r && r->ck.size() == 16 && r->ck[0] == 0xC0, "CK extracted"); Check(r && r->ik.size() == 16 && r->ik[0] == 0xD0, "IK extracted"); + // the same answer parted into its data and its status word + auto parted = ParseApduAnswer(body); + auto r2 = parted ? ParseAkaResponse(*parted) : std::nullopt; + Check(r2 && r2->res == r->res && r2->ck == r->ck && r2->ik == r->ik, "an ApduAnswer's AKA result is the raw answer's"); + std::vector refused = {0x69, 0x82}; + auto no = ParseApduAnswer(refused); + Check(no && !ParseAkaResponse(*no).has_value(), "a status word alone is no AKA result"); } { // sync-failure tag (0xDC) or truncated body -> nullopt @@ -123,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" @@ -144,6 +235,212 @@ int main() { Check(!ParsePani(Zeros).has_value(), "PANI all-zero cell rejected"); } + // ---- the ISIM application of the slot in use + { + auto sel = ParseCardStatus(CardStatusIsim); + Check(sel && sel->slot == 1 && sel->aid == "A0000000871002FFFFFFFF8903020000", "the ready USIM beside an ISIM is still the USIM read"); + auto isim = ParseIsimApp(CardStatusIsim, 1); + Check(isim.has_value(), "the ISIM of slot 1 is found"); + Check(isim && isim->aid == "A0000000871004FFFFFFFF8903020000", "its AID, uppercase, colons stripped"); + Check(isim && isim->state == "detected", "its state is the modem's word, detected"); + Check(!ParseIsimApp(CardStatusIsim, 2).has_value(), "an absent card in the slot asked for: no ISIM"); + Check(!ParseIsimApp(CardStatus, 2).has_value(), "a card with a USIM only: no ISIM"); + Check(!ParseIsimApp(CardStatus, 1).has_value(), "a slot with no card: no ISIM"); + Check(!ParseIsimApp("", 1).has_value(), "no card status: no ISIM"); + } + { + auto sel = ParseCardStatus(CardStatusIsimFirst); + Check(sel && sel->slot == 1 && sel->aid == "A0000000871002FFFFFFFF8903020000", "the USIM listed after an ISIM is read"); + auto first = ParseIsimApp(CardStatusIsimFirst, 1); + Check(first && first->aid == "A0000000871004FFFFFFFF8903020000" && first->state == "detected", "the ISIM listed before the USIM is found"); + // slot 2's ISIM is not slot 1's: each slot's reader gets its own card's + auto other = ParseIsimApp(CardStatusIsimFirst, 2); + Check(other && other->aid == "A0000000871004FF49FF0589", "the other slot's ISIM for the other slot: a twelve-byte AID, lower case made upper"); + Check(other && other->state == "ready", "its state, ready"); + Check(first && other && first->aid != other->aid, "slot 1 is not answered with slot 2's ISIM"); + Check(!ParseIsimApp(CardStatusIsimFirst, 3).has_value(), "a slot the status does not list: no ISIM"); + } + { + // an application of another type keeps its AID to itself, and an + // ISIM whose state line is missing is found with no state + auto none = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'csim (4)'\n\t\tApplication state: 'detected'\n\t\tApplication ID:\n\t\t\tA0:00:00:03:43:10:02:FF\n", 1); + Check(!none.has_value(), "a CSIM is no ISIM"); + auto bare = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'isim (5)'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:04:FF\n", 1); + Check(bare && bare->aid == "A0000000871004FF" && bare->state.empty(), "an ISIM without a state line: found, the state empty"); + // the state of the application before it is not taken for the ISIM's + auto after = ParseIsimApp("Slot [1]:\n\tApplication [1]:\n\t\tApplication type: 'usim (2)'\n\t\tApplication state: 'ready'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:02:FF\n\tApplication [2]:\n\t\tApplication type: 'isim (5)'\n\t\tApplication ID:\n\t\t\tA0:00:00:00:87:10:04:FF\n", 1); + Check(after && after->state.empty(), "the USIM's state is not the ISIM's"); + } + + // ---- the commands a file of the selected application is read with + Check(EfImpi == 0x6F02 && EfDomain == 0x6F03 && EfImpu == 0x6F04, "the three identity files' identifiers (TS 31.103 4.2.2 to 4.2.4)"); + Check(BuildSelectFileApdu(1, EfImpi) == "01a40004026f02", "SELECT EF_IMPI on channel 1"); + Check(BuildSelectFileApdu(5, EfDomain) == "41a40004026f03", "SELECT EF_DOMAIN on channel 5: the extended class byte"); + Check(BuildSelectFileApdu(2, 0x00AD) == "02a400040200ad", "a file identifier below 1000 keeps its four digits"); + Check(BuildReadBinaryApdu(1) == "01b0000000", "READ BINARY from offset 0, Le 00"); + Check(BuildReadBinaryApdu(4) == "40b0000000", "READ BINARY on channel 4"); + Check(BuildReadRecordApdu(1, 1) == "01b2010400", "READ RECORD 1, absolute, Le 00"); + Check(BuildReadRecordApdu(6, 2) == "42b2020400", "READ RECORD 2 on channel 6"); + + // ---- a card's answer, and the command it asks for next + { + std::vector offer = {0x61, 0x19}; + auto a = ParseApduAnswer(offer); + Check(a && a->data.empty() && a->sw1 == 0x61 && a->sw2 == 0x19, "61 19: no data, the status word"); + Check(a && !a->Ok() && a->Status() == "6119", "61 19 is not 90 00; written 6119"); + Check(a && Selected(*a), "a SELECT answered 61 XX has selected the file"); + Check(a && ApduFollowUp(1, "01a40004026f02", *a) == "01c0000019", "61 19 asks for GET RESPONSE with Le 19"); + Check(a && ApduFollowUp(5, "41b0000000", *a) == "41c0000019", "GET RESPONSE on the command's channel"); + + std::vector data = {0x80, 0x03, 'a', '.', 'b', 0x90, 0x00}; + auto d = ParseApduAnswer(data); + Check(d && d->data.size() == 5 && d->data[0] == 0x80 && d->data[4] == 'b', "data before 90 00 is the answer's data"); + Check(d && d->Ok() && d->Status() == "9000" && Selected(*d), "90 00 is Ok"); + Check(d && !ApduFollowUp(1, "01b0000000", *d).has_value(), "90 00 with data asks for nothing"); + + std::vector len = {0x6C, 0x23}; + auto l = ParseApduAnswer(len); + Check(l && ApduFollowUp(1, "01b0000000", *l) == "01b0000023", "6C 23 to READ BINARY: the command again with Le 23"); + Check(l && ApduFollowUp(4, "40b2010400", *l) == "40b2010423", "6C 23 to READ RECORD: the command again with Le 23"); + Check(l && !ApduFollowUp(1, "0188008122" "10" "11111111111111111111111111111111" "10" "22222222222222222222222222222222", *l).has_value(), "6C XX to a command that carries data: nothing to send again"); + Check(l && !Selected(*l), "6C XX is no selected file"); + + std::vector missing = {0x6A, 0x82}; + auto m = ParseApduAnswer(missing); + Check(m && m->Status() == "6a82" && !m->Ok() && !Selected(*m), "6A 82: file not found, nothing selected"); + Check(m && !ApduFollowUp(1, "01a40004026f09", *m).has_value(), "an error asks for nothing"); + + std::vector more = {0x80, 0x01, 'a', 0x61, 0x05}; + auto w = ParseApduAnswer(more); + Check(w && !ApduFollowUp(1, "01b0000000", *w).has_value(), "data with 61 XX is not followed"); + + std::vector one = {0x90}; + Check(!ParseApduAnswer(one).has_value(), "one byte is no answer"); + Check(!ParseApduAnswer({}).has_value(), "no bytes is no answer"); + std::vector sw = {0x90, 0x00}; + auto e = ParseApduAnswer(sw); + Check(e && e->data.empty() && e->Ok(), "90 00 alone: Ok, no data"); + + // a card with a proactive command waiting ends a command 91 XX, one + // with a data transfer session going on 92 XX + std::vector proactive = {0x80, 0x03, 'a', '.', 'b', 0x91, 0x0B}; + auto p = ParseApduAnswer(proactive); + Check(p && p->Ok() && Selected(*p) && HoldsRead(*p) && p->data.size() == 5, "91 XX is a normal ending"); + std::vector transfer = {0x80, 0x03, 'a', '.', 'b', 0x92, 0x10}; + auto x = ParseApduAnswer(transfer); + Check(x && x->Ok() && Selected(*x) && HoldsRead(*x), "92 XX is a normal ending"); + std::vector n9001 = {0x90, 0x01}, n9300 = {0x93, 0x00}; + Check(!ParseApduAnswer(n9001)->Ok(), "90 01 is no normal ending"); + Check(!ParseApduAnswer(n9300)->Ok(), "93 00 is no normal ending"); + + // a read may end 62 82 with all the file holds + std::vector eof = {0x80, 0x03, 'a', '.', 'b', 0x62, 0x82}; + auto f = ParseApduAnswer(eof); + Check(f && !f->Ok() && HoldsRead(*f) && !Selected(*f), "data under 62 82 is what a read holds, and no normal ending"); + Check(d && HoldsRead(*d), "data under 90 00 is what a read holds"); + std::vector bare6282 = {0x62, 0x82}, d6281 = {0x80, 0x01, 'a', 0x62, 0x81}, d6382 = {0x80, 0x01, 'a', 0x63, 0x82}; + Check(!HoldsRead(*ParseApduAnswer(bare6282)), "62 82 without data holds nothing"); + Check(!HoldsRead(*ParseApduAnswer(d6281)), "data under 62 81 is not taken"); + Check(!HoldsRead(*ParseApduAnswer(d6382)), "data under 63 82 is not taken"); + Check(m && !HoldsRead(*m), "6A 82 holds nothing"); + } + + // ---- the value an ISIM identity file holds (the data object with tag 80) + { + auto bytes = [](std::initializer_list head, std::string_view text, std::size_t pad) { + std::vector v(head); + v.insert(v.end(), text.begin(), text.end()); + v.insert(v.end(), pad, 0xFF); + return v; + }; + Check(ParseIsimValue(bytes({0x80, 0x0F}, "ims.example.net", 17)) == "ims.example.net", "the value of the object, the file's FF padding after it not read"); + Check(ParseIsimValue(bytes({0x80, 0x0F}, "ims.example.net", 0)) == "ims.example.net", "the value with nothing after it"); + Check(ParseIsimValue(bytes({0x80, 0x81, 0x0F}, "ims.example.net", 3)) == "ims.example.net", "a length in the 81 form"); + Check(ParseIsimValue(bytes({0x80, 0x82, 0x00, 0x0F}, "ims.example.net", 3)) == "ims.example.net", "a length in the 82 form"); + Check(ParseIsimValue(bytes({0x80, 0x23}, "001010123456789@private.example.net", 29)) == "001010123456789@private.example.net", "a private identity"); + Check(ParseIsimValue(bytes({0x80, 0x22}, "sip:001010123456789@ims.example.net", 30)) == "sip:001010123456789@ims.example.ne", "the length decides, not the bytes that follow"); + std::vector unused(64, 0xFF); + Check(!ParseIsimValue(unused).has_value(), "an unused record, all FF: no value"); + Check(!ParseIsimValue(bytes({0x81, 0x0F}, "ims.example.net", 0)).has_value(), "another tag: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x10}, "ims.example.net", 0)).has_value(), "a length past the data: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x00}, "", 4)).has_value(), "a length of zero: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x83, 0x00, 0x00, 0x0F}, "ims.example.net", 0)).has_value(), "a length form of three bytes: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x81}, "", 0)).has_value(), "an 81 form with no length byte: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x82, 0x00}, "", 0)).has_value(), "an 82 form cut short: no value"); + Check(!ParseIsimValue(bytes({0x80}, "", 0)).has_value(), "the tag alone: no value"); + Check(!ParseIsimValue({}).has_value(), "no bytes: no value"); + Check(ParseIsimValue(bytes({0x80, 0x12}, "ims.example.net", 3)) == "ims.example.net", "FF at the end of the length are padding counted into it"); + std::vector ffInside = {0x80, 0x05, 'a', '.', 0xFF, '.', 'b'}; + Check(!ParseIsimValue(ffInside).has_value(), "an FF before the value's end: no value"); + std::vector ffOnly = {0x80, 0x03, 0xFF, 0xFF, 0xFF, 0xFF}; + Check(!ParseIsimValue(ffOnly).has_value(), "a length of nothing but FF: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x0F}, "ims example.net", 0)).has_value(), "a blank in the value: no value"); + Check(!ParseIsimValue(bytes({0x80, 0x11}, "ims.example.net\r\n", 0)).has_value(), "a line break in the value: no value"); + std::vector nul = {0x80, 0x03, 'a', 0x00, 'b'}; + Check(!ParseIsimValue(nul).has_value(), "a NUL in the value: no value"); + std::vector utf8 = {0x80, 0x03, 'a', 0xC3, 0xA9}; + Check(!ParseIsimValue(utf8).has_value(), "a byte above ASCII in the value: no value"); + } + + // ---- the identity an ISIM holds + { + const Identity derived = MakeIdentity("001010123456789", "001", "01"); + // names unlike the derived ones: a domain of the operator's own + auto id = IsimIdentity(derived, "001010123456789@private.example.net", "one.example.net", "sip:001010123456789@one.example.net"); + Check(id.has_value(), "an ISIM's three values make an identity"); + Check(id && id->impi == "001010123456789@private.example.net", "the private identity is the card's"); + Check(id && id->domain == "one.example.net", "the home domain is the card's"); + Check(id && id->impu == "sip:001010123456789@one.example.net", "the public identity is the card's"); + Check(id && id->regUri == "sip:one.example.net", "the registration URI is that domain's"); + Check(id && id->imsi == derived.imsi && id->mcc == derived.mcc && id->mnc == derived.mnc, "the IMSI and the operator stay"); + // an ISIM that holds the names the IMSI gives: the same identity + auto same = IsimIdentity(derived, derived.impi, derived.domain, derived.impu); + Check(same && same->impi == derived.impi && same->domain == derived.domain && same->impu == derived.impu && same->regUri == derived.regUri, "the derived names from an ISIM give the derived identity"); + // a public identity that is a number, a domain with a hyphen and digits + Check(IsimIdentity(derived, "user@realm.example", "ims-1.example.net", "sip:+15555550100@ims-1.example.net").has_value(), "a number as the public identity, a hyphen in the domain"); + + auto no = [&](std::string_view impi, std::string_view domain, std::string_view impu) { return !IsimIdentity(derived, impi, domain, impu).has_value(); }; + const std::string_view P = "001010123456789@private.example.net", D = "one.example.net", U = "sip:001010123456789@one.example.net"; + Check(no("001010123456789", D, U), "a private identity without a realm is refused"); + Check(no("@private.example.net", D, U), "a private identity without a user is refused"); + Check(no("001010123456789@", D, U), "a private identity that ends at the @ is refused"); + Check(no("", D, U), "an empty private identity is refused"); + Check(no("0010101\"23456789@private.example.net", D, U), "a quote in the private identity is refused (it stands in a quoted string)"); + Check(no("001010123456789\\@private.example.net", D, U), "a backslash in the private identity is refused"); + Check(no("001010123456789@private.example.net\r\nVia: x", D, U), "a line break in the private identity is refused"); + Check(no("0010101 23456789@private.example.net", D, U), "a blank in the private identity is refused"); + Check(no(P, "", U), "an empty domain is refused"); + Check(no(P, "one.example.net>", U), "an angle bracket in the domain is refused"); + Check(no(P, "one_example.net", U), "an underscore in the domain is refused"); + Check(no(P, "one..example.net", U), "an empty label in the domain is refused"); + Check(no(P, ".one.example.net", U), "a domain that begins with a dot is refused"); + Check(no(P, "one.example.net.", U), "a domain that ends with a dot is refused"); + Check(no(P, "-one.example.net", U), "a label that begins with a hyphen is refused"); + Check(no(P, "one-.example.net", U), "a label that ends with a hyphen is refused"); + Check(no(P, "one.example.net-", U), "a domain that ends with a hyphen is refused"); + Check(no(P, "one.example.net:5060", U), "a port on the domain is refused"); + Check(no(P, "one.example.net;lr", U), "a parameter on the domain is refused"); + Check(no(P, "one.example.net\r\nRoute: ", U), "a line break in the domain is refused"); + Check(no(P, D, "tel:+15555550100"), "a tel: public identity is refused"); + Check(no(P, D, "sip:"), "a public identity that is the scheme alone is refused"); + Check(no(P, D, "001010123456789@one.example.net"), "a public identity without a scheme is refused"); + Check(no(P, D, "sip:001010123456789@one.example.net>;tag=x"), "an angle bracket in the public identity is refused (it stands between two)"); + Check(no(P, D, "sip:001010123456789@one.example.net"), "a line break in the public identity is refused"); + Check(no(P, D, "sip:0010101 23456789@one.example.net"), "a blank in the public identity is refused"); + Check(no(P, D, "sip:us\xC3\xA9r@one.example.net"), "a byte above ASCII in the public identity is refused"); + Check(no(P, std::string(64, 'a') + ".example.net", U), "a label of 64 characters in the domain is refused"); + Check(!no(P, std::string(63, 'a') + ".example.net", U), "a label of 63 characters is taken"); + Check(no(std::string(300, 'a') + "@x.example", D, U), "a private identity of 300 characters is refused"); + Check(no(std::string(246, 'a') + "@x.example", D, U), "a private identity of 256 characters is refused"); + Check(!no(std::string(245, 'a') + "@x.example", D, U), "a private identity of 255 characters is taken"); + Check(no(P, D, "sip:" + std::string(252, 'a')), "a public identity of 256 characters is refused"); + Check(!no(P, D, "sip:" + std::string(251, 'a')), "a public identity of 255 characters is taken"); + } + if (Failures == 0) std::println("Aka: 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/Engine/main.cpp b/tests/Engine/main.cpp index 9429a13..4a7c514 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 @@ -12,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: @@ -20,7 +26,9 @@ // fresh 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 (Holds/Restore), and a binding the network terminated -// (OnBindingTerminated). Then SMS over IP: the status-report book +// (OnBindingTerminated). Then WakeAt, when the phone has to be awake for +// imsd, and the policy's wake after a local wait (WakeTime). Then SMS +// over IP: the status-report book // (StatusReportBook with SameRecipient — a word for the whole message: a two-segment // message delivered with its last segment, a permanent failure the last // word, pending kept, another recipient no match, a reused TP-MR, a @@ -94,8 +102,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" @@ -152,6 +161,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) @@ -470,6 +503,55 @@ int main() { Check(m.Terminated(), "terminated on second timeout"); } + // ---- the client flow dies before any response to the INVITE: the shell + // 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); + Check(!m.Unanswered() && !m.ResendDue(), "no INVITE sent yet: nothing to send again"); + auto start = m.Start(); + const Action* inv = Sent(start, "INVITE "); + Check(m.Unanswered() && m.ResendDue(), "an INVITE with no response: a resend is due"); + auto again = m.OnFlowReopened(); + const Action* inv2 = Sent(again, "INVITE "); + Check(inv && inv2 && inv2->text == inv->text, "the resent INVITE is the first one, byte for byte"); + 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 INVITE"); + Check(m.OnFlowReopened().empty(), "a second reopen sends nothing"); + auto lost = m.OnFlowLost(); + const Action* t = Find(lost, Action::Type::State); + Check(t && t->reason == "error" && m.Terminated(), "a flow that dies again ends the call with error"); + Check(Has(lost, Action::Type::Deleted) && Sent(lost, "CANCEL ") == nullptr, "... deleted, and no CANCEL onto a dead flow"); + Check(!m.Unanswered() && m.OnFlowLost().empty() && m.OnFlowReopened().empty(), "an ended call has nothing more to end or to send"); + } + + // ---- ... not once a response has come (a 100 is one), the user has hung + // up or a deadline has cancelled the attempt, and never for an + // incoming call + { + imsd::util::Rng rng(17); + CallMachine m(c, rng, "ims-call-6c", "1233", 50004, false); + m.Start(); + m.OnInviteResponse(Final(m.CallId(), 100, "Trying")); + Check(!m.Unanswered() && !m.ResendDue(), "a 100 Trying is a response: no resend"); + Check(m.OnFlowReopened().empty() && m.OnFlowLost().empty() && !m.Terminated(), "... and the flow's death is left to the deadline"); + imsd::util::Rng rng2(18); + CallMachine n(c, rng2, "ims-call-6d", "1233", 50004, false); + n.Start(); + n.OnHangup(); + Check(!n.Unanswered() && n.OnFlowReopened().empty() && n.OnFlowLost().empty(), "an attempt the user cancelled is not sent again"); + imsd::util::Rng rng3(19); + CallMachine o(c, rng3, "ims-call-6e", "1233", 50004, false); + o.Start(); + o.OnDeadline(); // ring timeout: CANCEL + Check(!o.Unanswered() && o.OnFlowReopened().empty() && o.OnFlowLost().empty(), "nor one a deadline cancelled"); + imsd::util::Rng rng4(20); + CallMachine p(c, rng4, "ims-call-6f", IncomingInvite{MtInvite()}, 50004); + Check(!p.Unanswered() && p.OnFlowReopened().empty() && p.OnFlowLost().empty(), "an incoming call has no INVITE of ours to send again"); + } + // ================= incoming (terminating / UAS) ======================= // ---- full accepted incoming call: INVITE -> 100+180, Accept -> 200 with @@ -839,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 @@ -880,6 +1023,31 @@ int main() { Check(m.State() == CallState::Active, "active on the fallback leg"); } + // ---- the emergency chain with a flow that dies: each attempt has a + // resend of its own + { + imsd::util::Rng rng(44); + CallMachine m(c, rng, "ims-call-16b", "112", 50004, false, true); + auto start = m.Start(); + auto again = m.OnFlowReopened(); + const Action* sos = Sent(start, "INVITE "); + const Action* sos2 = Sent(again, "INVITE "); + Check(sos && sos2 && sos2->text == sos->text && sos2->text.starts_with("INVITE urn:service:sos "), "the sos INVITE again over a reopened flow"); + auto a = m.OnInviteResponse(Final(m.CallId(), 500, "Server Internal Error")); + const Action* plain = Sent(a, "INVITE "); + Check(plain && plain->text.starts_with("INVITE sip:112;phone-context="), "the fallback follows a resent sos attempt as it follows a first one"); + Check(m.Unanswered() && m.ResendDue(), "the fallback attempt has a resend of its own"); + auto again2 = m.OnFlowReopened(); + const Action* plain2 = Sent(again2, "INVITE "); + Check(plain && plain2 && plain2->text == plain->text, "... of the fallback's INVITE"); + imsd::util::Rng rng2(45); + CallMachine n(c, rng2, "ims-call-16c", "112", 50004, false, true); + n.Start(); + auto lost = n.OnFlowLost(); + const Action* t = Find(lost, Action::Type::State); + Check(t && t->reason == "error" && n.Terminated() && Sent(lost, "INVITE ") == nullptr, "a sos attempt whose flow is lost ends there: no fallback INVITE onto a dead flow"); + } + // ---- chain exhausted: the fallback leg's final terminates, no 3rd try { imsd::util::Rng rng(45); @@ -893,6 +1061,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); @@ -1322,6 +1732,129 @@ int main() { } } + // ---- WakeAt: when the phone has to be awake for imsd (the shell arms + // its wake alarm from it). The clock is ours: seconds. + { + Check(WakeAt(1000, true, true, 2800, 0, true, 1005) == 1000, "busy (a call, a text in flight): now, the phone is to stay awake"); + Check(WakeAt(1000, true, false, 0, 0, false, 0) == 1000, "…also where no registration stands (an emergency call)"); + Check(WakeAt(1000, false, true, 2800, 0, false, 0) == 2800, "a registration on a live flow: the refresh's due time"); + Check(WakeAt(1000, false, true, 2800, 0, true, 1005) == 2800, "…whatever the recovery policy names meanwhile"); + Check(WakeAt(1000, false, true, 990, 0, false, 0) == 990, "a refresh that is due: its time, which has come"); + Check(WakeAt(1000, false, true, 2800, 1300, false, 0) == 1300, "the reg-event subscription's renewal where it comes before the refresh"); + Check(WakeAt(1000, false, true, 2800, 600400, false, 0) == 2800, "…and the refresh where the renewal is far off"); + Check(WakeAt(1000, false, false, 2800, 1300, true, 1005) == 1005, "a dead flow under a registration: the recovery's next step"); + Check(WakeAt(1000, false, false, 2800, 0, true, 0) == 1000, "a step the policy says is due now (its 0): now, not no alarm"); + Check(WakeAt(1000, false, false, 2800, 0, true, 400) == 1000, "…and one whose time has passed"); + Check(WakeAt(1000, false, false, 2800, 0, false, 1005) == 0, "no flow and nothing to recover: no alarm"); + RegRecovery w; + w.OldGone(); w.OnFreshFailure(1000, RegRecovery::Failure::Throttled); + Check(WakeAt(1000, false, false, 0, 0, true, w.WakeTime(1000)) == 1000 + 21 * 60, "a throttled fresh registration: the alarm at the schedule's end, 21 min on"); + } + + // ---- RegRecovery: the wake after a local wait. Awake, the next look is + // LocalRetry on; a sleeping phone is woken for it after as long again as + // that kind of wait has lasted (no packet service: since the modem's + // first such word since the network last answered; a connect the kernel + // refused: since its first refusal since the modem was last without + // service or the network last answered, whichever came later), within + // LocalWakeMin and Max. A counted step is woken for at the policy's own + // time. + { + using L = RegRecovery::Local; + using F = RegRecovery::Failure; + RegRecovery g; + Check(!g.LocalLook() && g.WakeTime(1000) == 0, "nothing waits: the step's own time (due now)"); + { + RegRecovery o; + o.OnLocalRefusal(1000, L::NoService); o.OnLocalRefusal(1600, L::NoService); + Check(o.WakeTime(1600) == 1600 + 600, "600 s into a gap: the slower look, 600 s on"); + o.OldGone(); + Check(!o.LocalLook() && o.WakeTime(1600) == o.Next(1600).at, "the old registration written off meanwhile: a verdict, the wake at the policy's own time"); + } + g.OnLocalRefusal(1000, L::NoService); + Check(g.LocalLook() && g.Next(1000).at == 1000 + RegRecovery::LocalRetry, "a local wait: looked at again LocalRetry on"); + Check(g.WakeTime(1000) == 1000 + 10, "…a sleeping phone woken for it 10 s on, the floor (LocalWakeMin)"); + g.OnLocalRefusal(1005, L::NoService); g.OnLocalRefusal(1010, L::NoService); + Check(g.WakeTime(1010) == 1010 + RegRecovery::LocalWakeMin, "looks while awake push the wake on, the floor standing"); + g.OnLocalRefusal(1012, L::NoService); + Check(g.WakeTime(1012) == 1012 + 12, "12 s into the gap: woken after 12 s more"); + g.OnLocalRefusal(1200, L::NoService); + Check(g.WakeTime(1200) == 1200 + 200, "200 s into the gap: woken after 200 s more"); + g.OnLocalRefusal(4000, L::NoService); + Check(g.WakeTime(4000) == 4000 + 900, "a long gap: every 15 min, the ceiling (LocalWakeMax)"); + Check(g.Next(4000).at == 4000 + RegRecovery::LocalRetry, "…the awake pace as it was"); + // the modem has service again and the kernel refuses the connect (the old flow's 4-tuple): looked at soon + g.OnLocalRefusal(4100, L::Kernel); + Check(g.WakeTime(4100) == 4100 + RegRecovery::LocalWakeMin, "the first connect the kernel refuses after the gap: woken LocalWakeMin on"); + g.OnLocalRefusal(4130, L::Kernel); + Check(g.WakeTime(4130) == 4130 + 30, "…30 s of such refusals: 30 s more"); + // the modem's word alternates: the gap's pace does not start over, the kernel's does at each return + g.OnLocalRefusal(4200, L::NoService); + Check(g.WakeTime(4200) == 4200 + RegRecovery::LocalWakeMax, "no service again: the gap's count goes on from its first word, at the ceiling by now"); + g.OnLocalRefusal(5000, L::Kernel); + Check(g.WakeTime(5000) == 5000 + RegRecovery::LocalWakeMin, "the kernel's refusal after it: counted from this one, not from before the gap"); + g.OnLocalRefusal(5100, L::NoService); + Check(g.WakeTime(5100) == 5100 + RegRecovery::LocalWakeMax, "…and no service again: the gap's pace still"); + // a counted step is woken for at its own time, and the gap's count stands through a silent one + RegRecovery a = g; a.OnReconnectFailure(5110, F::Silent); + Check(!a.LocalLook() && a.WakeTime(5110) == a.Next(5110).at && a.Next(5110).at == 5110 + RegRecovery::ReconnectDelayMin, "a silent cycle: the policy's own time, not the gap's pace"); + a.OnLocalRefusal(5200, L::NoService); + Check(a.WakeTime(5200) == 5200 + RegRecovery::LocalWakeMax, "…no service after it: the gap's pace goes on where it was"); + RegRecovery b = g; b.OnFreshFailure(5110, F::Silent); + Check(!b.LocalLook() && b.WakeTime(5110) == b.Next(5110).at, "a silent fresh attempt: the policy's own time"); + b.OnLocalRefusal(5200, L::NoService); + Check(b.WakeTime(5200) == 5200 + RegRecovery::LocalWakeMax, "…and the gap's pace after it"); + // the network's answer starts both counts over + RegRecovery r = g; r.OnReconnectFailure(5110, F::Refused); + Check(!r.LocalLook() && r.WakeTime(5110) == r.Next(5110).at, "a refusal: the policy's own time"); + r.OnLocalRefusal(5300, L::NoService); + Check(r.WakeTime(5300) == 5300 + RegRecovery::LocalWakeMin, "…and a gap after the network's answer starts at the floor"); + RegRecovery th = g; th.OnFreshFailure(5110, F::Throttled); th.OldGone(); th.OnLocalRefusal(5300, L::NoService); + Check(th.Next(5300).at == 5110 + 21 * 60 && th.WakeTime(5300) == 5110 + 21 * 60, "a throttle with the old registration written off: the look after it woken for at the schedule's end, which is later than the look's floor"); + RegRecovery tr = g; tr.OnFreshFailure(5110, F::Throttled); tr.OnLocalRefusal(5300, L::NoService); + Check(tr.WakeTime(5300) == 5300 + 10, "a throttle is the network's answer too: a gap after it starts at the floor"); + RegRecovery tf = g; tf.OnFreshFailure(5110, F::Refused); tf.OnLocalRefusal(5300, L::NoService); + Check(tf.WakeTime(5300) == 5300 + 10, "…and so is a refused fresh attempt"); + RegRecovery c = g; c.OnBindingTerminated(5110, "expired"); + Check(!c.LocalLook(), "a terminated binding: a counted step"); + c.OnLocalRefusal(5300, L::NoService); + Check(c.WakeTime(5300) == 5300 + 10, "…and the network's word: a gap after it starts at the floor"); + RegRecovery d = g; d.OnSuccess(); + Check(!d.LocalLook() && d.WakeTime(5110) == 0, "a success: everything over"); + d.OnLocalRefusal(5200, L::NoService); + Check(d.WakeTime(5200) == 5200 + 10, "…the gap's count too: a gap after it starts at the floor"); + RegRecovery kq; kq.OnLocalRefusal(2000, L::Kernel); kq.OnLocalRefusal(2400, L::Kernel); + Check(kq.WakeTime(2400) == 2400 + 400, "400 s of the kernel's refusals: 400 s more"); + RegRecovery n = kq; n.OnNetworkAnswered(); n.OnLocalRefusal(2410, L::Kernel); + Check(n.WakeTime(2410) == 2410 + RegRecovery::LocalWakeMin, "an answered connect, then the kernel's refusal: the floor again"); + RegRecovery n2 = kq; n2.OnLocalRefusal(2410, L::Kernel); + Check(n2.WakeTime(2410) == 2410 + 410, "…where without the answer the count had gone on"); + // …and the kernel's count at each of the policy's own: 800 s of refusals would be woken for 800 s on + RegRecovery kr = kq; kr.OnReconnectFailure(2405, F::Refused); kr.OnLocalRefusal(2800, L::Kernel); + Check(kr.WakeTime(2800) == 2800 + 10, "a refused reconnect starts the kernel's count over too"); + RegRecovery kt = kq; kt.OnFreshFailure(2405, F::Throttled); kt.OnLocalRefusal(2800, L::Kernel); + Check(kt.WakeTime(2800) == 2800 + 10, "…a throttled fresh attempt"); + RegRecovery kf = kq; kf.OnFreshFailure(2405, F::Refused); kf.OnLocalRefusal(2800, L::Kernel); + Check(kf.WakeTime(2800) == 2800 + 10, "…a refused one"); + RegRecovery kc = kq; kc.OnBindingTerminated(2405, "expired"); kc.OnLocalRefusal(2800, L::Kernel); + Check(kc.WakeTime(2800) == 2800 + 10, "…a terminated binding"); + RegRecovery ks = kq; ks.OnSuccess(); ks.OnLocalRefusal(2800, L::Kernel); + Check(ks.WakeTime(2800) == 2800 + 10, "…and a success"); + RegRecovery kn = kq; kn.OnReconnectFailure(2405, F::Silent); kn.OnLocalRefusal(2800, L::Kernel); + Check(kn.WakeTime(2800) == 2800 + 800, "…and not a silent cycle: 800 s of refusals, 800 s more"); + RegRecovery kb = kq; kb.OnFreshFailure(2405, F::Silent); kb.OnLocalRefusal(2800, L::Kernel); + Check(kb.WakeTime(2800) == 2800 + 800, "…nor a silent fresh attempt"); + RegRecovery gq = g; gq.OnNetworkAnswered(); gq.OnLocalRefusal(5200, L::NoService); + Check(gq.WakeTime(5200) == 5200 + RegRecovery::LocalWakeMin, "an answer, then a gap: the floor, where without it the gap's count was at its ceiling"); + // a hold the network set outlasts the look's pace + RegRecovery h; h.OnReconnectFailure(1000, F::Refused, 600); h.OnLocalRefusal(1100, L::NoService); + Check(h.Next(1100).at == 1600 && h.WakeTime(1100) == 1600, "a hold that outlasts the look's pace: woken for at the hold's end, not 10 s on"); + RegRecovery k; k.OnLocalRefusal(1000); + Check(k.WakeTime(1000) == 1000 + RegRecovery::LocalWakeMin, "a refusal with no kind named and no gap before it: the floor"); + RegRecovery kd; kd.OnLocalRefusal(1000, L::NoService); kd.OnLocalRefusal(1600); + Check(kd.WakeTime(1600) == 1600 + 10, "…and it is the kernel's (the default kind): 600 s into a gap its own count starts, at the floor"); + } + // ---- SMS over IP: SmsOutbound and OnSmsMessage (TS 24.341) ---------- { using namespace imsd::sms; diff --git a/tests/Ipsec/main.cpp b/tests/Ipsec/main.cpp index d8e3088..6512087 100644 --- a/tests/Ipsec/main.cpp +++ b/tests/Ipsec/main.cpp @@ -3,9 +3,13 @@ // Imsd:Ipsec unit tests — the `ip xfrm` setup command sequence (byte-exact // argv), the warm-SA reader, fed `ip xfrm state`/`policy` output in the -// exact shape captured from a registered FP6 (addresses/keys synthetic), and +// exact shape captured from a registered FP6 (addresses/keys synthetic) and, +// for the entry it rebuilds, states in the shape a Linux 7.2 `ip xfrm state` +// 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, KPN's single mechanism). +// six-mechanism Mavenir shape verbatim, under a null and under an aes-cbc +// 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; @@ -77,6 +81,42 @@ int main() { Check(sa && sa->spiPc == 0x0526f2c1u, "spi_pc (UE->P reqid2)"); Check(sa && sa->securityServer == "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; " "spi-c=86438593; spi-s=86438592; port-c=33421; port-s=6000", "reconstructed Security-Server value"); } + // the rebuilt entry names the pair's own algorithms: the state towards + // the P-CSCF's server port as `ip xfrm state` prints it for each + // algorithm imsd installs (the null cipher has no key: a trailing space) + { + constexpr std::string_view Sha1 = "\tauth-trunc hmac(sha1) 0x00112233445566778899aabbccddeeff 96\n"; + constexpr std::string_view Md5 = "\tauth-trunc hmac(md5) 0x00112233445566778899aabbccddeeff 96\n"; + constexpr std::string_view Aes = "\tenc cbc(aes) 0xffeeddccbbaa99887766554433221100\n"; + constexpr std::string_view Null = "\tenc ecb(cipher_null) \n"; + constexpr std::string_view Des3 = "\tenc cbc(des3_ede) 0xffeeddccbbaa99887766554433221100ffeeddccbbaa9988\n"; + // `first` is the reqid-1 state's two lines (the state that gives spi-s), + // `second` the reqid-2 state's + auto rebuilt = [](std::string_view first, std::string_view second, bool reqid1Listed1st = false) { + auto block = [](std::string_view spi, int reqid, std::string_view lines) { + return std::format( + "src 2001:db8:1111:2222:3333:4444:5555:db43 dst 2001:db8::105\n" + "\tproto esp spi {} reqid {} mode transport\n" + "\treplay-window 0 \n" + "{}" + "\tanti-replay context: seq 0x0, oseq 0x0, bitmap 0x00000000\n" + "\tsel src ::/0 dst ::/0 \n", spi, reqid, lines); + }; + const std::string one = block("0x0526f2c0", 1, first); + const std::string two = block("0x0526f2c1", 2, second); + auto sa = ParseExistingSa(reqid1Listed1st ? one + two : two + one, Policy, "2001:db8::105", "2001:db8:1111:2222:3333:4444:5555:db43"); + return sa ? sa->securityServer : std::string(); + }; + auto entry = [](std::string_view alg, std::string_view ealg) { return std::format("ipsec-3gpp; q=0.1; alg={}; ealg={}; spi-c=86438593; spi-s=86438592; port-c=33421; port-s=6000", alg, ealg); }; + auto both = [](std::string_view a, std::string_view b) { return std::string(a) + std::string(b); }; + Check(rebuilt(both(Sha1, Aes), both(Sha1, Aes)) == entry("hmac-sha-1-96", "aes-cbc"), "rebuilt entry: a sha1 and aes-cbc pair"); + Check(rebuilt(both(Sha1, Null), both(Sha1, Null)) == entry("hmac-sha-1-96", "null"), "rebuilt entry: a null pair names ealg=null"); + Check(rebuilt(both(Sha1, Des3), both(Sha1, Des3)) == entry("hmac-sha-1-96", "des-ede3-cbc"), "rebuilt entry: a 3DES pair names des-ede3-cbc"); + Check(rebuilt(both(Md5, Aes), both(Md5, Aes)) == entry("hmac-md5-96", "aes-cbc"), "rebuilt entry: an md5 pair names hmac-md5-96"); + Check(rebuilt(both(Md5, Null), both(Sha1, Des3)) == entry("hmac-md5-96", "null") && rebuilt(both(Md5, Null), both(Sha1, Des3), true) == entry("hmac-md5-96", "null"), "rebuilt entry: the algorithms are those of the state that gives spi-s, listed first or last"); + Check(rebuilt("", both(Md5, Null)) == entry("hmac-sha-1-96", "aes-cbc"), "rebuilt entry: a state that prints no algorithm reads as sha1 and aes-cbc"); + Check(rebuilt("\tauth-trunc hmac(sha256) 0x00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff 96\n\tenc cbc(camellia) 0xffeeddccbbaa99887766554433221100\n", "") == entry("hmac-sha-1-96", "aes-cbc"), "rebuilt entry: names imsd does not install read as sha1 and aes-cbc"); + } // the environment's spelling must not matter: upper case, uncompressed, // bracketed — the kernel prints RFC 5952 form and both sides are // canonicalised before the compare @@ -249,7 +289,7 @@ int main() { "ipsec-3gpp;q=0.98;alg=hmac-sha-1-96;mod=trans;ealg=aes-cbc"; { // alyx's offer (EALG=null): the entry O2 marked is also the only one matching the offer - auto ss = ParseSecurityServer(O2, "hmac-sha-1-96", "null"); + auto ss = ParseSecurityServer(O2, "hmac-sha-1-96", {"null"}); Check(ss.has_value() && ss->mechanisms.size() == 6, "O2/null: six mechanisms"); Check(ss && ss->selected == 3 && ss->carrier == 3 && ss->offerMatched, "O2/null: the fourth mechanism (sha1, no ealg, the SPIs) selected, offer matched"); if (ss) { @@ -263,44 +303,108 @@ int main() { Check(m.text == "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427852;spi-s=133937015;port-c=6051;port-s=6060", "O2/null: selected text verbatim"); Check(ss->mechanisms[1].ealg == "des-ede3-cbc" && !ss->mechanisms[1].spiPs, "O2/null: the 3DES entry is parsed but carries no SPIs"); } - // the default offer (EALG=aes-cbc): the spec picks sha1+aes (q=0.98); the SPIs stay with the marked entry - auto sa = ParseSecurityServer(O2, "hmac-sha-1-96", "aes-cbc"); + // an offer of aes-cbc alone: sha1+aes (q=0.98) is the offered entry; the SPIs stay with the marked entry + auto sa = ParseSecurityServer(O2, "hmac-sha-1-96", {"aes-cbc"}); Check(sa && sa->selected == 5 && sa->offerMatched, "O2/aes: sha1+aes-cbc (q=0.98) selected for the aes offer"); Check(sa && sa->carrier == 3 && sa->Carrier().spiPs == 133937015u && sa->Carrier().portPs == 6060, "O2/aes: SPIs/ports from the entry carrying them"); Check(sa && sa->Selected().ealg == "aes-cbc" && sa->Selected().alg == "hmac-sha-1-96", "O2/aes: algorithms from the selected entry"); // an offer O2 does not list (3des alias -> des-ede3-cbc): sha1+3des (q=0.96) - auto s3 = ParseSecurityServer(O2, "hmac-sha-1-96", "3des"); + auto s3 = ParseSecurityServer(O2, "hmac-sha-1-96", {"3des"}); Check(s3 && s3->selected == 4 && s3->offerMatched && s3->carrier == 3, "O2/3des: the alias matches des-ede3-cbc (q=0.96), SPIs from the marked entry"); } // ---- KPN: one mechanism, spaces after the separators, explicit ealg { - auto ss = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000", "hmac-sha-1-96", "aes-cbc"); + auto ss = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000", "hmac-sha-1-96", {"aes-cbc"}); Check(ss && ss->mechanisms.size() == 1 && ss->selected == 0 && ss->carrier == 0 && ss->offerMatched, "KPN: single mechanism selected, offer matched"); Check(ss && ss->Selected().alg == "hmac-sha-1-96" && ss->Selected().ealg == "aes-cbc", "KPN: alg + ealg"); Check(ss && ss->Selected().spiPc == 49889723u && ss->Selected().spiPs == 49889722u && ss->Selected().portPc == 33142 && ss->Selected().portPs == 6000, "KPN: SPIs + ports"); Check(ss && ss->Selected().qMilli == 100, "KPN: q=0.1"); - auto nul = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", "null"); + auto nul = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", {"null"}); Check(nul && nul->Selected().ealg == "null" && nul->offerMatched, "KPN: explicit ealg=null matches the null offer"); // the P-CSCF answers a cipher we did not offer: still the only entry, installed as answered, flagged - auto other = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", "aes-cbc"); + auto other = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=33998503; spi-s=33998502; port-c=33021; port-s=6000", "hmac-sha-1-96", {"aes-cbc"}); Check(other && other->selected == 0 && other->carrier == 0 && !other->offerMatched, "single entry not matching the offer: selected via the spi-s fallback, offerMatched=false"); // the fresh-SA throttle answer: spi-s present and zero - auto thr = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=1; spi-s=0; port-c=33102; port-s=6000", "hmac-sha-1-96", "aes-cbc"); + auto thr = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=1; spi-s=0; port-c=33102; port-s=6000", "hmac-sha-1-96", {"aes-cbc"}); Check(thr && thr->Carrier().spiPs.has_value() && *thr->Carrier().spiPs == 0, "KPN throttle: spi-s=0 is present, not absent"); // no SPIs anywhere: parsed, nothing to build from - auto bare = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null;", "hmac-sha-1-96", "null"); + auto bare = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null;", "hmac-sha-1-96", {"null"}); Check(bare && bare->mechanisms.size() == 1 && bare->offerMatched && !bare->Carrier().spiPs && !bare->Carrier().portPs, "no spi-s: absent, not zero"); } + // ---- the offer: EALG as a list, the default when it names nothing + { + using L = std::vector; + Check(DefaultEalgOffer() == L{"aes-cbc", "null"}, "default offer: aes-cbc, then null"); + Check(ParseEalgOffer("null").ciphers == L{"null"} && ParseEalgOffer("aes-cbc").ciphers == L{"aes-cbc"}, "EALG: one name is a list of one"); + Check(ParseEalgOffer("null,aes-cbc").ciphers == L{"null", "aes-cbc"}, "EALG: the order written is the order offered"); + Check(ParseEalgOffer(" AES-CBC ,\tNull ").ciphers == L{"aes-cbc", "null"}, "EALG: case, spaces and tabs ignored"); + Check(ParseEalgOffer("3des").ciphers == L{"des-ede3-cbc"} && ParseEalgOffer("des-ede3-cbc,3DES").ciphers == L{"des-ede3-cbc"}, "EALG: 3des is des-ede3-cbc, a repeat dropped"); + auto mixed = ParseEalgOffer("aes-gcm,null, HMAC-SHA-1-96,aes-gcm"); + Check(mixed.ciphers == L{"null"} && mixed.unknown == L{"aes-gcm", "hmac-sha-1-96"}, "EALG: a name imsd cannot install goes to unknown, once, in lower case without spaces"); + Check(ParseEalgOffer("").ciphers == DefaultEalgOffer() && ParseEalgOffer("").unknown.empty() && ParseEalgOffer(" , ,").ciphers == DefaultEalgOffer() && ParseEalgOffer(" , ,").unknown.empty(), "EALG: empty or blank elements name nothing: the default offer"); + Check(ParseEalgOffer("aes-gcm").ciphers == DefaultEalgOffer() && ParseEalgOffer("aes-gcm").unknown == L{"aes-gcm"}, "EALG: no known name -> the default offer, the name in unknown"); + Check(ParseEalgOffer("aes-cbc,").ciphers == L{"aes-cbc"} && ParseEalgOffer("aes-cbc,").unknown.empty(), "EALG: an empty element is no name, not the null cipher"); + } + // ---- selection against more than one offered cipher + { + const std::vector both = {"aes-cbc", "null"}; + // KPN's answer: one entry + auto kpn = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000", "hmac-sha-1-96", both); + Check(kpn && kpn->selected == 0 && kpn->offerMatched && kpn->Selected().ealg == "aes-cbc", "both offered, KPN's aes-cbc entry: selected, offer matched"); + // Odido's answer to an offer of the null cipher (2026-07-13), verbatim + auto odido = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=null; spi-c=30890423; spi-s=30890422; port-c=32997; port-s=6000", "hmac-sha-1-96", both); + Check(odido && odido->selected == 0 && odido->offerMatched && NormalizeEalg(odido->Selected().ealg) == "null" && odido->Carrier().spiPs == 30890422u, "both offered, Odido's null entry: selected, offer matched"); + // O2's list as it answered a null offer: the SPIs on sha1/null (q=0.94). With + // both ciphers offered that marked entry is taken, not sha1/aes-cbc (q=0.98) + auto o2null = ParseSecurityServer(O2, "hmac-sha-1-96", both); + Check(o2null && o2null->selected == 3 && o2null->carrier == 3 && o2null->offerMatched, "both offered, O2's list marking sha1/null: the marked entry, not the higher-q sha1/aes-cbc"); + Check(o2null && NormalizeEalg(o2null->Selected().ealg) == "null" && o2null->Selected().alg == "hmac-sha-1-96", "both offered, O2 marking sha1/null: the selected entry is sha1 with the null cipher"); + // O2's list as it answered an aes-cbc offer (alyx report 14, 2026-09-20), verbatim: the SPIs on sha1/aes-cbc + constexpr std::string_view O2Aes = + "ipsec-3gpp;q=0.88;alg=hmac-md5-96;mod=trans," + "ipsec-3gpp;q=0.9;alg=hmac-md5-96;mod=trans;ealg=des-ede3-cbc," + "ipsec-3gpp;q=0.92;alg=hmac-md5-96;mod=trans;ealg=aes-cbc," + "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans," + "ipsec-3gpp;q=0.96;alg=hmac-sha-1-96;mod=trans;ealg=des-ede3-cbc," + "ipsec-3gpp;q=0.98;alg=hmac-sha-1-96;mod=trans;ealg=aes-cbc;spi-c=53871876;spi-s=58749351;port-c=6058;port-s=6060"; + auto o2aes = ParseSecurityServer(O2Aes, "hmac-sha-1-96", both); + Check(o2aes && o2aes->selected == 5 && o2aes->carrier == 5 && o2aes->offerMatched && o2aes->Selected().ealg == "aes-cbc", "both offered, O2's list marking sha1/aes-cbc: that entry"); + Check(ParseSecurityServer(O2Aes, "hmac-sha-1-96", {"aes-cbc"})->selected == 5 && ParseSecurityServer(O2Aes, "hmac-sha-1-96", {"null"})->selected == 3, "one cipher offered: the entry of that cipher, marked or not"); + // the marked entry is one we did not offer (md5): the highest-q offered entry, its SPIs + auto md5marked = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc,ipsec-3gpp;q=0.4;alg=hmac-sha-1-96,ipsec-3gpp;q=0.9;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", both); + Check(md5marked && md5marked->selected == 0 && md5marked->carrier == 2 && md5marked->offerMatched, "both offered, the marked entry not offered: the highest-q offered entry, SPIs from the marked one"); + // every entry carries the SPIs: nothing is marked — the highest q, without q the first + auto listq = ParseSecurityServer("ipsec-3gpp;q=0.4;alg=hmac-sha-1-96;ealg=null;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", both); + Check(listq && listq->selected == 1 && listq->carrier == 1 && listq->offerMatched, "both offered, both entries carry the SPIs: the highest q"); + auto listfirst = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=null;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", both); + Check(listfirst && listfirst->selected == 0 && listfirst->offerMatched, "both offered, both entries carry the SPIs, no q: the first on the list"); + // neither offered cipher listed: the P-CSCF's entry, flagged + auto neither = ParseSecurityServer("ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=des-ede3-cbc; spi-c=1; spi-s=2; port-c=3; port-s=4", "hmac-sha-1-96", both); + Check(neither && neither->selected == 0 && !neither->offerMatched, "both offered, a 3DES answer: taken via the spi-s fallback, offerMatched=false"); + // the marked entry over a higher-q offered one also under one offered cipher (same algorithms, the entry's own mod) + auto onecipher = ParseSecurityServer("ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=aes-cbc;mod=tun,ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;mod=trans;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", {"aes-cbc"}); + Check(onecipher && onecipher->selected == 1 && onecipher->Selected().mod == "trans", "one cipher offered, two entries of it: the marked one"); + // the resume's choice under the same offer: O2's stored list, and a list whose two entries carry SPIs of their own + ExistingSa sa; + sa.spiPc = 129427852u; sa.spiPs = 133937015u; sa.portPc = 6051; sa.portPs = 6060; + sa.securityServer = "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=129427852; spi-s=133937015; port-c=6051; port-s=6060"; + auto rsv = ChooseResumeSecurityVerify(O2, sa, both); + Check(rsv.source == ResumeSecurityVerify::Source::Stored && rsv.value == O2 && rsv.mechanisms == 6, "resume, both offered: O2's stored list for the kernel's pair"); + constexpr std::string_view TwoPairs = "ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=null;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8"; + ExistingSa aesPair; + aesPair.spiPc = 5; aesPair.spiPs = 6; aesPair.portPc = 7; aesPair.portPs = 8; + Check(ChooseResumeSecurityVerify(TwoPairs, aesPair, {"aes-cbc"}).source == ResumeSecurityVerify::Source::Stored && ChooseResumeSecurityVerify(TwoPairs, aesPair, both).source == ResumeSecurityVerify::Source::OtherSa, "resume: the offer handed in decides which entry's SPIs are held against the kernel's pair"); + } // ---- the resume's Security-Verify: the stored list only for the SA pair the kernel holds { using Source = ResumeSecurityVerify::Source; ExistingSa sa; sa.spiPc = 129427852u; sa.spiPs = 133937015u; sa.portPc = 6051; sa.portPs = 6060; sa.securityServer = "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=129427852; spi-s=133937015; port-c=6051; port-s=6060"; - auto ok = ChooseResumeSecurityVerify(O2, sa, "null"); + auto ok = ChooseResumeSecurityVerify(O2, sa, {"null"}); Check(ok.source == Source::Stored && ok.value == O2 && ok.mechanisms == 6, "resume: O2's six-entry list whose carrier is the kernel's pair -> the list verbatim, six mechanisms"); - auto okAes = ChooseResumeSecurityVerify(O2, sa, "aes-cbc"); - Check(okAes.source == Source::Stored && okAes.value == O2, "resume: the same under the aes offer (the carrier does not depend on the offer)"); + auto okAes = ChooseResumeSecurityVerify(O2, sa, {"aes-cbc"}); + Check(okAes.source == Source::Stored && okAes.value == O2, "resume: the same under the aes offer (O2's list has one carrier)"); constexpr std::pair off[] = { {"spi-c", "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427853;spi-s=133937015;port-c=6051;port-s=6060"}, {"spi-s", "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427852;spi-s=133937016;port-c=6051;port-s=6060"}, @@ -308,19 +412,19 @@ int main() { {"port-s", "ipsec-3gpp;q=0.94;alg=hmac-sha-1-96;mod=trans;spi-c=129427852;spi-s=133937015;port-c=6051;port-s=6061"}, }; for (const auto& [field, text] : off) { - auto r = ChooseResumeSecurityVerify(text, sa, "null"); + auto r = ChooseResumeSecurityVerify(text, sa, {"null"}); Check(r.source == Source::OtherSa && r.value == sa.securityServer, std::format("resume: {} off by one -> the rebuilt entry", field)); } - auto offSpiS = ChooseResumeSecurityVerify(off[1].second, sa, "null"); + auto offSpiS = ChooseResumeSecurityVerify(off[1].second, sa, {"null"}); Check(offSpiS.storedSpiPs && *offSpiS.storedSpiPs == 133937016u, "resume: the stored spi-s is reported for the log line"); - auto none = ChooseResumeSecurityVerify("", sa, "null"); + auto none = ChooseResumeSecurityVerify("", sa, {"null"}); Check(none.source == Source::NoneStored && none.value == sa.securityServer, "resume: nothing stored -> the rebuilt entry"); - auto junk = ChooseResumeSecurityVerify("not a list", sa, "null"); + auto junk = ChooseResumeSecurityVerify("not a list", sa, {"null"}); Check(junk.source == Source::OtherSa && junk.value == sa.securityServer && !junk.storedSpiPs, "resume: an unparseable value -> the rebuilt entry, no spi-s to report"); ExistingSa kpn; kpn.spiPc = 49889723u; kpn.spiPs = 49889722u; kpn.portPc = 33142; kpn.portPs = 6000; kpn.securityServer = "ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=49889723; spi-s=49889722; port-c=33142; port-s=6000"; - auto k = ChooseResumeSecurityVerify(kpn.securityServer, kpn, "aes-cbc"); + auto k = ChooseResumeSecurityVerify(kpn.securityServer, kpn, {"aes-cbc"}); Check(k.source == Source::Stored && k.value == kpn.securityServer && k.mechanisms == 1, "resume: KPN's one-entry list for its pair -> the list, one mechanism"); } // ---- a state file another attempt left behind: the file's UE SPIs against the kernel pair's @@ -335,44 +439,60 @@ int main() { // ---- selection rules and syntax corners { // spec-shaped list: every entry carries the SPI set, md5 preferred by q — we offered sha1, so sha1 wins (audit A1) - auto a1 = ParseSecurityServer("ipsec-3gpp;q=0.1;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14,ipsec-3gpp;q=0.2;alg=hmac-md5-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14", "hmac-sha-1-96", "aes-cbc"); + auto a1 = ParseSecurityServer("ipsec-3gpp;q=0.1;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14,ipsec-3gpp;q=0.2;alg=hmac-md5-96;ealg=aes-cbc;spi-c=11;spi-s=12;port-c=13;port-s=14", "hmac-sha-1-96", {"aes-cbc"}); Check(a1 && a1->selected == 0 && a1->offerMatched && a1->Selected().alg == "hmac-sha-1-96", "every entry carries SPIs, md5 preferred: the offered sha1 is selected, not the highest q"); // two sha1 entries with different ciphers, both carrying SPIs: the offered cipher wins over q (audit A3) - auto a3 = ParseSecurityServer("ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=des-ede3-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.8;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc"); + auto a3 = ParseSecurityServer("ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=des-ede3-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.8;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"}); Check(a3 && a3->selected == 1 && a3->Carrier().spiPs == 6u, "offered cipher wins over a higher-q cipher we did not offer"); // two matching entries: the higher q - auto two = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc"); + auto two = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"}); Check(two && two->selected == 1 && two->Selected().spiPs == 6u, "two matching entries: highest q selected"); // nothing matches the offer (md5-only list): fallback = the highest-q carrier, flagged - auto md5 = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc"); + auto md5 = ParseSecurityServer("ipsec-3gpp;q=0.5;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;q=0.9;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"}); Check(md5 && md5->selected == 1 && !md5->offerMatched && md5->carrier == 1, "no match: highest-q carrier, offerMatched=false"); // no q at all, nothing matching: the first carrier - auto noq = ParseSecurityServer("ipsec-3gpp;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", "aes-cbc"); + auto noq = ParseSecurityServer("ipsec-3gpp;alg=hmac-md5-96;spi-c=1;spi-s=2;port-c=3;port-s=4,ipsec-3gpp;alg=hmac-md5-96;ealg=aes-cbc;spi-c=5;spi-s=6;port-c=7;port-s=8", "hmac-sha-1-96", {"aes-cbc"}); Check(noq && noq->selected == 0 && !noq->offerMatched, "no q, no match: first carrier"); // absent alg on the entry counts as the offered one - auto noalg = ParseSecurityServer("ipsec-3gpp;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", "aes-cbc"); + auto noalg = ParseSecurityServer("ipsec-3gpp;ealg=aes-cbc;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", {"aes-cbc"}); Check(noalg && noalg->offerMatched, "absent alg matches the offer"); // only non-ipsec mechanisms: nothing for us - Check(!ParseSecurityServer("tls;q=0.2,digest;d-alg=MD5", "hmac-sha-1-96", "aes-cbc").has_value(), "tls/digest only -> nullopt"); + Check(!ParseSecurityServer("tls;q=0.2,digest;d-alg=MD5", "hmac-sha-1-96", {"aes-cbc"}).has_value(), "tls/digest only -> nullopt"); // a quoted comma must not split the list; tokens are case-insensitive - auto q = ParseSecurityServer("digest;d-alg=MD5;d-qop=\"auth,auth-int\",IPSEC-3GPP; ALG=HMAC-SHA-1-96; EALG=AES-CBC; SPI-C=11; SPI-S=12; PORT-C=13; PORT-S=14", "HMAC-SHA-1-96", "AES-CBC"); + auto q = ParseSecurityServer("digest;d-alg=MD5;d-qop=\"auth,auth-int\",IPSEC-3GPP; ALG=HMAC-SHA-1-96; EALG=AES-CBC; SPI-C=11; SPI-S=12; PORT-C=13; PORT-S=14", "HMAC-SHA-1-96", {"AES-CBC"}); Check(q && q->mechanisms.size() == 2 && q->mechanisms[0].name == "digest", "quoted comma stays inside the digest mechanism"); Check(q && q->selected == 1 && q->offerMatched && q->Selected().name == "ipsec-3gpp" && q->Selected().alg == "hmac-sha-1-96" && q->Selected().ealg == "aes-cbc" && q->Selected().spiPs == 12u && q->Selected().portPs == 14, "case-insensitive names and values, lower-cased; offer compared case-insensitively"); // prot/mod parsed for the caller to refuse - auto tun = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;prot=ah;mod=tun;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", "aes-cbc"); + auto tun = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;prot=ah;mod=tun;spi-c=1;spi-s=2;port-c=3;port-s=4", "hmac-sha-1-96", {"aes-cbc"}); Check(tun && tun->Selected().prot == "ah" && tun->Selected().mod == "tun", "prot/mod parsed"); // spi-s beyond 32 bits, a port beyond 16 bits or zero: absent, not garbage - auto bad = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=4294967296;port-c=0;port-s=70000", "hmac-sha-1-96", "aes-cbc"); + auto bad = ParseSecurityServer("ipsec-3gpp;alg=hmac-sha-1-96;ealg=aes-cbc;spi-c=1;spi-s=4294967296;port-c=0;port-s=70000", "hmac-sha-1-96", {"aes-cbc"}); Check(bad && !bad->Selected().spiPs && !bad->Selected().portPs && !bad->Selected().portPc && bad->Selected().spiPc == 1u, "out-of-range spi-s/port-s and port 0 are absent"); // q syntax - auto q1 = ParseSecurityServer("ipsec-3gpp;q=1;spi-s=1", "hmac-sha-1-96", "null"); + auto q1 = ParseSecurityServer("ipsec-3gpp;q=1;spi-s=1", "hmac-sha-1-96", {"null"}); Check(q1 && q1->Selected().qMilli == 1000, "q=1 -> 1000"); - auto qx = ParseSecurityServer("ipsec-3gpp;q=x;spi-s=1", "hmac-sha-1-96", "null"); + auto qx = ParseSecurityServer("ipsec-3gpp;q=x;spi-s=1", "hmac-sha-1-96", {"null"}); Check(qx && !qx->Selected().qMilli, "q=x -> no q"); - Check(!ParseSecurityServer("", "hmac-sha-1-96", "null").has_value() && !ParseSecurityServer(" , ", "hmac-sha-1-96", "null").has_value(), "empty value -> nullopt"); + Check(!ParseSecurityServer("", "hmac-sha-1-96", {"null"}).has_value() && !ParseSecurityServer(" , ", "hmac-sha-1-96", {"null"}).has_value(), "empty value -> nullopt"); 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 e8f6c6f..ec2994e 100644 --- a/tests/Messages/main.cpp +++ b/tests/Messages/main.cpp @@ -8,7 +8,7 @@ // by the lines of one 180 and by its answers to an INVITE in long and in // compact form). A divergence here is a wire-format change, i.e. a // registration or call that the commercial IMS core may reject; these are the -// hardest pins in the project. Two deliberate post-parity divergences: +// hardest pins in the project. Three deliberate post-parity divergences: // the REGISTER Contact carries +sip.instance and the MMTEL ICSI feature tag // (the Python stack registered without them, which made the network divert // incoming calls to voicemail — see ContactFeatures in Imsd:Messages), and @@ -16,7 +16,16 @@ // TS 24.229 coding and what the stock modem sends on the wire; the Python // stack's plain-colon form is a different string under RFC 3841 matching // and left terminating access-domain selection routing incoming calls to -// CS fallback (observed live 2026-07-20). Then the SMS over IP shapes: the +// 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. 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. 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 // IP-SM-GW with In-Reply-To (TS 24.341 5.3.1.2, 5.3.2.4), and a final other @@ -68,7 +77,7 @@ namespace { "Authorization: Digest username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\", nonce=\"\", response=\"\"\r\n" "Require: sec-agree\r\n" "Proxy-Require: sec-agree\r\n" - "Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n" + "Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n" "Supported: sec-agree, path\r\n" "Expires: 600000\r\n" "P-Access-Network-Info: 3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=0010112340ABCDE0\r\n" @@ -88,7 +97,7 @@ namespace { "Authorization: Digest username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\", nonce=\"NONCEXYZ\", qop=auth, nc=00000001, cnonce=\"CNONCE0123456789\", response=\"RESP0000\", algorithm=AKAv1-MD5\r\n" "Require: sec-agree\r\n" "Proxy-Require: sec-agree\r\n" - "Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n" + "Security-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n" "Security-Verify: ipsec-3gpp; q=0.1; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=86438593; spi-s=86438592; port-c=33421; port-s=6000\r\n" "Supported: sec-agree, path\r\n" "Expires: 600000\r\n" @@ -187,7 +196,8 @@ namespace { int main() { Context c = MakeCtx(); - // ---- REGISTER (initial + protected), byte-exact vs Python + // ---- REGISTER (initial + protected), byte-exact (the header of this + // file has what differs from the Python stack's bytes) Eq(BuildRegisterInitial(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u), Reg1, "unprotected REGISTER"); @@ -205,13 +215,34 @@ int main() { { std::string auth = AuthAka(c, "NONCEXYZ", "CNONCE0123456789", "RESP0000"); std::string r3 = BuildRegisterProtected(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 3, 55555u, 66666u, auth, 45063); - Check(r3.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062\r\n"), "refresh Security-Client: new SPIs, a new client port, the same server port"); + Check(r3.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062\r\n"), "refresh Security-Client: new SPIs, a new client port, the same server port, in both mechanisms"); Check(r3.contains("\r\nCSeq: 3 REGISTER\r\n") && r3.contains("\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;") && r3.contains("@[2001:db8::db43]:45062>"), "refresh: CSeq+1, the server port in Via and Contact"); Check(r3.contains(std::format("\r\n{}\r\n", auth)), "refresh carries the last challenge answer verbatim"); std::string r3same = BuildRegisterProtected(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 3, 55555u, 66666u, auth); Check(r3same.contains("port-c=45061; port-s=45062\r\n"), "without a client port the in-use one is offered (the initial registration's second REGISTER)"); } + // ---- the offer: one mechanism per offered cipher, in the list's order, + // every one with the REGISTER's SPIs and ports + { + Check(c.ealgOffer == imsd::ipsec::DefaultEalgOffer(), "the default context offers the default list"); + Context one = c; + one.ealgOffer = {"aes-cbc"}; + Check(BuildRegisterInitial(one, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u).contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "one cipher offered: one mechanism, the header as it was before the default offer had two"); + Context two = c; + two.ealgOffer = {"aes-cbc", "null"}; + std::string r1 = BuildRegisterInitial(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u); + Check(r1.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "two ciphers offered: two mechanisms in one Security-Client"); + std::string auth = AuthAka(two, "NONCEXYZ", "CNONCE0123456789", "RESP0000"); + std::string r2 = BuildRegisterProtected(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth); + Check(r2.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "the protected REGISTER repeats the initial one's Security-Client (TS 33.203 Annex H)"); + std::string r3 = BuildRegisterProtected(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 3, 55555u, 66666u, auth, 45063); + Check(r3.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=aes-cbc; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=55555; spi-s=66666; port-c=45063; port-s=45062\r\n"), "a reregistration's new SPIs and client port in every mechanism"); + two.ealgOffer = {"null", "des-ede3-cbc"}; + std::string r4 = BuildRegisterInitial(two, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u); + Check(r4.contains("\r\nSecurity-Client: ipsec-3gpp; alg=hmac-sha-1-96; ealg=null; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062, ipsec-3gpp; alg=hmac-sha-1-96; ealg=des-ede3-cbc; spi-c=7449812; spi-s=176466735; port-c=45061; port-s=45062\r\n"), "the list's order is the header's order"); + } + // ---- protected-leg transport follows Context.transport (SIP_TRANSPORT=udp, // or the auto fallback): every protected request's Via says UDP, the // challenge's Via stays UDP either way, and TCP is the untouched default. @@ -227,6 +258,42 @@ int main() { Check(BuildRegisterProtected(c, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth).contains("\r\nVia: SIP/2.0/TCP [2001:db8::db43]:45062;"), "default transport stays TCP"); } + // ---- the REGISTERs of an identity an ISIM holds (imsd::aka::IsimIdentity): + // every name is the card's — the Request-URI the home domain's, From and + // To the public identity, the digest's username the private identity, + // its realm the home domain; the rest of the message is the one pinned + // above. + { + Context ci = c; + ci.id = *imsd::aka::IsimIdentity(c.id, "001010123456789@private.example.net", "one.example.net", "sip:001010123456789@one.example.net"); + std::string want1(Reg1); + auto swap = [](std::string& s, std::string_view from, std::string_view to) { + int n = 0; + for (std::size_t at = s.find(from); at != std::string::npos; at = s.find(from, at + to.size())) { s.replace(at, from.size(), to); n++; } + return n; + }; + Check(swap(want1, "REGISTER sip:ims.mnc001.mcc001.3gppnetwork.org SIP/2.0", "REGISTER sip:one.example.net SIP/2.0") == 1, "the pinned REGISTER has one Request-URI"); + Check(swap(want1, "", "") == 2, "the pinned REGISTER has the public identity in From and To"); + Check(swap(want1, "username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\"", + "username=\"001010123456789@private.example.net\", realm=\"one.example.net\", uri=\"sip:one.example.net\"") == 1, "the pinned REGISTER has one digest"); + Check(!want1.contains("3gppnetwork.org"), "no derived name is left in the expected REGISTER"); + Eq(BuildRegisterInitial(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u), want1, "unprotected REGISTER of an ISIM's identity"); + + std::string want2(Reg2); + swap(want2, "REGISTER sip:ims.mnc001.mcc001.3gppnetwork.org SIP/2.0", "REGISTER sip:one.example.net SIP/2.0"); + swap(want2, "", ""); + swap(want2, "username=\"001010123456789@ims.mnc001.mcc001.3gppnetwork.org\", realm=\"ims.mnc001.mcc001.3gppnetwork.org\", uri=\"sip:ims.mnc001.mcc001.3gppnetwork.org\"", + "username=\"001010123456789@private.example.net\", realm=\"one.example.net\", uri=\"sip:one.example.net\""); + Check(!want2.contains("3gppnetwork.org"), "no derived name is left in the expected protected REGISTER"); + std::string auth = AuthAka(ci, "NONCEXYZ", "CNONCE0123456789", "RESP0000"); + Eq(BuildRegisterProtected(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 2, 7449812u, 176466735u, auth), want2, "protected REGISTER of an ISIM's identity"); + // the Contact keeps the binding's own user-part: the IMSI here, as in + // the pinned message (an old state file's shape) + Check(BuildRegisterInitial(ci, "REGCALLID@2001:db8::db43", "FTAG5678", "REGBRANCH123456", 7449812u, 176466735u).contains("\r\nContact: "), "the Contact is not the public identity"); + // RuriFor with a home domain that is not a derived one + Eq(RuriFor("+31612345678", ci.id.domain), "sip:+31612345678@one.example.net;user=phone", "RuriFor puts a number at the domain it is given, an ISIM's here"); + } + // ---- RuriFor variants Eq(RuriFor("1233", c.id.domain), "sip:1233;phone-context=ims.mnc001.mcc001.3gppnetwork.org@ims.mnc001.mcc001.3gppnetwork.org;user=phone", "ruri short code"); Eq(RuriFor("+31612345678", c.id.domain), "sip:+31612345678@ims.mnc001.mcc001.3gppnetwork.org;user=phone", "ruri E.164"); @@ -359,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"); @@ -374,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 @@ -384,6 +457,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 { @@ -400,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 ------------ @@ -491,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" @@ -500,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 @@ -520,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; @@ -566,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" @@ -578,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 d4471a7..4d3784a 100644 --- a/tests/Sip/main.cpp +++ b/tests/Sip/main.cpp @@ -9,9 +9,12 @@ // with the Content-Length they read and the unfolding of a folded header // section (Unfolded) —, a request whose datagram ends before its body does // (CutShortRequest), a refused final's Retry-After and summary (RetryAfter, -// RefusalSummary), transaction matching (ResponseOf), our binding in a -// reg-event document (RegInfoContactState), and HeaderUri and Body. These pin -// the module's edge-case behavior; see the module header before "fixing" one. +// RefusalSummary), the interval a 422's Min-SE names (MinSe), transaction +// matching (ResponseOf), our binding in a +// 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; @@ -405,6 +408,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 = @@ -552,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 } diff --git a/tests/Util/main.cpp b/tests/Util/main.cpp index ae86762..15b1925 100644 --- a/tests/Util/main.cpp +++ b/tests/Util/main.cpp @@ -3,7 +3,7 @@ // Imsd:Util unit tests — MD5 against the RFC 1321 test suite, base64/hex // decoding, host/port formatting, the RFC 5952 canonical IPv6 text and the -// address-list parser, and the deterministic-seed RNG. MD5 and +// address-list parser, a setting's count of seconds, and the deterministic-seed RNG. MD5 and // base64 are our own (the standard library ships neither) and the AKAv1-MD5 // digest depends on them exactly, so these are pinned hard. import std; @@ -136,6 +136,16 @@ int main() { Check(ParseAddressList("2001:db8::1").size() == 1, "list: single entry, no rejected sink"); } + // ---- WholeSeconds: a setting that counts seconds (CRLF_KEEPALIVE=) + { + Check(WholeSeconds("30") == 30, "seconds: 30"); + Check(WholeSeconds("0") == 0, "seconds: 0"); + Check(WholeSeconds("0840") == 840, "seconds: leading zero"); + Check(WholeSeconds("9876543210") == 9876543210L, "seconds: every digit, past an int"); + for (std::string_view s : {"", " 30", "30 ", "30s", "-30", "+30", "30.5", "0x1e", "1e2", "nan", "inf", "thirty", "99999999999999999999"}) + Check(!WholeSeconds(s), std::format("seconds: '{}' is no count of seconds", s)); + } + if (Failures == 0) std::println("Util: 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 }