Compare commits

..
Author SHA1 Message Date
c3b7d01d43
imsd 1.2.7
All checks were successful
package / package (push) Successful in 2m8s
2026-12-04 23:20:38 +01:00
a65724a252
messages, imsd: P-Access-Network-Info in responses and in requests within a dialog
imsd named the serving cell in its REGISTERs, the reg-event SUBSCRIBE,
an INVITE and a MESSAGE. TS 24.229 5.1.2A.1.1 and 5.1.2A.2 have a UE
insert the header into a request within a dialog as well, and into a
response within a dialog, to a request for a dialog and to a standalone
method: not into a CANCEL nor into a response to one, and into an ACK
at its choice. A PRACK and a BYE carry it now, and every response imsd
builds but a 100 Trying, the 200 to a CANCEL and the transport's 400 to
a request cut short.

The server ports (the protected ports' TCP listeners and UDP sockets)
take a request from any source (AGENTS.md §12), and the header is the
phone's cell. What they send in answer keeps it only on the two paths
of the SA pair the shell has on record, and loses it anywhere else.

Tested: the suites, and the daemon of this commit on the workstation
against a stand-in network that asks it from both sides of those paths
(the fp6 journal's 2026-12-04-pani-in-dialog capture, bench/), and on
the dev phone on KPN, where its answers to a text's two requests and a
call's 180 and 200 carried the header inside the SA pair (the
journal's 2026-12-04-imsd-1.2.7-range-on-dev-phone capture).
2026-12-04 23:20:38 +01:00
6d05aaed0d
imsd: a server port's answer finds its connection or socket when it is sent
A request that came in on a server port (the protected ports' TCP
listeners and UDP sockets) was answered through a closure that kept a
descriptor's number: its connection's over TCP, a socket's over UDP.
The daemon closes a connection's descriptor when the peer has ended
the connection, and the kernel gives a closed descriptor's number out
again. A call's later answers go through the closure of the call's
latest request when the user answers or refuses or the ringing ends
(the 200 of an Accept, a 486, a 480): they were written to that
number, whatever had it by then, the connection of whoever had
connected since among them.

A closure now keeps the port its request came in on and the peer it
came from, or which of the two UDP ports its answer leaves by. Over
TCP an answer is written to the newest connection the daemon holds
from that peer to that port, and is not sent where it holds none: the
journal says so once in a run. Over UDP it leaves from the socket its
port has at that moment, if it has one.

Tested: the daemon of this commit on the workstation against a
stand-in network that closes the connection its INVITE came on while
the call rings and then connects from another host, from another
port, from the same port to the daemon's other port or from the same
port to the same one, and one that resets the connection right behind
its INVITE and makes it again (the fp6 journal's
2026-12-04-pani-in-dialog capture, bench/); and on the dev phone on
KPN, where it answered a call that came in and the two requests that a
text to the phone's own number brings (the journal's
2026-12-04-imsd-1.2.7-range-on-dev-phone capture).
2026-12-04 23:20:38 +01:00
1eee41f0ed
imsd 1.2.6
All checks were successful
package / package (push) Successful in 2m14s
2026-12-01 15:51:21 +01:00
0026213073
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/).
2026-12-01 15:51:21 +01:00
3d702ec1f1
messages, engine: the INVITE's sequence number, session interval and Min-SE are the dialog's
BuildInvite wrote "CSeq: 1 INVITE", "Session-Expires:
1800;refresher=uac" and "Min-SE: 90" as fixed text, and the INVITE's
CANCEL, its two ACKs and a PRACK's RAck wrote the 1 again. The three
values are fields of the Dialog now, with those defaults, and nothing
in the daemon sets them otherwise yet: every message it sends is byte
for byte what it was.

Tested: the suites (tests/Messages has an INVITE, its CANCEL and its
ACKs for a dialog with other values).
2026-12-01 15:51:21 +01:00
e3b94a8415
AGENTS.md, imsd: an ISIM's identity has registered on a network
AGENTS.md §5 said that this daemon had sent no network a REGISTER with
names it read from an ISIM and no real ISIM an AUTHENTICATE, §13 that it
had not sent the US card's network the card's own names, and a comment
of the shell that no AKA in a real ISIM had run on this code. A
reporter's journal of 2026-11-25 has imsd read that card's ISIM and
register under its names on AT&T's network, without the line an
application that gives no result for the challenge leaves (imsd 1.2.4 by
the reporter's word; the fp6 journal's 2026-12-01-min-se-retry capture,
evidence/). §13 has what the journal shows.
2026-12-01 14:22:05 +01:00
640d261248
imsd 1.2.5
All checks were successful
package / package (push) Successful in 1m57s
2026-11-29 14:30:43 +01:00
3b9c0fed98
imsd, engine: the registration through a sleep
The refresh of the registration was due after so many awake seconds: its
gate ran on the steady clock, which stands still in a suspend, while the
network counts the registration's lifetime on. A phone that slept most
of two hours sent no refresh and lost its registration (the dev phone,
KPN, 1.1.0, 2026-11-19: registered 09:15:48 for 7200 s, the network's
NOTIFY of the expiry at 11:16:37, registered again 11:37:38 behind the
fresh-SA throttle). Until now the image imsd was written on did not let
its phone suspend.

The refresh's gate and the renewal of the reg-event subscription ahead
of its granted lifetime's end now run on the boot clock, as the recovery
policy's waits already did. And a timer on CLOCK_BOOTTIME_ALARM, which
the kernel turns into the RTC's alarm for a suspend, is armed at the end
of every turn of the loop that takes no command off the queue (one that
takes a command handles it and goes straight to the next turn) for the
time the new WakeAt names (Imsd:Engine): now while a call or a text is
in flight (the hold below); else, with a registration on a live flow,
the refresh's due time, or the subscription's renewal where that comes
first; with a dead flow under a registration the recovery policy's word;
none where nothing waits to be done. 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. A resume by itself sends nothing. Where the kernel gives no
such timer (it takes CAP_WAKE_ALARM) or has no RTC behind it, the
journal says so once.

What imsd waits for with the phone awake must not be cut off by a
suspend either. Beside the call's lock the main thread asks for a second
block inhibitor, in the way it asks for the call's, while a step of the
registration exchanges with the network (the refresh, a reconnect, a
fresh registration, the bring-up) and while a text is being sent, whose
waits (128 s for a MESSAGE's final, 130 s for the report) count awake
seconds; not while a bring-up waits out a hold the network set, which
can be an hour. A step can begin before the bus connection is there: its
lock, like a call's, is asked for when the connection comes. For a
suspend that begins all the same (logind refused such a lock where a
suspend's operation was already running; 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, 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 (alarmtimer_suspend, read at v7.3) where the
suspend comes to that check before the alarm has fired: it syncs and
freezes the processes first. A registration step keeps it at most 30 s
ahead while it waits for the network, whatever else is in flight, so
that a sleep that begins under the step ends there. The alarm fires
once, and a wait can outlast the sleep it ended: it is set anew before
every second of such a wait (a connect's answer, the pause before the
next try, a REGISTER's answer). One of those waits is a receive with a
timeout (the fresh registration's first answer, on a socket of its own),
which the kernel ends with EINTR when a suspend freezes the thread: it
is taken up again for the rest of its time. The connect for a call's
resend is no step and sets the 1.9 s anew the same way, before every
second. A wait for a helper program keeps the alarm that stood when it
began.

A coverage gap must not cost the phone its sleep. The recovery tried a
reconnect 5 s after each one that failed, over TCP 34 s of waiting for
an answer that cannot come: with a lock around the step and an alarm for
the next, a phone in a cellar would have been held awake 34 s of every
39. While the modem reports no packet service the recovery tries nothing
now and takes no lock, and a dead flow's socket that is still open then
is closed 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 a FIN sent into the gap would hold the address pair against the
reconnect after it, as the FIN of a step that closed its flow after an
unanswered wait does. A Dial that finds the flow dead in a gap ends at
once: the recovery's one 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, the pause that was between two
reconnects. 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 (RegRecovery::WakeTime), counted from the modem's first
word of no service since the network last answered: 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 while the
looks keep their pace. Every step that follows no local wait is woken
for at the policy's own time: 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. 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.

Left as they were, among others: the CRLF keepalive, the reg-event
subscription's Timer F, its retries and its renewal after the network
has ended it, the times SMS over IP measures (its two waits, the
30-minute age-out, its tables) and a step's own waits for the network
count awake seconds. Nothing holds a sleep off under the bring-up
script, which runs before the daemon, nor in the wait before a restart
after a failure: a phone suspended there does not register until it is
awake again. And between the alarm's waking the phone and the step it
woke it for, the loop's next turn, there is neither alarm nor lock; nor
is the alarm set again yet, for up to a second, after it has ended a
sleep under a step's wait (where the freeze has ended the receive of the
fresh registration's first wait with time left, it is set at once), and
a helper program the step goes on to in that second has none until the
step's next wait for the network.

Tested: the suites (WakeAt and the policy's wake after a local wait are
pinned in tests/Engine; the rest is the shell's). On the workstation
(the fp6 journal's 2026-11-25-through-sleep capture,
bench/bench-sleep.sh) the sleep is a preloaded clock_gettime under which
the boot clock runs ahead of the steady clock: with it 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 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 for the 256 s from a text's
sending to its "failed" where the stand-in network answered no MESSAGE.
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 daemon's own processor time stayed under a second (an
earlier build of this change, 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, the reconnect then 0.5 to 1.5 s after the gap's end; and in a
gap that let no segment through the daemon had no socket of the old flow
at the gap's end; 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;
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, and over UDP, it 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, a connect's 12 s and the 10 s before the
next try, a fresh registration's two waits with the stand-in holding its
answers back) it named a new time every second, and through the connect
for a call's resend, which the stand-in answered at once, 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 freeze does), the daemon registered when
the stand-in's held-back 401 came, five runs of five; an earlier build
of this change 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 daemon
built with the next commit's version string, the capture's phone/,
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); under a call a
suspend told to ignore inhibitors was refused by the kernel (alarmtimer,
-16), twice, systemd-sleep having tried its second state; under a text
in flight logind refused a suspend and the kernel a forced one; and
under a refresh whose REGISTER the phone itself dropped, a forced
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 of this change, which set the alarm once
for the wait, read zero at every reading until the wait had ended; in
another run, with two more forced 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). Seven recovery
steps that fell due under a sleep ran 1.5 to 3 s after their time (an
earlier build, 2026-11-25). A test program's datagram receive under a
timeout returned EINTR at the phone's resume from a suspend
(evidence/recv-eintr/ there). Not run: a suspend under a fresh
registration's first wait with the daemon on a phone; 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 forced suspend under one wait with this commit's 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; 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 subscription's renewal on a
network.
2026-11-29 14:30:43 +01:00
52d4b4f217
imsd: logind's block inhibitor for sleep while a call is in the calls table
Nothing of imsd runs while the phone is suspended: 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.

While the calls table holds a call the main thread holds logind's block
inhibitor for sleep (Inhibit with "sleep", "imsd", "a call", "block"):
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
and the refresh of the P-Access-Network-Info, to its removal. Under it
logind refused a plain "systemctl suspend" on the dev phone (below); a
request can tell logind to ignore inhibitors (systemctl suspend -i). The
engine starts before the bus connection is there: a lock wanted by then
is asked for when the connection comes.

On the dev phone (systemd 262.2) logind answered Inhibit for this lock
OperationInProgress in a sleep hook before a suspend, in one after it,
and to imsd 0.1 to 0.3 s after the resume, and gave it once it had
logged the operation's "finished". So a lock that was not given and is
still wanted is asked for again when logind sends PrepareForSleep with
false. Where logind gives none at all (the session bus of --session has
no logind) calls go on without one, and the journal says so once until a
call's lock is next given.

Tested: the suites (none reaches the change, which is the main
thread's). On the workstation the daemon of this commit and 1.2.4's ran
with a stand-in logind that 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, the daemon of this commit, the sleep targets
unmasked for the test; the capture's phone/), under a call to the
carrier's voicemail: the lock in systemd-inhibit's list, "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; the
lock wanted where it is held, which asks nothing (a suspend told to
ignore inhibitors under it; a Dial refused under a call that has it); a
desktop's own request for a suspend under the lock.
2026-11-29 14:30:43 +01:00
83a9eb539d
imsd: a re-REGISTER that was sent has used its CSeq, answered or not
A re-REGISTER on the registration's Call-ID (the refresh, a reconnect's,
a resume's) was given the number after the last one that was answered
200: the number was recorded when the 200 came, and only then. So the
REGISTER after one that got no answer, or a refusal, carried that one's
number again. RFC 3261 10.2 has a UA increment the CSeq by one for each
REGISTER with the same Call-ID, and a registrar that took the unanswered
one, its answer lost on the way, has no use for the number a second time
(10.3 step 7: it aborts the update unless the CSeq is higher than the
one it stored).

On the dev phone (KPN, 2026-11-25, a test build with 1.2.4's code at
this place; the fp6 journal's 2026-11-25-refresh-answer-lost capture) a
refresh got no reply: the phone's firewall dropped the network's packets
for 20 s in a test. The reconnect's re-REGISTER, 10 s after the refresh
had failed, was refused "482 Loop Detected", and so was the next one
that reached the network, 66 s later. The recovery then began a fresh
registration and deferred it at a Security-Server with spi-s=0
("fresh-SA throttle active"); the next two re-REGISTERs that reached the
network were answered "480 Temporarily Unavailable" with a Retry-After
of 180, and the phone registered again 25 min 55 s after the refresh had
failed. The journal does not print the number of a REGISTER that fails:
that the two refused with 482 carried the unanswered one's is read from
the code.

The number is now used once the REGISTER is sent (Engine::Reregister,
which all three callers go through), and the state file has it then,
before the answer is waited for: a daemon that dies between a REGISTER
and its answer resumes with the next number, where the file's old one
sent the resume into the same refusal. That write is the one the callers
make after the 200, less the 200's own news. In a resume the file then
also has what the resume made up, which is what the next resume would
make up again. A REGISTER the kernel did not take (the send failed) uses
no number; a refused one's is used like an unanswered one's.

Tested on the workstation: the suites (none of them reaches the change,
which is the shell's), and the daemon of this commit and 1.2.4's 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, and can take one refresh without answering it or refuse
one (the capture's bench/bench-cseq.sh). After a refresh whose answer is
lost this daemon's reconnect sends the next number on the same Call-ID,
is answered 200 and refreshes on; 1.2.4's sends the lost one's number
twice, is refused 482 twice and registers fresh. Killed under the wait
and started again, this daemon resumes with the next number; 1.2.4's
resume is refused 482 and it registers fresh. With either of the
change's two lines taken out the bench says so: without the count both
scenarios fail as 1.2.4 does, without the write the restart's does.
After a refresh the stand-in refuses (503) this daemon's reconnect sends
the next number, and 1.2.4's the refused one's again; the stand-in keeps
no number for a REGISTER it refuses and answers both 200. The stand-in
accepts the fresh registration at once, which KPN did not. And on the
dev phone (KPN, the daemon of this commit; the fp6 journal's
2026-11-25-through-sleep capture, phone/cseqtest-2-a and setup.log),
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:
the refresh failed with no reply, the reconnect was answered 200 10 s
later, and the next start resumed from the reconnect's number, one above
the lost one's (that start was of a build with the next commit's change
on this one, in the form it then had, which touches none of this; an
earlier build of this change, with the next two commits' work in
progress on it, in the first capture's phone/, had the next refresh
answered with the number after that). 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).
2026-11-29 14:30:43 +01:00
d48c1017da
imsd 1.2.4
All checks were successful
package / package (push) Successful in 1m56s
2026-11-25 11:50:16 +01:00
c93df591f1
imsd: no CRLF keepalive on the idle flow unless CRLF_KEEPALIVE names an interval
imsd sent a double CRLF, the ping of RFC 5626 4.4.1, on its idle TCP
flow to the P-CSCF every 30 seconds. On a phone that costs far more
than four bytes. The modem brings the ims bearer up for it; 11 to 13 s
later the bearer goes dormant, which the modem reports to
ModemManager, and 90 s after that the modem makes a file-system
request to rmtfs. Each of the two can wake a phone that has gone back to
sleep: in a loop of suspends on the dev phone (KPN, 2026-11-20, the
fp6 journal's 2026-11-20-modem-echo-wakes capture) the modem ended 29
sleeps of 29, 15 with the report and 14 with that request, and none
reached its 150-second alarm; with imsd held still all six did. Awake
and idle on a USB port the phone's battery lost 140 mA with the ping
and 59 mA without it (2026-11-24, one window of 40 min and one of 33).

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).

The ping is now sent only where CRLF_KEEPALIVE=<whole seconds> names
an interval. An empty value is as none; any other that is no whole
number of seconds is reported in the journal and sends none
(imsd::util::WholeSeconds).

What a ping does for a flow, outside a call: 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. The setting is for such a network. On the phone the ping also kept
the connection tracker's entry for the P-CSCF's ESP, without which the
firewall dropped what the network started; the commit before this one
gives the firewall a rule for ESP instead. Without the ping, a close by
the network is answered, outside a call, with a reconnect and a
re-REGISTER. 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 the refresh's, it fails once and the same reconnect
follows; where they are a call's INVITE, the flow is reopened for the
call; where they are a call's BYE, the BYE is lost: imsd sends no BYE
again, as before. Where they are a text's MESSAGE, it is lost with the
flow and the text's wait decides. An incoming call sends no request on
the flow before its BYE, and without the ping the flow can have been
silent, or dropped without a close, since long before such a call came
(AGENTS.md §7.6). A flow that died with no close and no reset reaching
the phone is noticed when the 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), and until
1.2.3 a ping's were among those every 30 s outside a call; a bearer that
left under a registered daemon was noticed at the refresh under the ping
as well (2026-10-02, AGENTS.md §7.2).

Tested: the suites, WholeSeconds in tests/Util; the daemon of this
commit and 1.2.3's on the workstation against a stand-in network that
prints every ping and can close a silent flow or forget it (the fp6
journal's 2026-11-24-crlf-keepalive capture, bench-keepalive.sh: no ping
by default, with CRLF_KEEPALIVE=0 or with an empty value, 1.2.3's three
in 100 s, the setting's, none over UDP, a value that is no number, the
reconnect at each close, the failed refresh and the reconnect on a
forgotten flow, neither a close nor a forgotten flow under the setting
or under 1.2.3's pings, a ping of 1.2.3's reset on a forgotten flow; and
bench-hangup.sh of the 2026-11-24-bye-resend capture: a placed call's
BYE not delivered where the network had forgotten or closed the flow
under the call, by this daemon as by 1.2.3's on the forgetting one). On
the dev phone on KPN, the binary of the range's tip: no packet on the
ims netdev in two idle minutes where 1.2.3 put one each way every 30 s,
the setting's start line and its pings, the line for a value that is no
number. And there, with builds of this change from before the commit of
the call's resend was put under it: the refresh after 1800 awake seconds
answered on the flow, silent until then, twice; and two loops of
suspends with no packet on the netdev, of six sleeps, none ended by the
modem, and of seven, one ended by it, for a file-system request no
packet had preceded (with the pings and the same ModemManager the modem
ended 5 of 8 on 2026-11-20). No network that closes or forgets an idle
flow has been met.
2026-11-25 11:50:16 +01:00
bc0e70a17f
ims-pdn-up: the firewall accepts the ims PDN's ESP itself, not only as an answer to a packet of the phone's
A request the network starts (a call to the phone, a text, a NOTIFY)
reaches the phone as an ESP packet on the ims netdev. That packet passes
the firewall's input chain before the kernel decapsulates it, and what
it carried passes the chain again afterwards. The script opened the
chain for the second, imsd's two protected ports. For the first there
was no rule, and pmOS's chain then lets an ESP packet in only as an
answer to one 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 dropped, and its retransmissions until
the phone next sends to that P-CSCF; imsd sees nothing of it.

What keeps the entry is the CRLF keepalive every 30 s, which goes out
over TCP and outside a call only.

The script now inserts a rule that accepts ESP on qmapmux*, under the
comment imsd-esp and with a check of its own, so that a ruleset which
carries the port rules already (fp6-img's 01_imsd.nft) gets it too. The
kernel drops an ESP packet no SA matches, and what an SA decapsulates
passes the chain again, under the rules a packet on qmapmux* meets
without ESP. Like the port rules the script inserts, the rule is in the
running ruleset only: a reload of the ruleset from its files removes it
until imsd next starts, so a ruleset whose files carry the port rules
has to carry this rule in them as well.

Tested: the script's firewall block by itself on the workstation against
nftables, in two network namespaces with an ESP SA pair between them and
the dev phone's ruleset as read from it (the fp6 journal's
2026-11-24-incoming-dropped-without-ping capture, bench-esp-rule.sh),
the tracker's timeout at 8 s: with 1.2.3's block a connection opened to
port 45062 from the network's side 11 s after the phone's last packet
got no answer, its ESP packets new to the tracker and none through the
chain; with this block the rule was inserted once and the same
connection accepted; an ESP packet with an SPI no SA has dropped by the
kernel behind the chain; a connection through the SA to another port
dropped by the chain; ESP on another interface and an AH packet not
accepted, ESP over IPv4 and ESP on a second qmapmux interface accepted;
the rule gone and the connection unanswered again after the ruleset was
loaded again from its file, and kept where the file carries the rule;
all three rules inserted on a ruleset without imsd's, and connections to
both ports accepted through them; nothing done where there is no inet
filter table. 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. On the dev phone on KPN the script
inserted the rule at imsd's start, above the port rules it found, and
the daemon resumed its registration; and with the tracker's timeout at 0
for the test, so that every ESP packet from the network came without an
entry, a text sent to the phone's own number was answered, reported and
delivered within a second with the rule (six such packets), and none of
the three reached the daemon in 20 s with the rule taken out (23 such
packets). 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).
2026-11-25 11:30:30 +01:00
0aea0dac7f
imsd: when the client flow is found dead before any response to a call's INVITE, one reconnect and the INVITE again, else the call ends
A flow that is dead in a way imsd has not seen yet, the peer having
dropped the connection's state, shows itself at the next bytes sent on
it, where the peer answers them with a reset. Where those bytes were an
outgoing call's INVITE, imsd read the reset, marked the flow dead and
did nothing more for the call: no reconnect runs while a call is up, so
the attempt stayed in `dialing` until its setup deadline, 90 s, sent a
CANCEL that could not go out and was given up 10 s later, where a call
that is no emergency call ends (`setup deadline expired`); the flow was
reconnected only once the call was gone. Against a stand-in network
that forgets a flow after 20 s of silence, 1.2.3's call ended 100 s
after the Dial.

The engine's loop now takes such a call up (MaybeResendInvite). When
the client flow is found dead under an outgoing attempt whose INVITE
has had no response, a 100 included, and no CANCEL, the dead socket is
closed without a FIN's exchange, the flow is reopened with one connect
and the same INVITE is sent again, the setup deadline running from
then. Once per attempt: an emergency call's fallback attempt has a
resend of its own. The INVITE is the first one byte for byte, its
branch included, so a server that did receive the first matches the
second to its transaction (RFC 3261 17.2.3). No REGISTER goes first:
the registration and its SAs stand, and TS 33.203 7.1 has a UE with no
TCP connection towards the P-CSCF set one up before it sends a request.
Where a reg-event NOTIFY has ended the binding nothing is reopened.
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`, an emergency call's first attempt too: there is no flow
for its fallback. The recovery policy takes the flow up once the call
is gone, as before.

The close without a FIN's exchange is for a flow the peer closed:
closed the usual way, such a socket stays in the kernel's table until
the peer has acknowledged imsd's own FIN, and a connect from its port
before that is refused. A reset goes out in the FIN's place there;
after a reset or the kernel's own giving up the socket is closed
already and nothing is sent; and the reopen runs on a flow already
found dead only. The recovery's reconnect closes the usual way, as
before, and connects once more 10 s after such a refusal (one is in a
user's log on O2, 2026-09-24, in the second the flow was found dead).

Not changed: 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
unacknowledged bytes, 924.6 s or more after them by its default
tcp_retries2, so an attempt whose own INVITE is the first such bytes
gets no response and is cancelled at its setup deadline, as before; a
flow found dead after a response to the INVITE is not reopened, as
before; a Dial whose INVITE cannot be sent ends its call at once, as
before.

Tested: tests/Engine (which attempt is sent again, the same bytes, once
per attempt, the deadline anew, the call's end where the flow is lost);
the daemon of this commit and 1.2.3's on the workstation against a
stand-in network (the fp6 journal's 2026-11-24-crlf-keepalive capture,
bench-dial.sh): a flow the network forgot, reopened and the INVITE
answered 486 as on a live flow, where 1.2.3's call ended after 100 s; a
flow the network closed at the INVITE, with the acknowledgement of the
daemon's close kept back; one that died on the daemon's side at the
kernel's retransmission limit; a network that takes no new connection,
one that resets the second INVITE's flow too and one that has ended the
binding, where the call ended within a second; UDP. And on the dev phone
on KPN, the binary of the range's tip: 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: reopened from the same port, the INVITE again 2.1
s after the death was found, answered 0.2 s later. By a call, no P-CSCF
that had dropped a flow's state has been met, and none that had received
the first INVITE before the flow died.
2026-11-25 10:24:07 +01:00
d3e495c333
imsd 1.2.3
All checks were successful
package / package (push) Successful in 2m23s
2026-11-23 19:32:58 +01:00
610d8e1300
imsd: with an identity read from the card's ISIM, a fresh registration is made under it and the ISIM is asked for the answer to the challenge
imsd registered the identity TS 23.003 derives from the IMSI on every
card and authenticated in the USIM. TS 23.003 has a UE derive its home
domain and a temporary public identity "if there is no ISIM
application" (13.2, 13.4B); TS 24.229 5.1.1.1A names the ISIM as
holding the parameters a registration starts from and says "The ISIM
shall always be used for authentication to the IM CN subsystem, if it
is present"; GSMA IR.92 2.2.1 has the UE register the public identity
of EF_IMPU's first record.

A US card on AT&T's network (operator name "Dark Star") holds names of
the operator's own: <IMSI>@private.att.net, one.att.net and
sip:<IMSI>@one.att.net (a read-only probe of the card, 2026-11-23).
imsd 1.1.0's first REGISTER there, with the derived names, was
answered 480 Temporarily Unavailable (2026-11-09); TS 24.229 5.3.1.3
has an I-CSCF answer 480 when the HSS lookup "cannot be completed".
This daemon has not sent that network the card's own names.

Unless ISIM=0 is set, a bring-up reads the ISIM application of the
USIM's slot, in whatever state the modem lists it, over a logical
channel: EF_IMPI, EF_DOMAIN and record 1 of EF_IMPU. When the three
make an identity it is the card's, and the ISIM is asked for the answer
to the challenge; an ISIM that gives no result is followed by the same
challenge to the card's USIM, where 1.2.2 sent every challenge.
Without an ISIM, with ISIM=0, or when the read or the check of the
three fails, the derived names and the USIM stand as before. An
`identity:` line in the journal says which and why. So with ISIM=0,
with an ISIM that gives no identity and behind one that gives no result
imsd asks the USIM where 5.1.1.1A has the ISIM used.

A fresh registration is made under the card's identity. A resumed one
keeps the identity it was made under until its next fresh registration,
as it keeps its P-CSCF and its address: the state file records the
three names, and a file without them is taken for one made under the
derived ones. Otherwise a card whose ISIM holds other names, on a
network that took the derived ones as well, would have its standing
registration refreshed under new names at the first start after the
upgrade. An ISIM that gave no identity at the bring-up
is read again at each recovery by a fresh registration later in the
same run, until it gives one: such a registration would else go out
under the derived names. A state file whose three names are no identity
imsd can register is no registration to resume, whatever transport the
file names.

Calls and texts follow the registration's identity. Its home domain is
what RuriFor takes for the address of a dialled number, an outgoing
call's Request-URI and To (the host, and the phone-context where it
writes one), and what ScPsi takes for the service centre's address of
an SMS submission; while no P-Associated-URI has named another, its
public identity is the one the reg-event SUBSCRIBE names and CallerId
gives. Under an identity read from an ISIM these are the ISIM's.

The read and the AKA run share one channel helper (UimChannel), which
closes its channel on every way out: 1.2.2 left the AKA's channel open
when the card's answer was the single byte 61.

Tested: the suites; the daemon of this commit on the workstation, its
registration against a stand-in for qmicli and a stand-in network that
answers a first REGISTER of any names but 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, among them
an ISIM with names of the operator's own, one with the derived names,
ISIM=0 on the first (480, as on 2026-11-09), an ISIM that cannot be
read or does not answer the challenge, the resume by this daemon of a
registration imsd 1.2.2 made under the derived names on a card whose
ISIM holds others, and a fresh registration in a run that resumed. Not
run on a phone yet, and on no network.
2026-11-23 19:32:58 +01:00
3754687b0d
aka: the ISIM application of a card, its identity files and the identity they hold
An ISIM holds the parameters a registration starts from (TS 24.229
5.1.1.1A): the private identity in EF_IMPI, the home domain in
EF_DOMAIN and public identities in EF_IMPU (TS 31.103 4.2.2 to 4.2.4),
of which the first record's is the one to register (GSMA IR.92 2.2.1).
TS 23.003 has a UE derive its home domain and a temporary public
identity from the IMSI "if there is no ISIM application" (13.2, 13.4B);
those derived names are the only ones imsd has. This is the part of
reading an ISIM that has no I/O; the daemon does not use it yet.

ParseIsimApp finds the ISIM application of one slot in qmicli's card
status, in whatever state the modem lists it. On the two cards with an
ISIM that a read-only probe read (a US card, 2026-11-23, and a
Norwegian one, 2026-11-21) the Fairphone 6's modem lists the ISIM
`detected` beside the `ready` USIM, and on both a logical channel
opened on it and its identity files were read.

The commands are the ones that probe sent: SELECT by file identifier,
READ BINARY, READ RECORD (TS 102 221 11.1.1, 11.1.3, 11.1.5).
ApduAnswer is a card's answer, '90 00', '91 XX' and '92 XX' its normal
endings (10.2.1.1), and ApduFollowUp the command it asks for next when
the answer brought no data: GET RESPONSE for '61 XX', a command without
data again with the length named for '6C XX' (7.3.1.1.5); an answer
with data is taken for the command's last. HoldsRead takes a read's
data under the warning '62 82' as well (10.2.1.3). ParseIsimValue takes
the value of the data object with tag '80' that a file begins with,
cuts 'FF' bytes from the end of its length as the probe does, and gives
none for a value with a blank or a byte that is not printable ASCII.
IsimIdentity checks the three values before they replace the derived
names: they are written into a quoted string and between the angle
brackets of SIP header fields. It refuses a value with a quote, a
backslash, an angle bracket, a blank, a line break or another byte
outside printable ASCII, a private or a public identity of more than
255 characters, 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, and a public identity that
does not begin sip: or is that alone.

The two readers of the card status share how they read a line;
ParseCardStatus gives what it gave.

Tested: tests/Aka (the application out of a card status with the US
card's two applications, in either order, and out of a second slot with
the Norwegian card's AID; the commands, the answers and their
follow-ups, the values, the identity and what is refused) and
tests/Messages (the two REGISTERs of an ISIM's identity against the
pinned ones).
2026-11-23 19:32:58 +01:00
460343e578
aka: a command on a logical channel from 4 to 19 carries the extended class byte
The AUTHENTICATE and the GET RESPONSE went out with the channel number
as their class byte. That is the coding of the standard logical
channels, 0 to 3 (ETSI TS 102 221 10.1.1, table 10.3: the channel in
bits b2 and b1). For the extended ones, 4 to 19, table 10.4a has
'01x0 xxxx' with the channel less four in the low four bits: a command
for channel 4 starts with 40. As 04 it is a command for channel 0 with
a secure-messaging bit set.

The channel is the one the modem returns when imsd opens a logical
channel for the AKA run; imsd does not log it, so whether a
registration ever got one above 3 is not on record.

tests/Aka pins the class byte of channels 0, 1, 3, 4, 5 and 19, the
AUTHENTICATE on channels 3 and 4 and the GET RESPONSE on channel 7.
2026-11-23 14:47:32 +01:00
16 changed files with 3738 additions and 284 deletions

1391
AGENTS.md

File diff suppressed because it is too large Load diff

View file

@ -90,10 +90,12 @@ 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` | | `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) | | `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/<version>` | 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 | | `USER_AGENT` | `imsd/<version>` | 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 | | `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 | | `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 | | `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] | | `REFRESH_INTERVAL` | *(auto)* | keepalive re-REGISTER period in s; default = half the granted expiry, clamped to [120, 1800] |
| `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 | | `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 | | `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) | | `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) |

File diff suppressed because it is too large Load diff

View file

@ -2,17 +2,26 @@
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // 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 * the AKAv1-MD5 HTTP-digest response (RFC 3310) the protected REGISTER
carries in its Authorization header — MD5 over the binary RES; carries in its Authorization header — MD5 over the binary RES;
* the home-network identity (IMPI/IMPU/registration URI/realm) derived * the home-network identity (IMPI/IMPU/registration URI/realm): derived
from IMSI + MCC/MNC; from IMSI + MCC/MNC (TS 23.003 13.2 to 13.4B, the names of a UE without
* text parsers for the SIM facts the daemon shell scrapes from qmicli an ISIM), and since 1.2.3 the one an ISIM holds (TS 24.229 5.1.1.1A) —
(`--uim-get-card-status`: which slot holds a ready USIM and its AID) and the value an identity file carries (`ParseIsimValue`) and the check of
ModemManager (`mmcli`: the primary SIM path, then IMSI + operator id); 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 * 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 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. shell's job — this module only shapes the bytes and reads the answers back.
@ -25,7 +34,9 @@ import :Util;
export namespace imsd::aka { 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 { struct Identity {
std::string imsi; std::string imsi;
std::string mcc; std::string mcc;
@ -75,24 +86,26 @@ export namespace imsd::aka {
return imsd::util::Md5::HexDigest(std::format("{}:{}:{}:{}:{}:{}", ha1, nonce, nc, cnonce, qop, ha2)); 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 { struct SimSelection {
int slot = 0; int slot = 0;
std::string aid; // uppercase, colons stripped std::string aid; // uppercase, colons stripped
}; };
// Parse qmicli `--uim-get-card-status`: the first ready USIM application, // The pieces of qmicli's card status both of its readers take.
// its slot number, and its Application ID (the hex line under namespace detail {
// "Application ID:"). nullopt if no ready USIM is present. Mirrors the // A line without the blanks before it and the blanks or the CR
// Python detect_sim() scan exactly. // after it.
std::optional<SimSelection> ParseCardStatus(std::string_view text) { inline std::string_view Trimmed(std::string_view t) {
int curSlot = 0; while (!t.empty() && (t.front() == ' ' || t.front() == '\t'))
bool inUsim = false; t.remove_prefix(1);
bool ready = false; while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r'))
std::optional<SimSelection> out; t.remove_suffix(1);
std::size_t pos = 0; return t;
auto isAidLine = [](std::string_view s) { }
// trimmed line is HH(:HH)+ — two-or-more colon-separated hex pairs // 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; std::size_t i = 0;
int pairs = 0; int pairs = 0;
auto hex = [](char c) { auto hex = [](char c) {
@ -108,36 +121,49 @@ export namespace imsd::aka {
i++; i++;
} }
return pairs >= 2; return pairs >= 2;
}; }
while (pos <= text.size()) { // Such a line's AID: uppercase, colons stripped.
std::size_t nl = text.find('\n', pos); inline std::string AidOf(std::string_view t) {
std::string_view line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos); std::string aid;
std::string_view t = line; for (char c : t)
while (!t.empty() && (t.front() == ' ' || t.front() == '\t')) if (c != ':') aid.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(c))));
t.remove_prefix(1); return aid;
while (!t.empty() && (t.back() == ' ' || t.back() == '\t' || t.back() == '\r')) }
t.remove_suffix(1); // The N of a "Slot [N]:" line: 0 when what stands between the
// brackets is no number, `fallback` for a line without the pair.
if (t.starts_with("Slot [")) { inline int SlotOf(std::string_view t, int fallback) {
std::size_t lb = t.find('['); std::size_t lb = t.find('[');
std::size_t rb = t.find(']', lb); std::size_t rb = t.find(']', lb);
if (lb != std::string_view::npos && rb != std::string_view::npos) { if (lb == std::string_view::npos || rb == std::string_view::npos) return fallback;
int v = 0; int v = 0;
std::from_chars(t.data() + lb + 1, t.data() + rb, v); std::from_chars(t.data() + lb + 1, t.data() + rb, v);
curSlot = 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<SimSelection> ParseCardStatus(std::string_view text) {
int curSlot = 0;
bool inUsim = false;
bool ready = false;
std::optional<SimSelection> out;
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);
inUsim = ready = false; inUsim = ready = false;
} else if (t.contains("Application type") && t.contains("usim")) { } else if (t.contains("Application type") && t.contains("usim")) {
inUsim = true; inUsim = true;
} else if (inUsim && t.contains("Application state") && t.contains("ready")) { } else if (inUsim && t.contains("Application state") && t.contains("ready")) {
ready = true; ready = true;
} else if (inUsim && isAidLine(t)) { } else if (inUsim && detail::AidLine(t)) {
if (ready && !out) { if (ready && !out) out = SimSelection{curSlot, detail::AidOf(t)};
std::string aid;
for (char c : t)
if (c != ':') aid.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(c))));
out = SimSelection{curSlot, aid};
}
inUsim = false; inUsim = false;
} }
if (nl == std::string_view::npos) break; if (nl == std::string_view::npos) break;
@ -146,6 +172,49 @@ export namespace imsd::aka {
return out; 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<IsimApp> 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: <path>" from `mmcli -m any`. // "primary sim path: <path>" from `mmcli -m any`.
std::optional<std::string> ParsePrimarySimPath(std::string_view text) { std::optional<std::string> ParsePrimarySimPath(std::string_view text) {
std::size_t at = text.find("primary sim path:"); 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=<mcc><mnc><tac:4hex><eci:7hex>" // "3GPP-E-UTRAN-FDD;utran-cell-id-3gpp=<mcc><mnc><tac:4hex><eci:7hex>"
// (TS 24.229 7.2A.4: E-UTRAN cell id = MCC + MNC as broadcast + 16-bit // (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 // 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 // take the low digits). The TAS reads it to see which access the UE
// every REGISTER/INVITE — 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 // 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 // and MM does not expose the duplex mode. nullopt when the fields are
// missing or zero (no serving cell) — callers then omit the header // 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) ---- // ---- 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: // The command APDU (hex, no separators) for a 3G AKA authentication:
// CLA=<channel byte> INS=88 P1=00 P2=81 Lc [10 RAND(16) 10 AUTN(16)] // CLA=<class byte> INS=88 P1=00 P2=81 Lc [10 RAND(16) 10 AUTN(16)]
// `channel` is the logical-channel number qmicli returned; the CLA low // `channel` is the logical-channel number qmicli returned.
// nibble carries it (Python: cla = "%02x" % ch).
std::string BuildAkaApdu(int channel, std::span<const std::uint8_t> rand16, std::span<const std::uint8_t> autn16) { std::string BuildAkaApdu(int channel, std::span<const std::uint8_t> rand16, std::span<const std::uint8_t> autn16) {
std::string data = std::format("10{}10{}", imsd::util::ToHex(rand16), imsd::util::ToHex(autn16)); std::string data = std::format("10{}10{}", imsd::util::ToHex(rand16), imsd::util::ToHex(autn16));
std::size_t lc = data.size() / 2; std::size_t lc = data.size() / 2;
// CLA INS=88 P1=00 P2=81 Lc <data> // CLA INS=88 P1=00 P2=81 Lc <data>
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). // GET RESPONSE APDU for when the card answers 61xx (xx bytes available).
std::string BuildGetResponseApdu(int channel, int le) { 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<std::uint8_t> 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<ApduAnswer> ParseApduAnswer(std::span<const std::uint8_t> 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<std::string> 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<std::string> ParseIsimValue(std::span<const std::uint8_t> 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<std::size_t>(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<char>(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<Identity> 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<unsigned char>(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 { struct AkaResult {
@ -293,4 +532,13 @@ export namespace imsd::aka {
if (!take(r.res) || !take(r.ck) || !take(r.ik)) return std::nullopt; if (!take(r.res) || !take(r.ck) || !take(r.ik)) return std::nullopt;
return r; return r;
} }
// The same of an answer already parted into its data and its status
// word (ParseApduAnswer).
std::optional<AkaResult> ParseAkaResponse(const ApduAnswer& answer) {
std::vector<std::uint8_t> resp = answer.data;
resp.push_back(answer.sw1);
resp.push_back(answer.sw2);
return ParseAkaResponse(std::span<const std::uint8_t>(resp));
}
} }

View file

@ -3,8 +3,8 @@
/* /*
Imsd:Engine — the daemon's decisions as pure reducers: the call state Imsd:Engine — the daemon's decisions as pure reducers: the call state
machine (CallMachine), the registration recovery policy (RegRecovery, machine (CallMachine), the registration recovery policy (RegRecovery, its own section below), when the phone has
its own section below) and SMS over IP's (the last paragraph here). 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 A CallMachine owns one call's SIP dialog, outgoing or incoming. It never
touches a socket, a clock, or a subprocess: each event (the INVITE's touches a socket, a clock, or a subprocess: each event (the INVITE's
@ -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 —
@ -76,8 +77,8 @@ export namespace imsd::engine {
// ---- registration recovery policy --------------------------------- // ---- registration recovery policy ---------------------------------
// //
// What the daemon does when the registration stops working after // What the daemon does when the registration stops working after
// bring-up, as a pure reducer: the shell supplies the clock and the // bring-up, as a pure reducer: the shell supplies the clock, the network and (at a local wait) its kind, the
// network, this decides the next step and how long to wait for it. Two // 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 // kinds of failure reach it. A REFUSAL: the network answered a refresh
// with a final other than 200 — a 401, re-authentication, included — or // with a final other than 200 — a 401, re-authentication, included — or
// a fresh registration's protected REGISTER with a final other than 200 // 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 // refused or throttled fresh attempt, a terminated binding's probation
// or its refusal schedule), which nothing cuts short — a // or its refusal schedule), which nothing cuts short — a
// restart of the process neither: the shell keeps the holds (Holds) // restart of the process neither: the shell keeps the holds (Holds)
// and hands them to the next one (Restore). The shell supplies the // and hands them to the next one (Restore). The shell supplies the clock, what the network answered or did not and,
// clock and the network; this holds the deadlines and names the next // at a local wait, its kind (the kernel's refusal, the modem's word); this holds the deadlines and each kind's count,
// step (Next). Success resets everything. // and names the next step (Next) and when a sleeping phone is woken for it (WakeTime). Success resets everything.
struct RegRecovery { struct RegRecovery {
enum class Failure { Refused, Silent, Throttled }; enum class Failure { Refused, Silent, Throttled };
enum class Step { Reconnect, Fresh }; 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 // untouched. Dev phone 2026-09-24: four such refusals in 26 s read
// as two silent cycles cost a fresh registration into the throttle. // as two silent cycles cost a fresh registration into the throttle.
static constexpr double LocalRetry = 5; 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 refusals = 0;
int silentCycles = 0; int silentCycles = 0;
@ -170,10 +186,14 @@ export namespace imsd::engine {
bool fresh = false; // the next registration attempt is a fresh one bool fresh = false; // the next registration attempt is a fresh one
bool oldGone = false; // the old registration is gone: nothing to reconnect over 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 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 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 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) 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 Fresh() const { return fresh; }
bool Reconnectable() const { return !oldGone; } bool Reconnectable() const { return !oldGone; }
@ -213,7 +233,32 @@ export namespace imsd::engine {
return {Step::Fresh, freshAt}; 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 // A refused keepalive refresh, or a failed reconnect + refresh
// cycle; `status` is the refusal's. The backoff paces the next step; // 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 // registration is due says the old registration is gone (KPN drops
// it the moment an initial REGISTER arrives, throttled or not). // it the moment an initial REGISTER arrives, throttled or not).
void OnReconnectFailure(double now, Failure f, long retryAfter = 0, int status = 0) { 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<double>(std::min(retryAfter, RetryAfterMax))); if (retryAfter > 0) holdUntil = std::max(holdUntil, now + static_cast<double>(std::min(retryAfter, RetryAfterMax)));
// A cycle over a registration already known gone — the network // A cycle over a registration already known gone — the network
// terminated the binding while the cycle waited for its final — // 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 // it off 30 s → 10 min. A reconnect over the old SA meanwhile waits
// at least the reconnect backoff. // at least the reconnect backoff.
void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) { void OnFreshFailure(double now, Failure f, long retryAfter = 0, bool saReplaced = false) {
lastLocal = false;
if (f != Failure::Silent) OnNetworkAnswered();
freshAttempts++; freshAttempts++;
fresh = true; fresh = true;
if (saReplaced) oldGone = 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 // reg-event dialog of the account carries it, a NOTIFY may be
// retransmitted), and never shortens a hold already running. // retransmitted), and never shortens a hold already running.
void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) { void OnBindingTerminated(double now, std::string_view event, long retryAfter = 0) {
lastLocal = false;
OnNetworkAnswered();
bool reported = terminated; bool reported = terminated;
terminated = true; terminated = true;
oldGone = true; oldGone = true;
@ -289,7 +340,7 @@ export namespace imsd::engine {
// The stored registration is not there to reconnect over (a resume // The stored registration is not there to reconnect over (a resume
// that failed at bring-up found its SAs unusable, or there are none). // 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. // A user's Dial cuts the backoff short, never the network's word.
void OnDial() { backoffUntil = 0; } void OnDial() { backoffUntil = 0; }
@ -297,6 +348,24 @@ export namespace imsd::engine {
void OnSuccess() { *this = RegRecovery{}; } 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 // 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). // imsd-media's: "AMR-WB", "AMR", "PCMA", "PCMU" (empty = none we play).
// `dtmfPt` is the telephone-event payload type at the codec's clock // `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. // 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;
@ -420,11 +493,50 @@ export namespace imsd::engine {
offer.codecs = codecs_; offer.codecs = codecs_;
std::string sdp = imsd::sdp::BuildOffer(offer); std::string sdp = imsd::sdp::BuildOffer(offer);
std::vector<Action> a; std::vector<Action> 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)); a.push_back(Deadline(InviteTimeout));
return a; 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<Action> OnFlowReopened() {
std::vector<Action> 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<Action> OnFlowLost() {
std::vector<Action> 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 // UAS: answer the inbound INVITE with 100 Trying + 180 Ringing (made
// reliable only when the caller Requires 100rel) and arm the ring // reliable only when the caller Requires 100rel) and arm the ring
// timeout. An offer we cannot serve — no audio line, or none of the // timeout. An offer we cannot serve — no audio line, or none of the
@ -491,14 +603,21 @@ 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;
answered_ = true;
int code = *st; int code = *st;
if (code > 100 && code < 200) { if (code > 100 && code < 200) {
if (state_ == CallState::Dialing) { if (state_ == CallState::Dialing) {
@ -510,7 +629,7 @@ export namespace imsd::engine {
if (rseq && require.contains("100rel") && !pracked_.contains(std::string(*rseq))) { if (rseq && require.contains("100rel") && !pracked_.contains(std::string(*rseq))) {
pracked_.insert(std::string(*rseq)); pracked_.insert(std::string(*rseq));
std::array<std::string, 1> extra = { std::array<std::string, 1> 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))); a.push_back(Send(imsd::msg::BuildInDialog(ctx_, d_, "PRACK", nextCseq_, rng_.Token(20), extra)));
nextCseq_++; nextCseq_++;
} }
@ -543,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;
@ -761,6 +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 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<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
@ -776,20 +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;
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 is re-attempted as a plain INVITE of the dialled // plain INVITE, unless the user hung up or the digits were tried
// digits: the pre-emergency-support behavior, so classification // before that attempt (the 380's upgrade below): the
// can only improve on the status quo, never block a call the old // pre-emergency-support behavior, so classification can only improve
// 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

@ -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, transport-mode ESP states in their direction or on the UE's ims-PDN address,
whoever installed them (§12); and `FileNamesAnotherPair`, whether a state 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 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 Pure std C++ (the shell runs the commands and captures the text). Command
shapes and the parser are pinned by tests/Ipsec. shapes and the parser are pinned by tests/Ipsec.
@ -180,6 +181,29 @@ export namespace imsd::ipsec {
return cmds; 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) ----------------------------------- // ---- Security-Server (RFC 3329 §2.2) -----------------------------------
// //
// The P-CSCF answers the challenge with the mechanisms it supports, each // The P-CSCF answers the challenge with the mechanisms it supports, each

View file

@ -5,9 +5,11 @@
Imsd:Messages — the SIP request/response text the engine puts on the wire. 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 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 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 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. but for the divergences that suite's header names.
@ -77,7 +79,13 @@ export namespace imsd::msg {
// P-Access-Network-Info value (imsd::aka::ParsePani from live mmcli // P-Access-Network-Info value (imsd::aka::ParsePani from live mmcli
// location: real MCC/MNC/TAC/ECI, FDD). Empty omits the header — // location: real MCC/MNC/TAC/ECI, FDD). Empty omits the header —
// never fabricate one: the network reads it to learn which access // 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; std::string panInfo;
// Advertise SMS over IP in the REGISTER Contact (+g.3gpp.smsip, TS // Advertise SMS over IP in the REGISTER Contact (+g.3gpp.smsip, TS
// 24.341 5.3.2.2): the network then delivers terminating short // 24.341 5.3.2.2): the network then delivers terminating short
@ -224,6 +232,18 @@ export namespace imsd::msg {
} }
return s; 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<std::string>& 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 ------------------------------------------------------- // ---- REGISTER -------------------------------------------------------
@ -333,7 +353,7 @@ export namespace imsd::msg {
// ---- call dialog ---------------------------------------------------- // ---- 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 // 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, // the responses; for an incoming call itag is the To tag we mint,
// dialogTo is the caller's From, and both feed BuildInDialog identically // dialogTo is the caller's From, and both feed BuildInDialog identically
@ -348,11 +368,18 @@ export namespace imsd::msg {
std::optional<std::string> remoteTarget; // remote Contact URI std::optional<std::string> remoteTarget; // remote Contact URI
std::string localUri; // our URI in this dialog: the UAS takes the std::string localUri; // our URI in this dialog: the UAS takes the
// INVITE's To URI; empty = CallerId(c) (UAC) // 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 // The identity we sign our own requests with: the registered public
// identity (P-Associated-URI sip: entry), else the tel: one, and the // 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 // 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 // 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. // the far phone) and a strict one may reject the request.
@ -381,7 +408,8 @@ export namespace imsd::msg {
} }
// INVITE with an AMR-WB SDP offer (passed in, built by Imsd:Sdp). MMTEL // 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 BuildInvite(const Context& c, const Dialog& d, std::string_view sdp, bool precond) {
std::string supported = precond ? "100rel, timer, precondition" std::string supported = precond ? "100rel, timer, precondition"
: "100rel, timer"; : "100rel, timer";
@ -393,7 +421,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: <{}>", d.ruri), std::format("To: <{}>", d.ruri),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
"CSeq: 1 INVITE", std::format("CSeq: {} INVITE", d.invCseq),
std::format("Contact: <sip:{}@{}>;+g.3gpp.icsi-ref=\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)), std::format("Contact: <sip:{}@{}>;+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", "Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER",
std::format("Supported: {}", supported), std::format("Supported: {}", supported),
@ -405,8 +433,8 @@ export namespace imsd::msg {
l.push_back(std::format("Security-Verify: {}", c.securityServer)); l.push_back(std::format("Security-Verify: {}", c.securityServer));
l.push_back("Proxy-Require: sec-agree"); l.push_back("Proxy-Require: sec-agree");
l.push_back("Require: sec-agree"); l.push_back("Require: sec-agree");
l.push_back("Session-Expires: 1800;refresher=uac"); l.push_back(std::format("Session-Expires: {};refresher=uac", d.sessionExpires));
l.push_back("Min-SE: 90"); l.push_back(std::format("Min-SE: {}", d.minSe));
l.push_back("Content-Type: application/sdp"); l.push_back("Content-Type: application/sdp");
l.push_back(std::format("Content-Length: {}", sdp.size())); l.push_back(std::format("Content-Length: {}", sdp.size()));
l.push_back(""); l.push_back("");
@ -415,6 +443,9 @@ export namespace imsd::msg {
// An in-dialog request (PRACK, BYE, UPDATE...) over the dialog route set. // An in-dialog request (PRACK, BYE, UPDATE...) over the dialog route set.
// `extra` lines go after CSeq; an optional body sets Content-Type/Length. // `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<const std::string> extra = {}, std::string_view body = {}, std::string_view ctype = {}) { std::string BuildInDialog(const Context& c, const Dialog& d, std::string_view method, int cseq, std::string_view viaBranch, std::span<const std::string> extra = {}, std::string_view body = {}, std::string_view ctype = {}) {
std::string target = d.remoteTarget.value_or(d.ruri); std::string target = d.remoteTarget.value_or(d.ruri);
std::string to = d.dialogTo.value_or(std::format("<{}>", d.ruri)); std::string to = d.dialogTo.value_or(std::format("<{}>", d.ruri));
@ -430,6 +461,7 @@ export namespace imsd::msg {
}; };
for (const std::string& e : extra) for (const std::string& e : extra)
l.push_back(e); l.push_back(e);
if (!c.panInfo.empty()) l.push_back(std::format("P-Access-Network-Info: {}", c.panInfo));
if (!body.empty()) { if (!body.empty()) {
l.push_back(std::format("Content-Type: {}", ctype)); l.push_back(std::format("Content-Type: {}", ctype));
l.push_back(std::format("Content-Length: {}", body.size())); l.push_back(std::format("Content-Length: {}", body.size()));
@ -453,7 +485,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: {}", to), std::format("To: {}", to),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
"CSeq: 1 ACK", std::format("CSeq: {} ACK", d.invCseq),
"Content-Length: 0", "Content-Length: 0",
}; };
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
@ -470,7 +502,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: {}", toHeader), std::format("To: {}", toHeader),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
"CSeq: 1 ACK", std::format("CSeq: {} ACK", d.invCseq),
"Content-Length: 0", "Content-Length: 0",
}; };
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
@ -486,7 +518,7 @@ export namespace imsd::msg {
std::format("From: <{}>;tag={}", FromUri(c, d), d.itag), std::format("From: <{}>;tag={}", FromUri(c, d), d.itag),
std::format("To: <{}>", d.ruri), std::format("To: <{}>", d.ruri),
std::format("Call-ID: {}", d.callid), std::format("Call-ID: {}", d.callid),
"CSeq: 1 CANCEL", std::format("CSeq: {} CANCEL", d.invCseq),
"Content-Length: 0", "Content-Length: 0",
}; };
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
@ -500,7 +532,8 @@ export namespace imsd::msg {
// half by tagging To (all but 100 Trying, which is hop-by-hop and // 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 // tagless). 1xx/2xx carry our Contact (the dialog's remote target for the
// caller) and Allow; `extra` appends headers (RSeq, Session-Expires...); // 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<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) { std::string BuildInviteResponse(const Context& c, std::string_view invite, int code, std::string_view text, std::string_view toTag, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) {
std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)}; std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)};
for (auto v : imsd::sip::Headers(invite, "Via")) for (auto v : imsd::sip::Headers(invite, "Via"))
@ -522,6 +555,7 @@ export namespace imsd::msg {
} }
for (const std::string& e : extra) for (const std::string& e : extra)
l.push_back(e); l.push_back(e);
detail::AccessInfo(l, c, invite, code);
if (sdp) { if (sdp) {
l.push_back("Content-Type: application/sdp"); l.push_back("Content-Type: application/sdp");
l.push_back(std::format("Content-Length: {}", sdp->size())); l.push_back(std::format("Content-Length: {}", sdp->size()));
@ -536,10 +570,12 @@ export namespace imsd::msg {
// 488 to one we did not: each Via row echoed in order (RFC 3261 // 488 to one we did not: each Via row echoed in order (RFC 3261
// 8.2.6.2), From, To with // 8.2.6.2), From, To with
// `toTag` added unless the request's To holds `tag=` (8.2.6.2 again), // `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 // 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. // 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) { // 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<std::string> l = {std::format("SIP/2.0 {} {}", code, text)}; std::vector<std::string> l = {std::format("SIP/2.0 {} {}", code, text)};
for (auto v : imsd::sip::Headers(request, "Via")) l.push_back(std::format("Via: {}", v)); 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)); if (auto f = imsd::sip::Header(request, "From")) l.push_back(std::format("From: {}", *f));
@ -549,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 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)); 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"); l.push_back("Content-Length: 0");
return std::format("{}\r\n", detail::Join(l)); return std::format("{}\r\n", detail::Join(l));
} }
@ -556,25 +593,30 @@ export namespace imsd::msg {
// The 400 to a request whose datagram ended before its body did (RFC // The 400 to a request whose datagram ended before its body did (RFC
// 3261 18.3), from the request's header section // 3261 18.3), from the request's header section
// (imsd::sip::CutShortRequest), as BuildResponse makes a final. imsd // (imsd::sip::CutShortRequest), as BuildResponse makes a final. imsd
// keeps nothing of such a request, so the To tag is made from the // keeps nothing of such a request, so the tag it adds to a To that holds
// request itself, "in a manner that will generate the same tag for the // none is made from the request itself, "in a manner that will generate
// same request consistently" (8.2.7), and from `secret`, which the // 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 // 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 // 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) { 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)); 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, // 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. // 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<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) { std::string BuildResponse200(const Context& c, std::string_view request, std::optional<std::string_view> sdp = std::nullopt, std::span<const std::string> extra = {}) {
std::vector<std::string> l = {"SIP/2.0 200 OK"}; std::vector<std::string> l = {"SIP/2.0 200 OK"};
for (std::string_view h : {"Via", "From", "To", "Call-ID", "CSeq"}) 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)); if (auto v = imsd::sip::Header(request, h)) l.push_back(std::format("{}: {}", h, *v));
for (const auto& e : extra) for (const auto& e : extra)
l.push_back(e); l.push_back(e);
detail::AccessInfo(l, c, request, 200);
if (sdp) { if (sdp) {
l.push_back(std::format("Contact: <sip:{}@{}>", ContactUser(c), imsd::util::HostPort(c.local, c.portUs))); l.push_back(std::format("Contact: <sip:{}@{}>", ContactUser(c), imsd::util::HostPort(c.local, c.portUs)));
l.push_back("Content-Type: application/sdp"); l.push_back("Content-Type: application/sdp");

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
@ -193,6 +193,26 @@ export namespace imsd::sip {
return out; 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<std::size_t>(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 // 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. // for requests / anything else. Only matches at the start of the message.
std::optional<int> Status(std::string_view msg) { std::optional<int> Status(std::string_view msg) {
@ -228,6 +248,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

@ -3,7 +3,8 @@
/* /*
Imsd:Util — small self-contained primitives the rest of the engine builds on: 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 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 (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 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; 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<long> 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 // 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 // material (the Python rand()). The generator is a parameter so tests can
// pin output; the default constructor seeds from random_device. // pin output; the default constructor seeds from random_device.

View file

@ -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 # 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. # listener, so terminating delivery failed and MT calls fell back to CS.
# 45061/45062 = imsd's protected client/server ports (kPortUc/kPortUs). # 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. # 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 table inet filter >/dev/null 2>&1; then
if ! nft list chain inet filter input | grep -q imsd-protected-ports; 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: opened protected ports 45061-45062 on qmapmux*" ||
log "nftables: rule insert failed (continuing)" log "nftables: rule insert failed (continuing)"
fi 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 fi
exit 0 exit 0

View file

@ -4,6 +4,10 @@
// Imsd:Aka unit tests — the AKAv1-MD5 digest against a vector cross-computed // Imsd:Aka unit tests — the AKAv1-MD5 digest against a vector cross-computed
// with the Python reference, identity assembly, the qmicli/mmcli text // with the Python reference, identity assembly, the qmicli/mmcli text
// parsers (fed real device output), and the AUTHENTICATE APDU build/parse. // 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 std;
import Imsd; 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\t\tA0:00:00:00:87:10:02:FF:31:F0:04:89:0E:00:00:01\n"
"\t\tPIN1 state: 'disabled'\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 = constexpr std::string_view MmcliSim =
" Properties | active: yes\n" " Properties | active: yes\n"
" | imsi: 001010123456789\n" " | imsi: 001010123456789\n"
@ -72,6 +139,10 @@ int main() {
Check(sel && sel->aid == "A0000000871002FF31F004890E000001", "AID uppercased, colons stripped"); Check(sel && sel->aid == "A0000000871002FF31F004890E000001", "AID uppercased, colons stripped");
} }
Check(!ParseCardStatus("Slot [1]:\n\tCard state: 'absent'\n").has_value(), "no ready USIM -> nullopt"); 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 // ---- mmcli parsers
Check(ParsePrimarySimPath(" SIM | primary sim path: /org/freedesktop/ModemManager1/SIM/0\n") == "/org/freedesktop/ModemManager1/SIM/0", "primary sim path"); 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(apdu == "0188008122" "10" "11111111111111111111111111111111" "10" "22222222222222222222222222222222", "APDU byte-exact");
Check(BuildGetResponseApdu(0x01, 0x2E) == "01c000002e", "GET RESPONSE APDU"); 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<std::uint8_t> 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) // DB | 08 RES | 10 CK | 10 IK | SW1 SW2(9000)
std::vector<std::uint8_t> body = {0xDB, 0x08}; std::vector<std::uint8_t> body = {0xDB, 0x08};
@ -112,6 +197,13 @@ int main() {
Check(r && r->res.size() == 8 && r->res[0] == 0xA0, "RES extracted"); 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->ck.size() == 16 && r->ck[0] == 0xC0, "CK extracted");
Check(r && r->ik.size() == 16 && r->ik[0] == 0xD0, "IK 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<std::uint8_t> 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 // sync-failure tag (0xDC) or truncated body -> nullopt
@ -123,8 +215,7 @@ int main() {
{ {
// P-Access-Network-Info from `mmcli --location-get` (real-device // P-Access-Network-Info from `mmcli --location-get` (real-device
// output shape; TAC/CI zero-padded wider than the 4/7 hex digits // output shape; TAC/CI zero-padded wider than the 4/7 hex digits
// PANI uses). The mcc+mnc+TAC+ECI concatenation was validated // PANI uses). Values here are synthetic.
// against a stock modem's on-wire PANI; values here are synthetic.
constexpr std::string_view Loc = constexpr std::string_view Loc =
" --------------------------\n" " --------------------------\n"
" 3GPP | operator mcc: 001\n" " 3GPP | operator mcc: 001\n"
@ -144,6 +235,212 @@ int main() {
Check(!ParsePani(Zeros).has_value(), "PANI all-zero cell rejected"); 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> one = {0x90};
Check(!ParseApduAnswer(one).has_value(), "one byte is no answer");
Check(!ParseApduAnswer({}).has_value(), "no bytes is no answer");
std::vector<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> head, std::string_view text, std::size_t pad) {
std::vector<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> ffInside = {0x80, 0x05, 'a', '.', 0xFF, '.', 'b'};
Check(!ParseIsimValue(ffInside).has_value(), "an FF before the value's end: no value");
std::vector<std::uint8_t> 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<std::uint8_t> nul = {0x80, 0x03, 'a', 0x00, 'b'};
Check(!ParseIsimValue(nul).has_value(), "a NUL in the value: no value");
std::vector<std::uint8_t> 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: <sip:x>", 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<sip:x@y"), "an opening angle bracket in the public identity is refused");
Check(no(P, std::string(63, 'a') + "." + std::string(63, 'b') + "." + std::string(63, 'c') + "." + std::string(63, 'd'), U), "a domain of 255 characters is refused");
Check(!no(P, std::string(63, 'a') + "." + std::string(63, 'b') + "." + std::string(63, 'c') + "." + std::string(61, 'd'), U), "a domain of 253 characters is taken");
Check(no(P, std::string(63, 'a') + "." + std::string(63, 'b') + "." + std::string(63, 'c') + "." + std::string(62, 'd'), U), "a domain of 254 characters is refused");
Check(no(P, D, "sip:001010123456789@one.example.net\r\nTo: <sip:x>"), "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"); 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 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
} }

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
@ -12,7 +14,11 @@
// ring and are answered at the offer's own payload types, ring timeout -> // 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 // 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 // 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 // call that negotiated telephone-event, and are dropped — with the reason
// — before the answer, after the call, without the negotiation or with a // — before the answer, after the call, without the negotiation or with a
// character that is no tone. Then RegRecovery, the registration recovery policy: // 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 // fresh backoffs, the throttle schedule, Retry-After, which waits a Dial
// may cut short, when the old registration counts as gone, the holds a // may cut short, when the old registration counts as gone, the holds a
// restart takes over (Holds/Restore), and a binding the network terminated // restart takes over (Holds/Restore), and a binding the network terminated
// (OnBindingTerminated). 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 // (StatusReportBook with SameRecipient — a word for the whole message: a two-segment
// message delivered with its last segment, a permanent failure the last // message delivered with its last segment, a permanent failure the last
// word, pending kept, another recipient no match, a reused TP-MR, a // word, pending kept, another recipient no match, a reused TP-MR, a
@ -94,8 +102,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"
@ -152,6 +161,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)
@ -470,6 +503,55 @@ int main() {
Check(m.Terminated(), "terminated on second timeout"); 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) ======================= // ================= incoming (terminating / UAS) =======================
// ---- full accepted incoming call: INVITE -> 100+180, Accept -> 200 with // ---- full accepted incoming call: INVITE -> 100+180, Accept -> 200 with
@ -839,6 +921,67 @@ int main() {
Check(m.Terminated(), "terminated"); 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: <sip:+31612345678@ims;user=phone>;tag=caller1\r\n"
"To: <sip:+31611111111@ims;user=phone>;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 (stage 1) ================================
// ---- emergency dial: the INVITE targets the sos URN over the normal // ---- 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"); 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 // ---- chain exhausted: the fallback leg's final terminates, no 3rd try
{ {
imsd::util::Rng rng(45); imsd::util::Rng rng(45);
@ -893,6 +1061,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);
@ -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) ---------- // ---- SMS over IP: SmsOutbound and OnSmsMessage (TS 24.341) ----------
{ {
using namespace imsd::sms; using namespace imsd::sms;

View file

@ -8,7 +8,8 @@
// prints, with its line for each algorithm imsd installs, and // prints, with its line for each algorithm imsd installs, and
// the Security-Server parser, fed the operator lines as captured (O2 UK's // the Security-Server parser, fed the operator lines as captured (O2 UK's
// six-mechanism Mavenir shape verbatim, under a null and under an aes-cbc // six-mechanism Mavenir shape verbatim, under a null and under an aes-cbc
// offer; KPN's single mechanism; Odido's), and the EALG list. // offer; KPN's single mechanism; Odido's), the EALG list, and the two
// paths an SA pair's outbound policies select (OnSaPath).
import std; import std;
import Imsd; import Imsd;
@ -476,6 +477,22 @@ int main() {
Check(NormalizeEalg("") == "null" && NormalizeEalg("3des") == "des-ede3-cbc" && NormalizeEalg("aes-cbc") == "aes-cbc", "NormalizeEalg"); 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"); 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 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
} }

View file

@ -18,7 +18,14 @@
// and left terminating access-domain selection routing incoming calls to // and left terminating access-domain selection routing incoming calls to
// CS fallback (observed live 2026-07-20); and the REGISTERs' Security-Client // CS fallback (observed live 2026-07-20); and the REGISTERs' Security-Client
// carries the default offer's two mechanisms, where the Python stack offered // carries the default offer's two mechanisms, where the Python stack offered
// one cipher. Then the SMS over IP shapes: the // 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 // +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 // 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 // IP-SM-GW with In-Reply-To (TS 24.341 5.3.1.2, 5.3.2.4), and a final other
@ -251,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"); 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, "<sip:001010123456789@ims.mnc001.mcc001.3gppnetwork.org>", "<sip:001010123456789@one.example.net>") == 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, "<sip:001010123456789@ims.mnc001.mcc001.3gppnetwork.org>", "<sip:001010123456789@one.example.net>");
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: <sip:001010123456789@[2001:db8::db43]:5060>"), "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 // ---- 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("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"); Eq(RuriFor("+31612345678", c.id.domain), "sip:+31612345678@ims.mnc001.mcc001.3gppnetwork.org;user=phone", "ruri E.164");
@ -383,11 +426,11 @@ int main() {
Check(prack.contains("To: <sip:1233@x>;tag=remote99\r\n"), "PRACK To has remote tag"); Check(prack.contains("To: <sip:1233@x>;tag=remote99\r\n"), "PRACK To has remote tag");
Check(prack.contains("CSeq: 2 PRACK\r\n"), "PRACK CSeq"); Check(prack.contains("CSeq: 2 PRACK\r\n"), "PRACK CSeq");
Check(prack.contains("RAck: 42 1 INVITE\r\n"), "PRACK RAck"); 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"); 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.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", "<ignored>"); std::string ack = BuildAck2xx(c, d, "ackbranch", "<ignored>");
Check(ack.starts_with("ACK sip:termgw@2001:db8::9 SIP/2.0\r\n"), "ACK 2xx target"); Check(ack.starts_with("ACK sip:termgw@2001:db8::9 SIP/2.0\r\n"), "ACK 2xx target");
@ -398,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.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("branch=z9hG4bKib;rport\r\n"), "CANCEL reuses INVITE branch");
Check(cancel.contains("CSeq: 1 CANCEL\r\n"), "CANCEL CSeq copies INVITE"); 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, "<sip:x@y>;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 // non-2xx ACK uses the INVITE branch + registration route + resp To
@ -408,6 +457,20 @@ int main() {
Check(ack.contains(std::format("Route: {}\r\n", c.route)), "non-2xx ACK registration route"); Check(ack.contains(std::format("Route: {}\r\n", c.route)), "non-2xx ACK registration route");
Check(ack.contains("To: <sip:x@y>;tag=z\r\n"), "non-2xx ACK echoes response To"); Check(ack.contains("To: <sip:x@y>;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, "<sip:x@y>;tag=z").contains("\r\nCSeq: 2 ACK\r\n"), "non-2xx ACK copies the INVITE's number");
Check(BuildAck2xx(c, d, "ab", "<sip:x@y>;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 // ---- 200 OK response echoes the request's dialog headers, in order
{ {
@ -424,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("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("Call-ID: xyz@far\r\n"), "200 echoes Call-ID");
Check(r.contains("CSeq: 7 BYE\r\n"), "200 echoes CSeq"); 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 // with an SDP answer: our Contact + application/sdp appear
std::string r2 = BuildResponse200(c, req, Sdp); std::string r2 = BuildResponse200(c, req, Sdp);
Check(r2.contains("Content-Type: application/sdp\r\n"), "200 w/ SDP content-type"); Check(r2.contains("Content-Type: application/sdp\r\n"), "200 w/ SDP content-type");
Check(r2.contains("Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"), "200 w/ SDP includes our Contact"); Check(r2.contains("Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"), "200 w/ SDP includes our Contact");
Check(r2.ends_with(Sdp), "200 w/ SDP body"); 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 ------------ // ---- s53 oracle diff: UUID Contact user-part + User-Agent ------------
@ -515,7 +587,9 @@ int main() {
"Call-ID: in1@net\r\n" "Call-ID: in1@net\r\n"
"CSeq: 9 MESSAGE\r\n" "CSeq: 9 MESSAGE\r\n"
"Content-Length: 0\r\n\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" "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::105]:6000;branch=z9hG4bKnet1\r\n"
"Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n" "Via: SIP/2.0/UDP [2001:db8::77]:5060;branch=z9hG4bKgw0\r\n"
@ -524,6 +598,16 @@ int main() {
"Call-ID: in1@net\r\n" "Call-ID: in1@net\r\n"
"CSeq: 9 MESSAGE\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"); "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: <sip:ipsmgw@ims>;tag=N1\r\n"
"To: <sip:me@ims>;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: <sip:ipsmgw@ims>;tag=N2\r\nTo: <sip:me@ims>;tag=had\r\nCall-ID: in2@net\r\nCSeq: 1 MESSAGE\r\nContent-Length: 0\r\n\r\n"; 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: <sip:ipsmgw@ims>;tag=N2\r\nTo: <sip:me@ims>;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: <sip:me@ims>;tag=had\r\n"), "a To that already carries a tag is echoed as it is"); Check(BuildResponse(c, tagged, 200, "OK", "unused").contains("\r\nTo: <sip:me@ims>;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 // 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
@ -544,6 +628,7 @@ int main() {
"CSeq: 9 MESSAGE\r\n" "CSeq: 9 MESSAGE\r\n"
"Content-Length: 0\r\n\r\n", "its 400 echoes every Via and tags To with sixteen hex digits of the MD5 of the secret and the header section"); "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"); 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 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); const std::string r1 = BuildBadRequest(head, secret);
std::string other = cut; std::string other = cut;
@ -590,6 +675,18 @@ int main() {
"i: call3@net\r\n" "i: call3@net\r\n"
"CSeq: 1 INVITE\r\n" "CSeq: 1 INVITE\r\n"
"l: 0\r\n\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: <sip:[2001:db8::105]:6000;lr>\r\n"
"From: <sip:caller@ims>;tag=N3\r\n"
"To: <sip:me@ims>;tag=T180\r\n"
"Call-ID: call3@net\r\n"
"CSeq: 1 INVITE\r\n"
"Contact: <sip:001010123456789@[2001:db8::db43]:45062>\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"); const std::string ringing = BuildInviteResponse(c, invite, 180, "Ringing", "T180");
Eq(ringing, Eq(ringing,
"SIP/2.0 180 Ringing\r\n" "SIP/2.0 180 Ringing\r\n"
@ -602,7 +699,21 @@ int main() {
"CSeq: 1 INVITE\r\n" "CSeq: 1 INVITE\r\n"
"Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n" "Contact: <sip:001010123456789@[2001:db8::db43]:45062>\r\n"
"Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, PRACK, UPDATE, MESSAGE, REFER\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<std::string, 2> 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, 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"); 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: <sip:me@ims>;tag=T486\r\n") && !BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("Record-Route"), "a 486 tags To and returns no Record-Route"); Check(BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("\r\nTo: <sip:me@ims>;tag=T486\r\n") && !BuildInviteResponse(c, invite, 486, "Busy Here", "T486").contains("Record-Route"), "a 486 tags To and returns no Record-Route");

View file

@ -9,9 +9,12 @@
// 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
// reg-event document (RegInfoContactState), and HeaderUri and Body. These pin // matching (ResponseOf), our binding in a
// the module's edge-case behavior; see the module header before "fixing" one. // reg-event document (RegInfoContactState), HeaderUri and Body, and a
// message less every line on which one header is found (WithoutHeader).
// These pin the module's edge-case behavior; see the module header before
// "fixing" one.
import std; import std;
import Imsd; 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"); 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 =
@ -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"); 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"); if (Failures == 0) std::println("Sip: all tests passed");
return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that return Failures != 0; // not the count: `crafter-build test` takes an exit status of 77 for a skipped suite, and this suite has more checks than that
} }

View file

@ -3,7 +3,7 @@
// Imsd:Util unit tests — MD5 against the RFC 1321 test suite, base64/hex // 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 // 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 // base64 are our own (the standard library ships neither) and the AKAv1-MD5
// digest depends on them exactly, so these are pinned hard. // digest depends on them exactly, so these are pinned hard.
import std; import std;
@ -136,6 +136,16 @@ int main() {
Check(ParseAddressList("2001:db8::1").size() == 1, "list: single entry, no rejected sink"); 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"); 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 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
} }