Commit graph imsd/tests
Author SHA1 Message Date
1267fe1ada
sip: a header is found under its compact form, and with white space before the colon
RFC 3261 7.3.3 lets a sender write a header name in its one-letter form
at any time and has every implementation accept both forms. The text
layer matched the long name only, so to every reader a header sent in
compact form was absent: the TCP framer took no body length from `l:`
and read the body as the start of the next message, a response with
`i:` matched no transaction and a request no call, the finals imsd
builds left out a Via, From, To or Call-ID that came in compact form,
and a short message whose content type came as `c:` was answered 200
and logged instead of taken (issue #2).

MatchHeaderLine now takes a line under the name it is asked for or
under that name's compact form: the ten RFC 3261 defines, and `o` for
Event (RFC 6665) and `x` for Session-Expires (RFC 4028), the two
extension headers imsd reads that have one. Every reader goes through
it — Header, Headers, the framer, DatagramMessage — so no reader
changes for it. It also takes white space between the name and the
colon, which the same grammar allows (25.1's HCOLON; 7.3.1's
"Subject      :      lunch") and the matcher refused. A value folded
onto further lines is still read by its first line.

One reader is changed for the rows it is now handed. ViaResponsePort
gives the port the top Via names, to which the answer to a request that
came in a datagram on a server port goes (RFC 3261 18.2.2), and none
where that Via carries `rport` (RFC 3581): the answer then goes back to
the port the request came from. It took `rport` for present where
those five letters, in lower case, stood anywhere behind the row's
first semicolon. Parameter names are case-insensitive (7.3.1), and a
request whose top Via came as `v: …;RPORT`, a row 1.2.0 passed over,
would have been answered to the port that Via names, its `rport` not
seen. ViaResponsePort now reads the Via's parameters one by one, each
to the next semicolon outside a quoted string, and `rport` is one by
its name, in any case: not those letters in a value or in a longer
name. Read so, the last parameter of the top value would run on into
the next value where a row holds a list — `rport, SIP/2.0/UDP …` is no
`rport`, and 1.2.0's search of the letters found it —, so the top value
is cut from the row first, at the first comma outside a quoted string.
With that cut a lower value's `rport` no longer counts for the top
one's, as it did in 1.2.0 for a list on one line.

Tested by the suites: tests/Sip pins each of the twelve forms through
Header, in lower and in upper case, and through Headers, `l:` through
the framer and DatagramMessage, 7.3.1's four spellings of the colon, and
ViaResponsePort's reading of a Via row, `rport` by its name and of a
list on one line the top value alone; tests/Engine drives an incoming
call from an INVITE in compact form, an outgoing call from responses in
compact form and a delivered MESSAGE in compact form through the
reducers; tests/Messages builds BuildResponse, BuildResponse200 and
BuildInviteResponse for a request in compact form. On the workstation's
loopback (the fp6 journal's 2026-11-20-issues-2-5 capture, server-ports,
at this commit and at the one before) a request on a server port whose
Via row is a list on one line with `rport` on its lower value is
answered from the client-port socket, the way to the port its top value
names, where the commit before answered it from the socket it had come
on. On the dev phone the binary of this range's last commit answered a
MESSAGE the phone sent to its own protected server port from the
client-port socket where its Via row was such a list, and from the
socket it had come on where its one Via came as `v: …;RPORT` (the
capture's phone-form6, inject-bench.log).
2026-11-22 17:35:11 +01:00
ca825937bf
tests: the Sip suite's header names its sections, and its reginfo fixture takes a documentation address and the suites' instance id
The suite's header comment named five of its sections — header access,
the status line, the granted lifetime, the caller's identity and the
frame buffer — and left out six: ViaResponsePort, DatagramMessage,
RetryAfter and RefusalSummary, ResponseOf, RegInfoContactState,
HeaderUri and Body. Its reg-event fixture had a contact at
[2a03:db8::1], outside the documentation prefix 2001:db8::/32, and an
instance id built on a real phone model's type allocation code. The
header now names every section; the fixture has [2001:db8::1] and the
instance id that tests/Aka and tests/Messages use, 35999999-000000-1.
No check changes.
2026-11-22 17:35:11 +01:00
a63132deb8
tests: every suite returns 1 for a failure, not the count
Six suites ended in `return Failures;`. `crafter-build test` takes an
exit status of 77 for a skipped suite and then succeeds, and an exit
status keeps 8 bits: 77 failing checks read as a skip, 256 as a pass.
All nine now return 1 after any failure, as Engine, Sip and Sms did.

Tested with 77 failing checks added to Ipsec, to Messages and to Sdp
in turn (the fp6 journal's 2026-11-20-issues-2-5 capture, exit-status):
before, `crafter-build test` ended `8 passed, 1 skipped` with exit
status 0; now it ends `8 passed, 1 failed` with exit status 1.
2026-11-22 17:35:11 +01:00
e39f7e39d6
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-19 18:26:21 +01:00
04c615fc15
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-19 18:26:20 +01:00
910e2594a0
project, docs: the linter goes
The Catcrafts house-style rules (Crafter.LintRules) rode in project.cpp
as a dependency crafter-build cloned once and built on every load; the tree
never passed them (111 findings on the 1.1.0 tree, 156 on an early freeze
of this range (2e87e26), 100 of the 156 the shared naming rule's, each
for a variable whose name begins with a capital — the
fp6 journal's lint captures, lint-tip-2e87e26), CI never ran them,
and AGENTS.md kept a census nobody acted on. Out: the dependency, the
import and the five AddRules calls, the lint-disable comments in 25
files and on 4 lines, §4.2 and the census of §6 — now "Code style", the
three rules that were never the linter's; the cross-compiling section
becomes §4.2 and its six citations — §4.1's sysroot sentence, §9.1, the CI
workflow, the APKBUILD, build-package.sh, make-sysroot.sh — follow. Jorijn, 2026-10-17: "just
remove the linter, we are ignoring it anyway".
2026-11-19 16:43:16 +01:00
d0cfaf712d
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-11-19 16:43:16 +01:00
aa3c394041
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-11-19 16:43:16 +01:00
4de5f0be45
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-11-19 16:43:15 +01:00
0717c3008a
messages: the SIP MESSAGE of SMS over IP, +g.3gpp.smsip behind a context flag
TS 24.341 5.3.1.2 has a submission travel as a SIP MESSAGE to the
service centre's PSI with the RP-DATA as an application/vnd.3gpp.sms
body, and 5.3.2.4 the delivery report as one to the IP-SM-GW with
In-Reply-To naming the delivered MESSAGE: BuildMessageSms builds both,
out of dialog over the registration's Route with the same
P-Preferred-Identity, P-Access-Network-Info and sec-agree headers as the
INVITE and the reg-event SUBSCRIBE, and no Contact (RFC 3428 4). The REGISTER Contact carries +g.3gpp.smsip only
when Context::smsOverIp says so — the tag routes terminating short
messages to imsd (the 2026-10-17 bench's mt-last-message-in.raw), which
at this commit still answers them 200 and logs them — after the ICSI.
BuildResponse builds a final for an inbound request outside a call (the
488 of 5.3.1.2 for a report that is not ours, or a 200); the shell does
not call it in this commit — it still answers a MESSAGE with
BuildResponse200.

tests/Messages pins the Contact with the tag, the MESSAGE's headers and
body bytes both ways, the absence of Contact, and the 488.

BuildResponse echoes each Via: line and the To, with a tag added unless
the To already holds `tag=` (RFC 3261 8.2.6.2 has a UAS add a tag to a
To that carries none); tests/Messages pins the 488 and a 200.

ScPsi gives the service centre's PSI from its international number
(5.3.1.2 NOTE 1: the SC's E.164 number as a SIP URI with user=phone, or
a tel URI; the home domain is imsd's choice); RuriFor's dialled-number guess, whose trunk 0 is Dutch, has no
place there. Pinned in tests/Messages.
2026-11-19 16:43:15 +01:00
89048c3602
sip: a header is read from the header section only
Header and Headers iterated every line of a message, body included, so a
body line that spells a header name — a text someone typed, or the UCS-2
bytes of one — would be read as that header: a second Via for a final to
echo, a P-Asserted-Identity that CallerId takes for the sender. ForEachLine now ends
at the first empty line after a line of text (RFC 3261 7: the headers
end at the empty line) and skips empty lines before it (a keepalive's
CRLFs ahead of a message), so every reader of a header reads the header
section. Pinned in tests/Sip:
a body Via is no Via, a name that occurs only in the body is absent,
leading CRLFs are skipped. With these the suite has more than 77 checks,
so it returns 1 for any failure and no longer their count: `crafter-build
test` takes an exit status of 77 for a skipped suite.
2026-11-19 16:43:15 +01:00
c88de31a0a
sms: the short message codecs of TS 23.038, 23.040 and 24.011, and EF_SMSP
SMS over IP (TS 24.341) carries the bytes a 2G/3G phone puts in an
RP-DATA inside a SIP MESSAGE body of type application/vnd.3gpp.sms, so
imsd needs the whole stack below SIP once it owns SMS on a carrier whose
modem IMS is off: the GSM 7-bit default alphabet with its extension table
and the septet packing, UCS-2 for everything else (TS 23.038); SMS-SUBMIT
built per segment with the concatenation header, SMS-DELIVER,
SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed, the SMS-DELIVER-REPORT
that acknowledges a delivery, the user-data header and the reassembly of
a concatenated message (TS 23.040); RP-DATA, RP-ACK and RP-ERROR in both
directions with their causes (TS 24.011); and EF_SMSP, where the (U)SIM
names the service centre the RP-DATA is addressed to (TS 31.102 4.2.27,
the KPN SIM's record read on the dev phone on 2026-10-16: +31653131313).

A new partition, Imsd:Sms, pure std with no SIP, clock or I/O; tests/Sms
checks it against the classic
public PDU vectors ("hellohello", the "How are you?" SMS-DELIVER) and
vectors cross-generated by an independent Python reference.

A concatenated set with one alphabet throughout is decoded from its
segments' joined units — the septets, or the UTF-16BE octets — not from
the segments' texts, so a surrogate pair or an escape pair a sender cut
at a segment boundary comes out whole; a U+0000 in UCS-2 decodes as
U+FFFD, since no text means it and a D-Bus string cannot carry it.

A status report's TP-ST is read as TS 23.040 9.2.3.15 has the MS read it:
a reserved value, any with bit 7 set among them, as "Service Rejected" —
a temporary error after which the SC is not making any more transfer
attempts (StatusAsRead, pinned over all 256 values; StatusText has the
clause's four classes in words). Three more readings follow their
clauses the same way, each pinned: a time stamp semi-octet that is no
digit reads as 0 (9.2.3.11); `1111` before an address's last semi-octet
is skipped, not taken for its end (9.1.2.3); an SMS-SUBMIT-REPORT for
RP-ERROR with an unused bit of its first octet set gives TP-FCS 0xFF,
unspecified, with nothing else examined (9.2.2.2a).
2026-11-19 16:43:15 +01:00
e31887bf21
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-16 22:25:49 +02:00
92fba40da0
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-16 22:25:49 +02:00
a89ca5a60c
qmi, imsd-pcscf: read the ims PDN's P-CSCF list from the modem's runtime settings
The network hands the P-CSCF addresses to the modem in the PDN's Protocol
Configuration Options; ModemManager's bearer code does not ask the modem
for them, qmicli (libqmi 1.39) prints none of them, and libqmi has no TLV
for the IPv6 list (0x2E), which is why PCSCF= was a required setting. A
second QMI WDS client reads them once it is bound to the bearer's mux
data port (the binding ModemManager gives its own clients): Bind Mux
Data Port, Set IP Family 6, Get Current Settings, over one AF_QIPCRTR
socket. Imsd:Qmi holds the bytes and the readers (0x22 the flag, 0x23
IPv4, 0x24 FQDN, 0x2E IPv6 in Qualcomm's layout: a count, then 16 bytes
each); imsd-pcscf is the socket, the service lookup and the sequence, and
prints the list, one address per line; nothing runs it yet. It sends
no Start Network and no Stop Network; the bearer stayed connected and the
registration stood after its runs (the fp6 journal's probe capture 04,
benches 38 and 39). The
build, the CI cross-compile, the tarball and the apk gain the product;
linux-headers is named in the sysroot for <linux/qrtr.h>.

Tested: crafter-build test, 8 passed; the aarch64 build of this commit's
helper on the dev phone (KPN) against the live ims bearer.
2026-10-13 22:28:02 +02:00
40a960f749
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-13 22:28:02 +02:00
21cb0f870d
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
b60a3633c1
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-13 22:28:02 +02:00
146d4368d0
util: canonical IPv6 text (RFC 5952 §4) and an address-list parser
imsd compares addresses as text against `ip xfrm` output, which prints
RFC 5952 form, while PCSCF= and LOCAL= arrive in whatever spelling the
user typed. CanonicalIp6 produces the §4 form from an IPv6 literal
(brackets accepted; a zone, a port, a dotted-quad tail, a name or an IPv4
address are refused; an IPv4-mapped address spelled in hex comes back in
hex, where inet_ntop writes it dotted), CanonicalAddr applies it to IPv6 only, and
ParseAddressList turns a comma-separated list into canonical,
deduplicated IPv6 literals in order, keeping the entries CanonicalIp6
accepts and naming every entry it refuses — an IPv4 address, a name, an
IPv6 literal with a zone or a dotted-quad tail — to a caller who asks for
them (duplicates and blanks are dropped
silently). Pure std, so the partitions stay free of inet_pton; nothing calls them yet.

Tested: crafter-build test, 7 passed.
2026-10-13 22:28:02 +02:00
729ccaa01d
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-11 02:56:47 +02:00
799fd1a802
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:43:07 +02:00
a00b14a5a9
engine: a refused refresh with a Retry-After escalates to a fresh registration at once
RegRecovery retried a refused refresh once over the same registration
before escalating, on the reading that one 503 may be a hiccup. A
refusal whose Retry-After is at least a second is the network's
considered answer: on O2 UK (2026-10-08, imsd 0.3.10) the keepalive was
refused 503 with Retry-After 414 and the refresh after that wait 503
with Retry-After 772, so 0.3.10 scheduled the fresh registration no
earlier than 414 + 772 s after the keepalive's refusal. Refusals
without such a Retry-After (none, 0, unparsable) keep the two-refusal
rule, so KPN's bare 403 is unchanged.

Tested with the Engine suite, whose checks of a refusal carrying a
Retry-After now expect the fresh step.
2026-10-10 21:00:28 +02:00
7eb2deae0c
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-10-06 14:01:33 +02:00
db848c6490
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-06 14:01:33 +02:00
142adf057c
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-10-06 14:01:33 +02:00
46bf363915
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-10-06 14:01:33 +02:00
52736295a1
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
5c89dcb033
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 16:22:22 +02:00
7978b94502 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
c5cba2e7ff tests: dial a documentation-style number in the CODECS offer scenario 2026-09-08 19:51:24 +02:00
37ec8660b7 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
d5aaf57e49 sdp: offer AMR narrowband after AMR-WB
Our offer listed AMR-WB alone. A call we place TO a landline then depends
on the far side transcoding up to wideband; a gateway that will not is
entitled to refuse. AMR narrowband is the 3GPP-mandatory codec every IMS
core and PSTN gateway can answer, so it goes second, with telephone-event
at the 8 kHz clock beside the existing 16 kHz one. AMR-WB stays first, so
a mobile-to-mobile call negotiates exactly what it did before; if the
network does answer AMR, the engine already starts the media leg on the
answered codec.

Byte pins in tests/Sdp and tests/Messages re-pinned (INVITE body 323 ->
466 bytes).

NOTE FOR RELEASE: this changes the MO INVITE on the path the arranged 112
calls used. One bench MO call on KPN before it ships.
2026-09-02 03:21:06 +02:00
daaba2d657 engine/sdp: accept AMR-NB and G.711 offers; name the offered codecs on 488
An incoming INVITE whose offer carried no AMR-WB was refused with 488
before ringing. A landline caller arrives through the PSTN gateway, which
offers narrowband — AMR (NB) and/or G.711 — so every landline call was
refused, deterministically. Field report 2026-09-01 (Telia Norge): a
doctor's office called twice, both 488; a mobile caller rang fine.

The parser now recognises PCMA/PCMU by rtpmap name or by static payload
type (a G.711 offer may carry no rtpmap line at all, RFC 3551 §6), matches
encoding names case-insensitively (RFC 4566 §6), and prefers
AMR-WB > AMR > PCMA > PCMU with octet-aligned first within AMR — a mobile
caller offering everything still lands on AMR-WB. The engine accepts any
codec the media leg plays and answers at the offer's own payload type with
the DTMF clock matching the codec (8 kHz for narrowband). A refused offer
now logs what WAS offered ('offered: 18 G729, 101 TELEPHONE-EVENT'), so a
field journal answers 'which codec did the gateway want' without a raw SIP
dump.

The media leg gains the matching codecs in the next commit.
2026-09-02 03:11:11 +02:00
f2a404855f 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-03 09:27:03 +02:00
6e77823933 imsd 0.2.7 — initial public snapshot
Userspace VoLTE/IMS daemon for mainline Linux phones (developed on the
Fairphone 6): a GLib-free core (SIP, SDP, USIM AKA, IPsec SA setup, RTP
media, call engine) behind a GDBus control daemon, a standalone AMR-WB
media leg, and a Plasma Dialer backend. C++26 modules built with Crafter
Build; the tree is clean under the project's house-style linter
(crafter-build lint) across all three build products.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Jorijn van der Graaf <jorijnvdgraaf@catcrafts.net>
2026-07-22 23:04:21 +02:00