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:
parent
4de5f0be45
commit
aa3c394041
11 changed files with 1269 additions and 78 deletions
|
|
@ -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) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue