sip, engine: the retry of an INVITE refused 422

imsd asks for a session interval of 1800 s in a call's first INVITE. A
422 (Session Interval Too Small) is a server's answer to an interval
below its minimum and carries that minimum in a Min-SE (RFC 4028 6);
TS 24.229 5.1.2A.1.1 has a UE that supports RFC 4028 retry an INVITE so
refused in accordance with RFC 4028 7.4. imsd announces "timer" and
took a 422 for any other refusal: on a reporter's phone on AT&T's
network each of the five calls of one boot ended "INVITE final 422"
(AGENTS.md §13).

The call machine now sends the INVITE again in the same call: a new
transaction under the Call-ID, with the next sequence number, the 422's
Min-SE and a session interval no smaller. AGENTS.md §7.6 has when it
does not, and what becomes of an answer to an INVITE it has replaced.

Tested: the suites, and the daemon of this commit on the workstation
against a stand-in network that answers 422 (the fp6 journal's
2026-12-01-min-se-retry capture, bench/).
This commit is contained in:
Jorijn van der Graaf 2026-12-01 15:51:21 +01:00
commit 0026213073
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
6 changed files with 459 additions and 39 deletions

View file

@ -44,7 +44,7 @@ PipeWire. The verified device/carrier combinations are in the README.
| `project.cpp` | The canonical build description, for [Crafter Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build). Chooses the product by `--product=`. | | `project.cpp` | The canonical build description, for [Crafter Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build). Chooses the product by `--product=`. |
| `interfaces/Imsd.cppm` | The primary module interface of `imsd-core`: `export import`s the nine partitions below. | | `interfaces/Imsd.cppm` | The primary module interface of `imsd-core`: `export import`s the nine partitions below. |
| `interfaces/Imsd-Util.cppm` | `imsd::util` — SIP tokens, IPv6 host/port formatting, the RFC 5952 §4 IPv6 text (`CanonicalIp6`/`CanonicalAddr`; an IPv4-mapped address spelled in hex stays hex, where §5 and `inet_ntop` write it dotted) and the comma-separated address-list parser (`ParseAddressList`), the count of seconds a setting names (`WholeSeconds`), hex/base64, MD5 (RFC 1321), the fixed protected ports `PortUc`/`PortUs` (45061/45062). | | `interfaces/Imsd-Util.cppm` | `imsd::util` — SIP tokens, IPv6 host/port formatting, the RFC 5952 §4 IPv6 text (`CanonicalIp6`/`CanonicalAddr`; an IPv4-mapped address spelled in hex stays hex, where §5 and `inet_ntop` write it dotted) and the comma-separated address-list parser (`ParseAddressList`), the count of seconds a setting names (`WholeSeconds`), hex/base64, MD5 (RFC 1321), the fixed protected ports `PortUc`/`PortUs` (45061/45062). |
| `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `Unfolded`, by which the framers hand a message on with its folded header lines — 7.3.1 — joined; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number), `CutShortRequest`: the header section of a request — any but an ACK or a CANCEL — whose datagram has fewer body bytes than the Content-Length read from it says, which its 400 is built from. Not a full RFC 3261 parser, deliberately. | | `interfaces/Imsd-Sip.cppm` | `imsd::sip` — SIP as a text layer plus TCP framing: header extraction (from the header section only: a read ends at the first empty line after the start line, empty lines before it skipped; a header is asked for by its long name and found under that or its compact form — RFC 3261 7.3.3: the RFC's ten, and `o` for Event and `x` for Session-Expires — with or without white space before the colon; `Unfolded`, by which the framers hand a message on with its folded header lines — 7.3.1 — joined; `HeaderUri`: the party a header names; `Body`, moved here out of `CallMachine`), status codes, the granted lifetime, `MinSe` (the interval a `Min-SE` names), `ResponseOf` transaction matching (the Call-ID, and the CSeq as its number and its method, whatever spaces or tabs part them and whatever zeros stand before the number), `CutShortRequest`: the header section of a request — any but an ACK or a CANCEL — whose datagram has fewer body bytes than the Content-Length read from it says, which its 400 is built from. Not a full RFC 3261 parser, deliberately. |
| `interfaces/Imsd-Sdp.cppm` | `imsd::sdp` — SDP offer/answer: the AMR-WB + AMR + telephone-event offer (optional IR.92 preconditions; `OfferedTelephoneEventPt` names its telephone-event numbers), the parser the media plane needs (the codec, its payload type and mode, and the telephone-event payload type the m-line lists at that codec's clock), `BuildAnswer` for the terminating side, the `CODECS` override. | | `interfaces/Imsd-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-Sms.cppm` | `imsd::sms` — the short message codecs SMS over IP rides on (TS 24.341 carries the bytes a 2G/3G phone puts in an RP-DATA, in a SIP MESSAGE body): the GSM 7-bit default alphabet with its extension table and the septet packing, UCS-2 (TS 23.038); the SM-TL PDUs (TS 23.040: SMS-SUBMIT built, one per segment with the concatenation header when the text needs more than one; SMS-DELIVER, SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed; the SMS-DELIVER-REPORT that acknowledges a delivery; the user-data header — concatenation, application ports — and the `Reassembler` of a concatenated message); the SM-RL messages (TS 24.011: RP-DATA, RP-ACK, RP-ERROR in both directions, the cause values) and `RpCauseIsTemporary`, the causes of a submission after which imsd sends the segment again; EF_SMSP (TS 31.102 §4.2.27), where the (U)SIM names the service centre, and qmicli's hex dump of it. Byte-level only: no SIP, no clock, no I/O. |
| `interfaces/Imsd-Aka.cppm` | `imsd::aka` — the card's side of a registration: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response; since 1.2.3 the ISIM: the application of the slot in use out of the card status (`ParseIsimApp`, in whatever state the modem lists it), the SELECT and the two READ commands its identity files are read with, a card's answer (`ApduAnswer`: `90 00`, `91 XX` and `92 XX` are its normal endings; `HoldsRead` takes a read's data under `62 82` as well) and the command it asks for next (`ApduFollowUp`, for an answer without data: GET RESPONSE for `61 XX`, a command without data again for `6C XX`), the value a file holds (`ParseIsimValue`: the data object with tag `80`, the `FF` bytes at the end of its length cut, no blank and no byte outside printable ASCII) and `IsimIdentity`, the check of the three values — an `@` between two parts, a domain of labels of letters, digits and inner hyphens, 63 characters a label and 253 in all at most, a `sip:` at the start and more after it, the two identities 255 characters at most, no blank, no byte outside printable ASCII and no `"`, `\`, `<` or `>` — before they replace the derived names. | | `interfaces/Imsd-Aka.cppm` | `imsd::aka` — the card's side of a registration: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response; since 1.2.3 the ISIM: the application of the slot in use out of the card status (`ParseIsimApp`, in whatever state the modem lists it), the SELECT and the two READ commands its identity files are read with, a card's answer (`ApduAnswer`: `90 00`, `91 XX` and `92 XX` are its normal endings; `HoldsRead` takes a read's data under `62 82` as well) and the command it asks for next (`ApduFollowUp`, for an answer without data: GET RESPONSE for `61 XX`, a command without data again for `6C XX`), the value a file holds (`ParseIsimValue`: the data object with tag `80`, the `FF` bytes at the end of its length cut, no blank and no byte outside printable ASCII) and `IsimIdentity`, the check of the three values — an `@` between two parts, a domain of labels of letters, digits and inner hyphens, 63 characters a label and 253 in all at most, a `sip:` at the start and more after it, the two identities 255 characters at most, no blank, no byte outside printable ASCII and no `"`, `\`, `<` or `>` — before they replace the derived names. |
@ -168,7 +168,7 @@ answers' reading, the follow-up, the value of a file and the check of the
identity are `Imsd:Aka`'s, with tests; the shell's part ran against 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 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 before any response to its INVITE (1.2.4, §7.6) has its decisions in
`CallMachine`, with tests: which attempt is sent again, with which bytes, `CallMachine`, with tests: which INVITE is sent again, with which bytes,
and when the call ends instead. The shell's part (`MaybeResendInvite`: the dead flow closed 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 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 old registration may be reconnected over) ran against a stand-in network on
@ -410,7 +410,9 @@ What the suites pin:
zeros before its number: the zeros before its number: the
transaction's; another number, another method, a method in other letter transaction's; another number, another method, a method in other letter
case, a CSeq without one of the two: not), refused finals with reason 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 reginfo documents, `HeaderUri` and `Body`. A change that flips one of
those tests is a behaviour change, not a cleanup. those tests is a behaviour change, not a cleanup.
- `Sdp` — the offer's exact bytes, the parser (the telephone-event payload - `Sdp` — the offer's exact bytes, the parser (the telephone-event payload
@ -442,9 +444,22 @@ What the suites pin:
(reliable 18x/PRACK, 2xx ACK + media start, far-end hangup, CANCEL/answer (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, 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 G.711-only and AMR-NB gateway offers, ring timeout, BYE both ways, the
emergency chain, an attempt's INVITE with no response and no CANCEL yet emergency chain, an INVITE refused 422 sent again in the same call (the
sent again over a flow the shell reopened, byte for byte and once per Call-ID, the From and the To kept, the number after the refused
attempt, and its call ended where the flow is lost (an emergency call's 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 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 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 call, without the negotiation, for a character that is no tone or for a
@ -1982,12 +1997,14 @@ sent, emit this D-Bus state change, arm this deadline). States and reasons are t
- Outgoing: INVITE with the SDP offer (AMR-WB + AMR + telephone-event by - Outgoing: INVITE with the SDP offer (AMR-WB + AMR + telephone-event by
default; `CODECS` restricts and orders; `PRECOND=1` adds IR.92 default; `CODECS` restricts and orders; `PRECOND=1` adds IR.92
preconditions), reliable 18x with PRACK, 2xx ACK and media start, CANCEL preconditions), reliable 18x with PRACK, 2xx ACK and media start, CANCEL
before answer, BYE after. Busy and error finals end the call with before answer, BYE after. Busy and error finals end the call, unless
`refused-or-busy` or `error`. Where the client flow is found dead after 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 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 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 FIN's exchange, reopens the flow with one connect and the same INVITE
goes out again, once per attempt of the emergency chain, the setup goes out again, once for each INVITE a call sends (an attempt of the
emergency chain's, or one sent again for a 422, below), the setup
deadline running from then (`MaybeResendInvite`). No REGISTER goes deadline running from then (`MaybeResendInvite`). No REGISTER goes
first: the registration and its SAs stand (where a reg-event NOTIFY has 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 ended the binding, §7.4, nothing is reopened), and TS 33.203 7.1 has a
@ -2054,6 +2071,33 @@ sent, emit this D-Bus state change, arm this deadline). States and reasons are t
a plain INVITE answered `380 Alternative Service` with an emergency body is a plain INVITE answered `380 Alternative Service` with an emergency body is
re-attempted as `urn:service:sos`. An attempt whose client flow is lost re-attempted as `urn:service:sos`. An attempt whose client flow is lost
(above) ends the call there: no fallback follows it. (above) ends the call there: no fallback follows it.
- Session timer (RFC 4028): the first INVITE of a dialog announces
`timer` and asks for a session interval of 1800 s with `refresher=uac`
and a `Min-SE` of 90. The shell hands a call every response on the
client flow to an INVITE under its Call-ID; of a call imsd places the
machine takes those whose sequence number is its current INVITE's
(`ResponseOf`) and drops the others. Where the current INVITE awaits
its final (no CANCEL of it out, no answer taken) and is answered `422`
with a `Min-SE` (what `imsd::sip::MinSe` reads of it: a number of up to
nine digits, zeros before it aside) above the one it carried, the
INVITE goes out again in the same call (TS 24.229 5.1.2A.1.1; RFC 4028
7.3, 7.4), at most three times under one Call-ID (`MinSeAgainMax`,
imsd's own bound): the Call-ID, the From with its tag and the To as
they were, a new branch and the 422's `Min-SE` as its `Min-SE`
(`CallMachine::AgainWithMinSe`). The session interval it asks for is
the one asked for before, or that `Min-SE` where the interval was
smaller. Its sequence number is the next the Call-ID has not carried:
RFC 4028 7.3 has "one higher than the previous", which imsd takes as
the one after the refused INVITE's; where a PRACK followed that INVITE
imsd takes the one after the last PRACK's instead. The setup deadline
runs anew from each INVITE. Any other 422 to the current INVITE is a
refusal like any other, to a call and to an attempt of the emergency
chain, whose fallback is a new dialog and starts at 1800 and 90 again.
What answers an INVITE the call has replaced is dropped with the
others: its 422 coming a second time is not acknowledged again. In a
call it places imsd asks to be the refresher and sends no session
refresh of its own (the call machine sends no UPDATE and no re-INVITE;
one from the far side is answered).
- DTMF (`SendDtmf`): the tones go out as RFC 4733 telephone-event packets - 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 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 codec's clock (`MediaLeg::dtmfPt`: the answer's for an outgoing call, the
@ -2246,6 +2290,11 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `:
- `call X: the client flow died before any response to the INVITE; reopening it` and, when the connect - `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 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. died before any response to the INVITE` where the call ends instead.
- `call X: INVITE final 422, Min-SE N — the INVITE again with Session-Expires S` when an INVITE goes out again
for a 422 (§7.6). A 422 that is a refusal like any other has what was read of it in the line it leaves, as
`INVITE final 422, Min-SE N` or `INVITE final 422, no Min-SE read`: the call's `ended:` line, or an
emergency attempt's `— retrying as plain INVITE of the digits`. In each of the three a `Reason` header of
the 422 follows the `Min-SE` part (`…, Reason: …`).
- `sleep is held off while the call lasts (logind's inhibitor)` when the - `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 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 (no call)` when that lock is released, the table's last call gone
@ -3642,7 +3691,7 @@ the related code.
Service-Route, with a `tel:` P-Associated-URI and a `sip:` one at 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 `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 the hour. Each of the five calls placed in that boot ended `INVITE
final 422`. final 422` (§7.6).
- **A folded `WWW-Authenticate`** — the 401 to the unprotected REGISTER - **A folded `WWW-Authenticate`** — the 401 to the unprotected REGISTER
came with its `WWW-Authenticate` over four lines on KPN (2026-07-18) 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 and on Odido (2026-07-13), the nonce on the second (RFC 3261 7.3.1; one

View file

@ -2957,8 +2957,9 @@ private:
} }
// A client flow found dead under an outgoing call whose INVITE has had // A client flow found dead under an outgoing call whose INVITE has had
// no response and no CANCEL (CallMachine::Unanswered) is reopened once // no response and no CANCEL (CallMachine::Unanswered) is reopened, once
// per attempt and the INVITE sent again: a flow the network had // 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 // 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 // call's. No REGISTER goes first: the registration and its SAs stand
// (not where the network has ended the binding: RegRecovery's // (not where the network has ended the binding: RegRecovery's

View file

@ -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 finals, CANCEL/answer races, remote BYE, media-plane far-end-hangup, the
emergency attempt chain (urn:service:sos first for a classified number, one 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 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 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 DTMF, which reaches the media leg only on an active call whose SDP
negotiated telephone-event, as the tones a keypad has — negotiated telephone-event, as the tones a keypad has —
@ -417,6 +418,10 @@ export namespace imsd::engine {
// imsd.py INVITE_TIMEOUT / CANCEL_487_TIMEOUT constants. // imsd.py INVITE_TIMEOUT / CANCEL_487_TIMEOUT constants.
inline constexpr double InviteTimeout = 90.0; inline constexpr double InviteTimeout = 90.0;
inline constexpr double Cancel487Timeout = 10.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 // How long an unanswered incoming call may ring before we 480 it — a
// safety net behind the network's own CANCEL, so generous. // safety net behind the network's own CANCEL, so generous.
inline constexpr double IncomingRingTimeout = 120.0; inline constexpr double IncomingRingTimeout = 120.0;
@ -494,22 +499,23 @@ export namespace imsd::engine {
return a; return a;
} }
// The current outgoing attempt has sent its INVITE and has had no // An outgoing call's current INVITE has been sent and has had no
// response to it, not a 100 either, and no CANCEL has followed it. // 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 // 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 // flow the network had forgotten is reset at the first bytes sent
// on it, and those may be this INVITE. // on it, and those may be this INVITE.
bool Unanswered() const { bool Unanswered() const {
return state_ == CallState::Dialing && !inviteOut_.empty() && !answered_ && !cancelled_; return state_ == CallState::Dialing && !inviteOut_.empty() && !answered_ && !cancelled_;
} }
// … and the attempt has not been sent again yet. // … and that INVITE has not gone out a second time over a reopened
// flow.
bool ResendDue() const { return Unanswered() && !resent_; } bool ResendDue() const { return Unanswered() && !resent_; }
// The shell reopened the flow under an attempt whose resend is due: // The shell reopened the flow under an INVITE whose resend is due:
// the same INVITE again, byte for byte (the same branch: RFC 3261 // 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 // 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 // its transaction), and the setup deadline from now. Once per
// attempt. // INVITE: one that AgainWithMinSe sends has a resend of its own.
std::vector<Action> OnFlowReopened() { std::vector<Action> OnFlowReopened() {
std::vector<Action> a; std::vector<Action> a;
if (!ResendDue()) return a; if (!ResendDue()) return a;
@ -520,7 +526,7 @@ export namespace imsd::engine {
return a; return a;
} }
// The flow under an unanswered attempt is dead and stays so (it // The flow under an unanswered INVITE is dead and stays so (it
// could not be reopened, or died again after the resend): the call // could not be reopened, or died again after the resend): the call
// ends here, an emergency call's first attempt too, with nothing to // ends here, an emergency call's first attempt too, with nothing to
// send a CANCEL on and no flow for a fallback attempt. // send a CANCEL on and no flow for a fallback attempt.
@ -597,11 +603,17 @@ export namespace imsd::engine {
return a; 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<Action> OnInviteResponse(std::string_view msg) { std::vector<Action> OnInviteResponse(std::string_view msg) {
std::vector<Action> a; std::vector<Action> a;
if (direction_ == Direction::Incoming) if (direction_ == Direction::Incoming)
return a; // a UAS has no INVITE transaction of its own 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); AbsorbDialog(msg);
auto st = imsd::sip::Status(msg); auto st = imsd::sip::Status(msg);
if (!st) return a; if (!st) return a;
@ -650,7 +662,24 @@ export namespace imsd::engine {
} }
// non-2xx final // non-2xx final
a.push_back(Send(imsd::msg::BuildAckNon2xx(ctx_, d_, std::string(imsd::sip::Header(msg, "To").value_or(""))))); 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)) { if (auto sos = FallbackTo(code, msg)) {
Append(a, Retry(*sos, fin)); Append(a, Retry(*sos, fin));
return a; return a;
@ -868,12 +897,13 @@ export namespace imsd::engine {
bool sosTried_ = false; bool sosTried_ = false;
bool plainTried_ = false; bool plainTried_ = false;
bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline bool userCancelled_ = false; // CANCEL came from OnHangup, not a deadline
// The current outgoing attempt's INVITE as sent, whether any response // The current INVITE as sent, whether any response to it has come,
// to it has come, and whether it went out a second time over a // and whether it went out a second time over a reopened flow
// reopened flow (OnFlowReopened). // (OnFlowReopened).
std::string inviteOut_; std::string inviteOut_;
bool answered_ = false; bool answered_ = false;
bool resent_ = false; bool resent_ = false;
int minSeAgain_ = 0; // INVITEs sent again for a 422 under this Call-ID
std::set<std::string> pracked_; std::set<std::string> pracked_;
std::string answerSdp_; std::string answerSdp_;
std::optional<int> dtmfPt_; // the running leg's telephone-event pt, set at media start std::optional<int> dtmfPt_; // the running leg's telephone-event pt, set at media start
@ -889,23 +919,65 @@ export namespace imsd::engine {
d_.callid = std::format("{}@{}", rng_.Token(20), ctx_.local); d_.callid = std::format("{}@{}", rng_.Token(20), ctx_.local);
d_.itag = rng_.Token(10); d_.itag = rng_.Token(10);
d_.invBranch = rng_.Token(20); d_.invBranch = rng_.Token(20);
nextCseq_ = 2; NewTransaction();
pracked_.clear();
answerSdp_.clear();
cancelled_ = false; cancelled_ = false;
userCancelled_ = 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; answered_ = false;
resent_ = 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<Action> 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<Action> 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) // The emergency fallback chain — where the next attempt (if any)
// points. `msg` may be empty (deadline paths). // points. `msg` may be empty (deadline paths).
// - a sos INVITE that fails for any reason other than the user // - asked after a sos attempt, it answers the dialled digits as a
// hanging up, its own send failing at the Dial (Fail) or the // plain INVITE, unless the user hung up or the digits were tried
// client flow lost under it (OnFlowLost: there is nothing to send // before that attempt (the 380's upgrade below): the
// on) is re-attempted as a plain INVITE of the dialled digits: the
// pre-emergency-support behavior, so classification can only improve // pre-emergency-support behavior, so classification can only improve
// on the status quo, never block a call the old code would have placed. // 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 // - a plain INVITE answered 380 Alternative Service whose body
// names emergency (TS 24.229 5.1.6: the network classified a // 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 // number we didn't) is re-attempted as urn:service:sos. A 380

View file

@ -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 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, whole messages as strings and pulls out exactly what it needs (headers,
status codes, the granted registration lifetime), which keeps every message status codes, the granted registration lifetime, the interval a Min-SE
loggable and testable as text. A header is asked for by its long name and 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 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, (empty header values, line anchoring, white space before the colon,
keepalive discards) is pinned by tests/Sip — a change that flips one of keepalive discards) is pinned by tests/Sip — a change that flips one of
@ -228,6 +228,18 @@ export namespace imsd::sip {
return LeadingDigits(*v); 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<int> 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<int>(*n);
}
// A refused final for the journal: its status line, then the headers // 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), // 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 // Warning (20.43: the node's own words), Reason (RFC 3326), Server

View file

@ -4,7 +4,9 @@
// Imsd:Engine unit tests — the call state machine driven through recorded // Imsd:Engine unit tests — the call state machine driven through recorded
// network dialogs. Outgoing: reliable-18x PRACK, 2xx ACK + media start, // network dialogs. Outgoing: reliable-18x PRACK, 2xx ACK + media start,
// media-plane far-end hangup, local hang-up (CANCEL before answer, BYE // 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 // on the INVITE (reliable when the caller requires 100rel), Accept -> 200
// with the SDP answer at the offer's payload types + media, ACK silence, // with the SDP answer at the offer's payload types + media, ACK silence,
// reject -> 486, remote CANCEL -> 200+487, unusable offer -> 488 (naming // reject -> 486, remote CANCEL -> 200+487, unusable offer -> 488 (naming
@ -96,8 +98,9 @@ namespace {
return nullptr; return nullptr;
} }
// Build a response with the machine's own Call-ID (so dialog matching in a // Build a response with the machine's own Call-ID and its INVITE's first
// real shell would hold; the reducer itself doesn't re-check). // 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) { std::string R183(std::string_view callid) {
return std::format( return std::format(
"SIP/2.0 183 Session Progress\r\n" "SIP/2.0 183 Session Progress\r\n"
@ -154,6 +157,30 @@ namespace {
code, text, callid); 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: <sip:001010123456789@ims.mnc001.mcc001.3gppnetwork.org>;tag=it\r\n"
"To: <sip:1233@ims>;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<Action>& 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`. // First SendResponse whose text starts with `prefix`.
const Action* Responded(const std::vector<Action>& a, std::string_view prefix) { const Action* Responded(const std::vector<Action>& a, std::string_view prefix) {
for (const auto& x : a) for (const auto& x : a)
@ -473,7 +500,7 @@ int main() {
} }
// ---- the client flow dies before any response to the INVITE: the shell // ---- the client flow dies before any response to the INVITE: the shell
// reopens it and the same INVITE goes out again, once per attempt // reopens it and the same INVITE goes out again, once per INVITE
{ {
imsd::util::Rng rng(16); imsd::util::Rng rng(16);
CallMachine m(c, rng, "ims-call-6b", "1233", 50004, false); CallMachine m(c, rng, "ims-call-6b", "1233", 50004, false);
@ -487,7 +514,7 @@ int main() {
const Action* dl = Find(again, Action::Type::SetDeadline); const Action* dl = Find(again, Action::Type::SetDeadline);
Check(dl && dl->seconds == imsd::engine::InviteTimeout, "the resend arms the setup deadline anew"); 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.State() == CallState::Dialing && !m.Terminated(), "still dialing after the resend");
Check(m.Unanswered() && !m.ResendDue(), "one resend per attempt"); Check(m.Unanswered() && !m.ResendDue(), "one resend per INVITE");
Check(m.OnFlowReopened().empty(), "a second reopen sends nothing"); Check(m.OnFlowReopened().empty(), "a second reopen sends nothing");
auto lost = m.OnFlowLost(); auto lost = m.OnFlowLost();
const Action* t = Find(lost, Action::Type::State); const Action* t = Find(lost, Action::Type::State);
@ -969,6 +996,248 @@ int main() {
Check(m.Terminated(), "terminated when the chain is exhausted"); 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: <sip:1233@ims>;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: <sip:1233@ims>;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: <sip:[2001:db8::bad]:6000;lr>\r\nContact: <sip:refuser@[2001:db8::bad]:5060>\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 // ---- user hangup during the sos attempt kills the chain: 487 ends it
{ {
imsd::util::Rng rng(47); imsd::util::Rng rng(47);

View file

@ -9,7 +9,8 @@
// with the Content-Length they read and the unfolding of a folded header // with the Content-Length they read and the unfolding of a folded header
// section (Unfolded) —, a request whose datagram ends before its body does // section (Unfolded) —, a request whose datagram ends before its body does
// (CutShortRequest), a refused final's Retry-After and summary (RetryAfter, // (CutShortRequest), a refused final's Retry-After and summary (RetryAfter,
// RefusalSummary), transaction matching (ResponseOf), our binding in a // RefusalSummary), the interval a 422's Min-SE names (MinSe), transaction
// matching (ResponseOf), our binding in a
// reg-event document (RegInfoContactState), and HeaderUri and Body. These pin // reg-event document (RegInfoContactState), and HeaderUri and Body. These pin
// the module's edge-case behavior; see the module header before "fixing" one. // the module's edge-case behavior; see the module header before "fixing" one.
import std; import std;
@ -405,6 +406,22 @@ int main() {
Check(CutShortRequest("MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP\r\n [2001:db8::2]:6000\r\nContent-Length:\r\n\t9\r\n\r\nhello") == "MESSAGE sip:a@example.net SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::2]:6000\r\nContent-Length: 9\r\n\r\n", "a request cut short of a folded Content-Length: its header section unfolded, for the 400"); 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) // ---- RetryAfter / RefusalSummary (what a refused final is logged as)
{ {
std::string r503 = std::string r503 =