2026-07-22 22:53:28 +02:00
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
imsd — the userspace IMS / VoLTE daemon ( control plane ) .
Owns net . catcrafts . IMS1 on the system bus with the project ' s frozen D - Bus ABI
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
( AGENTS . md § 8.1 ) and drives it with the engine core : register on the IMS PDN ( by default the
identity the card ' s ISIM holds , else the one derived from the IMSI ; AKA in that
ISIM , else in the USIM ; IPsec sec - agree , fresh or warm - resume , with a keepalive
re - REGISTER refresh ) ,
2026-07-22 22:53:28 +02:00
run outgoing and incoming calls through the Imsd : Engine call machine ( inbound
INVITEs on the protected - port listeners become ringing calls a dialer answers
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
via Accept ) , spawn one imsd - media data - plane process per answered call , and
since 1.2 .0 send and take short messages over IMS ( AGENTS . md § 7.9 : the SIP
MESSAGE with an RP - DATA , the Messaging interface on the same object ) .
imsd, imsd-ofonod: let polkit decide call control, not the account name
The system-bus policies granted net.catcrafts.IMS1 and org.ofono to root
and to the account `user`, postmarketOS's default name, so on a unit
whose account is called something else dbus denied every Dial from the
dialer — nothing in imsd's journal, nothing on screen. A field user
found it by trial (alyx report 14, 2026-09-20; ims ledger F14).
Let any local account reach both names and have the daemons decide:
placing, answering or ending a call needs polkit's
net.catcrafts.IMS1.Voice (the active local session; not an ssh login, an
inactive session or a system service account). imsd-ofonod asks about
its own callers, since its calls reach imsd as root. Reads such as the
status and the call list are not gated, and a refusal is logged with the
sender; a `--session` run, the development mode without root or polkit,
leaves the gate off. The check is ImsdBus, a small GLib module both
daemons link; the package depends on polkit.
An upgrade restarts both daemons (the previous commit), so the open
policy faces the old, ungated daemons only until the apk transaction
ends.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 20:44:58 +02:00
GLib / GDBus lives only here and in ImsdBus ( the polkit gate in front of call
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
control and messaging , shared with imsd - ofonod ) — the integration daemons imsd - dialerd and
imsd, imsd-ofonod: let polkit decide call control, not the account name
The system-bus policies granted net.catcrafts.IMS1 and org.ofono to root
and to the account `user`, postmarketOS's default name, so on a unit
whose account is called something else dbus denied every Dial from the
dialer — nothing in imsd's journal, nothing on screen. A field user
found it by trial (alyx report 14, 2026-09-20; ims ledger F14).
Let any local account reach both names and have the daemons decide:
placing, answering or ending a call needs polkit's
net.catcrafts.IMS1.Voice (the active local session; not an ssh login, an
inactive session or a system service account). imsd-ofonod asks about
its own callers, since its calls reach imsd as root. Reads such as the
status and the call list are not gated, and a refusal is logged with the
sender; a `--session` run, the development mode without root or polkit,
leaves the gate off. The check is ImsdBus, a small GLib module both
daemons link; the package depends on polkit.
An upgrade restarts both daemons (the previous commit), so the open
policy faces the old, ungated daemons only until the apk transaction
ends.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 20:44:58 +02:00
imsd - ofonod carry their own ; every message , digest , SA command , and
call - state decision comes from the GLib - free core .
2026-07-22 22:53:28 +02:00
Threads : a dedicated engine thread runs the SIP loop ( blocking framed recv ,
protected - port listeners , media reaping , keepalive ) ; the GLib main loop owns
the bus . D - Bus method calls push commands to the engine queue ; engine events
reach the bus via g_idle_add , where the calls table + status snapshot live
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
( touched only on the main thread ) . The Messaging interface ' s Subscribe keeps
its subscriber set on the main thread too .
2026-07-22 22:53:28 +02:00
imsd, imsd-ofonod: let polkit decide call control, not the account name
The system-bus policies granted net.catcrafts.IMS1 and org.ofono to root
and to the account `user`, postmarketOS's default name, so on a unit
whose account is called something else dbus denied every Dial from the
dialer — nothing in imsd's journal, nothing on screen. A field user
found it by trial (alyx report 14, 2026-09-20; ims ledger F14).
Let any local account reach both names and have the daemons decide:
placing, answering or ending a call needs polkit's
net.catcrafts.IMS1.Voice (the active local session; not an ssh login, an
inactive session or a system service account). imsd-ofonod asks about
its own callers, since its calls reach imsd as root. Reads such as the
status and the call list are not gated, and a refusal is logged with the
sender; a `--session` run, the development mode without root or polkit,
leaves the gate off. The check is ImsdBus, a small GLib module both
daemons link; the package depends on polkit.
An upgrade restarts both daemons (the previous commit), so the open
policy faces the old, ungated daemons only until the apk transaction
ends.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 20:44:58 +02:00
- - session own the name on the session bus ( development ; no policy , no
polkit )
2026-07-22 22:53:28 +02:00
*/
# include <arpa/inet.h>
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
# include <dirent.h>
2026-07-22 22:53:28 +02:00
# include <fcntl.h>
# include <gio/gio.h>
# include <glib-unix.h>
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
# include <ifaddrs.h>
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
# include <limits.h>
2026-07-22 22:53:28 +02:00
# include <netinet/in.h>
# include <poll.h>
# include <pthread.h>
imsd, media: aim call audio at logind's seat0 session, not an account named `user`
imsd-media defaulted AUDIO_USER to `user`, postmarketOS's default
account name, and with no such account a call had no audio on the phone
and noise at the far end, the message only in imsd-media's stderr, at
each call. A field user found it by trial (alyx report 14, 2026-09-20;
ims ledger F14).
Have imsd, as packaged (root, on the system bus), resolve the session
from logind when a call's media starts — the user session active on
seat0 (a greeter is not one) when it has a PipeWire socket — and hand it
to imsd-media as AUDIO_USER; set in imsd's own environment to an
account's name, AUDIO_USER pins that account instead. imsd as packaged
(root, on the system bus) logs the resolution at start, before the first
call, and when a call's media starts.
No session is an empty AUDIO_USER. imsd-media started without the
variable at all keeps `user`: that is an imsd older than 0.3.10, still
running while an upgrade replaces the helper under it, whose calls would
otherwise be silent until the restart, or a hand run.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-25 17:15:02 +02:00
# include <pwd.h>
2026-07-22 22:53:28 +02:00
# include <signal.h>
# include <sys/socket.h>
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
# include <sys/stat.h>
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
# include <sys/timerfd.h>
2026-07-22 22:53:28 +02:00
# include <sys/wait.h>
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
# include <time.h>
2026-07-22 22:53:28 +02:00
# include <unistd.h>
import std ;
import Imsd ;
imsd, imsd-ofonod: let polkit decide call control, not the account name
The system-bus policies granted net.catcrafts.IMS1 and org.ofono to root
and to the account `user`, postmarketOS's default name, so on a unit
whose account is called something else dbus denied every Dial from the
dialer — nothing in imsd's journal, nothing on screen. A field user
found it by trial (alyx report 14, 2026-09-20; ims ledger F14).
Let any local account reach both names and have the daemons decide:
placing, answering or ending a call needs polkit's
net.catcrafts.IMS1.Voice (the active local session; not an ssh login, an
inactive session or a system service account). imsd-ofonod asks about
its own callers, since its calls reach imsd as root. Reads such as the
status and the call list are not gated, and a refusal is logged with the
sender; a `--session` run, the development mode without root or polkit,
leaves the gate off. The check is ImsdBus, a small GLib module both
daemons link; the package depends on polkit.
An upgrade restarts both daemons (the previous commit), so the open
policy faces the old, ungated daemons only until the apk transaction
ends.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 20:44:58 +02:00
import ImsdBus ;
2026-07-22 22:53:28 +02:00
namespace {
// ---- static config (env-overridable, same knobs as imsd.py) ---------------
2026-11-25 11:50:16 +01:00
constexpr const char * Version = " 1.2.4 " ;
2026-07-22 22:53:28 +02:00
constexpr const char * BusName = " net.catcrafts.IMS1 " ;
constexpr const char * ObjPath = " /net/catcrafts/IMS1 " ;
constexpr const char * Iface = " net.catcrafts.IMS1 " ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
constexpr const char * MessagingIface = " net.catcrafts.IMS1.Messaging " ;
2026-07-22 22:53:28 +02:00
constexpr int PortUc = imsd : : util : : PortUc ;
constexpr int PortUs = imsd : : util : : PortUs ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
constexpr int PortUcNext = imsd : : util : : PortUcNext ;
2026-07-22 22:53:28 +02:00
constexpr int InitPort = 5060 ;
std : : string EnvOr ( const char * k , std : : string d ) {
const char * v = std : : getenv ( k ) ;
return v ? std : : string ( v ) : std : : move ( d ) ;
}
std : : string SelfDir ; // dir of argv[0], for locating imsd-media
void Log ( std : : string_view m ) { std : : println ( " imsd: {} " , m ) ; std : : fflush ( stdout ) ; }
bool Is6 ( std : : string_view a ) { return a . contains ( ' : ' ) ; }
// ---- subprocess exec ------------------------------------------------------
struct ProcResult { int rc = - 1 ; std : : string out ; } ;
// Run argv, capture stdout (stderr discarded), wait. No shell.
ProcResult RunCapture ( const std : : vector < std : : string > & argv ) {
int pipefd [ 2 ] ;
if ( pipe ( pipefd ) ! = 0 ) return { } ;
pid_t pid = fork ( ) ;
if ( pid = = 0 ) {
dup2 ( pipefd [ 1 ] , STDOUT_FILENO ) ;
close ( pipefd [ 0 ] ) ; close ( pipefd [ 1 ] ) ;
int dn = open ( " /dev/null " , O_WRONLY ) ;
if ( dn > = 0 ) { dup2 ( dn , STDERR_FILENO ) ; close ( dn ) ; }
std : : vector < char * > c ;
for ( auto & s : argv ) c . push_back ( const_cast < char * > ( s . c_str ( ) ) ) ;
c . push_back ( nullptr ) ;
execvp ( c [ 0 ] , c . data ( ) ) ;
_exit ( 127 ) ;
}
if ( pid < 0 ) { close ( pipefd [ 0 ] ) ; close ( pipefd [ 1 ] ) ; return { } ; }
close ( pipefd [ 1 ] ) ;
std : : string out ;
char buf [ 4096 ] ;
ssize_t n ;
while ( ( n = read ( pipefd [ 0 ] , buf , sizeof buf ) ) > 0 )
out . append ( buf , static_cast < std : : size_t > ( n ) ) ;
close ( pipefd [ 0 ] ) ;
int status = 0 ;
waitpid ( pid , & status , 0 ) ;
return { WIFEXITED ( status ) ? WEXITSTATUS ( status ) : - 1 , std : : move ( out ) } ;
}
// Run argv, discard output, return exit code.
int RunCmd ( const std : : vector < std : : string > & argv ) { return RunCapture ( argv ) . rc ; }
ipsec: build the SAs from the Security-Server mechanism the UE selects
A P-CSCF may answer the challenge with every mechanism it supports and
attach the SPIs and ports to the one it applied. O2 UK's core lists six
ipsec-3gpp entries with q-values, md5 first, and marks the fourth (sha1,
no ealg). imsd took the first ealg= anywhere in the header - the 3DES of
an entry the P-CSCF had not selected - and installed SAs the far end
could not decrypt: every protected packet after the 401 was dropped at
its IPsec layer, over TCP and UDP alike, with nothing to answer.
The 401 handling now parses the Security-Server as a mechanism list
(commas outside quotes, parameters on semicolons, names and values
case-insensitive) and selects the highest-q ipsec-3gpp mechanism that
matches what Security-Client offered (RFC 3329 2.3.1, TS 24.229
5.1.1.5.1): alg equal to ours, ealg (absent = null) equal to the offer.
The SPIs and ports are per registration and come from the entry carrying
them. When no entry matches the offer, the entry carrying the SPIs is
installed as listed and the journal says so; hmac-md5-96 becomes
hmac(md5) with IK as the key. A single-mechanism header selects itself:
on KPN the SAs are the same as before (unit-pinned argv, verified on the
phone). An answer that cannot be used - no ipsec-3gpp entry, a missing
spi/port, an alg, ealg, prot or mod the kernel cannot be handed - defers
the bring-up on the throttle schedule with the reason, before the AKA is
spent, instead of a fatal that would restart imsd every RestartSec with
an initial REGISTER each time; spi-s=0 stays the throttle deferral.
Repeated Security-Server header lines are joined into the one list
Security-Verify echoes.
The journal shows the Security-Server line, the selected mechanism, the
SA parameters, and any ip xfrm command that fails (keys masked) at every
fresh registration - the silence this bug produced had no line to read.
2026-09-19 21:36:57 +02:00
// argv as one journal line with key material (the "0x…" tokens) masked.
std : : string RedactKeys ( const std : : vector < std : : string > & argv ) {
std : : string s ;
for ( const auto & a : argv ) {
if ( ! s . empty ( ) ) s + = ' ' ;
s + = a . starts_with ( " 0x " ) ? " <key> " : a ;
}
return s ;
}
ipsec, imsd: the SA setup deletes by exact key instead of flushing the host's xfrm
A fresh registration's SA setup began with `ip xfrm state flush` and `ip
xfrm policy flush`: every SA userspace had installed and every SPD policy
went, a policy-based VPN's (strongSwan's, libreswan's) SAs and policies
included. The setup now takes out what two rules select and leaves the
rest; and the SA reader, which took the P-CSCF ports for a resume from any
reqid-1/2 `dir out` policy — correct only while the flush left imsd's pair
alone in the kernel — takes them from the policies between our two
addresses only. Whether imsd runs beside a live strongSwan or libreswan
connection is unmeasured: the dev phone shows a tunnel policy and a tunnel
state left in place (Tested below), no more.
OwnXfrmDeleteCommands (Imsd:Ipsec) builds the deletes from the kernel text
the shell reads: every transport-mode policy with reqid 1 or 2 whose
selector carries imsd's protected port on the UE side, by the selector ip
xfrm policy prints (src, dst, proto, sport, dport, dev) and its direction,
and every transport-mode reqid-1/2 ESP state running from such a policy's
source to its destination or anchored on the UE's ims-PDN address, by src,
dst, proto esp and SPI — policy or not: a setup whose policy add failed
leaves such states (the setup logs a failed add and goes on), and an ESP
state another transport-mode user put on that address with reqid 1 or 2 goes
with them (an AH or IPComp state is not selected: the rule asks for ESP).
Every reader of the policy text — the deletes and the SA
reader's port pass here — goes through one predicate (detail::OwnPolicy),
written for whatever reads that text later.
BuildSetupCommands loses its two flush lines and the shell runs the deletes
right before it (RunOwnXfrmDeletes); BuildTeardownCommands, the same two
flushes with no caller, goes. A policy-based VPN's tunnel entries and
another transport-mode user's pair on other ports and addresses stay.
Residual: a transport-mode policy with reqid 1 and the UE-side port 45061,
or reqid 2 and 45062 — alone or paired, between any addresses — carries
imsd's fingerprint and goes, with the reqid-1/2 transport-mode ESP states
in its direction, and a reqid-1/2 transport-mode ESP state on the UE's
ims-PDN address goes whoever made it (tests/Ipsec pins both, and that an AH state
stays).
Tested: crafter-build test, 7 passed (the eight deletes byte-exact on the
fixture in the registered FP6's shape (synthetic addresses and keys); a VPN's tunnel SA and policies beside the pair
untouched; another transport-mode user's pair on other ports and addresses
untouched, its reqid-1 ESP state on the UE's address deleted whoever made
it, its AH state left; a policy-less state on the UE's address deleted, one
between other addresses left; the reader's ports from our pair beside
a foreign transport policy with ports); on the dev phone (KPN), in builds of
this series, a fresh registration with a VPN's tunnel policy and state in
the kernel: both still there afterwards, imsd's previous pair gone.
2026-10-13 22:28:02 +02:00
// imsd's own xfrm entries out of the kernel, each by its key (the
// OwnXfrmDeleteCommands list — never `ip xfrm … flush`: another IPsec user's
// entries, a policy-based VPN's, stay, §12); a delete that fails (an entry
// gone between the read and the delete) is logged and the rest go on. At
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// file scope, as LoadHolds and PersistHolds are: the Engine and main() both
// run it (main() through RemoveDeadPair).
ipsec, imsd: the SA setup deletes by exact key instead of flushing the host's xfrm
A fresh registration's SA setup began with `ip xfrm state flush` and `ip
xfrm policy flush`: every SA userspace had installed and every SPD policy
went, a policy-based VPN's (strongSwan's, libreswan's) SAs and policies
included. The setup now takes out what two rules select and leaves the
rest; and the SA reader, which took the P-CSCF ports for a resume from any
reqid-1/2 `dir out` policy — correct only while the flush left imsd's pair
alone in the kernel — takes them from the policies between our two
addresses only. Whether imsd runs beside a live strongSwan or libreswan
connection is unmeasured: the dev phone shows a tunnel policy and a tunnel
state left in place (Tested below), no more.
OwnXfrmDeleteCommands (Imsd:Ipsec) builds the deletes from the kernel text
the shell reads: every transport-mode policy with reqid 1 or 2 whose
selector carries imsd's protected port on the UE side, by the selector ip
xfrm policy prints (src, dst, proto, sport, dport, dev) and its direction,
and every transport-mode reqid-1/2 ESP state running from such a policy's
source to its destination or anchored on the UE's ims-PDN address, by src,
dst, proto esp and SPI — policy or not: a setup whose policy add failed
leaves such states (the setup logs a failed add and goes on), and an ESP
state another transport-mode user put on that address with reqid 1 or 2 goes
with them (an AH or IPComp state is not selected: the rule asks for ESP).
Every reader of the policy text — the deletes and the SA
reader's port pass here — goes through one predicate (detail::OwnPolicy),
written for whatever reads that text later.
BuildSetupCommands loses its two flush lines and the shell runs the deletes
right before it (RunOwnXfrmDeletes); BuildTeardownCommands, the same two
flushes with no caller, goes. A policy-based VPN's tunnel entries and
another transport-mode user's pair on other ports and addresses stay.
Residual: a transport-mode policy with reqid 1 and the UE-side port 45061,
or reqid 2 and 45062 — alone or paired, between any addresses — carries
imsd's fingerprint and goes, with the reqid-1/2 transport-mode ESP states
in its direction, and a reqid-1/2 transport-mode ESP state on the UE's
ims-PDN address goes whoever made it (tests/Ipsec pins both, and that an AH state
stays).
Tested: crafter-build test, 7 passed (the eight deletes byte-exact on the
fixture in the registered FP6's shape (synthetic addresses and keys); a VPN's tunnel SA and policies beside the pair
untouched; another transport-mode user's pair on other ports and addresses
untouched, its reqid-1 ESP state on the UE's address deleted whoever made
it, its AH state left; a policy-less state on the UE's address deleted, one
between other addresses left; the reader's ports from our pair beside
a foreign transport policy with ports); on the dev phone (KPN), in builds of
this series, a fresh registration with a VPN's tunnel policy and state in
the kernel: both still there afterwards, imsd's previous pair gone.
2026-10-13 22:28:02 +02:00
void RunOwnXfrmDeletes ( const std : : vector < std : : vector < std : : string > > & cmds ) {
for ( auto & cmd : cmds ) {
int rc = RunCmd ( cmd ) ;
if ( rc ! = 0 ) Log ( std : : format ( " {} -> rc {} " , RedactKeys ( cmd ) , rc ) ) ;
}
}
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// The kernel's SA pair when nothing can resume it and no fresh registration
// replaces it, and whatever else of imsd's own is left (a policy-less state
// on the UE's address): taken out by exact key, as the SA setup takes imsd's
// previous pair out (RunOwnXfrmDeletes — nothing else in the kernel is
// touched, §12), so the next bring-up finds nothing to resume. Run by the
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// no-target bring-up and by main()'s idle before the bus name.
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
void RemoveDeadPair ( std : : string_view local ) {
auto state = RunCapture ( { " ip " , " xfrm " , " state " } ) ;
auto policy = RunCapture ( { " ip " , " xfrm " , " policy " } ) ;
auto cmds = imsd : : ipsec : : OwnXfrmDeleteCommands ( state . out , policy . out , local ) ;
if ( cmds . empty ( ) ) return ;
if ( auto peer = imsd : : ipsec : : SaPeer ( policy . out ) ) Log ( std : : format ( " the SA pair to {} is nothing to resume: removing it " , * peer ) ) ;
else Log ( std : : format ( " {} xfrm entr{} of imsd's own with no pair to resume: removing them " , cmds . size ( ) , cmds . size ( ) = = 1 ? " y " : " ies " ) ) ;
RunOwnXfrmDeletes ( cmds ) ;
}
2026-07-22 22:53:28 +02:00
// ---- small text extractors (401 header params, qmicli "completed:") -------
std : : optional < std : : string > QuotedAfter ( std : : string_view text , std : : string_view key ) {
std : : size_t at = text . find ( key ) ;
if ( at = = std : : string_view : : npos ) return std : : nullopt ;
std : : size_t start = at + key . size ( ) ;
std : : size_t end = text . find ( ' " ' , start ) ;
if ( end = = std : : string_view : : npos ) return std : : nullopt ;
return std : : string ( text . substr ( start , end - start ) ) ;
}
std : : optional < long > IntAfter ( std : : string_view text , std : : string_view key ) {
std : : size_t at = text . find ( key ) ;
if ( at = = std : : string_view : : npos ) return std : : nullopt ;
std : : size_t i = at + key . size ( ) ;
std : : size_t start = i ;
while ( i < text . size ( ) & & text [ i ] > = ' 0 ' & & text [ i ] < = ' 9 ' ) i + + ;
if ( i = = start ) return std : : nullopt ;
long v = 0 ;
std : : from_chars ( text . data ( ) + start , text . data ( ) + i , v ) ;
return v ;
}
// value after "completed:" — integer or the hex ("AB:CD:..") token
std : : optional < long > CompletedInt ( std : : string_view out ) {
return IntAfter ( out , " completed: " ) ;
}
std : : optional < std : : string > CompletedHex ( std : : string_view out ) {
std : : size_t at = out . find ( " completed: " ) ;
if ( at = = std : : string_view : : npos ) return std : : nullopt ;
std : : size_t i = at + 10 ;
while ( i < out . size ( ) & & ( out [ i ] = = ' ' | | out [ i ] = = ' \t ' ) ) i + + ;
std : : size_t start = i ;
auto ok = [ ] ( char c ) {
return ( c > = ' 0 ' & & c < = ' 9 ' ) | | ( c > = ' A ' & & c < = ' F ' ) | |
( c > = ' a ' & & c < = ' f ' ) | | c = = ' : ' ;
} ;
while ( i < out . size ( ) & & ok ( out [ i ] ) ) i + + ;
if ( i = = start ) return std : : nullopt ;
std : : string s ( out . substr ( start , i - start ) ) ;
std : : string h ;
for ( char c : s ) if ( c ! = ' : ' ) h . push_back ( static_cast < char > ( std : : tolower ( c ) ) ) ;
return h ;
}
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
// ---- the card, through qmicli's UIM logical channels ----------------------
// A logical channel to one application of the card: opened on the
// application's AID, closed when the object goes. Exchange sends one command
// and returns the card's answer to it; Transmit also sends what the card asks
// for after it (imsd::aka::ApduFollowUp, for an answer without data: GET
// RESPONSE for '61 XX', a command without data again with the length a
// '6C XX' names — two follow-ups at most) and returns the last answer.
// nullopt when one of the exchanges
// brought no answer with a status word back: qmicli printed none, or fewer
// than two bytes.
class UimChannel {
public :
UimChannel ( int slot , std : : string_view aid ) : slot_ ( slot ) {
auto open = RunCapture ( { " qmicli " , " -d " , " qrtr://0 " , std : : format ( " --uim-open-logical-channel={},{} " , slot , aid ) } ) ;
if ( auto ch = CompletedInt ( open . out ) ) channel_ = static_cast < int > ( * ch ) ;
}
UimChannel ( const UimChannel & ) = delete ;
UimChannel & operator = ( const UimChannel & ) = delete ;
~ UimChannel ( ) {
if ( channel_ > = 0 ) RunCapture ( { " qmicli " , " -d " , " qrtr://0 " , std : : format ( " --uim-close-logical-channel={},{} " , slot_ , channel_ ) } ) ;
}
bool Open ( ) const { return channel_ > = 0 ; }
int Number ( ) const { return channel_ ; }
std : : optional < imsd : : aka : : ApduAnswer > Exchange ( std : : string_view apdu ) const {
auto r = RunCapture ( { " qmicli " , " -d " , " qrtr://0 " , std : : format ( " --uim-send-apdu={},{},{} " , slot_ , channel_ , apdu ) } ) ;
auto hex = CompletedHex ( r . out ) ;
if ( ! hex ) return std : : nullopt ;
auto bytes = imsd : : util : : FromHex ( * hex ) ;
if ( ! bytes ) return std : : nullopt ;
return imsd : : aka : : ParseApduAnswer ( * bytes ) ;
}
std : : optional < imsd : : aka : : ApduAnswer > Transmit ( std : : string apdu ) const {
auto answer = Exchange ( apdu ) ;
for ( int i = 0 ; answer & & i < 2 ; i + + ) {
auto next = imsd : : aka : : ApduFollowUp ( channel_ , apdu , * answer ) ;
if ( ! next ) break ;
apdu = std : : move ( * next ) ;
answer = Exchange ( apdu ) ;
}
return answer ;
}
private :
int slot_ ;
int channel_ = - 1 ;
} ;
// Whether two identities are the same three names.
bool SameNames ( const imsd : : aka : : Identity & a , const imsd : : aka : : Identity & b ) {
return a . impi = = b . impi & & a . domain = = b . domain & & a . impu = = b . impu ;
}
// The identity the card's ISIM application holds (TS 24.229 5.1.1.1A): the
// private identity of EF_IMPI, the home domain of EF_DOMAIN and the public
// identity of EF_IMPU's first record (GSMA IR.92 2.2.1), read over a logical
// channel on the application with the commands that read two reporters'
// cards (AGENTS.md §13); a SELECT's '61 XX' is taken for the file selected
// and the control parameters it offers are not fetched, as there. nullopt,
// with `why` saying what was missing, when it gives none.
std : : optional < imsd : : aka : : Identity > ReadIsimIdentity ( int slot , const imsd : : aka : : IsimApp & app , const imsd : : aka : : Identity & derived , std : : string & why ) {
UimChannel ch ( slot , app . aid ) ;
if ( ! ch . Open ( ) ) { why = " no logical channel opened on it " ; return std : : nullopt ; }
auto read = [ & ] ( std : : uint16_t file , std : : string_view name , bool record ) - > std : : optional < std : : string > {
auto selected = ch . Exchange ( imsd : : aka : : BuildSelectFileApdu ( ch . Number ( ) , file ) ) ;
if ( ! selected ) { why = std : : format ( " {}: no answer with a status word to the SELECT " , name ) ; return std : : nullopt ; }
if ( ! imsd : : aka : : Selected ( * selected ) ) { why = std : : format ( " {}: the SELECT answered {} " , name , selected - > Status ( ) ) ; return std : : nullopt ; }
auto got = ch . Transmit ( record ? imsd : : aka : : BuildReadRecordApdu ( ch . Number ( ) , 1 ) : imsd : : aka : : BuildReadBinaryApdu ( ch . Number ( ) ) ) ;
if ( ! got ) { why = std : : format ( " {}: an exchange of the read brought no answer with a status word " , name ) ; return std : : nullopt ; }
if ( ! imsd : : aka : : HoldsRead ( * got ) ) { why = std : : format ( " {}: the read answered {} " , name , got - > Status ( ) ) ; return std : : nullopt ; }
auto value = imsd : : aka : : ParseIsimValue ( got - > data ) ;
if ( ! value ) why = std : : format ( " {}: no value in the {} bytes read " , name , got - > data . size ( ) ) ;
return value ;
} ;
auto impi = read ( imsd : : aka : : EfImpi , " EF_IMPI " , false ) ;
if ( ! impi ) return std : : nullopt ;
auto domain = read ( imsd : : aka : : EfDomain , " EF_DOMAIN " , false ) ;
if ( ! domain ) return std : : nullopt ;
auto impu = read ( imsd : : aka : : EfImpu , " EF_IMPU record 1 " , true ) ;
if ( ! impu ) return std : : nullopt ;
auto id = imsd : : aka : : IsimIdentity ( derived , * impi , * domain , * impu ) ;
if ( ! id ) why = std : : format ( " EF_IMPI '{}', EF_DOMAIN '{}' and EF_IMPU record 1 '{}' are no identity imsd can register " , * impi , * domain , * impu ) ;
return id ;
}
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
// The UE address on the ims PDN when LOCAL is not given: a global IPv6 on
// <dev> that is neither temporary nor RA-derived (`dynamic`) — the one
// ims-pdn-up.sh assigned from ModemManager — else the first non-temporary
// one, else the first. The kernel lists the temporary (privacy) address
// first, and registering on it binds Contact, Via and the SAs to an address
// that is deprecated after a day and removed after two (ims ledger F18).
2026-07-22 22:53:28 +02:00
std : : optional < std : : string > DetectLocal ( const std : : string & dev ) {
auto r = RunCapture ( { " ip " , " -6 " , " addr " , " show " , " dev " , dev , " scope " , " global " } ) ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
std : : optional < std : : string > first , nonTemporary , assigned ;
std : : size_t pos = 0 ;
while ( ( pos = r . out . find ( " inet6 " , pos ) ) ! = std : : string : : npos ) {
std : : size_t start = pos + 6 ;
pos = start ;
std : : size_t eol = r . out . find ( ' \n ' , start ) ;
if ( eol = = std : : string : : npos ) eol = r . out . size ( ) ;
std : : size_t slash = r . out . find ( ' / ' , start ) ;
if ( slash = = std : : string : : npos | | slash > eol ) continue ;
std : : string addr = r . out . substr ( start , slash - start ) ;
std : : string_view flags = std : : string_view ( r . out ) . substr ( slash , eol - slash ) ;
bool temporary = flags . contains ( " temporary " ) ;
bool dynamic = flags . contains ( " dynamic " ) ;
if ( ! first ) first = addr ;
if ( ! temporary & & ! nonTemporary ) nonTemporary = addr ;
if ( ! temporary & & ! dynamic & & ! assigned ) assigned = addr ;
}
if ( assigned ) return assigned ;
if ( nonTemporary ) return nonTemporary ;
return first ;
}
// Whether `addr` is configured on `dev` now. Compared as bytes, so any
// spelling of the address matches; when the interface list cannot be read
// the answer is yes — nothing here acts on a guess that it is gone.
bool OnLink ( const std : : string & dev , const std : : string & addr ) {
int fam = Is6 ( addr ) ? AF_INET6 : AF_INET ;
unsigned char want [ 16 ] = { } ;
if ( inet_pton ( fam , addr . c_str ( ) , want ) ! = 1 ) return false ;
ifaddrs * ifs = nullptr ;
if ( getifaddrs ( & ifs ) ! = 0 ) return true ;
bool found = false ;
for ( ifaddrs * i = ifs ; i & & ! found ; i = i - > ifa_next ) {
if ( ! i - > ifa_addr | | i - > ifa_addr - > sa_family ! = fam | | dev ! = i - > ifa_name ) continue ;
const void * have = fam = = AF_INET6 ? static_cast < const void * > ( & reinterpret_cast < sockaddr_in6 * > ( i - > ifa_addr ) - > sin6_addr )
: static_cast < const void * > ( & reinterpret_cast < sockaddr_in * > ( i - > ifa_addr ) - > sin_addr ) ;
found = std : : memcmp ( have , want , fam = = AF_INET6 ? 16 : 4 ) = = 0 ;
}
freeifaddrs ( ifs ) ;
return found ;
2026-07-22 22:53:28 +02:00
}
imsd, media: aim call audio at logind's seat0 session, not an account named `user`
imsd-media defaulted AUDIO_USER to `user`, postmarketOS's default
account name, and with no such account a call had no audio on the phone
and noise at the far end, the message only in imsd-media's stderr, at
each call. A field user found it by trial (alyx report 14, 2026-09-20;
ims ledger F14).
Have imsd, as packaged (root, on the system bus), resolve the session
from logind when a call's media starts — the user session active on
seat0 (a greeter is not one) when it has a PipeWire socket — and hand it
to imsd-media as AUDIO_USER; set in imsd's own environment to an
account's name, AUDIO_USER pins that account instead. imsd as packaged
(root, on the system bus) logs the resolution at start, before the first
call, and when a call's media starts.
No session is an empty AUDIO_USER. imsd-media started without the
variable at all keeps `user`: that is an imsd older than 0.3.10, still
running while an upgrade replaces the helper under it, whose calls would
otherwise be silent until the restart, or a hand run.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-25 17:15:02 +02:00
// The account whose PipeWire session carries call audio: AUDIO_USER when
// it names an account, else logind's seat0 session (`loginctl show-seat
// seat0` -> `show-session`) when that is a user session — not phrog's
// greeter — with a PipeWire socket. imsd-media gets the answer as
// AUDIO_USER. As packaged (root, on the system bus) imsd resolves it at
// start, so a wrong name or a missing session is in the journal before the
// first call rather than after two silent rounds of trial (alyx report 14,
// 2026-09-20), and again when a call's media starts, because the answer
// changes when someone logs in.
struct AudioSession { std : : string name ; unsigned uid = 0 ; std : : string how ; } ;
std : : string LoginctlProp ( std : : string_view text , std : : string_view key ) {
for ( auto line : std : : views : : split ( text , ' \n ' ) ) {
std : : string_view l ( line ) ;
if ( l . size ( ) > key . size ( ) & & l . starts_with ( key ) & & l [ key . size ( ) ] = = ' = ' ) return std : : string ( l . substr ( key . size ( ) + 1 ) ) ;
}
return { } ;
}
AudioSession ResolveAudioSession ( ) {
AudioSession s ;
passwd pw { } ;
passwd * res = nullptr ;
char buf [ 4096 ] ;
std : : string want = EnvOr ( " AUDIO_USER " , " " ) ;
if ( ! want . empty ( ) ) {
if ( getpwnam_r ( want . c_str ( ) , & pw , buf , sizeof buf , & res ) = = 0 & & res ) {
s . name = want ; s . uid = res - > pw_uid ; s . how = " AUDIO_USER " ;
return s ;
}
Log ( std : : format ( " AUDIO_USER '{}' is not an account; using logind's seat0 session instead " , want ) ) ;
}
auto seat = RunCapture ( { " loginctl " , " show-seat " , " seat0 " , " -p " , " ActiveSession " , " --value " } ) ;
std : : string id = seat . out ;
while ( ! id . empty ( ) & & ( id . back ( ) = = ' \n ' | | id . back ( ) = = ' ' ) ) id . pop_back ( ) ;
if ( seat . rc ! = 0 | | id . empty ( ) ) { s . how = " no session on seat0 " ; return s ; }
auto sess = RunCapture ( { " loginctl " , " show-session " , id , " -p " , " Name " , " -p " , " Class " , " -p " , " User " } ) ;
std : : string name = LoginctlProp ( sess . out , " Name " ) , cls = LoginctlProp ( sess . out , " Class " ) , uid = LoginctlProp ( sess . out , " User " ) ;
unsigned u = 0 ;
auto [ end , err ] = std : : from_chars ( uid . data ( ) , uid . data ( ) + uid . size ( ) , u ) ;
if ( sess . rc ! = 0 | | name . empty ( ) | | err ! = std : : errc { } | | end ! = uid . data ( ) + uid . size ( ) ) { s . how = std : : format ( " seat0 session {} not readable " , id ) ; return s ; }
if ( ! cls . starts_with ( " user " ) ) { s . how = std : : format ( " seat0 session {} is {}'s {} session, nobody logged in " , id , name , cls ) ; return s ; }
std : : error_code ec ;
if ( ! std : : filesystem : : exists ( std : : format ( " /run/user/{}/pipewire-0 " , u ) , ec ) ) { s . how = std : : format ( " seat0 session {} ({}) has no PipeWire socket in /run/user/{} " , id , name , u ) ; return s ; }
s . name = name ; s . uid = u ; s . how = std : : format ( " logind seat0 session {} " , id ) ;
return s ;
}
std : : string AudioSessionLine ( const AudioSession & s ) {
if ( ! s . name . empty ( ) ) return std : : format ( " audio session: {} (uid {}, {}) " , s . name , s . uid , s . how ) ;
return std : : format ( " audio session: none — {} " , s . how ) ;
}
void LogAudioSession ( ) {
AudioSession s = ResolveAudioSession ( ) ;
Log ( AudioSessionLine ( s ) + ( s . name . empty ( ) ? " ; looked up again at each call, set AUDIO_USER to pin one " : " " ) ) ;
}
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
// The P-CSCF a fresh registration goes to, from the environment: PCSCF=
// when set (one address, any spelling — a list is left as it came and
// refused at bring-up), else the first address of PCSCF_DISCOVERED=, the
// list the bring-up read from the PDN's PCO (comma-separated IPv6, PCO
// order). `discovered` and `rejected` get the list and what was not an
// IPv6 literal, for the caller's log lines.
std : : string FreshPcscfFromEnv ( std : : vector < std : : string > * discovered = nullptr , std : : vector < std : : string > * rejected = nullptr ) {
std : : string configured = imsd : : util : : CanonicalAddr ( EnvOr ( " PCSCF " , " " ) ) ;
std : : vector < std : : string > list = imsd : : util : : ParseAddressList ( EnvOr ( " PCSCF_DISCOVERED " , " " ) , rejected ) ;
if ( discovered ) * discovered = list ;
if ( ! configured . empty ( ) ) return configured ;
return list . empty ( ) ? std : : string ( ) : list . front ( ) ;
}
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// The no-target bring-up's two outcomes, told apart by the script's word in
// /run/imsd.env (§7.3). The PCO naming no P-CSCF is a fact
// (PCSCF_DISCOVERY=none): a daemon with nothing to resume idles on it until
// a boot or a start. A reader that did not answer is not
// (PCSCF_DISCOVERY=failed): exit 1, and the unit's restart runs discovery
// again. Nothing here depends on a configuration file existing — installing
// the package and inserting a SIM is the opt-in.
bool DiscoveryFailed ( ) { return EnvOr ( " PCSCF_DISCOVERY " , " " ) = = " failed " ; }
constexpr std : : string_view NoPcscfIdleText = " no P-CSCF — none configured (PCSCF=), none discovered (see the ims-pdn-up lines) — and nothing to resume; set PCSCF= in /etc/imsd.env to name one " ;
constexpr std : : string_view NoPcscfDiscoveryFailed = " no P-CSCF: discovery failed (see the ims-pdn-up lines) and nothing to resume " ;
2026-07-22 22:53:28 +02:00
// ---- sockaddr helper ------------------------------------------------------
socklen_t MakeAddr ( std : : string_view ip , int port , sockaddr_storage & ss ) {
std : : memset ( & ss , 0 , sizeof ss ) ;
std : : string s ( ip ) ;
if ( Is6 ( ip ) ) {
auto * a = reinterpret_cast < sockaddr_in6 * > ( & ss ) ;
a - > sin6_family = AF_INET6 ; a - > sin6_port = htons ( static_cast < uint16_t > ( port ) ) ;
inet_pton ( AF_INET6 , s . c_str ( ) , & a - > sin6_addr ) ;
return sizeof ( sockaddr_in6 ) ;
}
auto * a = reinterpret_cast < sockaddr_in * > ( & ss ) ;
a - > sin_family = AF_INET ; a - > sin_port = htons ( static_cast < uint16_t > ( port ) ) ;
inet_pton ( AF_INET , s . c_str ( ) , & a - > sin_addr ) ;
return sizeof ( sockaddr_in ) ;
}
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
// The port a socket address names.
int PortOf ( const sockaddr_storage & ss ) {
return ss . ss_family = = AF_INET6 ? ntohs ( reinterpret_cast < const sockaddr_in6 * > ( & ss ) - > sin6_port ) : ntohs ( reinterpret_cast < const sockaddr_in * > ( & ss ) - > sin_port ) ;
}
2026-07-22 22:53:28 +02:00
// ---- SIP over the protected TCP flow --------------------------------------
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
enum class Transport { Tcp , Udp } ;
constexpr std : : string_view TransportName ( Transport t ) { return t = = Transport : : Udp ? " UDP " : " TCP " ; }
// The protected client flow: our requests to the P-CSCF's protected server
// port and their responses. TCP is the shape every carrier that works so far
// serves; UDP is the alternative for a P-CSCF that never answers the TCP
// connect (O2 UK, 2026-09-17). Both run through the same SA pair — the xfrm
// policies select on ports only — and the same Via port.
// A P-CSCF refusing a fresh security association (KPN: Security-Server
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// spi-s=0 to a fresh REGISTER on an address whose registration is still
// live). Handled in-process: a
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// systemd restart every RestartSec would never clear it.
struct ThrottledError : std : : runtime_error { using std : : runtime_error : : runtime_error ; } ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
// A REGISTER the network refused: the protected one, or a reregistration,
// answered with a final other than 200 (a reregistration's 401 asks for a
// re-authentication imsd does not do over the old SAs: a refusal carrying
// 401); the unprotected initial one answered with a final from 300 up (its
// 401 is the challenge). The status and its Retry-After feed
// imsd::engine::RegRecovery.
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
struct RefusedError : std : : runtime_error {
int status ;
long retryAfter ;
RefusedError ( const std : : string & what , int st , long ra ) : std : : runtime_error ( what ) , status ( st ) , retryAfter ( ra ) { }
} ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// Bytes of SIP that fit one ESP-protected IPv6 packet at the ims PDN's
// 1280-byte MTU (40 IPv6 + 8 ESP + 16 IV + 8 UDP + padding + 12 ICV).
constexpr std : : size_t UdpSinglePacketBudget = 1190 ;
sip, messages, imsd: the client flow answers a request datagram cut short of the Content-Length it reads with a 400, unless an ACK or a CANCEL
RFC 3261 18.3 on a datagram that ends before its message's body does:
"If the message is a response, it MUST be discarded. If the message is
a request, the element SHOULD generate a 400 (Bad Request) response."
The client flow's datagram read ignored either, where the
Content-Length it read said more bytes than came, with one line, `UDP:
datagram truncated (…) — ignored`.
CutShortRequest gives the header section of a request whose datagram
has fewer body bytes than the Content-Length read from it says, and
BuildBadRequest the 400 for it, in the shape of BuildResponse's finals:
every Via row echoed, the To tagged unless it holds a tag. The client
flow sends that 400 and its line ends `— answered 400`. Such a request
is known by its first line, which ends with the SIP version where a
status line begins with it (7.1, 7.2), in upper or in lower case: a
response cut short so, bytes that are no SIP cut short so and a
datagram without an end of headers are ignored as before. imsd keeps
nothing of a request it answers so, and follows 8.2.7 for an element
that answers without state: a To tag it adds is made from the
request's header section and a secret drawn once for the run, "in a
manner that will generate the same tag for the same request
consistently", and an ACK or a CANCEL cut short so gets no answer. The
server ports and the init port hand a datagram on as it came, as
before this commit.
Tested by tests/Sip (CutShortRequest: the header section of a request
cut short, with line breaks before it, under a compact Content-Length
and with its version in lower case; nothing for a body that is all
there, no Content-Length, no end of headers, a response in either
letter case, bytes that are no SIP, an ACK, a CANCEL) and by
tests/Messages (the 400 by its lines, its tag against Python's
hashlib; the same request, the same 400; another request or another
secret, another tag). On the workstation's loopback, SipFlow built
around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture,
cut-short, at this commit and at the one before): a MESSAGE with five
body bytes of nine draws the 400, and the same one when it is sent
again, where the commit before ignored it; a response cut short the
same way, in upper and in lower case, an ACK, a CANCEL, bytes that are
no SIP and a request without an end of headers draw nothing at either
commit; the MESSAGE with its Content-Length folded is handed on at
either commit, a folded value being read by its first line; a whole
request sent after them is returned by the flow.
2026-11-22 17:35:11 +01:00
// The secret in the To tag of a 400 to a request cut short
// (imsd::msg::BuildBadRequest): drawn at the first such request, the same
// until imsd stops.
const std : : string & BadRequestSecret ( ) {
static const std : : string secret = imsd : : util : : Rng ( ) . Token ( 16 ) ;
return secret ;
}
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
class SipFlow {
2026-07-22 22:53:28 +02:00
public :
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// TCP: connect up to `tries` times (12-s timeout each, 10 s apart). An
// attempt the network never answers counts towards `silentLimit` (0 =
// unlimited); an attempt refused locally — connect() itself failing:
// EADDRNOTAVAIL (the 4-tuple still in TIME_WAIT from the previous flow),
// ENETUNREACH (no route yet) — does not, so a restart within 60 s of the
// last one keeps retrying instead of concluding the P-CSCF is silent. UDP: bind the same client port and connect() the
// datagram socket to the same peer — the kernel then delivers that peer's
// datagrams here in preference to the unconnected ServerPorts socket on
// the same port. A UDP connect() cannot be refused by the peer, so it is
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
// one attempt. `tick` is called before every try and then before every
// second of a try's wait for its answer and of the pause before the
// next try: what the caller must do at least that often while this
// thread waits (the wake alarm, under a registration step and under
// the connect for a call's resend).
bool Connect ( const std : : string & local , int lport , const std : : string & pcscf , int pport , Transport t , int tries = 10 , int silentLimit = 0 ,
const std : : function < void ( ) > & tick = { } ) {
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
transport_ = t ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
lastConnectLocal_ = false ;
2026-07-22 22:53:28 +02:00
int fam = Is6 ( local ) ? AF_INET6 : AF_INET ;
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
if ( tick ) tick ( ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( t = = Transport : : Udp ) {
int fd = socket ( fam , SOCK_DGRAM , 0 ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( fd < 0 ) return SocketFailed ( ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
int one = 1 ;
setsockopt ( fd , SOL_SOCKET , SO_REUSEADDR , & one , sizeof one ) ;
setsockopt ( fd , SOL_SOCKET , SO_REUSEPORT , & one , sizeof one ) ;
sockaddr_storage la ; socklen_t ll = MakeAddr ( local , lport , la ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( ! Bind ( fd , la , ll , local , lport ) ) return false ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
sockaddr_storage pa ; socklen_t pl = MakeAddr ( pcscf , pport , pa ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( connect ( fd , reinterpret_cast < sockaddr * > ( & pa ) , pl ) ! = 0 ) {
// a UDP connect() cannot be refused by the peer: no route
// yet, and the like — local, like the TCP path's ENETUNREACH
Log ( std : : format ( " UDP connect: {} " , std : : strerror ( errno ) ) ) ;
close ( fd ) ; lastConnectLocal_ = true ; return false ;
}
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
fd_ = fd ; alive_ = true ; fb_ = { } ; sizeWarned_ = false ;
return true ;
}
int silent = 0 ;
2026-07-22 22:53:28 +02:00
for ( int attempt = 0 ; attempt < tries ; attempt + + ) {
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
if ( tick & & attempt > 0 ) tick ( ) ;
2026-07-22 22:53:28 +02:00
int fd = socket ( fam , SOCK_STREAM , 0 ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( fd < 0 ) return SocketFailed ( ) ;
2026-07-22 22:53:28 +02:00
int one = 1 ;
setsockopt ( fd , SOL_SOCKET , SO_REUSEADDR , & one , sizeof one ) ;
// REUSEPORT (paired with the listener's): a reconnect must bind
// the protected client port while the ServerPorts listener holds
// it in LISTEN state — REUSEADDR alone only covers TIME_WAIT.
setsockopt ( fd , SOL_SOCKET , SO_REUSEPORT , & one , sizeof one ) ;
sockaddr_storage la ; socklen_t ll = MakeAddr ( local , lport , la ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( ! Bind ( fd , la , ll , local , lport ) ) return false ;
2026-07-22 22:53:28 +02:00
sockaddr_storage pa ; socklen_t pl = MakeAddr ( pcscf , pport , pa ) ;
// non-blocking connect + poll: Linux connect() ignores SO_SNDTIMEO,
// so bound it ourselves (a silent P-CSCF must not hang the engine).
fcntl ( fd , F_SETFL , O_NONBLOCK ) ;
int rc = connect ( fd , reinterpret_cast < sockaddr * > ( & pa ) , pl ) ;
bool connected = ( rc = = 0 ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
bool localRefusal = ( rc < 0 & & errno ! = EINPROGRESS ) ;
int err = localRefusal ? errno : 0 ;
2026-07-22 22:53:28 +02:00
if ( rc < 0 & & errno = = EINPROGRESS ) {
pollfd p { fd , POLLOUT , 0 } ;
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
if ( PollTicked ( p , 12000 , tick ) > 0 ) {
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
socklen_t el = sizeof err ;
2026-07-22 22:53:28 +02:00
getsockopt ( fd , SOL_SOCKET , SO_ERROR , & err , & el ) ;
connected = ( err = = 0 ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
} else err = ETIMEDOUT ;
2026-07-22 22:53:28 +02:00
}
if ( connected ) {
fcntl ( fd , F_SETFL , fcntl ( fd , F_GETFL ) & ~ O_NONBLOCK ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
fd_ = fd ; alive_ = true ; fb_ = { } ; sizeWarned_ = false ;
2026-07-22 22:53:28 +02:00
return true ;
}
close ( fd ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
lastConnectLocal_ = localRefusal ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( ! localRefusal ) silent + + ;
// An answer (RST → ECONNREFUSED, ICMP → EHOSTUNREACH/ENETUNREACH)
// counts towards the silent limit like a timeout: either way the
// P-CSCF does not serve TCP on that port. The log says which.
const char * why = err = = ETIMEDOUT ? " no answer " : ( err = = EADDRNOTAVAIL ? " TIME_WAIT? " : std : : strerror ( err ) ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( attempt = = tries - 1 ) {
Log ( std : : format ( " connect failed ({}) [{}/{}] " , why , attempt + 1 , tries ) ) ;
return false ;
}
if ( silentLimit > 0 & & silent > = silentLimit ) {
Log ( std : : format ( " connect: no answer from the P-CSCF {} times ({}) " , silent , why ) ) ;
return false ;
}
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
Log ( std : : format ( " connect failed; retry in 10s ({}) [{}/{}] " , why , attempt + 1 , tries ) ) ;
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
for ( int s = 0 ; s < 10 ; s + + ) {
if ( tick ) tick ( ) ;
sleep ( 1 ) ;
}
2026-07-22 22:53:28 +02:00
}
return false ;
}
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
// poll(2) on one descriptor for `ms`, in pieces of a second with `tick`
// called before each where there is one. Answers as poll does.
static int PollTicked ( pollfd & p , int ms , const std : : function < void ( ) > & tick ) {
if ( ! tick ) return poll ( & p , 1 , ms ) ;
for ( ; ; ) {
tick ( ) ;
int piece = std : : min ( ms , 1000 ) ;
int r = poll ( & p , 1 , piece ) ;
if ( r ! = 0 | | ( ms - = piece ) < = 0 ) return r ;
}
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// socket() failing is ours, not the network's: logged, and a local
// refusal like a connect() the kernel turns down.
bool SocketFailed ( ) {
Log ( std : : format ( " connect failed: socket: {} " , std : : strerror ( errno ) ) ) ;
lastConnectLocal_ = true ;
return false ;
}
// A bind the kernel refuses (the address is not on the link:
// EADDRNOTAVAIL) is logged and counts like the network's silence — it is
// not a transient refusal to retry every 5 s. Closes fd on failure.
bool Bind ( int fd , const sockaddr_storage & la , socklen_t ll , const std : : string & local , int lport ) {
if ( bind ( fd , reinterpret_cast < const sockaddr * > ( & la ) , ll ) = = 0 ) return true ;
int err = errno ;
close ( fd ) ;
lastConnectLocal_ = false ;
Log ( std : : format ( " connect failed: cannot bind {} ({}) " , imsd : : util : : HostPort ( local , lport ) , std : : strerror ( err ) ) ) ;
return false ;
}
// Whether the last failed Connect() ended on a local refusal (our own
// 4-tuple still in TIME_WAIT, no route yet) rather than on the network's
// silence or answer — the recovery policy counts only the latter.
bool LastConnectLocal ( ) const { return lastConnectLocal_ ; }
2026-07-22 22:53:28 +02:00
// MSG_NOSIGNAL: a flow the network killed (CSFB excursion, P-CSCF idle
// drop) must surface as a send error, not a SIGPIPE.
bool Send ( std : : string_view msg ) {
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( transport_ = = Transport : : Udp & & msg . size ( ) > UdpSinglePacketBudget & & ! sizeWarned_ ) {
sizeWarned_ = true ;
Log ( std : : format ( " UDP: {} bytes of SIP exceed the single-packet ESP budget (~{}) at MTU 1280; the kernel sends it as IPv6 fragments — a P-CSCF that cannot reassemble ESP fragments drops it silently " , msg . size ( ) , UdpSinglePacketBudget ) ) ;
}
2026-07-22 22:53:28 +02:00
std : : size_t off = 0 ;
while ( off < msg . size ( ) ) {
ssize_t w = send ( fd_ , msg . data ( ) + off , msg . size ( ) - off , MSG_NOSIGNAL ) ;
if ( w < = 0 ) { alive_ = false ; return false ; }
off + = static_cast < std : : size_t > ( w ) ;
}
return true ;
}
void SendKeepalive ( ) {
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( transport_ = = Transport : : Udp ) return ; // RFC 5626 4.4.1: CRLF keepalives are for connection-oriented transports
2026-07-22 22:53:28 +02:00
if ( send ( fd_ , " \r \n \r \n " , 4 , MSG_NOSIGNAL ) < = 0 ) alive_ = false ;
}
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
// The next whole message on the flow, within `timeoutSec`. With a
// `tick` the wait for the socket is PollTicked's (Connect has what the
// tick is for).
std : : optional < std : : string > RecvMsg ( double timeoutSec , const std : : function < void ( ) > & tick = { } ) {
2026-07-22 22:53:28 +02:00
auto deadline = std : : chrono : : steady_clock : : now ( ) +
std : : chrono : : duration_cast < std : : chrono : : steady_clock : : duration > ( std : : chrono : : duration < double > ( timeoutSec ) ) ;
for ( ; ; ) {
if ( auto m = fb_ . TryExtract ( ) ) return m ;
auto now = std : : chrono : : steady_clock : : now ( ) ;
if ( now > = deadline ) return std : : nullopt ;
int ms = static_cast < int > ( std : : chrono : : duration_cast < std : : chrono : : milliseconds > ( deadline - now ) . count ( ) ) ;
pollfd p { fd_ , POLLIN , 0 } ;
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
int r = PollTicked ( p , ms , tick ) ;
2026-07-22 22:53:28 +02:00
if ( r < = 0 ) { if ( r = = 0 ) return std : : nullopt ; if ( errno = = EINTR ) continue ; return std : : nullopt ; }
imsd: what the client flow already holds is read before an SMS wait is judged
The run loop judged the wait of the message in flight — its MESSAGE's
final, its submit report — after draining the server ports and before
its read of the client flow. A final that had arrived in time and was
still unread at that pass counted as none: the segment was sent again —
before the repeat existed, the message failed — and the final then
found nothing to own (issue #3, the third of its three cases).
The pass now reads what the flow holds, without waiting, before it
judges: SipFlow::RecvReady returns a message that is whole in the frame
buffer or readable on the socket now. RecvMsg's read of the socket
moved into a helper both use (ReadOnce), and the handling of a message
read from the flow into OnFlowMessage, for the loop's two reads.
Tested on the workstation's loopback with the daemon's own SipFlow built
around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture,
flow-read): over TCP and over UDP RecvReady returns a message the socket
holds without waiting and none when it holds none, and RecvMsg waits its
time and returns a message when one comes; over TCP RecvReady leaves a
message that is not whole yet. On the dev phone the binary of this
range's last commit judged a report's wait at that pass, 130.06 s after
the final, and sent the repeat (the capture's phone-form6,
visit-journal.txt); the pass has not run with a final waiting unread:
that takes a final timed to it.
2026-11-22 17:35:13 +01:00
std : : optional < std : : string > m ;
if ( ! ReadOnce ( m ) ) return std : : nullopt ;
if ( m ) return m ;
}
}
// A message the flow already holds — whole in the frame buffer, or
// readable on the socket now — without waiting; none when it holds
// none whole.
std : : optional < std : : string > RecvReady ( ) {
for ( ; ; ) {
if ( auto m = fb_ . TryExtract ( ) ) return m ;
pollfd p { fd_ , POLLIN , 0 } ;
if ( poll ( & p , 1 , 0 ) < = 0 ) return std : : nullopt ;
std : : optional < std : : string > m ;
if ( ! ReadOnce ( m ) ) return std : : nullopt ;
if ( m ) return m ;
2026-07-22 22:53:28 +02:00
}
}
int Fd ( ) const { return fd_ ; }
bool Alive ( ) const { return fd_ > = 0 & & alive_ ; }
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
Transport CurrentTransport ( ) const { return transport_ ; }
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// What was read and not yet dispatched goes with the flow: nothing
// read from it can be answered once it is closed.
void Close ( ) { if ( fd_ > = 0 ) { close ( fd_ ) ; fd_ = - 1 ; } alive_ = false ; fb_ = { } ; }
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
// Close without the FIN's exchange: the kernel drops the connection at
// once (after the peer's FIN with a reset in our FIN's place; where a
// reset or its own giving up has ended it, it sends nothing), so the
// same local port can connect to the same peer again in the same
// breath. A socket closed with Close() after the peer's FIN stays in the
// kernel's table until the peer has acknowledged ours, and a connect from
// its port meanwhile is refused (EADDRNOTAVAIL). For a dead flow only.
void Abort ( ) {
if ( fd_ > = 0 ) { linger l { 1 , 0 } ; setsockopt ( fd_ , SOL_SOCKET , SO_LINGER , & l , sizeof l ) ; }
Close ( ) ;
}
2026-07-22 22:53:28 +02:00
private :
imsd: what the client flow already holds is read before an SMS wait is judged
The run loop judged the wait of the message in flight — its MESSAGE's
final, its submit report — after draining the server ports and before
its read of the client flow. A final that had arrived in time and was
still unread at that pass counted as none: the segment was sent again —
before the repeat existed, the message failed — and the final then
found nothing to own (issue #3, the third of its three cases).
The pass now reads what the flow holds, without waiting, before it
judges: SipFlow::RecvReady returns a message that is whole in the frame
buffer or readable on the socket now. RecvMsg's read of the socket
moved into a helper both use (ReadOnce), and the handling of a message
read from the flow into OnFlowMessage, for the loop's two reads.
Tested on the workstation's loopback with the daemon's own SipFlow built
around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture,
flow-read): over TCP and over UDP RecvReady returns a message the socket
holds without waiting and none when it holds none, and RecvMsg waits its
time and returns a message when one comes; over TCP RecvReady leaves a
message that is not whole yet. On the dev phone the binary of this
range's last commit judged a report's wait at that pass, 130.06 s after
the final, and sent the repeat (the capture's phone-form6,
visit-journal.txt); the pass has not run with a final waiting unread:
that takes a final timed to it.
2026-11-22 17:35:13 +01:00
// One read of the socket once poll(2) has named it: `m` is the message a
// datagram held (UDP); on TCP the bytes go to the frame buffer. False
// when the flow is dead and the caller has nothing more to read.
bool ReadOnce ( std : : optional < std : : string > & m ) {
char buf [ 65535 ] ;
ssize_t n = recv ( fd_ , buf , sizeof buf , 0 ) ;
if ( transport_ = = Transport : : Udp ) {
// One datagram = one message (RFC 3261 18.3): never accumulated
// across datagrams. An empty datagram is not EOF. A recv error
// is the kernel relaying an ICMP for the inner (decrypted) UDP
// — port unreachable → ECONNREFUSED, prohibited/policy → EACCES
// — i.e. the peer answering "no"; an ICMP quoting the ESP
// packet itself never reaches us (esp6_err ignores all but
// PKT_TOOBIG), so UDP has no dead-flow signal beyond these and
// the refresh timeouts.
if ( n < 0 ) {
if ( errno = = EAGAIN | | errno = = EWOULDBLOCK | | errno = = EINTR ) return true ;
Log ( std : : format ( " UDP flow: recv error: {} " , std : : strerror ( errno ) ) ) ;
alive_ = false ; return false ;
}
if ( n = = 0 ) return true ;
const std : : string_view d ( buf , static_cast < std : : size_t > ( n ) ) ;
std : : string why ;
m = imsd : : sip : : DatagramMessage ( d , & why ) ;
if ( ! m & & ! why . empty ( ) ) {
// A request cut short of its Content-Length is answered 400
// (RFC 3261 18.3; CutShortRequest says which); whatever else
// DatagramMessage refuses is ignored.
const auto head = imsd : : sip : : CutShortRequest ( d ) ;
Log ( std : : format ( " UDP: {} — {} " , why , head ? " answered 400 " : " ignored " ) ) ;
if ( head & & ! Send ( imsd : : msg : : BuildBadRequest ( * head , BadRequestSecret ( ) ) ) ) return false ;
}
return true ;
}
// EOF/RST is not a timeout: mark the flow dead so the engine's
// reconnect path notices within one loop turn instead of at the
// next (possibly 30-min-away) keepalive refresh.
if ( n < = 0 ) { alive_ = false ; return false ; }
fb_ . Append ( std : : string_view ( buf , static_cast < std : : size_t > ( n ) ) ) ;
return true ;
}
2026-07-22 22:53:28 +02:00
int fd_ = - 1 ;
bool alive_ = false ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
bool lastConnectLocal_ = false ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
Transport transport_ = Transport : : Tcp ;
bool sizeWarned_ = false ;
2026-07-22 22:53:28 +02:00
imsd : : sip : : FrameBuffer fb_ ;
} ;
// ---- protected-port listeners (terminating requests: remote BYE/UPDATE) ---
struct Inbound {
std : : string msg ;
std : : function < void ( const std : : string & ) > reply ;
} ;
class ServerPorts {
public :
void Open ( const std : : string & local ) {
int fam = Is6 ( local ) ? AF_INET6 : AF_INET ;
for ( int port : { PortUc , PortUs } ) {
int ls = socket ( fam , SOCK_STREAM , 0 ) ;
if ( ls > = 0 ) {
int one = 1 ;
setsockopt ( ls , SOL_SOCKET , SO_REUSEADDR , & one , sizeof one ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// paired with SipFlow::Connect's REUSEPORT (reconnect binds
2026-07-22 22:53:28 +02:00
// the client port while this listener holds it)
setsockopt ( ls , SOL_SOCKET , SO_REUSEPORT , & one , sizeof one ) ;
sockaddr_storage a ; socklen_t l = MakeAddr ( local , port , a ) ;
if ( bind ( ls , reinterpret_cast < sockaddr * > ( & a ) , l ) = = 0 & & listen ( ls , 4 ) = = 0 ) {
fcntl ( ls , F_SETFL , O_NONBLOCK ) ;
listeners_ . push_back ( ls ) ;
} else { close ( ls ) ; }
}
int us = socket ( fam , SOCK_DGRAM , 0 ) ;
if ( us > = 0 ) {
int one = 1 ;
setsockopt ( us , SOL_SOCKET , SO_REUSEADDR , & one , sizeof one ) ;
sockaddr_storage a ; socklen_t l = MakeAddr ( local , port , a ) ;
if ( bind ( us , reinterpret_cast < sockaddr * > ( & a ) , l ) = = 0 ) {
fcntl ( us , F_SETFL , O_NONBLOCK ) ;
udp_ . push_back ( us ) ;
if ( port = = PortUc ) udpUc_ = us ;
} else { close ( us ) ; }
}
Log ( std : : format ( " listening on protected port {} (TCP+UDP) " , port ) ) ;
}
}
std : : vector < Inbound > Poll ( ) {
std : : vector < Inbound > out ;
for ( int ls : listeners_ ) {
for ( ; ; ) {
int c = accept ( ls , nullptr , nullptr ) ;
if ( c < 0 ) break ;
fcntl ( c , F_SETFL , O_NONBLOCK ) ;
conns_ . push_back ( { c , { } } ) ;
}
}
for ( int us : udp_ ) {
for ( ; ; ) {
char buf [ 65535 ] ;
sockaddr_storage src ; socklen_t sl = sizeof src ;
ssize_t n = recvfrom ( us , buf , sizeof buf , 0 , reinterpret_cast < sockaddr * > ( & src ) , & sl ) ;
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
if ( n < 0 ) break ;
2026-07-22 22:53:28 +02:00
std : : string_view sv ( buf , static_cast < std : : size_t > ( n ) ) ;
bool blank = sv . find_first_not_of ( " \r \n \t " ) = = std : : string_view : : npos ;
if ( blank ) continue ;
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
// One datagram = one message, framed as on the client flow
// (RFC 3261 18.3): bytes past its Content-Length are
// discarded; a request whose body is shorter than its
// Content-Length is answered 400 (CutShortRequest says
// which), the way any answer goes from here (below);
// whatever else DatagramMessage refuses is ignored with a
// line. One of white space alone, or of no bytes, was
// passed over above.
std : : string why ;
auto framed = imsd : : sip : : DatagramMessage ( sv , & why ) ;
bool cutShort = false ;
if ( ! framed ) {
framed = imsd : : sip : : CutShortRequest ( sv ) ;
cutShort = framed . has_value ( ) ;
}
if ( ! framed ) {
if ( ! why . empty ( ) ) Log ( std : : format ( " UDP: {} on server socket {} — ignored " , why , us = = udpUc_ ? PortUc : PortUs ) ) ;
continue ;
}
std : : string msg = std : : move ( * framed ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( imsd : : sip : : Status ( msg ) . has_value ( ) ) {
// A response here means the P-CSCF answered to the Via port
// instead of the source port of our request (rport) — it
// never reaches the client flow. Say so.
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
Log ( std : : format ( " UDP response on server socket {} from port {} ignored: {} " , us = = udpUc_ ? PortUc : PortUs , PortOf ( src ) , std : : string_view ( msg ) . substr ( 0 , msg . find ( " \r \n " ) ) ) ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
continue ;
}
2026-07-22 22:53:28 +02:00
if ( ! imsd : : sip : : Status ( msg ) . has_value ( ) ) { // request only
sockaddr_storage s = src ; socklen_t sll = sl ;
int rs = us ;
// RFC 3261 18.2.2: rport-less UDP requests get their
// response at the Via sent-by port, not the source
// port. KPN's P-CSCF sends in-dialog requests from its
// protected client port but silently drops responses
// sent back there (s57: every UPDATE/BYE 200 ignored,
// audit kills the call); the Via port is its protected
// server port, whose SA pairs with OUR client-port
// socket — respond from that one so the uc->ps SA
// carries it.
if ( auto vp = imsd : : sip : : ViaResponsePort ( msg ) ) {
if ( s . ss_family = = AF_INET6 )
reinterpret_cast < sockaddr_in6 * > ( & s ) - > sin6_port =
htons ( static_cast < uint16_t > ( * vp ) ) ;
else
reinterpret_cast < sockaddr_in * > ( & s ) - > sin_port =
htons ( static_cast < uint16_t > ( * vp ) ) ;
if ( udpUc_ > = 0 ) rs = udpUc_ ;
}
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
auto reply = [ rs , s , sll ] ( const std : : string & r ) mutable {
2026-07-22 22:53:28 +02:00
sendto ( rs , r . data ( ) , r . size ( ) , 0 , reinterpret_cast < sockaddr * > ( & s ) , sll ) ;
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
} ;
if ( cutShort ) {
Log ( std : : format ( " UDP: {} on server socket {} — answered 400 " , why , us = = udpUc_ ? PortUc : PortUs ) ) ;
reply ( imsd : : msg : : BuildBadRequest ( msg , BadRequestSecret ( ) ) ) ;
continue ;
}
out . push_back ( { std : : move ( msg ) , std : : move ( reply ) } ) ;
2026-07-22 22:53:28 +02:00
}
}
}
for ( auto it = conns_ . begin ( ) ; it ! = conns_ . end ( ) ; ) {
bool eof = false ;
for ( ; ; ) {
char buf [ 65535 ] ;
ssize_t n = recv ( it - > fd , buf , sizeof buf , 0 ) ;
if ( n = = 0 ) { eof = true ; break ; }
if ( n < 0 ) break ;
it - > fb . Append ( std : : string_view ( buf , static_cast < std : : size_t > ( n ) ) ) ;
}
while ( auto m = it - > fb . TryExtract ( ) ) {
if ( ! imsd : : sip : : Status ( * m ) . has_value ( ) ) {
int fd = it - > fd ;
out . push_back ( { * m , [ fd ] ( const std : : string & r ) {
( void ) ! write ( fd , r . data ( ) , r . size ( ) ) ;
} } ) ;
}
}
if ( eof ) { close ( it - > fd ) ; it = conns_ . erase ( it ) ; } else { + + it ; }
}
return out ;
}
void CloseAll ( ) {
for ( int f : listeners_ ) close ( f ) ;
for ( int f : udp_ ) close ( f ) ;
for ( auto & c : conns_ ) close ( c . fd ) ;
listeners_ . clear ( ) ; udp_ . clear ( ) ; conns_ . clear ( ) ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
udpUc_ = - 1 ;
2026-07-22 22:53:28 +02:00
}
private :
struct Conn { int fd ; imsd : : sip : : FrameBuffer fb ; } ;
int udpUc_ = - 1 ;
std : : vector < int > listeners_ , udp_ ;
std : : vector < Conn > conns_ ;
} ;
// ---- registration state ---------------------------------------------------
struct RegState {
std : : string callid , ftag ;
long cseq = 2 ;
std : : uint32_t spiUc = 0 ;
std : : uint32_t spiUs = 0 ;
long expiry = 0 ;
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
// The card application the challenge goes to, by its slot and AID: the
// ISIM when the card's identity was read from it, else the USIM.
2026-07-22 22:53:28 +02:00
int slot = 0 ;
std : : string aid ;
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
// The identity this registration was made under. Set on the fresh 200
// and when a resume takes its state file's (the file's since 1.2.3; the
// derived one for an older file, as 1.2.2 wrote it for a registration
// under it); empty before the first of either.
imsd : : aka : : Identity id ;
2026-07-22 22:53:28 +02:00
// Contact user-part of the stored binding (UUID since the s53 oracle
// diff; empty = legacy IMSI binding from an older state file).
std : : string contactUser ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
// The answer to the last challenge — the 401's nonce, our cnonce and
// the response — which every reregistration carries verbatim (TS
// 24.229 5.1.1.4.2 a). Empty = a registration resumed from a pre-0.3.11
// state file; its reregistrations carry an empty digest, the pre-0.3.11
// shape, until the next fresh registration.
std : : string authNonce , authCnonce , authResponse ;
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
// The Security-Verify this registration's protected REGISTERs, its
// reg-event SUBSCRIBE and its INVITEs echo: the 401's whole
// Security-Server list (RFC 3329 §2.3.1). Set on the fresh 200 and at
// the resume, never from an attempt in flight:
// the member ss_ holds a fresh attempt's 401 before that attempt can
// still abort (the throttle, an unsupported mechanism), and the
// standing registration's state writes must not store it.
std : : string securityServer ;
2026-07-22 22:53:28 +02:00
} ;
// Writable directory for the daemon's own files: the persisted registration
// context, media stats, and optional debug dumps. Root daemon (the packaged
// service): /var/lib/imsd; --session/dev runs: the XDG state dir.
std : : string StateDir ( ) {
if ( geteuid ( ) = = 0 ) return " /var/lib/imsd " ;
if ( const char * x = std : : getenv ( " XDG_STATE_HOME " ) ) return std : : format ( " {}/imsd " , std : : string ( x ) ) ;
return std : : format ( " {}/.local/state/imsd " , EnvOr ( " HOME " , " /tmp " ) ) ;
}
// tiny JSON reader/writer for the persisted registration context.
std : : string StatePath ( ) { return EnvOr ( " STATE_FILE " , std : : format ( " {}/imsreg.state " , StateDir ( ) ) ) ; }
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// The next TP-MR, kept across restarts (TS 23.040 9.2.3.6's intent without
// the (U)SIM's EF_SMSS): one decimal number in <state dir>/sms-tpmr.
std : : string TpMrPath ( ) { return std : : format ( " {}/sms-tpmr " , StateDir ( ) ) ; }
std : : optional < std : : uint8_t > LoadTpMr ( ) {
std : : ifstream in ( TpMrPath ( ) ) ;
int v = - 1 ;
if ( ! ( in > > v ) | | v < 0 | | v > 255 ) return std : : nullopt ;
return static_cast < std : : uint8_t > ( v ) ;
}
void SaveTpMr ( std : : uint8_t mr ) {
std : : error_code ec ;
std : : filesystem : : create_directories ( StateDir ( ) , ec ) ;
const std : : string tmp = TpMrPath ( ) + " .tmp " ;
{ std : : ofstream out ( tmp , std : : ios : : trunc ) ; out < < static_cast < int > ( mr ) < < ' \n ' ; }
std : : rename ( tmp . c_str ( ) , TpMrPath ( ) . c_str ( ) ) ; // a torn write must not read as a number
}
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
// `security_server` is the registration's Security-Verify (RegState's
// securityServer: the 401's joined list); a resume takes it from here
// since 0.3.12. The file's values are quoted without escaping; a value
// with a quote, a backslash or a newline in it (none RFC 3329's token
// syntax produces) is written empty, and the resume falls back to the SA.
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
// `impi`, `domain` and `impu` (since 1.2.3) are the identity the
// registration was made under, which a resume keeps (TryResume); the three
// have passed imsd::aka::IsimIdentity or are MakeIdentity's, so none holds
// a character the quoting cannot carry.
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
void PersistState ( const RegState & r , const std : : string & route , const std : : string & ppi , const std : : string & aor , const std : : string & transport , const std : : string & pcscf ) {
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
std : : string ss = r . securityServer . find_first_of ( " \" \\ \n " ) = = std : : string : : npos ? r . securityServer : std : : string ( ) ;
2026-07-22 22:53:28 +02:00
std : : string j = std : : format (
" {{ \" callid \" : \" {} \" , \" ftag \" : \" {} \" , \" cseq \" : {}, \" spi_uc \" : {}, "
" \" spi_us \" : {}, \" expiry \" : {}, \" route \" : \" {} \" , \" ppi \" : \" {} \" , "
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
" \" aor \" : \" {} \" , \" contact_user \" : \" {} \" , \" transport \" : \" {} \" , "
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
" \" auth_nonce \" : \" {} \" , \" auth_cnonce \" : \" {} \" , \" auth_response \" : \" {} \" , "
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
" \" security_server \" : \" {} \" , \" pcscf \" : \" {} \" , "
" \" impi \" : \" {} \" , \" domain \" : \" {} \" , \" impu \" : \" {} \" }} " ,
messages: sign our requests with the public identity, not the IMSI IMPU
Every request we originated — INVITE, CANCEL, both ACKs, in-dialog BYE and
friends — put the IMSI-derived temporary IMPU in From. 3GPP allows that
identity in REGISTER only; the same lesson was learned for the reg-event
SUBSCRIBE (480) and never carried to calls. Most P-CSCFs overwrite From
and hid it; a Telia node did not, and a reporter's IMSI appeared on the
callee's screen (field report 2026-09-01). A strict P-CSCF may reject the
INVITE outright.
CallerId(): the registered sip: public identity (P-Associated-URI), else
the tel: one, and the temporary IMPU only before either is learned. One
helper feeds all five builders, so a dialog's From never drifts. As UAS the
dialog's local URI is the INVITE's To (RFC 3261 12.2.1.1), stored on the
Dialog, so an incoming call's BYE is signed the way the network addressed
us. The identity is persisted in the state file and restored on warm
resume, so a call placed before the refresh 200 re-learns it cannot fall
back. DUMP_SIP now also writes the last outgoing INVITE
(imsd-invite-out.raw): the one request a field log could never show.
The byte-pinned INVITE fixture moves to the tel: identity its test context
knows; new scenarios cover the sip: identity, the tel: fallback, the
pre-learning case and the UAS BYE.
Bench-verified on KPN 2026-09-08: outgoing INVITE From is the registered
sip: identity, call accepted and carried; caller ID at the far end
unchanged.
2026-09-08 20:37:47 +02:00
r . callid , r . ftag , r . cseq , r . spiUc , r . spiUs , r . expiry , route , ppi , aor ,
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
r . contactUser , transport , r . authNonce , r . authCnonce , r . authResponse , ss , pcscf ,
r . id . impi , r . id . domain , r . id . impu ) ;
2026-07-22 22:53:28 +02:00
std : : string path = StatePath ( ) ;
std : : error_code ec ;
std : : filesystem : : create_directories ( std : : filesystem : : path ( path ) . parent_path ( ) , ec ) ;
if ( std : : FILE * f = std : : fopen ( path . c_str ( ) , " w " ) ) {
std : : fwrite ( j . data ( ) , 1 , j . size ( ) , f ) ;
std : : fclose ( f ) ;
}
}
sip: a received message's header section is unfolded where it is framed
RFC 3261 7.3.1 lets a header value go on over further lines, each begun
with a space or a tab: "The line break and the whitespace at the
beginning of the next line are treated as a single SP character." The
text layer read a header from one line, so of a folded value it had the
first line only. Networks fold: KPN's 401 to the unprotected REGISTER
of 2026-07-18 and Odido's of 2026-07-13 had the WWW-Authenticate over
four lines (AGENTS.md §13; imsd finds a 401's nonce by a search of the
whole message, on a continuation line as on any other). A
Security-Server folded the same way would be read by its first line
alone, without the SPIs and ports on the further lines, and the
bring-up deferred; a short message whose Content-Type stands on a
continuation line would be taken for a page-mode text, answered 200
and never shown; a folded Content-Length on a connection would frame
no body, and the body's bytes begin the next message.
Unfolded takes the folds out of a header section, and the two framers
— FrameBuffer::TryExtract for a stream, DatagramMessage for a datagram
— hand a message on with its header section unfolded and its body as
it came; the Content-Length that frames the body is read from the
unfolded section. CutShortRequest reads its Content-Length so too, and
the header section it gives for the 400 is unfolded. Every socket imsd
reads SIP from goes through one of the two framers, so each reader of
a header still reads one line. A DUMP_SIP dump of a received message
holds it as framed.
Jorijn's decision of 2026-11-21 ("Unfold now").
Tested by tests/Sip — Unfolded on 7.3.1's own example, a tab, a bare LF,
a value begun on the next line and a line break that nothing follows;
both framers on a 401 whose WWW-Authenticate goes over four lines and
whose Content-Length is folded; CutShortRequest on a request cut short
of a folded Content-Length; ViaResponsePort on a Via list folded after
its comma, through the datagram framer — and by tests/Engine, a
delivered MESSAGE whose Content-Type came folded. On the workstation's
loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, init-port,
server-ports and cut-short, at this commit and at the one before): a
stand-in's 401 with its Security-Server over three lines gives the whole
value, where the commit before deferred the bring-up for want of SPIs; a
request with its Content-Type and Content-Length on continuation lines
comes out of the server ports unfolded and framed by that length, as a
datagram and over a connection; a request cut short of a folded
Content-Length, its Via on a continuation line, is answered 400 with its
Via whole, on a server port and on the client flow, where the commit
before did not read the folded length and handed the request on as it
came; a request on a server port whose Via row is a list folded after
its comma, `rport` on its lower value, is answered from the client-port
socket, the way to the port its top value names, as at the commit
before. On the dev phone the binary of this range's last commit
registered fresh on KPN after a reboot; the 401 was not dumped, so
whether it came folded that time is not on record. A MESSAGE the phone
sent to its own protected server port, its Via row a list folded after
its comma with `rport` on the lower value, was answered from the
client-port socket (the capture's phone-form6, fresh-check.log and
inject-bench.log).
2026-11-22 17:35:12 +01:00
// A dump of a SIP message for offline reading (the README's DUMP_SIP row
// lists the dumps): one imsd received, as its framer hands it on — bytes
// past its body gone, its folded header lines joined — or one of its own,
// dumped before the send is tried. One file per kind, overwritten by the
// next dump of its kind. The dumps carry the subscriber's IMSI/MSISDN and
// addresses, so they are opt-in (DUMP_SIP=1) and mode 0600.
2026-07-22 22:53:28 +02:00
void DumpRaw ( std : : string_view name , std : : string_view msg ) {
if ( EnvOr ( " DUMP_SIP " , " 0 " ) ! = " 1 " ) return ;
std : : string path = std : : format ( " {}/{} " , EnvOr ( " DUMP_DIR " , StateDir ( ) ) , name ) ;
int fd = open ( path . c_str ( ) , O_WRONLY | O_CREAT | O_TRUNC , 0600 ) ;
if ( fd < 0 ) return ;
( void ) ! write ( fd , msg . data ( ) , msg . size ( ) ) ;
close ( fd ) ;
}
struct PersistedState {
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
std : : optional < std : : string > callid , ftag , route , ppi , aor , contactUser , transport , authNonce , authCnonce , authResponse , securityServer , pcscf , impi , domain , impu ;
2026-07-22 22:53:28 +02:00
std : : optional < long > cseq , spiUc , spiUs , expiry ;
} ;
std : : optional < PersistedState > LoadState ( ) {
std : : FILE * f = std : : fopen ( StatePath ( ) . c_str ( ) , " r " ) ;
if ( ! f ) return std : : nullopt ;
std : : string s ;
char buf [ 1024 ] ; std : : size_t n ;
while ( ( n = std : : fread ( buf , 1 , sizeof buf , f ) ) > 0 ) s . append ( buf , n ) ;
std : : fclose ( f ) ;
PersistedState ps ;
ps . callid = QuotedAfter ( s , " \" callid \" : \" " ) ;
ps . ftag = QuotedAfter ( s , " \" ftag \" : \" " ) ;
ps . route = QuotedAfter ( s , " \" route \" : \" " ) ;
ps . ppi = QuotedAfter ( s , " \" ppi \" : \" " ) ;
messages: sign our requests with the public identity, not the IMSI IMPU
Every request we originated — INVITE, CANCEL, both ACKs, in-dialog BYE and
friends — put the IMSI-derived temporary IMPU in From. 3GPP allows that
identity in REGISTER only; the same lesson was learned for the reg-event
SUBSCRIBE (480) and never carried to calls. Most P-CSCFs overwrite From
and hid it; a Telia node did not, and a reporter's IMSI appeared on the
callee's screen (field report 2026-09-01). A strict P-CSCF may reject the
INVITE outright.
CallerId(): the registered sip: public identity (P-Associated-URI), else
the tel: one, and the temporary IMPU only before either is learned. One
helper feeds all five builders, so a dialog's From never drifts. As UAS the
dialog's local URI is the INVITE's To (RFC 3261 12.2.1.1), stored on the
Dialog, so an incoming call's BYE is signed the way the network addressed
us. The identity is persisted in the state file and restored on warm
resume, so a call placed before the refresh 200 re-learns it cannot fall
back. DUMP_SIP now also writes the last outgoing INVITE
(imsd-invite-out.raw): the one request a field log could never show.
The byte-pinned INVITE fixture moves to the tel: identity its test context
knows; new scenarios cover the sip: identity, the tel: fallback, the
pre-learning case and the UAS BYE.
Bench-verified on KPN 2026-09-08: outgoing INVITE From is the registered
sip: identity, call accepted and carried; caller ID at the far end
unchanged.
2026-09-08 20:37:47 +02:00
ps . aor = QuotedAfter ( s , " \" aor \" : \" " ) ;
2026-07-22 22:53:28 +02:00
ps . contactUser = QuotedAfter ( s , " \" contact_user \" : \" " ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
ps . transport = QuotedAfter ( s , " \" transport \" : \" " ) ; // absent in pre-0.3.5 files: TCP
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
ps . authNonce = QuotedAfter ( s , " \" auth_nonce \" : \" " ) ; // the three absent in pre-0.3.11 files
ps . authCnonce = QuotedAfter ( s , " \" auth_cnonce \" : \" " ) ;
ps . authResponse = QuotedAfter ( s , " \" auth_response \" : \" " ) ;
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
ps . securityServer = QuotedAfter ( s , " \" security_server \" : \" " ) ; // absent in pre-0.3.12 files
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
ps . pcscf = QuotedAfter ( s , " \" pcscf \" : \" " ) ; // absent in pre-1.0.0 files
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
ps . impi = QuotedAfter ( s , " \" impi \" : \" " ) ; // the three absent in pre-1.2.3 files
ps . domain = QuotedAfter ( s , " \" domain \" : \" " ) ;
ps . impu = QuotedAfter ( s , " \" impu \" : \" " ) ;
2026-07-22 22:53:28 +02:00
ps . cseq = IntAfter ( s , " \" cseq \" : " ) ;
ps . spiUc = IntAfter ( s , " \" spi_uc \" : " ) ;
ps . spiUs = IntAfter ( s , " \" spi_us \" : " ) ;
ps . expiry = IntAfter ( s , " \" expiry \" : " ) ;
return ps ;
}
// ---- daemon-level shared state (main thread only) -------------------------
struct CallInfo {
std : : string uni , number , state , reason ;
std : : int64_t startedAt = 0 ;
std : : int64_t answeredAt = 0 ;
std : : string direction = " outgoing " ;
} ;
struct StatusSnapshot {
bool registered = false ;
std : : string local , pcscf , ppi ;
std : : int64_t expiry = 0 ;
std : : int64_t cseq = 0 ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
std : : string smsc ; // the service centre a submission goes to (empty: none known)
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
std : : string simOperator ; // the SIM's operator id: MCC then MNC, as ModemManager gives it (empty: no SIM read when the status was taken)
2026-07-22 22:53:28 +02:00
} ;
// engine -> main-loop event
struct Event {
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
enum class Type { Added , State , Deleted , Registration , Status , Fatal , Idle , SmsReceived , SmsState , Work } type ;
2026-07-22 22:53:28 +02:00
CallInfo info ; // Added
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
std : : string uni , state , reason ; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id)
2026-07-22 22:53:28 +02:00
StatusSnapshot status ; // Registration/Status
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
std : : string text ; // Fatal, Idle
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
imsd : : engine : : SmsReceived sms ; // SmsReceived
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
std : : int64_t at = 0 ; // SmsReceived: when it arrived (epoch seconds)
imsd, engine: a received text records the subscriber it arrived for
The Messaging interface gave a received text with its sender and the
service centre but not the subscriber it was for. A consumer completing a
national-form sender with a country code had to take the code from the
daemon's status at import time, which is the wrong moment: the daemon
keeps a text on disk until an app deletes it, so the app that imports it
after a SIM change knows only the new SIM's code, and a national number
under the old SIM's plan is keyed, and replied to, under the new one —
another subscriber. Only the daemon knows at receipt which subscriber a
text arrived for. The stored record and the Received and List
dictionaries carry it
as `to`: the own number the daemon holds at the moment of receipt — the
first tel: P-Associated-URI of this run's latest answer to a fresh
registration, a resume or a reconnect that carried one (a periodic
refresh's answer is not read for it) and, until the first such, the
state file's once a resume attempt has taken it up. The key is absent
while the daemon holds none.
It is additive: an app that does not know it ignores it, and a record
without it reads as before. The value comes from a header, so the
emission makes it valid UTF-8, as it does a failed submission's reason.
Tested: tests/Engine, the record round trip with `to` and a record
without it.
2026-11-02 20:54:15 +01:00
std : : string to ; // SmsReceived: the subscriber it arrived for (the own number the daemon held then)
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
std : : string simOperator ; // SmsReceived: the operator id of the SIM it arrived under
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
bool on = false ; // Work: a registration step or a text's sending wants the work's lock (true: at its begin, after its wait for a hold) or no longer does (at its end, for such a wait)
2026-07-22 22:53:28 +02:00
} ;
GDBusConnection * DbusConn = nullptr ;
std : : map < std : : string , CallInfo > Calls ; // main thread only
StatusSnapshot StatusSnap ; // main thread only
GMainLoop * MainLoop = nullptr ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
bool FatalExit = false ; // set by an engine-fatal event: main() exits non-zero so systemd restarts us
2026-07-22 22:53:28 +02:00
std : : int64_t NowEpoch ( ) {
return std : : chrono : : duration_cast < std : : chrono : : seconds > ( std : : chrono : : system_clock : : now ( ) . time_since_epoch ( ) ) . count ( ) ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// The recovery policy's holds, kept for the next process: the network's
// word (a Retry-After, the schedule after a refused or throttled fresh
packaging: restart imsd and imsd-ofonod on upgrade
An upgrade left the old imsd and imsd-ofonod running until they were
next restarted, while a changed bus policy is live the moment apk writes
it: dbus-broker-launch reloads on its own. A policy that relies on a
check inside the daemons would face the old daemons in between.
Mark imsd.service and imsd-ofonod.service needs-restart in post-upgrade
scripts; the systemd trigger restarts them once the transaction is done
(enqueue-marked). A call in progress ends. The same scripts run as
post-install: `apk del` removes a package's files and leaves its daemon
running, so a later `apk add` of the package is this upgrade for that
daemon — and apk runs the post-install script, not post-upgrade, for a
package it adds. GNOME Calls 50.0 dials nothing after imsd-ofonod
restarts under it until it restarts too, so imsd-ofonod's ExecStartPost
restarts the Calls daemon of each user running one — not at the unit's
first start since boot, when a Calls that runs already is left alone.
A daemon older than 0.3.10 kept its bring-up throttle wait in memory
only, so a restart lost it. imsd's post-upgrade records that daemon's
invocation, and imsd-handover.sh, an ExecStartPre after ims-pdn-up.sh,
reads the invocation's journal and, while the fresh-SA throttle's wait
it finds there still runs (`spi-s=0`; the old daemon's other deferrals
are not handed over), writes what is left of it to the holds file when
this start's LOCAL is the address the wait was earned on, or when that
address cannot be read; when LOCAL is another address, only the verdict
that the old registration is gone.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-04 00:09:37 +02:00
// attempt, a terminated binding's wait) outlives a restart of imsd, and
// an upgrade restarts it. They are filed under the PDN's address —
// another one, or a reboot, starts clean — so the file names that
// address and the boot, and lives in /run. Seconds left at
// `written_at`, which is on the boot clock: no clock step moves it, and
// it runs through a suspend as the network's timers do. Whether the old
// registration is gone travels with them: a restart inside a hold must
// not resume over SAs the network has written off.
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
std : : int64_t BootSeconds ( ) {
timespec ts { } ;
clock_gettime ( CLOCK_BOOTTIME , & ts ) ;
return ts . tv_sec ;
}
std : : string BootId ( ) {
std : : string id ;
if ( std : : FILE * f = std : : fopen ( " /proc/sys/kernel/random/boot_id " , " r " ) ) {
char buf [ 64 ] ;
id . assign ( buf , std : : fread ( buf , 1 , sizeof buf , f ) ) ;
std : : fclose ( f ) ;
}
while ( ! id . empty ( ) & & std : : isspace ( static_cast < unsigned char > ( id . back ( ) ) ) ) id . pop_back ( ) ;
return id ;
}
// The recovery policy runs on the same clock: a hold in the process and
// its copy in the file age alike, through a suspend as the network's
// timers do.
double Boot ( ) {
timespec ts { } ;
clock_gettime ( CLOCK_BOOTTIME , & ts ) ;
return static_cast < double > ( ts . tv_sec ) + static_cast < double > ( ts . tv_nsec ) / 1e9 ;
}
std : : string HoldsPath ( ) {
if ( const char * o = std : : getenv ( " HOLDS_FILE " ) ) return o ;
if ( geteuid ( ) = = 0 ) return " /run/imsd.holds " ;
return std : : format ( " {}/imsd.holds " , EnvOr ( " XDG_RUNTIME_DIR " , " /tmp " ) ) ;
}
void PersistHolds ( const imsd : : engine : : RegRecovery : : Held & h , const std : : string & pdn ) {
std : : string path = HoldsPath ( ) ;
if ( ! h . Any ( ) ) {
// nothing to keep: the file goes — when it is ours. A device node or a
// link the HOLDS_FILE knob points at (/dev/null switches the file off) is
// emptied instead, never unlinked.
std : : error_code ec ;
auto st = std : : filesystem : : symlink_status ( path , ec ) ;
if ( std : : filesystem : : is_regular_file ( st ) ) std : : remove ( path . c_str ( ) ) ;
else if ( std : : filesystem : : exists ( st ) ) { if ( std : : FILE * f = std : : fopen ( path . c_str ( ) , " w " ) ) std : : fclose ( f ) ; }
return ;
}
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
std : : string j = std : : format ( " {{ \" pdn \" : \" {} \" , \" boot \" : \" {} \" , \" written_at \" : {}, \" hold \" : {}, \" fresh_hold \" : {}, \" throttle_minutes \" : {}, \" old_gone \" : {}, \" refusals \" : {}}} \n " ,
pdn , BootId ( ) , BootSeconds ( ) , static_cast < long > ( std : : ceil ( h . hold ) ) , static_cast < long > ( std : : ceil ( h . freshHold ) ) , h . throttleMinutes , h . oldGone ? " true " : " false " , h . refusals ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( std : : FILE * f = std : : fopen ( path . c_str ( ) , " w " ) ) {
std : : fwrite ( j . data ( ) , 1 , j . size ( ) , f ) ;
std : : fclose ( f ) ;
}
}
std : : optional < imsd : : engine : : RegRecovery : : Held > LoadHolds ( const std : : string & pdn ) {
std : : FILE * f = std : : fopen ( HoldsPath ( ) . c_str ( ) , " r " ) ;
if ( ! f ) return std : : nullopt ;
std : : string s ;
char buf [ 512 ] ; std : : size_t n ;
while ( ( n = std : : fread ( buf , 1 , sizeof buf , f ) ) > 0 ) s . append ( buf , n ) ;
std : : fclose ( f ) ;
ipsec, imsd, ims-pdn-up: the SA reader and the holds key compare in canonical form; LOCAL is canonicalised, PCSCF= accepted in RFC 5952 §4 form only
ParseExistingSa and SaLocals compared PCSCF= and LOCAL= as text against
`ip xfrm` output, which prints RFC 5952 form, so an upper-case or
uncompressed PCSCF= found no SAs and the restart registered fresh — on
KPN into the live-SA refusal; the holds file's pdn key compared the same
way. Both sides of each of those compares now go through
imsd::util::CanonicalAddr, LOCAL is canonicalised once on the way in, and PCSCF= is accepted in
that one spelling only — upper case, leading zeros or an uncompressed run
are refused at bring-up with the spelling to use, a dotted-quad tail (the
form ip prints for an IPv4-mapped address, which CanonicalIp6 does not read)
with the rule alone, a bracketed one by the bring-up script, which routes
the value as typed, with the rule (no brackets) — and a comma-separated
PCSCF= (a list) with its own message instead of reaching the socket layer: one spelling,
instead of a leniency both consumers of the setting would have to share.
Tested: crafter-build test, 7 passed; the upper-case PCSCF= refused with the spelling to use, a bracketed one
refused by the script, and the spelling they name resuming, in builds of
this series on the dev phone (KPN).
2026-10-11 15:55:19 +02:00
if ( imsd : : util : : CanonicalAddr ( QuotedAfter ( s , " \" pdn \" : \" " ) . value_or ( " " ) ) ! = imsd : : util : : CanonicalAddr ( pdn ) ) return std : : nullopt ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( QuotedAfter ( s , " \" boot \" : \" " ) . value_or ( " " ) ! = BootId ( ) ) return std : : nullopt ;
long elapsed = BootSeconds ( ) - IntAfter ( s , " \" written_at \" : " ) . value_or ( 0 ) ;
imsd : : engine : : RegRecovery : : Held h ;
h . hold = std : : max < long > ( 0 , IntAfter ( s , " \" hold \" : " ) . value_or ( 0 ) - elapsed ) ;
h . freshHold = std : : max < long > ( 0 , IntAfter ( s , " \" fresh_hold \" : " ) . value_or ( 0 ) - elapsed ) ;
h . throttleMinutes = static_cast < int > ( IntAfter ( s , " \" throttle_minutes \" : " ) . value_or ( h . throttleMinutes ) ) ;
h . oldGone = s . find ( " \" old_gone \" : true " ) ! = std : : string : : npos ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
h . refusals = static_cast < int > ( IntAfter ( s , " \" refusals \" : " ) . value_or ( 0 ) ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( ! h . Any ( ) ) return std : : nullopt ;
return h ;
}
2026-07-22 22:53:28 +02:00
// build an a{sv} from a CallInfo (matches imsd.py _d typing)
GVariant * CallVariant ( const CallInfo & c ) {
GVariantBuilder b ;
g_variant_builder_init ( & b , G_VARIANT_TYPE ( " a{sv} " ) ) ;
g_variant_builder_add ( & b , " {sv} " , " uni " , g_variant_new_string ( c . uni . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " number " , g_variant_new_string ( c . number . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " state " , g_variant_new_string ( c . state . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " reason " , g_variant_new_string ( c . reason . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " startedAt " , g_variant_new_int64 ( c . startedAt ) ) ;
g_variant_builder_add ( & b , " {sv} " , " answeredAt " , g_variant_new_int64 ( c . answeredAt ) ) ;
g_variant_builder_add ( & b , " {sv} " , " direction " , g_variant_new_string ( c . direction . c_str ( ) ) ) ;
return g_variant_builder_end ( & b ) ;
}
void EmitSignal ( const char * name , GVariant * params ) {
if ( ! DbusConn ) return ;
g_dbus_connection_emit_signal ( DbusConn , nullptr , ObjPath , Iface , name , params , nullptr ) ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// ---- Messaging subscribers (§8.4) — main thread only. The Messaging
// signals carry a text's content, so they are never broadcast: Subscribe
// runs the Messaging polkit gate and records the caller's unique bus name,
// and Received / StateChanged go unicast to each name recorded, which the
// bus delivers to that connection (root's busctl monitor sees them as
// well). A subscription ends with the
// connection (its name watch). The submission's outcome (sent / failed)
// also reaches the connection that called Send, subscribed or not; the
// later delivery states reach subscribers.
std : : set < std : : string > Subscribers ;
std : : map < std : : string , guint > SubscriberWatches ;
std : : map < std : : string , std : : string > SendOrigins ; // message id -> the Send caller's unique name
void OnSubscriberVanished ( GDBusConnection * , const gchar * name , gpointer ) {
if ( ! Subscribers . erase ( name ) ) return ;
if ( auto it = SubscriberWatches . find ( name ) ; it ! = SubscriberWatches . end ( ) ) { g_bus_unwatch_name ( it - > second ) ; SubscriberWatches . erase ( it ) ; }
Log ( std : : format ( " sms: {} unsubscribed (its connection is gone; {} subscriber(s)) " , name , Subscribers . size ( ) ) ) ;
}
void SubscribeMessaging ( GDBusConnection * conn , const std : : string & sender ) {
if ( ! Subscribers . insert ( sender ) . second ) return ;
SubscriberWatches [ sender ] = g_bus_watch_name_on_connection ( conn , sender . c_str ( ) , G_BUS_NAME_WATCHER_FLAGS_NONE , nullptr , OnSubscriberVanished , nullptr , nullptr ) ;
Log ( std : : format ( " sms: {} subscribed ({} subscriber(s)) " , sender , Subscribers . size ( ) ) ) ;
}
// a Messaging signal to one connection
void EmitSignalTo ( const std : : string & destination , const char * name , GVariant * params ) {
if ( ! DbusConn ) return ;
g_dbus_connection_emit_signal ( DbusConn , destination . c_str ( ) , ObjPath , MessagingIface , name , params , nullptr ) ;
}
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
// ---- the store of received messages (§7.9): one record file per message
// under <state dir>/sms, written by the engine thread as a message arrives
// and read, listed and deleted by the D-Bus thread (List/Delete, §8.4).
// A record is written whole to a .tmp beside it, fsynced, linked to its
// name with link(2) — which refuses a name already taken — and the .tmp
// removed, the directory fsynced after it, so a listing never sees a
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
// half-written one and nothing is replaced. The three scans — the start's
// sweep, List's read and the count for the journal — go through
// opendir(3), readdir(3), stat(2) and read(2), whose errors come back as
// values. What a scan cannot read is a StoreFault, logged by the scan that
// met it;
// List's read and the count hand theirs back as well.
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
std : : string SmsStoreDir ( ) { return std : : format ( " {}/sms " , StateDir ( ) ) ; }
bool ValidSmsId ( std : : string_view id ) {
if ( id . empty ( ) | | id . size ( ) > 64 ) return false ;
for ( char c : id )
if ( ! std : : isalnum ( static_cast < unsigned char > ( c ) ) & & c ! = ' - ' ) return false ;
return true ;
}
std : : string SmsRecordPath ( std : : string_view id ) { return std : : format ( " {}/{}.msg " , SmsStoreDir ( ) , id ) ; }
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
// What kept a scan of the store from reading it whole: where it stopped
// and the system's error. Empty when nothing did.
struct StoreFault {
std : : string path ;
int err = 0 ;
explicit operator bool ( ) const { return err ! = 0 ; }
std : : string Reason ( ) const { return std : : generic_category ( ) . message ( err ) ; }
} ;
void LogStoreFault ( const StoreFault & f ) { Log ( std : : format ( " sms store: cannot read {}: {} " , f . path , f . Reason ( ) ) ) ; }
// The names in the store directory. A directory that is not there holds
// none and is no fault: the first record stored makes it. Any other
// failure to open it, or to read it to its end, is — and the names read
// until then are not handed over.
StoreFault SmsStoreNames ( std : : vector < std : : string > & names ) {
const std : : string dir = SmsStoreDir ( ) ;
DIR * d = opendir ( dir . c_str ( ) ) ;
if ( ! d ) {
const int err = errno ; // read before the fault copies the path: an allocation may change it
return err = = ENOENT ? StoreFault { } : StoreFault { dir , err } ;
}
StoreFault fault ;
for ( ; ; ) {
errno = 0 ; // readdir(3): a null with errno unchanged is the end
const dirent * e = readdir ( d ) ;
if ( ! e ) {
if ( const int err = errno ; err ! = 0 ) fault = { dir , err } ;
break ;
}
names . emplace_back ( e - > d_name ) ;
}
closedir ( d ) ;
if ( fault ) names . clear ( ) ;
return fault ;
}
// A store file's name by its ending: `<something>.msg` a record,
// `<something>.tmp` a writer's temporary file.
bool HasStoreSuffix ( std : : string_view name , std : : string_view suffix ) { return name . size ( ) > suffix . size ( ) & & name . ends_with ( suffix ) ; }
// Whether `path` is a regular file, a symbolic link to one included. One
// that is gone since the directory was read is not, and no fault; any
// other failure of stat(2) is the fault.
bool IsStoreFile ( const std : : string & path , StoreFault & fault ) {
struct stat st { } ;
if ( stat ( path . c_str ( ) , & st ) ! = 0 ) {
if ( const int err = errno ; err ! = ENOENT ) fault = { path , err } ;
return false ;
}
return S_ISREG ( st . st_mode ) ;
}
// A store file's whole content into `text`. False when the file is gone
// since the directory was read (no fault) or could not be opened or read
// to its end (the fault).
bool ReadStoreFile ( const std : : string & path , std : : string & text , StoreFault & fault ) {
const int fd = open ( path . c_str ( ) , O_RDONLY | O_CLOEXEC ) ;
if ( fd < 0 ) {
if ( const int err = errno ; err ! = ENOENT ) fault = { path , err } ;
return false ;
}
bool whole = false ;
char buf [ 4096 ] ;
for ( ; ; ) {
const ssize_t n = read ( fd , buf , sizeof buf ) ;
if ( n > 0 ) { text . append ( buf , static_cast < std : : size_t > ( n ) ) ; continue ; }
const int err = n < 0 ? errno : 0 ;
if ( err = = EINTR ) continue ;
if ( err ! = 0 ) fault = { path , err } ;
else whole = true ;
break ;
}
close ( fd ) ;
return whole ;
}
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
// The .tmp files a crash left (between the open and the link, or between
// the link and the unlink, when one is a record's second name): unlinked
// at the engine's start, before it takes its first message; the count is
// of those the unlink removed. A record whose second name goes keeps its
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
// inode. A store that cannot be read is logged and left: the daemon
// starts all the same.
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
int SweepSmsStore ( ) {
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
std : : vector < std : : string > names ;
StoreFault fault = SmsStoreNames ( names ) ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
int n = 0 ;
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
for ( const std : : string & name : names ) {
if ( ! HasStoreSuffix ( name , " .tmp " ) ) continue ;
const std : : string path = std : : format ( " {}/{} " , SmsStoreDir ( ) , name ) ;
StoreFault here ;
if ( ! IsStoreFile ( path , here ) ) {
if ( here & & ! fault ) fault = here ;
continue ;
}
if ( unlink ( path . c_str ( ) ) = = 0 ) n + + ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
}
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
if ( fault ) LogStoreFault ( fault ) ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
return n ;
}
// Stores a received message under its id. Exists: the store already
// holds that name (a run's own ids never repeat); the caller takes the
// next id. Failed (with `why`): the directory or the
// file could not be made.
enum class StoreResult { Stored , Exists , Failed } ;
StoreResult StoreReceivedSms ( const imsd : : engine : : StoredSms & r , std : : string & why ) {
std : : error_code ec ;
const std : : filesystem : : path dir = SmsStoreDir ( ) ;
std : : filesystem : : create_directories ( dir , ec ) ;
if ( ec ) { why = std : : format ( " {}: {} " , dir . string ( ) , ec . message ( ) ) ; return StoreResult : : Failed ; }
std : : filesystem : : permissions ( dir , std : : filesystem : : perms : : owner_all , std : : filesystem : : perm_options : : replace , ec ) ;
const std : : string path = SmsRecordPath ( r . id ) ;
const std : : string tmp = path + " .tmp " ;
const std : : string text = imsd : : engine : : FormatStoredSms ( r ) ;
// a stale .tmp — a crash between link(2) and unlink(2) below — may be a
// record's second name: unlinked, never truncated (every .tmp is also
// swept at the engine's start, SweepSmsStore); close-on-exec, so no descriptor of this
// writer reaches a program imsd runs
unlink ( tmp . c_str ( ) ) ;
int fd = open ( tmp . c_str ( ) , O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC , 0600 ) ;
if ( fd < 0 ) { why = std : : format ( " {}: {} " , tmp , std : : strerror ( errno ) ) ; return StoreResult : : Failed ; }
std : : size_t done = 0 ;
while ( done < text . size ( ) ) {
const ssize_t n = write ( fd , text . data ( ) + done , text . size ( ) - done ) ;
if ( n < 0 ) { why = std : : format ( " {}: {} " , tmp , std : : strerror ( errno ) ) ; close ( fd ) ; unlink ( tmp . c_str ( ) ) ; return StoreResult : : Failed ; }
done + = static_cast < std : : size_t > ( n ) ;
}
const int syncErr = fsync ( fd ) < 0 ? errno : 0 ;
const int closeErr = close ( fd ) < 0 ? errno : 0 ; // closed on every path
if ( syncErr | | closeErr ) { why = std : : format ( " {}: {} " , tmp , std : : strerror ( syncErr ? syncErr : closeErr ) ) ; unlink ( tmp . c_str ( ) ) ; return StoreResult : : Failed ; }
// link(2) publishes the name only if it is free — rename(2) would
// replace a record already there
if ( link ( tmp . c_str ( ) , path . c_str ( ) ) < 0 ) {
const int e = errno ;
unlink ( tmp . c_str ( ) ) ;
if ( e = = EEXIST ) return StoreResult : : Exists ;
why = std : : format ( " {} -> {}: {} " , tmp , path , std : : strerror ( e ) ) ;
return StoreResult : : Failed ;
}
unlink ( tmp . c_str ( ) ) ;
// the directory entry too: link(2) and unlink(2) are durable only with
// the directory's own fsync (its result, like the open's, is not checked:
// a failure here does not unstore the record)
if ( int dfd = open ( dir . c_str ( ) , O_RDONLY | O_DIRECTORY | O_CLOEXEC ) ; dfd > = 0 ) { fsync ( dfd ) ; close ( dfd ) ; }
return StoreResult : : Stored ;
}
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
// The stored messages, oldest first: the `.msg` files, one that reads and
// is no record skipped (logged when `log`) — one corrupt file does not
// close the store. The scan stops at the first thing it cannot read — the
// directory, a file's type, a file — with that as `fault`, logged: the
// records are then not the store's, and a caller must not hand them over
// as if they were.
struct StoreRead {
std : : vector < imsd : : engine : : StoredSms > records ;
StoreFault fault ;
} ;
StoreRead LoadStoredSms ( bool log = true ) {
StoreRead out ;
std : : vector < std : : string > names ;
out . fault = SmsStoreNames ( names ) ;
for ( const std : : string & name : names ) {
if ( out . fault ) break ;
if ( ! HasStoreSuffix ( name , " .msg " ) ) continue ;
const std : : string path = std : : format ( " {}/{} " , SmsStoreDir ( ) , name ) ;
std : : string text ;
if ( ! IsStoreFile ( path , out . fault ) | | ! ReadStoreFile ( path , text , out . fault ) ) continue ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
auto r = imsd : : engine : : ParseStoredSms ( text ) ;
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
if ( ! r ) { if ( log ) Log ( std : : format ( " sms store: {} is no record; skipped " , path ) ) ; continue ; }
out . records . push_back ( std : : move ( * r ) ) ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
}
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
if ( out . fault ) LogStoreFault ( out . fault ) ;
std : : sort ( out . records . begin ( ) , out . records . end ( ) , imsd : : engine : : StoredSmsBefore ) ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
return out ;
}
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
// The records in the store (what List would hand over), not the files;
// none when the store could not be read.
std : : optional < std : : size_t > StoredSmsCount ( ) {
const StoreRead store = LoadStoredSms ( false ) ;
if ( store . fault ) return std : : nullopt ;
return store . records . size ( ) ;
}
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// a received short message as the Messaging interface's a{sv} (§8.4)
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
GVariant * SmsVariant ( const imsd : : engine : : SmsReceived & m , std : : int64_t receivedAt , const std : : string & to , const std : : string & simOperator ) {
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
GVariantBuilder b ;
g_variant_builder_init ( & b , G_VARIANT_TYPE ( " a{sv} " ) ) ;
g_variant_builder_add ( & b , " {sv} " , " from " , g_variant_new_string ( m . from . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " text " , g_variant_new_string ( m . text . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " timestamp " , g_variant_new_string ( m . scts . c_str ( ) ) ) ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
g_variant_builder_add ( & b , " {sv} " , " received " , g_variant_new_int64 ( receivedAt ) ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
g_variant_builder_add ( & b , " {sv} " , " sc " , g_variant_new_string ( m . sc . c_str ( ) ) ) ;
imsd, engine: a received text records the subscriber it arrived for
The Messaging interface gave a received text with its sender and the
service centre but not the subscriber it was for. A consumer completing a
national-form sender with a country code had to take the code from the
daemon's status at import time, which is the wrong moment: the daemon
keeps a text on disk until an app deletes it, so the app that imports it
after a SIM change knows only the new SIM's code, and a national number
under the old SIM's plan is keyed, and replied to, under the new one —
another subscriber. Only the daemon knows at receipt which subscriber a
text arrived for. The stored record and the Received and List
dictionaries carry it
as `to`: the own number the daemon holds at the moment of receipt — the
first tel: P-Associated-URI of this run's latest answer to a fresh
registration, a resume or a reconnect that carried one (a periodic
refresh's answer is not read for it) and, until the first such, the
state file's once a resume attempt has taken it up. The key is absent
while the daemon holds none.
It is additive: an app that does not know it ignores it, and a record
without it reads as before. The value comes from a header, so the
emission makes it valid UTF-8, as it does a failed submission's reason.
Tested: tests/Engine, the record round trip with `to` and a record
without it.
2026-11-02 20:54:15 +01:00
// from a header: made valid UTF-8 like a failed submission's reason
if ( ! to . empty ( ) ) g_variant_builder_add ( & b , " {sv} " , " to " , g_variant_new_take_string ( g_utf8_make_valid ( to . c_str ( ) , - 1 ) ) ) ;
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
if ( ! simOperator . empty ( ) ) g_variant_builder_add ( & b , " {sv} " , " operator " , g_variant_new_string ( simOperator . c_str ( ) ) ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
g_variant_builder_add ( & b , " {sv} " , " class " , g_variant_new_int32 ( m . msgClass . value_or ( - 1 ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " pid " , g_variant_new_byte ( m . pid ) ) ;
g_variant_builder_add ( & b , " {sv} " , " dcs " , g_variant_new_byte ( m . dcs ) ) ;
g_variant_builder_add ( & b , " {sv} " , " segments " , g_variant_new_int32 ( m . segments ) ) ;
g_variant_builder_add ( & b , " {sv} " , " message-waiting " , g_variant_new_boolean ( m . messageWaiting ? TRUE : FALSE ) ) ;
if ( m . portDst ) g_variant_builder_add ( & b , " {sv} " , " port-dst " , g_variant_new_uint32 ( * m . portDst ) ) ;
if ( m . portSrc ) g_variant_builder_add ( & b , " {sv} " , " port-src " , g_variant_new_uint32 ( * m . portSrc ) ) ;
if ( ! m . data . empty ( ) ) g_variant_builder_add ( & b , " {sv} " , " data " , g_variant_new_fixed_array ( G_VARIANT_TYPE_BYTE , m . data . data ( ) , m . data . size ( ) , 1 ) ) ;
g_variant_builder_add ( & b , " {sv} " , " pdu " , g_variant_new_fixed_array ( G_VARIANT_TYPE_BYTE , m . tpdu . data ( ) , m . tpdu . size ( ) , 1 ) ) ;
return g_variant_builder_end ( & b ) ;
}
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
// ---- logind's inhibitor for sleep (main thread only) -----------------------
// Nothing of imsd runs while the phone is suspended: a suspend under a
// call stops this daemon and the call's media leg for as long as the
// phone sleeps. So imsd takes logind's block inhibitor for sleep while
// the calls table holds a call: from the call's addition (an incoming
// call's ringing; for a Dial after the recovery's try on a dead flow and
// the PANI refresh) to its removal. Under it logind refused a plain
// `systemctl suspend` on the dev phone; a request can tell it to ignore
// inhibitors (`systemctl suspend -i`).
// Where it was asked for during a suspend's operation logind refused this lock (systemd 262 on the
// dev phone: refused in a suspend's hooks before and after the sleep and
// to a call 0.1 to 0.3 s after the resume, given once logind had logged
// the operation's "finished"). So a lock that is wanted and not held is
// asked for again when logind sends PrepareForSleep with false; one
// wanted before the bus connection is there, when it comes.
// Where logind gives no lock at all (the session bus of --session has no
// logind) calls go on without one. The journal says so once until a
// call's lock is next given.
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
// A second lock is asked for, in the way the call's is, while the engine has work in flight that waits for
// the network: a step of the registration (Engine::Step) or a text being
// sent. A suspend under one would leave it where it stood until something
// wakes the phone: a text's waits count awake seconds. It is asked for where it is wanted and not
// held, released when nothing wants it any more, and the journal has no line for any of that.
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
struct SleepLock {
const char * why ; // logind's "why": what the lock is held for
bool told ; // its taking, its release and a refusal go to the journal
bool want = false ;
int fd = - 1 ; // the inhibitor's file descriptor (-1: not held)
} ;
SleepLock CallLock { " a call " , true } ;
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
SleepLock WorkLock { " a registration step or a text in flight " , false } ;
int WorksInFlight = 0 ; // the engine's Work events, true less false: what wants the work's lock now (a step that waits out a hold is not in it)
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
bool NoSleepLockTold = false ; // the journal has a refusal's line since a call's lock was last given
void HoldSleepOff ( SleepLock & lock , bool want ) {
lock . want = want ;
if ( want = = ( lock . fd > = 0 ) ) return ;
if ( ! want ) {
close ( lock . fd ) ;
lock . fd = - 1 ;
if ( lock . told ) Log ( " sleep is no longer held off (no call) " ) ;
return ;
}
if ( ! DbusConn ) return ;
GError * err = nullptr ;
GUnixFDList * fds = nullptr ;
GVariant * r = g_dbus_connection_call_with_unix_fd_list_sync (
DbusConn , " org.freedesktop.login1 " , " /org/freedesktop/login1 " , " org.freedesktop.login1.Manager " , " Inhibit " ,
g_variant_new ( " (ssss) " , " sleep " , " imsd " , lock . why , " block " ) , G_VARIANT_TYPE ( " (h) " ) ,
G_DBUS_CALL_FLAGS_NONE , 2000 , nullptr , & fds , nullptr , & err ) ;
if ( r ) {
gint32 handle = - 1 ;
g_variant_get ( r , " (h) " , & handle ) ;
g_variant_unref ( r ) ;
if ( fds & & handle > = 0 ) lock . fd = g_unix_fd_list_get ( fds , handle , nullptr ) ;
}
if ( fds ) g_object_unref ( fds ) ;
if ( lock . fd > = 0 ) {
if ( lock . told ) {
Log ( " sleep is held off while the call lasts (logind's inhibitor) " ) ;
NoSleepLockTold = false ;
}
} else if ( lock . told & & ! NoSleepLockTold ) {
Log ( std : : format ( " no sleep inhibitor from logind ({}): asked again when it says a sleep is over " , err ? err - > message : " no file descriptor in its answer " ) ) ;
NoSleepLockTold = true ;
}
g_clear_error ( & err ) ;
}
// logind's PrepareForSleep: at one with false, a lock that is wanted and
// not held is asked for.
void OnPrepareForSleep ( GDBusConnection * , const gchar * , const gchar * , const gchar * , const gchar * , GVariant * params , gpointer ) {
if ( ! g_variant_is_of_type ( params , G_VARIANT_TYPE ( " (b) " ) ) ) return ;
gboolean entering = TRUE ;
g_variant_get ( params , " (b) " , & entering ) ;
if ( entering ) return ;
HoldSleepOff ( CallLock , CallLock . want ) ;
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
HoldSleepOff ( WorkLock , WorkLock . want ) ;
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
}
2026-07-22 22:53:28 +02:00
gboolean OnIdleEvent ( gpointer data ) {
std : : unique_ptr < Event > ev ( static_cast < Event * > ( data ) ) ;
switch ( ev - > type ) {
case Event : : Type : : Added : {
Calls [ ev - > info . uni ] = ev - > info ;
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
HoldSleepOff ( CallLock , true ) ;
2026-07-22 22:53:28 +02:00
EmitSignal ( " CallAdded " , g_variant_new ( " (s@a{sv}) " , ev - > info . uni . c_str ( ) , CallVariant ( ev - > info ) ) ) ;
break ;
}
case Event : : Type : : State : {
auto it = Calls . find ( ev - > uni ) ;
if ( it ! = Calls . end ( ) ) {
it - > second . state = ev - > state ;
it - > second . reason = ev - > reason ;
if ( ev - > state = = " active " & & it - > second . answeredAt = = 0 ) it - > second . answeredAt = NowEpoch ( ) ;
}
EmitSignal ( " CallStateChanged " , g_variant_new ( " (sss) " , ev - > uni . c_str ( ) , ev - > state . c_str ( ) , ev - > reason . c_str ( ) ) ) ;
break ;
}
case Event : : Type : : Deleted :
Calls . erase ( ev - > uni ) ;
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
HoldSleepOff ( CallLock , ! Calls . empty ( ) ) ;
2026-07-22 22:53:28 +02:00
EmitSignal ( " CallDeleted " , g_variant_new ( " (s) " , ev - > uni . c_str ( ) ) ) ;
break ;
case Event : : Type : : Registration :
StatusSnap = ev - > status ;
EmitSignal ( " RegistrationChanged " , g_variant_new ( " (b) " , ev - > status . registered ? TRUE : FALSE ) ) ;
break ;
case Event : : Type : : Status :
StatusSnap = ev - > status ;
break ;
case Event : : Type : : Fatal :
Log ( std : : format ( " engine fatal: {} — exiting for systemd restart " , ev - > text ) ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
FatalExit = true ; // non-zero exit, or Restart=on-failure never fires
2026-07-22 22:53:28 +02:00
g_main_loop_quit ( MainLoop ) ;
break ;
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
case Event : : Type : : Idle :
// nothing to do (§7.3): a clean exit, which Restart=on-failure
// leaves alone
Log ( std : : format ( " idle: {} — nothing to do; systemctl start imsd when that changes " , ev - > text ) ) ;
g_main_loop_quit ( MainLoop ) ;
break ;
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
case Event : : Type : : Work :
WorksInFlight = std : : max ( 0 , WorksInFlight + ( ev - > on ? 1 : - 1 ) ) ;
HoldSleepOff ( WorkLock , WorksInFlight > 0 ) ;
break ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
case Event : : Type : : SmsReceived :
for ( const std : : string & to : Subscribers )
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
EmitSignalTo ( to , " Received " , g_variant_new ( " (s@a{sv}) " , ev - > uni . c_str ( ) , SmsVariant ( ev - > sms , ev - > at , ev - > to , ev - > simOperator ) ) ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
break ;
case Event : : Type : : SmsState : {
std : : set < std : : string > to = Subscribers ;
if ( auto it = SendOrigins . find ( ev - > uni ) ; it ! = SendOrigins . end ( ) ) {
to . insert ( it - > second ) ;
if ( ev - > state = = imsd : : engine : : SmsStateSent | | ev - > state = = imsd : : engine : : SmsStateFailed ) SendOrigins . erase ( it ) ;
}
// a failed submission's reason can hold the network's text (a
// refused final's, RefusalSummary); a D-Bus string must be valid
// UTF-8, so bytes that are not become U+FFFD here, and the C
// string read ends at a NUL byte — the id and the state are
// imsd's own ASCII
gchar * reason = g_utf8_make_valid ( ev - > reason . c_str ( ) , - 1 ) ;
for ( const std : : string & t : to )
EmitSignalTo ( t , " StateChanged " , g_variant_new ( " (sss) " , ev - > uni . c_str ( ) , ev - > state . c_str ( ) , reason ) ) ;
g_free ( reason ) ;
break ;
}
2026-07-22 22:53:28 +02:00
}
return G_SOURCE_REMOVE ;
}
void PostEvent ( std : : unique_ptr < Event > ev ) {
g_idle_add ( OnIdleEvent , ev . release ( ) ) ;
}
// ================= engine ==================================================
class Engine {
public :
Engine ( ) {
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
// The P-CSCF a fresh registration goes to: PCSCF= when set, else the
// first address the bring-up read from the PDN's PCO
// (PCSCF_DISCOVERED=); no baked-in default — carrier infrastructure.
// A resume follows the kernel's SAs instead (TryResume), whatever
// this says today.
{
std : : vector < std : : string > rejected ;
pcscfTarget_ = FreshPcscfFromEnv ( & pcscfCandidates_ , & rejected ) ;
pcscf_ = pcscfTarget_ ;
std : : string configured = imsd : : util : : CanonicalAddr ( EnvOr ( " PCSCF " , " " ) ) ;
std : : string list ;
for ( const std : : string & c : pcscfCandidates_ ) list + = ( list . empty ( ) ? " " : " , " ) + c ;
if ( ! configured . empty ( ) )
Log ( pcscfCandidates_ . empty ( ) ? std : : format ( " pcscf: configured {} " , configured )
: std : : format ( " pcscf: configured {}; discovery gave {} (ignored: PCSCF= wins) " , configured , list ) ) ;
else if ( ! pcscfCandidates_ . empty ( ) )
Log ( std : : format ( " pcscf: discovered {} (using {}) " , list , pcscfTarget_ ) ) ;
for ( const std : : string & r : rejected ) Log ( std : : format ( " pcscf: PCSCF_DISCOVERED entry '{}' is not an IPv6 address; ignored " , r ) ) ;
}
2026-07-22 22:53:28 +02:00
pcscfPort_ = std : : atoi ( EnvOr ( " PCSCF_PORT " , " 5060 " ) . c_str ( ) ) ;
dev_ = EnvOr ( " DEV " , " qmapmux0.0 " ) ;
outDir_ = EnvOr ( " OUT_DIR " , StateDir ( ) ) ;
rtpPort_ = std : : atoi ( EnvOr ( " RTP_PORT " , " 50004 " ) . c_str ( ) ) ;
precond_ = EnvOr ( " PRECOND " , " 0 " ) = = " 1 " ;
ipsec, messages, imsd: the offered ESP ciphers are a list
imsd's Security-Client held one mechanism, its cipher the value of EALG,
aes-cbc when unset. TS 33.203 7.2 has the UE's first REGISTER carry "a
list of identifiers for the integrity and encryption algorithms, which
the UE supports", and imsd can install three ciphers: an offer of one
could not say so.
EALG is now a comma-separated list, offered in the order written: one
mechanism per cipher in a single Security-Client, each with the
REGISTER's SPIs and ports (7.2 NOTE 1, NOTE 2). The default stays
aes-cbc alone. A name imsd cannot install is ignored with a journal
line where it used to go out as written, `3des` is offered as
des-ede3-cbc, RFC 3329's name for it, a setting that names no cipher
gives the default, and the bring-up logs what is offered (`ESP ciphers
offered: …`).
An offer of more than one cipher needs a further rule for the 401's
list. O2 UK's P-CSCF lists six mechanisms and puts the SPIs on one: the
sha1 entry without a cipher for a null offer, the sha1 entry with
aes-cbc for an aes-cbc offer (2026-09-17, 2026-09-20). The second has
the higher q, so with both ciphers offered the highest-q offered entry
and the entry carrying the SPIs can be two entries. The entry carrying
the SPIs is therefore taken when it is the only such entry and one of
the offer; otherwise the highest-q offered entry, as before. With one
cipher offered the two name the same algorithms; they can differ in mod
or prot, and there the marked entry's are now taken, where 1.2.1 took
the highest-q entry's.
Tested: tests/Ipsec (the setting; the selection against two offered
ciphers) and tests/Messages (a Security-Client of two mechanisms); the
daemon of this commit against a stand-in P-CSCF on the workstation, with
one cipher offered and with two.
2026-11-23 10:08:04 +01:00
// EALG: the ESP ciphers Security-Client offers, in the order
// written (imsd::ipsec::ParseEalgOffer: with no cipher named, the
// default list). A name imsd cannot install is passed over with a
// line.
{
imsd : : ipsec : : EalgSetting ealg = imsd : : ipsec : : ParseEalgOffer ( EnvOr ( " EALG " , " " ) ) ;
for ( const std : : string & u : ealg . unknown ) Log ( std : : format ( " EALG entry '{}' is not a cipher imsd can install; ignored " , u ) ) ;
ealgOffer_ = std : : move ( ealg . ciphers ) ;
}
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// SIP_TRANSPORT: the protected leg's transport. auto (default) = TCP,
// and when the P-CSCF never answers the TCP connect, a fresh
// registration over UDP; tcp / udp force one. The challenge (first
// REGISTER) is UDP regardless.
sipPolicy_ = EnvOr ( " SIP_TRANSPORT " , " auto " ) ;
if ( sipPolicy_ ! = " auto " & & sipPolicy_ ! = " tcp " & & sipPolicy_ ! = " udp " ) {
Log ( std : : format ( " SIP_TRANSPORT={} unknown; using auto " , sipPolicy_ ) ) ;
sipPolicy_ = " auto " ;
}
transport_ = sipPolicy_ = = " udp " ? Transport : : Udp : Transport : : Tcp ;
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
// CRLF_KEEPALIVE=<seconds>: an RFC 5626 4.4.1 ping that often on the
// idle TCP flow, for a P-CSCF that drops a flow it hears nothing on.
// None by default (until 1.2.3: one every 30 s): no registration of
// imsd's negotiates them, and a ping can wake a suspended phone
// afterwards (AGENTS.md §13). An empty value is as none; any other
// that is no whole number of seconds is reported and sends none.
if ( std : : string v = EnvOr ( " CRLF_KEEPALIVE " , " " ) ; ! v . empty ( ) ) {
if ( auto s = imsd : : util : : WholeSeconds ( v ) ) crlfKeepalive_ = * s ;
else Log ( std : : format ( " CRLF_KEEPALIVE={} is not a whole number of seconds; no CRLF keepalive " , v ) ) ;
}
2026-07-22 22:53:28 +02:00
mediaBin_ = ResolveMediaBin ( ) ;
engine/sdp: CODECS override for the codecs we offer and accept
KPN's interconnect gateway transcodes every caller up: a G.711-only
fixed-line INVITE reached the phone offering PCMA, PCMU, AMR and AMR-WB
(bench call 2026-09-08), so the AMR-WB-only build rang and the narrowband
path — the one the Telia field report hit with 488 — cannot be reached on
the air through KPN by any caller.
CODECS=<list> (comma-separated over AMR-WB, AMR/AMR-NB, PCMA, PCMU) makes
the list both the codecs offered on an outgoing call and the acceptance
preference for an inbound offer, in that order: CODECS=PCMA takes G.711
A-law out of the mixed offer above, CODECS=PCMA,PCMU sends a G.711-only
offer toward the network. Unset, nothing changes — the default offer
bytes and the AMR-WB > AMR > PCMA > PCMU preference stay pinned. The
daemon logs an active override at startup.
2026-09-08 17:53:26 +02:00
// CODECS: restrict + reorder the codecs we offer and accept (bench
// knob — a gateway that transcodes every caller up to AMR-WB never
// lets the narrowband path run otherwise). Empty = defaults.
codecs_ = imsd : : sdp : : ParseCodecList ( EnvOr ( " CODECS " , " " ) ) ;
if ( ! codecs_ . empty ( ) ) {
std : : string list ;
for ( const auto & c : codecs_ ) list + = ( list . empty ( ) ? " " : " , " ) + c ;
Log ( std : : format ( " CODECS override active: {} " , list ) ) ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// SMS_OVER_IMS=1: advertise +g.3gpp.smsip and take short messages
// over IMS (§7.9) — off by default: with the tag the network may
// deliver terminating SMS over IMS rather than the modem's NAS path
// (operator policy, TS 24.341 5.3.3.4.2 NOTE 2). SMSC= names
// the service centre instead of EF_SMSP.
smsOverIp_ = EnvOr ( " SMS_OVER_IMS " , " 0 " ) = = " 1 " ;
smscOverride_ = EnvOr ( " SMSC " , " " ) ;
if ( ! smsOverIp_ ) Log ( " SMS over IP: off (SMS_OVER_IMS=1 enables it) " ) ;
// TS 23.040 9.2.3.6 has TP-MR continue from the (U)SIM's
// Last-Used-TP-MR; imsd continues from its own last one instead
// (<state dir>/sms-tpmr, written when a message's segments take
// theirs, the write neither checked nor synced) and starts at random only without
// one, to keep a status report for a message sent before a restart
// from meeting its TP-MR on a newer one. RP-MR and the concatenation
// reference start at random.
tpMr_ = LoadTpMr ( ) . value_or ( static_cast < std : : uint8_t > ( rng_ . UInt ( 0 , 255 ) ) ) ;
rpMr_ = static_cast < std : : uint8_t > ( rng_ . UInt ( 0 , 255 ) ) ;
concatRef_ = static_cast < std : : uint8_t > ( rng_ . UInt ( 0 , 255 ) ) ;
Emergency calling, stage 1: urn:service:sos with a digits fallback
Classify 112/911 (plus EMERGENCY_NUMBERS) at Dial. A classified call
INVITEs urn:service:sos over the existing registration and, on any
non-2xx final not caused by the user hanging up (including the
setup-timeout CANCEL paths), retries once as a plain INVITE of the
dialled digits — the pre-0.3.0 behavior, so classification can never
place a call worse than the status quo. The reverse edge: a 380
Alternative Service whose body carries the emergency indication
upgrades an unclassified call to the sos URN; a bare 380 stays an
error, since promoting an arbitrary redirect would put a
non-emergency call through to a PSAP. An emergency dial preempts an
in-progress call, and an answer racing a deadline-initiated CANCEL is
taken instead of BYE'd (user-initiated CANCEL races still BYE).
No emergency registration, no emergency PDN, no CS fallback, no
SIM-less calling, no AML — and no carrier has confirmed the sos path
end-to-end. The README warning states exactly that.
Assisted-by: Claude:claude-fable-5
2026-08-01 22:29:12 +02:00
// EMERGENCY_NUMBERS: comma-separated additions to the builtin
// 112/911 (a lab core's advertised short code, carrier extras).
std : : string extra = EnvOr ( " EMERGENCY_NUMBERS " , " " ) ;
for ( std : : size_t pos = 0 ; pos < = extra . size ( ) ; ) {
std : : size_t comma = extra . find ( ' , ' , pos ) ;
std : : size_t end = comma = = std : : string : : npos ? extra . size ( ) : comma ;
std : : string n = extra . substr ( pos , end - pos ) ;
std : : erase ( n , ' ' ) ;
if ( ! n . empty ( ) ) emergencyExtra_ . push_back ( std : : move ( n ) ) ;
if ( comma = = std : : string : : npos ) break ;
pos = comma + 1 ;
}
2026-07-22 22:53:28 +02:00
}
ipsec, imsd, ims-pdn-up: the SA reader and the holds key compare in canonical form; LOCAL is canonicalised, PCSCF= accepted in RFC 5952 §4 form only
ParseExistingSa and SaLocals compared PCSCF= and LOCAL= as text against
`ip xfrm` output, which prints RFC 5952 form, so an upper-case or
uncompressed PCSCF= found no SAs and the restart registered fresh — on
KPN into the live-SA refusal; the holds file's pdn key compared the same
way. Both sides of each of those compares now go through
imsd::util::CanonicalAddr, LOCAL is canonicalised once on the way in, and PCSCF= is accepted in
that one spelling only — upper case, leading zeros or an uncompressed run
are refused at bring-up with the spelling to use, a dotted-quad tail (the
form ip prints for an IPv4-mapped address, which CanonicalIp6 does not read)
with the rule alone, a bracketed one by the bring-up script, which routes
the value as typed, with the rule (no brackets) — and a comma-separated
PCSCF= (a list) with its own message instead of reaching the socket layer: one spelling,
instead of a leniency both consumers of the setting would have to share.
Tested: crafter-build test, 7 passed; the upper-case PCSCF= refused with the spelling to use, a bracketed one
refused by the script, and the spelling they name resuming, in builds of
this series on the dev phone (KPN).
2026-10-11 15:55:19 +02:00
void SetLocal ( std : : string l ) { local_ = imsd : : util : : CanonicalAddr ( l ) ; pdnLocal_ = local_ ; }
2026-07-22 22:53:28 +02:00
void SetDevMode ( bool d ) { devMode_ = d ; }
const std : : string & Local ( ) const { return local_ ; }
// Dial() runs on the D-Bus thread: allocate the uni, queue the work.
std : : string Dial ( const std : : string & number ) {
std : : scoped_lock g ( cmdLock_ ) ;
std : : string uni = std : : format ( " ims-call-{} " , + + callSeq_ ) ;
cmds_ . push_back ( { Cmd : : Kind : : Dial , uni , number } ) ;
return uni ;
}
void HangUp ( const std : : string & uni ) {
std : : scoped_lock g ( cmdLock_ ) ;
cmds_ . push_back ( { Cmd : : Kind : : HangUp , uni , { } } ) ;
}
void Accept ( const std : : string & uni ) {
std : : scoped_lock g ( cmdLock_ ) ;
cmds_ . push_back ( { Cmd : : Kind : : Accept , uni , { } } ) ;
}
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
void SendDtmf ( const std : : string & uni , const std : : string & tones ) {
std : : scoped_lock g ( cmdLock_ ) ;
cmds_ . push_back ( { Cmd : : Kind : : Dtmf , uni , tones } ) ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
bool SmsEnabled ( ) const { return smsOverIp_ ; }
// Send() runs on the D-Bus thread: allocate the id, queue the work.
std : : string SendSms ( const std : : string & number , const std : : string & text , bool statusReport ) {
std : : scoped_lock g ( cmdLock_ ) ;
std : : string id = imsd : : engine : : SentSmsId ( smsRun_ , smsStart_ , + + smsSeq_ ) ;
cmds_ . push_back ( { Cmd : : Kind : : SendSms , id , number , text , statusReport } ) ;
return id ;
}
2026-07-22 22:53:28 +02:00
void Stop ( ) {
{ std : : scoped_lock g ( cmdLock_ ) ; cmds_ . push_back ( { Cmd : : Kind : : Stop , { } , { } } ) ; }
quit_ . store ( true ) ;
}
void Run ( ) {
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
if ( const int n = SweepSmsStore ( ) ; n > 0 ) Log ( std : : format ( " sms store: {} stale temporary file(s) removed " , n ) ) ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
if ( auto h = LoadHolds ( pdnLocal_ ) ) {
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
recovery_ . Restore ( Boot ( ) , * h ) ;
auto kept = recovery_ . Holds ( Boot ( ) ) ; // what the policy took over: the file's values after the clamp
if ( kept . hold > 0 | | kept . freshHold > 0 )
Log ( std : : format ( " a hold the network set before this start stands ({:.0f} s for any attempt, {:.0f} s for a fresh registration; the refusal schedule at {} min) " , kept . hold , kept . freshHold , kept . throttleMinutes ) ) ;
else if ( kept . throttleMinutes > imsd : : engine : : RegRecovery : : ThrottleMinutesMin )
Log ( std : : format ( " the refusal schedule stands at {} min from before this start: a refused or throttled fresh registration waits that long " , kept . throttleMinutes ) ) ;
if ( kept . oldGone ) Log ( " the old registration was gone before this start: no resume over its SAs, the fresh registration once its wait has run " ) ;
}
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
for ( ; ; ) {
2026-07-22 22:53:28 +02:00
try {
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
Step step ( * this ) ;
2026-07-22 22:53:28 +02:00
BringUp ( ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
break ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
} catch ( const Stopping & ) {
return ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
} catch ( const ThrottledError & e ) {
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
DeferBringUp ( e . what ( ) , imsd : : engine : : RegRecovery : : Failure : : Throttled , 0 ) ;
if ( quit_ . load ( ) ) return ;
continue ;
} catch ( const RefusedError & e ) {
// A refused initial registration (403, 5xx) waits like a
// throttle: a fatal would restart imsd every RestartSec with an
// initial REGISTER each time.
DeferBringUp ( e . what ( ) , imsd : : engine : : RegRecovery : : Failure : : Refused , e . retryAfter ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( quit_ . load ( ) ) return ;
continue ;
2026-07-22 22:53:28 +02:00
} catch ( const std : : exception & e ) {
if ( devMode_ ) {
// dev/session mode (no modem): keep the ABI up, unregistered,
// so the D-Bus surface can be exercised without a phone.
Log ( std : : format ( " bring-up skipped (dev mode): {} " , e . what ( ) ) ) ;
registered_ = false ;
EmitStatus ( true ) ;
DevLoop ( ) ;
return ;
}
Log ( std : : format ( " bring-up FAILED: {} " , e . what ( ) ) ) ;
auto ev = std : : make_unique < Event > ( ) ;
ev - > type = Event : : Type : : Fatal ; ev - > text = e . what ( ) ;
PostEvent ( std : : move ( ev ) ) ;
return ;
}
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
}
2026-07-22 22:53:28 +02:00
try { server_ . Open ( local_ ) ; }
catch ( . . . ) { Log ( " server ports unavailable; remote hangup/incoming not seen " ) ; }
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
OnRegistered ( ) ;
2026-07-22 22:53:28 +02:00
while ( ! quit_ . load ( ) ) {
if ( auto cmd = PopCmd ( ) ) { HandleCmd ( * cmd ) ; continue ; }
for ( Inbound & in : server_ . Poll ( ) ) {
reply_ = in . reply ;
DispatchRequest ( in . msg ) ;
}
imsd: what the client flow already holds is read before an SMS wait is judged
The run loop judged the wait of the message in flight — its MESSAGE's
final, its submit report — after draining the server ports and before
its read of the client flow. A final that had arrived in time and was
still unread at that pass counted as none: the segment was sent again —
before the repeat existed, the message failed — and the final then
found nothing to own (issue #3, the third of its three cases).
The pass now reads what the flow holds, without waiting, before it
judges: SipFlow::RecvReady returns a message that is whole in the frame
buffer or readable on the socket now. RecvMsg's read of the socket
moved into a helper both use (ReadOnce), and the handling of a message
read from the flow into OnFlowMessage, for the loop's two reads.
Tested on the workstation's loopback with the daemon's own SipFlow built
around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture,
flow-read): over TCP and over UDP RecvReady returns a message the socket
holds without waiting and none when it holds none, and RecvMsg waits its
time and returns a message when one comes; over TCP RecvReady leaves a
message that is not whole yet. On the dev phone the binary of this
range's last commit judged a report's wait at that pass, 130.06 s after
the final, and sent the repeat (the capture's phone-form6,
visit-journal.txt); the pass has not run with a final waiting unread:
that takes a final timed to it.
2026-11-22 17:35:13 +01:00
// the SMS deadline (the final's wait, the report's) is judged after
// the server ports were drained above — a submit report that landed
// during a blocking re-REGISTER below must not count as a timeout —
// and after what the client flow already holds is read here, without
// waiting: a final that came in time and was not yet read must not
// count as one either
if ( SmsWaitOver ( ) ) {
while ( SmsWaitOver ( ) ) {
auto pending = sip_ . RecvReady ( ) ;
if ( ! pending ) break ;
OnFlowMessage ( * pending ) ;
}
if ( SmsWaitOver ( ) ) {
ExecuteSms ( smsOut_ - > OnDeadline ( Mono ( ) ) ) ;
AfterSms ( ) ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
}
// a concatenated set that got no segment for §7.9's 30 min ages out
// on the loop's clock, whether or not another MESSAGE ever comes
for ( const auto & d : reassembler_ . Purge ( Mono ( ) , SmsReassemblyMaxAge ) )
Log ( std : : format ( " sms: a concatenated text from {} (set {}, {} of {} segments held) dropped after {} min: the rest never came " , d . from , d . ref , d . held , d . total , static_cast < int > ( SmsReassemblyMaxAge / 60 ) ) ) ;
2026-07-22 22:53:28 +02:00
MaybeRefresh ( ) ;
MaybeReconnect ( ) ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
MaybeResubscribe ( ) ;
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
MaybeResendInvite ( ) ;
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
if ( crlfKeepalive_ > 0 & & ! call_ & & sip_ . Alive ( ) & & Mono ( ) - lastKa_ > crlfKeepalive_ ) { sip_ . SendKeepalive ( ) ; lastKa_ = Mono ( ) ; }
2026-07-22 22:53:28 +02:00
ReapMedia ( ) ;
if ( call_ & & call_ - > State ( ) ! = imsd : : engine : : CallState : : Active & & Mono ( ) > deadline_ ) {
Execute ( call_ - > OnDeadline ( ) ) ;
MaybeDropCall ( ) ;
}
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
ArmWake ( WakeDue ( ) ) ;
imsd: what the client flow already holds is read before an SMS wait is judged
The run loop judged the wait of the message in flight — its MESSAGE's
final, its submit report — after draining the server ports and before
its read of the client flow. A final that had arrived in time and was
still unread at that pass counted as none: the segment was sent again —
before the repeat existed, the message failed — and the final then
found nothing to own (issue #3, the third of its three cases).
The pass now reads what the flow holds, without waiting, before it
judges: SipFlow::RecvReady returns a message that is whole in the frame
buffer or readable on the socket now. RecvMsg's read of the socket
moved into a helper both use (ReadOnce), and the handling of a message
read from the flow into OnFlowMessage, for the loop's two reads.
Tested on the workstation's loopback with the daemon's own SipFlow built
around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture,
flow-read): over TCP and over UDP RecvReady returns a message the socket
holds without waiting and none when it holds none, and RecvMsg waits its
time and returns a message when one comes; over TCP RecvReady leaves a
message that is not whole yet. On the dev phone the binary of this
range's last commit judged a report's wait at that pass, 130.06 s after
the final, and sent the repeat (the capture's phone-form6,
visit-journal.txt); the pass has not run with a final waiting unread:
that takes a final timed to it.
2026-11-22 17:35:13 +01:00
if ( auto msg = sip_ . RecvMsg ( 0.3 ) ) OnFlowMessage ( * msg ) ;
2026-07-22 22:53:28 +02:00
}
// shutdown: release an active call, keep the SA/registration for resume
if ( call_ ) { Execute ( call_ - > OnHangup ( ) ) ; MaybeDropCall ( ) ; }
sip_ . Close ( ) ;
Log ( " engine stopped (SA left up for resume) " ) ;
}
private :
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
struct Cmd {
enum class Kind { Dial , HangUp , Accept , Dtmf , SendSms , Stop } kind ;
std : : string uni , arg ; // arg: the number to dial, the tones, or a short message's destination
std : : string text ; // SendSms: the text
bool statusReport = false ; // SendSms: ask the SC for a status report
} ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
struct Stopping { } ; // the engine was told to stop while a bring-up waited
imsd: what the client flow already holds is read before an SMS wait is judged
The run loop judged the wait of the message in flight — its MESSAGE's
final, its submit report — after draining the server ports and before
its read of the client flow. A final that had arrived in time and was
still unread at that pass counted as none: the segment was sent again —
before the repeat existed, the message failed — and the final then
found nothing to own (issue #3, the third of its three cases).
The pass now reads what the flow holds, without waiting, before it
judges: SipFlow::RecvReady returns a message that is whole in the frame
buffer or readable on the socket now. RecvMsg's read of the socket
moved into a helper both use (ReadOnce), and the handling of a message
read from the flow into OnFlowMessage, for the loop's two reads.
Tested on the workstation's loopback with the daemon's own SipFlow built
around a bench main (the fp6 journal's 2026-11-20-issues-2-5 capture,
flow-read): over TCP and over UDP RecvReady returns a message the socket
holds without waiting and none when it holds none, and RecvMsg waits its
time and returns a message when one comes; over TCP RecvReady leaves a
message that is not whole yet. On the dev phone the binary of this
range's last commit judged a report's wait at that pass, 130.06 s after
the final, and sent the repeat (the capture's phone-form6,
visit-journal.txt); the pass has not run with a final waiting unread:
that takes a final timed to it.
2026-11-22 17:35:13 +01:00
// Whether the wait of the message in flight — its MESSAGE's final, its
// submit report — has run out by the clock.
bool SmsWaitOver ( ) const { return smsOut_ & & smsOut_ - > Deadline ( ) > 0 & & Mono ( ) > smsOut_ - > Deadline ( ) ; }
// A message read from the client flow outside a REGISTER wait: a request
// is dispatched and answered on the flow; a response goes to the call
// whose INVITE it answers, else to the short message or the delivery
// report whose MESSAGE it answers, else to the reg-event subscription.
void OnFlowMessage ( const std : : string & msg ) {
auto st = imsd : : sip : : Status ( msg ) ;
if ( ! st ) { reply_ = [ this ] ( const std : : string & r ) { sip_ . Send ( r ) ; } ; DispatchRequest ( msg ) ; return ; }
std : : string cseq ( imsd : : sip : : Header ( msg , " CSeq " ) . value_or ( " " ) ) ;
std : : string callid ( imsd : : sip : : Header ( msg , " Call-ID " ) . value_or ( " " ) ) ;
if ( call_ & & callid = = call_ - > CallId ( ) & & cseq . ends_with ( " INVITE " ) ) {
Execute ( call_ - > OnInviteResponse ( msg ) ) ;
MaybeDropCall ( ) ;
} else if ( ! OnSmsResponse ( msg , * st ) ) {
OnSubscribeResponse ( msg , * st ) ;
}
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// A bring-up the network deferred (a fresh-SA throttle) or refused: wait
// it out here, in process, on the recovery policy's schedule, then try
// the bring-up again. There is nothing to reconnect over meanwhile (the
// resume just found the stored SAs unusable, or there are none) and no
// recovery step runs from inside the wait — portPs_ says so to
// MaybeReconnect, whatever the attempt left in it — so a Dial
// meanwhile collapses at once, as in dev mode.
void DeferBringUp ( std : : string_view why , imsd : : engine : : RegRecovery : : Failure f , long retryAfter ) {
FreshAttemptFailed ( f , retryAfter , std : : format ( " bring-up deferred: {} " , why ) ) ;
portPs_ = 0 ;
registered_ = false ;
EmitStatus ( true ) ;
WaitForPolicy ( ) ;
}
// Wait until the policy's next step is due. A Dial/Accept/HangUp
// arriving meanwhile must not wait in the queue and run stale once
// registration succeeds; with no flow the call collapses to terminated
// at once (DevLoop's rule). A wait can be long (an hour on the
// schedule), so the REGISTER after one names the access network read
// after it, not before. False when the engine is stopping.
bool WaitForPolicy ( ) {
bool waited = false ;
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
// No lock under this wait, which can be an hour: nothing is waited
// for from the network, and the alarm ends a sleep at its end. For a
// step it is called from (the bring-up's) the lock is asked for again after.
const int paused = ! quit_ . load ( ) & & recovery_ . Next ( Boot ( ) ) . at > Boot ( ) ? steps_ : 0 ;
for ( int i = 0 ; i < paused ; i + + ) PostWork ( false ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
while ( ! quit_ . load ( ) & & recovery_ . Next ( Boot ( ) ) . at > Boot ( ) ) {
waited = true ;
if ( auto cmd = PopCmd ( ) ) { HandleCmd ( * cmd ) ; MaybeDropCall ( ) ; continue ; }
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
ArmWake ( recovery_ . Next ( Boot ( ) ) . at ) ; // a wait the phone sleeps under ends with the phone awake
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
std : : this_thread : : sleep_for ( std : : chrono : : seconds ( 1 ) ) ;
}
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
for ( int i = 0 ; i < paused ; i + + ) PostWork ( true ) ;
if ( waited ) netAlarm_ ( ) ; // the wait's alarm has fired where the phone slept under it
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( waited & & ! quit_ . load ( ) ) RefreshPani ( ) ;
return ! quit_ . load ( ) ;
}
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
void KeepHolds ( ) { PersistHolds ( recovery_ . Holds ( Boot ( ) ) , pdnLocal_ ) ; }
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// what follows a resume that failed: with a fresh target the fresh
// registration, without one the restart's new resume attempt
std : : string ResumeFailedNext ( ) const { return pcscfTarget_ . empty ( ) ? " the restart tries the resume again " : " the next registration is a fresh one " ; }
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
// a pair nothing can resume (no state file, the file another attempt's or its identity failing the check): with a fresh target the fresh registration replaces it; with none BringUp writes it off and takes it out of the kernel
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
std : : string ResumeDeadNext ( ) const { return pcscfTarget_ . empty ( ) ? " nothing can resume it: the pair is removed " : " resume falls back to fresh " ; }
// the failed resume's line tail by the engine's verdict: a registration it
// wrote off is removed (no fresh target) or replaced by the fresh one; with
// no fresh target a resume it gives up (a 401, a refusal with a Retry-After,
// the second refusal) is removed too; else what ResumeFailedNext says
std : : string ResumeFailedTail ( const std : : string & next ) {
if ( ! recovery_ . Reconnectable ( ) ) return pcscfTarget_ . empty ( ) ? " written off by the network: the pair is removed " : " written off by the network: the next registration is a fresh one " ;
if ( pcscfTarget_ . empty ( ) & & recovery_ . Fresh ( ) ) return " the resume is given up (the engine's rule): the pair is removed " ;
return next ;
}
2026-07-22 22:53:28 +02:00
// dev/session mode without a modem: process commands so the ABI answers,
// but there is no SIP socket — a Dial collapses to terminated/error.
void DevLoop ( ) {
while ( ! quit_ . load ( ) ) {
if ( auto cmd = PopCmd ( ) ) { HandleCmd ( * cmd ) ; MaybeDropCall ( ) ; continue ; }
std : : this_thread : : sleep_for ( std : : chrono : : milliseconds ( 200 ) ) ;
}
}
// config
ipsec, messages, imsd: the offered ESP ciphers are a list
imsd's Security-Client held one mechanism, its cipher the value of EALG,
aes-cbc when unset. TS 33.203 7.2 has the UE's first REGISTER carry "a
list of identifiers for the integrity and encryption algorithms, which
the UE supports", and imsd can install three ciphers: an offer of one
could not say so.
EALG is now a comma-separated list, offered in the order written: one
mechanism per cipher in a single Security-Client, each with the
REGISTER's SPIs and ports (7.2 NOTE 1, NOTE 2). The default stays
aes-cbc alone. A name imsd cannot install is ignored with a journal
line where it used to go out as written, `3des` is offered as
des-ede3-cbc, RFC 3329's name for it, a setting that names no cipher
gives the default, and the bring-up logs what is offered (`ESP ciphers
offered: …`).
An offer of more than one cipher needs a further rule for the 401's
list. O2 UK's P-CSCF lists six mechanisms and puts the SPIs on one: the
sha1 entry without a cipher for a null offer, the sha1 entry with
aes-cbc for an aes-cbc offer (2026-09-17, 2026-09-20). The second has
the higher q, so with both ciphers offered the highest-q offered entry
and the entry carrying the SPIs can be two entries. The entry carrying
the SPIs is therefore taken when it is the only such entry and one of
the offer; otherwise the highest-q offered entry, as before. With one
cipher offered the two name the same algorithms; they can differ in mod
or prot, and there the marked entry's are now taken, where 1.2.1 took
the highest-q entry's.
Tested: tests/Ipsec (the setting; the selection against two offered
ciphers) and tests/Messages (a Security-Client of two mechanisms); the
daemon of this commit against a stand-in P-CSCF on the workstation, with
one cipher offered and with two.
2026-11-23 10:08:04 +01:00
std : : string pcscf_ , dev_ , outDir_ , local_ , mediaBin_ ;
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
long crlfKeepalive_ = 0 ; // CRLF_KEEPALIVE=: seconds between pings on the idle TCP flow; 0: none
ipsec, messages, imsd: the offered ESP ciphers are a list
imsd's Security-Client held one mechanism, its cipher the value of EALG,
aes-cbc when unset. TS 33.203 7.2 has the UE's first REGISTER carry "a
list of identifiers for the integrity and encryption algorithms, which
the UE supports", and imsd can install three ciphers: an offer of one
could not say so.
EALG is now a comma-separated list, offered in the order written: one
mechanism per cipher in a single Security-Client, each with the
REGISTER's SPIs and ports (7.2 NOTE 1, NOTE 2). The default stays
aes-cbc alone. A name imsd cannot install is ignored with a journal
line where it used to go out as written, `3des` is offered as
des-ede3-cbc, RFC 3329's name for it, a setting that names no cipher
gives the default, and the bring-up logs what is offered (`ESP ciphers
offered: …`).
An offer of more than one cipher needs a further rule for the 401's
list. O2 UK's P-CSCF lists six mechanisms and puts the SPIs on one: the
sha1 entry without a cipher for a null offer, the sha1 entry with
aes-cbc for an aes-cbc offer (2026-09-17, 2026-09-20). The second has
the higher q, so with both ciphers offered the highest-q offered entry
and the entry carrying the SPIs can be two entries. The entry carrying
the SPIs is therefore taken when it is the only such entry and one of
the offer; otherwise the highest-q offered entry, as before. With one
cipher offered the two name the same algorithms; they can differ in mod
or prot, and there the marked entry's are now taken, where 1.2.1 took
the highest-q entry's.
Tested: tests/Ipsec (the setting; the selection against two offered
ciphers) and tests/Messages (a Security-Client of two mechanisms); the
daemon of this commit against a stand-in P-CSCF on the workstation, with
one cipher offered and with two.
2026-11-23 10:08:04 +01:00
std : : vector < std : : string > ealgOffer_ ; // the ESP ciphers offered, in order
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
// The P-CSCF a fresh registration goes to (PCSCF=, else the first of
// PCSCF_DISCOVERED=) and the whole discovered list. pcscf_ is the one in
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// use: the same, or the kernel's SA peer while a resumed registration
// made to another one lives (TryResume) — the next fresh registration
// moves to the target, and back when it fails before the SA setup
// (FreshRecover), as local_ does against pdnLocal_.
std : : string pcscfTarget_ ;
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
std : : vector < std : : string > pcscfCandidates_ ;
ims-pdn-up: discover the P-CSCF list once the PDN is up and hand it to imsd
With the netdev configured, the script runs imsd-pcscf against the
netdev's rmnet mux id (and the ims profile index when it knows one) and
hands the IPv6 addresses it prints to imsd as PCSCF_DISCOVERED= in
/run/imsd.env and gives the first — the daemon's fresh target — a host
route (the SA peer of a registration imsd resumes is routed by imsd itself,
as the configured address's arm already left it); IPv4 addresses and names
are logged and dropped (the PDN is IPv6-only), at most eight are handed
over, and nothing usable is logged with its cause and is not the
script's failure: imsd resumes a registration of its own when it can, else
says so and exits, and the restart runs discovery again. PCSCF= still wins and skips discovery; a list in it is refused.
The script does not read the variable from its environment: the unit
hands it the previous run's file, and a stale discovered value must not
pass for the admin's setting. The reader's path is the IMSD_PCSCF seam
the mock bench uses.
Tested: on the mock bench against this commit's script (the twelve 0.3.10
scenarios; this step's discovery arms S13–S17 and S19–S22, with S18 the
pre-existing non-IPv6 refusal; S55, the reader's rc-0 answer without an
address), and in builds of this series on the dev phone (KPN), whose PCO —
two IPv6 addresses, nothing else — reaches the plain found arm; the
configured skip, the bracketed refusal and, through the IMSD_PCSCF seam, the
reader's failure and its exit 2 ran on the phone too; the v4/FQDN line, the
eight-address cap, the IPv4-only and no-mux-id skips, the comma-list refusal
and the rc-0 arm on the mock only. On a tip build of this series (daemon
2ec1a02f62831edb; bench 40, 2026-10-13) a fresh registration reached a target
this script had not routed — the reader stubbed through the IMSD_PCSCF seam to
find none, the address in /etc/imsd.env as PCSCF_DISCOVERED= — over imsd's own
route, and a resume stood with the peer's route removed first.
2026-10-11 16:16:46 +02:00
static constexpr std : : string_view NoFreshPcscf = " no P-CSCF for a fresh registration: none configured (PCSCF=) and none discovered (PCSCF_DISCOVERED empty — see the ims-pdn-up lines) " ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
// The PDN's own address (LOCAL, else DetectLocal) — every fresh
// registration's. local_ differs from it only while a resume runs on the
// address an older registration was made on (TryResume).
std : : string pdnLocal_ ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
std : : string sipPolicy_ ; // SIP_TRANSPORT: auto | tcp | udp
Transport transport_ = Transport : : Tcp ; // the protected leg's transport in effect
void SetTransport ( Transport t ) { transport_ = t ; ctx_ . transport = std : : string ( TransportName ( t ) ) ; }
Emergency calling, stage 1: urn:service:sos with a digits fallback
Classify 112/911 (plus EMERGENCY_NUMBERS) at Dial. A classified call
INVITEs urn:service:sos over the existing registration and, on any
non-2xx final not caused by the user hanging up (including the
setup-timeout CANCEL paths), retries once as a plain INVITE of the
dialled digits — the pre-0.3.0 behavior, so classification can never
place a call worse than the status quo. The reverse edge: a 380
Alternative Service whose body carries the emergency indication
upgrades an unclassified call to the sos URN; a bare 380 stays an
error, since promoting an arbitrary redirect would put a
non-emergency call through to a PSAP. An emergency dial preempts an
in-progress call, and an answer racing a deadline-initiated CANCEL is
taken instead of BYE'd (user-initiated CANCEL races still BYE).
No emergency registration, no emergency PDN, no CS fallback, no
SIM-less calling, no AML — and no carrier has confirmed the sos path
end-to-end. The README warning states exactly that.
Assisted-by: Claude:claude-fable-5
2026-08-01 22:29:12 +02:00
std : : vector < std : : string > emergencyExtra_ ;
2026-07-22 22:53:28 +02:00
int pcscfPort_ = 5060 ;
int rtpPort_ = 50004 ;
bool precond_ = false ;
engine/sdp: CODECS override for the codecs we offer and accept
KPN's interconnect gateway transcodes every caller up: a G.711-only
fixed-line INVITE reached the phone offering PCMA, PCMU, AMR and AMR-WB
(bench call 2026-09-08), so the AMR-WB-only build rang and the narrowband
path — the one the Telia field report hit with 488 — cannot be reached on
the air through KPN by any caller.
CODECS=<list> (comma-separated over AMR-WB, AMR/AMR-NB, PCMA, PCMU) makes
the list both the codecs offered on an outgoing call and the acceptance
preference for an inbound offer, in that order: CODECS=PCMA takes G.711
A-law out of the mixed offer above, CODECS=PCMA,PCMU sends a G.711-only
offer toward the network. Unset, nothing changes — the default offer
bytes and the AMR-WB > AMR > PCMA > PCMU preference stay pinned. The
daemon logs an active override at startup.
2026-09-08 17:53:26 +02:00
std : : vector < std : : string > codecs_ ; // CODECS override; empty = defaults
2026-07-22 22:53:28 +02:00
// registration
imsd : : msg : : Context ctx_ ;
RegState reg_ ;
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
// The identity the card gives — its ISIM's, else the one derived from
// the IMSI — and the derived one. A fresh registration is made under the
// first. A resumed one keeps the identity it was made under (reg_.id)
// until the next fresh registration, as it keeps its P-CSCF and its
// address: the binding to refresh is the one made under those names.
imsd : : aka : : Identity cardId_ ;
imsd : : aka : : Identity derivedId_ ;
// The card's USIM: the challenge goes to it when the identity is not an
// ISIM's, and after an ISIM that gave the identity and gives no result
// for the challenge.
std : : string usimAid_ ;
// The ISIM application that has given no identity since the bring-up:
// asked again at each recovery by a fresh registration later in the
// same run (FreshRecover), which else would go out under the derived
// names.
std : : optional < imsd : : aka : : IsimApp > isimOwed_ ;
2026-07-22 22:53:28 +02:00
std : : string route_ , ppi_ , ss_ ;
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
std : : string simOperator_ ; // the SIM's operator id as read at bring-up: MCC then MNC
2026-07-22 22:53:28 +02:00
bool registered_ = false ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
SipFlow sip_ ;
2026-07-22 22:53:28 +02:00
ServerPorts server_ ;
std : : string subCallid_ ; // live reg-event subscription dialog (empty: none)
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
bool subPending_ = false ; // SUBSCRIBE sent, no final yet
double subSentAt_ = 0 ;
double subRetryAt_ = 0 ; // a failed/ended subscription is renewed at this time (0: none due)
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
double subRenewAt_ = 0 ; // the live subscription is subscribed anew at this time on the boot clock, ahead of its granted expiry (0: none)
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
double subRetryDelay_ = 60 ; // 60 s doubling to 10 min between failed SUBSCRIBEs
2026-07-22 22:53:28 +02:00
int portPs_ = 0 ; // P-CSCF protected server port (reconnect target)
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
imsd : : engine : : RegRecovery recovery_ ; // what to do when the registration stops working
bool saReplaced_ = false ; // the running fresh attempt got past the SA setup (the old registration's SAs are gone)
2026-07-22 22:53:28 +02:00
// call
imsd : : util : : Rng rng_ ;
std : : optional < imsd : : engine : : CallMachine > call_ ;
bool dropCall_ = false ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
bool closeFlowWhenIdle_ = false ; // a binding was terminated under a call: its flow closes with the call
2026-07-22 22:53:28 +02:00
pid_t mediaPid_ = - 1 ;
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
int mediaCtl_ = - 1 ; // our end of the leg's control pipe (its stdin)
2026-07-22 22:53:28 +02:00
double deadline_ = 0 ;
// reply_ answers the inbound request being dispatched right now;
// callReply_ is the call's durable response channel — refreshed from
// reply_ on every in-dialog request, so an Accept()'s 200 OK (which
// happens outside any inbound dispatch) still reaches the caller.
std : : function < void ( const std : : string & ) > reply_ ;
std : : function < void ( const std : : string & ) > callReply_ ;
// timers
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
double lastRefresh_ = 0 ; // on the boot clock (Boot): the registration's lifetime runs at the network while the phone sleeps
double lastKa_ = 0 ; // on the steady clock (Mono)
int wakeFd_ = - 1 ; // the wake alarm, a timer on CLOCK_BOOTTIME_ALARM (-2: the kernel gave none)
double wakeAt_ = 0 ; // the boot-clock time it was last armed for, fired or not (0: not armed)
2026-07-22 22:53:28 +02:00
std : : atomic < bool > quit_ { false } ;
bool devMode_ = false ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// SMS over IP (§7.9)
bool smsOverIp_ = false ;
std : : string smscOverride_ ; // SMSC=
std : : string smsc_ ; // the service centre's number (empty: none known)
std : : vector < std : : uint8_t > scAddress_ ; // the same as the RP-DATA's destination: [octets][toa][digits]
std : : optional < std : : uint8_t > smsValidity_ ; // EF_SMSP's TP-Validity-Period
engine, imsd: a submit report for a MESSAGE no longer in flight that this run sent in the last hour is answered 200
TS 24.341 5.3.1.2 has a submit report answered 200 when its In-Reply-To
"indicates that the request corresponds to a short message submitted by
the SM-over-IP sender" and 488 when it does not, and its NOTE 3 has the
sender store the Call-ID for that. imsd knew only the Call-ID of the
segment in flight (OwnsReport): a report that came once its message had
ended — the 40 s wait run out — or once its segment was followed by the
next was answered 488 like a stranger's, and its line said only "no
MESSAGE of ours in flight" (issue #3, the first of its three cases).
RecentSubmissions keeps the Call-ID of every MESSAGE a submission goes
out in for an hour, with the message's id and the segment. A report
In-Reply-To one of them that the message in flight does not take is
answered 200, and the journal has `submit report (RP-ACK) In-Reply-To
…: sms <id>'s segment i/n, no longer in flight; 200`, an RP-ERROR's
with its cause. The 488 is left for an In-Reply-To that names no MESSAGE
of ours on record, and its line says so ("on record" for "in flight").
A report without In-Reply-To that no message in flight takes by its
RP-MR is answered 200 as before; its line ends `that no message in
flight owns; 200` where it ended `for no message in flight; 200`.
The bus is told nothing of a late report: the Messaging interface is
frozen with `failed` as a message's last word (AGENTS.md §8.4), so a
text the service centre took after its wait had run out stays `failed`
there; the journal's line is the record of it.
Tested by tests/Engine: the table (a Call-ID on record for 3600 s, the
first of a list that is ours, each segment's MESSAGE put on record as it
goes out) and OnSmsMessage (200 and the line for a report on a segment
that was followed by the next, on a message that was sent and, with an
RP-ERROR's cause, on one its wait had ended; 488 and its line for a
stranger's). On the dev phone, with the binary of this range's last
commit, no report came for a MESSAGE no longer in flight (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6), so the 200 for
one and its line have run in the suite alone.
2026-11-22 17:35:12 +01:00
imsd : : engine : : RecentSubmissions smsSubmitted_ ; // the Call-IDs of the MESSAGEs our submissions went out in, an hour each: a late submit report is answered 200, not 488
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
std : : optional < imsd : : engine : : SmsOutbound > smsOut_ ; // the message in flight
std : : deque < std : : pair < std : : string , imsd : : engine : : SmsOutbound : : Params > > smsPending_ ; // queued behind it
std : : set < std : : string > reportCallIds_ ; // the delivery reports' Call-IDs, each until a final comes for it
imsd : : engine : : StatusReportBook reports_ ; // the messages that asked for a status report, by TP-MR: a word for the whole message
imsd : : engine : : SmsWordOrder smsOrder_ ; // the submission's word before a report's (§8.4)
imsd : : sms : : Reassembler reassembler_ ;
imsd : : engine : : RecentTransactions recentMessages_ ; // the retransmission table of inbound MESSAGEs outside a call's dialog (TimerJ)
std : : uint8_t tpMr_ = 0 ; // the next TP-MR, RP-MR and concatenation reference
std : : uint8_t rpMr_ = 0 ;
std : : uint8_t concatRef_ = 0 ;
const std : : string smsRun_ = imsd : : engine : : RunToken ( std : : random_device { } ( ) ) ; // every id's first field after its prefix: this run's token — another run gives an id out again only with the same token, second and counter
const std : : int64_t smsStart_ = NowEpoch ( ) ; // the sent ids' second
std : : atomic < std : : uint64_t > smsSeq_ { 0 } ; // Send (D-Bus thread) mints ids
std : : uint64_t smsInSeq_ = 0 ; // received messages' ids (engine thread)
2026-07-22 22:53:28 +02:00
// command queue
std : : mutex cmdLock_ ;
std : : deque < Cmd > cmds_ ;
// atomic: Dial (D-Bus thread) and an inbound INVITE (engine thread) both mint unis
std : : atomic < std : : uint64_t > callSeq_ { 0 } ;
static double Mono ( ) {
return std : : chrono : : duration < double > ( std : : chrono : : steady_clock : : now ( ) . time_since_epoch ( ) ) . count ( ) ;
}
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
// The refresh's interval: half the granted lifetime (of 3600 s where none
// was granted), within 120-1800 s (REFRESH_INTERVAL= sets it).
double RefreshInterval ( ) const {
if ( const char * o = std : : getenv ( " REFRESH_INTERVAL " ) ) return std : : atof ( o ) ;
long exp = reg_ . expiry ? reg_ . expiry : 3600 ;
return std : : max ( 120.0 , std : : min ( exp * 0.5 , 1800.0 ) ) ;
}
// The wake alarm. The registration's lifetime runs at the network while
// the phone sleeps, and the steady clock does not: a refresh counted in
// awake seconds comes too late for a phone that sleeps most of the time
// (the dev phone, 2026-11-19: asleep for most of a registration's two hours, no refresh, the
// binding expired). So the refresh is due on the boot clock, and a timer
// on CLOCK_BOOTTIME_ALARM, armed by the loop for the time WakeDue names (ArmWake's other callers arm their own), makes the
// kernel wake a sleeping phone then (its RTC's alarm; CAP_WAKE_ALARM,
// which the system service has). The descriptor is never read: the
// waking is the whole of it, and the loop's own clock checks act once
// the phone is awake. Where the kernel gives no such timer the journal
// says so once and the daemon runs without: awake, nothing differs.
void ArmWake ( double at ) {
if ( wakeTrace_ ) TraceWake ( at ) ;
if ( wakeFd_ = = - 2 | | at = = wakeAt_ ) return ;
if ( wakeFd_ < 0 ) {
// the timer can be had without an RTC behind it, and then
// neither wakes the phone nor makes the kernel refuse a suspend:
// the clock's resolution is what the kernel answers only with one
timespec res { } ;
if ( clock_getres ( CLOCK_BOOTTIME_ALARM , & res ) ! = 0 ) {
Log ( " no wake alarm (no RTC that can wake the phone): a sleeping phone is not woken for the registration's refresh " ) ;
wakeFd_ = - 2 ;
return ;
}
wakeFd_ = timerfd_create ( CLOCK_BOOTTIME_ALARM , TFD_CLOEXEC ) ;
if ( wakeFd_ < 0 ) {
Log ( std : : format ( " no wake alarm ({}): a sleeping phone is not woken for the registration's refresh " , std : : strerror ( errno ) ) ) ;
wakeFd_ = - 2 ;
return ;
}
Log ( " wake alarm: a sleeping phone is woken when the registration's refresh is due " ) ;
}
itimerspec its { } ; // all zero disarms
if ( at > 0 ) {
its . it_value . tv_sec = static_cast < time_t > ( at ) ;
its . it_value . tv_nsec = static_cast < long > ( ( at - std : : floor ( at ) ) * 1e9 ) ;
}
if ( timerfd_settime ( wakeFd_ , TFD_TIMER_ABSTIME , & its , nullptr ) < 0 ) {
Log ( std : : format ( " wake alarm not set: {} " , std : : strerror ( errno ) ) ) ;
return ;
}
wakeAt_ = at ;
}
// What the loop arms the alarm for at the end of a turn that took no
// command off the queue (one that took a command handles it and goes
// straight to the next turn). A time that has come (a call, a text in
// flight; a step that is due, which the next turn runs) is armed
// WakeHold ahead at every such turn: the kernel refuses a suspend
// that finds an alarm less than two seconds ahead at its check (alarmtimer_suspend),
// whoever asks for it. For a step that follows a local wait (no
// packet service, a connect the kernel refused) the policy names the
// slower look's time: with no call and no text in flight nothing is
// held then.
static constexpr double WakeHold = 1.9 ;
// WAKE_TRACE=1, a test seam: a line whenever the time the alarm is
// armed for changes (by the second), with or without a timer to arm (a
// bench has none). A time under two seconds ahead is "held", said once
// while it lasts.
const bool wakeTrace_ = EnvOr ( " WAKE_TRACE " , " 0 " ) = = " 1 " ;
std : : string wakeTraced_ ;
void TraceWake ( double at ) {
double ahead = at - Boot ( ) ;
std : : string s = at < = 0 ? " none " : ahead < 2 ? " held under 2 s ahead " : std : : format ( " {:.0f} s on the boot clock " , at ) ;
if ( s = = wakeTraced_ ) return ;
wakeTraced_ = s ;
Log ( at > 0 & & ahead > = 2 ? std : : format ( " wake trace: {} ({:.0f} s ahead) " , s , ahead ) : std : : format ( " wake trace: {} " , s ) ) ;
}
double WakeDue ( ) const {
bool recovering = portPs_ ! = 0 & & ! reg_ . callid . empty ( ) ; // MaybeReconnect's own condition
bool renewal = registered_ & & ! subCallid_ . empty ( ) & & ! subPending_ ; // MaybeResubscribe's own, with the live flow
double now = Boot ( ) ;
double at = imsd : : engine : : WakeAt ( now , call_ . has_value ( ) | | smsOut_ . has_value ( ) , ! reg_ . callid . empty ( ) & & sip_ . Alive ( ) ,
lastRefresh_ + RefreshInterval ( ) , renewal ? subRenewAt_ : 0 ,
recovering , recovering ? recovery_ . WakeTime ( now ) : 0 ) ;
return at > 0 & & at < now + WakeHold ? now + WakeHold : at ;
}
// A step of the registration that exchanges with the network: the
// refresh, a reconnect, a fresh registration, the bring-up. The main
// thread asks for logind's sleep lock while one runs (WorkLock, which a
// text in flight wants as well; held where logind gives it), so that the step's waits run their
// awake seconds in one piece; not while the bring-up waits out a hold
// (WaitForPolicy). For a sleep that begins under a step all the same
// (logind refused such a lock on the dev phone where a suspend's operation was already running; a suspend
// told to ignore inhibitors) the alarm stands at most WakeNet ahead
// while the step waits for the network: set as it begins, and anew
// before every second of a connect's wait, of the pause before the next
// try and of a wait for a REGISTER's answer. It fires once, and a wait
// can outlast the sleep it ended: set every second, it stands again
// within a second of that wake, for the sleep that may follow. Where there is an alarm the
// sleep ends there, a lock logind had refused is asked for at its end (one held is kept), and the step goes
// on. A wait for a helper program (mmcli, qmicli, ip) has the alarm
// that stood when it began, once. After the step
// the loop's own arming takes over again (WakeDue).
static constexpr double WakeNet = 30 ;
struct Step {
explicit Step ( Engine & engine ) : e ( engine ) { e . steps_ + + ; e . PostWork ( true ) ; e . netAlarm_ ( ) ; }
~ Step ( ) { e . steps_ - - ; e . PostWork ( false ) ; }
Step ( const Step & ) = delete ;
Step & operator = ( const Step & ) = delete ;
Engine & e ;
} ;
int steps_ = 0 ; // the steps under way: what a hold's wait pauses (WaitForPolicy)
bool noServiceTold_ = false ; // the journal has the line of the coverage gap that runs
// What a step sets the alarm to as it begins and before every second of
// its waits for the network: WakeNet ahead, also where a call or a text
// is in flight (the loop's WakeHold needs setting anew within two
// seconds, which a helper program's wait does not give: under a step
// the sleep is bounded, not refused).
const std : : function < void ( ) > netAlarm_ = [ this ] { ArmWake ( Boot ( ) + WakeNet ) ; } ;
// The connect for a call's resend is no step: no helper program runs
// under it, and the loop arms again at the end of the turn it runs in.
// It keeps the loop's hold through its wait, set anew every second.
const std : : function < void ( ) > holdAlarm_ = [ this ] { ArmWake ( Boot ( ) + WakeHold ) ; } ;
void PostWork ( bool on ) {
auto ev = std : : make_unique < Event > ( ) ;
ev - > type = Event : : Type : : Work ; ev - > on = on ;
PostEvent ( std : : move ( ev ) ) ;
}
2026-07-22 22:53:28 +02:00
std : : optional < Cmd > PopCmd ( ) {
std : : scoped_lock g ( cmdLock_ ) ;
if ( cmds_ . empty ( ) ) return std : : nullopt ;
Cmd c = cmds_ . front ( ) ; cmds_ . pop_front ( ) ;
return c ;
}
static std : : string ResolveMediaBin ( ) {
if ( const char * e = std : : getenv ( " IMSD_MEDIA " ) ) return e ;
if ( ! SelfDir . empty ( ) ) {
std : : string p = std : : format ( " {}/imsd-media " , SelfDir ) ;
if ( access ( p . c_str ( ) , X_OK ) = = 0 ) return p ;
}
return " /usr/libexec/imsd-media " ;
}
// Refresh P-Access-Network-Info from the live serving cell (mmcli 3GPP
// location). Serving cell changes as the phone moves, so this runs
// before every REGISTER/INVITE-carrying step; on failure the previous
// value (possibly empty = header omitted) stays.
void RefreshPani ( ) {
auto loc = RunCapture ( { " mmcli " , " -m " , " any " , " --location-get " } ) ;
if ( auto p = imsd : : aka : : ParsePani ( loc . out ) ) ctx_ . panInfo = * p ;
}
// ---- bring-up: warm resume if an SA + state file exist, else fresh ----
void BringUp ( ) {
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
if ( pcscfTarget_ . contains ( ' , ' ) ) throw std : : runtime_error ( std : : format ( " PCSCF='{}' must be one address " , pcscfTarget_ ) ) ;
ipsec, imsd, ims-pdn-up: the SA reader and the holds key compare in canonical form; LOCAL is canonicalised, PCSCF= accepted in RFC 5952 §4 form only
ParseExistingSa and SaLocals compared PCSCF= and LOCAL= as text against
`ip xfrm` output, which prints RFC 5952 form, so an upper-case or
uncompressed PCSCF= found no SAs and the restart registered fresh — on
KPN into the live-SA refusal; the holds file's pdn key compared the same
way. Both sides of each of those compares now go through
imsd::util::CanonicalAddr, LOCAL is canonicalised once on the way in, and PCSCF= is accepted in
that one spelling only — upper case, leading zeros or an uncompressed run
are refused at bring-up with the spelling to use, a dotted-quad tail (the
form ip prints for an IPv4-mapped address, which CanonicalIp6 does not read)
with the rule alone, a bracketed one by the bring-up script, which routes
the value as typed, with the rule (no brackets) — and a comma-separated
PCSCF= (a list) with its own message instead of reaching the socket layer: one spelling,
instead of a leniency both consumers of the setting would have to share.
Tested: crafter-build test, 7 passed; the upper-case PCSCF= refused with the spelling to use, a bracketed one
refused by the script, and the spelling they name resuming, in builds of
this series on the dev phone (KPN).
2026-10-11 15:55:19 +02:00
// PCSCF= is accepted in one spelling only: the one `ip` prints (RFC
// 5952 — what the journal and `ip xfrm` show). Another spelling is
// refused with the one to use rather than normalised, so the bring-up
// script, which routes the value as typed, and the daemon agree on it.
if ( std : : string raw = EnvOr ( " PCSCF " , " " ) ; ! raw . empty ( ) ) {
auto canon = imsd : : util : : CanonicalIp6 ( raw ) ;
if ( ! canon | | * canon ! = raw ) throw std : : runtime_error ( std : : format ( " PCSCF='{}' is not written as ip prints it; use PCSCF={} " , raw , canon . value_or ( " <one bare IPv6 address, RFC 5952 form> " ) ) ) ;
}
2026-07-22 22:53:28 +02:00
auto card = RunCapture ( { " qmicli " , " -d " , " qrtr://0 " , " --uim-get-card-status " } ) ;
auto sel = imsd : : aka : : ParseCardStatus ( card . out ) ;
if ( ! sel ) throw std : : runtime_error ( " no ready USIM found " ) ;
auto modem = RunCapture ( { " mmcli " , " -m " , " any " } ) ;
auto simPath = imsd : : aka : : ParsePrimarySimPath ( modem . out ) ;
if ( ! simPath ) throw std : : runtime_error ( " no primary SIM path " ) ;
auto siminfo = RunCapture ( { " mmcli " , " -i " , * simPath } ) ;
auto info = imsd : : aka : : ParseSimInfo ( siminfo . out ) ;
if ( ! info ) throw std : : runtime_error ( " SIM IMSI/operator not found " ) ;
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
derivedId_ = imsd : : aka : : MakeIdentity ( info - > imsi , info - > mcc , info - > mnc ) ;
cardId_ = derivedId_ ;
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
simOperator_ = info - > mcc + info - > mnc ;
2026-07-22 22:53:28 +02:00
ctx_ . local = local_ ;
ctx_ . ealgOffer = ealgOffer_ ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
SetTransport ( transport_ ) ;
Log ( std : : format ( " SIP transport: {} ({}) " , TransportName ( transport_ ) , sipPolicy_ ) ) ;
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
if ( crlfKeepalive_ > 0 ) Log ( std : : format ( " CRLF keepalive: every {} s on an idle TCP flow (CRLF_KEEPALIVE) " , crlfKeepalive_ ) ) ;
ipsec, messages, imsd: the offered ESP ciphers are a list
imsd's Security-Client held one mechanism, its cipher the value of EALG,
aes-cbc when unset. TS 33.203 7.2 has the UE's first REGISTER carry "a
list of identifiers for the integrity and encryption algorithms, which
the UE supports", and imsd can install three ciphers: an offer of one
could not say so.
EALG is now a comma-separated list, offered in the order written: one
mechanism per cipher in a single Security-Client, each with the
REGISTER's SPIs and ports (7.2 NOTE 1, NOTE 2). The default stays
aes-cbc alone. A name imsd cannot install is ignored with a journal
line where it used to go out as written, `3des` is offered as
des-ede3-cbc, RFC 3329's name for it, a setting that names no cipher
gives the default, and the bring-up logs what is offered (`ESP ciphers
offered: …`).
An offer of more than one cipher needs a further rule for the 401's
list. O2 UK's P-CSCF lists six mechanisms and puts the SPIs on one: the
sha1 entry without a cipher for a null offer, the sha1 entry with
aes-cbc for an aes-cbc offer (2026-09-17, 2026-09-20). The second has
the higher q, so with both ciphers offered the highest-q offered entry
and the entry carrying the SPIs can be two entries. The entry carrying
the SPIs is therefore taken when it is the only such entry and one of
the offer; otherwise the highest-q offered entry, as before. With one
cipher offered the two name the same algorithms; they can differ in mod
or prot, and there the marked entry's are now taken, where 1.2.1 took
the highest-q entry's.
Tested: tests/Ipsec (the setting; the selection against two offered
ciphers) and tests/Messages (a Security-Client of two mechanisms); the
daemon of this commit against a stand-in P-CSCF on the workstation, with
one cipher offered and with two.
2026-11-23 10:08:04 +01:00
{
std : : string list ;
for ( const std : : string & e : ealgOffer_ ) list + = ( list . empty ( ) ? " " : " , " ) + e ;
Log ( std : : format ( " ESP ciphers offered: {} " , list ) ) ;
}
2026-07-22 22:53:28 +02:00
// USER_AGENT overrides (some networks fingerprint UAs — setting the
// stock firmware's build string gives oracle parity, journal/ims.md
// s53); USER_AGENT= (empty) omits the header.
ctx_ . userAgent = EnvOr ( " USER_AGENT " , std : : format ( " imsd/{} " , Version ) ) ;
if ( auto imei = imsd : : aka : : ParseEquipmentId ( modem . out ) )
if ( auto urn = imsd : : aka : : ImeiUrn ( * imei ) ) ctx_ . instanceId = * urn ;
reg_ . slot = sel - > slot ;
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
reg_ . aid = usimAid_ = sel - > aid ;
// The identity so far is the one TS 23.003 derives from the IMSI,
// the names of a UE without an ISIM (TS 24.229 5.1.1.1A). When the
// card's ISIM gives an identity, that one is the card's and the
// challenge goes to the ISIM. The names can be the operator's own: a US
// card on AT&T's network holds <IMSI>@private.att.net and
// one.att.net, and the derived names drew a 480 to the first
// REGISTER there (2026-11-09; the read of the card 2026-11-23,
// AGENTS.md §13). An ISIM that gives none leaves the derived
// identity and the USIM, what 1.2.2 registered with; ISIM=0 asks for
// that.
std : : optional < imsd : : aka : : IsimApp > app ;
if ( EnvOr ( " ISIM " , " 1 " ) = = " 0 " ) {
Log ( " identity: derived from the IMSI (ISIM=0) " ) ;
} else {
app = imsd : : aka : : ParseIsimApp ( card . out , sel - > slot ) ;
if ( ! app ) Log ( " identity: derived from the IMSI (the card has no ISIM application) " ) ;
}
isimOwed_ = app & & ! TakeIsimIdentity ( * app ) ? app : std : : nullopt ;
ctx_ . id = cardId_ ;
2026-07-22 22:53:28 +02:00
Log ( std : : format ( " SIM slot={} IMSI={} domain={} " , sel - > slot , info - > imsi , ctx_ . id . domain ) ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
ctx_ . smsOverIp = smsOverIp_ ;
if ( smsOverIp_ ) LoadSmsParameters ( ) ;
2026-07-22 22:53:28 +02:00
RefreshPani ( ) ;
std : : string resume = EnvOr ( " RESUME " , " auto " ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// A resume that the network refuses (403 after another process
// registered fresh for the same IMPI, a stale binding, …) is not
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// fatal while there is a fresh target: the fresh registration below
// replaces its SAs, and only a failed FRESH registration is. With no
// fresh target the bring-up ends as §7.2 step 1 says.
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// The network's word holds at bring-up as it does in recovery: a
// hold from before this start is waited out before the resume (a
// refresh's Retry-After) or the fresh registration (a fresh attempt's
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// schedule or Retry-After, a terminated binding's wait), and so is
// one the resume itself earns — a refusal's Retry-After, a binding
// a NOTIFY terminated under it.
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
ResumeOutcome outcome = ResumeOutcome : : Dead ; // not tried (RESUME=0, or written off before this start): a pair nothing resumes
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( resume ! = " 0 " ) {
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( ! WaitForPolicy ( ) ) throw Stopping { } ;
// a registration the network wrote off before this start (the
// holds carry it) is not resumed: the wait above was the fresh one
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
const std : : string next = ResumeFailedNext ( ) ;
try { if ( recovery_ . Reconnectable ( ) ) { outcome = TryResume ( ) ; if ( outcome = = ResumeOutcome : : Done ) return ; } }
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
catch ( const RefusedError & e ) {
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
outcome = ResumeOutcome : : Failed ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
CloseFlowAfterWait ( ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// the network's word (a Retry-After) reaches the reducer as before;
// with no fresh target every refusal does — its count travels in
// the holds, so a restart's refusal is the second (§7.4). With a
// target a refusal without one feeds nothing: the fresh
// registration follows at once, not after a self-imposed backoff
// the fresh path would log as the network's hold
if ( e . retryAfter > 0 | | pcscfTarget_ . empty ( ) ) recovery_ . OnReconnectFailure ( Boot ( ) , imsd : : engine : : RegRecovery : : Failure : : Refused , e . retryAfter , e . status ) ;
Log ( std : : format ( " resume failed: {} — {} " , e . what ( ) , ResumeFailedTail ( next ) ) ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
}
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
catch ( const std : : exception & e ) { outcome = ResumeOutcome : : Failed ; CloseFlowAfterWait ( ) ; Log ( std : : format ( " resume failed: {} — {} " , e . what ( ) , ResumeFailedTail ( next ) ) ) ; }
// the engine's verdict decides, in one place for both arms: a
// registration it wrote off (a 403 once a fresh registration is
// due; a binding a NOTIFY terminated under the re-REGISTER wait,
// Imsd-Engine.cppm) is nothing to resume any more, and so, with no
// fresh target, is one whose resume it gives up (a 401, a refusal
// with a Retry-After, the second refusal — RefusalsBeforeFresh,
// the count surviving the restart): Dead, taken out below. With a
// target the fresh registration follows either way.
if ( outcome = = ResumeOutcome : : Failed & & ( ! recovery_ . Reconnectable ( ) | | ( pcscfTarget_ . empty ( ) & & recovery_ . Fresh ( ) ) ) ) outcome = ResumeOutcome : : Dead ;
}
if ( pcscfTarget_ . empty ( ) ) {
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// No fresh registration follows, so a resumable pair is not written
// off: one whose attempt failed (a silent connect, an
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// unanswered or refused refresh — its Retry-After is in the
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// holds) stays for the restart to resume (the fatal and the
// retry) — unless the engine's rule wrote the registration off or
// gave the resume up (a 403 once fresh is due, a NOTIFY-terminated
// binding; a 401, a refusal with a Retry-After, the second refusal —
// the count travels in the holds; Dead above); a pair nothing can
// resume (its UE address left the link, no
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
// state file, the file another attempt's or its identity failing
// the check, written off before this
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// start) is written off and taken out of the kernel by exact key
// — the fresh registration that would have replaced it does not
// come — so the next bring-up finds nothing to resume, and the
// daemon idles (RequestIdle: a clean exit, §7.3): the PCO named no
// P-CSCF and nothing is configured, a fact until a boot or a
// start. A discovery that FAILED (the reader did not answer) is
// no fact: the fatal, and the restart runs it again.
if ( outcome = = ResumeOutcome : : Dead ) { recovery_ . OldGone ( ) ; RemoveDeadPair ( pdnLocal_ ) ; }
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
KeepHolds ( ) ;
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
if ( outcome = = ResumeOutcome : : Failed | | DiscoveryFailed ( ) ) throw std : : runtime_error ( std : : string ( NoFreshPcscf ) ) ;
RequestIdle ( std : : string ( NoPcscfIdleText ) ) ; throw Stopping { } ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// a resume that failed found the stored SAs unusable (and after a
// reboot there are none): nothing to reconnect over while a deferred
// fresh registration waits
recovery_ . OldGone ( ) ;
portPs_ = 0 ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
local_ = pdnLocal_ ; ctx_ . local = local_ ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
KeepHolds ( ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
pcscf_ = pcscfTarget_ ;
ims-pdn-up: discover the P-CSCF list once the PDN is up and hand it to imsd
With the netdev configured, the script runs imsd-pcscf against the
netdev's rmnet mux id (and the ims profile index when it knows one) and
hands the IPv6 addresses it prints to imsd as PCSCF_DISCOVERED= in
/run/imsd.env and gives the first — the daemon's fresh target — a host
route (the SA peer of a registration imsd resumes is routed by imsd itself,
as the configured address's arm already left it); IPv4 addresses and names
are logged and dropped (the PDN is IPv6-only), at most eight are handed
over, and nothing usable is logged with its cause and is not the
script's failure: imsd resumes a registration of its own when it can, else
says so and exits, and the restart runs discovery again. PCSCF= still wins and skips discovery; a list in it is refused.
The script does not read the variable from its environment: the unit
hands it the previous run's file, and a stale discovered value must not
pass for the admin's setting. The reader's path is the IMSD_PCSCF seam
the mock bench uses.
Tested: on the mock bench against this commit's script (the twelve 0.3.10
scenarios; this step's discovery arms S13–S17 and S19–S22, with S18 the
pre-existing non-IPv6 refusal; S55, the reader's rc-0 answer without an
address), and in builds of this series on the dev phone (KPN), whose PCO —
two IPv6 addresses, nothing else — reaches the plain found arm; the
configured skip, the bracketed refusal and, through the IMSD_PCSCF seam, the
reader's failure and its exit 2 ran on the phone too; the v4/FQDN line, the
eight-address cap, the IPv4-only and no-mux-id skips, the comma-list refusal
and the rc-0 arm on the mock only. On a tip build of this series (daemon
2ec1a02f62831edb; bench 40, 2026-10-13) a fresh registration reached a target
this script had not routed — the reader stubbed through the IMSD_PCSCF seam to
find none, the address in /etc/imsd.env as PCSCF_DISCOVERED= — over imsd's own
route, and a resume stood with the peer's route removed first.
2026-10-11 16:16:46 +02:00
// the target's host route is imsd's own: the bring-up script routes the
// first address of its own read, not a list set in /etc/imsd.env nor a
// route lost with the PDN — the same idempotent replace as a media peer's
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
RunCmd ( { " ip " , Is6 ( pcscf_ ) ? " -6 " : " -4 " , " route " , " replace " , pcscf_ , " dev " , dev_ } ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( recovery_ . Next ( Boot ( ) ) . at > Boot ( ) ) Log ( std : : format ( " the network's hold stands; {} " , NextStep ( ) ) ) ;
if ( ! WaitForPolicy ( ) ) throw Stopping { } ;
2026-07-22 22:53:28 +02:00
FreshRegister ( ) ;
}
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// What a bring-up's resume attempt found: the registration (resumed),
// no pair of ours in the kernel, a pair nothing can resume, or a
// resumable pair whose attempt failed — worth a retry.
enum class ResumeOutcome { Done , None , Dead , Failed } ;
ResumeOutcome TryResume ( ) {
2026-07-22 22:53:28 +02:00
auto state = RunCapture ( { " ip " , " xfrm " , " state " } ) ;
auto policy = RunCapture ( { " ip " , " xfrm " , " policy " } ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// The registration was made to whatever P-CSCF the kernel's SAs name
// (the SA setup takes imsd's previous pair out), whatever PCSCF= says
// today: resume there and move at the next fresh registration — a
// fresh one now would cost the registration, on KPN with the
// 21-minute refusal. A route to it exists while the netdev lives;
// the replace covers a target that changed under a running phone.
auto peer = imsd : : ipsec : : SaPeer ( policy . out ) ;
if ( ! peer ) return ResumeOutcome : : None ;
if ( * peer ! = pcscf_ ) {
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
bool listed = * peer = = pcscfTarget_ | | std : : ranges : : find ( pcscfCandidates_ , * peer ) ! = pcscfCandidates_ . end ( ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
Log ( pcscfTarget_ . empty ( )
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
? std : : format ( " pcscf: resuming on {}, the registration's SA peer (no P-CSCF configured or discovered) " , * peer )
: std : : format ( " pcscf: resuming on {}, the registration's SA peer; the next fresh registration goes to {}{} " , * peer , pcscfTarget_ , listed ? " " : " (the peer is not in today's list) " ) ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
pcscf_ = * peer ;
}
2026-07-22 22:53:28 +02:00
auto sa = imsd : : ipsec : : ParseExistingSa ( state . out , policy . out , pcscf_ , local_ ) ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
// The registration may sit on another address of the link: before
// 0.3.10 imsd registered on the kernel's temporary one (ims ledger
packaging: restart imsd and imsd-ofonod on upgrade
An upgrade left the old imsd and imsd-ofonod running until they were
next restarted, while a changed bus policy is live the moment apk writes
it: dbus-broker-launch reloads on its own. A policy that relies on a
check inside the daemons would face the old daemons in between.
Mark imsd.service and imsd-ofonod.service needs-restart in post-upgrade
scripts; the systemd trigger restarts them once the transaction is done
(enqueue-marked). A call in progress ends. The same scripts run as
post-install: `apk del` removes a package's files and leaves its daemon
running, so a later `apk add` of the package is this upgrade for that
daemon — and apk runs the post-install script, not post-upgrade, for a
package it adds. GNOME Calls 50.0 dials nothing after imsd-ofonod
restarts under it until it restarts too, so imsd-ofonod's ExecStartPost
restarts the Calls daemon of each user running one — not at the unit's
first start since boot, when a Calls that runs already is left alone.
A daemon older than 0.3.10 kept its bring-up throttle wait in memory
only, so a restart lost it. imsd's post-upgrade records that daemon's
invocation, and imsd-handover.sh, an ExecStartPre after ims-pdn-up.sh,
reads the invocation's journal and, while the fresh-SA throttle's wait
it finds there still runs (`spi-s=0`; the old daemon's other deferrals
are not handed over), writes what is left of it to the holds file when
this start's LOCAL is the address the wait was earned on, or when that
address cannot be read; when LOCAL is another address, only the verdict
that the old registration is gone.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-04 00:09:37 +02:00
// F18). Resume there while it is still up — a restart, an upgrade
// among them, keeps the registration for the price of a re-REGISTER,
// where a fresh one is an AKA run, a new SA pair and, when KPN
// refuses it, the old registration and a 21-minute wait (KPN
// refuses a fresh pair on an address whose registration is live and
// has accepted one on another address of the link meanwhile; other
// carriers' rules are unknown) — and move at the next fresh
// registration.
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
if ( ! sa ) {
for ( const std : : string & other : imsd : : ipsec : : SaLocals ( state . out , pcscf_ ) ) {
if ( other = = local_ | | ! OnLink ( dev_ , other ) ) continue ;
sa = imsd : : ipsec : : ParseExistingSa ( state . out , policy . out , pcscf_ , other ) ;
if ( ! sa ) continue ;
Log ( std : : format ( " the registration's SAs are on {}, not the PDN's own address {}: resuming there until the next fresh registration " , other , local_ ) ) ;
local_ = other ; ctx_ . local = other ;
break ;
}
}
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
if ( ! sa ) { Log ( std : : format ( " the SA pair to {} has no SA on an address of {}: nothing to resume " , pcscf_ , dev_ ) ) ; return ResumeOutcome : : Dead ; }
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
// the peer's host route is imsd's own once the SAs are confirmed (a peer
// named by a pair that is not ours gets no route into the PDN), whether
// or not the bring-up script routed the same address — idempotent
RunCmd ( { " ip " , Is6 ( pcscf_ ) ? " -6 " : " -4 " , " route " , " replace " , pcscf_ , " dev " , dev_ } ) ;
2026-07-22 22:53:28 +02:00
auto ps = LoadState ( ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
if ( ! ps | | ! ps - > callid ) { Log ( std : : format ( " no reg state file; {} " , ResumeDeadNext ( ) ) ) ; return ResumeOutcome : : Dead ; }
// A file another attempt left behind — one that got through the SA
// setup and did not live to record, to this or another P-CSCF — names
// another SA pair than the kernel's (its spi_uc/spi_us; a 0.3.x file
// carries them too): its dialog is that attempt's, and a Call-ID
// cannot be rebuilt from an SA (the Security-Verify can —
// ChooseResumeSecurityVerify).
if ( imsd : : ipsec : : FileNamesAnotherPair ( ps - > spiUc , ps - > spiUs , sa - > spiUc , sa - > spiUs ) ) {
Log ( std : : format ( " the state file names another SA pair ({:#x}/{:#x}{}) than the kernel's ({:#x}/{:#x} to {}): another attempt's; {} " ,
static_cast < std : : uint32_t > ( * ps - > spiUc ) , static_cast < std : : uint32_t > ( * ps - > spiUs ) ,
ps - > pcscf & & ! ps - > pcscf - > empty ( ) ? std : : format ( " to {} " , imsd : : util : : CanonicalAddr ( * ps - > pcscf ) ) : std : : string ( ) ,
sa - > spiUc , sa - > spiUs , pcscf_ , ResumeDeadNext ( ) ) ) ;
return ResumeOutcome : : Dead ;
}
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
// The registration's identity is the one it was made under, whatever
// the card gives today: the file's since 1.2.3, and for an older file
// the derived one, under which 1.2.2 registered. A file whose three
// names are no identity imsd can write names a registration nothing
// can refresh, whatever else the file holds: judged before the
// transport, as the file of another attempt is.
imsd : : aka : : Identity made = derivedId_ ;
if ( ps - > impi | | ps - > domain | | ps - > impu ) {
auto filed = imsd : : aka : : IsimIdentity ( derivedId_ , ps - > impi . value_or ( " " ) , ps - > domain . value_or ( " " ) , ps - > impu . value_or ( " " ) ) ;
if ( ! filed ) { Log ( std : : format ( " the state file's identity is not one imsd can register; {} " , ResumeDeadNext ( ) ) ) ; return ResumeOutcome : : Dead ; }
made = * filed ;
}
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// The registration's transport is what the P-CSCF knows; a resume
// must reuse it. A forced policy that disagrees means a fresh start
// — decided before anything from the file is adopted.
Transport t = ps - > transport . value_or ( " TCP " ) = = " UDP " ? Transport : : Udp : Transport : : Tcp ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
if ( sipPolicy_ ! = " auto " & & t ! = transport_ ) { Log ( std : : format ( " state file transport differs from SIP_TRANSPORT; {} " , ResumeFailedNext ( ) ) ) ; return ResumeOutcome : : Failed ; }
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
if ( ! SameNames ( made , cardId_ ) )
Log ( std : : format ( " identity: the registration to resume was made under private identity {}, home domain {}, public identity {}; it keeps them until the next fresh registration, which takes the card's " , made . impi , made . domain , made . impu ) ) ;
ctx_ . id = made ;
reg_ . id = made ;
2026-07-22 22:53:28 +02:00
route_ = ps - > route . value_or ( std : : format ( " <sip:{};lr> " , imsd : : util : : HostPort ( pcscf_ , sa - > portPs ) ) ) ;
// No fallback identity: an empty ppi omits P-Preferred-Identity and
// is re-learned from the next 200's P-Associated-URI.
ppi_ = ps - > ppi . value_or ( " " ) ;
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
// The Security-Verify the protected REGISTERs, the reg-event
// SUBSCRIBE and the INVITEs echo: the 401's whole Security-Server
// list (RFC 3329 §2.3.1), from the state file since 0.3.12, or the
// one-mechanism entry rebuilt from the SA — Imsd:Ipsec chooses
ipsec: the Security-Verify rebuilt from the kernel's SA names the SA's algorithms
A resume sends the 401's Security-Server list from the state file as its
Security-Verify, and where the file holds none for the pair in the
kernel, one mechanism rebuilt from that pair: its SPIs and ports, with
alg=hmac-sha-1-96 and ealg=aes-cbc written in whatever the pair was
installed with. Over a pair with the null cipher, 3DES or hmac-md5-96
that entry named an algorithm the pair does not use, and RFC 3329 2.3.1
has a server answer a Security-Verify that differs from its own list
with a 494.
ParseExistingSa now reads the two names from the state it takes spi-s
from: `ip xfrm state` prints them on its auth-trunc and enc lines, in
the kernel's names for what imsd installs. A state that prints neither
line, or another name, reads as hmac-sha-1-96 and aes-cbc, as before.
Tested: tests/Ipsec, on the lines `ip xfrm state` prints for the SAs
imsd installs (Linux 7.2, iproute2 7.2).
2026-11-23 10:07:59 +01:00
// (ChooseResumeSecurityVerify). The rebuilt entry names the pair's
// own algorithms: KPN's answer to the default offer in the same
// bytes, not a list such as O2's six,
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
// which the RFC has the server answer with a 494; a refused resume
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// registers fresh where there is a fresh target (§7.2 step 1 otherwise).
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
auto rsv = imsd : : ipsec : : ChooseResumeSecurityVerify ( ps - > securityServer . value_or ( " " ) , * sa , ealgOffer_ ) ;
ss_ = rsv . value ;
using Source = imsd : : ipsec : : ResumeSecurityVerify : : Source ;
switch ( rsv . source ) {
case Source : : Stored :
Log ( std : : format ( " Security-Verify from the state file ({} mechanism{}) " , rsv . mechanisms , rsv . mechanisms = = 1 ? " " : " s " ) ) ;
break ;
case Source : : NoneStored :
Log ( " state file holds no Security-Server (a pre-0.3.12 file, or a list the file cannot hold): Security-Verify rebuilt from the SA as one mechanism " ) ;
break ;
case Source : : OtherSa :
Log ( std : : format ( " state file's Security-Server names another SA pair than the one in the kernel (spi-s {} vs {}): Security-Verify rebuilt from the SA as one mechanism " ,
rsv . storedSpiPs ? std : : to_string ( * rsv . storedSpiPs ) : " none " , sa - > spiPs ) ) ;
break ;
}
messages: sign our requests with the public identity, not the IMSI IMPU
Every request we originated — INVITE, CANCEL, both ACKs, in-dialog BYE and
friends — put the IMSI-derived temporary IMPU in From. 3GPP allows that
identity in REGISTER only; the same lesson was learned for the reg-event
SUBSCRIBE (480) and never carried to calls. Most P-CSCFs overwrite From
and hid it; a Telia node did not, and a reporter's IMSI appeared on the
callee's screen (field report 2026-09-01). A strict P-CSCF may reject the
INVITE outright.
CallerId(): the registered sip: public identity (P-Associated-URI), else
the tel: one, and the temporary IMPU only before either is learned. One
helper feeds all five builders, so a dialog's From never drifts. As UAS the
dialog's local URI is the INVITE's To (RFC 3261 12.2.1.1), stored on the
Dialog, so an incoming call's BYE is signed the way the network addressed
us. The identity is persisted in the state file and restored on warm
resume, so a call placed before the refresh 200 re-learns it cannot fall
back. DUMP_SIP now also writes the last outgoing INVITE
(imsd-invite-out.raw): the one request a field log could never show.
The byte-pinned INVITE fixture moves to the tel: identity its test context
knows; new scenarios cover the sip: identity, the tel: fallback, the
pre-learning case and the UAS BYE.
Bench-verified on KPN 2026-09-08: outgoing INVITE From is the registered
sip: identity, call accepted and carried; caller ID at the far end
unchanged.
2026-09-08 20:37:47 +02:00
// The public identity our requests are signed with (From) — restored
// here so a call placed before the refresh 200 re-learns it does not
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
// fall back to the identity's own (for a registration made under the
// derived names, the temporary IMPU).
messages: sign our requests with the public identity, not the IMSI IMPU
Every request we originated — INVITE, CANCEL, both ACKs, in-dialog BYE and
friends — put the IMSI-derived temporary IMPU in From. 3GPP allows that
identity in REGISTER only; the same lesson was learned for the reg-event
SUBSCRIBE (480) and never carried to calls. Most P-CSCFs overwrite From
and hid it; a Telia node did not, and a reporter's IMSI appeared on the
callee's screen (field report 2026-09-01). A strict P-CSCF may reject the
INVITE outright.
CallerId(): the registered sip: public identity (P-Associated-URI), else
the tel: one, and the temporary IMPU only before either is learned. One
helper feeds all five builders, so a dialog's From never drifts. As UAS the
dialog's local URI is the INVITE's To (RFC 3261 12.2.1.1), stored on the
Dialog, so an incoming call's BYE is signed the way the network addressed
us. The identity is persisted in the state file and restored on warm
resume, so a call placed before the refresh 200 re-learns it cannot fall
back. DUMP_SIP now also writes the last outgoing INVITE
(imsd-invite-out.raw): the one request a field log could never show.
The byte-pinned INVITE fixture moves to the tel: identity its test context
knows; new scenarios cover the sip: identity, the tel: fallback, the
pre-learning case and the UAS BYE.
Bench-verified on KPN 2026-09-08: outgoing INVITE From is the registered
sip: identity, call accepted and carried; caller ID at the far end
unchanged.
2026-09-08 20:37:47 +02:00
ctx_ . aor = ps - > aor . value_or ( " " ) ;
2026-07-22 22:53:28 +02:00
ctx_ . route = route_ ; ctx_ . ppi = ppi_ ; ctx_ . securityServer = ss_ ;
ctx_ . portUc = PortUc ; ctx_ . portUs = PortUs ;
Log ( std : : format ( " RESUME via existing SA (cseq {}) " , ps - > cseq . value_or ( 1 ) ) ) ;
portPs_ = sa - > portPs ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
SetTransport ( t ) ;
// Local refusals (TIME_WAIT after a restart) keep retrying; two
// silences mean the flow is not coming back — fresh instead.
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
if ( ! sip_ . Connect ( local_ , PortUc , pcscf_ , sa - > portPs , transport_ , 10 , 2 , netAlarm_ ) ) {
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
Log ( std : : format ( " resume connect failed; {} " , ResumeFailedNext ( ) ) ) ;
return ResumeOutcome : : Failed ;
2026-07-22 22:53:28 +02:00
}
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
if ( transport_ = = Transport : : Tcp ) recovery_ . OnNetworkAnswered ( ) ;
2026-07-22 22:53:28 +02:00
reg_ . callid = * ps - > callid ;
reg_ . ftag = ps - > ftag . value_or ( " " ) ;
// The refresh must carry the SAME Contact URI as the stored binding;
// an absent key means the binding predates the oracle diff and used
// the IMSI (the empty-contactUser fallback).
reg_ . contactUser = ps - > contactUser . value_or ( " " ) ;
ctx_ . contactUser = reg_ . contactUser ;
reg_ . cseq = ps - > cseq . value_or ( 1 ) ;
reg_ . spiUc = static_cast < std : : uint32_t > ( ps - > spiUc . value_or ( sa - > spiUc ) ) ;
reg_ . spiUs = static_cast < std : : uint32_t > ( ps - > spiUs . value_or ( sa - > spiUs ) ) ;
reg_ . expiry = ps - > expiry . value_or ( 0 ) ;
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
reg_ . securityServer = ss_ ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
reg_ . authNonce = ps - > authNonce . value_or ( " " ) ; reg_ . authCnonce = ps - > authCnonce . value_or ( " " ) ; reg_ . authResponse = ps - > authResponse . value_or ( " " ) ;
if ( reg_ . authNonce . empty ( ) ) Log ( " state file holds no challenge answer (pre-0.3.11): the refresh carries an empty digest " ) ;
auto [ okMsg , used ] = Reregister ( reg_ . callid , reg_ . ftag , reg_ . cseq + 1 ) ;
2026-07-22 22:53:28 +02:00
reg_ . cseq = used ;
if ( auto e = imsd : : sip : : GrantedExpires ( okMsg ) ) reg_ . expiry = * e ;
UpdateRouteAndPpi ( okMsg ) ;
LogBindings ( okMsg ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
PersistState ( reg_ , route_ , ppi_ , ctx_ . aor , ctx_ . transport , pcscf_ ) ;
2026-07-22 22:53:28 +02:00
Log ( " REGISTERED (resumed + true-refreshed) " ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
return ResumeOutcome : : Done ;
2026-07-22 22:53:28 +02:00
}
// The registrar's 200 OK echoes EVERY current binding for the implicit
// set — the network's own view. Log them: a stale binding at a dead
// SLAAC address is still tried by terminating routing until it expires.
void LogBindings ( const std : : string & ok ) {
for ( auto ct : imsd : : sip : : Headers ( ok , " Contact " ) )
Log ( std : : format ( " binding: {} " , ct ) ) ;
}
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
// The ISIM application's identity for the card: when the three files
// read and pass the check it is the card's, and the challenge goes to
// the ISIM. The journal's `identity:` line says which way it went.
bool TakeIsimIdentity ( const imsd : : aka : : IsimApp & app ) {
std : : string state = app . state . empty ( ) ? " unknown " : app . state ;
std : : string why ;
auto id = ReadIsimIdentity ( reg_ . slot , app , derivedId_ , why ) ;
if ( ! id ) {
Log ( std : : format ( " identity: derived from the IMSI: the ISIM application (state {}) gave none — {} " , state , why ) ) ;
return false ;
}
cardId_ = * id ;
reg_ . aid = app . aid ;
Log ( std : : format ( " identity: the ISIM's (application state {}): private identity {}, home domain {}, public identity {}; {} " ,
state , id - > impi , id - > domain , id - > impu ,
SameNames ( cardId_ , derivedId_ ) ? " the names the IMSI gives " : std : : format ( " not the names the IMSI gives (home domain {}) " , derivedId_ . domain ) ) ) ;
return true ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// A fresh registration. The attempt mints its own Contact user-part into
// ctx_ for its REGISTERs; on any failure the stored binding's comes back,
// so requests over the existing SA meanwhile (a reconnect, a refresh)
// carry the binding the network knows. reg_ takes the new one on the 200.
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
// The identity goes the same way: the attempt registers the card's
// (cardId_), and on a failure the one ctx_ held before it comes back —
// a resumed registration's can be another than the card's (TryResume).
2026-07-22 22:53:28 +02:00
void FreshRegister ( ) {
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
saReplaced_ = false ;
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
imsd : : aka : : Identity before = ctx_ . id ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
try { FreshRegisterAttempt ( ) ; }
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
catch ( . . . ) {
ctx_ . contactUser = reg_ . contactUser ;
ctx_ . id = before ;
throw ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
}
void FreshRegisterAttempt ( ) {
2026-07-22 22:53:28 +02:00
Log ( " FRESH registration " ) ;
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
if ( ! SameNames ( ctx_ . id , cardId_ ) )
Log ( std : : format ( " identity: the fresh registration takes the card's: private identity {}, home domain {}, public identity {} " , cardId_ . impi , cardId_ . domain , cardId_ . impu ) ) ;
ctx_ . id = cardId_ ;
2026-07-22 22:53:28 +02:00
// Oracle diff (journal/ims.md s53): stock's Contact user-part is a
// fresh UUID per registration, not the IMSI. Minted before reg1 so
// both REGISTERs and the stored binding carry the same URI.
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
std : : string contactUser = imsd : : util : : Uuid4 ( rng_ ) ;
ctx_ . contactUser = contactUser ;
Log ( std : : format ( " contact user-part: {} " , contactUser ) ) ;
2026-07-22 22:53:28 +02:00
std : : string callidReg = std : : format ( " {}@{} " , rng_ . Token ( 16 ) , local_ ) ;
std : : string ftag = rng_ . Token ( 8 ) ;
std : : uint32_t spiUc = rng_ . UInt ( 0x10000 , 0xFFFFFFF ) ;
std : : uint32_t spiUs = rng_ . UInt ( 0x10000 , 0xFFFFFFF ) ;
ctx_ . portUc = PortUc ; ctx_ . portUs = PortUs ; ctx_ . initPort = InitPort ;
// reg1 over UDP from the init port -> 401
int fam = Is6 ( local_ ) ? AF_INET6 : AF_INET ;
int us = socket ( fam , SOCK_DGRAM , 0 ) ;
int one = 1 ; setsockopt ( us , SOL_SOCKET , SO_REUSEADDR , & one , sizeof one ) ;
sockaddr_storage la ; socklen_t ll = MakeAddr ( local_ , InitPort , la ) ;
if ( bind ( us , reinterpret_cast < sockaddr * > ( & la ) , ll ) ! = 0 ) {
close ( us ) ; throw std : : runtime_error ( " bind init port failed " ) ;
}
std : : string reg1 = imsd : : msg : : BuildRegisterInitial ( ctx_ , callidReg , ftag , rng_ . Token ( 16 ) , spiUc , spiUs ) ;
sockaddr_storage pa ; socklen_t pl = MakeAddr ( pcscf_ , pcscfPort_ , pa ) ;
sendto ( us , reg1 . data ( ) , reg1 . size ( ) , 0 , reinterpret_cast < sockaddr * > ( & pa ) , pl ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
std : : string resp = AwaitInitialFinal ( us , callidReg ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( auto st1 = imsd : : sip : : Status ( resp ) ; st1 ! = 401 ) {
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
DumpRaw ( " imsd-register-fail.raw " , resp ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
std : : string what = std : : format ( " expected 401, got {} " , imsd : : sip : : RefusalSummary ( resp ) ) ;
if ( st1 & & * st1 > = 300 ) throw RefusedError ( what , * st1 , imsd : : sip : : RetryAfter ( resp ) . value_or ( 0 ) ) ;
throw std : : runtime_error ( what ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
}
2026-07-22 22:53:28 +02:00
auto nonceB64 = QuotedAfter ( resp , " nonce= \" " ) ;
if ( ! nonceB64 ) throw std : : runtime_error ( " no nonce in 401 " ) ;
auto raw = imsd : : util : : FromBase64 ( * nonceB64 ) ;
if ( ! raw | | raw - > size ( ) < 32 ) throw std : : runtime_error ( " bad nonce " ) ;
std : : vector < std : : uint8_t > rand16 ( raw - > begin ( ) , raw - > begin ( ) + 16 ) ;
std : : vector < std : : uint8_t > autn16 ( raw - > begin ( ) + 16 , raw - > begin ( ) + 32 ) ;
ipsec: build the SAs from the Security-Server mechanism the UE selects
A P-CSCF may answer the challenge with every mechanism it supports and
attach the SPIs and ports to the one it applied. O2 UK's core lists six
ipsec-3gpp entries with q-values, md5 first, and marks the fourth (sha1,
no ealg). imsd took the first ealg= anywhere in the header - the 3DES of
an entry the P-CSCF had not selected - and installed SAs the far end
could not decrypt: every protected packet after the 401 was dropped at
its IPsec layer, over TCP and UDP alike, with nothing to answer.
The 401 handling now parses the Security-Server as a mechanism list
(commas outside quotes, parameters on semicolons, names and values
case-insensitive) and selects the highest-q ipsec-3gpp mechanism that
matches what Security-Client offered (RFC 3329 2.3.1, TS 24.229
5.1.1.5.1): alg equal to ours, ealg (absent = null) equal to the offer.
The SPIs and ports are per registration and come from the entry carrying
them. When no entry matches the offer, the entry carrying the SPIs is
installed as listed and the journal says so; hmac-md5-96 becomes
hmac(md5) with IK as the key. A single-mechanism header selects itself:
on KPN the SAs are the same as before (unit-pinned argv, verified on the
phone). An answer that cannot be used - no ipsec-3gpp entry, a missing
spi/port, an alg, ealg, prot or mod the kernel cannot be handed - defers
the bring-up on the throttle schedule with the reason, before the AKA is
spent, instead of a fatal that would restart imsd every RestartSec with
an initial REGISTER each time; spi-s=0 stays the throttle deferral.
Repeated Security-Server header lines are joined into the one list
Security-Verify echoes.
The journal shows the Security-Server line, the selected mechanism, the
SA parameters, and any ip xfrm command that fails (keys masked) at every
fresh registration - the silence this bug produced had no line to read.
2026-09-19 21:36:57 +02:00
// Every Security-Server instance is one comma-list (RFC 3261
// §7.3.1); the joined value is what Security-Verify echoes — RFC
2026-11-23 08:40:03 +01:00
// 3329 §2.3.1 wants the whole list back, not the chosen entry.
ipsec: build the SAs from the Security-Server mechanism the UE selects
A P-CSCF may answer the challenge with every mechanism it supports and
attach the SPIs and ports to the one it applied. O2 UK's core lists six
ipsec-3gpp entries with q-values, md5 first, and marks the fourth (sha1,
no ealg). imsd took the first ealg= anywhere in the header - the 3DES of
an entry the P-CSCF had not selected - and installed SAs the far end
could not decrypt: every protected packet after the 401 was dropped at
its IPsec layer, over TCP and UDP alike, with nothing to answer.
The 401 handling now parses the Security-Server as a mechanism list
(commas outside quotes, parameters on semicolons, names and values
case-insensitive) and selects the highest-q ipsec-3gpp mechanism that
matches what Security-Client offered (RFC 3329 2.3.1, TS 24.229
5.1.1.5.1): alg equal to ours, ealg (absent = null) equal to the offer.
The SPIs and ports are per registration and come from the entry carrying
them. When no entry matches the offer, the entry carrying the SPIs is
installed as listed and the journal says so; hmac-md5-96 becomes
hmac(md5) with IK as the key. A single-mechanism header selects itself:
on KPN the SAs are the same as before (unit-pinned argv, verified on the
phone). An answer that cannot be used - no ipsec-3gpp entry, a missing
spi/port, an alg, ealg, prot or mod the kernel cannot be handed - defers
the bring-up on the throttle schedule with the reason, before the AKA is
spent, instead of a fatal that would restart imsd every RestartSec with
an initial REGISTER each time; spi-s=0 stays the throttle deferral.
Repeated Security-Server header lines are joined into the one list
Security-Verify echoes.
The journal shows the Security-Server line, the selected mechanism, the
SA parameters, and any ip xfrm command that fails (keys masked) at every
fresh registration - the silence this bug produced had no line to read.
2026-09-19 21:36:57 +02:00
auto ssLines = imsd : : sip : : Headers ( resp , " Security-Server " ) ;
if ( ssLines . empty ( ) ) throw std : : runtime_error ( " no Security-Server " ) ;
ss_ . clear ( ) ;
for ( std : : string_view line : ssLines ) {
if ( ! ss_ . empty ( ) ) ss_ + = ' , ' ;
ss_ + = line ;
}
Log ( std : : format ( " Security-Server: {} " , ss_ ) ) ;
ipsec, messages, imsd: the offered ESP ciphers are a list
imsd's Security-Client held one mechanism, its cipher the value of EALG,
aes-cbc when unset. TS 33.203 7.2 has the UE's first REGISTER carry "a
list of identifiers for the integrity and encryption algorithms, which
the UE supports", and imsd can install three ciphers: an offer of one
could not say so.
EALG is now a comma-separated list, offered in the order written: one
mechanism per cipher in a single Security-Client, each with the
REGISTER's SPIs and ports (7.2 NOTE 1, NOTE 2). The default stays
aes-cbc alone. A name imsd cannot install is ignored with a journal
line where it used to go out as written, `3des` is offered as
des-ede3-cbc, RFC 3329's name for it, a setting that names no cipher
gives the default, and the bring-up logs what is offered (`ESP ciphers
offered: …`).
An offer of more than one cipher needs a further rule for the 401's
list. O2 UK's P-CSCF lists six mechanisms and puts the SPIs on one: the
sha1 entry without a cipher for a null offer, the sha1 entry with
aes-cbc for an aes-cbc offer (2026-09-17, 2026-09-20). The second has
the higher q, so with both ciphers offered the highest-q offered entry
and the entry carrying the SPIs can be two entries. The entry carrying
the SPIs is therefore taken when it is the only such entry and one of
the offer; otherwise the highest-q offered entry, as before. With one
cipher offered the two name the same algorithms; they can differ in mod
or prot, and there the marked entry's are now taken, where 1.2.1 took
the highest-q entry's.
Tested: tests/Ipsec (the setting; the selection against two offered
ciphers) and tests/Messages (a Security-Client of two mechanisms); the
daemon of this commit against a stand-in P-CSCF on the workstation, with
one cipher offered and with two.
2026-11-23 10:08:04 +01:00
// Algorithms from the mechanism ParseSecurityServer selects against
// our offer, SPIs/ports from the entry carrying them (O2 lists
ipsec: build the SAs from the Security-Server mechanism the UE selects
A P-CSCF may answer the challenge with every mechanism it supports and
attach the SPIs and ports to the one it applied. O2 UK's core lists six
ipsec-3gpp entries with q-values, md5 first, and marks the fourth (sha1,
no ealg). imsd took the first ealg= anywhere in the header - the 3DES of
an entry the P-CSCF had not selected - and installed SAs the far end
could not decrypt: every protected packet after the 401 was dropped at
its IPsec layer, over TCP and UDP alike, with nothing to answer.
The 401 handling now parses the Security-Server as a mechanism list
(commas outside quotes, parameters on semicolons, names and values
case-insensitive) and selects the highest-q ipsec-3gpp mechanism that
matches what Security-Client offered (RFC 3329 2.3.1, TS 24.229
5.1.1.5.1): alg equal to ours, ealg (absent = null) equal to the offer.
The SPIs and ports are per registration and come from the entry carrying
them. When no entry matches the offer, the entry carrying the SPIs is
installed as listed and the journal says so; hmac-md5-96 becomes
hmac(md5) with IK as the key. A single-mechanism header selects itself:
on KPN the SAs are the same as before (unit-pinned argv, verified on the
phone). An answer that cannot be used - no ipsec-3gpp entry, a missing
spi/port, an alg, ealg, prot or mod the kernel cannot be handed - defers
the bring-up on the throttle schedule with the reason, before the AKA is
spent, instead of a fatal that would restart imsd every RestartSec with
an initial REGISTER each time; spi-s=0 stays the throttle deferral.
Repeated Security-Server header lines are joined into the one list
Security-Verify echoes.
The journal shows the Security-Server line, the selected mechanism, the
SA parameters, and any ip xfrm command that fails (keys masked) at every
fresh registration - the silence this bug produced had no line to read.
2026-09-19 21:36:57 +02:00
// six and marks one; ims ledger F11). An answer we cannot use is a
// deferral on the throttle schedule, not a fatal: a fatal restarts
// imsd every RestartSec, an initial REGISTER each time.
auto ss = imsd : : ipsec : : ParseSecurityServer ( ss_ , " hmac-sha-1-96 " , ealgOffer_ ) ;
if ( ! ss ) throw ThrottledError ( " Security-Server has no ipsec-3gpp mechanism " ) ;
const imsd : : ipsec : : SecurityMechanism & mech = ss - > Selected ( ) ;
const imsd : : ipsec : : SecurityMechanism & carrier = ss - > Carrier ( ) ;
Log ( std : : format ( " selected mechanism {} of {}{}: {} " , ss - > selected + 1 , ss - > mechanisms . size ( ) , ss - > offerMatched ? " " : " (none matches our offer; taking the P-CSCF's) " , mech . text ) ) ;
if ( ss - > carrier ! = ss - > selected ) Log ( std : : format ( " SPIs/ports from mechanism {}: {} " , ss - > carrier + 1 , carrier . text ) ) ;
if ( carrier . spiPs = = 0u ) throw ThrottledError ( " fresh-SA throttle active (spi-s=0) " ) ;
if ( ! carrier . spiPs | | ! carrier . spiPc | | ! carrier . portPs | | ! carrier . portPc ) throw ThrottledError ( " Security-Server carries no spi-c/spi-s/port-c/port-s " ) ;
std : : string alg = mech . alg . empty ( ) ? " hmac-sha-1-96 " : mech . alg ; // absent: what we offered
std : : string ealg = imsd : : ipsec : : NormalizeEalg ( mech . ealg ) ; // absent: the null cipher (RFC 3329)
if ( ! imsd : : ipsec : : KernelAuth ( alg ) ) throw ThrottledError ( std : : format ( " Security-Server alg={} unsupported " , alg ) ) ;
if ( ! imsd : : ipsec : : KnownEalg ( ealg ) ) throw ThrottledError ( std : : format ( " Security-Server ealg={} unsupported " , ealg ) ) ;
if ( ! mech . prot . empty ( ) & & mech . prot ! = " esp " ) throw ThrottledError ( std : : format ( " Security-Server prot={} unsupported " , mech . prot ) ) ;
if ( ! mech . mod . empty ( ) & & mech . mod ! = " trans " ) throw ThrottledError ( std : : format ( " Security-Server mod={} unsupported " , mech . mod ) ) ;
std : : uint32_t spiPs = * carrier . spiPs ;
std : : uint32_t spiPc = * carrier . spiPc ;
int portPs = * carrier . portPs ;
int portPc = * carrier . portPc ;
Log ( std : : format ( " SA: alg={} ealg={}{} spi-c={} spi-s={} port-c={} port-s={} " , alg , ealg , mech . ealg . empty ( ) ? " (absent) " : " " , spiPc , spiPs , portPc , portPs ) ) ;
2026-07-22 22:53:28 +02:00
auto aka = Authenticate ( rand16 , autn16 ) ;
if ( ! aka ) throw std : : runtime_error ( " USIM AKA failed " ) ;
// install the IPsec SA pair
imsd : : ipsec : : SaParams sp ;
sp . local = local_ ; sp . pcscf = pcscf_ ;
sp . ik = aka - > ik ; sp . ck = aka - > ck ;
sp . spiUc = spiUc ; sp . spiUs = spiUs ; sp . spiPc = spiPc ; sp . spiPs = spiPs ;
sp . portUc = PortUc ; sp . portUs = PortUs ; sp . portPs = portPs ; sp . portPc = portPc ;
ipsec: build the SAs from the Security-Server mechanism the UE selects
A P-CSCF may answer the challenge with every mechanism it supports and
attach the SPIs and ports to the one it applied. O2 UK's core lists six
ipsec-3gpp entries with q-values, md5 first, and marks the fourth (sha1,
no ealg). imsd took the first ealg= anywhere in the header - the 3DES of
an entry the P-CSCF had not selected - and installed SAs the far end
could not decrypt: every protected packet after the 401 was dropped at
its IPsec layer, over TCP and UDP alike, with nothing to answer.
The 401 handling now parses the Security-Server as a mechanism list
(commas outside quotes, parameters on semicolons, names and values
case-insensitive) and selects the highest-q ipsec-3gpp mechanism that
matches what Security-Client offered (RFC 3329 2.3.1, TS 24.229
5.1.1.5.1): alg equal to ours, ealg (absent = null) equal to the offer.
The SPIs and ports are per registration and come from the entry carrying
them. When no entry matches the offer, the entry carrying the SPIs is
installed as listed and the journal says so; hmac-md5-96 becomes
hmac(md5) with IK as the key. A single-mechanism header selects itself:
on KPN the SAs are the same as before (unit-pinned argv, verified on the
phone). An answer that cannot be used - no ipsec-3gpp entry, a missing
spi/port, an alg, ealg, prot or mod the kernel cannot be handed - defers
the bring-up on the throttle schedule with the reason, before the AKA is
spent, instead of a fatal that would restart imsd every RestartSec with
an initial REGISTER each time; spi-s=0 stays the throttle deferral.
Repeated Security-Server header lines are joined into the one list
Security-Verify echoes.
The journal shows the Security-Server line, the selected mechanism, the
SA parameters, and any ip xfrm command that fails (keys masked) at every
fresh registration - the silence this bug produced had no line to read.
2026-09-19 21:36:57 +02:00
sp . alg = alg ;
2026-07-22 22:53:28 +02:00
sp . ealg = ealg ;
ipsec, imsd: the SA setup deletes by exact key instead of flushing the host's xfrm
A fresh registration's SA setup began with `ip xfrm state flush` and `ip
xfrm policy flush`: every SA userspace had installed and every SPD policy
went, a policy-based VPN's (strongSwan's, libreswan's) SAs and policies
included. The setup now takes out what two rules select and leaves the
rest; and the SA reader, which took the P-CSCF ports for a resume from any
reqid-1/2 `dir out` policy — correct only while the flush left imsd's pair
alone in the kernel — takes them from the policies between our two
addresses only. Whether imsd runs beside a live strongSwan or libreswan
connection is unmeasured: the dev phone shows a tunnel policy and a tunnel
state left in place (Tested below), no more.
OwnXfrmDeleteCommands (Imsd:Ipsec) builds the deletes from the kernel text
the shell reads: every transport-mode policy with reqid 1 or 2 whose
selector carries imsd's protected port on the UE side, by the selector ip
xfrm policy prints (src, dst, proto, sport, dport, dev) and its direction,
and every transport-mode reqid-1/2 ESP state running from such a policy's
source to its destination or anchored on the UE's ims-PDN address, by src,
dst, proto esp and SPI — policy or not: a setup whose policy add failed
leaves such states (the setup logs a failed add and goes on), and an ESP
state another transport-mode user put on that address with reqid 1 or 2 goes
with them (an AH or IPComp state is not selected: the rule asks for ESP).
Every reader of the policy text — the deletes and the SA
reader's port pass here — goes through one predicate (detail::OwnPolicy),
written for whatever reads that text later.
BuildSetupCommands loses its two flush lines and the shell runs the deletes
right before it (RunOwnXfrmDeletes); BuildTeardownCommands, the same two
flushes with no caller, goes. A policy-based VPN's tunnel entries and
another transport-mode user's pair on other ports and addresses stay.
Residual: a transport-mode policy with reqid 1 and the UE-side port 45061,
or reqid 2 and 45062 — alone or paired, between any addresses — carries
imsd's fingerprint and goes, with the reqid-1/2 transport-mode ESP states
in its direction, and a reqid-1/2 transport-mode ESP state on the UE's
ims-PDN address goes whoever made it (tests/Ipsec pins both, and that an AH state
stays).
Tested: crafter-build test, 7 passed (the eight deletes byte-exact on the
fixture in the registered FP6's shape (synthetic addresses and keys); a VPN's tunnel SA and policies beside the pair
untouched; another transport-mode user's pair on other ports and addresses
untouched, its reqid-1 ESP state on the UE's address deleted whoever made
it, its AH state left; a policy-less state on the UE's address deleted, one
between other addresses left; the reader's ports from our pair beside
a foreign transport policy with ports); on the dev phone (KPN), in builds of
this series, a fresh registration with a VPN's tunnel policy and state in
the kernel: both still there afterwards, imsd's previous pair gone.
2026-10-13 22:28:02 +02:00
// imsd's previous pair out first, each entry by its key — not `ip xfrm …
// flush`: another IPsec user's entries (a policy-based VPN's) stay (§12)
{
auto state = RunCapture ( { " ip " , " xfrm " , " state " } ) ;
auto policy = RunCapture ( { " ip " , " xfrm " , " policy " } ) ;
RunOwnXfrmDeletes ( imsd : : ipsec : : OwnXfrmDeleteCommands ( state . out , policy . out , local_ ) ) ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
saReplaced_ = true ; // from here on the old registration's SAs are gone
ipsec: build the SAs from the Security-Server mechanism the UE selects
A P-CSCF may answer the challenge with every mechanism it supports and
attach the SPIs and ports to the one it applied. O2 UK's core lists six
ipsec-3gpp entries with q-values, md5 first, and marks the fourth (sha1,
no ealg). imsd took the first ealg= anywhere in the header - the 3DES of
an entry the P-CSCF had not selected - and installed SAs the far end
could not decrypt: every protected packet after the 401 was dropped at
its IPsec layer, over TCP and UDP alike, with nothing to answer.
The 401 handling now parses the Security-Server as a mechanism list
(commas outside quotes, parameters on semicolons, names and values
case-insensitive) and selects the highest-q ipsec-3gpp mechanism that
matches what Security-Client offered (RFC 3329 2.3.1, TS 24.229
5.1.1.5.1): alg equal to ours, ealg (absent = null) equal to the offer.
The SPIs and ports are per registration and come from the entry carrying
them. When no entry matches the offer, the entry carrying the SPIs is
installed as listed and the journal says so; hmac-md5-96 becomes
hmac(md5) with IK as the key. A single-mechanism header selects itself:
on KPN the SAs are the same as before (unit-pinned argv, verified on the
phone). An answer that cannot be used - no ipsec-3gpp entry, a missing
spi/port, an alg, ealg, prot or mod the kernel cannot be handed - defers
the bring-up on the throttle schedule with the reason, before the AKA is
spent, instead of a fatal that would restart imsd every RestartSec with
an initial REGISTER each time; spi-s=0 stays the throttle deferral.
Repeated Security-Server header lines are joined into the one list
Security-Verify echoes.
The journal shows the Security-Server line, the selected mechanism, the
SA parameters, and any ip xfrm command that fails (keys masked) at every
fresh registration - the silence this bug produced had no line to read.
2026-09-19 21:36:57 +02:00
for ( auto & cmd : imsd : : ipsec : : BuildSetupCommands ( sp ) ) {
int rc = RunCmd ( cmd ) ;
if ( rc ! = 0 ) Log ( std : : format ( " {} -> rc {} " , RedactKeys ( cmd ) , rc ) ) ;
}
2026-07-22 22:53:28 +02:00
ctx_ . securityServer = ss_ ;
portPs_ = portPs ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
// The fallback is for a P-CSCF that never served TCP. Once a TCP
// registration has succeeded on this phone (the state file records
// it), a silent connect is an outage, not a policy — two unanswered
// SYNs during a radio gap must not become a second initial REGISTER
// (the throttle trigger on KPN).
bool tcpKnownGood = false ;
if ( auto ps = LoadState ( ) ; ps & & ps - > callid . has_value ( ) ) {
std : : string t = ps - > transport . value_or ( " TCP " ) ;
tcpKnownGood = ( t = = " TCP " ) ;
// A phone whose last registration was UDP goes straight to UDP:
// a TCP probe on every boot would be a second initial REGISTER
// per boot on a carrier that never answers it.
if ( sipPolicy_ = = " auto " & & t = = " UDP " & & transport_ = = Transport : : Tcp ) {
Log ( " state file records a UDP registration; skipping the TCP probe " ) ;
SetTransport ( Transport : : Udp ) ;
}
}
bool autoTcp = ( sipPolicy_ = = " auto " & & transport_ = = Transport : : Tcp & & ! tcpKnownGood ) ;
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
if ( ! sip_ . Connect ( local_ , PortUc , pcscf_ , portPs , transport_ , 10 , autoTcp ? 2 : 0 , netAlarm_ ) ) {
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
if ( autoTcp ) {
// Two unanswered TCP connects: treat the P-CSCF as UDP-only
// and register again over UDP — a new challenge and a new SA
ipsec, imsd: the SA setup deletes by exact key instead of flushing the host's xfrm
A fresh registration's SA setup began with `ip xfrm state flush` and `ip
xfrm policy flush`: every SA userspace had installed and every SPD policy
went, a policy-based VPN's (strongSwan's, libreswan's) SAs and policies
included. The setup now takes out what two rules select and leaves the
rest; and the SA reader, which took the P-CSCF ports for a resume from any
reqid-1/2 `dir out` policy — correct only while the flush left imsd's pair
alone in the kernel — takes them from the policies between our two
addresses only. Whether imsd runs beside a live strongSwan or libreswan
connection is unmeasured: the dev phone shows a tunnel policy and a tunnel
state left in place (Tested below), no more.
OwnXfrmDeleteCommands (Imsd:Ipsec) builds the deletes from the kernel text
the shell reads: every transport-mode policy with reqid 1 or 2 whose
selector carries imsd's protected port on the UE side, by the selector ip
xfrm policy prints (src, dst, proto, sport, dport, dev) and its direction,
and every transport-mode reqid-1/2 ESP state running from such a policy's
source to its destination or anchored on the UE's ims-PDN address, by src,
dst, proto esp and SPI — policy or not: a setup whose policy add failed
leaves such states (the setup logs a failed add and goes on), and an ESP
state another transport-mode user put on that address with reqid 1 or 2 goes
with them (an AH or IPComp state is not selected: the rule asks for ESP).
Every reader of the policy text — the deletes and the SA
reader's port pass here — goes through one predicate (detail::OwnPolicy),
written for whatever reads that text later.
BuildSetupCommands loses its two flush lines and the shell runs the deletes
right before it (RunOwnXfrmDeletes); BuildTeardownCommands, the same two
flushes with no caller, goes. A policy-based VPN's tunnel entries and
another transport-mode user's pair on other ports and addresses stay.
Residual: a transport-mode policy with reqid 1 and the UE-side port 45061,
or reqid 2 and 45062 — alone or paired, between any addresses — carries
imsd's fingerprint and goes, with the reqid-1/2 transport-mode ESP states
in its direction, and a reqid-1/2 transport-mode ESP state on the UE's
ims-PDN address goes whoever made it (tests/Ipsec pins both, and that an AH state
stays).
Tested: crafter-build test, 7 passed (the eight deletes byte-exact on the
fixture in the registered FP6's shape (synthetic addresses and keys); a VPN's tunnel SA and policies beside the pair
untouched; another transport-mode user's pair on other ports and addresses
untouched, its reqid-1 ESP state on the UE's address deleted whoever made
it, its AH state left; a policy-less state on the UE's address deleted, one
between other addresses left; the reader's ports from our pair beside
a foreign transport policy with ports); on the dev phone (KPN), in builds of
this series, a fresh registration with a VPN's tunnel policy and state in
the kernel: both still there afterwards, imsd's previous pair gone.
2026-10-13 22:28:02 +02:00
// pair (the SA setup takes this one out), same ports.
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
Log ( " protected TCP connect unanswered; registering fresh over UDP " ) ;
SetTransport ( Transport : : Udp ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
FreshRegisterAttempt ( ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
return ;
}
throw std : : runtime_error ( std : : format ( " protected {} connect failed " , TransportName ( transport_ ) ) ) ;
}
Log ( std : : format ( " protected leg over {} " , TransportName ( transport_ ) ) ) ;
2026-07-22 22:53:28 +02:00
std : : string cnonce = rng_ . Token ( 16 ) ;
std : : string response = imsd : : aka : : DigestAkav1 ( * nonceB64 , aka - > res , cnonce , ctx_ . id . regUri , ctx_ . id . impi , ctx_ . id . domain ) ;
std : : string auth = imsd : : msg : : AuthAka ( ctx_ , * nonceB64 , cnonce , response ) ;
std : : string reg2 = imsd : : msg : : BuildRegisterProtected ( ctx_ , callidReg , ftag , rng_ . Token ( 16 ) , 2 , spiUc , spiUs , auth ) ;
if ( ! sip_ . Send ( reg2 ) ) throw std : : runtime_error ( " send protected REGISTER failed " ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
std : : string ok = AwaitFinal ( callidReg , 2 , " protected REGISTER " ) ;
if ( auto st = imsd : : sip : : Status ( ok ) ; st ! = 200 ) {
DumpRaw ( " imsd-register-fail.raw " , ok ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
throw RefusedError ( std : : format ( " REGISTER refused: {} " , imsd : : sip : : RefusalSummary ( ok ) ) , * st , imsd : : sip : : RetryAfter ( ok ) . value_or ( 0 ) ) ;
2026-07-22 22:53:28 +02:00
}
reg_ . callid = callidReg ; reg_ . ftag = ftag ; reg_ . cseq = 2 ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
reg_ . contactUser = contactUser ;
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
reg_ . id = ctx_ . id ;
2026-07-22 22:53:28 +02:00
reg_ . spiUc = spiUc ; reg_ . spiUs = spiUs ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
reg_ . authNonce = * nonceB64 ; reg_ . authCnonce = cnonce ; reg_ . authResponse = response ;
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
reg_ . securityServer = ss_ ;
2026-07-22 22:53:28 +02:00
reg_ . expiry = imsd : : sip : : GrantedExpires ( ok ) . value_or ( 0 ) ;
DumpRaw ( " imsd-register-200.raw " , ok ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// The Route for everything over this registration is the P-CSCF it
// was made at — never a previous one's, after a move from the
// resumed peer — unless the 200 carries a Service-Route, which
// UpdateRouteAndPpi puts in its place.
route_ = std : : format ( " <sip:{};lr> " , imsd : : util : : HostPort ( pcscf_ , portPs ) ) ;
2026-07-22 22:53:28 +02:00
UpdateRouteAndPpi ( ok ) ;
LogBindings ( ok ) ;
ctx_ . route = route_ ; ctx_ . ppi = ppi_ ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
PersistState ( reg_ , route_ , ppi_ , ctx_ . aor , ctx_ . transport , pcscf_ ) ;
2026-07-22 22:53:28 +02:00
Log ( " REGISTERED (fresh) " ) ;
}
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
// Closes the flow of a REGISTER wait that failed. A call that arrived
// under the wait (AwaitFinal dispatches requests) ends with it: a 486
// while the flow still carries one, and the bus told.
void CloseFlowAfterWait ( ) {
if ( call_ ) {
Log ( std : : format ( " call {} arrived under a registration that failed; ending it " , call_ - > Uni ( ) ) ) ;
Execute ( call_ - > OnHangup ( ) ) ;
MaybeDropCall ( ) ;
if ( call_ ) { Execute ( call_ - > Abandon ( " registration failed " ) ) ; MaybeDropCall ( ) ; }
}
sip_ . Close ( ) ;
}
// The final of the REGISTER (callid, cseq) just sent, within 12 s of
// the send or of its last provisional. A request arriving on the client
// flow meanwhile (a NOTIFY, an OPTIONS) is dispatched and answered, not
// read as the reply; a provisional of our own transaction keeps the
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// wait going; a response to our reg-event SUBSCRIBE or to one of our MESSAGEs is handled as the
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// run loop handles it, any other transaction's is ignored. Throws
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
// when nothing answers or the flow dies under a dispatched request.
std : : string AwaitFinal ( const std : : string & callid , long cseq , std : : string_view what ) {
std : : string want = std : : format ( " {} REGISTER " , cseq ) ;
double deadline = Mono ( ) + 12.0 ;
for ( ; ; ) {
double left = deadline - Mono ( ) ;
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
// the alarm is set anew before every second of the wait (Step)
auto m = left > 0 ? sip_ . RecvMsg ( left , netAlarm_ ) : std : : nullopt ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
if ( ! m ) throw std : : runtime_error ( std : : format ( " no reply to {} " , what ) ) ;
auto st = imsd : : sip : : Status ( * m ) ;
if ( ! st ) {
reply_ = [ this ] ( const std : : string & r ) { sip_ . Send ( r ) ; } ;
DispatchRequest ( * m ) ;
if ( ! sip_ . Alive ( ) ) throw std : : runtime_error ( std : : format ( " flow closed while awaiting the {} reply " , what ) ) ;
continue ;
}
if ( ! imsd : : sip : : ResponseOf ( * m , callid , want ) ) {
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
if ( ! OnSubscribeResponse ( * m , * st ) & & ! OnSmsResponse ( * m , * st ) ) Log ( std : : format ( " ignoring a response to another transaction while awaiting the {} reply " , what ) ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
continue ;
}
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
recovery_ . OnNetworkAnswered ( ) ; // a response to our REGISTER, whatever it says: the network is in reach
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
if ( * st > = 200 ) return * m ;
Log ( std : : format ( " {} -> {} (provisional); waiting for the final " , what , * st ) ) ;
deadline = Mono ( ) + 12.0 ;
}
}
// The final of the unprotected REGISTER (callid, CSeq 1) on the init
// socket, within 8 s of the send or of its last provisional. The socket
// is bound to the init port, not connected: what else it delivers — a
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
// late final of an earlier attempt, a stray datagram — is skipped,
// never judged as the reply, and logged with its source port unless it
// holds nothing but line breaks. A datagram is framed as on the other
// sockets (RFC 3261 18.3; DatagramMessage), but a request gets no
// answer here, whole or cut short: the socket is that REGISTER's own.
// Closes the socket; throws when nothing answers.
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
std : : string AwaitInitialFinal ( int us , const std : : string & callid ) {
double deadline = Mono ( ) + 8.0 ;
char buf [ 65535 ] ;
for ( ; ; ) {
double left = deadline - Mono ( ) ;
if ( left < = 0 ) break ;
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
// in pieces of a second, the alarm set anew before each (Step)
netAlarm_ ( ) ;
left = std : : min ( left , 1.0 ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
long sec = static_cast < long > ( left ) ;
long usec = static_cast < long > ( ( left - static_cast < double > ( sec ) ) * 1e6 ) ;
if ( sec = = 0 & & usec = = 0 ) usec = 1000 ;
timeval tv { sec , usec } ;
setsockopt ( us , SOL_SOCKET , SO_RCVTIMEO , & tv , sizeof tv ) ;
sockaddr_storage src ; socklen_t sl = sizeof src ;
ssize_t n = recvfrom ( us , buf , sizeof buf , 0 , reinterpret_cast < sockaddr * > ( & src ) , & sl ) ;
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
if ( n < 0 ) {
// a piece is over, or the receive was interrupted (EINTR: by
// a suspend's freeze, after which the kernel takes a poll up
// again but not a datagram receive under a timeout; by a stop and a
// continue; by a signal handled here): the deadline is looked at above
if ( errno = = EAGAIN | | errno = = EWOULDBLOCK | | errno = = EINTR ) continue ;
break ;
}
imsd: a datagram on a server port or the init port is framed as one on the client flow is
SipFlow passes a datagram of the client flow through DatagramMessage:
one datagram is one message, the bytes past the Content-Length read
from it are no part of it and one whose body is shorter than that
length is no message (RFC 3261 18.3), nor is one that has no end of
headers. The two other places that read a datagram handed it on as it
came: the protected server ports, where the network's requests arrive,
and the init port, where the 401 to the unprotected REGISTER does.
Bytes after a body so reached its readers: behind an RP-ACK or an
RP-ERROR without user data, bytes shaped like that element (0x41, a
length and at least as many bytes) would be read as its submit report.
Both go through DatagramMessage now. On a server port a request cut
short of the Content-Length read from it is answered 400 as on the
client flow (Jorijn's decision of 2026-11-22, asked of him for this
port), by the way any answer from that port goes, and its line reads
`UDP: … on server socket <port> — answered 400`; whatever else
DatagramMessage refuses there is ignored with that line's `— ignored`.
The init port answers no request, whole or cut short: what
DatagramMessage refuses there is ignored with `UDP: … on the init
port, from port <n> — ignored`. A datagram of line breaks alone is
passed over on all three, and so is one of no bytes: on the init port
it ended the wait for the 401, and on a server port that pass's read
of the socket, with whatever stood behind it left for the next pass.
The server ports pass over one of other white space alone, as before.
Tested on the workstation's loopback with stand-ins for the network
(the fp6 journal's 2026-11-20-issues-2-5 capture, init-port and
server-ports; each at this commit and at the one before). The init
port, with the daemon in dev mode: an empty datagram and one of line
breaks are passed over, a 401 cut short of its Content-Length is
ignored with its line, and the 401 after each is taken, where the
commit before ended its wait at the empty one and took the cut-short
one for the reply; a request, cut short or whole, draws no answer at
either. The server ports, their class built around a bench main: a
request with bytes after its body comes out without them; one with a
short body is answered 400 on either port; a response, an ACK and a
CANCEL cut short so and a request without an end of headers are
ignored with their lines; a request behind a datagram of no bytes
comes out in the same pass. The commit before handed each of those
requests on as it came and stopped its pass at the datagram of no
bytes. A request whose Content-Length is folded is handed on at either
commit, with a body shorter than that length or with the bytes past
it, a folded value being read by its first line. On the dev phone the
binary of this range's last commit registered fresh through the init
port after a reboot; the submit report and the delivery of each of two
texts came to the server port as datagrams, by a packet counter; and a
MESSAGE with a Content-Length larger than its body, sent from the
phone to its own server port, was answered 400 (the capture's
phone-form6: fresh-check.log, checks.log, inject-bench.log).
2026-11-22 17:35:11 +01:00
const int sp = PortOf ( src ) ;
std : : string why ;
auto framed = imsd : : sip : : DatagramMessage ( std : : string_view ( buf , static_cast < std : : size_t > ( n ) ) , & why ) ;
if ( ! framed ) {
if ( ! why . empty ( ) ) Log ( std : : format ( " UDP: {} on the init port, from port {} — ignored " , why , sp ) ) ;
continue ;
}
std : : string m = std : : move ( * framed ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
if ( ! imsd : : sip : : ResponseOf ( m , callid , " 1 REGISTER " ) ) {
std : : string_view sv = m ;
Log ( std : : format ( " ignoring a datagram on the init port from port {} that is not the unprotected REGISTER's reply: {} " , sp , sv . substr ( 0 , sv . find ( " \r \n " ) ) ) ) ;
continue ;
}
int st = * imsd : : sip : : Status ( m ) ;
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
recovery_ . OnNetworkAnswered ( ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
if ( st > = 200 ) { close ( us ) ; return m ; }
Log ( std : : format ( " unprotected REGISTER -> {} (provisional); waiting for the final " , st ) ) ;
deadline = Mono ( ) + 8.0 ;
}
close ( us ) ;
throw std : : runtime_error ( " no 401 to unprotected REGISTER " ) ;
}
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
// A reregistration over the (resumed or live) SA, TS 24.229 5.1.1.4.2:
// the same Call-ID and Contact, CSeq+1, the Authorization of the last
// successful authentication, a Security-Client with new SPIs and a new
// client port for the SA pairs a re-authentication would set up (the
// server port stays, TS 33.203 7.4.0), the Security-Verify (the 401's
imsd: a resumed registration echoes the 401's Security-Server list from the state file
A warm resume rebuilt its Security-Verify from the kernel's SA: one
mechanism with hmac-sha-1-96 and aes-cbc written in, where RFC 3329
§2.3.1 has the client mirror the server's whole list. The fresh
registration kept the 401's list in memory, so a registration this
process made fresh echoed it; after a restart, the resumed
registration's re-REGISTER, its keepalives, its reg-event SUBSCRIBE and
its INVITEs carried the rebuilt entry until the next fresh registration.
KPN's one-entry answer to the default offer is the rebuilt entry byte
for byte; against a six-entry list (O2's) the mirror is broken, which
the RFC has the server answer with a 494, and a refused resume
registers fresh.
The fresh registration now stores the joined Security-Server value in the
state file (security_server, next to the challenge answer) and the resume
takes it from there, logging the mechanism count, when the entry
carrying its SPIs names the SA pair in the kernel: a file an attempt the
process did not live to record left behind (its SAs installed, its 200
not written) names another. A file from before this change holds none.
In both cases the resume falls back to the rebuilt entry, says which,
and the registration's next state write stores that entry, which is what
it echoes; the choice is Imsd:Ipsec's, pinned in tests/Ipsec with O2's
recorded list and KPN's. A value with a quote, a backslash or a newline in it is
written empty, which the resume treats as absent; RFC 3329's token
syntax produces none of these, a quoted-string extension parameter
could carry the first two.
Tested on the dev phone (KPN) with the build of this tree: a resume from
a state file the 0.3.11 daemon wrote logs the fallback and succeeds, so
do one from a file whose list names another SA pair and one whose list
is empty; two keepalives at a 120-s interval; a fresh registration
stores KPN's list byte-for-byte as the journal shows it received; a
restart resumes with the list from the file; an outgoing call.
2026-10-10 23:42:01 +02:00
// list, kept in the state file since 0.3.12 so a resumed registration
// echoes it too; a resume from an older file sends the one entry
// rebuilt from the kernel's SA). Returns (200 msg, used cseq). A 401
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
// asks for re-authentication over temporary SAs on the proposed ports,
// which imsd does not do: it is thrown as a refusal whose recovery is a
// fresh registration (RegRecovery's 401 rule). Every refresh of the
// pre-0.3.11 shape on record from O2 UK — an initial registration's
// empty digest, the in-use SPIs — was refused 503 (2026-09-24 under
// 0.3.9, 2026-10-08 under 0.3.10) while the fresh registrations that
// followed were accepted; KPN accepted both shapes without a challenge.
std : : pair < std : : string , long > Reregister ( const std : : string & callid , const std : : string & ftag , long cseq ) {
std : : string auth = reg_ . authNonce . empty ( ) ? imsd : : msg : : AuthEmpty ( ctx_ )
: imsd : : msg : : AuthAka ( ctx_ , reg_ . authNonce , reg_ . authCnonce , reg_ . authResponse ) ;
std : : uint32_t spiUc = 0 , spiUs = 0 ;
do spiUc = rng_ . UInt ( 0x10000 , 0xFFFFFFF ) ; while ( spiUc = = reg_ . spiUc | | spiUc = = reg_ . spiUs ) ;
do spiUs = rng_ . UInt ( 0x10000 , 0xFFFFFFF ) ; while ( spiUs = = reg_ . spiUc | | spiUs = = reg_ . spiUs | | spiUs = = spiUc ) ;
std : : string reg = imsd : : msg : : BuildRegisterProtected ( ctx_ , callid , ftag , rng_ . Token ( 16 ) , cseq , spiUc , spiUs , auth , PortUcNext ) ;
if ( ! sip_ . Send ( reg ) ) throw std : : runtime_error ( " send re-REGISTER failed " ) ;
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
// Sent, the number is used, whatever comes back: the next REGISTER
// on this Call-ID carries a higher one (RFC 3261 10.2), where a
// registrar that took this one and whose answer did not arrive
// refuses the same number (10.3 step 7; KPN answered 482 Loop
// Detected where, by 1.2.4's code, two re-REGISTERs carried an
// unanswered refresh's: the dev phone, 2026-11-25). After a restart
// too: the state file has the number before the answer is waited for.
reg_ . cseq = cseq ;
PersistState ( reg_ , route_ , ppi_ , ctx_ . aor , ctx_ . transport , pcscf_ ) ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
std : : string m = AwaitFinal ( callid , cseq , " re-REGISTER " ) ;
auto st = imsd : : sip : : Status ( m ) ;
if ( st = = 200 ) return { m , cseq } ;
DumpRaw ( " imsd-register-fail.raw " , m ) ;
if ( st = = 401 ) throw RefusedError ( std : : format ( " re-REGISTER challenged: {}; re-authentication asked, the next registration is a fresh one " , imsd : : sip : : RefusalSummary ( m ) ) , 401 , imsd : : sip : : RetryAfter ( m ) . value_or ( 0 ) ) ;
throw RefusedError ( std : : format ( " re-REGISTER refused: {} " , imsd : : sip : : RefusalSummary ( m ) ) , * st , imsd : : sip : : RetryAfter ( m ) . value_or ( 0 ) ) ;
2026-07-22 22:53:28 +02:00
}
void UpdateRouteAndPpi ( const std : : string & okMsg ) {
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// an empty Service-Route value carries no route: ignored like a
// missing header, so the fallback Route the caller set stands
auto svcAll = imsd : : sip : : Headers ( okMsg , " Service-Route " ) ;
decltype ( svcAll ) svc ;
for ( auto & v : svcAll ) if ( ! v . empty ( ) ) svc . push_back ( v ) ;
2026-07-22 22:53:28 +02:00
if ( svc . empty ( ) ) Log ( " 200: no Service-Route (route stays P-CSCF) " ) ;
if ( ! svc . empty ( ) ) {
std : : string r ;
for ( std : : size_t i = 0 ; i < svc . size ( ) ; i + + ) { r + = svc [ i ] ; if ( i + 1 < svc . size ( ) ) r + = " , " ; }
route_ = r ; ctx_ . route = r ;
Log ( std : : format ( " 200 Service-Route: {} " , r ) ) ;
}
for ( auto p : imsd : : sip : : Headers ( okMsg , " Path " ) )
Log ( std : : format ( " 200 Path: {} " , p ) ) ;
auto pau = imsd : : sip : : Headers ( okMsg , " P-Associated-URI " ) ;
if ( pau . empty ( ) ) Log ( " 200: NO P-Associated-URI " ) ;
for ( auto a : pau )
Log ( std : : format ( " 200 P-Associated-URI: {} " , a ) ) ;
for ( auto a : imsd : : sip : : Headers ( okMsg , " P-Associated-URI " ) ) {
std : : size_t lt = a . find ( " <tel: " ) ;
if ( lt ! = std : : string_view : : npos ) {
std : : size_t gt = a . find ( ' > ' , lt ) ;
ppi_ = std : : string ( a . substr ( lt + 1 , gt - lt - 1 ) ) ;
ctx_ . ppi = ppi_ ;
break ;
}
}
// default public identity for self-targeted requests (reg-event
// SUBSCRIBE): first sip: P-Associated-URI entry, else the tel: one
// (the temporary IMPU is barred for anything but REGISTER)
for ( auto a : imsd : : sip : : Headers ( okMsg , " P-Associated-URI " ) ) {
std : : size_t lt = a . find ( " <sip: " ) ;
if ( lt ! = std : : string_view : : npos ) {
std : : size_t gt = a . find ( ' > ' , lt ) ;
ctx_ . aor = std : : string ( a . substr ( lt + 1 , gt - lt - 1 ) ) ;
break ;
}
}
if ( ctx_ . aor . empty ( ) & & ! ppi_ . empty ( ) ) ctx_ . aor = ppi_ ;
if ( ppi_ . empty ( ) ) Log ( " 200: no tel: P-Associated-URI — P-Preferred-Identity omitted " ) ;
Log ( std : : format ( " self AOR: {} " , ctx_ . aor . empty ( ) ? ctx_ . id . impu : ctx_ . aor ) ) ;
}
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
// AKA in the card: the challenge to the application that goes with the
// card's identity (reg_.aid: the ISIM when the identity was read from it,
// else the USIM), over a UIM logical channel. The command is the same in
// both: AUTHENTICATE with P2 '81' is the 3G context of a USIM (TS 31.102
// 7.1.2) and the IMS AKA context of an ISIM (TS 31.103 7.1.2), and both
// answer RES, CK and IK under tag DB.
// An ISIM that gives no result is not the end of the attempt: the same
// card's USIM is asked, where 1.2.2 sent every challenge —
// no AKA in a real ISIM has run on this code (AGENTS.md §5).
2026-07-22 22:53:28 +02:00
std : : optional < imsd : : aka : : AkaResult > Authenticate ( std : : span < const std : : uint8_t > rand16 , std : : span < const std : : uint8_t > autn16 ) {
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
std : : string what ;
auto result = AkaIn ( reg_ . aid , rand16 , autn16 , what ) ;
if ( ! result & & reg_ . aid ! = usimAid_ ) {
Log ( std : : format ( " AKA: the ISIM application gave no result ({}); asking the USIM " , what ) ) ;
result = AkaIn ( usimAid_ , rand16 , autn16 , what ) ;
}
if ( ! result ) Log ( std : : format ( " AKA: no result ({}) " , what ) ) ;
return result ;
}
// One AUTHENTICATE in the application `aid` of the card in reg_.slot;
// `what` says why there is no result.
std : : optional < imsd : : aka : : AkaResult > AkaIn ( const std : : string & aid , std : : span < const std : : uint8_t > rand16 , std : : span < const std : : uint8_t > autn16 , std : : string & what ) {
UimChannel ch ( reg_ . slot , aid ) ;
if ( ! ch . Open ( ) ) { what = " no logical channel opened " ; return std : : nullopt ; }
auto answer = ch . Transmit ( imsd : : aka : : BuildAkaApdu ( ch . Number ( ) , rand16 , autn16 ) ) ;
if ( ! answer ) { what = " an exchange brought no answer with a status word " ; return std : : nullopt ; }
auto result = imsd : : aka : : ParseAkaResponse ( * answer ) ;
if ( ! result ) {
what = answer - > data . empty ( ) ? std : : format ( " status word {} " , answer - > Status ( ) )
: answer - > data [ 0 ] = = 0xDC ? std : : string ( " a synchronisation failure, tag DC " )
: std : : format ( " {} bytes that are no AKA result, status word {} " , answer - > data . size ( ) , answer - > Status ( ) ) ;
}
return result ;
2026-07-22 22:53:28 +02:00
}
// ---- keepalive refresh (only while idle) ------------------------------
void MaybeRefresh ( ) {
if ( call_ | | reg_ . callid . empty ( ) ) return ;
if ( ! sip_ . Alive ( ) ) return ; // MaybeReconnect owns dead-flow recovery
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
if ( Boot ( ) - lastRefresh_ < RefreshInterval ( ) ) return ;
Step step ( * this ) ;
2026-07-22 22:53:28 +02:00
try {
RefreshPani ( ) ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
auto [ msg , used ] = Reregister ( reg_ . callid , reg_ . ftag , reg_ . cseq + 1 ) ;
2026-07-22 22:53:28 +02:00
reg_ . cseq = used ;
if ( auto e = imsd : : sip : : GrantedExpires ( msg ) ) reg_ . expiry = * e ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
PersistState ( reg_ , route_ , ppi_ , ctx_ . aor , ctx_ . transport , pcscf_ ) ;
2026-07-22 22:53:28 +02:00
Log ( std : : format ( " keepalive re-REGISTER ok (cseq {}) " , used ) ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
OnRegistered ( ) ;
} catch ( const RefusedError & e ) {
// The network refused the refresh: the recovery policy counts it
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
// — a refusal with a Retry-After of at least a second, or a 401
// (the refresh throws a challenge as a refusal), makes the fresh
// registration the next step, behind any wait the network set; a
// refusal with neither gets one more refresh first, a second
// refusal then escalates — and the flow is dropped so the next
// step runs after the wait.
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
Log ( std : : format ( " keepalive re-REGISTER failed: {} " , e . what ( ) ) ) ;
CloseFlowAfterWait ( ) ;
RecoveryFailed ( imsd : : engine : : RegRecovery : : Failure : : Refused , e . retryAfter , " keepalive refresh refused " , e . status ) ;
2026-07-22 22:53:28 +02:00
} catch ( const std : : exception & e ) {
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// A dead flow or a silent P-CSCF: the recovery is the same as a
// daemon restart's — drop the flow and let MaybeReconnect re-run
// the connect + true-refresh sequence at once.
2026-07-22 22:53:28 +02:00
Log ( std : : format ( " keepalive re-REGISTER failed: {} " , e . what ( ) ) ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
CloseFlowAfterWait ( ) ;
2026-07-22 22:53:28 +02:00
}
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
lastRefresh_ = Boot ( ) ;
2026-07-22 22:53:28 +02:00
lastKa_ = Mono ( ) ;
}
// The protected client flow can die under us while the SA and the
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
// registration stay valid — a CSFB excursion resets it, a P-CSCF may drop
// an idle flow — which is exactly the state a daemon restart resumes from
2026-07-22 22:53:28 +02:00
// (s51: "restart-to-recover"). Do what the restart does, in place:
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// reconnect the TCP leg over the existing SA and true-refresh. When that
// keeps failing — the network refuses the refresh, or nothing answers —
// do the rest of what a restart does: register fresh. RegRecovery holds
// the thresholds and the pacing (a dead PDN must not turn this into a
// hot loop; a carrier that refuses fresh SAs must not be hammered).
2026-07-22 22:53:28 +02:00
void MaybeReconnect ( ) {
if ( call_ | | sip_ . Alive ( ) | | portPs_ = = 0 | | reg_ . callid . empty ( ) ) return ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
auto plan = recovery_ . Next ( Boot ( ) ) ;
if ( plan . at > Boot ( ) ) return ;
if ( plan . step = = imsd : : engine : : RegRecovery : : Step : : Fresh ) FreshRecover ( ) ;
else ReconnectCycle ( ) ;
}
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
// A client flow found dead under an outgoing call whose INVITE has had
// no response and no CANCEL (CallMachine::Unanswered) is reopened once
// per attempt and the INVITE sent again: a flow the network had
// forgotten is reset at the first bytes sent on it, and those may be a
// call's. No REGISTER goes first: the registration and its SAs stand
// (not where the network has ended the binding: RegRecovery's
// Reconnectable, and then nothing is reopened), and TS 33.203 7.1 has a
// UE that has no TCP connection towards the P-CSCF set one up before it
// sends a request. One connect, which waits 12 s for an answer; where
// it fails, and where the flow dies again under the resent INVITE, the
// call ends (CallMachine::OnFlowLost), and the recovery policy takes
// the flow up when the call is gone (MaybeReconnect).
void MaybeResendInvite ( ) {
if ( ! call_ | | sip_ . Alive ( ) | | ! call_ - > Unanswered ( ) ) return ;
bool ok = false ;
if ( recovery_ . Reconnectable ( ) & & call_ - > ResendDue ( ) ) {
Log ( std : : format ( " call {}: the client flow died before any response to the INVITE; reopening it " , call_ - > Uni ( ) ) ) ;
sip_ . Abort ( ) ;
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
ok = sip_ . Connect ( local_ , PortUc , pcscf_ , portPs_ , transport_ , /*tries=*/ 1 , 0 , holdAlarm_ ) & & Execute ( call_ - > OnFlowReopened ( ) ) ;
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
}
if ( ! ok & & call_ & & ! call_ - > Terminated ( ) ) Execute ( call_ - > OnFlowLost ( ) ) ;
MaybeDropCall ( ) ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// The policy's next step, as the journal line: what, and when.
std : : string NextStep ( ) {
auto plan = recovery_ . Next ( Boot ( ) ) ;
double in = plan . at - Boot ( ) ;
std : : string what = plan . step = = imsd : : engine : : RegRecovery : : Step : : Fresh ? " fresh registration " : " reconnect over the existing SA " ;
if ( in < = 0 ) return std : : format ( " next: {} now " , what ) ;
if ( in > = 60 ) return std : : format ( " next: {} in {:.0f} min " , what , in / 60 ) ;
return std : : format ( " next: {} in {:.0f} s " , what , in ) ;
}
// ModemManager's word on the phone's own service, as ims-pdn-up.sh reads
// it (`mmcli -K`). False only when the modem clearly has none: a state
// short of registered, or packet service detached. Anything else —
// ModemManager not answering, a state or packet-service value this
// code does not know — counts as service: the network's silence, not
// the phone's, is the default.
bool PacketServiceUp ( ) {
auto r = RunCapture ( { " mmcli " , " -m " , " any " , " -K " } ) ;
auto field = [ & ] ( std : : string_view key ) - > std : : string {
std : : size_t at = r . out . find ( key ) ;
if ( at = = std : : string : : npos ) return { } ;
std : : size_t end = r . out . find ( ' \n ' , at ) ;
if ( end = = std : : string : : npos ) end = r . out . size ( ) ;
std : : size_t colon = r . out . find ( ' : ' , at ) ;
if ( colon = = std : : string : : npos | | colon > end ) return { } ;
std : : string v = r . out . substr ( colon + 1 , end - colon - 1 ) ;
while ( ! v . empty ( ) & & v . front ( ) = = ' ' ) v . erase ( v . begin ( ) ) ;
while ( ! v . empty ( ) & & ( v . back ( ) = = ' ' | | v . back ( ) = = ' \r ' ) ) v . pop_back ( ) ;
return v ;
} ;
std : : string state = field ( " modem.generic.state " ) , ps = field ( " modem.3gpp.packet-service-state " ) ;
for ( const char * down : { " failed " , " initializing " , " locked " , " disabled " , " disabling " , " enabling " , " enabled " , " searching " } )
if ( state = = down ) return false ;
return ps ! = " detached " ;
}
// A cycle that failed while the modem reports no packet service is the
// phone's silence, not the network's: not counted, retried on the
// local-refusal pace like a connect() the kernel refused — a radio gap
// across a refresh must not escalate to a fresh registration, which KPN
// refuses while the old one is live, and drops it for.
void CoverageGap ( std : : string_view what ) {
if ( registered_ ) { registered_ = false ; EmitStatus ( true ) ; }
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
recovery_ . OnLocalRefusal ( Boot ( ) , imsd : : engine : : RegRecovery : : Local : : NoService ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
Log ( std : : format ( " {} while the modem reports no packet service: not counted; {} " , what , NextStep ( ) ) ) ;
}
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
// While the modem reports no packet service the recovery tries nothing
// (this is its look before a reconnect cycle and before a fresh
// registration of its own; a bring-up does not ask): a reconnect would wait for answers that cannot come (over TCP
// two connects of 12 s, over UDP the re-REGISTER's 12 s), and a fresh registration its first REGISTER's 8 s, with the sleep
// lock held. The policy looks again LocalRetry on while the phone is
// awake, and wakes a sleeping one for a look at its slower pace
// (RegRecovery::WakeTime). One line where the modem is found without
// service, and again after a look that found it with. The modem's word
// does not start the gap's count over: only the network's answer does
// (RegRecovery::OnNetworkAnswered: the shell's calls and the policy's
// own). The look asks ModemManager, which can take its time: the alarm
// stands under it. A dead flow's socket that is still open does not
// outlive the look: left open through the wait a TCP one is readable at every
// turn of the loop (its end of file, its error), which would then spin
// instead of waiting, and a Dial's INVITE would be written into it.
// Abort, as at a call's reopen: a TCP FIN sent into a gap would hold the
// address pair against the reconnect after it, as a step's own close after an unanswered wait does (CloseFlowAfterWait). (A recovery step runs
// on a dead flow only: MaybeReconnect.)
bool NoService ( std : : string_view what ) {
netAlarm_ ( ) ;
if ( PacketServiceUp ( ) ) { noServiceTold_ = false ; return false ; }
sip_ . Abort ( ) ;
if ( registered_ ) { registered_ = false ; EmitStatus ( true ) ; }
recovery_ . OnLocalRefusal ( Boot ( ) , imsd : : engine : : RegRecovery : : Local : : NoService ) ;
if ( ! noServiceTold_ ) {
Log ( std : : format ( " the modem reports no packet service: {} waits until it has it again " , what ) ) ;
noServiceTold_ = true ;
}
return true ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
void ReconnectCycle ( ) {
using F = imsd : : engine : : RegRecovery : : Failure ;
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
if ( NoService ( " the reconnect " ) ) return ;
2026-07-22 22:53:28 +02:00
Log ( " client flow dead; reconnecting " ) ;
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
Step step ( * this ) ;
2026-07-22 22:53:28 +02:00
sip_ . Close ( ) ;
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
if ( ! sip_ . Connect ( local_ , PortUc , pcscf_ , portPs_ , transport_ , /*tries=*/ 2 , 0 , netAlarm_ ) ) {
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
if ( AddressGone ( ) ) return ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( sip_ . LastConnectLocal ( ) ) {
if ( registered_ ) { registered_ = false ; EmitStatus ( true ) ; }
recovery_ . OnLocalRefusal ( Boot ( ) ) ;
2026-07-22 22:53:28 +02:00
return ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( ! PacketServiceUp ( ) ) { CoverageGap ( " P-CSCF silent " ) ; return ; }
RecoveryFailed ( F : : Silent , 0 , " P-CSCF silent " ) ;
return ;
}
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
// a TCP connect the P-CSCF answered: the network is in reach (a
// UDP "connect" says nothing of it; there a REGISTER's response
// does, in AwaitFinal)
if ( transport_ = = Transport : : Tcp ) recovery_ . OnNetworkAnswered ( ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
try {
RefreshPani ( ) ;
engine, messages, util, imsd: the reregistration carries the last challenge answer and new SA parameters
The keepalive refresh and the resume's re-REGISTER carried an initial
registration's first-REGISTER Authorization — an empty nonce and
response — in the second REGISTER's frame, with a Security-Client
naming the SPIs and ports in use. TS 24.229 5.1.1.4.2 has a
reregistration carry the Authorization
of the last successful authentication — the last received nonce and
the last calculated response — and a Security-Client with the new
parameter values for the two SA pairs a re-authentication would set
up; TS 33.203 7.4.0 keeps the server ports and changes the client
ports. O2 UK refused the refresh of the old shape with 503 on every
occasion on record (alyx, 2026-09-24 to 10-08, a stationary phone
included) and accepted the fresh registrations that followed; KPN
accepted the old shape without a challenge.
The fresh registration now records the 401's nonce, our cnonce and
the response in the registration state (auth_nonce, auth_cnonce,
auth_response in the state file); a reregistration sends them
verbatim, mints new SPIs and proposes PortUcNext (45063) as the
client port with the server port unchanged. A registration resumed from a
state file written before this change has no answer: its
reregistrations carry the empty digest, as before, until its next
fresh registration, and the resume says so. A 401 to a reregistration asks
for re-authentication over temporary SAs on the proposed ports (TS
24.229 5.1.1.5.1), which imsd does not implement: the refresh throws
it as a refusal and RegRecovery makes the next step the fresh
registration, replacing the in-place answer over the old SAs.
Tested with the Messages and Engine suites and on the dev phone (KPN)
with a build of this commit's tree: a resume from the previous state
file, a fresh registration, a resume that sent the stored answer,
three refreshes at a 120-s interval, an outgoing call to a bench line
and an incoming call's ring.
2026-10-10 21:00:28 +02:00
auto [ msg , used ] = Reregister ( reg_ . callid , reg_ . ftag , reg_ . cseq + 1 ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
reg_ . cseq = used ;
if ( auto e = imsd : : sip : : GrantedExpires ( msg ) ) reg_ . expiry = * e ;
UpdateRouteAndPpi ( msg ) ;
LogBindings ( msg ) ;
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
PersistState ( reg_ , route_ , ppi_ , ctx_ . aor , ctx_ . transport , pcscf_ ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
Log ( " reconnected + re-registered " ) ;
OnRegistered ( ) ;
} catch ( const RefusedError & e ) {
Log ( std : : format ( " reconnect re-REGISTER failed: {} " , e . what ( ) ) ) ;
CloseFlowAfterWait ( ) ;
RecoveryFailed ( F : : Refused , e . retryAfter , " refresh refused " , e . status ) ;
} catch ( const std : : exception & e ) {
Log ( std : : format ( " reconnect re-REGISTER failed: {} " , e . what ( ) ) ) ;
CloseFlowAfterWait ( ) ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// the binding terminated under the wait (the flow closed, or
// under a call the wait timed out): that verdict named the next
// step, this is no silence
if ( ! recovery_ . Reconnectable ( ) ) return ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
if ( ! PacketServiceUp ( ) ) { CoverageGap ( " refresh unanswered " ) ; return ; }
RecoveryFailed ( F : : Silent , 0 , " refresh unanswered " ) ;
2026-07-22 22:53:28 +02:00
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
}
// A failed reconnect + refresh cycle: the status goes unregistered, the
// policy decides whether the next step is another cycle or a fresh
// registration, and when.
void RecoveryFailed ( imsd : : engine : : RegRecovery : : Failure f , long retryAfter , std : : string_view what , int status = 0 ) {
2026-07-22 22:53:28 +02:00
if ( registered_ ) { registered_ = false ; EmitStatus ( true ) ; }
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
bool wasReconnectable = recovery_ . Reconnectable ( ) ;
recovery_ . OnReconnectFailure ( Boot ( ) , f , retryAfter , status ) ;
KeepHolds ( ) ;
Log ( std : : format ( " {} ({} refused, {} silent cycles){}; {} " , what , recovery_ . refusals , recovery_ . silentCycles ,
wasReconnectable & & ! recovery_ . Reconnectable ( ) ? std : : format ( " — the old registration is gone ({}) " , status ) : " " , NextStep ( ) ) ) ;
}
// The rest of what a restart does, in place: a new Call-ID, a new
ipsec, imsd: the SA setup deletes by exact key instead of flushing the host's xfrm
A fresh registration's SA setup began with `ip xfrm state flush` and `ip
xfrm policy flush`: every SA userspace had installed and every SPD policy
went, a policy-based VPN's (strongSwan's, libreswan's) SAs and policies
included. The setup now takes out what two rules select and leaves the
rest; and the SA reader, which took the P-CSCF ports for a resume from any
reqid-1/2 `dir out` policy — correct only while the flush left imsd's pair
alone in the kernel — takes them from the policies between our two
addresses only. Whether imsd runs beside a live strongSwan or libreswan
connection is unmeasured: the dev phone shows a tunnel policy and a tunnel
state left in place (Tested below), no more.
OwnXfrmDeleteCommands (Imsd:Ipsec) builds the deletes from the kernel text
the shell reads: every transport-mode policy with reqid 1 or 2 whose
selector carries imsd's protected port on the UE side, by the selector ip
xfrm policy prints (src, dst, proto, sport, dport, dev) and its direction,
and every transport-mode reqid-1/2 ESP state running from such a policy's
source to its destination or anchored on the UE's ims-PDN address, by src,
dst, proto esp and SPI — policy or not: a setup whose policy add failed
leaves such states (the setup logs a failed add and goes on), and an ESP
state another transport-mode user put on that address with reqid 1 or 2 goes
with them (an AH or IPComp state is not selected: the rule asks for ESP).
Every reader of the policy text — the deletes and the SA
reader's port pass here — goes through one predicate (detail::OwnPolicy),
written for whatever reads that text later.
BuildSetupCommands loses its two flush lines and the shell runs the deletes
right before it (RunOwnXfrmDeletes); BuildTeardownCommands, the same two
flushes with no caller, goes. A policy-based VPN's tunnel entries and
another transport-mode user's pair on other ports and addresses stay.
Residual: a transport-mode policy with reqid 1 and the UE-side port 45061,
or reqid 2 and 45062 — alone or paired, between any addresses — carries
imsd's fingerprint and goes, with the reqid-1/2 transport-mode ESP states
in its direction, and a reqid-1/2 transport-mode ESP state on the UE's
ims-PDN address goes whoever made it (tests/Ipsec pins both, and that an AH state
stays).
Tested: crafter-build test, 7 passed (the eight deletes byte-exact on the
fixture in the registered FP6's shape (synthetic addresses and keys); a VPN's tunnel SA and policies beside the pair
untouched; another transport-mode user's pair on other ports and addresses
untouched, its reqid-1 ESP state on the UE's address deleted whoever made
it, its AH state left; a policy-less state on the UE's address deleted, one
between other addresses left; the reader's ports from our pair beside
a foreign transport policy with ports); on the dev phone (KPN), in builds of
this series, a fresh registration with a VPN's tunnel policy and state in
the kernel: both still there afterwards, imsd's previous pair gone.
2026-10-13 22:28:02 +02:00
// challenge, a new SA pair (FreshRegister takes the old ones out), then
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// the post-registration steps. A refused or throttled attempt waits on
// the throttle schedule (a wait no Dial cuts short — on KPN a refused
// attempt costs the old registration) and a silent one on the
// short backoff. The attempt's flow is closed whichever way it failed;
// past the SA setup the old registration's SAs are gone with it, so
// nothing is retried until the next fresh attempt.
void FreshRecover ( ) {
using F = imsd : : engine : : RegRecovery : : Failure ;
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
if ( NoService ( " the fresh registration " ) ) return ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
Log ( std : : format ( " registering fresh (recovery attempt {}) " , recovery_ . freshAttempts + 1 ) ) ;
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
Step step ( * this ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
sip_ . Close ( ) ;
saReplaced_ = false ; // this attempt's, whatever fails first
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// the subscription dialog is the registration's and goes with the
// attempt; a retry the network scheduled (its Retry-After) stands
// until a fresh registration replaces the old one; an attempt that
// fails before the SA setup leaves the old registration and that
// retry standing
subCallid_ . clear ( ) ; subPending_ = false ; subRenewAt_ = 0 ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
// a registration resumed on an older address (a pre-0.3.10 temporary
// one) moves to the PDN's own address here, server ports included;
// an attempt that fails before the SA setup leaves that registration
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// standing, so it moves back to it — the P-CSCF too, once the address
// verdict below says the registration still stands
if ( pcscfTarget_ . empty ( ) ) { RequestRestart ( std : : string ( NoFreshPcscf ) ) ; return ; }
std : : string fromPcscf = pcscf_ ;
if ( pcscf_ ! = pcscfTarget_ ) {
Log ( std : : format ( " the fresh registration moves from P-CSCF {} to {} " , pcscf_ , pcscfTarget_ ) ) ;
pcscf_ = pcscfTarget_ ;
}
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
std : : string from = local_ ;
if ( local_ ! = pdnLocal_ ) {
Log ( std : : format ( " the fresh registration moves from {} to the PDN's own address {} " , local_ , pdnLocal_ ) ) ;
MoveTo ( pdnLocal_ ) ;
}
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
// the fresh target's host route, imsd's own (BringUp's fresh path does the same)
RunCmd ( { " ip " , Is6 ( pcscf_ ) ? " -6 " : " -4 " , " route " , " replace " , pcscf_ , " dev " , dev_ } ) ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
bool ok = false ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
try {
RefreshPani ( ) ;
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
// an ISIM that has given no identity since the bring-up is asked
// again: its names can be the only ones the network takes
if ( isimOwed_ & & TakeIsimIdentity ( * isimOwed_ ) ) isimOwed_ . reset ( ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
FreshRegister ( ) ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
subRetryAt_ = 0 ; // a new registration: its subscription starts afresh
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
OnRegistered ( ) ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
ok = true ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
Log ( " recovered by a fresh registration " ) ;
} catch ( const ThrottledError & e ) {
FreshAttemptFailed ( F : : Throttled , 0 , std : : format ( " fresh registration deferred: {} " , e . what ( ) ) ) ;
} catch ( const RefusedError & e ) {
FreshAttemptFailed ( F : : Refused , e . retryAfter , std : : format ( " fresh registration refused: {} " , e . what ( ) ) ) ;
} catch ( const std : : exception & e ) {
FreshAttemptFailed ( F : : Silent , 0 , std : : format ( " fresh registration failed: {} " , e . what ( ) ) ) ;
}
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
if ( ! ok & & ! quit_ . load ( ) & & recovery_ . Reconnectable ( ) & & local_ ! = from ) {
if ( OnLink ( dev_ , from ) ) {
Log ( std : : format ( " back on {}: the old registration stands until the next fresh attempt " , from ) ) ;
MoveTo ( from ) ;
} else {
recovery_ . OldGone ( ) ;
KeepHolds ( ) ; // the verdict outlives a restart like the hold it goes with
Log ( std : : format ( " {} has left {}: the registration on it is gone; staying on {}; {} " , from , dev_ , local_ , NextStep ( ) ) ) ;
}
}
ipsec, engine, imsd: the state file records the P-CSCF and a resume follows the kernel's SA peer
A resume compared PCSCF= against the kernel's SAs and, when they did not
match, registered fresh without a word — a second initial REGISTER from an
address whose registration is live; on KPN a fresh pair to the same P-CSCF
meets the 21-minute refusal that costs the live registration (§13), what
another P-CSCF does with it is unmeasured. The registration was made to
whatever P-CSCF the SAs name (the SA setup takes imsd's previous pair
out first), so that is where a resume belongs: SaPeer reads
it from the dir-out transport policies — the one address a reqid-1 and a
reqid-2 policy both name, each with imsd's fixed protected port as its
selector's sport (reqid and mode alone are anyone's): the state text cannot tell the UE from the
P-CSCF, a lone policy is not ours and a VPN's beside the pair changes
nothing — TryResume resumes there, routes it, and says so when PCSCF=
differs; the next fresh registration moves to PCSCF= and moves back when
it fails before the SA setup and the old registration still stands (its
address still on the link), as it already did between addresses, and
its fallback Route is the P-CSCF it registers at, set before the 200's
Service-Route is looked for — an empty Service-Route value counts as
none — so a move never keeps the previous node's route. A file left by an attempt that got through the SA setup and did not live
to record — to this or another P-CSCF — is recognised by its SA pair: the
file's spi_uc/spi_us (a 0.3.x file carries them too) against the kernel's
(FileNamesAnotherPair, Imsd:Ipsec, pinned in tests/Ipsec), instead of
resumed with the wrong dialog; the state file gains pcscf, named in that
line. Both fresh paths — the bring-up's and recovery's — now set
their target themselves: with no PCSCF=, a bring-up that did not resume
fails with its own message, and since no fresh one follows: a resumable
pair whose attempt failed stays for the restart to resume, a pair nothing
can resume — one the engine's rule wrote off during the attempt among them,
a refresh refused with a 403 that carries a Retry-After or a binding a NOTIFY
terminated under the re-REGISTER wait, decided once after both catch arms by
its verdict (Reconnectable(), and with no fresh target Fresh(): a 401, a
refusal with a Retry-After, the second refusal — with no fresh target
every refusal reaches the reducer and its count travels in the holds, so
the restart's refusal is the second, while with a target only a
Retry-After does, as before — a refusal without one is not counted and the
fresh registration follows at once; without the count a refused no-target resume would re-REGISTER on the
same Call-ID at every RestartSec, the F16 loop) — is removed so the next
bring-up finds nothing — and a recovery step that needs one restarts the daemon; the "PCSCF not set" check at the top of BringUp is gone, so a
registration can be resumed with no setting at all. Three journal lines of
the fresh-target path change with it: `resume connect failed; falling back
to fresh` and `state file transport differs from SIP_TRANSPORT; fresh` end
in `the next registration is a fresh one`, and a resume the engine writes
off (a 403 with a Retry-After, a binding a NOTIFY terminated under the wait)
logs `resume failed: … — written off by the network: the next registration
is a fresh one` (§7.8). `no reg state file; resume falls back to fresh`
keeps its text with a fresh target and ends in `nothing can resume it: the
pair is removed` without one; the new `the state file names another SA pair
(0x…/0x…[ to X]) than the kernel's (0x…/0x… to Y): another attempt's; …`
line takes the same two tails.
Tested: crafter-build test, 7 passed (tests/Engine: the refusal count's travel
through the holds); the resume on the SA peer with
the fresh target absent in builds of this series on the dev
phone (KPN), and the no-target bring-up there with a resume that failed on
a transport mismatch (the pair kept, the restart resumed) and with the
state file removed (the pair removed, the next bring-up found nothing); the
two dead-resume lines' no-target tail — a missing file, a file with another
pair's SPIs — and the pair's removal on the tip's host build (bench 23f: a
fake modem on PATH, a real xfrm in a namespace; a file with the pair's SPIs
but another P-CSCF's address passes the check and the resume runs — `RESUME
via existing SA`, the connect then failing in the namespace); on the dev
phone (bench 41, the tip's build) a resume on a file without its pcscf key,
the live pair's SPIs.
2026-10-11 15:58:49 +02:00
// after the address verdict: a registration just declared gone has
// no P-CSCF to go back to
if ( ! ok & & ! quit_ . load ( ) & & recovery_ . Reconnectable ( ) & & pcscf_ ! = fromPcscf ) {
Log ( std : : format ( " back to P-CSCF {}: the old registration stands until the next fresh attempt " , fromPcscf ) ) ;
pcscf_ = fromPcscf ;
}
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
}
// Our address for everything from here on: the flow, the server ports,
// the requests' Via and Contact, the media leg.
void MoveTo ( const std : : string & addr ) {
server_ . CloseAll ( ) ;
local_ = addr ; ctx_ . local = addr ;
server_ . Open ( local_ ) ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
}
// After a failed fresh attempt, in recovery or at bring-up: the
// attempt's flow closed (a refused protected REGISTER leaves it open),
// the policy told, and its next step logged.
void FreshAttemptFailed ( imsd : : engine : : RegRecovery : : Failure f , long retryAfter , const std : : string & what ) {
CloseFlowAfterWait ( ) ;
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
if ( ! OnLink ( dev_ , local_ ) ) Log ( what ) ; // said before the address's own line: a refusal is always in the journal
if ( AddressGone ( ) ) return ;
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
bool wasReconnectable = recovery_ . Reconnectable ( ) ;
recovery_ . OnFreshFailure ( Boot ( ) , f , retryAfter , saReplaced_ ) ;
KeepHolds ( ) ;
Log ( std : : format ( " {}{}; {} " , what , wasReconnectable & & ! recovery_ . Reconnectable ( ) ? " — the old registration is gone " : " " , NextStep ( ) ) ) ;
}
ims-pdn-up, imsd: register on the PDN's own address, not the kernel's temporary one
imsd took the first global IPv6 on the ims netdev as its address, and
the kernel lists the temporary (privacy) SLAAC address first: `temporary
dynamic`, preferred for a day and valid for two by its lifetimes (read
2026-09-24). Contact, Via and the four SAs were bound to it, so once the
kernel removes it the registration has lost its address. The address
ModemManager assigned — the one the script installs — sat third on the
list. Seen on the dev phone; a field unit's journal shows the split too
— imsd registered on an address other than the one the script installed
(ims ledger F18).
Hand the assigned address to the daemon as LOCAL through /run/imsd.env,
next to DEV. For a manual run without it, prefer a global address that
is neither `temporary` nor `dynamic`, then any non-temporary one.
A restart after the upgrade finds the registration's SAs on the old
address. It resumes there while that address is still on the link, and
moves to the PDN's address in place: with its next fresh registration,
or when the old address leaves the link first. When the address it is
registered on leaves the netdev and the PDN's own address is not there
to move to, a registered imsd exits at its next recovery step, non-zero,
for a systemd restart, which runs the PDN bring-up again.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-28 18:28:58 +02:00
// After a failed recovery step: has our address left the link? An
// older registration's address (a pre-0.3.10 temporary one that
// expired) takes that registration with it: imsd moves to the PDN's
// own address and the policy's fresh step runs there, every wait it
// holds included. The PDN's own address leaving means the PDN went
// away — no retry brings it back; a restart runs the PDN bring-up
// again. True when the step that failed has nothing left to do.
bool AddressGone ( ) {
if ( OnLink ( dev_ , local_ ) ) return false ;
if ( local_ ! = pdnLocal_ & & OnLink ( dev_ , pdnLocal_ ) ) {
if ( registered_ ) { registered_ = false ; EmitStatus ( true ) ; }
std : : string from = local_ ;
recovery_ . OldGone ( ) ;
MoveTo ( pdnLocal_ ) ;
KeepHolds ( ) ; // the caller returns before its own write
Log ( std : : format ( " {} is no longer on {}: the registration on it is gone; on the PDN's own address {} now; {} " , from , dev_ , local_ , NextStep ( ) ) ) ;
return true ;
}
RequestRestart ( std : : format ( " {} is no longer on {} " , local_ , dev_ ) ) ;
return true ;
}
// Leave through systemd (Restart=on-failure), which runs ims-pdn-up.sh
// again and registers on the PDN's own address.
void RequestRestart ( const std : : string & why ) {
quit_ . store ( true ) ;
auto ev = std : : make_unique < Event > ( ) ;
ev - > type = Event : : Type : : Fatal ; ev - > text = why ;
PostEvent ( std : : move ( ev ) ) ;
}
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// Leave cleanly: nothing to do (§7.3); the
// unit stays inactive until the next boot, a `systemctl start imsd` or a
// start of imsd-ofonod (its Wants=imsd.service, the Phosh image).
void RequestIdle ( const std : : string & why ) {
quit_ . store ( true ) ;
auto ev = std : : make_unique < Event > ( ) ;
ev - > type = Event : : Type : : Idle ; ev - > text = why ;
PostEvent ( std : : move ( ev ) ) ;
}
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// After a registration succeeds — bring-up, a keepalive refresh, a
// reconnect + refresh, or a fresh recovery: the status (a signal only
// when it changes), the timers, the recovery policy, the reg-event
// subscription.
void OnRegistered ( ) {
recovery_ . OnSuccess ( ) ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
closeFlowWhenIdle_ = false ; // this registration's flow stands, whatever a verdict said of the one before
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
KeepHolds ( ) ;
bool was = registered_ ;
registered_ = true ;
EmitStatus ( ! was ) ;
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
lastRefresh_ = Boot ( ) ; lastKa_ = Mono ( ) ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// a refresh or a reconnect opens no subscription dialog while imsd
// holds one for the registration or has a retry scheduled; a fresh
// registration (or a start) has none yet, and a fresh attempt drops
// the one it holds before it sends. A retry already scheduled (the
// network's Retry-After, the backoff) is MaybeResubscribe's to send,
// not a registration's to bring forward — nor to start its backoff
// over: that resets with a subscription that starts afresh here, or
// is accepted
if ( subCallid_ . empty ( ) & & ! subPending_ & & subRetryAt_ = = 0 ) { subRetryDelay_ = 60 ; SubscribeRegEvent ( ) ; }
2026-07-22 22:53:28 +02:00
}
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// Subscribe to the reg event package (TS 24.229 5.1.1.3): one dialog per
// registration, sent over the registration flow; the S-CSCF's immediate
// NOTIFY (logged in DispatchRequest) is the network's own view of our
// bindings. Failure is non-fatal — registration is unaffected.
2026-07-22 22:53:28 +02:00
void SubscribeRegEvent ( ) {
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
subRetryAt_ = 0 ; subRenewAt_ = 0 ;
2026-07-22 22:53:28 +02:00
subCallid_ = std : : format ( " {}@{} " , rng_ . Token ( 16 ) , local_ ) ;
std : : string sub = imsd : : msg : : BuildSubscribeReg ( ctx_ , subCallid_ , rng_ . Token ( 8 ) , rng_ . Token ( 16 ) ) ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
if ( sip_ . Send ( sub ) ) { Log ( " reg-event SUBSCRIBE sent " ) ; subPending_ = true ; subSentAt_ = Mono ( ) ; }
else { Log ( " reg-event SUBSCRIBE send failed " ) ; subCallid_ . clear ( ) ; ScheduleResubscribe ( 0 ) ; }
}
// A response on the client flow that belongs to our reg-event
// SUBSCRIBE, wherever the flow is read (the run loop, a REGISTER
// wait). False when it is not ours.
bool OnSubscribeResponse ( const std : : string & msg , int st ) {
if ( subCallid_ . empty ( ) | | imsd : : sip : : Header ( msg , " Call-ID " ) ! = subCallid_ ) return false ;
if ( ! imsd : : sip : : Header ( msg , " CSeq " ) . value_or ( " " ) . ends_with ( " SUBSCRIBE " ) ) return false ;
if ( st > = 300 ) {
Log ( std : : format ( " reg-event SUBSCRIBE refused: {} " , imsd : : sip : : RefusalSummary ( msg ) ) ) ;
DumpRaw ( " imsd-subscribe-fail.raw " , msg ) ;
subPending_ = false ; subCallid_ . clear ( ) ;
ScheduleResubscribe ( imsd : : sip : : RetryAfter ( msg ) . value_or ( 0 ) ) ;
} else {
Log ( std : : format ( " reg-event SUBSCRIBE -> {} " , st ) ) ;
if ( st > = 200 ) {
DumpRaw ( " imsd-subscribe-200.raw " , msg ) ; subPending_ = false ; subRetryDelay_ = 60 ;
if ( auto e = imsd : : sip : : GrantedExpires ( msg ) ) ArmSubscriptionRenewal ( * e ) ;
}
}
return true ;
}
// The subscription is part of being registered (TS 24.229 5.1.1.3): a
// refused or unanswered SUBSCRIBE is retried, 60 s doubling to 10 min
// (a Retry-After wins), and a subscription the S-CSCF ends is renewed.
// Until now one failure left the daemon deaf to the network's view of
// its binding — O2 UK 2026-09-24: SUBSCRIBE 500, the registration
// killed 8 s later, nothing heard.
void ScheduleResubscribe ( long retryAfter ) {
double wait = std : : max ( subRetryDelay_ , static_cast < double > ( std : : min ( retryAfter , imsd : : engine : : RegRecovery : : RetryAfterMax ) ) ) ;
subRetryDelay_ = std : : min ( subRetryDelay_ * 2 , 600.0 ) ;
subRetryAt_ = Mono ( ) + wait ;
Log ( std : : format ( " reg-event: next SUBSCRIBE in {:.0f} s " , wait ) ) ;
}
void MaybeResubscribe ( ) {
if ( subPending_ & & Mono ( ) - subSentAt_ > 32 ) { // Timer F: no final at all
Log ( " reg-event SUBSCRIBE unanswered " ) ;
subPending_ = false ; subCallid_ . clear ( ) ;
ScheduleResubscribe ( 0 ) ;
}
if ( call_ | | ! registered_ | | ! sip_ . Alive ( ) ) return ;
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
if ( ! subCallid_ . empty ( ) & & ! subPending_ & & subRenewAt_ > 0 & & Boot ( ) > = subRenewAt_ ) {
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// the granted lifetime is running out: a new dialog (the S-CSCF
// closes the previous one — KPN with noresource), on the same
// registration
Log ( " reg-event: the subscription nears its expiry; subscribing anew " ) ;
subCallid_ . clear ( ) ; subRenewAt_ = 0 ;
SubscribeRegEvent ( ) ;
return ;
}
if ( subRetryAt_ = = 0 | | Mono ( ) < subRetryAt_ ) return ;
SubscribeRegEvent ( ) ;
}
// The network granted the subscription `expires` seconds (a SUBSCRIBE
// 2xx, a NOTIFY's Subscription-State): subscribe anew 10 min before the
// end, or halfway through a shorter grant.
void ArmSubscriptionRenewal ( long expires ) {
double ahead = expires > 1200 ? expires - 600.0 : expires / 2.0 ;
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
subRenewAt_ = Boot ( ) + std : : max ( ahead , 30.0 ) ;
Log ( std : : format ( " reg-event: subscription granted {} s; renewed in {:.0f} s " , expires , subRenewAt_ - Boot ( ) ) ) ;
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
}
// The network's view of our binding (RFC 3680 reginfo), read from any
// reg-event NOTIFY — a subscription an earlier process left behind
// carries the same account (O2, 2026-09-24: the previous dialog's NOTIFY
// reached a restarted daemon whose own SUBSCRIBE had just got 500). A
// binding the registrar terminated needs a new registration: the
// policy decides when (TS 24.229 5.4.1.5, 5.1.1.7 — now for deactivated
// and expired, after retry-after for probation, on the refusal schedule
// for rejected and unregistered). Active or not listed: nothing to do.
// Subscription state is per dialog: only our live dialog's end is ours
// to renew, unless the binding went with it.
void OnRegEventNotify ( const std : : string & msg , std : : string_view body ) {
using S = imsd : : sip : : RegInfoContact : : State ;
auto c = imsd : : sip : : RegInfoContactState ( body , imsd : : msg : : ContactUser ( ctx_ ) ) ;
bool bindingGone = false ;
if ( c . state = = S : : Terminated ) {
bindingGone = true ;
if ( registered_ ) { registered_ = false ; EmitStatus ( true ) ; }
// a call lives on the client flow: the flow closes when the
// call is dropped, not under it — the call goes on, or the
// network releases it, and the fresh step follows the call as
// every other recovery step does
if ( call_ ) closeFlowWhenIdle_ = true ;
else
sip_ . Close ( ) ;
subCallid_ . clear ( ) ; subPending_ = false ; subRetryAt_ = 0 ; subRenewAt_ = 0 ;
recovery_ . OnBindingTerminated ( Boot ( ) , c . event , c . retryAfter ) ;
KeepHolds ( ) ;
Log ( std : : format ( " reg-event: our binding is terminated ({}); {} " , c . event , NextStep ( ) ) ) ;
} else if ( c . state = = S : : Active ) {
Log ( " reg-event: our binding is active " ) ;
}
auto ss = imsd : : sip : : Header ( msg , " Subscription-State " ) ;
std : : string_view callid = imsd : : sip : : Header ( msg , " Call-ID " ) . value_or ( " " ) ;
bool ours = ! subCallid_ . empty ( ) & & callid = = subCallid_ ;
if ( ss & & ss - > starts_with ( " active " ) & & ours )
if ( auto e = IntAfter ( * ss , " expires= " ) ) ArmSubscriptionRenewal ( * e ) ;
if ( ss & & ss - > starts_with ( " terminated " ) & & ! ours & & ! bindingGone ) {
Log ( std : : format ( " reg-event: an earlier subscription ({}) ended ({}); ours ({}) stands " , callid , * ss , subCallid_ . empty ( ) ? " none " : subCallid_ ) ) ;
} else if ( ss & & ss - > starts_with ( " terminated " ) & & ! bindingGone ) {
// RFC 6665 §4.1.3: renew after deactivated, timeout, giveup and
// probation (after its retry-after, on the 60 s retry floor); not after rejected
// or noresource. KPN's S-CSCF ends a registration's previous
// subscription with noresource when a new one replaces it (dev
// phone 2026-09-25, Call-IDs compared); the 2026-09-24 reading
// that it ends every subscription came from opening a new one
// at every refresh and taking that closure for our own
std : : string reason ;
if ( auto r = ss - > find ( " reason= " ) ; r ! = std : : string_view : : npos ) {
std : : string_view v = ss - > substr ( r + 7 ) ;
reason = std : : string ( v . substr ( 0 , v . find_first_of ( " ;, \t \r " ) ) ) ;
}
subCallid_ . clear ( ) ; subPending_ = false ; subRenewAt_ = 0 ;
if ( reason = = " deactivated " | | reason = = " timeout " | | reason = = " giveup " | | reason = = " probation " ) {
Log ( std : : format ( " reg-event: subscription ended ({}); renewing " , * ss ) ) ;
ScheduleResubscribe ( IntAfter ( * ss , " retry-after= " ) . value_or ( 0 ) ) ;
} else {
Log ( std : : format ( " reg-event: subscription ended ({}); the next refresh subscribes anew " , * ss ) ) ;
}
}
2026-07-22 22:53:28 +02:00
}
// ---- command handling -------------------------------------------------
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
// A Dial while a call exists: refused, unless it is an emergency dial,
// which preempts whatever exists (TS 22.101) — released, and abandoned
// if it lingers awaiting a CANCEL's 487 (the late final is ignored by
// Call-ID mismatch). False when the dial was refused.
bool ClearForDial ( const Cmd & c , bool emergency ) {
if ( ! call_ ) return true ;
if ( ! emergency ) {
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
Log ( std : : format ( " dial({}) refused: call in progress " , c . arg ) ) ;
CallInfo bad { c . uni , c . arg , " terminated " , " error " , NowEpoch ( ) , 0 } ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
PostAdded ( bad ) ;
PostState ( c . uni , " terminated " , " error " ) ;
PostDeleted ( c . uni ) ;
return false ;
}
Log ( std : : format ( " emergency dial: preempting call {} " , call_ - > Uni ( ) ) ) ;
Execute ( call_ - > OnHangup ( ) ) ;
MaybeDropCall ( ) ;
if ( call_ ) { Execute ( call_ - > Abandon ( " preempted by emergency dial " ) ) ; MaybeDropCall ( ) ; }
return true ;
}
2026-07-22 22:53:28 +02:00
void HandleCmd ( const Cmd & c ) {
if ( c . kind = = Cmd : : Kind : : Stop ) { quit_ . store ( true ) ; return ; }
if ( c . kind = = Cmd : : Kind : : Dial ) {
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
bool emergency = imsd : : msg : : IsEmergency ( c . arg , emergencyExtra_ ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
if ( ! ClearForDial ( c , emergency ) ) return ;
2026-07-22 22:53:28 +02:00
// a dead client flow fails the INVITE instantly — give the
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
// recovery path one immediate shot first: user action cuts the
// backoff short, never a wait the network imposed (a
// Retry-After, the schedule after a refused or throttled fresh
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
// attempt, the one after a binding the network rejected or
// unregistered, probation's retry-after — the policy keeps those).
// The shot's REGISTER wait dispatches
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
// requests, so an incoming call may have arrived under it: the
// same rule again.
if ( ! sip_ . Alive ( ) ) {
engine: register fresh when the refresh is refused or nothing answers
After bring-up the daemon recovered a dead protected flow by
reconnecting through the existing SA and refreshing, on a 5 s → 5 min
backoff, forever. That was the whole recovery: a refresh the network
refused, or a P-CSCF that stopped answering, kept it in that loop on the
same Call-ID and SA until someone restarted the service. O2 UK,
2026-09-24: the 30-minute refresh answered 503, 21 refusals over 70 min;
after a manual restart the new registration's flow died 8 s in and no
connect over its SA succeeded for 2 h 39 min; a second restart
registered within two seconds (13:27:55 → 13:27:57 in the journal; ims
ledger F16).
Do in place the rest of what a restart does: when the refresh keeps
being refused, or reconnect cycles keep ending without an answer unless
the modem reports no packet service, register fresh. The fresh
registration is the expensive step, so a failed one waits before the
next: on a schedule (21 min, growing to 60) after a refusal or a
throttle, on a backoff after silence, and a Retry-After from the network
is honoured up to an hour. What the network set — a Retry-After, the
schedule after a refused or throttled attempt — is kept across a restart
in /run/imsd.holds, for the address it was set on. A refused initial
registration at bring-up — a final from 300 up to the unprotected
REGISTER (its 401 is the challenge), any final but 200 to the protected
one, a second 401 (rejected credentials) included — now waits on the
same schedule instead of exiting for a systemd restart every two minutes.
The policy is a pure reducer in Imsd:Engine (RegRecovery), shaped like
the call machine: the daemon supplies the clock and the network, the
reducer holds the deadlines and names the next step, and tests/Engine
pin it. tests/Engine now exits 0 or 1 instead of its failure count: with
more than 255 checks a count of 256 would exit 0, and crafter-build
reads 77 as a skipped suite. The bring-up's deferral is logged in the
policy's form: `bring-up deferred: <why> — attempt N, next fresh
registration in M min` becomes `bring-up deferred: <why>; next: fresh
registration in M min`.
A bring-up writes the verdict that the old registration is gone as well:
a start that goes on to register fresh — its resume failed, or there was
nothing to resume over — records it before the attempt, and when the
attempt then fails without an answer the daemon exits with the file in
place. The next start on the same address and boot does not resume,
where 0.3.9 retried the resume: it registers fresh at once. On KPN, with
the old registration in fact still live — a start during an outage,
staged on the dev phone — that attempt was throttled, and the 21-min
schedule began. A bring-up does not retry its resume through an outage
the way recovery reconnects.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:56:34 +02:00
recovery_ . OnDial ( ) ; MaybeReconnect ( ) ;
sip: log a refused REGISTER or SUBSCRIBE with its status line and reason headers
A refused final was logged as its bare status code ("re-REGISTER failed
503", "reg-event SUBSCRIBE -> 500") — the unprotected REGISTER's as
"expected 401", without even the code — so a field journal could not say
which node refused or what it said. O2 UK answered a phone's 30-minute
refresh with 503 twenty-one times over seventy minutes and then refused
a fresh registration's reg-event SUBSCRIBE with 500 (alyx, 2026-09-24);
the journal holds nothing but the numbers.
Log the status line with the headers that carry the reason —
Retry-After, Warning, Reason, Server — for a REGISTER's refused final
(initial, protected, refresh) and for a refused SUBSCRIBE the run loop
reads, and dump the refused message under DUMP_SIP as its own fail dump
next to the 200s.
To tell a REGISTER's final from what else arrives, the final is now
matched by Call-ID and CSeq, and a request that arrives on the client
flow while one is awaited is dispatched: a refresh no longer reads such
a request as a failed REGISTER. An INVITE among those requests is a call
like any other, announced on the bus: a Dial whose reconnect it arrived
under meets the call-in-progress rule again before it places its own,
and when a resume, a refresh or a reconnect fails the call that arrived
under it ends with the flow it came in on (486 while the flow still
carries one, and the bus told). The unprotected REGISTER's reply is
matched the same way on the init port.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-24 18:51:03 +02:00
if ( ! ClearForDial ( c , emergency ) ) return ;
}
2026-07-22 22:53:28 +02:00
RefreshPani ( ) ;
Emergency calling, stage 1: urn:service:sos with a digits fallback
Classify 112/911 (plus EMERGENCY_NUMBERS) at Dial. A classified call
INVITEs urn:service:sos over the existing registration and, on any
non-2xx final not caused by the user hanging up (including the
setup-timeout CANCEL paths), retries once as a plain INVITE of the
dialled digits — the pre-0.3.0 behavior, so classification can never
place a call worse than the status quo. The reverse edge: a 380
Alternative Service whose body carries the emergency indication
upgrades an unclassified call to the sos URN; a bare 380 stays an
error, since promoting an arbitrary redirect would put a
non-emergency call through to a PSAP. An emergency dial preempts an
in-progress call, and an answer racing a deadline-initiated CANCEL is
taken instead of BYE'd (user-initiated CANCEL races still BYE).
No emergency registration, no emergency PDN, no CS fallback, no
SIM-less calling, no AML — and no carrier has confirmed the sos path
end-to-end. The README warning states exactly that.
Assisted-by: Claude:claude-fable-5
2026-08-01 22:29:12 +02:00
if ( emergency )
Log ( std : : format ( " EMERGENCY dial ({}): urn:service:sos over the live registration, "
" fallback plain INVITE — stage 1, no emergency registration/PDN; "
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
" carrier-side behavior UNVERIFIED " , c . arg ) ) ;
call_ . emplace ( ctx_ , rng_ , c . uni , c . arg , rtpPort_ , precond_ , emergency , codecs_ ) ;
CallInfo info { c . uni , c . arg , " dialing " , " outgoing " , NowEpoch ( ) , 0 } ;
2026-07-22 22:53:28 +02:00
PostAdded ( info ) ;
bool ok = Execute ( call_ - > Start ( ) ) ;
if ( ! ok & & call_ & & ! call_ - > Terminated ( ) ) { Execute ( call_ - > Fail ( " error " ) ) ; }
MaybeDropCall ( ) ;
} else if ( c . kind = = Cmd : : Kind : : HangUp ) {
if ( call_ & & call_ - > Uni ( ) = = c . uni ) { Execute ( call_ - > OnHangup ( ) ) ; MaybeDropCall ( ) ; }
} else if ( c . kind = = Cmd : : Kind : : Accept ) {
if ( call_ & & call_ - > Uni ( ) = = c . uni ) { Execute ( call_ - > OnAccept ( ) ) ; MaybeDropCall ( ) ; }
else Log ( std : : format ( " Accept({}) ignored : no such ringing call " , c.uni)) ;
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
} else if ( c . kind = = Cmd : : Kind : : Dtmf ) {
if ( call_ & & call_ - > Uni ( ) = = c . uni ) Execute ( call_ - > OnDtmf ( c . arg ) ) ;
else Log ( std : : format ( " SendDtmf({}, '{}') ignored : no such call " , c.uni, c.arg)) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
} else if ( c . kind = = Cmd : : Kind : : SendSms ) {
QueueSms ( c ) ;
}
}
// ---- SMS over IP (§7.9) ---------------------------------------------
// The service centre a submission is addressed to (TS 24.341 5.3.1.2
// NOTE 1, NOTE 4): SMSC= when set, else EF_SMSP's TS-Service-Centre-
// Address (its validity period comes along). Without one a Send fails
// with the reason. A service centre is an international number: the
// MESSAGE's target is built from it (ScPsi), never guessed from a
// dialled form, so a service centre ScPsi makes nothing of — national,
// or with a '*' or '#' among the digits — is refused here, on ScPsi's
// own word, and never announced.
// EF_PSISMSC (a PSI of the SC configured by the operator, ahead of
// EF_SMSP in 5.3.1.2 NOTE 1's order) is not read.
void LoadSmsParameters ( ) {
scAddress_ . clear ( ) ; smsc_ . clear ( ) ; smsValidity_ . reset ( ) ;
if ( ! smscOverride_ . empty ( ) ) {
auto a = imsd : : sms : : Address : : ForNumber ( smscOverride_ ) ; // digits, * and #: the BCD table's a, b, c are not dialled (2026-10-18)
auto lv = a ? imsd : : sms : : EncodeRpAddress ( * a ) : std : : nullopt ;
if ( ! lv ) Log ( std : : format ( " sms: SMSC='{}' is not a number; SMS over IP cannot submit " , smscOverride_ ) ) ;
else if ( ! imsd : : msg : : ScPsi ( a - > Number ( ) , ctx_ . id . domain ) ) Log ( std : : format ( " sms: SMSC=' { } ' is not an international number ( + and digits ) ; SMS over IP cannot submit " , smscOverride_)); // the predicate the MESSAGE's target is built with: a '*' or '#' ForNumber dials is no service centre
else { scAddress_ = * lv ; smsc_ = a - > Number ( ) ; Log ( std : : format ( " sms: service centre {} (SMSC=) " , smsc_ ) ) ; }
} else {
auto r = RunCapture ( { " qmicli " , " -d " , " qrtr://0 " , " --uim-read-record=file=0x3F00-0x7FFF-0x6F42,record-number=1 " } ) ;
auto p = imsd : : sms : : ParseSmsp ( imsd : : sms : : ParseQmicliReadResult ( r . out ) ) ;
if ( ! p ) Log ( " sms: no service centre: EF_SMSP record 1 unreadable or without one; SMS over IP cannot submit (SMSC= in /etc/imsd.env names one) " ) ;
else if ( ! imsd : : msg : : ScPsi ( p - > scNumber , ctx_ . id . domain ) ) Log ( std : : format ( " sms: EF_SMSP's service centre ' { } ' is not an international number ( + and digits ) ; SMS over IP cannot submit ( SMSC = in / etc / imsd . env names one ) " , p->scNumber)) ;
else {
scAddress_ = p - > scAddress ; smsc_ = p - > scNumber ; smsValidity_ = p - > validity ;
Log ( std : : format ( " sms: service centre {} (EF_SMSP{}){} " , smsc_ , p - > alpha . empty ( ) ? std : : string ( ) : std : : format ( " '{}' " , p - > alpha ) ,
p - > validity ? std : : format ( " , validity period 0x{:02x} " , * p - > validity ) : std : : string ( ) ) ) ;
}
}
Log ( " SMS over IP: on (+g.3gpp.smsip advertised: short messages the network delivers over IMS arrive here) " ) ;
}
// A Send from the bus: queued behind the message in flight (one
// submission at a time on the flow), or failed, when the engine takes
// it up while imsd is not registered or its flow is down — it is not
// held for a recovery step, and the sender hears why. A queued message
// starts when the one before it ends, without this check.
void QueueSms ( const Cmd & c ) {
if ( ! registered_ | | ! sip_ . Alive ( ) ) {
PostSmsState ( c . uni , imsd : : engine : : SmsStateFailed , registered_ ? " the flow to the P-CSCF is down " : " imsd is not registered " ) ;
return ;
}
imsd : : engine : : SmsOutbound : : Params p ;
p . number = c . arg ;
p . text = c . text ;
p . scTarget = imsd : : msg : : ScPsi ( smsc_ , ctx_ . id . domain ) . value_or ( std : : string ( ) ) ; // empty without a service centre: Start fails the message with the reason
p . scAddress = scAddress_ ;
p . validity = smsValidity_ ;
p . statusReport = c . statusReport ;
smsPending_ . emplace_back ( c . uni , std : : move ( p ) ) ;
StartNextSms ( ) ;
}
// The queued messages start while none is in flight: one, and the next
// when that one ended at its start (Start refused it, or the flow
// refused its send) — in a loop, so a queue of such messages costs no
// stack.
void StartNextSms ( ) {
while ( ! smsOut_ & & ! smsPending_ . empty ( ) ) {
auto [ id , p ] = std : : move ( smsPending_ . front ( ) ) ;
smsPending_ . pop_front ( ) ;
p . tpMr = tpMr_ ; p . rpMr = rpMr_ ; p . concatRef = concatRef_ ;
const bool wantsReport = p . statusReport ;
const std : : string destination = p . number ;
engine, imsd: a submit report for a MESSAGE no longer in flight that this run sent in the last hour is answered 200
TS 24.341 5.3.1.2 has a submit report answered 200 when its In-Reply-To
"indicates that the request corresponds to a short message submitted by
the SM-over-IP sender" and 488 when it does not, and its NOTE 3 has the
sender store the Call-ID for that. imsd knew only the Call-ID of the
segment in flight (OwnsReport): a report that came once its message had
ended — the 40 s wait run out — or once its segment was followed by the
next was answered 488 like a stranger's, and its line said only "no
MESSAGE of ours in flight" (issue #3, the first of its three cases).
RecentSubmissions keeps the Call-ID of every MESSAGE a submission goes
out in for an hour, with the message's id and the segment. A report
In-Reply-To one of them that the message in flight does not take is
answered 200, and the journal has `submit report (RP-ACK) In-Reply-To
…: sms <id>'s segment i/n, no longer in flight; 200`, an RP-ERROR's
with its cause. The 488 is left for an In-Reply-To that names no MESSAGE
of ours on record, and its line says so ("on record" for "in flight").
A report without In-Reply-To that no message in flight takes by its
RP-MR is answered 200 as before; its line ends `that no message in
flight owns; 200` where it ended `for no message in flight; 200`.
The bus is told nothing of a late report: the Messaging interface is
frozen with `failed` as a message's last word (AGENTS.md §8.4), so a
text the service centre took after its wait had run out stays `failed`
there; the journal's line is the record of it.
Tested by tests/Engine: the table (a Call-ID on record for 3600 s, the
first of a list that is ours, each segment's MESSAGE put on record as it
goes out) and OnSmsMessage (200 and the line for a report on a segment
that was followed by the next, on a message that was sent and, with an
RP-ERROR's cause, on one its wait had ended; 488 and its line for a
stranger's). On the dev phone, with the binary of this range's last
commit, no report came for a MESSAGE no longer in flight (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6), so the 200 for
one and its line have run in the suite alone.
2026-11-22 17:35:12 +01:00
smsOut_ . emplace ( ctx_ , rng_ , smsSubmitted_ , id , std : : move ( p ) ) ;
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
PostWork ( true ) ; // the work's lock while it is in flight: its waits count awake seconds
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
auto actions = smsOut_ - > Start ( Mono ( ) ) ;
// on record from the start — the SC may deliver segment 1 and report on
// it while segment 2 is still in flight — and only for a message that
// asked for a report, with its destination: a report is matched by
// TP-MR and recipient, and the message gets a word for the whole
// (no TP-MRs when Start failed: nothing on record)
if ( wantsReport ) reports_ . Sent ( smsOut_ - > Id ( ) , destination , smsOut_ - > TpMrs ( ) ) ;
const std : : size_t segments = smsOut_ - > Segments ( ) ;
tpMr_ = static_cast < std : : uint8_t > ( tpMr_ + segments ) ;
if ( segments > 0 ) SaveTpMr ( tpMr_ ) ;
if ( segments > 1 ) concatRef_ + + ;
for ( const auto & a : actions )
if ( a . type = = imsd : : engine : : SmsAction : : Type : : SendClient ) DumpRaw ( " imsd-message-out.raw " , a . text ) ;
ExecuteSms ( actions ) ;
sms, engine, imsd: a segment that gets no answer, or an RP-ERROR with cause 41, is sent once more with TP-RD set
A submission whose submit report did not come in time ended as
`failed`, and nothing was sent again. The service centre may have the
text all the same, and a user who then sends it again delivers it
twice: the second submission has a new TP-MR, and the service centre
cannot tell that it is a repeat (issue #3, the second of its three
cases).
TS 23.040 9.2.3.6 has the MS "automatically repeat the SMS-SUBMIT", one
to three times, with the same TP-MR and TP-RD set, when no response or
an RP-ERROR with an appropriate cause comes, so that the service centre
can discard a duplicate. SmsOutbound now sends a segment once more: when
either wait runs out, on a final of 408 or 504 (RFC 3261 21.4.9: the
server "could not produce a response within a suitable amount of time";
21.5.5: it "did not receive a timely response from an external server")
and on an RP-ERROR with cause 41, temporary failure, or with a value TS
24.011 table 8.4's part 1 does not list, which it has "treated as cause
number 41". Of the causes part 1 lists, Annex E-2 says of 41 alone that
the MS "may wish to try another short message transfer attempt almost
immediately". The repeat is a MESSAGE of its own, under its own Call-ID
and the next RP-MR — the shell's counter now goes on after the last
RP-MR a message used, one per MESSAGE built — with the same SMS-SUBMIT,
TP-RD set by the codec's flag, which nothing set until now.
The two waits are longer, so that a repeat does not overtake an answer
that is only late: 128 s for the final and 130 s from the final for the
report. TS 24.229 table 7.7.1 recommends a UE whose requests name one
of the accesses clause 7.7 lists in P-Access-Network-Info a T1 of 2 s
and a timer F of 64*T1, and TS 24.341 5.3.1.1 NOTE 1 has an SM-over-IP
sender's TR1M set to a value greater than timer F (Jorijn, 2026-11-21).
The segment is accepted by an RP-ACK to either attempt — the first
attempt's is taken when it comes after the repeat went out — and by the
RP-ERROR whose TP-FCS is the duplicate rejection (0xC5) when it answers
the repeat and no RP-ERROR has answered the first attempt by then: the
service centre is taken to have the first. An RP-ERROR to the first
attempt that comes after the repeat went out leaves the segment to the
repeat's answer. Any other end of the repeat fails the message, with
both attempts' ends in the reason. A final refused with another status
and an RP-ERROR with another cause fail the message at once, as before.
What the duplicate rejection does not say is which SMS-SUBMIT the
service centre holds: one of this subscription's that reached it
another way under the same TP-MR can draw the rejection too, and with
imsd's first attempt lost the message is then `sent` for a text that
never arrived (Jorijn, 2026-11-21: taken as the clause has it).
Not done of the clause's repeat: it cannot be switched off, and a failed
message is not kept for a user's retransmission under its TP-MR.
No member of the Messaging interface changes: `sent` and `failed` come
as before, a `failed` later by the waits — with nothing answering, 256 s
after the MESSAGE where 1.2.0 said it after 32 s — and texts queued
behind the message wait as long.
Tested by tests/Engine and tests/Sms (RpCauseIsTemporary over all 128
values; a cross-generated SMS-SUBMIT with TP-RD), and on the dev phone
against KPN with the binary of this range's last commit (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6, repeat-bench.log):
with the phone deaf on its protected server port a text to the own
number got its 202 and no submit report, went out again 130 s after the
final under the next RP-MR, with the same TP-MR and TP-RD set, and ended
`sent`; the message after it took the RP-MR after the repeat's.
KPN's service centre did not discard the repeat in that bench, nor in
the six before it (one of them with a build that waited 40 s): the
repeat got an RP-ACK under a time stamp of its own, and once the port
was open again the text came twice, under the two attempts' time
stamps: the recipient got the text twice without the user sending it
again, and the message was `sent`. 1.2.0 ends a submission whose report
does not come as `failed` and sends nothing again.
The repeat is sent all the same, on Jorijn's decision of 2026-11-20 with
the first of those benches before him: the clause has the MS repeat
("shall") and the service centre discard ("should"), and Android's
framework sends its own retries so (AOSP's ImsSmsDispatcher and
GsmSMSDispatcher set TP-RD and the earlier TP-MR; the capture's
repeat-research).
2026-11-22 17:35:12 +01:00
if ( smsOut_ & & smsOut_ - > Done ( ) ) EndSms ( ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
}
}
sms, engine, imsd: a segment that gets no answer, or an RP-ERROR with cause 41, is sent once more with TP-RD set
A submission whose submit report did not come in time ended as
`failed`, and nothing was sent again. The service centre may have the
text all the same, and a user who then sends it again delivers it
twice: the second submission has a new TP-MR, and the service centre
cannot tell that it is a repeat (issue #3, the second of its three
cases).
TS 23.040 9.2.3.6 has the MS "automatically repeat the SMS-SUBMIT", one
to three times, with the same TP-MR and TP-RD set, when no response or
an RP-ERROR with an appropriate cause comes, so that the service centre
can discard a duplicate. SmsOutbound now sends a segment once more: when
either wait runs out, on a final of 408 or 504 (RFC 3261 21.4.9: the
server "could not produce a response within a suitable amount of time";
21.5.5: it "did not receive a timely response from an external server")
and on an RP-ERROR with cause 41, temporary failure, or with a value TS
24.011 table 8.4's part 1 does not list, which it has "treated as cause
number 41". Of the causes part 1 lists, Annex E-2 says of 41 alone that
the MS "may wish to try another short message transfer attempt almost
immediately". The repeat is a MESSAGE of its own, under its own Call-ID
and the next RP-MR — the shell's counter now goes on after the last
RP-MR a message used, one per MESSAGE built — with the same SMS-SUBMIT,
TP-RD set by the codec's flag, which nothing set until now.
The two waits are longer, so that a repeat does not overtake an answer
that is only late: 128 s for the final and 130 s from the final for the
report. TS 24.229 table 7.7.1 recommends a UE whose requests name one
of the accesses clause 7.7 lists in P-Access-Network-Info a T1 of 2 s
and a timer F of 64*T1, and TS 24.341 5.3.1.1 NOTE 1 has an SM-over-IP
sender's TR1M set to a value greater than timer F (Jorijn, 2026-11-21).
The segment is accepted by an RP-ACK to either attempt — the first
attempt's is taken when it comes after the repeat went out — and by the
RP-ERROR whose TP-FCS is the duplicate rejection (0xC5) when it answers
the repeat and no RP-ERROR has answered the first attempt by then: the
service centre is taken to have the first. An RP-ERROR to the first
attempt that comes after the repeat went out leaves the segment to the
repeat's answer. Any other end of the repeat fails the message, with
both attempts' ends in the reason. A final refused with another status
and an RP-ERROR with another cause fail the message at once, as before.
What the duplicate rejection does not say is which SMS-SUBMIT the
service centre holds: one of this subscription's that reached it
another way under the same TP-MR can draw the rejection too, and with
imsd's first attempt lost the message is then `sent` for a text that
never arrived (Jorijn, 2026-11-21: taken as the clause has it).
Not done of the clause's repeat: it cannot be switched off, and a failed
message is not kept for a user's retransmission under its TP-MR.
No member of the Messaging interface changes: `sent` and `failed` come
as before, a `failed` later by the waits — with nothing answering, 256 s
after the MESSAGE where 1.2.0 said it after 32 s — and texts queued
behind the message wait as long.
Tested by tests/Engine and tests/Sms (RpCauseIsTemporary over all 128
values; a cross-generated SMS-SUBMIT with TP-RD), and on the dev phone
against KPN with the binary of this range's last commit (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6, repeat-bench.log):
with the phone deaf on its protected server port a text to the own
number got its 202 and no submit report, went out again 130 s after the
final under the next RP-MR, with the same TP-MR and TP-RD set, and ended
`sent`; the message after it took the RP-MR after the repeat's.
KPN's service centre did not discard the repeat in that bench, nor in
the six before it (one of them with a build that waited 40 s): the
repeat got an RP-ACK under a time stamp of its own, and once the port
was open again the text came twice, under the two attempts' time
stamps: the recipient got the text twice without the user sending it
again, and the message was `sent`. 1.2.0 ends a submission whose report
does not come as `failed` and sends nothing again.
The repeat is sent all the same, on Jorijn's decision of 2026-11-20 with
the first of those benches before him: the clause has the MS repeat
("shall") and the service centre discard ("should"), and Android's
framework sends its own retries so (AOSP's ImsSmsDispatcher and
GsmSMSDispatcher set TP-RD and the earlier TP-MR; the capture's
repeat-research).
2026-11-22 17:35:12 +01:00
// The message in flight has ended: the RP-MR counter goes on after the
// last it used (every MESSAGE built for it took one, a repeat too).
void EndSms ( ) {
rpMr_ = smsOut_ - > NextRpMr ( ) ;
smsOut_ . reset ( ) ;
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
PostWork ( false ) ;
sms, engine, imsd: a segment that gets no answer, or an RP-ERROR with cause 41, is sent once more with TP-RD set
A submission whose submit report did not come in time ended as
`failed`, and nothing was sent again. The service centre may have the
text all the same, and a user who then sends it again delivers it
twice: the second submission has a new TP-MR, and the service centre
cannot tell that it is a repeat (issue #3, the second of its three
cases).
TS 23.040 9.2.3.6 has the MS "automatically repeat the SMS-SUBMIT", one
to three times, with the same TP-MR and TP-RD set, when no response or
an RP-ERROR with an appropriate cause comes, so that the service centre
can discard a duplicate. SmsOutbound now sends a segment once more: when
either wait runs out, on a final of 408 or 504 (RFC 3261 21.4.9: the
server "could not produce a response within a suitable amount of time";
21.5.5: it "did not receive a timely response from an external server")
and on an RP-ERROR with cause 41, temporary failure, or with a value TS
24.011 table 8.4's part 1 does not list, which it has "treated as cause
number 41". Of the causes part 1 lists, Annex E-2 says of 41 alone that
the MS "may wish to try another short message transfer attempt almost
immediately". The repeat is a MESSAGE of its own, under its own Call-ID
and the next RP-MR — the shell's counter now goes on after the last
RP-MR a message used, one per MESSAGE built — with the same SMS-SUBMIT,
TP-RD set by the codec's flag, which nothing set until now.
The two waits are longer, so that a repeat does not overtake an answer
that is only late: 128 s for the final and 130 s from the final for the
report. TS 24.229 table 7.7.1 recommends a UE whose requests name one
of the accesses clause 7.7 lists in P-Access-Network-Info a T1 of 2 s
and a timer F of 64*T1, and TS 24.341 5.3.1.1 NOTE 1 has an SM-over-IP
sender's TR1M set to a value greater than timer F (Jorijn, 2026-11-21).
The segment is accepted by an RP-ACK to either attempt — the first
attempt's is taken when it comes after the repeat went out — and by the
RP-ERROR whose TP-FCS is the duplicate rejection (0xC5) when it answers
the repeat and no RP-ERROR has answered the first attempt by then: the
service centre is taken to have the first. An RP-ERROR to the first
attempt that comes after the repeat went out leaves the segment to the
repeat's answer. Any other end of the repeat fails the message, with
both attempts' ends in the reason. A final refused with another status
and an RP-ERROR with another cause fail the message at once, as before.
What the duplicate rejection does not say is which SMS-SUBMIT the
service centre holds: one of this subscription's that reached it
another way under the same TP-MR can draw the rejection too, and with
imsd's first attempt lost the message is then `sent` for a text that
never arrived (Jorijn, 2026-11-21: taken as the clause has it).
Not done of the clause's repeat: it cannot be switched off, and a failed
message is not kept for a user's retransmission under its TP-MR.
No member of the Messaging interface changes: `sent` and `failed` come
as before, a `failed` later by the waits — with nothing answering, 256 s
after the MESSAGE where 1.2.0 said it after 32 s — and texts queued
behind the message wait as long.
Tested by tests/Engine and tests/Sms (RpCauseIsTemporary over all 128
values; a cross-generated SMS-SUBMIT with TP-RD), and on the dev phone
against KPN with the binary of this range's last commit (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6, repeat-bench.log):
with the phone deaf on its protected server port a text to the own
number got its 202 and no submit report, went out again 130 s after the
final under the next RP-MR, with the same TP-MR and TP-RD set, and ended
`sent`; the message after it took the RP-MR after the repeat's.
KPN's service centre did not discard the repeat in that bench, nor in
the six before it (one of them with a build that waited 40 s): the
repeat got an RP-ACK under a time stamp of its own, and once the port
was open again the text came twice, under the two attempts' time
stamps: the recipient got the text twice without the user sending it
again, and the message was `sent`. 1.2.0 ends a submission whose report
does not come as `failed` and sends nothing again.
The repeat is sent all the same, on Jorijn's decision of 2026-11-20 with
the first of those benches before him: the clause has the MS repeat
("shall") and the service centre discard ("should"), and Android's
framework sends its own retries so (AOSP's ImsSmsDispatcher and
GsmSMSDispatcher set TP-RD and the earlier TP-MR; the capture's
repeat-research).
2026-11-22 17:35:12 +01:00
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// The message in flight ended: the next queued message starts (its
// TP-MRs went on record when it started).
void AfterSms ( ) {
if ( ! smsOut_ | | ! smsOut_ - > Done ( ) ) return ;
sms, engine, imsd: a segment that gets no answer, or an RP-ERROR with cause 41, is sent once more with TP-RD set
A submission whose submit report did not come in time ended as
`failed`, and nothing was sent again. The service centre may have the
text all the same, and a user who then sends it again delivers it
twice: the second submission has a new TP-MR, and the service centre
cannot tell that it is a repeat (issue #3, the second of its three
cases).
TS 23.040 9.2.3.6 has the MS "automatically repeat the SMS-SUBMIT", one
to three times, with the same TP-MR and TP-RD set, when no response or
an RP-ERROR with an appropriate cause comes, so that the service centre
can discard a duplicate. SmsOutbound now sends a segment once more: when
either wait runs out, on a final of 408 or 504 (RFC 3261 21.4.9: the
server "could not produce a response within a suitable amount of time";
21.5.5: it "did not receive a timely response from an external server")
and on an RP-ERROR with cause 41, temporary failure, or with a value TS
24.011 table 8.4's part 1 does not list, which it has "treated as cause
number 41". Of the causes part 1 lists, Annex E-2 says of 41 alone that
the MS "may wish to try another short message transfer attempt almost
immediately". The repeat is a MESSAGE of its own, under its own Call-ID
and the next RP-MR — the shell's counter now goes on after the last
RP-MR a message used, one per MESSAGE built — with the same SMS-SUBMIT,
TP-RD set by the codec's flag, which nothing set until now.
The two waits are longer, so that a repeat does not overtake an answer
that is only late: 128 s for the final and 130 s from the final for the
report. TS 24.229 table 7.7.1 recommends a UE whose requests name one
of the accesses clause 7.7 lists in P-Access-Network-Info a T1 of 2 s
and a timer F of 64*T1, and TS 24.341 5.3.1.1 NOTE 1 has an SM-over-IP
sender's TR1M set to a value greater than timer F (Jorijn, 2026-11-21).
The segment is accepted by an RP-ACK to either attempt — the first
attempt's is taken when it comes after the repeat went out — and by the
RP-ERROR whose TP-FCS is the duplicate rejection (0xC5) when it answers
the repeat and no RP-ERROR has answered the first attempt by then: the
service centre is taken to have the first. An RP-ERROR to the first
attempt that comes after the repeat went out leaves the segment to the
repeat's answer. Any other end of the repeat fails the message, with
both attempts' ends in the reason. A final refused with another status
and an RP-ERROR with another cause fail the message at once, as before.
What the duplicate rejection does not say is which SMS-SUBMIT the
service centre holds: one of this subscription's that reached it
another way under the same TP-MR can draw the rejection too, and with
imsd's first attempt lost the message is then `sent` for a text that
never arrived (Jorijn, 2026-11-21: taken as the clause has it).
Not done of the clause's repeat: it cannot be switched off, and a failed
message is not kept for a user's retransmission under its TP-MR.
No member of the Messaging interface changes: `sent` and `failed` come
as before, a `failed` later by the waits — with nothing answering, 256 s
after the MESSAGE where 1.2.0 said it after 32 s — and texts queued
behind the message wait as long.
Tested by tests/Engine and tests/Sms (RpCauseIsTemporary over all 128
values; a cross-generated SMS-SUBMIT with TP-RD), and on the dev phone
against KPN with the binary of this range's last commit (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6, repeat-bench.log):
with the phone deaf on its protected server port a text to the own
number got its 202 and no submit report, went out again 130 s after the
final under the next RP-MR, with the same TP-MR and TP-RD set, and ended
`sent`; the message after it took the RP-MR after the repeat's.
KPN's service centre did not discard the repeat in that bench, nor in
the six before it (one of them with a build that waited 40 s): the
repeat got an RP-ACK under a time stamp of its own, and once the port
was open again the text came twice, under the two attempts' time
stamps: the recipient got the text twice without the user sending it
again, and the message was `sent`. 1.2.0 ends a submission whose report
does not come as `failed` and sends nothing again.
The repeat is sent all the same, on Jorijn's decision of 2026-11-20 with
the first of those benches before him: the clause has the MS repeat
("shall") and the service centre discard ("should"), and Android's
framework sends its own retries so (AOSP's ImsSmsDispatcher and
GsmSMSDispatcher set TP-RD and the earlier TP-MR; the capture's
repeat-research).
2026-11-22 17:35:12 +01:00
EndSms ( ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
StartNextSms ( ) ;
}
void ExecuteSms ( const std : : vector < imsd : : engine : : SmsAction > & actions ) {
using T = imsd : : engine : : SmsAction : : Type ;
bool inFlightFailed = false ;
for ( const auto & a : actions ) {
switch ( a . type ) {
case T : : SendClient :
if ( ! sip_ . Send ( a . text ) ) {
if ( smsOut_ & & imsd : : sip : : Header ( a . text , " Call-ID " ) = = smsOut_ - > CallId ( ) ) inFlightFailed = true ;
else Log ( " sms: delivery report not sent: the flow to the P-CSCF is down " ) ;
}
break ;
case T : : SendResponse :
if ( reply_ ) reply_ ( a . text ) ;
break ;
case T : : Received : PostSmsReceived ( a . received ) ; break ;
case T : : StatusReport : OnStatusReport ( a . report ) ; break ;
case T : : State : OnSubmissionWord ( a . id , a . state , a . reason ) ; break ;
case T : : Log : Log ( a . text ) ; break ;
}
2026-07-22 22:53:28 +02:00
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
if ( inFlightFailed & & smsOut_ ) ExecuteSms ( smsOut_ - > OnSendFailed ( ) ) ; // carries no send of its own
}
// A response on the client flow to a MESSAGE of ours: the message in
// flight's, or a delivery report's (logged, nothing more to do).
bool OnSmsResponse ( const std : : string & msg , int st ) {
if ( smsOut_ & & smsOut_ - > OwnsResponse ( msg ) ) {
ExecuteSms ( smsOut_ - > OnResponse ( msg , st , Mono ( ) ) ) ;
AfterSms ( ) ;
return true ;
}
if ( ! imsd : : sip : : Header ( msg , " CSeq " ) . value_or ( " " ) . ends_with ( " MESSAGE " ) ) return false ;
auto it = reportCallIds_ . find ( std : : string ( imsd : : sip : : Header ( msg , " Call-ID " ) . value_or ( " " ) ) ) ;
if ( it = = reportCallIds_ . end ( ) ) return false ;
if ( st > = 200 ) {
Log ( st > = 300 ? std : : format ( " sms: delivery report refused: {} " , imsd : : sip : : RefusalSummary ( msg ) ) : std : : format ( " sms: delivery report -> {} " , st ) ) ;
reportCallIds_ . erase ( it ) ;
}
return true ;
}
// An inbound MESSAGE (TS 24.341 5.3.2.3): answered on its own channel
// first, then what it carried — a message to the bus and its delivery
// report on the flow, a status report, a submit report for the message
// in flight. A set of a concatenated message to which no segment comes
// for SmsReassemblyMaxAge is dropped.
static constexpr double SmsReassemblyMaxAge = 1800.0 ;
void OnInboundMessage ( const std : : string & msg ) {
DumpRaw ( " imsd-message-in.raw " , msg ) ;
// a retransmission (RFC 3261 17.2.2): the same final again, nothing else
const std : : string key = imsd : : engine : : RecentTransactions : : Key ( msg ) ;
if ( auto again = recentMessages_ . Repeat ( key , Mono ( ) ) ) {
Log ( std : : format ( " MESSAGE retransmitted ({}): answered again, not handled again " , key ) ) ;
if ( reply_ ) reply_ ( * again ) ;
return ;
}
engine, imsd: a submit report for a MESSAGE no longer in flight that this run sent in the last hour is answered 200
TS 24.341 5.3.1.2 has a submit report answered 200 when its In-Reply-To
"indicates that the request corresponds to a short message submitted by
the SM-over-IP sender" and 488 when it does not, and its NOTE 3 has the
sender store the Call-ID for that. imsd knew only the Call-ID of the
segment in flight (OwnsReport): a report that came once its message had
ended — the 40 s wait run out — or once its segment was followed by the
next was answered 488 like a stranger's, and its line said only "no
MESSAGE of ours in flight" (issue #3, the first of its three cases).
RecentSubmissions keeps the Call-ID of every MESSAGE a submission goes
out in for an hour, with the message's id and the segment. A report
In-Reply-To one of them that the message in flight does not take is
answered 200, and the journal has `submit report (RP-ACK) In-Reply-To
…: sms <id>'s segment i/n, no longer in flight; 200`, an RP-ERROR's
with its cause. The 488 is left for an In-Reply-To that names no MESSAGE
of ours on record, and its line says so ("on record" for "in flight").
A report without In-Reply-To that no message in flight takes by its
RP-MR is answered 200 as before; its line ends `that no message in
flight owns; 200` where it ended `for no message in flight; 200`.
The bus is told nothing of a late report: the Messaging interface is
frozen with `failed` as a message's last word (AGENTS.md §8.4), so a
text the service centre took after its wait had run out stays `failed`
there; the journal's line is the record of it.
Tested by tests/Engine: the table (a Call-ID on record for 3600 s, the
first of a list that is ours, each segment's MESSAGE put on record as it
goes out) and OnSmsMessage (200 and the line for a report on a segment
that was followed by the next, on a message that was sent and, with an
RP-ERROR's cause, on one its wait had ended; 488 and its line for a
stranger's). On the dev phone, with the binary of this range's last
commit, no report came for a MESSAGE no longer in flight (the fp6
journal's 2026-11-20-issues-2-5 capture, phone-form6), so the 200 for
one and its line have run in the suite alone.
2026-11-22 17:35:12 +01:00
auto r = imsd : : engine : : OnSmsMessage ( ctx_ , rng_ , msg , reassembler_ , smsOut_ ? & * smsOut_ : nullptr , smsSubmitted_ , Mono ( ) ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
recentMessages_ . Remember ( key , r . response , Mono ( ) ) ;
if ( reply_ ) reply_ ( r . response ) ;
if ( ! r . reportCallId . empty ( ) ) reportCallIds_ . insert ( r . reportCallId ) ;
ExecuteSms ( r . actions ) ;
AfterSms ( ) ;
}
// The SC's word on a message we sent (an SMS-STATUS-REPORT), matched
// to the message that asked for it by TP-MR and recipient, a word for
// the whole message (StatusReportBook): delivered when its last segment
// is, still being tried, or given up on (TS 23.040 9.2.3.15's classes, a
// reserved value read as Service Rejected). A report that matches
// nothing is logged. The word is posted
// after the submission's (SmsWordOrder): held while the message is the
// one in flight.
void OnStatusReport ( const imsd : : sms : : StatusReport & sr ) {
using Word = imsd : : engine : : StatusReportBook : : Word ;
const auto o = reports_ . Report ( sr . mr , sr . recipient . Number ( ) , sr . status ) ;
switch ( o . word ) {
case Word : : NoMessage : Log ( std : : format ( " sms: status report for TP-MR {} to {}: no message of ours on record " , sr . mr , sr . recipient . Number ( ) ) ) ; return ;
case Word : : SegmentDelivered : Log ( std : : format ( " sms {}: a segment delivered (TP-MR {}); {} still to be reported " , o . id , sr . mr , o . outstanding ) ) ; return ;
case Word : : Delivered : OnReportWord ( o . id , imsd : : engine : : SmsStateDelivered , imsd : : sms : : StatusText ( sr . status ) ) ; return ;
case Word : : Pending : OnReportWord ( o . id , imsd : : engine : : SmsStateDeliveryPending , imsd : : sms : : StatusText ( sr . status ) ) ; return ;
case Word : : Failed : OnReportWord ( o . id , imsd : : engine : : SmsStateDeliveryFailed , imsd : : sms : : StatusText ( sr . status ) ) ; return ;
}
}
void OnReportWord ( const std : : string & id , std : : string_view state , std : : string_view reason ) {
const bool inFlight = smsOut_ & & smsOut_ - > Id ( ) = = id ;
const auto post = smsOrder_ . Report ( id , state , reason , inFlight ) ;
if ( post . empty ( ) ) Log ( std : : format ( " sms {}: {}: {} — held until the submission ends " , id , state , reason ) ) ;
for ( const auto & w : post ) PostSmsState ( w . id , w . state , w . reason ) ;
}
// The submission's word, the message's first (§8.4): `sent`, then the
// report's word held meanwhile; `failed`, and the message's TP-MRs are
// forgotten — unless the SC had reported every segment delivered, when
// the message is `sent` and `delivered` (the last submit report lost).
void OnSubmissionWord ( const std : : string & id , std : : string_view state , std : : string_view reason ) {
const auto e = smsOrder_ . Submission ( id , state , reason ) ;
if ( e . forget ) reports_ . ForgetMessage ( id ) ;
for ( const auto & w : e . post ) PostSmsState ( w . id , w . state , w . reason ) ;
}
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
// A received message: stored first, then the bus hears it. The id is
// this run's token, the arrival's epoch second and a per-start sequence
// number — the token tells runs apart where the clock cannot; a name
// the store already holds is never replaced: the store refuses it and
// the next number is tried, a thousand at most. A store failure is logged and the signal still goes
// out — the message is then the listener's or nobody's, and the
// delivery report stays an RP-ACK: the protocol's refusal (RP-ERROR
// cause 22) is half of a mechanism whose other half, the
// memory-available notification, imsd does not send yet (AGENTS.md §7.9).
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
void PostSmsReceived ( const imsd : : engine : : SmsReceived & m ) {
auto ev = std : : make_unique < Event > ( ) ;
ev - > type = Event : : Type : : SmsReceived ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
ev - > at = NowEpoch ( ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
ev - > sms = m ;
imsd, engine: a received text records the subscriber it arrived for
The Messaging interface gave a received text with its sender and the
service centre but not the subscriber it was for. A consumer completing a
national-form sender with a country code had to take the code from the
daemon's status at import time, which is the wrong moment: the daemon
keeps a text on disk until an app deletes it, so the app that imports it
after a SIM change knows only the new SIM's code, and a national number
under the old SIM's plan is keyed, and replied to, under the new one —
another subscriber. Only the daemon knows at receipt which subscriber a
text arrived for. The stored record and the Received and List
dictionaries carry it
as `to`: the own number the daemon holds at the moment of receipt — the
first tel: P-Associated-URI of this run's latest answer to a fresh
registration, a resume or a reconnect that carried one (a periodic
refresh's answer is not read for it) and, until the first such, the
state file's once a resume attempt has taken it up. The key is absent
while the daemon holds none.
It is additive: an app that does not know it ignores it, and a record
without it reads as before. The value comes from a header, so the
emission makes it valid UTF-8, as it does a failed submission's reason.
Tested: tests/Engine, the record round trip with `to` and a record
without it.
2026-11-02 20:54:15 +01:00
ev - > to = ppi_ ; // the subscriber it arrived for: the own number held now, not a later SIM's
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
ev - > simOperator = simOperator_ ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
std : : string why ;
StoreResult stored = StoreResult : : Failed ;
for ( int tries = 0 ; tries < 1000 ; tries + + ) {
ev - > uni = imsd : : engine : : ReceivedSmsId ( smsRun_ , ev - > at , + + smsInSeq_ ) ;
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
stored = StoreReceivedSms ( { ev - > uni , ev - > at , m , ppi_ , simOperator_ } , why ) ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
if ( stored ! = StoreResult : : Exists ) break ;
Log ( std : : format ( " sms store: {} exists already; taking the next id " , ev - > uni ) ) ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
Log ( std : : format ( " sms {}: from {} via {}, {}{} " , ev - > uni , m . from , m . sc , m . data . empty ( ) ? std : : format ( " {} bytes of text " , m . text . size ( ) ) : std : : format ( " {} bytes of 8-bit data " , m . data . size ( ) ) ,
m . segments > 1 ? std : : format ( " in {} segments " , m . segments ) : std : : string ( ) ) ) ;
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
if ( stored = = StoreResult : : Stored ) {
// a store that cannot be read back costs this line its count (the scan has logged why), never the signal or the delivery report
const auto kept = StoredSmsCount ( ) ;
Log ( kept ? std : : format ( " sms {}: stored ({} kept until an app deletes them) " , ev - > uni , * kept ) : std : : format ( " sms {}: stored " , ev - > uni ) ) ;
} else {
Log ( std : : format ( " sms {}: NOT stored — {}; the bus signal is its only delivery " , ev - > uni , stored = = StoreResult : : Exists ? " a thousand names taken " : why ) ) ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
PostEvent ( std : : move ( ev ) ) ;
}
void PostSmsState ( const std : : string & id , std : : string_view state , std : : string_view reason ) {
Log ( std : : format ( " sms {}: {}: {} " , id , state , reason ) ) ;
auto ev = std : : make_unique < Event > ( ) ;
ev - > type = Event : : Type : : SmsState ;
ev - > uni = id ; ev - > state = std : : string ( state ) ; ev - > reason = std : : string ( reason ) ;
PostEvent ( std : : move ( ev ) ) ;
2026-07-22 22:53:28 +02:00
}
void DispatchRequest ( const std : : string & msg ) {
std : : string callid ( imsd : : sip : : Header ( msg , " Call-ID " ) . value_or ( " " ) ) ;
std : : size_t sp = msg . find ( ' ' ) ;
std : : string method = msg . substr ( 0 , sp = = std : : string : : npos ? 0 : sp ) ;
if ( call_ & & callid = = call_ - > CallId ( ) ) {
callReply_ = reply_ ; // freshest channel for this dialog
Execute ( call_ - > OnRequest ( msg ) ) ;
MaybeDropCall ( ) ;
return ;
}
// ACK is never answered — e.g. the caller ACKing the 486/487 of a
// call machine we already dropped
if ( method = = " ACK " ) return ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// MESSAGE: a short message, a status report or a submit report
// over IP (§7.9), or a page-mode text — the engine says what it
// was and what to answer
if ( method = = " MESSAGE " ) {
OnInboundMessage ( msg ) ;
return ;
}
2026-07-22 22:53:28 +02:00
// reg-event NOTIFY: log the S-CSCF's reginfo (every binding it holds
// for the implicit set, feature tags as stored), then 200 it below.
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
if ( method = = " NOTIFY " ) {
sip, engine: the SMS over IP transactions as reducers
TS 24.341 has a submission travel as a MESSAGE with the RP-DATA, answered
with a final and then with the submit report in a MESSAGE of the
IP-SM-GW's own, and a delivery arrive as a MESSAGE with the RP-DATA to be
answered and acknowledged with an RP-ACK in a MESSAGE of ours. Two
pure reducers carry that, in the shape CallMachine has: SmsOutbound takes
one message of ours segment by segment — the MESSAGE, its final (a 32 s
wait, which a provisional starts over), the RP-ACK or RP-ERROR matched by
In-Reply-To, else by RP-MR (within 40 s of the final, a length TR1M may
have),
then the next segment with the next RP-MR and TP-MR — and ends it
as sent or failed, its State action carrying the reason; OnSmsMessage turns an
inbound MESSAGE into its final, the message or status report it carried
and the delivery report to send, 488 for a
submit report In-Reply-To no MESSAGE of ours in flight — one that is not
ours (5.3.1.2), or ours once the message has ended (its report's wait
run out, judged by the reducer's caller; a failure; sent) or its segment
was superseded by the next, which gets the same answer — an RP-ERROR for
a TPDU that is
unusable (a delivery or a status report that does not parse, or one of
the submit-report type), and a 200 with a log line for what it makes
nothing of: a MESSAGE whose Content-Type does not contain the SMS one, a
body that is no RP message, a submit report without In-Reply-To for no
message in flight. Imsd:Sip gains
HeaderUri, the URI of a header's first element, a quoted display name
before it passed over (none when that URI holds an ASCII control
character, a space, `<`, `>` or `"`: it goes into a request line), and
Body, moved out of CallMachine (its four call sites and the shell's
NOTIFY/MESSAGE branch follow).
No retransmission (TS 23.040 9.2.3.6's repeat with TP-RD is not done):
an unanswered MESSAGE or a report that never comes fails the message.
RecentTransactions, the reducer, keys a request by Call-ID, CSeq and Via
branch — the value of the first `branch=` of its first Via line; a
request with none or an empty one is not remembered — and gives back the
final remembered for it within 32 s (TimerJ, on every transport) — what
a caller needs to answer a retransmitted request again and not handle
it again (RFC 3261 17.2.2); without it a repeated RP-DATA would be
handled again: a second delivery report where the first got one and, of
a text in one segment, a second Received.
Every final OnSmsMessage gives an inbound MESSAGE — the 200, the 488 —
goes through BuildResponse: each Via: line echoed, the To echoed with a
tag minted for the request unless it holds `tag=` (RFC 3261 8.2.6.2).
tests/Engine drives both reducers through the dialogs above and the
retransmission table; tests/Sip pins the two helpers.
OnSmsMessage's header reads — the delivery report's target
(P-Asserted-Identity, else From) among them — go through the text
layer, which ends at the header section: a body line may spell a header
name (a text, or UCS-2 bytes that do) and must pick nothing. Pinned with
an 8-bit SMS-DELIVER whose data spells a P-Asserted-Identity line.
A UCS-2 surrogate pair a sender split across two segments comes out
whole in the Received action OnSmsMessage returns (the codec decodes a
set from its joined units); pinned.
Pinned as well: a submit report that arrives before the MESSAGE's own
final is taken (the message sent, or the next segment out under its own
Call-ID, and the late final nobody's), a text past 255 segments fails at
once naming the fit, and a delivery with no P-Asserted-Identity and no
From URI is handed over with no delivery report to send. A submit report
whose In-Reply-To lists Call-IDs (RFC 3261 20.21) is ours when ours is
among them, and a delivered MESSAGE's Call-ID with an ASCII control
character or a space in it is not written into the delivery report's
In-Reply-To.
2026-10-16 23:20:56 +02:00
std : : string_view body = imsd : : sip : : Body ( msg ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
if ( auto ev = imsd : : sip : : Header ( msg , " Event " ) ; ev & & ev - > starts_with ( " reg " ) ) {
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
Log ( std : : format ( " reg-event NOTIFY ({} bytes): \n {} " , body . size ( ) , body ) ) ;
if ( reply_ ) reply_ ( imsd : : msg : : BuildResponse200 ( ctx_ , msg ) ) ;
OnRegEventNotify ( msg , body ) ;
return ;
}
2026-07-22 22:53:28 +02:00
if ( reply_ ) reply_ ( imsd : : msg : : BuildResponse200 ( ctx_ , msg ) ) ;
return ;
}
if ( method = = " INVITE " ) {
OnIncomingInvite ( msg ) ;
return ;
}
if ( reply_ )
reply_ ( imsd : : msg : : BuildResponse200 ( ctx_ , msg ) ) ; // unsolicited (OPTIONS etc.)
}
// An out-of-dialog INVITE: a terminating (incoming) call.
void OnIncomingInvite ( const std : : string & msg ) {
if ( call_ ) {
Log ( " incoming INVITE while a call exists: 486 " ) ;
if ( reply_ ) reply_ ( imsd : : msg : : BuildInviteResponse ( ctx_ , msg , 486 , " Busy Here " , rng_ . Token ( 10 ) ) ) ;
return ;
}
std : : string uni = std : : format ( " ims-call-{} " , + + callSeq_ ) ;
DumpRaw ( " imsd-invite-in.raw " , msg ) ;
engine/sdp: CODECS override for the codecs we offer and accept
KPN's interconnect gateway transcodes every caller up: a G.711-only
fixed-line INVITE reached the phone offering PCMA, PCMU, AMR and AMR-WB
(bench call 2026-09-08), so the AMR-WB-only build rang and the narrowband
path — the one the Telia field report hit with 488 — cannot be reached on
the air through KPN by any caller.
CODECS=<list> (comma-separated over AMR-WB, AMR/AMR-NB, PCMA, PCMU) makes
the list both the codecs offered on an outgoing call and the acceptance
preference for an inbound offer, in that order: CODECS=PCMA takes G.711
A-law out of the mixed offer above, CODECS=PCMA,PCMU sends a G.711-only
offer toward the network. Unset, nothing changes — the default offer
bytes and the AMR-WB > AMR > PCMA > PCMU preference stay pinned. The
daemon logs an active override at startup.
2026-09-08 17:53:26 +02:00
call_ . emplace ( ctx_ , rng_ , uni , imsd : : engine : : IncomingInvite { msg } , rtpPort_ , codecs_ ) ;
2026-07-22 22:53:28 +02:00
callReply_ = reply_ ;
Log ( std : : format ( " incoming call {} from {} " , uni , call_ - > Number ( ) ) ) ;
2026-09-02 03:18:58 +02:00
// Validate the offer BEFORE the UI hears of the call. A refused
// INVITE (488: nothing we can play) is answered and dropped without
// ever announcing it — announcing first produced a 24 ms
// added/terminated/deleted burst that left Plasma Dialer stuck as a
// lock-screen overlay with no call to show (field report 2026-09-01).
// The journal keeps the record: caller and reason are logged above
// and by the engine's teardown line.
auto actions = call_ - > OnInvite ( ) ;
if ( call_ - > Terminated ( ) ) {
Execute ( actions , /*announce=*/ false ) ;
MaybeDropCall ( ) ;
return ;
}
2026-07-22 22:53:28 +02:00
CallInfo info { uni , call_ - > Number ( ) , " incoming " , " incoming " , NowEpoch ( ) , 0 ,
" incoming " } ;
PostAdded ( info ) ;
2026-09-02 03:18:58 +02:00
Execute ( actions ) ;
2026-07-22 22:53:28 +02:00
MaybeDropCall ( ) ;
}
// ---- action execution -------------------------------------------------
// Returns false if a client-flow send failed (used to fail a dial's INVITE).
2026-09-02 03:18:58 +02:00
// `announce` false suppresses the D-Bus state/deleted events — for a call
// that was never announced (refused before ringing), so the bus never
// sees a call it cannot show.
bool Execute ( const std : : vector < imsd : : engine : : Action > & actions , bool announce = true ) {
2026-07-22 22:53:28 +02:00
using T = imsd : : engine : : Action : : Type ;
bool sendOk = true ;
for ( const auto & a : actions ) {
switch ( a . type ) {
case T : : SendClient :
messages: sign our requests with the public identity, not the IMSI IMPU
Every request we originated — INVITE, CANCEL, both ACKs, in-dialog BYE and
friends — put the IMSI-derived temporary IMPU in From. 3GPP allows that
identity in REGISTER only; the same lesson was learned for the reg-event
SUBSCRIBE (480) and never carried to calls. Most P-CSCFs overwrite From
and hid it; a Telia node did not, and a reporter's IMSI appeared on the
callee's screen (field report 2026-09-01). A strict P-CSCF may reject the
INVITE outright.
CallerId(): the registered sip: public identity (P-Associated-URI), else
the tel: one, and the temporary IMPU only before either is learned. One
helper feeds all five builders, so a dialog's From never drifts. As UAS the
dialog's local URI is the INVITE's To (RFC 3261 12.2.1.1), stored on the
Dialog, so an incoming call's BYE is signed the way the network addressed
us. The identity is persisted in the state file and restored on warm
resume, so a call placed before the refresh 200 re-learns it cannot fall
back. DUMP_SIP now also writes the last outgoing INVITE
(imsd-invite-out.raw): the one request a field log could never show.
The byte-pinned INVITE fixture moves to the tel: identity its test context
knows; new scenarios cover the sip: identity, the tel: fallback, the
pre-learning case and the UAS BYE.
Bench-verified on KPN 2026-09-08: outgoing INVITE From is the registered
sip: identity, call accepted and carried; caller ID at the far end
unchanged.
2026-09-08 20:37:47 +02:00
// the outgoing INVITE is the one request a field log could
// never show (DUMP_SIP dumped inbound messages only)
if ( a . text . starts_with ( " INVITE " ) ) DumpRaw ( " imsd-invite-out.raw " , a . text ) ;
2026-07-22 22:53:28 +02:00
if ( ! sip_ . Send ( a . text ) ) { sendOk = false ; Log ( " client send failed " ) ; }
break ;
case T : : SendResponse :
if ( callReply_ ) callReply_ ( a . text ) ;
else if ( reply_ ) reply_ ( a . text ) ;
break ;
case T : : StartMedia : StartMedia ( a . media ) ; break ;
case T : : StopMedia : StopMedia ( ) ; break ;
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
case T : : SendDtmf : SendDtmfToMedia ( a . text ) ; break ;
2026-09-02 03:18:58 +02:00
case T : : State :
if ( announce ) PostState ( call_ - > Uni ( ) , a . state , a . reason ) ;
break ;
case T : : Deleted :
if ( announce ) PostDeleted ( call_ - > Uni ( ) ) ;
dropCall_ = true ;
break ;
2026-07-22 22:53:28 +02:00
case T : : SetDeadline : deadline_ = Mono ( ) + a . seconds ; break ;
case T : : Log : Log ( a . text ) ; break ;
}
}
return sendOk ;
}
void MaybeDropCall ( ) {
engine: keep the reg-event subscription alive and act on a terminated binding
The reg-event subscription is the network's own account of our binding
(TS 24.229 5.1.1.3), and the daemon opened a new dialog for it at every
refresh and reconnect and otherwise never looked back: a refused
SUBSCRIBE was forgotten, an unanswered one had no timeout, an ended
subscription got nothing until the next refresh's new dialog, and a
NOTIFY was logged whatever it said. O2 UK, 2026-09-24: a fresh
registration's SUBSCRIBE got 500, a NOTIFY arrived all the same and
showed our contact active, the flow died eight seconds after the 200 and
no connect over the SA succeeded after that; the 500 was logged and
nothing was done about it.
Keep the subscription alive: retry a refused or unanswered SUBSCRIBE on
a backoff, renew one the S-CSCF ends with deactivated, timeout, giveup
or probation (RFC 6665 4.1.3; after any other reason, or none, the next
refresh subscribes anew), and subscribe anew ahead of the lifetime the
S-CSCF granted. A refresh or a reconnect opens no dialog while imsd
holds one for the registration or has a retry scheduled.
Read the reginfo for our own contact and act on its state: a NOTIFY that
terminates our binding schedules a fresh registration — at once for
deactivated or expired, after the network's retry-after (up to an hour)
for probation, on imsd's own refusal schedule (21 min, growing to 60)
for rejected or unregistered (RFC 3680). A hold already running stands,
and a REGISTER wait a call kept open that still gets its 200 after such
a NOTIFY leaves that registration standing. The parser is in Imsd:Sip
and pinned by tests/Sip with the O2 document shapes; the policy is
RegRecovery's (OnBindingTerminated, added here with its tests in
tests/Engine).
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 19:36:23 +02:00
if ( ! dropCall_ ) return ;
call_ . reset ( ) ; callReply_ = nullptr ; dropCall_ = false ;
if ( closeFlowWhenIdle_ ) {
closeFlowWhenIdle_ = false ;
Log ( " the call is over: closing the flow of the binding the network terminated under it " ) ;
sip_ . Close ( ) ;
}
2026-07-22 22:53:28 +02:00
}
void StartMedia ( const imsd : : engine : : MediaLeg & leg ) {
if ( ! leg . Valid ( ) ) { Log ( " SDP answer missing media endpoint; no media leg " ) ; return ; }
sdp, engine, imsd, media: the far end's telephone-event packets are played as the tones they stand for
Keys pressed on the other phone reached imsd-media as RFC 4733 events and
were dropped with every packet that is not the audio's. The playout now
takes them: the gap before an event's start (a stock sender's DTX silence
often precedes a key press) is filled as before an audio frame, each
packet reports the event's duration so far from its start stamp, and what
the clock has not covered yet is synthesized as the event's Q.23
frequency pair at the packet's volume, so a retransmitted end packet adds
nothing, a lost update is caught up by the next, and a far end whose
audio resumes past the event (the stock phone's does) meets the clock
with the usual fill. An answer may renumber telephone-event from what we
offered (RFC 3264: the answerer sends with the offer's numbers, §6.1,
and the offerer with the answer's, §5.1), so the leg gets both: DTMF_PT
to send with, DTMF_RX_PT to take events at as well — our own SDP's
number: the offer's 98 or 100 on a call we placed, the offer's number we
echoed on one we answered; when the answer gave the audio our offer's
number, that number is the leg's audio and DTMF_RX_PT is the answer's
telephone-event number instead — and takes events at either number,
never at the audio's. --selftest pins the frequency table; the stats
gain rx_dtmf, tones and dtmf_rx_pt.
Tested: --selftest, tests/Sdp and tests/Engine (the eight suites pass);
the loopback's --dtmf-rx arm on a host build of this commit's tree
(journal/ims/captures/2026-10-15-dtmf-loopback-c3-rx.txt; the tx, both,
plain and collision runs beside it); the dev phone's dtmf benches ran in
builds of this series.
2026-10-15 21:18:28 +02:00
Log ( std : : format ( " media {} pt={} octet={} -> [{}]:{}, telephone-event pt {}{} " , leg . codec , leg . payloadType , leg . octetAlign , leg . remoteIp , leg . remotePort ,
leg . dtmfPt ? std : : to_string ( * leg . dtmfPt ) : std : : string ( " none " ) ,
leg . dtmfRxPt & & leg . dtmfRxPt ! = leg . dtmfPt ? std : : format ( " (theirs {}) " , * leg . dtmfRxPt ) : std : : string ( ) ) ) ;
2026-07-22 22:53:28 +02:00
if ( Is6 ( leg . remoteIp ) ) RunCmd ( { " ip " , " -6 " , " route " , " replace " , leg . remoteIp , " dev " , dev_ } ) ;
else
RunCmd ( { " ip " , " route " , " replace " , leg . remoteIp , " dev " , dev_ } ) ;
std : : string outBase = std : : format ( " {}/dialer_{} " , outDir_ , call_ ? call_ - > Uni ( ) : std : : string ( " x " ) ) ;
std : : vector < std : : string > argv = {
mediaBin_ , local_ , std : : to_string ( rtpPort_ ) , leg . remoteIp ,
std : : to_string ( leg . remotePort ) , std : : to_string ( leg . payloadType ) ,
" 86400 " , outBase } ;
imsd, media: aim call audio at logind's seat0 session, not an account named `user`
imsd-media defaulted AUDIO_USER to `user`, postmarketOS's default
account name, and with no such account a call had no audio on the phone
and noise at the far end, the message only in imsd-media's stderr, at
each call. A field user found it by trial (alyx report 14, 2026-09-20;
ims ledger F14).
Have imsd, as packaged (root, on the system bus), resolve the session
from logind when a call's media starts — the user session active on
seat0 (a greeter is not one) when it has a PipeWire socket — and hand it
to imsd-media as AUDIO_USER; set in imsd's own environment to an
account's name, AUDIO_USER pins that account instead. imsd as packaged
(root, on the system bus) logs the resolution at start, before the first
call, and when a call's media starts.
No session is an empty AUDIO_USER. imsd-media started without the
variable at all keeps `user`: that is an imsd older than 0.3.10, still
running while an upgrade replaces the helper under it, whose calls would
otherwise be silent until the restart, or a hand run.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-25 17:15:02 +02:00
AudioSession session ;
if ( geteuid ( ) = = 0 ) {
session = ResolveAudioSession ( ) ;
Log ( AudioSessionLine ( session ) + ( session . name . empty ( ) ? " ; this call has no audio " : " " ) ) ;
}
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
// the control pipe: imsd-media reads `dtmf <tones>` lines on its
// stdin (§7.6); our end closes with the leg, no other child inherits
// it, and it never blocks the engine thread — a leg that stopped
// reading fails the write (EAGAIN once the pipe is full) instead
int ctl [ 2 ] = { - 1 , - 1 } ;
if ( pipe ( ctl ) ! = 0 ) {
Log ( std : : format ( " media control pipe: {}; this call has no DTMF " , std : : strerror ( errno ) ) ) ;
} else {
fcntl ( ctl [ 0 ] , F_SETFD , FD_CLOEXEC ) ;
fcntl ( ctl [ 1 ] , F_SETFD , FD_CLOEXEC ) ;
fcntl ( ctl [ 1 ] , F_SETFL , O_NONBLOCK ) ;
}
2026-07-22 22:53:28 +02:00
pid_t pid = fork ( ) ;
if ( pid = = 0 ) {
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
if ( ctl [ 0 ] > = 0 ) dup2 ( ctl [ 0 ] , STDIN_FILENO ) ; // dup2 clears the close-on-exec
imsd, media: aim call audio at logind's seat0 session, not an account named `user`
imsd-media defaulted AUDIO_USER to `user`, postmarketOS's default
account name, and with no such account a call had no audio on the phone
and noise at the far end, the message only in imsd-media's stderr, at
each call. A field user found it by trial (alyx report 14, 2026-09-20;
ims ledger F14).
Have imsd, as packaged (root, on the system bus), resolve the session
from logind when a call's media starts — the user session active on
seat0 (a greeter is not one) when it has a PipeWire socket — and hand it
to imsd-media as AUDIO_USER; set in imsd's own environment to an
account's name, AUDIO_USER pins that account instead. imsd as packaged
(root, on the system bus) logs the resolution at start, before the first
call, and when a call's media starts.
No session is an empty AUDIO_USER. imsd-media started without the
variable at all keeps `user`: that is an imsd older than 0.3.10, still
running while an upgrade replaces the helper under it, whose calls would
otherwise be silent until the restart, or a hand run.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-25 17:15:02 +02:00
if ( geteuid ( ) = = 0 ) {
// no session is said with an empty value: imsd-media reads a
// missing variable as a caller older than 0.3.10
setenv ( " AUDIO_USER " , session . name . c_str ( ) , 1 ) ;
}
2026-07-22 22:53:28 +02:00
setenv ( " MIC " , EnvOr ( " MIC " , " 1 " ) . c_str ( ) , 1 ) ;
setenv ( " PLAY " , EnvOr ( " PLAY " , " 1 " ) . c_str ( ) , 1 ) ;
setenv ( " GAIN " , EnvOr ( " GAIN " , " 10 " ) . c_str ( ) , 1 ) ;
setenv ( " PLAY_GAIN " , EnvOr ( " PLAY_GAIN " , " 1.0 " ) . c_str ( ) , 1 ) ;
setenv ( " AMR_MODE " , EnvOr ( " AMR_MODE " , " 2 " ) . c_str ( ) , 1 ) ;
setenv ( " DTX " , EnvOr ( " DTX " , " 0 " ) . c_str ( ) , 1 ) ;
setenv ( " OCTET_ALIGN " , leg . octetAlign ? " 1 " : " 0 " , 1 ) ;
media: play AMR narrowband and G.711 as well as AMR-WB
imsd-media spoke exactly one codec, AMR-WB. A landline caller reaches the
IMS core through the PSTN gateway, which offers narrowband — AMR (NB)
and/or G.711 — so with the engine now accepting those offers the media leg
has to play them.
CODEC (set by the daemon from the negotiated SDP) selects AMR-WB (the
default, unchanged), AMR, PCMA or PCMU. AMR narrowband rides the same RFC
4867 payload code as AMR-WB with its own frame-size table (RFC 4867 table
1) and libopencore-amrnb dlopen'd like the wideband pair — same package as
the AMR-WB decoder, no new dependency; AMR_MODE defaults to 7 (12.2 kbit/s)
for it. G.711 is the ITU-T table codec, raw samples in the payload, digital
zero as keepalive. The narrowband path runs pw-record/pw-play at 8 kHz and
steps the RTP clock by 160 per frame.
Two test seams so the leg can be driven against a synthetic RTP peer with
no PipeWire and no network: MIC_SRC=<file> feeds raw PCM through the
encoder in real time instead of pw-record, PCM_DUMP=1 writes the decoded
downlink to <out>.pcm. --selftest now covers both AMR tables (both payload
formats) and G.711 (digital zero, idempotence over the full 16-bit range,
1 kHz sine SNR >= 30 dB for both laws).
Verified on the workstation with a Python gateway stand-in for PCMA, PCMU
and AMR (octet-aligned and bandwidth-efficient): uplink RTP shape (pt, seq,
ts step 160, payload sizes 160 / 33 / 32) and a 440 Hz mic tone recovered
from our packets by an independent decoder; a 1 kHz gateway tone recovered
from our decoded downlink. The AMR-WB default path keeps its legacy
keepalive shape (ts step 320, FT0 payloads 19/18 bytes).
2026-09-02 03:18:58 +02:00
setenv ( " CODEC " , leg . codec . c_str ( ) , 1 ) ;
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
setenv ( " DTMF_PT " , leg . dtmfPt ? std : : to_string ( * leg . dtmfPt ) . c_str ( ) : " " , 1 ) ;
sdp, engine, imsd, media: the far end's telephone-event packets are played as the tones they stand for
Keys pressed on the other phone reached imsd-media as RFC 4733 events and
were dropped with every packet that is not the audio's. The playout now
takes them: the gap before an event's start (a stock sender's DTX silence
often precedes a key press) is filled as before an audio frame, each
packet reports the event's duration so far from its start stamp, and what
the clock has not covered yet is synthesized as the event's Q.23
frequency pair at the packet's volume, so a retransmitted end packet adds
nothing, a lost update is caught up by the next, and a far end whose
audio resumes past the event (the stock phone's does) meets the clock
with the usual fill. An answer may renumber telephone-event from what we
offered (RFC 3264: the answerer sends with the offer's numbers, §6.1,
and the offerer with the answer's, §5.1), so the leg gets both: DTMF_PT
to send with, DTMF_RX_PT to take events at as well — our own SDP's
number: the offer's 98 or 100 on a call we placed, the offer's number we
echoed on one we answered; when the answer gave the audio our offer's
number, that number is the leg's audio and DTMF_RX_PT is the answer's
telephone-event number instead — and takes events at either number,
never at the audio's. --selftest pins the frequency table; the stats
gain rx_dtmf, tones and dtmf_rx_pt.
Tested: --selftest, tests/Sdp and tests/Engine (the eight suites pass);
the loopback's --dtmf-rx arm on a host build of this commit's tree
(journal/ims/captures/2026-10-15-dtmf-loopback-c3-rx.txt; the tx, both,
plain and collision runs beside it); the dev phone's dtmf benches ran in
builds of this series.
2026-10-15 21:18:28 +02:00
setenv ( " DTMF_RX_PT " , leg . dtmfRxPt ? std : : to_string ( * leg . dtmfRxPt ) . c_str ( ) : " " , 1 ) ;
2026-07-22 22:53:28 +02:00
std : : vector < char * > c ;
for ( auto & s : argv ) c . push_back ( const_cast < char * > ( s . c_str ( ) ) ) ;
c . push_back ( nullptr ) ;
execvp ( c [ 0 ] , c . data ( ) ) ;
_exit ( 127 ) ;
}
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
if ( ctl [ 0 ] > = 0 ) close ( ctl [ 0 ] ) ;
if ( pid < 0 & & ctl [ 1 ] > = 0 ) { close ( ctl [ 1 ] ) ; ctl [ 1 ] = - 1 ; }
2026-07-22 22:53:28 +02:00
mediaPid_ = pid ;
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
mediaCtl_ = ctl [ 1 ] ;
}
// The engine's SendDtmf action: one `dtmf <tones>` line down the
// control pipe, whole or not at all — a write of at most PIPE_BUF bytes
// to a pipe is atomic, and the engine's DtmfMaxTones keeps the line
// under it (a longer line is refused here too, never half-written to
// be joined with the next). The leg may have died since the action was
// decided (its exit is reaped on this thread, after the actions ran):
// then the write fails with EPIPE — SIGPIPE is ignored in main() — and
// the tones are lost with the call, which the reap ends.
void SendDtmfToMedia ( const std : : string & tones ) {
if ( mediaCtl_ < 0 ) { Log ( std : : format ( " DTMF '{}' not sent: no control pipe to the media leg " , tones ) ) ; return ; }
const std : : string line = std : : format ( " dtmf {} \n " , tones ) ;
if ( line . size ( ) > PIPE_BUF ) { Log ( std : : format ( " DTMF of {} tones not sent: longer than the control pipe's atomic write " , tones . size ( ) ) ) ; return ; }
const ssize_t n = write ( mediaCtl_ , line . data ( ) , line . size ( ) ) ;
if ( n ! = static_cast < ssize_t > ( line . size ( ) ) ) Log ( std : : format ( " DTMF '{}' not sent: {} " , tones , n < 0 ? std : : strerror ( errno ) : " short write to the media leg " ) ) ;
}
void CloseMediaCtl ( ) {
if ( mediaCtl_ > = 0 ) close ( mediaCtl_ ) ;
mediaCtl_ = - 1 ;
2026-07-22 22:53:28 +02:00
}
void StopMedia ( ) {
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
CloseMediaCtl ( ) ;
2026-07-22 22:53:28 +02:00
if ( mediaPid_ < = 0 ) return ;
kill ( mediaPid_ , SIGTERM ) ;
for ( int i = 0 ; i < 100 ; i + + ) {
if ( waitpid ( mediaPid_ , nullptr , WNOHANG ) ! = 0 ) { mediaPid_ = - 1 ; return ; }
usleep ( 100000 ) ;
}
kill ( mediaPid_ , SIGKILL ) ;
waitpid ( mediaPid_ , nullptr , 0 ) ;
mediaPid_ = - 1 ;
}
void ReapMedia ( ) {
if ( ! call_ | | mediaPid_ < = 0 ) return ;
if ( call_ - > State ( ) ! = imsd : : engine : : CallState : : Active ) return ;
int status = 0 ;
pid_t r = waitpid ( mediaPid_ , & status , WNOHANG ) ;
if ( r = = 0 ) return ; // still running
int code = WIFEXITED ( status ) ? WEXITSTATUS ( status ) : - 1 ;
mediaPid_ = - 1 ; // reaped; don't re-terminate
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
CloseMediaCtl ( ) ;
2026-07-22 22:53:28 +02:00
Execute ( call_ - > OnMediaExit ( code ) ) ;
MaybeDropCall ( ) ;
}
// ---- events -----------------------------------------------------------
void EmitStatus ( bool registrationSignal ) {
auto ev = std : : make_unique < Event > ( ) ;
ev - > type = registrationSignal ? Event : : Type : : Registration : Event : : Type : : Status ;
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
ev - > status = StatusSnapshot { registered_ , local_ , pcscf_ , ppi_ , reg_ . expiry , reg_ . cseq , smsc_ , simOperator_ } ;
2026-07-22 22:53:28 +02:00
PostEvent ( std : : move ( ev ) ) ;
}
void PostAdded ( const CallInfo & info ) {
auto ev = std : : make_unique < Event > ( ) ; ev - > type = Event : : Type : : Added ; ev - > info = info ;
PostEvent ( std : : move ( ev ) ) ;
}
void PostState ( const std : : string & uni , const std : : string & state , const std : : string & reason ) {
auto ev = std : : make_unique < Event > ( ) ; ev - > type = Event : : Type : : State ;
ev - > uni = uni ; ev - > state = state ; ev - > reason = reason ;
PostEvent ( std : : move ( ev ) ) ;
}
void PostDeleted ( const std : : string & uni ) {
auto ev = std : : make_unique < Event > ( ) ; ev - > type = Event : : Type : : Deleted ; ev - > uni = uni ;
PostEvent ( std : : move ( ev ) ) ;
}
} ;
Engine * TheEngine = nullptr ;
// ================= GDBus ===================================================
constexpr const char * IntrospectionXml = R " xml(
< node >
< interface name = " net.catcrafts.IMS1 " >
< method name = " Dial " >
< arg type = " s " name = " number " direction = " in " / >
< arg type = " s " name = " callUni " direction = " out " / >
< / method >
< method name = " HangUp " > < arg type = " s " name = " callUni " direction = " in " / > < / method >
< method name = " Accept " > < arg type = " s " name = " callUni " direction = " in " / > < / method >
< method name = " SendDtmf " >
< arg type = " s " name = " callUni " direction = " in " / >
< arg type = " s " name = " tones " direction = " in " / >
< / method >
< method name = " GetCalls " > < arg type = " aa{sv} " name = " calls " direction = " out " / > < / method >
< method name = " GetStatus " > < arg type = " a{sv} " name = " status " direction = " out " / > < / method >
< signal name = " CallAdded " > < arg type = " s " name = " callUni " / > < arg type = " a{sv} " name = " info " / > < / signal >
< signal name = " CallStateChanged " >
< arg type = " s " name = " callUni " / > < arg type = " s " name = " state " / > < arg type = " s " name = " reason " / >
< / signal >
< signal name = " CallDeleted " > < arg type = " s " name = " callUni " / > < / signal >
< signal name = " RegistrationChanged " > < arg type = " b " name = " registered " / > < / signal >
< / interface >
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
< interface name = " net.catcrafts.IMS1.Messaging " >
< method name = " Send " >
< arg type = " s " name = " number " direction = " in " / >
< arg type = " s " name = " text " direction = " in " / >
< arg type = " a{sv} " name = " options " direction = " in " / >
< arg type = " s " name = " id " direction = " out " / >
< / method >
< method name = " GetStatus " > < arg type = " a{sv} " name = " status " direction = " out " / > < / method >
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
< method name = " List " > < arg type = " a(sa{sv}) " name = " messages " direction = " out " / > < / method >
< method name = " Delete " > < arg type = " s " name = " id " direction = " in " / > < / method >
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
< method name = " Subscribe " / >
< signal name = " Received " > < arg type = " s " name = " id " / > < arg type = " a{sv} " name = " message " / > < / signal >
< signal name = " StateChanged " >
< arg type = " s " name = " id " / > < arg type = " s " name = " state " / > < arg type = " s " name = " reason " / >
< / signal >
< / interface >
2026-07-22 22:53:28 +02:00
< / node > ) xml " ;
void HandleMethodCall ( GDBusConnection * , const gchar * , const gchar * , const gchar * , const gchar * method , GVariant * params , GDBusMethodInvocation * inv , gpointer ) {
std : : string_view m = method ;
if ( m = = " Dial " ) {
const gchar * number = nullptr ;
g_variant_get ( params , " (&s) " , & number ) ;
std : : string uni = TheEngine - > Dial ( number ? number : " " ) ;
g_dbus_method_invocation_return_value ( inv , g_variant_new ( " (s) " , uni . c_str ( ) ) ) ;
return ;
}
if ( m = = " HangUp " ) {
const gchar * uni = nullptr ;
g_variant_get ( params , " (&s) " , & uni ) ;
TheEngine - > HangUp ( uni ? uni : " " ) ;
g_dbus_method_invocation_return_value ( inv , nullptr ) ;
return ;
}
if ( m = = " Accept " ) {
const gchar * uni = nullptr ;
g_variant_get ( params , " (&s) " , & uni ) ;
TheEngine - > Accept ( uni ? uni : " " ) ;
g_dbus_method_invocation_return_value ( inv , nullptr ) ;
return ;
}
if ( m = = " SendDtmf " ) {
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
const gchar * uni = nullptr ;
const gchar * tones = nullptr ;
g_variant_get ( params , " (&s&s) " , & uni , & tones ) ;
TheEngine - > SendDtmf ( uni ? uni : " " , tones ? tones : " " ) ;
2026-07-22 22:53:28 +02:00
g_dbus_method_invocation_return_value ( inv , nullptr ) ;
return ;
}
if ( m = = " GetCalls " ) {
GVariantBuilder b ;
g_variant_builder_init ( & b , G_VARIANT_TYPE ( " aa{sv} " ) ) ;
for ( auto & [ uni , info ] : Calls )
g_variant_builder_add_value ( & b , CallVariant ( info ) ) ;
g_dbus_method_invocation_return_value ( inv , g_variant_new ( " (aa{sv}) " , & b ) ) ;
return ;
}
if ( m = = " GetStatus " ) {
GVariantBuilder b ;
g_variant_builder_init ( & b , G_VARIANT_TYPE ( " a{sv} " ) ) ;
g_variant_builder_add ( & b , " {sv} " , " registered " , g_variant_new_boolean ( StatusSnap . registered ) ) ;
g_variant_builder_add ( & b , " {sv} " , " local " , g_variant_new_string ( StatusSnap . local . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " pcscf " , g_variant_new_string ( StatusSnap . pcscf . c_str ( ) ) ) ;
g_variant_builder_add ( & b , " {sv} " , " expiry " , g_variant_new_int64 ( StatusSnap . expiry ) ) ;
g_variant_builder_add ( & b , " {sv} " , " cseq " , g_variant_new_int64 ( StatusSnap . cseq ) ) ;
g_variant_builder_add ( & b , " {sv} " , " ppi " , g_variant_new_string ( StatusSnap . ppi . c_str ( ) ) ) ;
g_dbus_method_invocation_return_value ( inv , g_variant_new ( " (a{sv}) " , & b ) ) ;
return ;
}
g_dbus_method_invocation_return_dbus_error ( inv , " org.freedesktop.DBus.Error.UnknownMethod " , " no such method " ) ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
// net.catcrafts.IMS1.Messaging (§8.4): Send is gated by the Messaging
// action; GetStatus is a read.
void HandleMessagingMethod ( GDBusConnection * conn , const gchar * , const gchar * , const gchar * , const gchar * method , GVariant * params , GDBusMethodInvocation * inv , gpointer ) {
std : : string_view m = method ;
if ( m = = " Send " ) {
const gchar * number = nullptr ;
const gchar * text = nullptr ;
GVariant * options = nullptr ;
g_variant_get ( params , " (&s&s@a{sv}) " , & number , & text , & options ) ;
gboolean statusReport = FALSE ;
if ( options ) { g_variant_lookup ( options , " status-report " , " b " , & statusReport ) ; g_variant_unref ( options ) ; }
if ( ! TheEngine - > SmsEnabled ( ) ) {
g_dbus_method_invocation_return_dbus_error ( inv , " org.freedesktop.DBus.Error.NotSupported " , " SMS over IP is off (SMS_OVER_IMS=1 in /etc/imsd.env enables it) " ) ;
return ;
}
std : : string id = TheEngine - > SendSms ( number ? number : " " , text ? text : " " , statusReport = = TRUE ) ;
SendOrigins [ id ] = g_dbus_method_invocation_get_sender ( inv ) ;
g_dbus_method_invocation_return_value ( inv , g_variant_new ( " (s) " , id . c_str ( ) ) ) ;
return ;
}
if ( m = = " Subscribe " ) {
SubscribeMessaging ( conn , g_dbus_method_invocation_get_sender ( inv ) ) ;
g_dbus_method_invocation_return_value ( inv , nullptr ) ;
return ;
}
if ( m = = " GetStatus " ) {
GVariantBuilder b ;
g_variant_builder_init ( & b , G_VARIANT_TYPE ( " a{sv} " ) ) ;
// the configuration, not the registration snapshot: an asker before
// the first registration (a script at login, an app at start) reads
// the truth
g_variant_builder_add ( & b , " {sv} " , " enabled " , g_variant_new_boolean ( TheEngine - > SmsEnabled ( ) ? TRUE : FALSE ) ) ;
g_variant_builder_add ( & b , " {sv} " , " smsc " , g_variant_new_string ( StatusSnap . smsc . c_str ( ) ) ) ;
2026-11-02 22:26:52 +01:00
g_variant_builder_add ( & b , " {sv} " , " ppi " , g_variant_new_take_string ( g_utf8_make_valid ( StatusSnap . ppi . c_str ( ) , - 1 ) ) ) ; // from a header, as `to`
imsd, engine: the Messaging status and a received text carry the SIM's operator
A consumer that keeps a number in the form it was written in — a
national number, an operator's short code — has to know where it was
written before it dials it again: a national number's country, a short
code's operator. The own number's country code is not enough for either:
countries share a code, and the operators of one country share theirs.
The daemon reads the SIM's operator id at bring-up (ModemManager's: MCC
then MNC), which names the subscription's country and operator. The
Messaging GetStatus gives it as `operator`, from the snapshot `ppi`
comes from, and a received text's record and its Received and List
dictionaries carry the one the daemon held at receipt, beside `to` —
additive keys, as `to` and `ppi` are, and the operator id only, never
the IMSI.
Tested: tests/Engine, the record round trip with `operator` and a
record without it.
2026-11-12 00:21:41 +01:00
g_variant_builder_add ( & b , " {sv} " , " operator " , g_variant_new_string ( StatusSnap . simOperator . c_str ( ) ) ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
g_variant_builder_add ( & b , " {sv} " , " registered " , g_variant_new_boolean ( StatusSnap . registered ? TRUE : FALSE ) ) ;
g_variant_builder_add ( & b , " {sv} " , " subscribers " , g_variant_new_uint32 ( static_cast < guint32 > ( Subscribers . size ( ) ) ) ) ;
g_dbus_method_invocation_return_value ( inv , g_variant_new ( " (a{sv}) " , & b ) ) ;
return ;
}
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
if ( m = = " List " ) {
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
const StoreRead store = LoadStoredSms ( ) ;
if ( store . fault ) {
// not a shorter list: a consumer takes a record List leaves out for one it may forget
g_dbus_method_invocation_return_dbus_error ( inv , " org.freedesktop.DBus.Error.IOError " , store . fault . Reason ( ) . c_str ( ) ) ;
return ;
}
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
GVariantBuilder b ;
g_variant_builder_init ( & b , G_VARIANT_TYPE ( " a(sa{sv}) " ) ) ;
imsd: List answers IOError for a store it could not read, and a scan's read error no longer ends the daemon
LoadStoredSms had no way to report a failure. A store directory that
could not be opened read as an empty store, and a record that could not
be opened read as a corrupt file and was skipped: Messaging.List
answered success with texts missing. A consumer that forgets a deleted
text's id once List no longer carries it forgets it too early then, and
imports the text again when a later List has it; and a text that
arrived while no app ran stays unseen until another List (issue #5).
The scans also walked the directory with the iterator's throwing
increment and tested each entry with is_regular_file() in its throwing
form, and nothing catches that at the start's sweep, in List's handler
or in the run loop: a read error there ended the process — in the run
loop from the count for the `stored` journal line, with a text stored
and its delivery report unsent.
The three scans now go through opendir, readdir, stat and read. What a
scan cannot read is a StoreFault, logged by the scan that met it;
List's read and the count hand theirs back as well. List answers
org.freedesktop.DBus.Error.IOError with the system's reason, the error
Delete gives for a removal that failed: no list, so a consumer takes
nothing for deleted and asks again. A store directory that does not
exist is still an empty list, and a file that reads and is no record is
still skipped with its line. The sweep logs the fault and lets the
daemon start; the `stored` line goes without its count. The journal
names what could not be read: `sms store: cannot read <path>:
<reason>`.
The Messaging interface is frozen as of 1.2.0 (AGENTS.md §8.4): no
member, signature, key, state word or error name changes; List gains a
failure answer under an error name the interface has.
Tested in dev mode on a private session bus, on the workstation's
build of this commit (the fp6 journal's 2026-11-20-issues-2-5 capture,
list-io): IOError with "Permission denied" for the store directory at
mode 000 and at mode 400 and for a record at mode 000, and with "Not a
directory" for a file in the directory's place; an empty list with no
directory; both records listed beside a file that is no record, a
directory and a dangling link named like records; a start with the
directory at mode 000 logs the sweep's fault and the daemon answers.
On the dev phone, with the binary of this range's last commit (the
capture's phone-form6): an empty list with the store directory moved
away, IOError with "Not a directory" with a file in its place, the
fault in the journal for each call it refused. Not benched: a read
that fails part-way, a file removed between the directory's read and
its own, a process out of descriptors, the `stored` line without its
count.
2026-11-22 17:35:12 +01:00
for ( const auto & r : store . records ) g_variant_builder_add ( & b , " (s@a{sv}) " , r . id . c_str ( ) , SmsVariant ( r . sms , r . receivedAt , r . to , r . simOperator ) ) ;
imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface
A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.
For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).
Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.
The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
2026-10-17 00:24:50 +02:00
g_dbus_method_invocation_return_value ( inv , g_variant_new ( " (a(sa{sv})) " , & b ) ) ;
return ;
}
if ( m = = " Delete " ) {
const gchar * id = nullptr ;
g_variant_get ( params , " (&s) " , & id ) ;
const std : : string_view sid = id ? id : " " ;
if ( ! ValidSmsId ( sid ) ) {
g_dbus_method_invocation_return_dbus_error ( inv , " org.freedesktop.DBus.Error.InvalidArgs " , " not a message id " ) ;
return ;
}
std : : error_code ec ;
const bool removed = std : : filesystem : : remove ( SmsRecordPath ( sid ) , ec ) ;
if ( ec ) {
// the removal failed: nothing says the record is gone
Log ( std : : format ( " sms {}: not deleted from the store: {} " , sid , ec . message ( ) ) ) ;
g_dbus_method_invocation_return_dbus_error ( inv , " org.freedesktop.DBus.Error.IOError " , ec . message ( ) . c_str ( ) ) ;
return ;
}
if ( ! removed ) {
g_dbus_method_invocation_return_dbus_error ( inv , " org.freedesktop.DBus.Error.FileNotFound " , " no such message " ) ;
return ;
}
// the record only: a `<id>.msg.tmp` beside it is left alone — the
// writer unlinks its own, and the engine's next start removes a crash's
// leftover (SweepSmsStore)
Log ( std : : format ( " sms {}: deleted from the store " , sid ) ) ;
g_dbus_method_invocation_return_value ( inv , nullptr ) ;
return ;
}
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
g_dbus_method_invocation_return_dbus_error ( inv , " org.freedesktop.DBus.Error.UnknownMethod " , " no such method " ) ;
}
imsd, imsd-ofonod: let polkit decide call control, not the account name
The system-bus policies granted net.catcrafts.IMS1 and org.ofono to root
and to the account `user`, postmarketOS's default name, so on a unit
whose account is called something else dbus denied every Dial from the
dialer — nothing in imsd's journal, nothing on screen. A field user
found it by trial (alyx report 14, 2026-09-20; ims ledger F14).
Let any local account reach both names and have the daemons decide:
placing, answering or ending a call needs polkit's
net.catcrafts.IMS1.Voice (the active local session; not an ssh login, an
inactive session or a system service account). imsd-ofonod asks about
its own callers, since its calls reach imsd as root. Reads such as the
status and the call list are not gated, and a refusal is logged with the
sender; a `--session` run, the development mode without root or polkit,
leaves the gate off. The check is ImsdBus, a small GLib module both
daemons link; the package depends on polkit.
An upgrade restarts both daemons (the previous commit), so the open
policy faces the old, ungated daemons only until the apk transaction
ends.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 20:44:58 +02:00
bool IsRead ( std : : string_view method ) { return method = = " GetStatus " | | method = = " GetCalls " ; }
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
bool IsMessagingRead ( std : : string_view method ) { return method = = " GetStatus " ; }
imsd, imsd-ofonod: let polkit decide call control, not the account name
The system-bus policies granted net.catcrafts.IMS1 and org.ofono to root
and to the account `user`, postmarketOS's default name, so on a unit
whose account is called something else dbus denied every Dial from the
dialer — nothing in imsd's journal, nothing on screen. A field user
found it by trial (alyx report 14, 2026-09-20; ims ledger F14).
Let any local account reach both names and have the daemons decide:
placing, answering or ending a call needs polkit's
net.catcrafts.IMS1.Voice (the active local session; not an ssh login, an
inactive session or a system service account). imsd-ofonod asks about
its own callers, since its calls reach imsd as root. Reads such as the
status and the call list are not gated, and a refusal is logged with the
sender; a `--session` run, the development mode without root or polkit,
leaves the gate off. The check is ImsdBus, a small GLib module both
daemons link; the package depends on polkit.
An upgrade restarts both daemons (the previous commit), so the open
policy faces the old, ungated daemons only until the apk transaction
ends.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 20:44:58 +02:00
constexpr char ErrAccessDenied [ ] = " org.freedesktop.DBus.Error.AccessDenied " ;
const GDBusInterfaceVTable Vtable = { imsd : : bus : : Gated < HandleMethodCall , IsRead , ErrAccessDenied , Log > , nullptr , nullptr , { } } ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
const GDBusInterfaceVTable MessagingVtable = { imsd : : bus : : Gated < HandleMessagingMethod , IsMessagingRead , ErrAccessDenied , Log , imsd : : bus : : MessagingAction > , nullptr , nullptr , { } } ;
2026-07-22 22:53:28 +02:00
void OnBusAcquired ( GDBusConnection * conn , const gchar * , gpointer ) {
DbusConn = conn ;
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
g_dbus_connection_signal_subscribe ( conn , " org.freedesktop.login1 " , " org.freedesktop.login1.Manager " , " PrepareForSleep " ,
" /org/freedesktop/login1 " , nullptr , G_DBUS_SIGNAL_FLAGS_NONE , OnPrepareForSleep , nullptr , nullptr ) ;
// the engine began before the bus was there: what it has asked for by now
HoldSleepOff ( CallLock , CallLock . want ) ;
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
HoldSleepOff ( WorkLock , WorkLock . want ) ;
imsd, engine, ImsdBus, packaging, README: SMS over IP behind SMS_OVER_IMS=1, net.catcrafts.IMS1.Messaging
With the modem's own IMS client off, a carrier that carries SMS over IMS
only leaves the phone no path for texts but imsd; on one with SMS over
NAS the +g.3gpp.smsip tag may take them off a path that works (the
order is operator policy, TS 24.341 5.3.3.4.2 NOTE 2). So the knob is the user's and off by default: SMS_OVER_IMS=1
advertises the tag (Context::smsOverIp), reads the service centre from
EF_SMSP record 1 at bring-up — SMSC= instead — and opens Send on a
second interface, net.catcrafts.IMS1.Messaging, beside the frozen one,
gated by a polkit action of its own (Gated's Action parameter; the Voice
action's callers are unchanged). The shell keeps one message in flight
on the flow and queues the rest, routes the in-flight MESSAGE's final
to it (OnSmsResponse; a submit report reaches it through OnSmsMessage),
seeds and advances the TP-MR, RP-MR and concatenation counters, answers an inbound
MESSAGE outside a call through OnSmsMessage (one inside the call's
dialog stays the CallMachine's, and is not the MESSAGE of any sentence
below) — the message to the bus as
Received, the delivery report on the flow with its final logged, a
status report matched by TP-MR and recipient to the message that asked
for one — and reports a message's fate as StateChanged. A Send is judged
when the engine takes its command up: unregistered or with the flow down
then, it fails with that reason.
The journal names a delivered message's sender, size and time — a text
reaches it only as the body of a MESSAGE whose Content-Type does not
contain application/vnd.3gpp.sms or as the hex of a body that is no RP
message or of an unusable TPDU; DUMP_SIP adds the two MESSAGE dumps.
While the knob is off a network may deliver a short message over IP
regardless; answering it 200 and acknowledging it would count it
delivered to nobody, so it is refused with 480 Temporarily Unavailable,
which lets the IP-SM-GW try the modem's path where the network has one
(TS 24.341 5.3.3.4.2 NOTE 2); a MESSAGE outside a call's dialog whose
Content-Type does not contain application/vnd.3gpp.sms (letter case
ignored) is still answered 200 and logged with its body — the 200 in
BuildResponse's shape now, the line with the content type. A
retransmitted MESSAGE — the same
Call-ID, CSeq and Via branch (the value of the first `branch=` of its
first Via line; a MESSAGE with none or an empty one is never taken for a
copy) within 32 s of our final, in the same run of the daemon — is
answered again and not handled again (the engine's RecentTransactions, a
table in memory), where a repeated RP-DATA would otherwise,
with SMS over IP on, be handled again: a second delivery report where
the first got one and, of a text in one segment, a second text.
The Messaging signals carry a text's content, and a D-Bus broadcast
reaches every account the bus policy lets receive from imsd — which
polkit cannot narrow — so they are never broadcast: Subscribe, behind the
same action as Send, records the caller's unique name, and Received and
StateChanged go unicast to each subscriber (the submission's sent or
failed also to the Send caller), which the bus delivers to those
connections — root's busctl monitor sees them as well. A subscription
ends with its connection; a consumer
subscribes at start and again when imsd's name reappears. GetStatus
answers `enabled` from the daemon's configuration, not from the
registration snapshot, so an asker before the first registration reads
the truth.
A message's id holds the run's token, eight hex digits drawn from
std::random_device at the daemon's start, ahead of a second and a
count: `ims-sms-<run>-<start>-<N>` for
a sent text, with the start second and a counter, and
`ims-sms-in-<run>-<epoch>-<N>` for a received one, with its second. A
counter starts over with the daemon, and the phone's wall clock reads
1970 until the first time sync, so a second repeats across runs: the
token is what tells one run's ids from another's, and a client keys by id
(RunToken, SentSmsId and ReceivedSmsId, pinned by tests/Engine).
Tested on the dev phone on KPN (2026-10-17; the fp6 journal's
2026-10-17-sms-over-ip-bench capture) on sms-branch builds ahead of this
history (195e91b, then c57765a with the retransmission absorption): the
tag on a resumed and on a fresh registration, Sends to 202 and their
submit reports in one and two segments and in UCS-2, texts received in
one and two segments and in UCS-2, every delivery report answered 202
but one of the two for the 01:23 text, refused 488 on the build before
the absorption, and a same-second retransmission absorbed under c57765a
(01:44) — AGENTS.md §5 has the record and §13 the network facts,
among them that the modem was CS-detached that night. On the host's
session bus in dev mode:
two Sends answered with ids and failed "imsd is not registered"
(2026-10-16), and three connections — a subscriber, a match-rule-only
listener, an unsubscribed sender — where only the subscriber and the
sender heard the StateChanged and the subscription ended with its
connection (2026-10-17); with the knob off, GetStatus's `enabled` false,
Send refused NotSupported and Subscribe answered (a private session bus,
this commit's host build, 2026-11-19; its sha256 begins 98e30a9522409d99).
The SMSC= override ran on 2026-10-18 from 02:17
(smsc-override-2026-10-18-0217):
the EF_SMSP number as an override and a Send through it to sent, and
SMSC=abc stopped at bring-up with "is not a number" (ForNumber dials
digits, * and # only; the bench's first run, on a build outside this
history that dialled the BCD table's a, b and c, submitted with them and
got an RP-ERROR back, RP cause 28).
A status report is matched to the message that asked for one by its TP-MR
and the recipient's number — among this run's messages: the book is in
memory — and the message gets a word for the whole (StatusReportBook,
pinned), by TS 23.040 9.2.3.15's classes of TP-ST: delivery-failed at the
first report in which the SC is not making any more transfer attempts (a
permanent error or a temporary one; a reserved value too, read as
"Service Rejected" as the clause has the MS read it), delivered when the
last of its segments is reported in the completed class (the SC's word
in the reason) — never a later segment's word over an earlier failure.
The next TP-MR is kept in
<state dir>/sms-tpmr across restarts, so the TP-MRs continue instead of
starting over at random: a reuse needs a full 256-segment wrap, not a
restart (a report can be days late) — as long as the file's last write
reached the disk: it is neither checked nor synced.
One message's StateChanged words come in the order they mean, which is
not the order imsd learns them: the service centre can deliver and report
on segment 1 while segment 2 is still on its way. SmsWordOrder
(Imsd:Engine, pure) gives the order §8.4 states: the submission's word
first — `sent`, or `failed`, after which nothing follows — and a
report's only after `sent`. A report's word on the message in flight is
held until the submission ends (the latest word; one message is in
flight at a time) and posted after `sent`. A submission that fails after
the centre reported every segment delivered posts `sent`, the failure in
its reason, and then `delivered`. A `failed` otherwise drops the held
word and StatusReportBook::ForgetMessage forgets the message's TP-MRs, so
a later report on a part that went matches nothing and is logged.
tests/Engine pins the book's forgetting and each of these orders.
BuildResponse (the messages commit) is the final of the inbound MESSAGE
path from here on — the 200, the 480 and the 488; BuildResponse200's hop-by-hop
shape stays for the other answers that had it.
The reassembler's 30-minute age-out is judged in the run loop beside the
SMS deadline, whether or not another MESSAGE ever comes.
The MESSAGE's target is the service centre's own international number
(ScPsi), not RuriFor's dialled-number guess, whose trunk-0 rule is
Dutch: a national SMSC= of nine or more characters starting with 0 would
have become a +31 number, a 00-prefixed one +<the rest>, any other
non-international value a phone-context URI at the home domain; a service
centre ScPsi makes nothing of (national, 00-prefixed, or a '*' or '#'
among the digits, which ForNumber dials) is refused at bring-up on that same
predicate with a journal line, never announced, and Send then fails
with no service centre.
A failed submission's StateChanged reason can hold the network's text (a
refused final's, RefusalSummary); a D-Bus string must be valid UTF-8, so
the emission makes it so (g_utf8_make_valid: bytes that are not become
U+FFFD, and a NUL byte ends the string).
2026-10-16 23:30:25 +02:00
GError * err = nullptr ;
GDBusNodeInfo * node = g_dbus_node_info_new_for_xml ( IntrospectionXml , & err ) ;
if ( ! node ) { Log ( std : : format ( " introspection XML: {} " , err ? err - > message : " ? " ) ) ; if ( err ) g_error_free ( err ) ; return ; }
for ( GDBusInterfaceInfo * * i = node - > interfaces ; * i ; i + + ) {
const GDBusInterfaceVTable * vt = std : : string_view ( ( * i ) - > name ) = = MessagingIface ? & MessagingVtable : & Vtable ;
if ( ! g_dbus_connection_register_object ( conn , ObjPath , * i , vt , nullptr , nullptr , & err ) ) {
Log ( std : : format ( " {} not registered at {}: {} " , ( * i ) - > name , ObjPath , err ? err - > message : " ? " ) ) ;
if ( err ) { g_error_free ( err ) ; err = nullptr ; }
}
}
2026-07-22 22:53:28 +02:00
g_dbus_node_info_unref ( node ) ;
Log ( std : : format ( " object registered at {} " , ObjPath ) ) ;
}
gboolean OnTerm ( gpointer loop ) {
Log ( " SIGTERM — stopping engine (SA kept) " ) ;
if ( TheEngine ) TheEngine - > Stop ( ) ;
g_timeout_add_seconds ( 2 , [ ] ( gpointer l ) - > gboolean {
g_main_loop_quit ( static_cast < GMainLoop * > ( l ) ) ; return G_SOURCE_REMOVE ; } , loop ) ;
return G_SOURCE_REMOVE ;
}
} // namespace
int main ( int argc , char * * argv ) {
bool session = false ;
for ( int i = 1 ; i < argc ; i + + )
if ( std : : string_view ( argv [ i ] ) = = " --session " ) session = true ;
if ( argv [ 0 ] ) {
std : : string p = argv [ 0 ] ;
auto slash = p . find_last_of ( ' / ' ) ;
if ( slash ! = std : : string : : npos ) SelfDir = p . substr ( 0 , slash ) ;
}
if ( ! session & & geteuid ( ) ! = 0 ) {
std : : println ( std : : cerr , " imsd: must run as root (xfrm / qmicli) " ) ;
return 1 ;
}
sdp, engine, imsd: SendDtmf sends the tones as RFC 4733 events over the media leg
SendDtmf was a stub: GNOME Calls' SendTones and Plasma Dialer's sendDtmf
reached imsd and went nowhere. The SDP parser reads the telephone-event
payload type at the chosen codec's clock into the answer, among the
m-line's formats only — an rtpmap the line does not list is not
negotiated, and nothing is sent with a format the answer does not carry
(RFC 3264 §8.3.2); an event's rate is its rtpmap clock (RFC 4733
§2.4.1), an offer with two codec clocks lists telephone-event at each,
and the name is matched as every encoding name is, case-insensitively,
with the clock whole. The media leg carries it, and imsd-media gets it
as DTMF_PT with its stdin on a pipe from imsd, the control pipe. The
SDP answer imsd sends to an inbound offer carries telephone-event by the
same rule, where it echoed any telephone-event rtpmap with a lower-case
name and a clock prefix before: an rtpmap off the offer's m-line is no
longer echoed, an upper-case name now is. The decision is the engine's:
OnDtmf lets the tones through on an active call that negotiated
telephone-event (the answer's number on a call we placed, the offer's on
one we answered) and drops them otherwise with a line that says why:
before the answer, after the call, no telephone-event at the codec's
clock in the SDP, a character that is no tone or more than 128 tones
(then the whole string, never part of what was pressed); letters are
upper-cased. The shell writes one `dtmf <tones>` line per SendDtmf,
whole or not at all: the bound keeps the line within one atomic pipe
write, the write end is non-blocking so that a leg that stopped reading
fails the write instead of holding the engine thread, and a longer line
is refused; SIGPIPE is ignored so that a write after the leg died fails
with EPIPE instead of ending the daemon. The command queue's one
argument is `arg` now — the number to dial, or the tones. The `media …`
start line gains the telephone-event pt at its end.
Tested: tests/Sdp and tests/Engine (the eight suites pass); the dev
phone's dtmf benches ran in builds of this series
(journal/ims/captures/2026-10-14-dtmf-bench-1/ onward).
2026-10-14 15:05:24 +02:00
// A write to the media leg's control pipe after the leg died must fail
// with EPIPE, not end the daemon (the client flow's sends carry
// MSG_NOSIGNAL; an inbound connection's reply is a plain write and is
// covered by this too).
signal ( SIGPIPE , SIG_IGN ) ;
2026-07-22 22:53:28 +02:00
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// The bring-up found nothing to do (IMSD_IDLE= in /run/imsd.env — the
// script's arms: no SIM, a refused ims PDN): say so and
// leave cleanly. Restart=on-failure leaves a clean exit alone, so the
// unit stays inactive until the next boot, a manual start or a start of
// imsd-ofonod (its Wants=imsd.service).
if ( std : : string idle = EnvOr ( " IMSD_IDLE " , " " ) ; ! idle . empty ( ) ) {
Log ( std : : format ( " idle: {} — nothing to do; systemctl start imsd when that changes " ,
idle = = " no-sim " ? " no SIM " : idle = = " no-ims-pdn " ? " no ims PDN from the network " : idle ) ) ;
return 0 ;
}
2026-07-22 22:53:28 +02:00
std : : string dev = EnvOr ( " DEV " , " qmapmux0.0 " ) ;
std : : string local = EnvOr ( " LOCAL " , " " ) ;
if ( local . empty ( ) ) {
if ( auto l = DetectLocal ( dev ) ) local = * l ;
}
if ( local . empty ( ) & & ! session ) {
std : : println ( std : : cerr , " imsd: no global IPv6 on {} — is the ims PDN up? " , dev ) ;
return 1 ;
}
ipsec, imsd, ims-pdn-up: the SA reader and the holds key compare in canonical form; LOCAL is canonicalised, PCSCF= accepted in RFC 5952 §4 form only
ParseExistingSa and SaLocals compared PCSCF= and LOCAL= as text against
`ip xfrm` output, which prints RFC 5952 form, so an upper-case or
uncompressed PCSCF= found no SAs and the restart registered fresh — on
KPN into the live-SA refusal; the holds file's pdn key compared the same
way. Both sides of each of those compares now go through
imsd::util::CanonicalAddr, LOCAL is canonicalised once on the way in, and PCSCF= is accepted in
that one spelling only — upper case, leading zeros or an uncompressed run
are refused at bring-up with the spelling to use, a dotted-quad tail (the
form ip prints for an IPv4-mapped address, which CanonicalIp6 does not read)
with the rule alone, a bracketed one by the bring-up script, which routes
the value as typed, with the rule (no brackets) — and a comma-separated
PCSCF= (a list) with its own message instead of reaching the socket layer: one spelling,
instead of a leniency both consumers of the setting would have to share.
Tested: crafter-build test, 7 passed; the upper-case PCSCF= refused with the spelling to use, a bracketed one
refused by the script, and the spelling they name resuming, in builds of
this series on the dev phone (KPN).
2026-10-11 15:55:19 +02:00
local = imsd : : util : : CanonicalAddr ( local ) ;
imsd: P-CSCF candidates from PCSCF_DISCOVERED when PCSCF= is not set
imsd reads PCSCF_DISCOVERED= — a comma-separated IPv6 list — from its
environment; nothing in this tree writes it yet. FreshPcscfFromEnv picks
the fresh target: PCSCF= when set — one address, it wins — else the first
entry of the list CanonicalIp6 accepts; the journal says which, and names
the entries it refused. imsd routes the P-CSCF it uses itself — the fresh
target before a fresh registration (BringUp, FreshRecover), the resumed SA
peer once its SAs are confirmed — with the same idempotent `ip -6 route
replace` as a call's media peer: the bring-up script routes only the configured
PCSCF=, so a target taken from PCSCF_DISCOVERED= (set by hand in this tree),
or a route lost with the PDN, had no route. The start line prints that target; a resume still follows the
kernel's SA peer and now says whether that peer is in today's list. With
neither variable and nothing to resume, the fatal names both.
Tested: crafter-build test, 8 passed; the configured, discovered, differing (the
discovered list's order flipped: the resume stays on the SA peer, the next
fresh registration's target is the other address) and empty arms in builds
of this series on the dev phone (KPN).
2026-10-11 16:09:45 +02:00
std : : string freshPcscf = FreshPcscfFromEnv ( ) ;
Log ( std : : format ( " LOCAL={} P-CSCF=[{}]:{} " , local , freshPcscf . empty ( ) ? " (none) " : freshPcscf , EnvOr ( " PCSCF_PORT " , " 5060 " ) ) ) ;
packaging, ims-pdn-up, imsd, README: imsd runs without /etc/imsd.env and idles without a SIM
With the P-CSCF coming from the PDN's PCO, the configuration file has no
required line left, so the apk's ConditionPathExists=/etc/imsd.env drop-in
goes: the unit starts on every phone with the package, and VoLTE is on by
default. Installing the package and inserting a SIM is the opt-in; the file
holds overrides only, and its existence changes nothing. By the versioning
rule (AGENTS §11, the first commit of this series) that is what moves the
major number: the release is 1.0.0, and §11 now records it. What used to be the
file's job — keeping a phone nobody configured out of a failing unit — is now
a rule on facts, the same for every phone: a modem in the failed state with
a SIM reason makes the script write IMSD_IDLE=no-sim to /run/imsd.env and
exit 0; a profile-indexed connect series the network refuses ten times in a
row — each a persistent 3GPP cause in ModemManager's typed error (not
subscribed, unknown APN, barred, not authorised in the PLMN, authentication
failed, the service option not supported, the wrong PDN type) with packet
service at the time; counted only while the modem reads registered,
connecting or connected with packet service not detached — stricter than
the daemon's PacketServiceUp; any other read, a timeout or a transient cause
starts the count again — writes IMSD_IDLE=no-ims-pdn; and a bring-up that
ends with no P-CSCF — none configured, none discovered: no IPv6 P-CSCF read
from the PCO (PCSCF_DISCOVERY=none in the hand-off, the reader's exit 2: the
list absent, empty, unreadable or IPv4/FQDN only), discovery skipped (no
rmnet mux id) or no hand-off at all (a manual run) — and no registration of
imsd's own to resume is the daemon's own idle, decided before it takes the bus name (SaPeer and the
holds' old_gone say what can be resumed; a pair the holds wrote off is taken
out of the kernel there) and at the no-target bring-up, where a pair nothing
can resume is written off and taken out of the kernel first. imsd reads the key, logs idle: … and exits 0, which Restart=on-failure
leaves alone, so the unit stays inactive until the next boot, a systemctl
start or a start of imsd-ofonod where that runs (its Wants starts an idle
imsd again). What is not a fact keeps the retry: no coverage, a SIM still
waiting for its PIN, a modem without an ims profile (the APN-string connect
is tried), an APN-string series (the modem's own wall), a resumable pair
whose attempt failed (the fatal), and a P-CSCF reader that did not answer
(PCSCF_DISCOVERY=failed: the daemon exits 1 and the restart runs discovery
again). A phone that never had the file keeps its stopped unit through the
upgrade and starts at its next boot, registering where the rule above lets
it — at the upgrade itself where imsd-ofonod runs, whose restart pulls imsd
in through its Wants (systemd queues the marked unit's try-restart, collapses
it to a restart and starts what the unit Wants in the same transaction:
job_type_collapse, transaction_add_job_and_dependencies, 262~rc3); the
opt-out is systemctl mask --now imsd, since a plain disable is undone by
that Wants. imsd-ofonod.service loses its After=imsd.service: with imsd
starting on every phone, GNOME Calls' backend would otherwise wait behind
the ims PDN bring-up at every boot and at its marked restart at an upgrade,
for the whole bring-up (up to its TimeoutStartSec=900); it starts at once and republishes when imsd's name
appears (OnImsdAppeared).
The configuration file's path is the IMSD_ENV seam the mock bench uses.
AGENTS §6's lint figures are this tree's (109 findings in 16 of 20 files,
2026-10-13; the 72 of 2026-10-06 predate the Qmi files).
Tested: crafter-build test, 8 passed; on the host build the daemon's idle
exit for the script's keys and, with no pair, for every discovery verdict
but failed (none, skipped, no hand-off) — exit 0 — and the exit 1 for
failed; the script's arms on the mock bench; on the dev phone (KPN), in
builds of this series: the daemon's idle at the no-target bring-up with the
dead pair removed and before the bus name for a pair the holds had written
off, the discovery-failed exit 1 and its restart, the start without the file, the pull-in by an imsd-ofonod restart
and the mask holding against it and a reboot, and imsd-ofonod starting at
once with imsd stopped and republishing when imsd's name appeared.
2026-10-11 16:20:07 +02:00
// The daemon's own dead end, decided here, before the bus name, so the
// exit is clean and the unit stays inactive (§7.3): nothing to register
// to — no PCSCF=, nothing discovered — and no registration of its own to
// resume (SaPeer finds no pair, or the holds' write-off for this PDN and
// boot says it cannot). The script decides the dead ends only it can see
// (no SIM, a refused ims PDN). A discovery that failed is no dead end:
// exit 1, and the unit's restart runs it again.
if ( ! session & & freshPcscf . empty ( ) ) {
auto policy = RunCapture ( { " ip " , " xfrm " , " policy " } ) ;
auto holds = LoadHolds ( local ) ;
auto peer = imsd : : ipsec : : SaPeer ( policy . out ) ;
const bool writtenOff = holds & & holds - > oldGone ;
if ( ! peer | | writtenOff ) {
// a pair the holds wrote off before this start is nothing to
// resume: taken out of the kernel here, as the no-target bring-up
// takes a dead pair out (§7.2 step 1), so no start of this boot
// finds it — the holds keep the write-off
if ( peer & & writtenOff ) RemoveDeadPair ( local ) ;
if ( DiscoveryFailed ( ) ) { Log ( std : : format ( " {} — exiting for systemd restart " , NoPcscfDiscoveryFailed ) ) ; return 1 ; }
Log ( std : : format ( " idle: {} — nothing to do; systemctl start imsd when that changes " , NoPcscfIdleText ) ) ; return 0 ;
}
}
imsd, media: aim call audio at logind's seat0 session, not an account named `user`
imsd-media defaulted AUDIO_USER to `user`, postmarketOS's default
account name, and with no such account a call had no audio on the phone
and noise at the far end, the message only in imsd-media's stderr, at
each call. A field user found it by trial (alyx report 14, 2026-09-20;
ims ledger F14).
Have imsd, as packaged (root, on the system bus), resolve the session
from logind when a call's media starts — the user session active on
seat0 (a greeter is not one) when it has a PipeWire socket — and hand it
to imsd-media as AUDIO_USER; set in imsd's own environment to an
account's name, AUDIO_USER pins that account instead. imsd as packaged
(root, on the system bus) logs the resolution at start, before the first
call, and when a call's media starts.
No session is an empty AUDIO_USER. imsd-media started without the
variable at all keeps `user`: that is an imsd older than 0.3.10, still
running while an upgrade replaces the helper under it, whose calls would
otherwise be silent until the restart, or a hand run.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-09-25 17:15:02 +02:00
if ( ! session ) LogAudioSession ( ) ;
imsd, imsd-ofonod: let polkit decide call control, not the account name
The system-bus policies granted net.catcrafts.IMS1 and org.ofono to root
and to the account `user`, postmarketOS's default name, so on a unit
whose account is called something else dbus denied every Dial from the
dialer — nothing in imsd's journal, nothing on screen. A field user
found it by trial (alyx report 14, 2026-09-20; ims ledger F14).
Let any local account reach both names and have the daemons decide:
placing, answering or ending a call needs polkit's
net.catcrafts.IMS1.Voice (the active local session; not an ssh login, an
inactive session or a system service account). imsd-ofonod asks about
its own callers, since its calls reach imsd as root. Reads such as the
status and the call list are not gated, and a refusal is logged with the
sender; a `--session` run, the development mode without root or polkit,
leaves the gate off. The check is ImsdBus, a small GLib module both
daemons link; the package depends on polkit.
An upgrade restarts both daemons (the previous commit), so the open
policy faces the old, ungated daemons only until the apk transaction
ends.
Tested on the dev phone (KPN) in builds of this series; not every path
has run there.
2026-10-03 20:44:58 +02:00
imsd : : bus : : AuthorizeCalls = ! session ;
2026-07-22 22:53:28 +02:00
Engine engine ;
engine . SetLocal ( local ) ;
engine . SetDevMode ( session ) ;
TheEngine = & engine ;
MainLoop = g_main_loop_new ( nullptr , FALSE ) ;
guint owner = g_bus_own_name (
session ? G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM , BusName ,
G_BUS_NAME_OWNER_FLAGS_NONE , OnBusAcquired ,
[ ] ( GDBusConnection * , const gchar * name , gpointer ) { Log ( std : : format ( " owning {} " , name ) ) ; } ,
[ ] ( GDBusConnection * , const gchar * name , gpointer lp ) {
Log ( std : : format ( " lost {} — exiting " , name ) ) ;
g_main_loop_quit ( static_cast < GMainLoop * > ( lp ) ) ;
} ,
MainLoop , nullptr ) ;
g_unix_signal_add ( SIGTERM , OnTerm , MainLoop ) ;
g_unix_signal_add ( SIGINT , OnTerm , MainLoop ) ;
// Run the engine on a pthread with an explicit 8 MiB stack: musl's default
// thread stack is only 128 KiB, and the registration paths hold 64 KiB SIP
// recv buffers on the stack (a std::thread here segfaults on entry). The
// registration is bus-independent, so start it immediately.
pthread_t engineTid { } ;
pthread_attr_t attr ;
pthread_attr_init ( & attr ) ;
pthread_attr_setstacksize ( & attr , 8 * 1024 * 1024 ) ;
pthread_create ( & engineTid , & attr , [ ] ( void * ) - > void * { TheEngine - > Run ( ) ; return nullptr ; } , nullptr ) ;
pthread_attr_destroy ( & attr ) ;
Log ( std : : format ( " starting on the {} bus " , session ? " session " : " system " ) ) ;
g_main_loop_run ( MainLoop ) ;
engine . Stop ( ) ;
pthread_join ( engineTid , nullptr ) ;
g_bus_unown_name ( owner ) ;
g_main_loop_unref ( MainLoop ) ;
sip: UDP for the protected leg, TCP first with a fallback
imsd's protected leg (the second REGISTER and everything after it) was
TCP only. A P-CSCF that never answers the TCP connect on its protected
server port (O2 UK: the SYNs leave ESP-protected, nothing comes back)
left the unit looping with no way forward, although the SAs, the
listener sockets and the firewall rule already covered UDP.
The client flow now carries a transport. UDP binds the same protected
client port and connect()s the datagram socket to the P-CSCF's protected
server port, so the kernel delivers that peer's datagrams to it ahead of
the unconnected listener on the same port. One datagram is one message
(RFC 3261 18.3: a Content-Length that fits truncates, one that does not
fit discards the datagram, none means the rest of the datagram); a
receive error is logged and marks the flow dead; a message over the
single-packet ESP budget at the ims PDN's MTU is logged once per flow,
since the kernel fragments it and a P-CSCF may drop the fragments.
Every protected request's Via follows the transport; the challenge
stays UDP.
SIP_TRANSPORT selects the policy: auto (default) registers over TCP and,
after two unanswered connects, registers again over UDP (new challenge,
new SA pair) - but only on a phone whose state file does not record a
successful TCP registration, so an outage on a TCP carrier never becomes
a second initial REGISTER; a phone whose last registration was UDP goes
straight to UDP. tcp and udp force one. A connect refused locally
(EADDRNOTAVAIL: the 4-tuple still in TIME_WAIT from the previous flow)
keeps retrying and is not counted as silence; SO_ERROR results are
logged by name. The registration's transport is persisted so a warm
resume reconnects the same way, and the resume gives up after two
silences.
Two things the change exposed and fixes: an engine-fatal event exited 0
("exiting for systemd restart" with Restart=on-failure never firing),
and a fresh registration refused with the P-CSCF's fresh-SA throttle
(Security-Server spi-s=0) must not be retried by a 120-s restart loop,
since every attempt re-arms the ~20-min window - it is now waited out
in-process, growing on repeats, with D-Bus commands still served. A
resume the network refuses falls through to a fresh registration. A
retransmitted 200 OK to our INVITE is ACKed again and no longer starts
a second media leg.
Verified on KPN: resume over TCP after a binary swap, MT and MO calls
with media both ways, the throttle deferral and its self-recovery, the
UDP client path up to KPN dropping the datagram. The UDP success path
is a field test; SIP retransmission timers over UDP are not in this
change.
2026-09-17 14:58:46 +02:00
return FatalExit ? 1 : 0 ;
2026-07-22 22:53:28 +02:00
}