imsd, engine, packaging: received short messages are kept until an app deletes them — List and Delete on the Messaging interface

A received message went to a bus signal and nowhere else but DUMP_SIP's
opt-in raw dump of the last MESSAGE outside a call's dialog, so with no
app listening it was gone. It is now written
to <state dir>/sms/<id>.msg — mode 0600 in a 0700 directory, whole to a
.tmp, linked to its name and the directory fsynced; the engine's FormatStoredSms/ParseStoredSms
record codec, pinned by tests/Engine — before the signal, and stays until
Delete. List hands over the records it can read, by arrival second, then
within a run by sequence number. The record is named by
the message's id and published with link(2), which refuses a name the
store already holds, so the next number is tried and nothing is
replaced. link(2) refuses only a name the store
still holds: a client that deleted the daemon's copy after importing it
freed the name, and the run's token in the id is what keeps a later run
from giving it to another text, unless that run draws the same token and
meets the same second and number. The two methods sit behind the
Messaging polkit action with Send, and the policy text says so; GetStatus,
the open read, does not count the store, since the count would tell any
local account when a text arrived, and the unit makes the state
directory 0700 (StateDirectoryMode) for the same reason.

For a message the store cannot write the delivery report stays an
RP-ACK: the signal is its only delivery, and the journal says so. The
protocol's refusal —
RP-ERROR "memory capacity exceeded", TS 24.011 cause 22 — is half of a
mechanism: the other half, the UE's memory-available notification
(RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment
would also lose its set. The
refusal was built and benched on KPN — the store made unwritable, the
text refused; it came again five minutes later, the store writable by
then, and a later text came at once — and taken out again; no other core
is measured. It returns
with the notification and a probe of the store. The record's directory is
fsynced after the link, its result unchecked like the directory open's; a
concatenated text's earlier segments are held in memory, not in the
store, until the set is whole (§7.9).

Tested on the dev phone (KPN): a text from the phone to its own number on
2026-10-18 23:30, under this publish (a build of this range ahead of this
history, 735dfda, whose StoreReceivedSms has this commit's code), stored
as
ims-sms-in-1792359045-1, an id of that build's shape; the store directory listed on 2026-10-19 holds
that record and no temporary (the fp6 journal's 2026-10-17-sms-over-ip-bench
capture: r20-tip-smoke-2026-10-18-2329, r22-store-backup-and-delete-proof).
The Exists path has no bench: a run's own ids never repeat. The refusal's bench (store-refused-2026-10-18-0136): the store directory
made immutable at 01:37, a text to the phone's own number not stored
(EPERM on its .tmp), the RP-ERROR answered 202, the text delivered again
at 01:42:56 under its first SC time stamp, stored and acknowledged, a later
text not held. Not on the phone: List's skip of a file that is no record
and four of Delete's answers ran on the workstation, in dev mode on a
private session bus, on this commit's host build (2026-11-19; its sha256
begins 8fdd9192866645d5): the skip, with its journal line; InvalidArgs
for a string that is no id; IOError, the
record still listed, for a record in a store directory made unwritable;
the removal once it was writable; FileNotFound for an id with no record.

The engine's start sweeps the .tmp names a crash left — one it cannot
unlink stays, unreported — so a deleted text's second name goes at the
next engine start that can remove it (Delete leaves .tmp
names alone). A Delete whose removal fails answers IOError with the system's
reason, and a record that is there is kept; FileNotFound is left for a
removal that found no file.
List's order breaks a tie between two texts of one run in one second by
the sequence number (pinned), not by the id as text.
This commit is contained in:
Jorijn van der Graaf 2026-10-17 00:24:50 +02:00
commit d0cfaf712d
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
10 changed files with 475 additions and 77 deletions

5
.gitignore vendored
View file

@ -10,5 +10,8 @@ imsd-*.tar.gz
*.stats
imsreg.state
# SMS over IP's state: the next TP-MR (and its .tmp)
# SMS over IP's state: the next TP-MR, and the store's records, the texts
# with their numbers (and a .tmp of either)
sms-tpmr*
*.msg
*.msg.tmp

196
AGENTS.md
View file

@ -19,7 +19,7 @@ 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, and since 1.2.0 short messages over IMS (TS 24.341: the SIP MESSAGE
carrying an RP-DATA, the Messaging interface —
carrying an RP-DATA, a store for what arrives, 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.
@ -47,7 +47,7 @@ PipeWire. The verified device/carrier combinations are in the README.
| `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 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-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 (§7.9): `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); `StoredSms` with `FormatStoredSms`/`ParseStoredSms`, the record codec of the received-message store, and `StoredSmsBefore`, `List`'s order. |
| `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 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. |
@ -63,7 +63,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 — and, of SMS over IP's
state, `sms-tpmr*` (the next TP-MR).
state, `sms-tpmr*` (the next TP-MR), `*.msg` and `*.msg.tmp` (the store's
records, the texts with their numbers).
## 3. Build products
@ -158,7 +159,12 @@ 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.
and `StatusReportBook`, all with tests. The received-message store (§7.9)
keeps in the shell, among others, the `link(2)` publish and its retry with the next id,
the sweep of `.tmp` files at the engine's start, `Delete`'s id check and its
answers by the removal's outcome, `List`'s skip of a file that is no record and the delivery
report a store failure leaves unchanged; the record codec and `List`'s
order are the core's, with tests.
## 4. Building
@ -387,7 +393,11 @@ What the suites pin:
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;
counter, the longest received id no longer than 64 bytes;
and the store's record codec (`FormatStoredSms`/`ParseStoredSms`: a
full record round trip, defaults for absent keys, a value that does not
parse or a missing id refused) and `List`'s order (`StoredSmsBefore`: the arrival
second, then within a run the sequence number — -9 before -10);
and `RecentTransactions`: a retransmitted request gets its final again,
for 32 s (`TimerJ`); no branch, no match.
@ -584,25 +594,32 @@ Rules:
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
parsed, stored, the RP-ACK delivery report sent and answered 202,
`List` reading them back); 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
`mt-0123-duplicate-message-in`, came over UDP from the P-CSCF) and became
two stored texts and two delivery reports, one of them refused 488, which is where the retransmission
absorption (`RecentTransactions`) came from; the
store surviving the restart that installed c57765a, a bench build ahead of
this history carrying the retransmission absorption (between 01:26 and
01:33: seven records before it, the duplicate's `Delete` over the live
bus at 01:28 leaving six — `r22-store-backup-and-delete-proof` and
`r22-sent-texts-2026-10-17-from-the-session-transcript`); 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
segments (set 174, 159 + 102 bytes) reassembled byte-identical (SC time
stamp 01:40:26, the whole logged at 01:40:28; the text sent against the stored record,
`r22-sent-texts-2026-10-17-from-the-session-transcript` and
`r22-store-backup-and-delete-proof`); 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
own, the ✓ arrived as a one-character UCS-2 text (its stored record,
`r22-store-backup-and-delete-proof`); 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
— one stored text, 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
@ -628,7 +645,13 @@ Rules:
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
interface that does not register (§7.8), the store's Exists path (a name the store already holds: the next id
tried), a store failure under this code (`NOT
stored`, the signal still out, the RP-ACK kept — the one bench,
`store-refused-2026-10-18-0136`, ran the build that answered RP-ERROR,
since taken out; the start sweep itself was reached,
`r14-tip-sanity-2026-10-18-0408`: `sms store: 1 stale temporary file(s)
removed`). 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
@ -636,10 +659,8 @@ Rules:
(`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
flow could not send, `LoadSmsParameters`' refusals, the MESSAGE inside a call's dialog, the queue's two, the store'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
@ -647,7 +668,13 @@ Rules:
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).
answered); the store's `List`/`Delete` on the same bus
(2026-10-17), and in dev mode on a private session bus (2026-11-19)
`List` skipping a file that is no record, with its journal line, and
four of `Delete`'s answers: `InvalidArgs` for a string that is no id;
`IOError` for a record in a store directory
made unwritable, the record still listed; the removal once it was
writable; `FileNotFound` for an id with no record.
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
@ -728,9 +755,9 @@ 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`, sending a short message over IP and subscribing
to the message signals `net.catcrafts.IMS1.Messaging`
(`packaging/net.catcrafts.IMS1.policy`, both
`net.catcrafts.IMS1.Voice`, sending a short message over IP, subscribing
to the message signals, listing and deleting the stored ones
`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`,
@ -745,7 +772,10 @@ 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 Messaging interface's
`Subscribe` keeps its subscriber set on the main thread as well (§7.9).
`Subscribe` keeps its subscriber set on the main thread as well, and
`List` and `Delete` read and unlink the received-message store there while
the engine thread writes it — safe through the `.tmp` + `link(2)` publish
(§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
@ -1359,6 +1389,7 @@ account `user`, its old default.
| `/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) |
| `/var/lib/imsd/sms/<id>.msg` | imsd | received short messages until an app deletes them (§7.9, `List`/`Delete`): the texts, mode 0600 in a 0700 directory |
| `$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
@ -1511,6 +1542,12 @@ Lines the operator (and the scripts) look for, all prefixed `imsd: `:
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.
- The store (§7.9): `sms <id>: stored (N kept until an app deletes them)`;
`sms store: <id> exists already; taking the next id`; `sms store: N stale
temporary file(s) removed` (at the engine's start); `sms <id>: NOT
stored — <why>; the bus signal is its only delivery`; `sms <id>: deleted
from the store`; `sms <id>: not deleted from the store: <reason>`; `sms
store: <path> is no record; skipped`.
- `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
@ -1578,6 +1615,53 @@ folded onto further lines the first is read (7.3.1 allows both).
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 store.** A received message is written to
`/var/lib/imsd/sms/<id>.msg` (mode 0600, the directory 0700; whole to a
`.tmp` beside it, then `link(2)`ed to its name) before the bus hears
`Received`, and stays until `Delete` — the daemon is the message store
the way the modem's memory is for ModemManager, so a whole text that
arrives while no app runs, or none exists, is not lost (a concatenated
one's earlier segments wait in memory until the set is whole — the
**Receiving** bullet below); `List` is an app's way
in. The record is key=value lines, the sender, the text, the data and
the PDU as hex (`FormatStoredSms`/`ParseStoredSms` in `Imsd:Engine`,
pinned by `tests/Engine`); the id is this run's token (eight hex digits
drawn once at start), the arrival's epoch second and a per-start
sequence number — another run gives the same id only with the same
token, second and number — and the record is published with `link(2)`,
which refuses a name the store already holds — the next number is
tried, never a replacement. A `.tmp` a crash left — an orphan, or a
record's second name — is removed when the engine next starts (`sms store: N stale
temporary file(s) removed`; a start that exits before the engine runs
leaves it, and one the sweep cannot unlink stays unreported); `Delete`
leaves `.tmp` names alone. `received` is that wall clock: before a boot's first time
sync it reads 1970, and `List`'s oldest-first order follows it, so an
app that cares orders by the SC's `timestamp`. A store failure is logged,
the signal still goes out, and the delivery report stays an RP-ACK —
the message is then the listener's or nobody's. Not the protocol's
refusal, RP-ERROR cause 22 "memory capacity exceeded", because it is
half of a mechanism — the other half, the UE's memory-available
notification (RP-SMMA, TS 24.341 5.3.2.5), imsd does not send; a refused last segment would also
lose its set, since the reassembler forgets a set the moment it is
whole. The refusal was built and benched on KPN (2026-10-18: the store
made unwritable, the text refused; the same text came again five
minutes later, the store writable by then, and was stored, and a later
text came at once)
and taken out again; no other core is measured. The refusal with the
notification and a probe of the store, and a reassembly that survives a
refused segment, are a later release's work. No cap on the count. Why a store at all
(Jorijn, 2026-10-17, on the recommendation): the bus queues nothing for
an absent listener; the 200 goes out first, then the store write, then
`Received` is handed to the bus thread and after that the RP-ACK, when one goes — the
signal goes whenever the main loop runs, and neither waits on a listener —
a signal
alone loses
every text that arrives between boot and the session, during an app's
restart or upgrade, or on a phone whose app is no daemon. The
storage-free alternative — refuse delivery with RP-ERROR cause 22
(memory capacity exceeded) while no app is attached and send RP-SMMA
when one appears — is
protocol-correct but needs an attach registry; not taken.
- **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
@ -1627,8 +1711,8 @@ folded onto further lines the first is read (7.3.1 allows both).
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
an upgrade's, a `Restart=` — loses the set; a store of parts is a later release's work,
with the refusal of the store bullet) 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,
@ -1673,25 +1757,30 @@ folded onto further lines the first is read (7.3.1 allows both).
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
200. The journal names a received message's sender, size and time,
not its text (§12 has the cases in which a text does reach it); the text
is in the store (the store bullet above) until
an app deletes it — unless it was not stored (`NOT stored`, the
store bullet). 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
and not show, is stored and 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 stored 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
additive to the frozen interface; `Send`, `Subscribe`, `List` and `Delete` 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.
stand in for; `imsd-messages`, the app built for this interface, speaks
it (its first run against imsd on the dev phone: 2026-10-18 01:21–01:36)
— its flatpak on the `flatpak.catcrafts.net` remote accompanies this
release.
## 8. D-Bus ABI and desktop integration
@ -1815,21 +1904,24 @@ busctl --user call org.ofono / org.ofono.Manager GetModems
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.
its name). This one is frozen as of 1.2.0 as well: an app outside this
repository consumes it (`imsd-messages`). 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) |
| `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). No count of the store: `GetStatus` is the open read, and a count would tell any local account when a text arrived; `List`'s length is behind the gate |
| `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 |
| `List()` | `→ a(sa{sv})`: the stored messages it can read, by the arrival second on the phone's wall clock, then within a run the sequence number — oldest first on a synced clock (a 1970 second before the first time sync sorts first; the SC's `timestamp` is the chronology, §7.9) — each the id and the same dictionary `Received` carries (its `received` the arrival time) |
| `Delete(id)` | `s`: removes a stored message; `org.freedesktop.DBus.Error.InvalidArgs` for an empty string, one over 64 bytes or one with a character other than an ASCII letter, an ASCII digit or `-`; `org.freedesktop.DBus.Error.FileNotFound` for any other string when the removal found no file; `org.freedesktop.DBus.Error.IOError`, with the system's reason, when the removal failed — a record that is there is kept |
| `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);
`Send`, `Subscribe`, `List` and `Delete` 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
@ -2019,14 +2111,16 @@ 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.
SMS over IP's state stays out likewise: `sms-tpmr`, the next TP-MR, and
the store's `*.msg`, the texts with their numbers.
## 12. Security considerations
- imsd runs as root (xfrm, qmicli). Its attack surface on the bus is the
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
Messaging action; `Delete` unlinks a record under `/var/lib/imsd/sms` as
root behind it). 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
@ -2075,7 +2169,11 @@ only the imsd side of its bus choice.
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.
the TPDU's TP-OA, decoded and unchecked;
the store under `/var/lib/imsd/sms` holds the texts, 0600 in a 0700
directory under a 0700 state directory (`StateDirectoryMode`: even the
store directory's mtime would tell another account when a text arrived),
until an app deletes them.
`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 —

View file

@ -69,13 +69,13 @@ session and root may place, answer and end calls; an ssh login may not.
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.
centre or the one `SMSC` names, and receives texts the network delivers over IMS;
its store for received texts is `/var/lib/imsd/sms`, and a text in it stays
until a messaging app deletes it. Apps that read ModemManager, such as Spacebar and
Chatty, do not see texts that arrive this way; `imsd-messages`, the app built
for imsd's `net.catcrafts.IMS1.Messaging` interface, shows them. The details are
in AGENTS.md: the behaviour and the store in §7.9, the interface in §8.4,
what was verified on which network in §5.
## Full config:
@ -155,10 +155,12 @@ gain a key.
| `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 |
| `List()` | `→ a(sa{sv})`: the stored messages it can read, by the arrival second on the phone's wall clock, then within a run the sequence number (a 1970 clock before the first time sync sorts first; the SC's `timestamp` is the real chronology), each the id and the dictionary `Received` carries |
| `Delete(id)` | `s`: removes a stored message |
| `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`.
`Send`, `Subscribe`, `List` and `Delete` are gated by polkit's `net.catcrafts.IMS1.Messaging`.
## License

View file

@ -833,6 +833,7 @@ struct Event {
StatusSnapshot status; // Registration/Status
std::string text; // Fatal, Idle
imsd::engine::SmsReceived sms; // SmsReceived
std::int64_t at = 0; // SmsReceived: when it arrived (epoch seconds)
};
GDBusConnection* DbusConn = nullptr;
@ -977,14 +978,114 @@ void EmitSignalTo(const std::string& destination, const char* name, GVariant* pa
g_dbus_connection_emit_signal(DbusConn, destination.c_str(), ObjPath, MessagingIface, name, params, nullptr);
}
// ---- the store of received messages (§7.9): one record file per message
// under <state dir>/sms, written by the engine thread as a message arrives
// and read, listed and deleted by the D-Bus thread (List/Delete, §8.4).
// A record is written whole to a .tmp beside it, fsynced, linked to its
// name with link(2) — which refuses a name already taken — and the .tmp
// removed, the directory fsynced after it, so a listing never sees a
// half-written one and nothing is replaced.
std::string SmsStoreDir() { return std::format("{}/sms", StateDir()); }
bool ValidSmsId(std::string_view id) {
if (id.empty() || id.size() > 64) return false;
for (char c : id)
if (!std::isalnum(static_cast<unsigned char>(c)) && c != '-') return false;
return true;
}
std::string SmsRecordPath(std::string_view id) { return std::format("{}/{}.msg", SmsStoreDir(), id); }
// The .tmp files a crash left (between the open and the link, or between
// the link and the unlink, when one is a record's second name): unlinked
// at the engine's start, before it takes its first message; the count is
// of those the unlink removed. A record whose second name goes keeps its
// inode.
int SweepSmsStore() {
std::error_code ec;
int n = 0;
for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) {
if (!e.is_regular_file() || e.path().extension() != ".tmp") continue;
if (unlink(e.path().c_str()) == 0) n++;
}
return n;
}
// Stores a received message under its id. Exists: the store already
// holds that name (a run's own ids never repeat); the caller takes the
// next id. Failed (with `why`): the directory or the
// file could not be made.
enum class StoreResult { Stored, Exists, Failed };
StoreResult StoreReceivedSms(const imsd::engine::StoredSms& r, std::string& why) {
std::error_code ec;
const std::filesystem::path dir = SmsStoreDir();
std::filesystem::create_directories(dir, ec);
if (ec) { why = std::format("{}: {}", dir.string(), ec.message()); return StoreResult::Failed; }
std::filesystem::permissions(dir, std::filesystem::perms::owner_all, std::filesystem::perm_options::replace, ec);
const std::string path = SmsRecordPath(r.id);
const std::string tmp = path + ".tmp";
const std::string text = imsd::engine::FormatStoredSms(r);
// a stale .tmp — a crash between link(2) and unlink(2) below — may be a
// record's second name: unlinked, never truncated (every .tmp is also
// swept at the engine's start, SweepSmsStore); close-on-exec, so no descriptor of this
// writer reaches a program imsd runs
unlink(tmp.c_str());
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
if (fd < 0) { why = std::format("{}: {}", tmp, std::strerror(errno)); return StoreResult::Failed; }
std::size_t done = 0;
while (done < text.size()) {
const ssize_t n = write(fd, text.data() + done, text.size() - done);
if (n < 0) { why = std::format("{}: {}", tmp, std::strerror(errno)); close(fd); unlink(tmp.c_str()); return StoreResult::Failed; }
done += static_cast<std::size_t>(n);
}
const int syncErr = fsync(fd) < 0 ? errno : 0;
const int closeErr = close(fd) < 0 ? errno : 0; // closed on every path
if (syncErr || closeErr) { why = std::format("{}: {}", tmp, std::strerror(syncErr ? syncErr : closeErr)); unlink(tmp.c_str()); return StoreResult::Failed; }
// link(2) publishes the name only if it is free — rename(2) would
// replace a record already there
if (link(tmp.c_str(), path.c_str()) < 0) {
const int e = errno;
unlink(tmp.c_str());
if (e == EEXIST) return StoreResult::Exists;
why = std::format("{} -> {}: {}", tmp, path, std::strerror(e));
return StoreResult::Failed;
}
unlink(tmp.c_str());
// the directory entry too: link(2) and unlink(2) are durable only with
// the directory's own fsync (its result, like the open's, is not checked:
// a failure here does not unstore the record)
if (int dfd = open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); dfd >= 0) { fsync(dfd); close(dfd); }
return StoreResult::Stored;
}
// The stored messages, oldest first: the `.msg` files, one that is no
// record skipped (logged when `log`).
std::vector<imsd::engine::StoredSms> LoadStoredSms(bool log = true) {
std::vector<imsd::engine::StoredSms> out;
std::error_code ec;
for (const auto& e : std::filesystem::directory_iterator(SmsStoreDir(), ec)) {
if (!e.is_regular_file() || e.path().extension() != ".msg") continue;
std::ifstream in(e.path(), std::ios::binary);
std::string text((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
auto r = imsd::engine::ParseStoredSms(text);
if (!r) { if (log) Log(std::format("sms store: {} is no record; skipped", e.path().string())); continue; }
out.push_back(std::move(*r));
}
std::sort(out.begin(), out.end(), imsd::engine::StoredSmsBefore);
return out;
}
// The records in the store (what List would hand over), not the files.
std::size_t StoredSmsCount() { return LoadStoredSms(false).size(); }
// a received short message as the Messaging interface's a{sv} (§8.4)
GVariant* SmsVariant(const imsd::engine::SmsReceived& m) {
GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt) {
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}", "received", g_variant_new_int64(receivedAt));
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));
@ -1040,7 +1141,7 @@ gboolean OnIdleEvent(gpointer data) {
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)));
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms, ev->at)));
break;
case Event::Type::SmsState: {
std::set<std::string> to = Subscribers;
@ -1185,6 +1286,7 @@ public:
}
void Run() {
if (const int n = SweepSmsStore(); n > 0) Log(std::format("sms store: {} stale temporary file(s) removed", n));
if (auto h = LoadHolds(pdnLocal_)) {
recovery_.Restore(Boot(), *h);
auto kept = recovery_.Holds(Boot()); // what the policy took over: the file's values after the clamp
@ -2784,13 +2886,32 @@ private:
for (const auto& w : e.post) PostSmsState(w.id, w.state, w.reason);
}
// A received message: stored first, then the bus hears it. The id is
// this run's token, the arrival's epoch second and a per-start sequence
// number — the token tells runs apart where the clock cannot; a name
// the store already holds is never replaced: the store refuses it and
// the next number is tried, a thousand at most. A store failure is logged and the signal still goes
// out — the message is then the listener's or nobody's, and the
// delivery report stays an RP-ACK: the protocol's refusal (RP-ERROR
// cause 22) is half of a mechanism whose other half, the
// memory-available notification, imsd does not send yet (AGENTS.md §7.9).
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->at = NowEpoch();
ev->sms = m;
std::string why;
StoreResult stored = StoreResult::Failed;
for (int tries = 0; tries < 1000; tries++) {
ev->uni = imsd::engine::ReceivedSmsId(smsRun_, ev->at, ++smsInSeq_);
stored = StoreReceivedSms({ev->uni, ev->at, m}, why);
if (stored != StoreResult::Exists) break;
Log(std::format("sms store: {} exists already; taking the next id", ev->uni));
}
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()));
if (stored == StoreResult::Stored) Log(std::format("sms {}: stored ({} kept until an app deletes them)", ev->uni, StoredSmsCount()));
else Log(std::format("sms {}: NOT stored — {}; the bus signal is its only delivery", ev->uni, stored == StoreResult::Exists ? "a thousand names taken" : why));
PostEvent(std::move(ev));
}
void PostSmsState(const std::string& id, std::string_view state, std::string_view reason) {
@ -3083,6 +3204,8 @@ constexpr const char* IntrospectionXml = R"xml(
<arg type="s" name="id" direction="out"/>
</method>
<method name="GetStatus"><arg type="a{sv}" name="status" direction="out"/></method>
<method name="List"><arg type="a(sa{sv})" name="messages" direction="out"/></method>
<method name="Delete"><arg type="s" name="id" direction="in"/></method>
<method name="Subscribe"/>
<signal name="Received"><arg type="s" name="id"/><arg type="a{sv}" name="message"/></signal>
<signal name="StateChanged">
@ -3183,6 +3306,40 @@ void HandleMessagingMethod(GDBusConnection* conn, const gchar*, const gchar*, co
g_dbus_method_invocation_return_value(inv, g_variant_new("(a{sv})", &b));
return;
}
if (m == "List") {
GVariantBuilder b;
g_variant_builder_init(&b, G_VARIANT_TYPE("a(sa{sv})"));
for (const auto& r : LoadStoredSms()) g_variant_builder_add(&b, "(s@a{sv})", r.id.c_str(), SmsVariant(r.sms, r.receivedAt));
g_dbus_method_invocation_return_value(inv, g_variant_new("(a(sa{sv}))", &b));
return;
}
if (m == "Delete") {
const gchar* id = nullptr;
g_variant_get(params, "(&s)", &id);
const std::string_view sid = id ? id : "";
if (!ValidSmsId(sid)) {
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.InvalidArgs", "not a message id");
return;
}
std::error_code ec;
const bool removed = std::filesystem::remove(SmsRecordPath(sid), ec);
if (ec) {
// the removal failed: nothing says the record is gone
Log(std::format("sms {}: not deleted from the store: {}", sid, ec.message()));
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.IOError", ec.message().c_str());
return;
}
if (!removed) {
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.FileNotFound", "no such message");
return;
}
// the record only: a `<id>.msg.tmp` beside it is left alone — the
// writer unlinks its own, and the engine's next start removes a crash's
// leftover (SweepSmsStore)
Log(std::format("sms {}: deleted from the store", sid));
g_dbus_method_invocation_return_value(inv, nullptr);
return;
}
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.UnknownMethod", "no such method");
}

View file

@ -39,7 +39,8 @@ again and is not handled again; one whose first Via line has no
`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++.
words) and the ids (RunToken, SentSmsId, ReceivedSmsId), and the received-message store's record codec
(FormatStoredSms/ParseStoredSms) and order (StoredSmsBefore). Pure std C++.
*/
export module Imsd:Engine;
@ -1297,13 +1298,104 @@ export namespace imsd::engine {
// 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.
// repeats across runs, and a client that deleted the daemon's copy of a
// text freed its name.
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); }
// ---- the store of received messages (§7.9) ---------------------------
// A received message as the daemon keeps it until an app takes it
// (`List`/`Delete` on the Messaging interface, §8.4): its id, when it
// arrived (epoch seconds) and the message. One record per file,
// key=value lines; the sender, the text, the data and the PDU as hex
// (a sender or a text may hold any character). Absent keys read as
// their defaults; a record without an id, or with a number or hex
// value that does not parse, is no record.
struct StoredSms {
std::string id;
std::int64_t receivedAt = 0;
SmsReceived sms;
};
std::string FormatStoredSms(const StoredSms& r) {
auto hex = [](std::string_view s) { return imsd::util::ToHex(std::span<const std::uint8_t>(reinterpret_cast<const std::uint8_t*>(s.data()), s.size())); }; // lint-disable-line no-char-pointer
std::string out;
out += std::format("id={}\n", r.id);
out += std::format("received={}\n", r.receivedAt);
out += std::format("from={}\n", hex(r.sms.from));
out += std::format("sc={}\n", r.sms.sc);
out += std::format("timestamp={}\n", r.sms.scts);
out += std::format("class={}\n", r.sms.msgClass.value_or(-1));
out += std::format("pid={}\n", r.sms.pid);
out += std::format("dcs={}\n", r.sms.dcs);
out += std::format("segments={}\n", r.sms.segments);
out += std::format("message-waiting={}\n", r.sms.messageWaiting ? 1 : 0);
if (r.sms.portDst) out += std::format("port-dst={}\n", *r.sms.portDst);
if (r.sms.portSrc) out += std::format("port-src={}\n", *r.sms.portSrc);
out += std::format("text={}\n", hex(r.sms.text));
out += std::format("data={}\n", imsd::util::ToHex(r.sms.data));
out += std::format("pdu={}\n", imsd::util::ToHex(r.sms.tpdu));
return out;
}
// The store's order, oldest first: by the arrival second, then — two
// texts of one run in one second share the id's prefix — by the sequence
// number, which the shorter id carries the smaller of (as text, -10
// would sort before -9).
bool StoredSmsBefore(const StoredSms& a, const StoredSms& b) {
if (a.receivedAt != b.receivedAt) return a.receivedAt < b.receivedAt;
if (a.id.size() != b.id.size()) return a.id.size() < b.id.size();
return a.id < b.id;
}
std::optional<StoredSms> ParseStoredSms(std::string_view text) {
StoredSms r;
bool ok = true;
auto bytesOf = [&](std::string_view v) -> std::vector<std::uint8_t> {
if (v.empty()) return {};
auto b = imsd::util::FromHex(v);
if (!b) { ok = false; return {}; }
return *b;
};
auto stringOf = [&](std::string_view v) { auto b = bytesOf(v); return std::string(b.begin(), b.end()); };
auto intOf = [&](std::string_view v) -> std::int64_t {
std::int64_t n = 0;
auto [p, ec] = std::from_chars(v.data(), v.data() + v.size(), n);
if (ec != std::errc() || p != v.data() + v.size()) ok = false;
return n;
};
for (std::size_t pos = 0; pos < text.size();) {
const std::size_t nl = text.find('\n', pos);
std::string_view line = text.substr(pos, nl == std::string_view::npos ? std::string_view::npos : nl - pos);
pos = nl == std::string_view::npos ? text.size() : nl + 1;
const std::size_t eq = line.find('=');
if (eq == std::string_view::npos) continue;
std::string_view k = line.substr(0, eq);
std::string_view v = line.substr(eq + 1);
if (k == "id") r.id = std::string(v);
else if (k == "received") r.receivedAt = intOf(v);
else if (k == "from") r.sms.from = stringOf(v);
else if (k == "sc") r.sms.sc = std::string(v);
else if (k == "timestamp") r.sms.scts = std::string(v);
else if (k == "class") { const std::int64_t c = intOf(v); if (c >= 0) r.sms.msgClass = static_cast<int>(c); }
else if (k == "pid") r.sms.pid = static_cast<std::uint8_t>(intOf(v));
else if (k == "dcs") r.sms.dcs = static_cast<std::uint8_t>(intOf(v));
else if (k == "segments") r.sms.segments = static_cast<int>(intOf(v));
else if (k == "message-waiting") r.sms.messageWaiting = intOf(v) != 0;
else if (k == "port-dst") r.sms.portDst = static_cast<std::uint16_t>(intOf(v));
else if (k == "port-src") r.sms.portSrc = static_cast<std::uint16_t>(intOf(v));
else if (k == "text") r.sms.text = stringOf(v);
else if (k == "data") r.sms.data = bytesOf(v);
else if (k == "pdu") r.sms.tpdu = bytesOf(v);
}
if (!ok || r.id.empty()) return std::nullopt;
return r;
}
// ---- retransmitted requests (RFC 3261 17.2.2) ------------------------
// A request whose Via branch (the value of the first `branch=` of its

View file

@ -9,12 +9,12 @@ 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, and whether it may send
a short message or subscribe to the message signals
net.catcrafts.IMS1.Messaging
a short message, subscribe to the message signals or list and delete
the stored ones 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
list, Messaging's GetStatus) 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.
@ -74,7 +74,8 @@ 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.
// message over IP, subscribing to the message signals, listing and
// deleting the stored ones.
inline constexpr char VoiceAction[] = "net.catcrafts.IMS1.Voice";
inline constexpr char MessagingAction[] = "net.catcrafts.IMS1.Messaging";

View file

@ -31,6 +31,9 @@ EnvironmentFile=-/run/imsd.env
EnvironmentFile=-/etc/imsd.env
# registration state (imsreg.state) + media stats live here
StateDirectory=imsd
# 0700: the store of received texts lives under it, and even the store's mtime would
# tell any local account when a text arrived
StateDirectoryMode=0700
ExecStart=/usr/bin/imsd
# registration: resume an existing SA when possible (avoids fresh-SA
# throttles); a failed bring-up exits nonzero and systemd retries, as does

View file

@ -13,8 +13,8 @@
</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, or send short messages and subscribe to the
message signals — polkit's
answer or end a call, or send short messages, subscribe to the message
signals, list and delete the stored ones — 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. -->

View file

@ -6,8 +6,9 @@
<!-- Call control on imsd (net.catcrafts.IMS1) and imsd-ofonod (org.ofono):
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
before it sends a short message over IP for one, lets one hear the
message signals (Subscribe) or read and delete the stored ones
(List, Delete). 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
@ -26,8 +27,8 @@
</defaults>
</action>
<action id="net.catcrafts.IMS1.Messaging">
<description>Send short messages over IMS</description>
<message>System policy prevents sending short messages.</message>
<description>Send, read and delete short messages over IMS</description>
<message>System policy prevents access to short messages.</message>
<defaults>
<allow_any>no</allow_any>
<allow_inactive>no</allow_inactive>

View file

@ -39,9 +39,12 @@
// 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, 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.
// over IP is off refused with 480), and the store's record codec
// (FormatStoredSms/ParseStoredSms: a full record round trip, defaults
// for absent keys, a value that does not parse or a missing id refused) and order
// (StoredSmsBefore: the arrival second, then within a run the sequence
// number), 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;
@ -1451,11 +1454,19 @@ int main() {
// 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 store's order: two texts in one second by sequence number, not by the id as text
{
StoredSms nine; nine.id = "ims-sms-in-7f3a9c21-1792192663-9"; nine.receivedAt = 1792192663;
StoredSms ten; ten.id = "ims-sms-in-7f3a9c21-1792192663-10"; ten.receivedAt = 1792192663;
StoredSms later; later.id = "ims-sms-in-7f3a9c21-1792192664-1"; later.receivedAt = 1792192664;
Check(StoredSmsBefore(nine, ten) && !StoredSmsBefore(ten, nine) && StoredSmsBefore(ten, later) && !StoredSmsBefore(later, nine), "StoredSmsBefore: arrival second first, then within a run the sequence number");
}
// 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");
Check(ReceivedSmsId("ffffffff", std::numeric_limits<std::int64_t>::min(), std::numeric_limits<std::uint64_t>::max()).size() <= 64, "the longest received id is no longer than 64 bytes");
}
// inbound MESSAGEs, as the IP-SM-GW sends them
auto inbound = [](std::string_view bodyHex, std::string_view extraHeaders = "") {
@ -1658,6 +1669,36 @@ int main() {
auto r3 = OnSmsMessage(c, rng, plain, re, nullptr, 7.0);
Check(r3.response.starts_with("SIP/2.0 200 OK") && !r3.rp && hasSms(r3.actions, SmsAction::Type::Log) && findSms(r3.actions, SmsAction::Type::Log)->text.contains("hi"), "inbound: a page-mode text is 200'd and logged with its body");
}
// the store's record codec
{
StoredSms r;
r.id = "ims-sms-in-1792186043-7";
r.receivedAt = 1792186043;
r.sms.from = "KPN Service=\n\"x\"";
r.sms.text = "Grüße ❤\nline two=three";
r.sms.scts = "2026-10-16T22:50:00+02:00";
r.sms.sc = "+31653131313";
r.sms.msgClass = 0;
r.sms.pid = 0x40;
r.sms.dcs = 0x08;
r.sms.segments = 2;
r.sms.messageWaiting = true;
r.sms.portDst = 2948;
r.sms.portSrc = 9200;
r.sms.data = {0xDE, 0xAD};
r.sms.tpdu = {0x04, 0x0B, 0x91};
const std::string text = FormatStoredSms(r);
Check(text.starts_with("id=ims-sms-in-1792186043-7\nreceived=1792186043\nfrom=") && text.contains("\nport-dst=2948\nport-src=9200\n") && text.ends_with("\npdu=040b91\n") && !text.contains("Grüße"), "store: the record's shape, the text as hex");
auto back = ParseStoredSms(text);
Check(back && back->id == r.id && back->receivedAt == r.receivedAt && back->sms.from == r.sms.from && back->sms.text == r.sms.text && back->sms.scts == r.sms.scts && back->sms.sc == r.sms.sc && back->sms.msgClass == 0 && back->sms.pid == 0x40 && back->sms.dcs == 0x08 && back->sms.segments == 2 && back->sms.messageWaiting && back->sms.portDst == 2948 && back->sms.portSrc == 9200 && back->sms.data == r.sms.data && back->sms.tpdu == r.sms.tpdu, "store: a full record round-trips");
auto minimal = ParseStoredSms("id=x\n");
Check(minimal && minimal->id == "x" && minimal->receivedAt == 0 && !minimal->sms.msgClass && !minimal->sms.portDst && minimal->sms.segments == 1 && minimal->sms.text.empty(), "store: absent keys read as defaults");
Check(!ParseStoredSms("received=5\nfrom=00\n"), "store: no id, no record");
Check(!ParseStoredSms("id=x\ntext=zz\n"), "store: a malformed hex value, no record");
Check(!ParseStoredSms("id=x\nreceived=soon\n"), "store: a malformed number, no record");
auto noClass = ParseStoredSms("id=x\nclass=-1\nmessage-waiting=0\n");
Check(noClass && !noClass->sms.msgClass && !noClass->sms.messageWaiting, "store: class -1 is none");
}
// a retransmitted MESSAGE: the same final again, nothing else, for 32 s (TimerJ)
{
RecentTransactions recent;