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).
This commit is contained in:
Jorijn van der Graaf 2026-10-16 23:30:25 +02:00
commit aa3c394041
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
11 changed files with 1269 additions and 78 deletions

3
.gitignore vendored
View file

@ -9,3 +9,6 @@ imsd-*.tar.gz
*.rtp
*.stats
imsreg.state
# SMS over IP's state: the next TP-MR (and its .tmp)
sms-tpmr*

475
AGENTS.md
View file

@ -18,7 +18,9 @@ firmware on such phones brings up the IMS PDN but cannot carry call audio, so
imsd does the whole IMS client itself: SIP registration with USIM AKA
authentication over kernel IPsec (ESP), call signalling for outgoing and
incoming calls, and the RTP media plane (AMR-WB, AMR, G.711) wired into
PipeWire. A stock mobile dialer — Plasma Dialer, or GNOME Calls under Phosh
PipeWire, and since 1.2.0 short messages over IMS (TS 24.341: the SIP MESSAGE
carrying an RP-DATA, the Messaging interface —
§7.9). A stock mobile dialer — Plasma Dialer, or GNOME Calls under Phosh
and GNOME Mobile — places and receives real VoLTE calls on a commercial
network through it.
@ -44,10 +46,10 @@ PipeWire. The verified device/carrier combinations are in the README.
| `interfaces/Imsd-Sms.cppm` | `imsd::sms` — the short message codecs SMS over IP rides on (TS 24.341 carries the bytes a 2G/3G phone puts in an RP-DATA, in a SIP MESSAGE body): the GSM 7-bit default alphabet with its extension table and the septet packing, UCS-2 (TS 23.038); the SM-TL PDUs (TS 23.040: SMS-SUBMIT built, one per segment with the concatenation header when the text needs more than one; SMS-DELIVER, SMS-STATUS-REPORT and SMS-SUBMIT-REPORT parsed; the SMS-DELIVER-REPORT that acknowledges a delivery; the user-data header — concatenation, application ports — and the `Reassembler` of a concatenated message); the SM-RL messages (TS 24.011: RP-DATA, RP-ACK, RP-ERROR in both directions, the cause values); EF_SMSP (TS 31.102 §4.2.27), where the (U)SIM names the service centre, and qmicli's hex dump of it. Byte-level only: no SIP, no clock, no I/O. |
| `interfaces/Imsd-Aka.cppm` | `imsd::aka` — USIM AKA glue: the AKAv1-MD5 digest (RFC 3310), IMPI/IMPU/realm from IMSI + MCC/MNC, parsers for `qmicli --uim-get-card-status` and `mmcli` output, the AUTHENTICATE APDU and its response. |
| `interfaces/Imsd-Ipsec.cppm` | `imsd::ipsec` — the two ESP SA pairs (TS 33.203) as `ip xfrm` argv lists, the Security-Server mechanism selection, and the reader that reconstructs SPIs/ports from `ip xfrm state`/`policy` text for a warm resume, and (1.0.0) `SaPeer`, the P-CSCF the kernel's pair is to, read from the `dir out` policies that carry imsd's fingerprint, `OwnXfrmDeleteCommands`, the deletes by exact key of what two rules select — the policies carrying imsd's fingerprint and the reqid-1/2 transport-mode ESP states in their direction or on the UE's ims-PDN address, whoever installed them (§12), and `FileNamesAnotherPair`, whether a state file's `spi_uc`/`spi_us` name the kernel's pair (unknown on either side decides nothing). |
| `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; `tests/Messages` is their suite, which calls every builder but `BuildInviteResponse` (`tests/Engine` checks the responses `CallMachine` builds with it). Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final `OnSmsMessage` builds for the MESSAGE it is handed (the 200, the 488): each `Via:` line echoed in order (the text layer reads long header names only, not RFC 3261 7.3.3's compact forms) and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. |
| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (TS 24.341): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (the final remembered for an inbound request by Call-ID, CSeq and Via branch — the value of the first `branch=` of its first `Via:` line; nothing is remembered for a request with none or an empty one — for 32 s (`TimerJ`), for a caller to answer a retransmission with it and not handle it again). |
| `interfaces/Imsd-Messages.cppm` | `imsd::msg` — every SIP request and response imsd sends, built from an explicit `Context` and per-request variables so the builders are pure functions; `tests/Messages` is their suite, which calls every builder but `BuildInviteResponse` (`tests/Engine` checks the responses `CallMachine` builds with it). Also `IsEmergency`. Since 1.2.0 the SIP MESSAGE of SMS over IP (`BuildMessageSms`: an RP-DATA to the service centre's PSI, or an RP-ACK/RP-ERROR to the IP-SM-GW with In-Reply-To — TS 24.341 5.3.1.2 and 5.3.2.4), the `+g.3gpp.smsip` Contact tag behind `Context::smsOverIp`, `BuildResponse`, the final for an inbound MESSAGE outside a call's dialog (the 200, the 480, the 488): each `Via:` line echoed in order (the text layer reads long header names only, not RFC 3261 7.3.3's compact forms) and the To echoed with a tag added unless it already holds `tag=` (RFC 3261 8.2.6.2); in-dialog requests, a MESSAGE among them, and the shell's answers to any other request outside a call — a NOTIFY, an OPTIONS, a method it does not handle; not an INVITE, whose 486 while a call exists is `BuildInviteResponse`'s — keep `BuildResponse200`'s hop-by-hop shape; and `ScPsi`, the service centre's PSI from its international number — never a dialled-number guess. |
| `interfaces/Imsd-Engine.cppm` | `imsd::engine` — the decisions as pure reducers: `CallMachine` (one call's dialog, returning `Action`s for the shell), `RegRecovery` (the registration recovery policy, §7.4) and, since 1.2.0, SMS over IP (TS 24.341): `SmsOutbound` (one short message of ours on its way to the service centre, segment by segment, returning `SmsAction`s) and `OnSmsMessage` (what an inbound MESSAGE outside a call's dialog leads to: its final, the message or status report it delivered, the delivery report to send), and `RecentTransactions` (an inbound request's retransmission — the same Call-ID, CSeq and Via branch within 32 s (`TimerJ`), the branch being the value of the first `branch=` of its first `Via:` line and a request with none or an empty one never matched — answered with the same final and not handled again); `SameRecipient` and `StatusReportBook`, a status report's match to the message that asked for one — TP-MR and recipient — and its word for the whole message, with `SmsWordOrder`, the order of a message's words: the submission's first, a report's held until then (§7.9); `RunToken`, `SentSmsId` and `ReceivedSmsId`, the ids (§8.4). |
| `interfaces/Imsd-Qmi.cppm` | `imsd::qmi` — the QMI WDS request bytes `imsd-pcscf` sends (Bind Mux Data Port, Set IP Family, Get Packet Service Status, Get Current Settings, Get Profile Settings), the message/TLV parser, the P-CSCF list readers (0x22 flag, 0x23 IPv4, 0x24 FQDN, 0x2E IPv6 — the last one libqmi does not model). |
| `interfaces/ImsdBus.cppm` | `imsd::bus` — the polkit gate in front of call control, shared by imsd and imsd-ofonod. GLib, so outside `imsd-core`. |
| `interfaces/ImsdBus.cppm` | `imsd::bus` — the polkit gate in front of call control and messaging (`Gated`'s `Action` parameter names the action), shared by imsd and imsd-ofonod. GLib, so outside `imsd-core`. |
| `implementations/main.cpp` | The `imsd` daemon shell: GLib main loop, GDBus service, sockets, subprocesses, the registration sequence and the run loop that pumps the core. |
| `implementations/media.cpp` | `imsd-media`, the per-call RTP leg, DTMF included (RFC 4733 events out, queued by `dtmf <tones>` lines on its stdin; the far end's events in, played as tones). Pure std + POSIX, dlopen's the AMR codecs. |
| `implementations/pcscf.cpp` | `imsd-pcscf`, the P-CSCF reader: the AF_QIPCRTR socket, the WDS service lookup and the Bind Mux Data Port / Set IP Family / Get Current Settings sequence around `Imsd:Qmi` (plus Get Profile Settings with `--profile`, Get Packet Service Status with `-v`). std + POSIX + the Linux QRTR UAPI (`<linux/qrtr.h>`), no GLib; never Start/Stop Network. |
@ -60,7 +62,8 @@ PipeWire. The verified device/carrier combinations are in the README.
Also ignored by `.gitignore`, and never to be committed: `*.raw`, `*.rtp`,
`*.stats`, `imsreg.state`, `imsd-*.tar.gz` — captures and runtime state carry
the subscriber's IMSI/MSISDN and network addresses.
the subscriber's IMSI/MSISDN and network addresses — and, of SMS over IP's
state, `sms-tpmr*` (the next TP-MR).
## 3. Build products
@ -71,7 +74,7 @@ in every source but the re-exporting `Imsd.cppm`, clang + libc++ + lld.
|---|---|---|---|---|
| `imsd-core` | static library | the `Imsd` module and its nine partitions | — | Pure `import std` C++, no GLib, no I/O side effects: every message, digest, SA command and call-state decision is here and unit-testable on any dev box without a bus, a modem or a phone. |
| `imsd` | executable | `implementations/main.cpp` | `imsd-core`, `imsd-bus`, gio-2.0, pthread | The daemon. Default product. |
| `imsd-bus` | static library | `interfaces/ImsdBus.cppm` | gio-2.0 | The polkit gate (`net.catcrafts.IMS1.Voice`) imsd and imsd-ofonod both link. A translation daemon that runs as root on the system bus reaches imsd as root, which polkit always allows, so it gates its own callers through this or it is a bypass. |
| `imsd-bus` | static library | `interfaces/ImsdBus.cppm` | gio-2.0 | The polkit gate (`net.catcrafts.IMS1.Voice`; since 1.2.0 `net.catcrafts.IMS1.Messaging` too) imsd and imsd-ofonod both link. A translation daemon that runs as root on the system bus reaches imsd as root, which polkit always allows, so it gates its own callers through this or it is a bypass. |
| `imsd-media` | executable | `implementations/media.cpp` | `-ldl -lpthread` | The RTP/AMR data plane, spawned once per call. No GLib, no core. A separate process for crash isolation and for the far-end-hangup exit-code contract (§7.6). `-- --product=media`. |
| `imsd-dialerd` | executable | `implementations/dialerd.cpp` | gio-2.0 | Plasma Mobile integration: a session daemon owning `org.kde.telephony.{CallUtils,DeviceUtils,UssdUtils}`, bridging to imsd. GDBus translation only. A separate process because those are per-user session-bus names a root system daemon cannot own. `-- --product=dialerd`. |
| `imsd-ofonod` | executable | `implementations/ofonod.cpp` | `imsd-bus`, gio-2.0 | GNOME Calls integration: a system daemon owning `org.ofono`, presenting imsd as an oFono modem. GDBus translation plus the polkit gate on its own callers. `-- --product=ofonod`. |
@ -82,7 +85,7 @@ that every decision in it has a unit test.** New protocol logic goes into a
partition with a test. The shell (`main.cpp`; from 1.0.0 also `pcscf.cpp`'s
QRTR control lookup and its matching of answers by type, transaction and
message id) holds protocol decisions no
test reaches — some older than 0.3.10, some added by 0.3.10, 0.3.11, 0.3.12 or 1.0.0: the P-CSCF in
test reaches — some older than 0.3.10, some added by a release since: the P-CSCF in
use (`pcscf_`: the kernel's SA peer at a resume, `PCSCF=` or the first of
`PCSCF_DISCOVERED=` at a fresh registration, the move between them and back —
§7.2); the reg-event
@ -135,7 +138,27 @@ both sides (1.0.0) is unbenched: no capture stages a holds file whose `pdn` is
spelled unlike `LOCAL`). For the schedule, a reducer next to
`RegRecovery`, with a Subscription-State parser in `Imsd:Sip` pinned by
`tests/Sip`, is the follow-up that moves it; a pure format/parse pair in
`Imsd:Engine` is the holds file's.
`Imsd:Engine` is the holds file's. SMS over IP (1.2.0, §7.9) keeps in the
shell, among others, the service centre's source (`SMSC=` over EF_SMSP, `LoadSmsParameters`),
the three counters (TP-MR, RP-MR, the concatenation reference), their
seeding and the TP-MR file, the routing of an inbound MESSAGE
(`DispatchRequest`: to the call when it carries the live call's Call-ID,
else through `OnInboundMessage` to `OnSmsMessage`), the one-at-a-time
queue, a `Send` failed when the engine takes it up unregistered or with
the flow down, a queued message started without that check, the
status-report book's entries (made at a message's start, and only for one
that asked for a report: `StartNextSms`), the routing of a MESSAGE
final to the message in flight (`OnSmsResponse` — ahead of the reg-event
subscription's handler in the run loop, after it inside `AwaitFinal`), the
judgement of the final's wait and of the report's after the server ports' drain, the reassembler's
30-minute age-out in the run loop, the retransmission check around
`OnSmsMessage`, the delivery reports' finals (`reportCallIds_`), a send
failure attributed by Call-ID, and the forwarding of a status report's
word to the bus — the transactions themselves are `SmsOutbound` and
`OnSmsMessage` (a submit report's routing to the message in flight, by
In-Reply-To, else RP-MR, is theirs), and the report's match to the message
that asked for one `SameRecipient`
and `StatusReportBook`, all with tests.
## 4. Building
@ -341,12 +364,30 @@ What the suites pin:
ended; ours once its segment was superseded), 200 for one without
In-Reply-To for no message, an unusable TPDU acknowledged with an
RP-ERROR, a body that is no RP message, a page-mode text 200'd and
logged;
logged, a short message while SMS over IP is off refused with 480;
a submit report before the MESSAGE's own final taken — the message sent
and the late final nobody's; with two segments the second goes out under
its own Call-ID — a text past 255 segments failed at once naming the fit,
a delivery with no gateway for its report handed over with the absence
logged;
`StatusReportBook` and `SameRecipient`: a two-segment message delivered
with its last segment, a delivered TP-MR forgotten, another recipient no
match, a temporary status pending with the entry kept, a permanent
failure the message's last word (a later segment finds nothing), a
reused TP-MR forgetting the older message whole, a message forgotten
whole by its id (`ForgetMessage`) with the other left on record; a number dialled
with a trunk 0, with `00` or — a US number — without its country code
matched against its international form; another number, `+31612345678`
against `+49612345678`, a short code against a longer number that ends in
it and an empty one not;
`SmsWordOrder`: a report on a message whose submission ended posted at
once, one on the message in flight held and posted after `sent`, a
`failed` after a held `delivered` posted as `sent` then `delivered`, any
other `failed` posted alone with the message to forget, another
message's submission leaving the held word alone; the ids (`RunToken`,
`SentSmsId`, `ReceivedSmsId`): eight zero-padded hex digits, the sent
and the received shape, two tokens' ids apart at the same second and
counter;
and `RecentTransactions`: a retransmitted request gets its final again,
for 32 s (`TimerJ`); no branch, no match.
@ -535,6 +576,84 @@ Rules:
clock stands), and an answer that renumbers telephone-event or gives the
audio our number (`DTMF_RX_PT` — KPN echoes our numbers; pinned in
`tests/Engine` and by the loopback's collision arm).
- SMS over IP (§7.9) ran on the dev phone on KPN on 2026-10-17 (the fp6
journal's `2026-10-17-sms-over-ip-bench` capture; §13 has the network
facts): the EF_SMSP read at bring-up and the
`+g.3gpp.smsip` tag on a resumed and on a fresh registration (echoed in
the reg-event reginfo); three `Send`s over `busctl` (one segment each:
MESSAGE → 202, the submit report → `sent`; the dump of the 00:53 one shows
a GSM 7-bit RP-DATA, its report's In-Reply-To naming our Call-ID); five
texts received at 01:17 (one segment each, GSM 7-bit:
parsed, the RP-ACK delivery report sent and answered 202); a sixth
(SC time stamp 01:23:10, logged at 01:23:12) that arrived twice within a second
(`journal-0123-duplicate`; the dump that survives,
`mt-0123-duplicate-message-in`, came over UDP from the P-CSCF) and was
handled twice, two delivery reports, one of them refused 488, which is where the retransmission
absorption (`RecentTransactions`) came from; a
240-character text (01:33) sent as two segments (consecutive
RP-MR/TP-MR, both 202 + RP-ACK) and received back (01:40) as two
segments (set 174, 159 + 102 bytes) reassembled (SC time stamp 01:40:26, the whole logged at 01:40:28: 240 bytes of
text in 2 segments, `journal-0133-mo-benches-and-0140-mt-concat`); a UCS-2
text with ü and ß, ❤, an emoji (surrogate pair) and Ω sent
(35 units, TP-UDL 70) and received back decoded (DCS 08) — its trailing
✓ missing in the copy that came back (34 of its 35 units: the text sent,
`r22-sent-texts-2026-10-17-from-the-session-transcript`, against the
MESSAGE dump `mt-0140-last-segment-message-in`; origin open); sent on its
own, a one-character UCS-2 text arrived at 01:44 (3 bytes of text,
`journal-0144-checkmark-and-absorbed-retransmission`); that one-character text's MESSAGE
retransmitted (01:44:24) and absorbed: answered again, not handled again
— one delivery report, 202; a text from the alphanumeric
sender AUTHMSG at 01:47 (55 bytes, its report answered 202; the day's every
arrival and report: `r24-phone-journal-authmsg-status-reports-2306`); and a
text at 23:08 under a build whose 200, by the capture's heading, echoes
every Via and carries a To tag (`mt-2308-new-final-shape`): the
same-second retransmission was answered again and absorbed, the delivery
report answered 202. No capture of the benches on
hardware holds a journal line of one of these arms (each arm's line is searched in them in the
fp6 journal's `2026-11-19-imsd-1.2.0-r32-cut` capture, `searches/arms.out`): a refused final to a submission's MESSAGE, an RP-ERROR this
code sends (the cause-96 unusable-TPDU path; an RP-ERROR that came in was
reached: `smsc-override-2026-10-18-0217`, 02:19:41, RP cause 28 + TP-FCS
0xc1, through `OnReport`), the final's wait and the report's
running out, a dead flow under a `Send`, a status report (one requested
at 01:33 with TP-SRR; none came in the following 11 minutes — the
unfiltered journal of 01:33:30–01:45:00,
`r23-phone-journal-2026-10-17-precise-and-modem-sms`; whether KPN's SC
sends them over this path is unknown), 8-bit data (an MMS
notification), a message while SMS over IP is off (the 480), a submit
report In-Reply-To no MESSAGE of ours in flight (the 488) or one without
In-Reply-To for no message in flight (the 200), a page-mode MESSAGE, a
body that is no RP message, a delivery that names no gateway, a text
past 255 segments, an EF_SMSP
record 1 that cannot be read or holds no service centre, or one whose
service centre is not an international number, a
delivery report the flow could not
send, a concatenated set aged out after its 30 min, a bus object or
interface that does not register (§7.8). Not searched for, as they write no journal line of their own: a submit report without
In-Reply-To taken by its RP-MR (the one dumped carries In-Reply-To) or one whose In-Reply-To
lists ours among several Call-IDs, a delivered MESSAGE whose
Call-ID holds an ASCII control character or a space, or whose P-Asserted-Identity lists several
identities in one row or begins with a quoted display name, a MESSAGE final arriving inside a REGISTER wait
(`AwaitFinal` → `OnSmsResponse`), a queued message started inside a REGISTER wait, a MESSAGE
inside a call's dialog, a stop with a message queued or in flight. The reducers for the arms of both sentences but the shell
paths — the final's routing inside `AwaitFinal`, the delivery report the
flow could not send, `LoadSmsParameters`' refusals, the MESSAGE
inside a call's dialog, the queue's two
and the bus object's registration — are pinned in
`tests/Engine` — but for EF_SMSP's parser and the reassembler's age-out (`Purge`, given an age), which `tests/Sms` pins, and `HeaderUri`'s reading of a header's value, which `tests/Sip` pins; the Messaging
interface's `Send`, `GetStatus`, `Subscribe` and `StateChanged` ran on
the host's session bus in dev mode (2026-10-16: two `Send`s answered
with ids and failed `imsd is not registered`; 2026-10-17: three
connections — a subscriber, a match-rule-only listener, an unsubscribed
sender — where only the subscriber and the sender heard the
`StateChanged`; 2026-11-19, on a private session bus with the setting
off: `enabled` false, `Send` refused with `NotSupported`, `Subscribe`
answered).
Reached from 2026-10-18 02:17 (`smsc-override-2026-10-18-0217`): the
`SMSC=` override — `SMSC=+31653131313` gives `service centre +31653131313
(SMSC=)` and a `Send` through it reaches `sent`; `SMSC=abc` gives
`SMSC='abc' is not a number` (`ForNumber` dials digits, `*` and `#` only;
the bench's first run, on a build outside this history that dialled a, b
and c, submitted with them and got an RP-ERROR back, RP cause 28).
- `imsd-pcscf` ran on the dev phone (KPN) on 2026-10-11 against the live ims
bearer: the `--mux 1 --profile 2 -v` sequence, a plain run, and `OutOfCall`
on an unbound mux (the fp6 journal's `2026-10-11-pcscf-pco-probe` capture,
@ -609,10 +728,14 @@ Beyond the rules:
`/net/catcrafts/IMS1`, interface `net.catcrafts.IMS1`; the frozen ABI, §8).
The bus policy `packaging/net.catcrafts.IMS1.conf` lets any local account
reach it; placing, answering and ending a call is polkit's
`net.catcrafts.IMS1.Voice` (`packaging/net.catcrafts.IMS1.policy`, shaped like
`net.catcrafts.IMS1.Voice`, sending a short message over IP and subscribing
to the message signals `net.catcrafts.IMS1.Messaging`
(`packaging/net.catcrafts.IMS1.policy`, both
shaped like
ModemManager's Voice action: the active local session and root — not an ssh
login, an inactive session or a system service account). Reads (`GetStatus`,
`GetCalls`) stay open, as ModemManager's are to every local account: the call
`GetCalls`, the Messaging interface's `GetStatus`) stay open, as
ModemManager's are to every local account: the call
signals reach them all anyway, the status (the address, the P-CSCF, the
phone number) travels in no signal.
@ -621,7 +744,8 @@ receive on the protected client flow, the protected-port listeners for
terminating requests, media reaping, the keepalive refresh); the GLib main
loop owns the bus. D-Bus method calls push commands to the engine queue;
engine events reach the bus through `g_idle_add`, where the calls table and
the status snapshot live (main thread only).
the status snapshot live (main thread only). The Messaging interface's
`Subscribe` keeps its subscriber set on the main thread as well (§7.9).
Per answered call imsd forks `imsd-media` (`IMSD_MEDIA`, default next to the
`imsd` binary, else `/usr/libexec/imsd-media`) with the addresses, ports and
@ -690,7 +814,9 @@ The daemon's own bring-up (`BringUp()` in `main.cpp`):
2. `qmicli -d qrtr://0 --uim-get-card-status` finds the ready USIM (slot, AID);
`mmcli -m any` gives the primary SIM path and the IMEI (for the
`+sip.instance` URN); `mmcli -i <sim>` gives IMSI and MCC/MNC, from which
the IMPI/IMPU/realm are derived. `mmcli --location-get` fills
the IMPI/IMPU/realm are derived; with SMS over IP on and `SMSC=` unset,
`qmicli --uim-read-record` of EF_SMSP record 1 names the service centre
(§7.9). `mmcli --location-get` fills
`P-Access-Network-Info`.
3. **Warm resume** when an SA pair is already in the kernel and the state
file (`STATE_FILE`, default `/var/lib/imsd/imsreg.state`) describes the
@ -1020,8 +1146,10 @@ When nothing is held the file is removed — when it is a regular file;
`/dev/null` switches the knob off and anything that is not a regular file is
emptied, never unlinked. The recovery policy's waits and the holds are
measured on the boot clock (`CLOCK_BOOTTIME`), so a suspend counts; the
keepalive refresh gate, the CRLF keepalive and the reg-event retry and
renewal timers run on the steady clock and count awake seconds only.
keepalive refresh gate, the CRLF keepalive, the reg-event retry and
renewal timers and the times SMS over IP measures (§7.9: its two waits,
the 30-minute age-out, the retransmission table's 32 s) run on the steady
clock and count awake seconds only.
The **reg-event subscription** (RFC 3680; the network's own view of the
binding) is one live dialog per registration, subscribed anew ahead of the
@ -1230,6 +1358,7 @@ account `user`, its old default.
| `/run/imsd-ofonod.started` | `imsd-ofono-restart-calls.sh` | marker: imsd-ofonod has started once since boot |
| `/var/lib/imsd/imsreg.state` (`STATE_FILE`) | imsd | the registration context for a warm resume |
| `/var/lib/imsd/*.stats`, `*.rtp`, `*.raw` | imsd, imsd-media | per-call media stats, raw RTP (`RTP_DUMP`), SIP dumps (`DUMP_SIP`; mode 0600 — they carry the IMSI/MSISDN) |
| `/var/lib/imsd/sms-tpmr` | imsd | the next TP-MR, one decimal number, written when a message's segments take their TP-MRs (§7.9) |
| `$XDG_STATE_HOME/imsd/` (else `~/.local/state/imsd/`), `$XDG_RUNTIME_DIR/imsd.holds` (else `/tmp/imsd.holds`) | imsd | the same files for a non-root (`--session`) run |
### 7.8 Journal vocabulary
@ -1326,7 +1455,62 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `:
Security-Verify rebuilt from the SA as one mechanism` at every resume.
- `connect: no answer from the P-CSCF N times (…)` when the protected
connect series ends unanswered.
- SMS over IP (§7.9): `SMS over IP: off (SMS_OVER_IMS=1 enables it)` at
start, or at bring-up `sms: service centre +… (EF_SMSP[ 'alpha'])[,
validity period 0xnn]` / `sms: service centre +… (SMSC=)` / `sms: no
service centre: EF_SMSP record 1 unreadable or without one; …` / `sms:
SMSC='…' is not a number; …` / `sms: SMSC='…' is not an international
number (+ and digits); …` / `sms: EF_SMSP's service centre '…' is not an
international number (+ and digits); …` and `SMS over IP: on (+g.3gpp.smsip
advertised: …)`; per message of ours `sms <id>: segment i/n to <number>
via <uri>: MESSAGE sent (RP-MR a, TP-MR b, N bytes)`, `sms <id>: segment
i/n -> <code>; awaiting the submit report`, then `sms <id>: sent: …` or
`sms <id>: failed: …` (the reason: `'…' is not a number`, `no service
centre …`, `the text does not fit 255 segments`, `imsd is not registered`, `the flow to the P-CSCF is down`,
`segment i/n refused: <status and its Retry-After / Warning / Reason / Server headers>`, `segment i/n refused
by the SC: RP cause N (…)[, TP-FCS 0xNN (…)]`, `no answer to the MESSAGE
of segment i/n within 32 s`, `no submit report for segment i/n within
40 s of the final`, `segment i/n not sent: the flow to the P-CSCF is
down`) and, after a status report, `sms <id>: delivered|delivery-pending|
delivery-failed: <TP-ST in words>` or `sms <id>: a segment delivered
(TP-MR n); k still to be reported`, and for a report's word on the
message still in flight `sms <id>: delivered|delivery-pending|
delivery-failed: <TP-ST in words> — held until the submission ends`; per delivery `short message from
<sender> via <sc> at <time>[, segment i/n of set r]: text|8-bit data (N
bytes)`, `sms ims-sms-in-<run>-<epoch>-<N>: from … via …, N bytes of text|8-bit data[ in
n segments]` once whole, `delivery report RP-ACK|RP-ERROR (RP-MR n) ->
<uri>` (its final and its failures: the bus and MESSAGE lines below) or,
for a MESSAGE that names no gateway, `no P-Asserted-Identity or From URI on
the delivered MESSAGE: no delivery report RP-ACK|RP-ERROR sent`;
`status report from <sc>: TP-MR n to <number>: … (discharged
<time>)`, `sms: status report for TP-MR n to <number>: no message of ours on record`;
`submit report (RP-ACK|RP-ERROR) In-Reply-To …: no MESSAGE of ours in flight; 488`,
`submit report (…, RP-MR n) for no message in flight; 200`; `RP-DATA from
… whose TPDU is unusable (…): RP-ERROR`; `MESSAGE from … (<content
type>, N bytes):` followed by the body for a MESSAGE outside a call's dialog whose `Content-Type`
does not contain `application/vnd.3gpp.sms`, letter case ignored
(`<content type>` its value in lower case, or `no content type`); `MESSAGE from … with N bytes that are no RP message: <hex>`.
- SMS over IP's bus and MESSAGE lines (§7.9): `sms: <name> subscribed (N
subscriber(s))` / `sms: <name> unsubscribed (its connection is gone; N
subscriber(s))`; `MESSAGE retransmitted (<Call-ID>|<CSeq>|<branch>):
answered again, not handled again`; `sms: a concatenated text from
<sender> (set <ref>, <held> of <total> segments held) dropped after 30 min:
the rest never came`; `short message over IP from <caller id>
(<n> bytes) while SMS_OVER_IMS is off: 480` — `<caller id>` the number or user a
P-Asserted-Identity of the MESSAGE gives, else its From's, empty when
neither gives one: who sent the MESSAGE, not who wrote the text, which is
not read while the setting is off; `sms: delivery report -> <code>` / `sms: delivery
report refused: <summary>` / `sms: delivery report not sent: the flow to
the P-CSCF is down`; `<Method> refused: <bus name> is not authorized for
net.catcrafts.IMS1.Messaging` / `<Method> refused: <bus name>: polkit did
not answer: …` for a gated call of the Messaging interface that polkit
does not grant (the frozen interface's gated calls give the same lines
with `net.catcrafts.IMS1.Voice`).
- The bus object at start: `introspection XML: <error>` when the interface
description does not parse (nothing is registered) and `<interface> not
registered at /net/catcrafts/IMS1: <error>` for an interface the bus
refuses; the daemon runs on without it.
- `idle: no SIM — nothing to do; systemctl start imsd when that changes`
(or `idle: no ims PDN from the network — …` from `IMSD_IDLE`; `idle: no
P-CSCF — none configured (PCSCF=), none discovered (see the ims-pdn-up
@ -1349,6 +1533,166 @@ Y` (the configured address or the first discovered), `wrote
/run/imsd.env: DEV=… LOCAL=… PCSCF_DISCOVERED=… PCSCF_DISCOVERY=…` —,
`imsd-handover: …`, `imsd-ofono-restart-calls: …`.
### 7.9 SMS over IP (TS 24.341)
Off unless `SMS_OVER_IMS=1`: with the modem's own IMS client off, a
network that gives the modem no SMS path leaves the phone none but imsd
(which networks
do so for which attach types is unmeasured), while on one whose modem
still delivers texts over NAS the 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 the release default leaves the NAS path alone. On, the REGISTER Contact
carries `+g.3gpp.smsip` (`Context::smsOverIp`, 5.3.2.2) and what the network
delivers over IP — terminating short messages, submit reports — comes as SIP MESSAGEs with
an `application/vnd.3gpp.sms` body — the RP message of TS 24.011 a 2G/3G
phone would see, with the TPDU of TS 23.040 inside (`Imsd:Sms`, §2); a
status report would come the same way (5.3.3.4.4); a search of the dev phone's
journal for imsd's status-report lines found none from 2026-10-16 to its reading on 2026-10-19
03:05 (`r24-phone-journal-authmsg-status-reports-2306`), a span in which at
least three submissions asked for one (TP-SRR: the three commands of
`r25-status-report-requests-from-the-session-transcript`). Off, `Send` is refused with `NotSupported`, and a short
message the network sends anyway outside a call's dialog is refused with 480 Temporarily Unavailable — a 200 and an RP-ACK would
count it delivered to nobody, a failure lets the
IP-SM-GW try the SGSN/MSC path, by operator policy (TS 24.341 5.3.3.4.2
NOTE 2) — where the network gives the modem one. On the dev phone on KPN
on 2026-10-17 the modem was CS-detached (§13): the one
text sent before the tag was advertised came over IMS, 36 min after its SC
time stamp, in a burst with four sent after it (§13); on 2026-08-18 the same subscription sent
a text over NAS — whether KPN or the phone's attach type decides it is
unmeasured.
A MESSAGE outside a call's dialog whose `Content-Type` does not contain
`application/vnd.3gpp.sms`, letter case ignored — a page-mode MESSAGE — is
still answered 200 and logged with its body: the 200 is `BuildResponse`'s
now and the line names the content type (§7.8). Every header of a MESSAGE
is read by its long name, on one line with the colon straight after the
name: a compact form (RFC 3261 7.3.3) is not seen, so
a `c:` line is no `Content-Type`, an `i:` line no Call-ID and a `v:` line
no `Via`; nor is a name with white space before its colon, and of a value
folded onto further lines the first is read (7.3.1 allows both).
- **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:
`RecentTransactions`, standing in for RFC 3261 17.2.2's server
transaction) gets that final again and is not
handled again: no second text, no second delivery report (of the
bench's two, one was refused with 488, §5). The table is this run's: a copy
that comes after an imsd restart is handled as a new MESSAGE.
- **The service centre.** `SMSC=` when set, else EF_SMSP record 1 read
with `qmicli --uim-read-record` at bring-up (`LoadSmsParameters`): its
TS-Service-Centre-Address is the RP-DATA's destination byte for byte
and, as a SIP URI with `user=phone` built from its international number
(`ScPsi` — never a dialled-number guess: `RuriFor`'s trunk 0 is Dutch),
the MESSAGE's Request-URI and To (5.3.1.2 NOTE 1); its TP-Validity-Period
goes into every SMS-SUBMIT. A service centre whose number is not `+` and
digits — a national `SMSC=`, a `*` or `#` in it, an EF_SMSP record whose
type of number is not international — is refused at bring-up on
`ScPsi`'s own word (an `SMSC=` is read as a number first: its spaces,
dashes and dots dropped, one that is no number refused on `ForNumber`'s),
each with a journal line (§7.8), never announced, and `Send` then fails
with no service centre. EF_PSISMSC (an
operator-configured PSI, ahead of EF_SMSP in 5.3.1.2 NOTE 1's order) is
not read. Without a
service centre `Send` fails with the reason.
- **Submitting** (`SmsOutbound`, `Imsd:Engine`): the text as GSM 7-bit
septets when every character is in the default alphabet or its
extension, else UCS-2; one SMS-SUBMIT per segment (160/70 septets or
UTF-16 units alone — an extension character two septets, a character
beyond the BMP two units — 153/67 with the concatenation header, an
escape or surrogate pair never split), TP-MR counting up per segment from
the one in `/var/lib/imsd/sms-tpmr`, random only when the file gives none (TS 23.040 9.2.3.6's
Last-Used-TP-MR on the (U)SIM is not read or written), RP-MR from a
counter seeded at random at start. One message on the
flow at a time, segment by segment: the MESSAGE with the
RP-DATA, its final within 32 s of the MESSAGE or of its latest provisional (a
provisional starts the wait over); the submit report — an
RP-ACK or RP-ERROR in a MESSAGE of its own, matched by In-Reply-To, else
by RP-MR, answered 200 — within 40 s of a 2xx final (a length TS 24.011
10.1 allows TR1M, which 6.3.1 sets when the RP-DATA is transferred); then the
next segment. Every
segment's RP-ACK: `sent`, with the SC's time stamp when its submit
report carries one; a refused final, an RP-ERROR (its cause and the
submit report's TP-FCS), a wait that runs out or a flow that is down:
`failed` with the reason; a wait is judged at the run loop's passes,
after the server ports are read, so an answer read before that counts
however late. No retransmission (9.2.3.6's repeat with
TP-RD is not done): the sender retries. A `Send` is judged when the engine
takes its command up: unregistered or with the flow down at that moment,
it fails with that reason and is not held for a recovery step; otherwise
it starts, or queues behind the message in flight, and a queued message
starts when the one before it ends, without that check again.
- **Receiving** (`OnSmsMessage`): the MESSAGE is answered 200 on the
channel it came in on first; an SMS-DELIVER is decoded (7-bit, UCS-2 or
8-bit data; the class, the ports, a message-waiting indication), a
concatenated one reassembled (`Reassembler`, in memory: a set to
which no segment has come for 30 min is dropped at the run loop's next pass with a journal line
naming the sender, the set and the segments held, and an imsd restart between segments —
an upgrade's, a `Restart=` — loses the set; a store of parts is a later release's work)
and handed to the bus whole as
`Received`; each segment
is acknowledged with an RP-ACK carrying the SMS-DELIVER-REPORT in a
MESSAGE to the IP-SM-GW — the delivered MESSAGE's P-Asserted-Identity,
else its From — with In-Reply-To naming it (5.3.2.4; left out when its Call-ID holds an ASCII control
character or a space); no report goes for
one that gives neither URI, nor when the flow to the P-CSCF cannot send
it (it is dropped, not held), and the journal says which; a report's
final is logged. An SMS-STATUS-REPORT is acknowledged the same way and matched
to the message that asked for one by TP-MR and the recipient's number
(the book is in memory: after an imsd restart it holds none of the
messages sent before),
and the message gets a word for the whole (`StatusReportBook`), by TS
23.040 9.2.3.15's four classes of TP-ST:
`delivery-failed` at the first report in either of the two in which the
SC is not making any more transfer attempts (a permanent error or a
temporary one, 0x40–0x7F; the message's other TP-MRs are forgotten with
it),
`delivered` when the last of its segments is reported in the completed
class (received by the SME, forwarded by the SC unconfirmed, replaced,
or an SC's own value of that class; the reason has the words),
`delivery-pending` while
the service centre is still trying one (a segment delivered with others
outstanding is logged only); a reserved value, any with bit 7 set among
them, is read as "Service Rejected", a failure, as the clause has the MS
read it (`StatusAsRead`); a report that matches no message is logged. A
message's words come in order (`SmsWordOrder`): the submission's first —
the SC can deliver and report segment 1 while segment 2 is still on its
way, so a report's word on the message in flight is held until the
submission ends and posted after `sent`; a submission that fails after
the SC reported every segment delivered (its last submit report lost or
late) ends as `sent` and `delivered`, not `failed`; one that fails
otherwise drops the held word and forgets the message's TP-MRs, so a
report on a part that went matches nothing. The next TP-MR lives in `/var/lib/imsd/sms-tpmr`
across restarts (9.2.3.6's intent without EF_SMSS), so across a restart
the TP-MRs continue instead of starting over at random — a reuse needs a
full 256-segment wrap, not a restart, while the file's last write reached
the disk (it is neither checked nor synced); RP-MR and the concatenation
reference start at random per start. A TPDU that is unusable — a delivery or a
status report that does not parse, or one of the submit-report type — is
acknowledged the same way with an RP-ERROR (cause 96, TP-FCS "TPDU not supported"). A submit
report In-Reply-To no MESSAGE of ours in flight is answered 488 — 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 shell; a failure; sent) or its segment was superseded by the next, which
gets the same answer; one without In-Reply-To for no message in flight,
200. Nothing is stored: a message that reaches the bus while no app
listens is in the journal (sender, size, time — never the text) and
nowhere else but `DUMP_SIP`'s raw dump of the last MESSAGE. Class 2 messages are not written to the (U)SIM; RP-SMMA
(memory available) is never sent; nothing is done by TP-PID — a short
message type 0, which TS 23.040 9.2.3.9 has an MS acknowledge, discard
and not show, is handed over like any text, its `pid` (0x40) the
consumer's to act on, a Replace Short Message type replaces nothing and
a (U)SIM data download is not passed to the card; a class 0 message is
handed over like any other, its `class` the consumer's to act on; a 7-bit text under a national language shift
table (TS 23.040 9.2.3.24.15 and 9.2.3.24.16, the header's elements 0x24
and 0x25) is read with the default tables, and a compressed text (TS
23.038 4: bit 5 of the coding scheme) as if it were not compressed.
- **The bus** (§8.4): `net.catcrafts.IMS1.Messaging` on the same object,
additive to the frozen interface; `Send` and `Subscribe` gated by
`net.catcrafts.IMS1.Messaging`, the signals unicast to the subscribed
connections (the submission's `sent` / `failed` also to the `Send`
caller's), never broadcast. Spacebar (ModemManager-Qt) and Chatty
(libmm-glib) read ModemManager's Messaging interface, which imsd cannot
stand in for: a messaging app has to speak this one.
## 8. D-Bus ABI and desktop integration
### 8.1 `net.catcrafts.IMS1` (frozen)
@ -1374,7 +1718,9 @@ new translation daemon, not a change here.
refused caller gets `org.freedesktop.DBus.Error.AccessDenied`, and polkit not
answering is logged with the sender. A translation daemon that runs as root
on the system bus must gate its own callers through `imsd-bus`, or it is a
bypass of `net.catcrafts.IMS1.Voice`.
bypass of `net.catcrafts.IMS1.Voice`. Since 1.2.0 a second interface,
`net.catcrafts.IMS1.Messaging`, lives on the same object (§8.4); this one
is unchanged by it.
### 8.2 Plasma Mobile (`imsd-dialerd`)
@ -1465,6 +1811,42 @@ sandbox: §4.1):
busctl --user call org.ofono / org.ofono.Manager GetModems
```
### 8.4 `net.catcrafts.IMS1.Messaging` (since 1.2.0)
Short messages over IP (§7.9), on the object `/net/catcrafts/IMS1` beside
the frozen interface (§8.1's; "the frozen interface" in this document stays
its name). This one is frozen as of 1.2.0 as well. The members, their
signatures, the keys' names, types and meanings, the state words and the
error names stay as they are; a dictionary imsd gives may gain a key, which
a consumer ignores when it does not know it.
| Member | Signature |
|---|---|
| `Send(number, text, options)` | `ssa{sv} → s` (the message's id, `ims-sms-<run>-<start>-<N>`: this run's token — eight hex digits drawn at the daemon's start —, its start second and a counter; a later run gives the same id only if it draws the same token and starts in the same second, and a received id (`ims-sms-in-<run>-<epoch>-<N>`) only with the same token, arrival second and counter; a client keys `StateChanged` by id); options: `status-report` (b). `org.freedesktop.DBus.Error.NotSupported` while `SMS_OVER_IMS` is off |
| `GetStatus()` | `→ a{sv}`: `enabled` (b, the daemon's configuration — answered before the first registration too), `smsc` (s, the service centre as of the daemon's last status snapshot, the one the frozen `GetStatus` answers from — so empty before a run's first, and when none is known), `registered` (b), `subscribers` (u) |
| `Subscribe()` | `→` nothing: the caller's connection receives the two signals below from now on, until it closes. It succeeds while SMS over IP is off too (only `Send` is refused then); a consumer reads `enabled` for that state |
| `Received` | `s a{sv}` — unicast to each subscriber (id `ims-sms-in-<run>-<epoch>-<N>`; `from` s, `text` s, `timestamp` s (the SC's, with its offset: `2026-10-16T22:50:00+02:00`), `received` x (epoch), `sc` s, `class` i (-1: none), `pid` y, `dcs` y, `segments` i, `message-waiting` b, `port-dst`/`port-src` u when the header addresses a port, `data` ay for 8-bit data, `pdu` ay — the SMS-DELIVER as received; of a concatenated message, the segment that completed the set, the last to arrive) |
| `StateChanged` | `s s s` — unicast to each subscriber, and the submission's `sent` / `failed` also to the connection that called `Send` (id, state, reason): `sent` / `failed` for the submission, `delivered` / `delivery-pending` / `delivery-failed` from a status report — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once; `delivered` only when every segment's report is in the completed class (§7.9; the reason carries the SC's status word). The words of one message come in this order: the submission's first — `sent`, or `failed`, after which nothing follows — and a status report's only after `sent` (a report the SC sends while a later segment is still on its way is held until the submission ends; a submission whose every segment the SC reported delivered before its last submit report came ends as `sent` then `delivered`), so a consumer applies each word as it comes. Every string of the two signals is valid UTF-8: a `failed` reason can hold the network's text (a refused final's, `RefusalSummary`), so the emission makes it valid — bytes that are not UTF-8 become U+FFFD, and a NUL byte ends the string (the `Received` strings are the codecs' own) |
`Send` and `Subscribe` are gated by polkit's `net.catcrafts.IMS1.Messaging`
through the same `imsd-bus` gate (`Gated`'s `Action` parameter);
`GetStatus` is a read. The signals are never broadcast: a D-Bus broadcast
reaches every account the bus policy lets receive from imsd, which polkit
cannot narrow, so `Received` and `StateChanged` are emitted unicast to the
unique names `Subscribe` admitted (and the submission's `sent` / `failed`
to the `Send` caller's), which the bus delivers to those connections. A
subscription ends with its connection (imsd watches the name); imsd's own
restart empties the list, so a consumer subscribes at start and again
whenever `net.catcrafts.IMS1` reappears on the bus. A `Send` whose
`StateChanged` had not come when the name left the bus has an unknown fate:
imsd keeps no queue across a restart, and the message in flight may or may
not have reached the service centre; nor does it keep its record of the
messages that asked for a status report, so a report that comes after a
restart is matched to none of them. Root sees the signals
with `busctl monitor` as before. With SMS over IP on, the `imsd --session` dev mode answers `Send` with an
id and a `failed: imsd is not registered` state (2026-10-16,
`SMS_OVER_IMS=1`, the host's session bus).
## 9. Packaging, CI and releases
### 9.1 The APKBUILD
@ -1561,7 +1943,7 @@ documentation: the tables are in the README.
### 10.1 imsd
The README's first table. The protected client/server ports are fixed at
The README's `Full config` table (`SMS_OVER_IMS` and `SMSC` among its rows: §7.9). The protected client/server ports are fixed at
45061/45062 (`imsd::util::PortUc`/`PortUs`) — changing them in source also
requires updating the firewall rules `ims-pdn-up.sh` installs. `PCSCF` and
`PCSCF_DISCOVERED` are read at start (`FreshPcscfFromEnv`, for the start line
@ -1580,8 +1962,9 @@ resume.
### 10.2 imsd-media (per call, set through imsd's environment)
The README's second table. These are not configuration and are left out
there:
The imsd-media table under the README's `Full config` (the second
`Variable | Default | Meaning` table). These are not configuration and are
left out there:
| Variable | Default | Meaning |
|---|---|---|
@ -1636,11 +2019,14 @@ only the imsd side of its bus choice.
path stays live for any direct upgrade from an older daemon.
- **Never commit captures or state** (`*.raw`, `*.rtp`, `*.stats`,
`imsreg.state`): they carry the subscriber's identity.
SMS over IP's state stays out likewise: `sms-tpmr`, the next TP-MR.
## 12. Security considerations
- imsd runs as root (xfrm, qmicli). Its attack surface on the bus is the
frozen ABI; the writes are polkit-gated (§7.1, §8.1). Do not add an
frozen ABI (§8.1) and, since 1.2.0, the Messaging interface on the same
object (§8.4), the writes of both polkit-gated (§7.1: the Voice and the
Messaging action). Do not add an
ungated write member, and do not add a root translation daemon that
forwards calls without gating its own callers through `imsd-bus`.
- imsd deletes by exact key what two rules select, whoever installed it. A
@ -1677,6 +2063,24 @@ only the imsd side of its bus choice.
A change that routes anything else over it needs a reason and a bench.
- The fixed protected ports (45061/45062) are opened in nftables for
`qmapmux*` only, by the bring-up script.
- Short messages (§7.9): `Send` is behind `net.catcrafts.IMS1.Messaging`
(an ungated `Send` would let any local account text from the
subscriber's number); the journal names a delivered message's sender, size and
time — a text reaches it only as the hex of a body that is no RP message
or of an unusable TPDU, and as the body of a MESSAGE whose `Content-Type`
does not contain `application/vnd.3gpp.sms` (§7.9); the
`DUMP_SIP` MESSAGE dumps do carry texts, mode
0600 like the rest. A MESSAGE outside a call's dialog whose `Content-Type`
contains `application/vnd.3gpp.sms` (§7.9) is taken for a short message
under `SMS_OVER_IMS=1` (refused with 480 without it), from the P-CSCF over the SA
or in plaintext from any address that reaches the server ports on the ims
PDN — imsd checks neither the source nor the sender, and `from` is
the TPDU's TP-OA, decoded and unchecked.
`Received` and `StateChanged` go unicast to the connections `Subscribe`
admitted through the Messaging action — a submission's `sent`/`failed`
also to the connection that called `Send`, admitted by the same action —
never broadcast: a text's content
reaches no connection polkit did not allow.
- **`imsd-pcscf` holds a QMI WDS client of its own on the modem, as root,
from `ims-pdn-up.sh`.** It binds to the bearer's mux data port and reads
@ -1774,6 +2178,10 @@ the related code.
every name the receiver owns (the `org.ofono.conf` detail).
- **The phone's wall clock reads 1970 until the first NTP sync**; anything
that ages a journal line uses the monotonic or boot clock.
- **KPN's EF_SMSP** (the dev phone's SIM, 2026-10-16): one record of 43
octets, no alpha identifier, parameter indicators 0xED (TP-SCA and TP-VP
present), TS-Service-Centre-Address `07 91 13 56 13 13 13 F3` =
+31653131313, TP-VP 0xA9 (3 days). What KPN's IP-SM-GW does with it: the 2026-10-17 bench bullet below.
- **A WDS client bound to the bearer's mux data port, with IP family 6 set,
reads the call's runtime settings; one that sent neither the binding nor Set IP Family got
`OutOfCall`.** ModemManager owns the ims
@ -1788,3 +2196,30 @@ the related code.
2026-10-11; the fp6 journal's `2026-10-11-pcscf-pco-probe` capture).
libqmi does not model 0x2E and qmicli cannot print any of it, hence
`imsd-pcscf`.
- **KPN, SMS over IP (dev phone, KPN eSIM, 2026-10-17 bench — fp6 journal
`captures/2026-10-17-sms-over-ip-bench/`).** That night the modem was
CS-detached (NAS: CS detached, LTE domain ps, voice support no, no 2G/3G
service);
on 2026-08-18 the same subscription had a NAS SMS path (the MO/MT NAS
proof) — whether the network or the phone's attach type decides it is
unmeasured. Submissions: MESSAGE to the EF_SMSP service centre's PSI → 202 within
a second (79–241 ms over seven MESSAGEs of 2026-10-17 — six submissions,
one in two segments — by the journal's microsecond stamps,
`r23-phone-journal-2026-10-17-precise-and-modem-sms`); the one RP-ACK
submit report whose dump the capture keeps (`mo-loop-test-submit-report-in`) is a
MESSAGE (From tag `smsavipsmsc03.app.gen.local-…`,
P-Asserted-Identity +316530850013) with
`In-Reply-To` and `Accept-Contact: *;+g.3gpp.smsip;require;explicit`, over
UDP from the P-CSCF to the protected server port. Deliveries: a MESSAGE whose From tag and
Call-ID begin `smsavipsmsc04.app.gen.local` (P-Asserted-Identity +316530850014),
`Request-Disposition: no-fork`, the RP-DATA's originator the sending
subscriber's service centre (+31624000000 for the A16 on Odido, the sender
of every text delivered on 2026-10-17 but AUTHMSG's, via +31626000230;
EF_SMSP's +31653131313 for a text from the phone's own KPN number,
2026-10-18 01:37 and 02:18); our RP-ACK delivery report
MESSAGE is answered 202 (one of the 01:23 pair was refused 488, §5). One text sent before the tag was advertised and
four sent after the 00:45:10 registration with it arrived in one burst at
01:17:41–45, 28–36 min after their SC time stamps; what held them is
unknown. The registrar echoes `+g.3gpp.smsip` in the reg-event reginfo
(`<unknown-param name="+g.3gpp.smsip"/>`) on both AORs.

View file

@ -65,6 +65,18 @@ Do not run it alongside a real `ofonod`.
Call control is polkit's `net.catcrafts.IMS1.Voice`: the active local
session and root may place, answer and end calls; an ssh login may not.
## SMS over IMS
Off unless `SMS_OVER_IMS=1` is set in `/etc/imsd.env`. On, imsd sends texts
over the IMS registration it already holds, through the SIM's service
centre or the one `SMSC` names, and receives texts the network delivers over IMS, and
announces a received text on its
`net.catcrafts.IMS1.Messaging` interface. Apps that read ModemManager, such as
Spacebar and Chatty, do not see texts that arrive this way; an app gets them
by subscribing on the Messaging interface. The details are in
AGENTS.md: the behaviour in §7.9, the interface in §8.4, what was verified
on which network in §5.
## Full config:
Configuration is environment variables in `/etc/imsd.env`, none are required.
@ -84,11 +96,13 @@ Configuration is environment variables in `/etc/imsd.env`, none are required.
| `REFRESH_INTERVAL` | *(auto)* | keepalive re-REGISTER period in s; default = half the granted expiry, clamped to [120, 1800] |
| `EALG` | `aes-cbc` | offered ESP cipher (`aes-cbc`, `des-ede3-cbc`, `null`). From the 401's `Security-Server` list imsd selects the highest-preference `ipsec-3gpp` mechanism that matches this offer (RFC 3329 §2.3.1) and takes the SPIs/ports from the entry carrying them (some cores list every mechanism they support and put the SPIs on the one they applied); when no entry matches, the P-CSCF's SPI-carrying entry is installed as listed (`hmac-md5-96`, an absent `ealg` = null) and the journal says so. The line, the selection and the SA parameters are logged at every fresh registration |
| `SIP_TRANSPORT` | `auto` | transport of the protected leg (the second REGISTER and everything after it): `tcp`, `udp`, or `auto` = TCP, falling back to a fresh registration over UDP when the P-CSCF leaves two TCP connects unanswered — but only on a phone that has never registered over TCP: once the state file records a TCP registration, a silent connect is treated as an outage, not a policy (delete the file or set `udp` to override, e.g. after a SIM change). The challenge (first REGISTER) is always UDP. Over UDP a REGISTER or INVITE larger than ~1.2 KB leaves as IPv6 fragments at the ims PDN's 1280-byte MTU (the journal says so once per flow); there are no SIP retransmission timers over UDP yet, so a lost datagram costs a timeout. The SAs, the listener and the firewall rule cover both transports |
| `SMS_OVER_IMS` | `0` | `1` takes short messages over IMS (AGENTS.md §7.9): the REGISTER Contact advertises `+g.3gpp.smsip` and `net.catcrafts.IMS1.Messaging.Send` submits one; off, imsd does not advertise it and refuses `Send` (AGENTS.md §7.9 says how imsd answers a text the network sends anyway) |
| `SMSC` | *(EF_SMSP)* | the service centre a submission is addressed to, in international form (`+31653131313`; spaces, dashes and dots dropped; a national or `00`-prefixed number, or a `*` or `#` in it, is refused at bring-up); unset, imsd reads the (U)SIM's EF_SMSP record 1. Without either, `Send` fails with the reason |
| `EMERGENCY_NUMBERS` | *(empty)* | comma-separated additions to the builtin 112/911 emergency numbers (e.g. a private test core's short code). SIM `EF_ECC` is not read yet. `imsd-ofonod` reads it too, for the oFono `EmergencyNumbers` property |
| `RTP_PORT` | `50004` | local RTP port advertised in SDP |
| `PRECOND` | `0` | `1` offers SDP QoS preconditions |
| `CODECS` | *(empty — defaults)* | comma-separated codec preference list over `AMR-WB`, `AMR` (or `AMR-NB`), `PCMA`, `PCMU`: restricts and orders both the codecs offered on an outgoing call and those accepted from an inbound offer (default: offer AMR-WB + AMR, accept all four in that order). A bench knob — a network whose gateway transcodes every caller up to AMR-WB otherwise never lets the narrowband path run |
| `DUMP_SIP` | `0` | `1` writes raw REGISTER-200/SUBSCRIBE-200 dumps, the last refused REGISTER or SUBSCRIBE final (`imsd-register-fail.raw`, `imsd-subscribe-fail.raw`), the last inbound INVITE (`imsd-invite-in.raw`) and the last outgoing INVITE (`imsd-invite-out.raw`), mode 0600, for debugging — they contain your IMSI/MSISDN and addresses. A refused REGISTER or SUBSCRIBE is logged with its status line and any Retry-After / Warning / Reason / Server headers |
| `DUMP_SIP` | `0` | `1` writes raw REGISTER-200/SUBSCRIBE-200 dumps, the last refused REGISTER or SUBSCRIBE final (`imsd-register-fail.raw`, `imsd-subscribe-fail.raw`), the last incoming call's INVITE (`imsd-invite-in.raw`), the last outgoing INVITE (`imsd-invite-out.raw`), the last inbound MESSAGE outside a call's dialog (`imsd-message-in.raw`) and the last MESSAGE a submission started with (`imsd-message-out.raw`), mode 0600, for debugging — they contain your IMSI/MSISDN and addresses, and the two MESSAGE dumps the text of a short message. A refused REGISTER or SUBSCRIBE is logged with its status line and any Retry-After / Warning / Reason / Server headers |
| `DUMP_DIR`, `OUT_DIR` | state dir | where dumps / per-call media stats land |
| `IMSD_MEDIA` | *(auto)* | path to `imsd-media` (default: next to `imsd`, else `/usr/libexec/imsd-media`) |
| `IMSD_ENV` | `/etc/imsd.env` | the configuration file's path — a bench seam for manual runs of `ims-pdn-up.sh` (the packaged unit reads `/etc/imsd.env` through `EnvironmentFile=`). The file's existence changes nothing |
@ -129,6 +143,23 @@ updating the firewall rules `ims-pdn-up.sh` installs.
Both `imsd-dialerd` and `imsd-ofonod` are users of this ABI.
A new desktop needs a new translation daemon, not changes here.
### `net.catcrafts.IMS1.Messaging` (since 1.2.0)
A second interface on the same object, for short messages over IMS
(`SMS_OVER_IMS=1`). Additive: the interface above is unchanged. Frozen as of
1.2.0: what the table lists stays as it is, and a dictionary imsd gives may
gain a key.
| Member | Signature |
|---|---|
| `Send(number, text, options)` | `ssa{sv} → s` (id); options: `status-report` (b, ask the SC to report delivery). Refused with `NotSupported` while SMS over IMS is off |
| `GetStatus()` | `→ a{sv}`: `enabled` (b), `smsc` (s), `registered` (b), `subscribers` (u) |
| `Subscribe()` | `→` nothing: the calling connection receives `Received` and `StateChanged` from now on (unicast, never broadcast: to subscribers, and a submission's `sent` / `failed` also to its `Send` caller); subscribe again when imsd's name reappears on the bus |
| `Received` | `s a{sv}` (id, message: `from`, `text`, `timestamp` (the SC's, as `2026-10-16T22:50:00+02:00`), `received` (x), `sc`, `class` (i, -1 none), `pid` (y), `dcs` (y), `segments` (i), `message-waiting` (b), `port-dst`/`port-src` (u, when addressed to a port), `data` (ay, 8-bit data), `pdu` (ay, the SMS-DELIVER as received; of a concatenated message, the segment that completed it)) |
| `StateChanged` | `s s s` (id, state, reason): `sent` (every segment accepted by the SC), `failed` (why), and with a status report `delivered` (every segment), `delivery-pending`, `delivery-failed` — each speaks for the whole message, never for one segment, and `delivery-pending` can come more than once |
`Send` and `Subscribe` are gated by polkit's `net.catcrafts.IMS1.Messaging`.
## License
GPL-3.0-only - see [LICENSE](LICENSE).

View file

@ -10,9 +10,11 @@ Owns net.catcrafts.IMS1 on the system bus with the project's frozen D-Bus ABI
+ IPsec sec-agree, fresh or warm-resume, with a keepalive re-REGISTER refresh),
run outgoing and incoming calls through the Imsd:Engine call machine (inbound
INVITEs on the protected-port listeners become ringing calls a dialer answers
via Accept), and spawn one imsd-media data-plane process per answered call.
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).
GLib/GDBus lives only here and in ImsdBus (the polkit gate in front of call
control, shared with imsd-ofonod) — the integration daemons imsd-dialerd and
control and messaging, shared with imsd-ofonod) — the integration daemons imsd-dialerd and
imsd-ofonod carry their own; every message, digest, SA command, and
call-state decision comes from the GLib-free core.
@ -20,7 +22,8 @@ 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
(touched only on the main thread).
(touched only on the main thread). The Messaging interface's Subscribe keeps
its subscriber set on the main thread too.
--session own the name on the session bus (development; no policy, no
polkit)
@ -53,6 +56,7 @@ constexpr const char* Version = "1.1.0";
constexpr const char* BusName = "net.catcrafts.IMS1";
constexpr const char* ObjPath = "/net/catcrafts/IMS1";
constexpr const char* Iface = "net.catcrafts.IMS1";
constexpr const char* MessagingIface = "net.catcrafts.IMS1.Messaging";
constexpr int PortUc = imsd::util::PortUc;
constexpr int PortUs = imsd::util::PortUs;
constexpr int PortUcNext = imsd::util::PortUcNext;
@ -721,6 +725,23 @@ std::string StateDir() {
// tiny JSON reader/writer for the persisted registration context.
std::string StatePath() { return EnvOr("STATE_FILE", std::format("{}/imsreg.state", StateDir())); }
// 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
}
// `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
@ -801,15 +822,17 @@ struct StatusSnapshot {
std::string local, pcscf, ppi;
std::int64_t expiry = 0;
std::int64_t cseq = 0;
std::string smsc; // the service centre a submission goes to (empty: none known)
};
// engine -> main-loop event
struct Event {
enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle } type;
enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState } type;
CallInfo info; // Added
std::string uni, state, reason; // State/Deleted
std::string uni, state, reason; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id)
StatusSnapshot status; // Registration/Status
std::string text; // Fatal, Idle
imsd::engine::SmsReceived sms; // SmsReceived
};
GDBusConnection* DbusConn = nullptr;
@ -923,6 +946,58 @@ void EmitSignal(const char* name, GVariant* params) {
g_dbus_connection_emit_signal(DbusConn, nullptr, ObjPath, Iface, name, params, nullptr);
}
// ---- 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);
}
// a received short message as the Messaging interface's a{sv} (§8.4)
GVariant* SmsVariant(const imsd::engine::SmsReceived& m) {
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()));
g_variant_builder_add(&b, "{sv}", "received", g_variant_new_int64(NowEpoch()));
g_variant_builder_add(&b, "{sv}", "sc", g_variant_new_string(m.sc.c_str()));
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);
}
gboolean OnIdleEvent(gpointer data) {
std::unique_ptr<Event> ev(static_cast<Event*>(data));
switch (ev->type) {
@ -963,6 +1038,27 @@ gboolean OnIdleEvent(gpointer data) {
Log(std::format("idle: {} — nothing to do; systemctl start imsd when that changes", ev->text));
g_main_loop_quit(MainLoop);
break;
case Event::Type::SmsReceived:
for (const std::string& to : Subscribers)
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms)));
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;
}
}
return G_SOURCE_REMOVE;
}
@ -1020,6 +1116,24 @@ public:
for (const auto& c : codecs_) list += (list.empty() ? "" : ",") + c;
Log(std::format("CODECS override active: {}", list));
}
// 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_NUMBERS: comma-separated additions to the builtin
// 112/911 (a lab core's advertised short code, carrier extras).
std::string extra = EnvOr("EMERGENCY_NUMBERS", "");
@ -1057,6 +1171,14 @@ public:
std::scoped_lock g(cmdLock_);
cmds_.push_back({Cmd::Kind::Dtmf, uni, tones});
}
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;
}
void Stop() {
{ std::scoped_lock g(cmdLock_); cmds_.push_back({Cmd::Kind::Stop, {}, {}}); }
quit_.store(true);
@ -1116,6 +1238,17 @@ public:
reply_ = in.reply;
DispatchRequest(in.msg);
}
// the SMS deadline (the final's wait, the report's) is judged right
// after the server ports were drained: a submit report that landed
// during a blocking re-REGISTER below must not count as a timeout
if (smsOut_ && smsOut_->Deadline() > 0 && Mono() > smsOut_->Deadline()) {
ExecuteSms(smsOut_->OnDeadline());
AfterSms();
}
// 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)));
MaybeRefresh();
MaybeReconnect();
MaybeResubscribe();
@ -1134,7 +1267,7 @@ public:
if (call_ && callid == call_->CallId() && cseq.ends_with("INVITE")) {
Execute(call_->OnInviteResponse(*msg));
MaybeDropCall();
} else {
} else if (!OnSmsResponse(*msg, *st)) {
OnSubscribeResponse(*msg, *st);
}
}
@ -1145,7 +1278,12 @@ public:
}
private:
struct Cmd { enum class Kind { Dial, HangUp, Accept, Dtmf, Stop } kind; std::string uni, arg; }; // arg: the number to dial, or the tones
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
};
struct Stopping {}; // the engine was told to stop while a bring-up waited
// A bring-up the network deferred (a fresh-SA throttle) or refused: wait
@ -1267,6 +1405,27 @@ private:
std::atomic<bool> quit_{false};
bool devMode_ = false;
// 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
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)
// command queue
std::mutex cmdLock_;
std::deque<Cmd> cmds_;
@ -1336,6 +1495,8 @@ private:
reg_.slot = sel->slot;
reg_.aid = sel->aid;
Log(std::format("SIM slot={} IMSI={} domain={}", sel->slot, info->imsi, ctx_.id.domain));
ctx_.smsOverIp = smsOverIp_;
if (smsOverIp_) LoadSmsParameters();
RefreshPani();
std::string resume = EnvOr("RESUME", "auto");
@ -1753,7 +1914,7 @@ private:
// 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
// wait going; a response to our reg-event SUBSCRIBE is handled as the
// wait going; a response to our reg-event SUBSCRIBE or to one of our MESSAGEs is handled as the
// run loop handles it, any other transaction's is ignored. Throws
// when nothing answers or the flow dies under a dispatched request.
std::string AwaitFinal(const std::string& callid, long cseq, std::string_view what) {
@ -1771,7 +1932,7 @@ private:
continue;
}
if (!imsd::sip::ResponseOf(*m, callid, want)) {
if (!OnSubscribeResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what));
if (!OnSubscribeResponse(*m, *st) && !OnSmsResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what));
continue;
}
if (*st >= 200) return *m;
@ -2425,9 +2586,221 @@ private:
} 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));
} 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;
smsOut_.emplace(ctx_, rng_, id, std::move(p));
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_);
rpMr_ = static_cast<std::uint8_t>(rpMr_ + segments);
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);
if (smsOut_ && smsOut_->Done()) smsOut_.reset();
}
}
// 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;
smsOut_.reset();
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;
}
}
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;
}
auto r = imsd::engine::OnSmsMessage(ctx_, rng_, msg, reassembler_, smsOut_ ? &*smsOut_ : nullptr, Mono());
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);
}
void PostSmsReceived(const imsd::engine::SmsReceived& m) {
auto ev = std::make_unique<Event>();
ev->type = Event::Type::SmsReceived;
ev->uni = imsd::engine::ReceivedSmsId(smsRun_, NowEpoch(), ++smsInSeq_);
ev->sms = m;
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()));
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));
}
void DispatchRequest(const std::string& msg) {
std::string callid(imsd::sip::Header(msg, "Call-ID").value_or(""));
std::size_t sp = msg.find(' ');
@ -2441,16 +2814,18 @@ private:
// ACK is never answered — e.g. the caller ACKing the 486/487 of a
// call machine we already dropped
if (method == "ACK") return;
// 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;
}
// 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.
// MESSAGE (terminating SMS-over-IP while +g.3gpp.smsip is
// advertised): log the whole body — the 200 acks delivery, so the
// journal is the only place the payload survives until real SMSoIP
// handling exists.
if (method == "NOTIFY" || method == "MESSAGE") {
if (method == "NOTIFY") {
std::string_view body = imsd::sip::Body(msg);
if (method == "MESSAGE") Log(std::format("MESSAGE from {} ({} bytes):\n{}", imsd::sip::CallerId(msg), body.size(), body));
else if (auto ev = imsd::sip::Header(msg, "Event"); ev && ev->starts_with("reg")) {
if (auto ev = imsd::sip::Header(msg, "Event"); ev && ev->starts_with("reg")) {
Log(std::format("reg-event NOTIFY ({} bytes):\n{}", body.size(), body));
if (reply_) reply_(imsd::msg::BuildResponse200(ctx_, msg));
OnRegEventNotify(msg, body);
@ -2657,7 +3032,7 @@ private:
void EmitStatus(bool registrationSignal) {
auto ev = std::make_unique<Event>();
ev->type = registrationSignal ? Event::Type::Registration : Event::Type::Status;
ev->status = StatusSnapshot{registered_, local_, pcscf_, ppi_, reg_.expiry, reg_.cseq};
ev->status = StatusSnapshot{registered_, local_, pcscf_, ppi_, reg_.expiry, reg_.cseq, smsc_};
PostEvent(std::move(ev));
}
void PostAdded(const CallInfo& info) {
@ -2700,6 +3075,20 @@ constexpr const char* IntrospectionXml = R"xml(
<signal name="CallDeleted"><arg type="s" name="callUni"/></signal>
<signal name="RegistrationChanged"><arg type="b" name="registered"/></signal>
</interface>
<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>
<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>
</node>)xml";
void HandleMethodCall(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* method, GVariant* params, GDBusMethodInvocation* inv, gpointer) {
@ -2756,14 +3145,65 @@ void HandleMethodCall(GDBusConnection*, const gchar*, const gchar*, const gchar*
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.UnknownMethod", "no such method");
}
// 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()));
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;
}
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.UnknownMethod", "no such method");
}
bool IsRead(std::string_view method) { return method == "GetStatus" || method == "GetCalls"; }
bool IsMessagingRead(std::string_view method) { return method == "GetStatus"; }
constexpr char ErrAccessDenied[] = "org.freedesktop.DBus.Error.AccessDenied";
const GDBusInterfaceVTable Vtable = { imsd::bus::Gated<HandleMethodCall, IsRead, ErrAccessDenied, Log>, nullptr, nullptr, {} };
const GDBusInterfaceVTable MessagingVtable = { imsd::bus::Gated<HandleMessagingMethod, IsMessagingRead, ErrAccessDenied, Log, imsd::bus::MessagingAction>, nullptr, nullptr, {} };
void OnBusAcquired(GDBusConnection* conn, const gchar*, gpointer) {
DbusConn = conn;
GDBusNodeInfo* node = g_dbus_node_info_new_for_xml(IntrospectionXml, nullptr);
g_dbus_connection_register_object(conn, ObjPath, node->interfaces[0], &Vtable, nullptr, nullptr, nullptr);
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; }
}
}
g_dbus_node_info_unref(node);
Log(std::format("object registered at {}", ObjPath));
}

View file

@ -36,7 +36,10 @@ MESSAGE outside a call's dialog leads to (the final for it, the message or
status report it delivered, the delivery report to send), with
RecentTransactions (a retransmitted request within 32 s gets its final
again and is not handled again; one whose first Via line has no
`branch=`, or an empty one, is never taken for a copy). Pure std C++.
`branch=`, or an empty one, is never taken for a copy), and StatusReportBook with SameRecipient (a status
report's match to the message that asked for one, TP-MR and recipient, and
its word for the whole message), SmsWordOrder (the order of a message's
words) and the ids (RunToken, SentSmsId, ReceivedSmsId). Pure std C++.
*/
export module Imsd:Engine;
@ -949,7 +952,7 @@ export namespace imsd::engine {
SendClient, // send `text` on the client flow (a MESSAGE of ours)
SendResponse, // answer the inbound MESSAGE being handled with `text`
Received, // hand `received` to the bus
StatusReport, // `report`: the SC's word on a message we sent (matched by TP-MR by the shell)
StatusReport, // `report`: the SC's word on a message we sent (the shell hands it to StatusReportBook)
State, // emit StateChanged(id, `state`, `reason`) for a message of ours
Log,
};
@ -960,6 +963,84 @@ export namespace imsd::engine {
imsd::sms::StatusReport report;
};
// Whether a status report's TP-Recipient-Address names the number a
// message was sent to. A status report may give a number dialled
// nationally in its international form (0612… as 31612…), so
// the digits are compared after a trunk 0: equal, or the shorter — at
// least seven digits, a short code must be equal — the longer's suffix.
// With the TP-MR that is match enough; separators and a '+' are ignored.
bool SameRecipient(std::string_view dialled, std::string_view reported) {
auto digits = [](std::string_view v) {
std::string d;
for (char c : v) if (std::isdigit(static_cast<unsigned char>(c))) d.push_back(c);
if (d.starts_with('0')) d.erase(0, 1);
return d;
};
const std::string a = digits(dialled), b = digits(reported);
if (a.empty() || b.empty()) return false;
if (a == b) return true;
const std::string& shorter = a.size() < b.size() ? a : b;
const std::string& longer = a.size() < b.size() ? b : a;
return shorter.size() >= 7 && longer.ends_with(shorter);
}
// The messages that asked for a status report, by the TP-MR of each
// segment (TS 23.040 9.2.3.6: a report names one SMS-SUBMIT). A message
// gets a word for the whole, by TP-ST as StatusAsRead gives it (a
// reserved value is a failure): Failed at the first report in which the
// service centre has stopped trying (0x40 and up; the message is
// forgotten), Delivered when the last of its segments is (below 0x20),
// Pending while the service centre is still trying one (0x20–0x3F); a
// segment delivered with others outstanding is SegmentDelivered, for
// the log. A report that names no
// message — an unknown TP-MR, or another recipient (SameRecipient) — is
// NoMessage. A TP-MR reused before its word came (256 segments later)
// forgets the older message whole.
class StatusReportBook {
public:
enum class Word { NoMessage, SegmentDelivered, Delivered, Pending, Failed };
struct Outcome { Word word = Word::NoMessage; std::string id; std::size_t outstanding = 0; };
void Sent(std::string_view id, std::string_view destination, std::span<const std::uint8_t> tpMrs) {
if (tpMrs.empty()) return;
for (std::uint8_t mr : tpMrs) Forget(mr);
auto m = std::make_shared<Message>();
m->id = id; m->destination = destination;
for (std::uint8_t mr : tpMrs) { m->outstanding.insert(mr); byMr_[mr] = m; }
}
Outcome Report(std::uint8_t mr, std::string_view recipient, std::uint8_t status) {
auto it = byMr_.find(mr);
if (it == byMr_.end() || !SameRecipient(it->second->destination, recipient)) return {};
auto m = it->second;
const std::uint8_t st = imsd::sms::StatusAsRead(status);
if (st >= 0x20 && st < 0x40) return {Word::Pending, m->id, m->outstanding.size()};
if (st >= 0x40) { Forget(mr); return {Word::Failed, m->id, 0}; }
m->outstanding.erase(mr);
byMr_.erase(it);
return {m->outstanding.empty() ? Word::Delivered : Word::SegmentDelivered, m->id, m->outstanding.size()};
}
std::size_t Size() const { return byMr_.size(); }
// the message `id`, every TP-MR of it: its submission failed, so a
// report on a part that went says nothing about the message
void ForgetMessage(std::string_view id) {
for (const auto& [mr, m] : byMr_)
if (m->id == id) { Forget(mr); return; }
}
private:
struct Message { std::string id, destination; std::set<std::uint8_t> outstanding; };
// the message holding this TP-MR, every TP-MR of it
void Forget(std::uint8_t mr) {
auto it = byMr_.find(mr);
if (it == byMr_.end()) return;
auto m = it->second;
for (std::uint8_t x : m->outstanding) byMr_.erase(x);
m->outstanding.clear();
}
std::map<std::uint8_t, std::shared_ptr<Message>> byMr_;
};
// The waits (TS 24.011 10: TR1M; TS 24.341 5.3.1.1 NOTE 1 has it
// exceed SIP timer F): a MESSAGE's final within 32 s
// of the MESSAGE or of its latest provisional, which starts the wait
@ -968,9 +1049,64 @@ export namespace imsd::engine {
inline constexpr double SmsSendTimeout = 32.0;
inline constexpr double SmsReportTimeout = 40.0;
// What the bus hears: `sent` once every segment's submit report is
// in, `failed` with the reason otherwise.
// in, `failed` with the reason; a status report's word
// after `sent` (StatusReportBook, SmsWordOrder, which also has the one
// failure posted as `sent`).
inline constexpr std::string_view SmsStateSent = "sent";
inline constexpr std::string_view SmsStateFailed = "failed";
inline constexpr std::string_view SmsStateDelivered = "delivered";
inline constexpr std::string_view SmsStateDeliveryPending = "delivery-pending";
inline constexpr std::string_view SmsStateDeliveryFailed = "delivery-failed";
// The order of one message's words (§8.4): the submission's first —
// `sent`, or `failed`, after which nothing follows — and a status
// report's only after `sent`. The SC can deliver and report segment 1
// while segment 2 is still on its way, so a report's word on the message
// in flight is held until the submission ends (the latest word, one per
// message). A submission that fails after the SC reported every segment
// delivered — its last submit report lost or late — ends as `sent` and
// then `delivered`, not `failed`; one that fails otherwise drops the held
// word and has the message's TP-MRs forgotten (`forget`), so a later
// report on a part that went matches nothing. One message is in flight
// at a time (the shell's queue), so one held word suffices.
class SmsWordOrder {
public:
struct Word { std::string id, state, reason; };
struct Ended { std::vector<Word> post; bool forget = false; };
// a report's word on `id`: posted now, or held while `id`'s submission is in flight
std::vector<Word> Report(std::string_view id, std::string_view state, std::string_view reason, bool inFlight) {
Word w{std::string(id), std::string(state), std::string(reason)};
if (!inFlight) return {std::move(w)};
held_ = std::move(w);
return {};
}
// the submission's word on `id`: the words to post, in order, and whether its TP-MRs are to be forgotten
Ended Submission(std::string_view id, std::string_view state, std::string_view reason) {
Ended e;
std::optional<Word> held;
if (held_ && held_->id == id) held = std::exchange(held_, std::nullopt);
if (state == SmsStateFailed) {
if (held && held->state == SmsStateDelivered) {
e.post.push_back({std::string(id), std::string(SmsStateSent), std::format("every segment reported delivered by the SC; {}", reason)});
e.post.push_back(std::move(*held));
return e;
}
e.forget = true;
e.post.push_back({std::string(id), std::string(state), std::string(reason)});
return e;
}
e.post.push_back({std::string(id), std::string(state), std::string(reason)});
if (held) e.post.push_back(std::move(*held));
return e;
}
bool Holding() const { return held_.has_value(); }
private:
std::optional<Word> held_;
};
// One short message of ours on its way to the service centre, segment
// by segment: the MESSAGE with the segment's RP-DATA, its final, the
@ -999,6 +1135,8 @@ export namespace imsd::engine {
: ctx_(ctx), rng_(rng), id_(std::move(id)), p_(std::move(p)) {}
const std::string& Id() const { return id_; }
// the segment in flight's MESSAGE (empty before the first went out)
const std::string& CallId() const { return callid_; }
Phase State() const { return phase_; }
bool Done() const { return phase_ == Phase::Done; }
// the engine's clock reading at which OnDeadline is due (0: none)
@ -1155,6 +1293,17 @@ export namespace imsd::engine {
double deadline_ = 0;
};
// The ids of the Messaging interface (§8.4): the run's token — eight hex
// digits drawn once at the daemon's start — then a second, then a
// counter. The token is what tells one run's ids from another's: the
// wall clock reads 1970 until the first time sync, so a second alone
// repeats across runs.
std::string RunToken(std::uint32_t bits) { return std::format("{:08x}", bits); }
std::string SentSmsId(std::string_view run, std::int64_t start, std::uint64_t n) { return std::format("ims-sms-{}-{}-{}", run, start, n); }
std::string ReceivedSmsId(std::string_view run, std::int64_t at, std::uint64_t n) { return std::format("ims-sms-in-{}-{}-{}", run, at, n); }
// ---- retransmitted requests (RFC 3261 17.2.2) ------------------------
// A request whose Via branch (the value of the first `branch=` of its
@ -1234,7 +1383,12 @@ export namespace imsd::engine {
// message in flight does not own is answered 488 when its In-Reply-To is
// not empty, else 200 and logged. A MESSAGE whose Content-Type
// does not contain the SMS one, or whose body is no RP message, is
// answered 200 and logged (the journal keeps what the 200 acknowledged).
// answered 200 and logged (the journal keeps what the 200 acknowledged). While SMS over IP is off (`ctx.smsOverIp`)
// every MESSAGE whose Content-Type contains the SMS one is refused
// with 480 Temporarily Unavailable instead, its body not parsed: a 200
// and an RP-ACK would count a short message delivered to nobody, a failure lets the IP-SM-GW try the
// modem's path (TS 24.341 5.3.3.4.2 NOTE 2) where the network gives the
// modem one.
SmsInbound OnSmsMessage(const imsd::msg::Context& ctx, imsd::util::Rng& rng, std::string_view message, imsd::sms::Reassembler& reassembler, SmsOutbound* outbound, double now) {
using imsd::sms::RpType;
SmsInbound r;
@ -1252,6 +1406,11 @@ export namespace imsd::engine {
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("MESSAGE from {} ({}, {} bytes):\n{}", from, ctype.empty() ? "no content type" : ctype, body.size(), body)});
return r;
}
if (!ctx.smsOverIp) {
r.response = imsd::msg::BuildResponse(ctx, message, 480, "Temporarily Unavailable", toTag);
r.actions.push_back(SmsAction{SmsAction::Type::Log, std::format("short message over IP from {} ({} bytes) while SMS_OVER_IMS is off: 480", from, body.size())});
return r;
}
std::span<const std::uint8_t> bytes(reinterpret_cast<const std::uint8_t*>(body.data()), body.size()); // lint-disable-line no-char-pointer
r.rp = imsd::sms::ParseRp(bytes, true);
if (!r.rp) {

View file

@ -522,8 +522,8 @@ export namespace imsd::msg {
return std::format("{}\r\n", detail::Join(l));
}
// The final for an inbound MESSAGE outside a call's dialog — the 200 to one we took, the 488 to
// one we did not: each `Via:` line echoed in order (the response
// The final for an inbound MESSAGE outside a call's dialog — the 200 to one we took, the 480 or
// 488 to one we did not: each `Via:` line echoed in order (the response
// travels the proxy chain back, RFC 3261 8.2.6.2; long header names only,
// not the compact forms), From, To with
// `toTag` added unless the request's To holds `tag=` (8.2.6.2 again),

View file

@ -4,16 +4,20 @@
// lint-disable-file fixed-width-types no-char-pointer
/*
ImsdBus — what the two system-bus daemons (imsd, imsd-ofonod) share on the
bus side: the polkit gate in front of call control.
bus side: the polkit gate in front of call control and messaging.
The bus policies let any local account reach both names, so the session
account can dial whatever it is called; whether a caller may place, answer
or end a call is polkit's net.catcrafts.IMS1.Voice
(packaging/net.catcrafts.IMS1.policy), shaped like ModemManager's Voice
action: the active local session and root, not an ssh login, an inactive
session or a system service account. Reads (status, the call list) stay
open, as ModemManager's are to every local account; the call signals reach
them all anyway.
or end a call is polkit's net.catcrafts.IMS1.Voice, and whether it may send
a short message or subscribe to the message signals
net.catcrafts.IMS1.Messaging
(packaging/net.catcrafts.IMS1.policy), both shaped like ModemManager's
Voice action: the active local session and root, not an ssh login, an
inactive session or a system service account. Reads (status, the call
list) stay open, as ModemManager's are to every local account, and the
call signals reach them all; the message signals go to the
connections Subscribe admitted through the same gate, a submission's
outcome also to the connection that called Send.
GLib, so not part of the GLib-free imsd-core.
*/
@ -25,8 +29,6 @@ import std;
namespace imsd::bus {
constexpr const char* VoiceAction = "net.catcrafts.IMS1.Voice";
// CheckAuthorization's AllowUserInteraction, as ModemManager passes it: a
// rule an administrator sets to auth_self prompts through the session's
// polkit agent.
@ -37,6 +39,7 @@ struct Pending {
GDBusInterfaceMethodCallFunc body;
const char* deniedError;
void (*log)(std::string_view);
const char* action;
};
void OnCheck(GObject* src, GAsyncResult* res, gpointer data) {
@ -60,7 +63,7 @@ void OnCheck(GObject* src, GAsyncResult* res, gpointer data) {
return;
}
std::string why = err ? std::format("{}: polkit did not answer: {}", g_dbus_method_invocation_get_sender(inv), err->message)
: std::format("{} is not authorized for {}", g_dbus_method_invocation_get_sender(inv), VoiceAction);
: std::format("{} is not authorized for {}", g_dbus_method_invocation_get_sender(inv), p->action);
p->log(std::format("{} refused: {}", g_dbus_method_invocation_get_method_name(inv), why));
g_dbus_method_invocation_return_dbus_error(inv, p->deniedError, why.c_str());
if (err) g_error_free(err);
@ -70,14 +73,20 @@ void OnCheck(GObject* src, GAsyncResult* res, gpointer data) {
export namespace imsd::bus {
// The polkit actions: call control, and messaging — sending a short
// message over IP and subscribing to the message signals.
inline constexpr char VoiceAction[] = "net.catcrafts.IMS1.Voice";
inline constexpr char MessagingAction[] = "net.catcrafts.IMS1.Messaging";
// Off for a --session run: the session bus has no polkit, and its callers
// are the owner's own processes.
inline bool AuthorizeCalls = true;
// Run `body` for the call `inv` once polkit allows its sender
// net.catcrafts.IMS1.Voice; otherwise answer `deniedError` and log why. The
// check is asynchronous — nothing else on the main loop waits for it.
void Authorize(GDBusMethodInvocation* inv, GDBusInterfaceMethodCallFunc body, const char* deniedError, void (*log)(std::string_view)) {
// Run `body` for the call `inv` once polkit allows its sender `action`
// (net.catcrafts.IMS1.Voice unless told otherwise); otherwise answer
// `deniedError` and log why. The check is asynchronous — nothing else on
// the main loop waits for it.
void Authorize(GDBusMethodInvocation* inv, GDBusInterfaceMethodCallFunc body, const char* deniedError, void (*log)(std::string_view), const char* action = VoiceAction) {
GVariantBuilder subject;
g_variant_builder_init(&subject, G_VARIANT_TYPE("a{sv}"));
g_variant_builder_add(&subject, "{sv}", "name", g_variant_new_string(g_dbus_method_invocation_get_sender(inv)));
@ -86,21 +95,22 @@ void Authorize(GDBusMethodInvocation* inv, GDBusInterfaceMethodCallFunc body, co
g_dbus_connection_call(g_dbus_method_invocation_get_connection(inv), "org.freedesktop.PolicyKit1",
"/org/freedesktop/PolicyKit1/Authority", "org.freedesktop.PolicyKit1.Authority",
"CheckAuthorization",
g_variant_new("((sa{sv})sa{ss}us)", "system-bus-name", &subject, VoiceAction, &details, AllowUserInteraction, ""),
g_variant_new("((sa{sv})sa{ss}us)", "system-bus-name", &subject, action, &details, AllowUserInteraction, ""),
G_VARIANT_TYPE("((bba{ss}))"), G_DBUS_CALL_FLAGS_NONE, G_MAXINT, nullptr, OnCheck,
new Pending{ inv, body, deniedError, log });
new Pending{ inv, body, deniedError, log, action });
}
// A vtable method handler for `Body` that lets `IsRead` methods through and
// puts every other method — call control, and anything added later — behind
// Authorize.
template <GDBusInterfaceMethodCallFunc Body, bool (*IsRead)(std::string_view), const char* DeniedError, void (*Log)(std::string_view)>
// Authorize for `Action` (the Voice action unless the interface names its
// own, as the Messaging interface does).
template <GDBusInterfaceMethodCallFunc Body, bool (*IsRead)(std::string_view), const char* DeniedError, void (*Log)(std::string_view), const char* Action = VoiceAction>
void Gated(GDBusConnection* conn, const gchar* sender, const gchar* path, const gchar* iface, const gchar* method, GVariant* params, GDBusMethodInvocation* inv, gpointer user) {
if (!AuthorizeCalls || IsRead(method)) {
Body(conn, sender, path, iface, method, params, inv, user);
return;
}
Authorize(inv, Body, DeniedError, Log);
Authorize(inv, Body, DeniedError, Log, Action);
}
} // namespace imsd::bus

View file

@ -18,7 +18,7 @@ url="https://forgejo.catcrafts.net/Catcrafts/imsd"
arch="aarch64"
license="GPL-3.0-only"
# the media leg dlopen's the AMR-WB codecs; pw-record/pw-play drive PipeWire;
# polkit answers the daemons' call-control check (ImsdBus)
# polkit answers the daemons' call-control and messaging checks (ImsdBus)
depends="modemmanager libc++ opencore-amr vo-amrwbenc pipewire-tools polkit"
# versioned provides = imsd satisfies soc-qcom-modem's 81voltd dependency AND
# excludes the real package: 81voltd serves the modem's own ims-PDN requests,

View file

@ -13,7 +13,9 @@
</policy>
<!-- Any local account may reach imsd: the dialer shim runs as the session
account, whatever it is called. imsd itself decides who may place,
answer or end a call — polkit's net.catcrafts.IMS1.Voice
answer or end a call, or send short messages and subscribe to the
message signals — polkit's
net.catcrafts.IMS1.Voice and net.catcrafts.IMS1.Messaging
(net.catcrafts.IMS1.policy: the active local session). Owning the name
stays root's. -->
<policy context="default">

View file

@ -4,12 +4,14 @@
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<!-- Call control on imsd (net.catcrafts.IMS1) and imsd-ofonod (org.ofono):
both daemons ask polkit about this action before they place, answer or
end a call for a caller. The defaults are ModemManager's Voice action as
the permissive polkit build ships it (the strict build has
allow_active auth_self_keep): the active local session, not an ssh
login, an inactive session or a system service account. root is always
allowed.
both daemons ask polkit about the Voice action before they place,
answer or end a call for a caller; imsd asks about the Messaging action
before it sends a short message over IP for one or lets one hear the
message signals (Subscribe). The defaults are
ModemManager's Voice action as the permissive polkit build ships it
(the strict build has allow_active auth_self_keep): the active local
session, not an ssh login, an inactive session or a system service
account. root is always allowed.
Install: /usr/share/polkit-1/actions/net.catcrafts.IMS1.policy -->
<policyconfig>
<vendor>Catcrafts</vendor>
@ -23,4 +25,13 @@
<allow_active>yes</allow_active>
</defaults>
</action>
<action id="net.catcrafts.IMS1.Messaging">
<description>Send short messages over IMS</description>
<message>System policy prevents sending short messages.</message>
<defaults>
<allow_any>no</allow_any>
<allow_inactive>no</allow_inactive>
<allow_active>yes</allow_active>
</defaults>
</action>
</policyconfig>

View file

@ -19,7 +19,14 @@
// fresh backoffs, the throttle schedule, Retry-After, which waits a Dial
// may cut short, when the old registration counts as gone, the holds a
// restart takes over (Holds/Restore), and a binding the network terminated
// (OnBindingTerminated). Then SMS over IP: SmsOutbound through a
// (OnBindingTerminated). Then SMS over IP: the status-report book
// (StatusReportBook with SameRecipient — a word for the whole message: a two-segment
// message delivered with its last segment, a permanent failure the last
// word, pending kept, another recipient no match, a reused TP-MR, a
// message forgotten whole by its id), the order of one message's words
// (SmsWordOrder: the submission's first, a report's after sent) and the
// ids (RunToken, SentSmsId, ReceivedSmsId);
// SmsOutbound through a
// submission (the MESSAGE with the RP-DATA, its 202, the RP-ACK -> sent; a
// refused final, an RP-ERROR with its cause, the final's wait and the
// report's running out, a failed send, two segments with consecutive
@ -31,9 +38,10 @@
// In-Reply-To, a concatenated pair whole once, a status report, a submit
// report routed to the message in flight, 488 for one that is not ours, an
// unusable TPDU acknowledged with an RP-ERROR, a body that is no RP
// message, a page-mode text 200'd and logged), and RecentTransactions (a
// retransmitted request gets its final again, for 32 s; no branch, no
// match). Pure reducers, no I/O.
// message, a page-mode text 200'd and logged, a short message while SMS
// over IP is off refused with 480), and RecentTransactions (a retransmitted
// request gets its final again, for 32 s; no branch, no match). Pure
// reducers, no I/O.
import std;
import Imsd;
@ -1251,6 +1259,7 @@ int main() {
const auto kpnSc = *imsd::util::FromHex("07911356131313f3");
Context c = MakeCtx();
c.aor = "sip:+31611111111@ims.mnc001.mcc001.3gppnetwork.org";
c.smsOverIp = true;
const SmsOutbound::Params p{"+31612345678", "Hello", "sip:+31653131313@ims.mnc001.mcc001.3gppnetwork.org;user=phone", kpnSc, 10, 20, 0x2A, 0xA9, false};
// a one-segment message: MESSAGE, 202, RP-ACK -> sent
@ -1374,6 +1383,80 @@ int main() {
Check(st && st->state == "failed" && st->reason.contains("no service centre"), "outbound: no service centre fails at once");
}
// the status-report book: a word for the whole message, by TP-MR and recipient
{
using Word = StatusReportBook::Word;
StatusReportBook book;
const std::vector<std::uint8_t> two{10, 11}, one{12}, eleven{11};
book.Sent("ims-sms-1", "+31612345678", two);
book.Sent("ims-sms-2", "0612345679", one);
Check(book.Report(10, "+31612345678", 0x00).word == Word::SegmentDelivered && book.Report(11, "+31612345678", 0x00).word == Word::Delivered && book.Size() == 1, "book: a two-segment message is delivered with its last segment");
Check(book.Report(10, "+31612345678", 0x00).word == Word::NoMessage, "book: a delivered TP-MR is forgotten");
Check(book.Report(12, "+31612345670", 0x00).word == Word::NoMessage && book.Size() == 1, "book: another recipient is no match");
Check(book.Report(12, "+31612345679", 0x30).word == Word::Pending && book.Size() == 1, "book: a temporary status is pending, the entry kept");
Check(book.Report(12, "+31612345679", 0x00).word == Word::Delivered && book.Size() == 0, "book: then delivered");
book.Sent("ims-sms-3", "+31612345678", two);
const auto f = book.Report(11, "+31612345678", 0x41);
Check(f.word == Word::Failed && f.id == "ims-sms-3" && book.Size() == 0 && book.Report(10, "+31612345678", 0x00).word == Word::NoMessage, "book: a permanent failure is the message's last word; a later segment finds nothing");
book.Sent("ims-sms-4", "+31612345678", two);
book.Sent("ims-sms-5", "+31612345678", eleven);
Check(book.Report(10, "+31612345678", 0x00).word == Word::NoMessage && book.Report(11, "+31612345678", 0x00).id == "ims-sms-5" && book.Size() == 0, "book: a TP-MR reused before its word forgets the older message whole");
book.Sent("ims-sms-8", "+31612345678", one);
Check(book.Report(12, "+31612345678", 0x62).word == Word::Failed && book.Size() == 0, "book: a temporary error after which the SC has stopped trying is a failure");
book.Sent("ims-sms-9", "+31612345678", one);
Check(book.Report(12, "+31612345678", 0x80).word == Word::Failed && book.Size() == 0, "book: a status with bit 7 set is reserved, so a failure — not the delivered its low bits spell");
book.Sent("ims-sms-10", "+31612345678", one);
Check(book.Report(12, "+31612345678", 0x26).word == Word::Failed && book.Size() == 0, "book: a reserved value among the still-trying ones is a failure, not pending");
book.Sent("ims-sms-11", "+31612345678", one);
Check(book.Report(12, "+31612345678", 0x03).word == Word::Failed && book.Size() == 0, "book: a reserved value among the completed ones is a failure, not delivered");
book.Sent("ims-sms-12", "+31612345678", one);
Check(book.Report(12, "+31612345678", 0x10).word == Word::Delivered && book.Size() == 0, "book: an SC's own completed value is delivered");
}
// the book forgets a message whole when its submission failed
{
using Word = StatusReportBook::Word;
StatusReportBook book;
const std::vector<std::uint8_t> two{10, 11}, one{12};
book.Sent("ims-sms-6", "+31612345678", two);
book.Sent("ims-sms-7", "+31612345678", one);
book.ForgetMessage("ims-sms-6");
Check(book.Size() == 1 && book.Report(10, "+31612345678", 0x30).word == Word::NoMessage && book.Report(11, "+31612345678", 0x00).word == Word::NoMessage, "book: a forgotten message's reports match nothing");
book.ForgetMessage("ims-sms-99");
Check(book.Size() == 1, "book: forgetting an unknown id changes nothing");
Check(book.Report(12, "+31612345678", 0x00).word == Word::Delivered, "book: the other message is still on record");
}
// the order of one message's words: the submission's first, a report's after `sent`
{
SmsWordOrder order;
auto now = order.Report("ims-sms-1", SmsStateDelivered, "received by the SME", false);
Check(now.size() == 1 && now[0].id == "ims-sms-1" && now[0].state == "delivered" && !order.Holding(), "order: a report on a message whose submission ended is posted at once");
Check(order.Report("ims-sms-2", SmsStateDeliveryPending, "congestion", true).empty() && order.Holding(), "order: a report on the message in flight is held");
auto e = order.Submission("ims-sms-2", SmsStateSent, "2 segment(s) accepted by the SC");
Check(e.post.size() == 2 && e.post[0].state == "sent" && e.post[1].state == "delivery-pending" && e.post[1].reason == "congestion" && !e.forget && !order.Holding(), "order: sent, then the held word");
e = order.Submission("ims-sms-3", SmsStateSent, "1 segment(s) accepted by the SC");
Check(e.post.size() == 1 && e.post[0].state == "sent" && !e.forget, "order: sent with nothing held");
order.Report("ims-sms-4", SmsStateDeliveryPending, "congestion", true);
order.Report("ims-sms-4", SmsStateDelivered, "received by the SME", true);
e = order.Submission("ims-sms-4", SmsStateFailed, "no submit report for segment 2/2 within 40 s of the final");
Check(e.post.size() == 2 && e.post[0].state == "sent" && e.post[0].reason.starts_with("every segment reported delivered by the SC; no submit report") && e.post[1].state == "delivered" && e.post[1].reason == "received by the SME" && !e.forget, "order: a failed after every segment was reported delivered is sent and delivered (the latest held word counts)");
order.Report("ims-sms-5", SmsStateDeliveryPending, "congestion", true);
e = order.Submission("ims-sms-5", SmsStateFailed, "segment 2/2 refused by the SC: RP cause 38");
Check(e.post.size() == 1 && e.post[0].state == "failed" && e.post[0].reason.starts_with("segment 2/2 refused") && e.forget && !order.Holding(), "order: a failed drops the held word and forgets the message's TP-MRs");
e = order.Submission("ims-sms-6", SmsStateFailed, "no service centre");
Check(e.post.size() == 1 && e.post[0].state == "failed" && e.forget, "order: a failed with nothing held is posted and forgets");
order.Report("ims-sms-7", SmsStateDelivered, "received by the SME", true);
e = order.Submission("ims-sms-8", SmsStateSent, "1 segment(s) accepted by the SC");
Check(e.post.size() == 1 && order.Holding(), "order: another message's submission leaves the held word alone");
}
// a status report's recipient against the number a message went to
Check(SameRecipient("+31612345678", "+31612345678") && SameRecipient("0612345678", "+31612345678") && SameRecipient("+31 6 1234 5678", "31612345678") && SameRecipient("0031612345678", "+31612345678") && SameRecipient("6125551234", "+16125551234"), "SameRecipient: equal digits, or a number dialled with a trunk 0, with 00 or without its country code against its international form");
Check(!SameRecipient("+31612345678", "+31687654321") && !SameRecipient("+31612345678", "+49612345678") && !SameRecipient("112", "+31612345112") && !SameRecipient("1266", "+31612341266") && !SameRecipient("", "+31612345678"), "SameRecipient: another number, +31 against +49, a short code as a suffix, an empty one");
// the ids of the Messaging interface: the run's token first after the prefix, so two runs with different tokens give different ids whatever the clock reads
{
Check(RunToken(0x7f3a9c21u) == "7f3a9c21" && RunToken(0) == "00000000" && RunToken(0xffffffffu) == "ffffffff", "RunToken: eight hex digits, zero-padded");
Check(SentSmsId("7f3a9c21", 1793474321, 3) == "ims-sms-7f3a9c21-1793474321-3" && ReceivedSmsId("7f3a9c21", 1793474321, 1) == "ims-sms-in-7f3a9c21-1793474321-1", "the sent and the received shape");
Check(ReceivedSmsId("7f3a9c21", 42, 1) != ReceivedSmsId("0b1d2e3f", 42, 1) && SentSmsId("7f3a9c21", 42, 1) != SentSmsId("0b1d2e3f", 42, 1), "two runs with different tokens: their ids differ at the same second and counter");
}
// inbound MESSAGEs, as the IP-SM-GW sends them
auto inbound = [](std::string_view bodyHex, std::string_view extraHeaders = "") {
auto b = *imsd::util::FromHex(bodyHex);
@ -1594,6 +1677,23 @@ int main() {
const std::string branchWithParams = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/UDP [2001:db8::105]:6000;branch=z9hG4bKabc;_aluscr_\r\nCall-ID: c@net\r\nCSeq: 7 MESSAGE\r\nContent-Length: 0\r\n\r\n";
Check(RecentTransactions::Key(branchWithParams) == "c@net|7 MESSAGE|z9hG4bKabc", "recent: the branch ends at the next parameter");
}
// SMS over IP off: a short message the network sends anyway is refused, a page-mode text still 200'd
{
imsd::util::Rng rng(85);
Reassembler re;
Context off = MakeCtx();
off.aor = c.aor;
const std::string_view offeredHex = "011107911356131313F3001E040B911346610089F60000208062917314080CC8F71D14969741F977FD07";
const std::string offered = inbound(offeredHex);
auto r = OnSmsMessage(off, rng, offered, re, nullptr, 8.0);
Check(r.response.starts_with("SIP/2.0 480 Temporarily Unavailable\r\n") && r.response.contains("Call-ID: in-011107@net\r\n"), "off: a short message is refused with 480");
Check(!hasSms(r.actions, SmsAction::Type::Received) && !hasSms(r.actions, SmsAction::Type::SendClient) && r.reportCallId.empty() && !r.rp && re.Pending() == 0, "off: nothing to the bus, no delivery report, nothing parsed");
const auto* log = findSms(r.actions, SmsAction::Type::Log);
Check(log && log->text.ends_with("while SMS_OVER_IMS is off: 480") && !log->text.contains("How are you") && !log->text.contains(std::string_view(offered).substr(offered.find("\r\n\r\n") + 4)) && !log->text.contains(imsd::util::ToHex(*imsd::util::FromHex(offeredHex))), "off: logged with a line that ends at the 480, without the text, the body or its hex");
const std::string plain = "MESSAGE sip:me@ims SIP/2.0\r\nVia: SIP/2.0/TCP [2001:db8::105]:6000;branch=z9hG4bKn3\r\nFrom: <sip:x@ims>;tag=1\r\nTo: <sip:me@ims>\r\nCall-ID: t2@net\r\nCSeq: 1 MESSAGE\r\nContent-Type: text/plain\r\nContent-Length: 2\r\n\r\nhi";
auto r2 = OnSmsMessage(off, rng, plain, re, nullptr, 9.0);
Check(r2.response.starts_with("SIP/2.0 200 OK") && hasSms(r2.actions, SmsAction::Type::Log), "off: a page-mode text is still 200'd and logged");
}
}
if (Failures == 0) std::println("Engine: all tests passed");