imsd, engine: a received text records the subscriber it arrived for

The Messaging interface gave a received text with its sender and the
service centre but not the subscriber it was for. A consumer completing a
national-form sender with a country code had to take the code from the
daemon's status at import time, which is the wrong moment: the daemon
keeps a text on disk until an app deletes it, so the app that imports it
after a SIM change knows only the new SIM's code, and a national number
under the old SIM's plan is keyed, and replied to, under the new one —
another subscriber. Only the daemon knows at receipt which subscriber a
text arrived for. The stored record and the Received and List
dictionaries carry it
as `to`: the own number the daemon holds at the moment of receipt — the
first tel: P-Associated-URI of this run's latest answer to a fresh
registration, a resume or a reconnect that carried one (a periodic
refresh's answer is not read for it) and, until the first such, the
state file's once a resume attempt has taken it up. The key is absent
while the daemon holds none.
It is additive: an app that does not know it ignores it, and a record
without it reads as before. The value comes from a header, so the
emission makes it valid UTF-8, as it does a failed submission's reason.

Tested: tests/Engine, the record round trip with `to` and a record
without it.
This commit is contained in:
Jorijn van der Graaf 2026-11-02 20:54:15 +01:00
commit 04c615fc15
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
5 changed files with 24 additions and 12 deletions

View file

@ -653,6 +653,8 @@ Rules:
`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).
No phone record shows `to` in a `Received` or a `List`; the store's round
trip with it is in `tests/Engine`.
- `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,
@ -719,7 +721,8 @@ login, an inactive session or a system service account). Reads (`GetStatus`,
`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.
phone number) travels in no broadcast signal — `Received` carries the
phone number (`to`), unicast to the Messaging interface's subscribers (§8.4).
Two threads: a dedicated engine thread runs the SIP loop (blocking framed
receive on the protected client flow, the protected-port listeners for
@ -1872,8 +1875,8 @@ when it does not know it.
| `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) |
| `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, `to` s when the daemon held an own number at receipt (the first tel: P-Associated-URI of this run's latest answer to a fresh registration, a resume or a reconnect that carried one — a periodic refresh's answer is not read for it — and, until the first such, the state file's once a resume attempt has taken it up): the subscriber the text arrived for, which a later SIM's status cannot tell, `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; `to` is made valid the same way) |
`Send`, `Subscribe`, `List` and `Delete` are gated by polkit's
`net.catcrafts.IMS1.Messaging` through the same `imsd-bus` gate (`Gated`'s `Action` parameter);

View file

@ -157,7 +157,7 @@ gain a key.
| `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)) |
| `Received` | `s a{sv}` (id, message: `from`, `text`, `timestamp` (the SC's, as `2026-10-16T22:50:00+02:00`), `received` (x), `sc`, `to` (when the daemon held an own number at receipt: that number, e.g. `tel:+31612345678`), `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`, `Subscribe`, `List` and `Delete` are gated by polkit's `net.catcrafts.IMS1.Messaging`.

View file

@ -833,6 +833,7 @@ struct Event {
std::string text; // Fatal, Idle
imsd::engine::SmsReceived sms; // SmsReceived
std::int64_t at = 0; // SmsReceived: when it arrived (epoch seconds)
std::string to; // SmsReceived: the subscriber it arrived for (the own number the daemon held then)
};
GDBusConnection* DbusConn = nullptr;
@ -1078,7 +1079,7 @@ std::vector<imsd::engine::StoredSms> LoadStoredSms(bool log = true) {
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, std::int64_t receivedAt) {
GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt, const std::string& to) {
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()));
@ -1086,6 +1087,8 @@ GVariant* SmsVariant(const imsd::engine::SmsReceived& m, std::int64_t receivedAt
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(receivedAt));
g_variant_builder_add(&b, "{sv}", "sc", g_variant_new_string(m.sc.c_str()));
// from a header: made valid UTF-8 like a failed submission's reason
if (!to.empty()) g_variant_builder_add(&b, "{sv}", "to", g_variant_new_take_string(g_utf8_make_valid(to.c_str(), -1)));
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));
@ -1140,7 +1143,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, ev->at)));
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms, ev->at, ev->to)));
break;
case Event::Type::SmsState: {
std::set<std::string> to = Subscribers;
@ -2899,11 +2902,12 @@ private:
ev->type = Event::Type::SmsReceived;
ev->at = NowEpoch();
ev->sms = m;
ev->to = ppi_; // the subscriber it arrived for: the own number held now, not a later SIM's
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);
stored = StoreReceivedSms({ev->uni, ev->at, m, ppi_}, why);
if (stored != StoreResult::Exists) break;
Log(std::format("sms store: {} exists already; taking the next id", ev->uni));
}
@ -3308,7 +3312,7 @@ void HandleMessagingMethod(GDBusConnection* conn, const gchar*, const gchar*, co
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));
for (const auto& r : LoadStoredSms()) g_variant_builder_add(&b, "(s@a{sv})", r.id.c_str(), SmsVariant(r.sms, r.receivedAt, r.to));
g_dbus_method_invocation_return_value(inv, g_variant_new("(a(sa{sv}))", &b));
return;
}

View file

@ -1309,7 +1309,8 @@ export namespace imsd::engine {
// 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,
// arrived (epoch seconds), the message and the subscriber it arrived
// for. 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
@ -1318,6 +1319,7 @@ export namespace imsd::engine {
std::string id;
std::int64_t receivedAt = 0;
SmsReceived sms;
std::string to; // the own number the daemon held at receipt (from a tel: P-Associated-URI); "" while it held none
};
std::string FormatStoredSms(const StoredSms& r) {
@ -1325,6 +1327,7 @@ export namespace imsd::engine {
std::string out;
out += std::format("id={}\n", r.id);
out += std::format("received={}\n", r.receivedAt);
if (!r.to.empty()) out += std::format("to={}\n", r.to);
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);
@ -1377,6 +1380,7 @@ export namespace imsd::engine {
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 == "to") r.to = std::string(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);

View file

@ -1673,6 +1673,7 @@ int main() {
StoredSms r;
r.id = "ims-sms-in-1792186043-7";
r.receivedAt = 1792186043;
r.to = "tel:+31612345678";
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";
@ -1687,11 +1688,11 @@ int main() {
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");
Check(text.starts_with("id=ims-sms-in-1792186043-7\nreceived=1792186043\nto=tel:+31612345678\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");
Check(back && back->id == r.id && back->receivedAt == r.receivedAt && back->to == r.to && 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(minimal && minimal->id == "x" && minimal->receivedAt == 0 && minimal->to.empty() && !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");