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
|
|
@ -10,9 +10,11 @@ Owns net.catcrafts.IMS1 on the system bus with the project's frozen D-Bus ABI
|
|||
+ IPsec sec-agree, fresh or warm-resume, with a keepalive re-REGISTER refresh),
|
||||
run outgoing and incoming calls through the Imsd:Engine call machine (inbound
|
||||
INVITEs on the protected-port listeners become ringing calls a dialer answers
|
||||
via Accept), and spawn one imsd-media data-plane process per answered call.
|
||||
via Accept), spawn one imsd-media data-plane process per answered call, and
|
||||
since 1.2.0 send and take short messages over IMS (AGENTS.md §7.9: the SIP
|
||||
MESSAGE with an RP-DATA, the Messaging interface on the same object).
|
||||
GLib/GDBus lives only here and in ImsdBus (the polkit gate in front of call
|
||||
control, shared with imsd-ofonod) — the integration daemons imsd-dialerd and
|
||||
control and messaging, shared with imsd-ofonod) — the integration daemons imsd-dialerd and
|
||||
imsd-ofonod carry their own; every message, digest, SA command, and
|
||||
call-state decision comes from the GLib-free core.
|
||||
|
||||
|
|
@ -20,7 +22,8 @@ Threads: a dedicated engine thread runs the SIP loop (blocking framed recv,
|
|||
protected-port listeners, media reaping, keepalive); the GLib main loop owns
|
||||
the bus. D-Bus method calls push commands to the engine queue; engine events
|
||||
reach the bus via g_idle_add, where the calls table + status snapshot live
|
||||
(touched only on the main thread).
|
||||
(touched only on the main thread). The Messaging interface's Subscribe keeps
|
||||
its subscriber set on the main thread too.
|
||||
|
||||
--session own the name on the session bus (development; no policy, no
|
||||
polkit)
|
||||
|
|
@ -53,6 +56,7 @@ constexpr const char* Version = "1.1.0";
|
|||
constexpr const char* BusName = "net.catcrafts.IMS1";
|
||||
constexpr const char* ObjPath = "/net/catcrafts/IMS1";
|
||||
constexpr const char* Iface = "net.catcrafts.IMS1";
|
||||
constexpr const char* MessagingIface = "net.catcrafts.IMS1.Messaging";
|
||||
constexpr int PortUc = imsd::util::PortUc;
|
||||
constexpr int PortUs = imsd::util::PortUs;
|
||||
constexpr int PortUcNext = imsd::util::PortUcNext;
|
||||
|
|
@ -721,6 +725,23 @@ std::string StateDir() {
|
|||
// tiny JSON reader/writer for the persisted registration context.
|
||||
std::string StatePath() { return EnvOr("STATE_FILE", std::format("{}/imsreg.state", StateDir())); }
|
||||
|
||||
// The next TP-MR, kept across restarts (TS 23.040 9.2.3.6's intent without
|
||||
// the (U)SIM's EF_SMSS): one decimal number in <state dir>/sms-tpmr.
|
||||
std::string TpMrPath() { return std::format("{}/sms-tpmr", StateDir()); }
|
||||
std::optional<std::uint8_t> LoadTpMr() {
|
||||
std::ifstream in(TpMrPath());
|
||||
int v = -1;
|
||||
if (!(in >> v) || v < 0 || v > 255) return std::nullopt;
|
||||
return static_cast<std::uint8_t>(v);
|
||||
}
|
||||
void SaveTpMr(std::uint8_t mr) {
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(StateDir(), ec);
|
||||
const std::string tmp = TpMrPath() + ".tmp";
|
||||
{ std::ofstream out(tmp, std::ios::trunc); out << static_cast<int>(mr) << '\n'; }
|
||||
std::rename(tmp.c_str(), TpMrPath().c_str()); // a torn write must not read as a number
|
||||
}
|
||||
|
||||
// `security_server` is the registration's Security-Verify (RegState's
|
||||
// securityServer: the 401's joined list); a resume takes it from here
|
||||
// since 0.3.12. The file's values are quoted without escaping; a value
|
||||
|
|
@ -801,15 +822,17 @@ struct StatusSnapshot {
|
|||
std::string local, pcscf, ppi;
|
||||
std::int64_t expiry = 0;
|
||||
std::int64_t cseq = 0;
|
||||
std::string smsc; // the service centre a submission goes to (empty: none known)
|
||||
};
|
||||
|
||||
// engine -> main-loop event
|
||||
struct Event {
|
||||
enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle } type;
|
||||
enum class Type { Added, State, Deleted, Registration, Status, Fatal, Idle, SmsReceived, SmsState } type;
|
||||
CallInfo info; // Added
|
||||
std::string uni, state, reason; // State/Deleted
|
||||
std::string uni, state, reason; // State/Deleted; SmsState (uni: the message id); SmsReceived (uni: the id)
|
||||
StatusSnapshot status; // Registration/Status
|
||||
std::string text; // Fatal, Idle
|
||||
imsd::engine::SmsReceived sms; // SmsReceived
|
||||
};
|
||||
|
||||
GDBusConnection* DbusConn = nullptr;
|
||||
|
|
@ -923,6 +946,58 @@ void EmitSignal(const char* name, GVariant* params) {
|
|||
g_dbus_connection_emit_signal(DbusConn, nullptr, ObjPath, Iface, name, params, nullptr);
|
||||
}
|
||||
|
||||
// ---- Messaging subscribers (§8.4) — main thread only. The Messaging
|
||||
// signals carry a text's content, so they are never broadcast: Subscribe
|
||||
// runs the Messaging polkit gate and records the caller's unique bus name,
|
||||
// and Received / StateChanged go unicast to each name recorded, which the
|
||||
// bus delivers to that connection (root's busctl monitor sees them as
|
||||
// well). A subscription ends with the
|
||||
// connection (its name watch). The submission's outcome (sent / failed)
|
||||
// also reaches the connection that called Send, subscribed or not; the
|
||||
// later delivery states reach subscribers.
|
||||
std::set<std::string> Subscribers;
|
||||
std::map<std::string, guint> SubscriberWatches;
|
||||
std::map<std::string, std::string> SendOrigins; // message id -> the Send caller's unique name
|
||||
|
||||
void OnSubscriberVanished(GDBusConnection*, const gchar* name, gpointer) {
|
||||
if (!Subscribers.erase(name)) return;
|
||||
if (auto it = SubscriberWatches.find(name); it != SubscriberWatches.end()) { g_bus_unwatch_name(it->second); SubscriberWatches.erase(it); }
|
||||
Log(std::format("sms: {} unsubscribed (its connection is gone; {} subscriber(s))", name, Subscribers.size()));
|
||||
}
|
||||
|
||||
void SubscribeMessaging(GDBusConnection* conn, const std::string& sender) {
|
||||
if (!Subscribers.insert(sender).second) return;
|
||||
SubscriberWatches[sender] = g_bus_watch_name_on_connection(conn, sender.c_str(), G_BUS_NAME_WATCHER_FLAGS_NONE, nullptr, OnSubscriberVanished, nullptr, nullptr);
|
||||
Log(std::format("sms: {} subscribed ({} subscriber(s))", sender, Subscribers.size()));
|
||||
}
|
||||
|
||||
// a Messaging signal to one connection
|
||||
void EmitSignalTo(const std::string& destination, const char* name, GVariant* params) {
|
||||
if (!DbusConn) return;
|
||||
g_dbus_connection_emit_signal(DbusConn, destination.c_str(), ObjPath, MessagingIface, name, params, nullptr);
|
||||
}
|
||||
|
||||
// a received short message as the Messaging interface's a{sv} (§8.4)
|
||||
GVariant* SmsVariant(const imsd::engine::SmsReceived& m) {
|
||||
GVariantBuilder b;
|
||||
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
|
||||
g_variant_builder_add(&b, "{sv}", "from", g_variant_new_string(m.from.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "text", g_variant_new_string(m.text.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "timestamp", g_variant_new_string(m.scts.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "received", g_variant_new_int64(NowEpoch()));
|
||||
g_variant_builder_add(&b, "{sv}", "sc", g_variant_new_string(m.sc.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "class", g_variant_new_int32(m.msgClass.value_or(-1)));
|
||||
g_variant_builder_add(&b, "{sv}", "pid", g_variant_new_byte(m.pid));
|
||||
g_variant_builder_add(&b, "{sv}", "dcs", g_variant_new_byte(m.dcs));
|
||||
g_variant_builder_add(&b, "{sv}", "segments", g_variant_new_int32(m.segments));
|
||||
g_variant_builder_add(&b, "{sv}", "message-waiting", g_variant_new_boolean(m.messageWaiting ? TRUE : FALSE));
|
||||
if (m.portDst) g_variant_builder_add(&b, "{sv}", "port-dst", g_variant_new_uint32(*m.portDst));
|
||||
if (m.portSrc) g_variant_builder_add(&b, "{sv}", "port-src", g_variant_new_uint32(*m.portSrc));
|
||||
if (!m.data.empty()) g_variant_builder_add(&b, "{sv}", "data", g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, m.data.data(), m.data.size(), 1));
|
||||
g_variant_builder_add(&b, "{sv}", "pdu", g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, m.tpdu.data(), m.tpdu.size(), 1));
|
||||
return g_variant_builder_end(&b);
|
||||
}
|
||||
|
||||
gboolean OnIdleEvent(gpointer data) {
|
||||
std::unique_ptr<Event> ev(static_cast<Event*>(data));
|
||||
switch (ev->type) {
|
||||
|
|
@ -963,6 +1038,27 @@ gboolean OnIdleEvent(gpointer data) {
|
|||
Log(std::format("idle: {} — nothing to do; systemctl start imsd when that changes", ev->text));
|
||||
g_main_loop_quit(MainLoop);
|
||||
break;
|
||||
case Event::Type::SmsReceived:
|
||||
for (const std::string& to : Subscribers)
|
||||
EmitSignalTo(to, "Received", g_variant_new("(s@a{sv})", ev->uni.c_str(), SmsVariant(ev->sms)));
|
||||
break;
|
||||
case Event::Type::SmsState: {
|
||||
std::set<std::string> to = Subscribers;
|
||||
if (auto it = SendOrigins.find(ev->uni); it != SendOrigins.end()) {
|
||||
to.insert(it->second);
|
||||
if (ev->state == imsd::engine::SmsStateSent || ev->state == imsd::engine::SmsStateFailed) SendOrigins.erase(it);
|
||||
}
|
||||
// a failed submission's reason can hold the network's text (a
|
||||
// refused final's, RefusalSummary); a D-Bus string must be valid
|
||||
// UTF-8, so bytes that are not become U+FFFD here, and the C
|
||||
// string read ends at a NUL byte — the id and the state are
|
||||
// imsd's own ASCII
|
||||
gchar* reason = g_utf8_make_valid(ev->reason.c_str(), -1);
|
||||
for (const std::string& t : to)
|
||||
EmitSignalTo(t, "StateChanged", g_variant_new("(sss)", ev->uni.c_str(), ev->state.c_str(), reason));
|
||||
g_free(reason);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return G_SOURCE_REMOVE;
|
||||
}
|
||||
|
|
@ -1020,6 +1116,24 @@ public:
|
|||
for (const auto& c : codecs_) list += (list.empty() ? "" : ",") + c;
|
||||
Log(std::format("CODECS override active: {}", list));
|
||||
}
|
||||
// SMS_OVER_IMS=1: advertise +g.3gpp.smsip and take short messages
|
||||
// over IMS (§7.9) — off by default: with the tag the network may
|
||||
// deliver terminating SMS over IMS rather than the modem's NAS path
|
||||
// (operator policy, TS 24.341 5.3.3.4.2 NOTE 2). SMSC= names
|
||||
// the service centre instead of EF_SMSP.
|
||||
smsOverIp_ = EnvOr("SMS_OVER_IMS", "0") == "1";
|
||||
smscOverride_ = EnvOr("SMSC", "");
|
||||
if (!smsOverIp_) Log("SMS over IP: off (SMS_OVER_IMS=1 enables it)");
|
||||
// TS 23.040 9.2.3.6 has TP-MR continue from the (U)SIM's
|
||||
// Last-Used-TP-MR; imsd continues from its own last one instead
|
||||
// (<state dir>/sms-tpmr, written when a message's segments take
|
||||
// theirs, the write neither checked nor synced) and starts at random only without
|
||||
// one, to keep a status report for a message sent before a restart
|
||||
// from meeting its TP-MR on a newer one. RP-MR and the concatenation
|
||||
// reference start at random.
|
||||
tpMr_ = LoadTpMr().value_or(static_cast<std::uint8_t>(rng_.UInt(0, 255)));
|
||||
rpMr_ = static_cast<std::uint8_t>(rng_.UInt(0, 255));
|
||||
concatRef_ = static_cast<std::uint8_t>(rng_.UInt(0, 255));
|
||||
// EMERGENCY_NUMBERS: comma-separated additions to the builtin
|
||||
// 112/911 (a lab core's advertised short code, carrier extras).
|
||||
std::string extra = EnvOr("EMERGENCY_NUMBERS", "");
|
||||
|
|
@ -1057,6 +1171,14 @@ public:
|
|||
std::scoped_lock g(cmdLock_);
|
||||
cmds_.push_back({Cmd::Kind::Dtmf, uni, tones});
|
||||
}
|
||||
bool SmsEnabled() const { return smsOverIp_; }
|
||||
// Send() runs on the D-Bus thread: allocate the id, queue the work.
|
||||
std::string SendSms(const std::string& number, const std::string& text, bool statusReport) {
|
||||
std::scoped_lock g(cmdLock_);
|
||||
std::string id = imsd::engine::SentSmsId(smsRun_, smsStart_, ++smsSeq_);
|
||||
cmds_.push_back({Cmd::Kind::SendSms, id, number, text, statusReport});
|
||||
return id;
|
||||
}
|
||||
void Stop() {
|
||||
{ std::scoped_lock g(cmdLock_); cmds_.push_back({Cmd::Kind::Stop, {}, {}}); }
|
||||
quit_.store(true);
|
||||
|
|
@ -1116,6 +1238,17 @@ public:
|
|||
reply_ = in.reply;
|
||||
DispatchRequest(in.msg);
|
||||
}
|
||||
// the SMS deadline (the final's wait, the report's) is judged right
|
||||
// after the server ports were drained: a submit report that landed
|
||||
// during a blocking re-REGISTER below must not count as a timeout
|
||||
if (smsOut_ && smsOut_->Deadline() > 0 && Mono() > smsOut_->Deadline()) {
|
||||
ExecuteSms(smsOut_->OnDeadline());
|
||||
AfterSms();
|
||||
}
|
||||
// a concatenated set that got no segment for §7.9's 30 min ages out
|
||||
// on the loop's clock, whether or not another MESSAGE ever comes
|
||||
for (const auto& d : reassembler_.Purge(Mono(), SmsReassemblyMaxAge))
|
||||
Log(std::format("sms: a concatenated text from {} (set {}, {} of {} segments held) dropped after {} min: the rest never came", d.from, d.ref, d.held, d.total, static_cast<int>(SmsReassemblyMaxAge / 60)));
|
||||
MaybeRefresh();
|
||||
MaybeReconnect();
|
||||
MaybeResubscribe();
|
||||
|
|
@ -1134,7 +1267,7 @@ public:
|
|||
if (call_ && callid == call_->CallId() && cseq.ends_with("INVITE")) {
|
||||
Execute(call_->OnInviteResponse(*msg));
|
||||
MaybeDropCall();
|
||||
} else {
|
||||
} else if (!OnSmsResponse(*msg, *st)) {
|
||||
OnSubscribeResponse(*msg, *st);
|
||||
}
|
||||
}
|
||||
|
|
@ -1145,7 +1278,12 @@ public:
|
|||
}
|
||||
|
||||
private:
|
||||
struct Cmd { enum class Kind { Dial, HangUp, Accept, Dtmf, Stop } kind; std::string uni, arg; }; // arg: the number to dial, or the tones
|
||||
struct Cmd {
|
||||
enum class Kind { Dial, HangUp, Accept, Dtmf, SendSms, Stop } kind;
|
||||
std::string uni, arg; // arg: the number to dial, the tones, or a short message's destination
|
||||
std::string text; // SendSms: the text
|
||||
bool statusReport = false; // SendSms: ask the SC for a status report
|
||||
};
|
||||
struct Stopping {}; // the engine was told to stop while a bring-up waited
|
||||
|
||||
// A bring-up the network deferred (a fresh-SA throttle) or refused: wait
|
||||
|
|
@ -1267,6 +1405,27 @@ private:
|
|||
std::atomic<bool> quit_{false};
|
||||
bool devMode_ = false;
|
||||
|
||||
// SMS over IP (§7.9)
|
||||
bool smsOverIp_ = false;
|
||||
std::string smscOverride_; // SMSC=
|
||||
std::string smsc_; // the service centre's number (empty: none known)
|
||||
std::vector<std::uint8_t> scAddress_; // the same as the RP-DATA's destination: [octets][toa][digits]
|
||||
std::optional<std::uint8_t> smsValidity_; // EF_SMSP's TP-Validity-Period
|
||||
std::optional<imsd::engine::SmsOutbound> smsOut_; // the message in flight
|
||||
std::deque<std::pair<std::string, imsd::engine::SmsOutbound::Params>> smsPending_; // queued behind it
|
||||
std::set<std::string> reportCallIds_; // the delivery reports' Call-IDs, each until a final comes for it
|
||||
imsd::engine::StatusReportBook reports_; // the messages that asked for a status report, by TP-MR: a word for the whole message
|
||||
imsd::engine::SmsWordOrder smsOrder_; // the submission's word before a report's (§8.4)
|
||||
imsd::sms::Reassembler reassembler_;
|
||||
imsd::engine::RecentTransactions recentMessages_; // the retransmission table of inbound MESSAGEs outside a call's dialog (TimerJ)
|
||||
std::uint8_t tpMr_ = 0; // the next TP-MR, RP-MR and concatenation reference
|
||||
std::uint8_t rpMr_ = 0;
|
||||
std::uint8_t concatRef_ = 0;
|
||||
const std::string smsRun_ = imsd::engine::RunToken(std::random_device{}()); // every id's first field after its prefix: this run's token — another run gives an id out again only with the same token, second and counter
|
||||
const std::int64_t smsStart_ = NowEpoch(); // the sent ids' second
|
||||
std::atomic<std::uint64_t> smsSeq_{0}; // Send (D-Bus thread) mints ids
|
||||
std::uint64_t smsInSeq_ = 0; // received messages' ids (engine thread)
|
||||
|
||||
// command queue
|
||||
std::mutex cmdLock_;
|
||||
std::deque<Cmd> cmds_;
|
||||
|
|
@ -1336,6 +1495,8 @@ private:
|
|||
reg_.slot = sel->slot;
|
||||
reg_.aid = sel->aid;
|
||||
Log(std::format("SIM slot={} IMSI={} domain={}", sel->slot, info->imsi, ctx_.id.domain));
|
||||
ctx_.smsOverIp = smsOverIp_;
|
||||
if (smsOverIp_) LoadSmsParameters();
|
||||
RefreshPani();
|
||||
|
||||
std::string resume = EnvOr("RESUME", "auto");
|
||||
|
|
@ -1753,7 +1914,7 @@ private:
|
|||
// the send or of its last provisional. A request arriving on the client
|
||||
// flow meanwhile (a NOTIFY, an OPTIONS) is dispatched and answered, not
|
||||
// read as the reply; a provisional of our own transaction keeps the
|
||||
// wait going; a response to our reg-event SUBSCRIBE is handled as the
|
||||
// wait going; a response to our reg-event SUBSCRIBE or to one of our MESSAGEs is handled as the
|
||||
// run loop handles it, any other transaction's is ignored. Throws
|
||||
// when nothing answers or the flow dies under a dispatched request.
|
||||
std::string AwaitFinal(const std::string& callid, long cseq, std::string_view what) {
|
||||
|
|
@ -1771,7 +1932,7 @@ private:
|
|||
continue;
|
||||
}
|
||||
if (!imsd::sip::ResponseOf(*m, callid, want)) {
|
||||
if (!OnSubscribeResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what));
|
||||
if (!OnSubscribeResponse(*m, *st) && !OnSmsResponse(*m, *st)) Log(std::format("ignoring a response to another transaction while awaiting the {} reply", what));
|
||||
continue;
|
||||
}
|
||||
if (*st >= 200) return *m;
|
||||
|
|
@ -2425,9 +2586,221 @@ private:
|
|||
} else if (c.kind == Cmd::Kind::Dtmf) {
|
||||
if (call_ && call_->Uni() == c.uni) Execute(call_->OnDtmf(c.arg));
|
||||
else Log(std::format("SendDtmf({}, '{}') ignored: no such call", c.uni, c.arg));
|
||||
} else if (c.kind == Cmd::Kind::SendSms) {
|
||||
QueueSms(c);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- SMS over IP (§7.9) ---------------------------------------------
|
||||
|
||||
// The service centre a submission is addressed to (TS 24.341 5.3.1.2
|
||||
// NOTE 1, NOTE 4): SMSC= when set, else EF_SMSP's TS-Service-Centre-
|
||||
// Address (its validity period comes along). Without one a Send fails
|
||||
// with the reason. A service centre is an international number: the
|
||||
// MESSAGE's target is built from it (ScPsi), never guessed from a
|
||||
// dialled form, so a service centre ScPsi makes nothing of — national,
|
||||
// or with a '*' or '#' among the digits — is refused here, on ScPsi's
|
||||
// own word, and never announced.
|
||||
// EF_PSISMSC (a PSI of the SC configured by the operator, ahead of
|
||||
// EF_SMSP in 5.3.1.2 NOTE 1's order) is not read.
|
||||
void LoadSmsParameters() {
|
||||
scAddress_.clear(); smsc_.clear(); smsValidity_.reset();
|
||||
if (!smscOverride_.empty()) {
|
||||
auto a = imsd::sms::Address::ForNumber(smscOverride_); // digits, * and #: the BCD table's a, b, c are not dialled (2026-10-18)
|
||||
auto lv = a ? imsd::sms::EncodeRpAddress(*a) : std::nullopt;
|
||||
if (!lv) Log(std::format("sms: SMSC='{}' is not a number; SMS over IP cannot submit", smscOverride_));
|
||||
else if (!imsd::msg::ScPsi(a->Number(), ctx_.id.domain)) Log(std::format("sms: SMSC='{}' is not an international number (+ and digits); SMS over IP cannot submit", smscOverride_)); // the predicate the MESSAGE's target is built with: a '*' or '#' ForNumber dials is no service centre
|
||||
else { scAddress_ = *lv; smsc_ = a->Number(); Log(std::format("sms: service centre {} (SMSC=)", smsc_)); }
|
||||
} else {
|
||||
auto r = RunCapture({"qmicli", "-d", "qrtr://0", "--uim-read-record=file=0x3F00-0x7FFF-0x6F42,record-number=1"});
|
||||
auto p = imsd::sms::ParseSmsp(imsd::sms::ParseQmicliReadResult(r.out));
|
||||
if (!p) Log("sms: no service centre: EF_SMSP record 1 unreadable or without one; SMS over IP cannot submit (SMSC= in /etc/imsd.env names one)");
|
||||
else if (!imsd::msg::ScPsi(p->scNumber, ctx_.id.domain)) Log(std::format("sms: EF_SMSP's service centre '{}' is not an international number (+ and digits); SMS over IP cannot submit (SMSC= in /etc/imsd.env names one)", p->scNumber));
|
||||
else {
|
||||
scAddress_ = p->scAddress; smsc_ = p->scNumber; smsValidity_ = p->validity;
|
||||
Log(std::format("sms: service centre {} (EF_SMSP{}){}", smsc_, p->alpha.empty() ? std::string() : std::format(" '{}'", p->alpha),
|
||||
p->validity ? std::format(", validity period 0x{:02x}", *p->validity) : std::string()));
|
||||
}
|
||||
}
|
||||
Log("SMS over IP: on (+g.3gpp.smsip advertised: short messages the network delivers over IMS arrive here)");
|
||||
}
|
||||
|
||||
// A Send from the bus: queued behind the message in flight (one
|
||||
// submission at a time on the flow), or failed, when the engine takes
|
||||
// it up while imsd is not registered or its flow is down — it is not
|
||||
// held for a recovery step, and the sender hears why. A queued message
|
||||
// starts when the one before it ends, without this check.
|
||||
void QueueSms(const Cmd& c) {
|
||||
if (!registered_ || !sip_.Alive()) {
|
||||
PostSmsState(c.uni, imsd::engine::SmsStateFailed, registered_ ? "the flow to the P-CSCF is down" : "imsd is not registered");
|
||||
return;
|
||||
}
|
||||
imsd::engine::SmsOutbound::Params p;
|
||||
p.number = c.arg;
|
||||
p.text = c.text;
|
||||
p.scTarget = imsd::msg::ScPsi(smsc_, ctx_.id.domain).value_or(std::string()); // empty without a service centre: Start fails the message with the reason
|
||||
p.scAddress = scAddress_;
|
||||
p.validity = smsValidity_;
|
||||
p.statusReport = c.statusReport;
|
||||
smsPending_.emplace_back(c.uni, std::move(p));
|
||||
StartNextSms();
|
||||
}
|
||||
|
||||
// The queued messages start while none is in flight: one, and the next
|
||||
// when that one ended at its start (Start refused it, or the flow
|
||||
// refused its send) — in a loop, so a queue of such messages costs no
|
||||
// stack.
|
||||
void StartNextSms() {
|
||||
while (!smsOut_ && !smsPending_.empty()) {
|
||||
auto [id, p] = std::move(smsPending_.front());
|
||||
smsPending_.pop_front();
|
||||
p.tpMr = tpMr_; p.rpMr = rpMr_; p.concatRef = concatRef_;
|
||||
const bool wantsReport = p.statusReport;
|
||||
const std::string destination = p.number;
|
||||
smsOut_.emplace(ctx_, rng_, id, std::move(p));
|
||||
auto actions = smsOut_->Start(Mono());
|
||||
// on record from the start — the SC may deliver segment 1 and report on
|
||||
// it while segment 2 is still in flight — and only for a message that
|
||||
// asked for a report, with its destination: a report is matched by
|
||||
// TP-MR and recipient, and the message gets a word for the whole
|
||||
// (no TP-MRs when Start failed: nothing on record)
|
||||
if (wantsReport) reports_.Sent(smsOut_->Id(), destination, smsOut_->TpMrs());
|
||||
const std::size_t segments = smsOut_->Segments();
|
||||
tpMr_ = static_cast<std::uint8_t>(tpMr_ + segments);
|
||||
if (segments > 0) SaveTpMr(tpMr_);
|
||||
rpMr_ = static_cast<std::uint8_t>(rpMr_ + segments);
|
||||
if (segments > 1) concatRef_++;
|
||||
for (const auto& a : actions)
|
||||
if (a.type == imsd::engine::SmsAction::Type::SendClient) DumpRaw("imsd-message-out.raw", a.text);
|
||||
ExecuteSms(actions);
|
||||
if (smsOut_ && smsOut_->Done()) smsOut_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
// The message in flight ended: the next queued message starts (its
|
||||
// TP-MRs went on record when it started).
|
||||
void AfterSms() {
|
||||
if (!smsOut_ || !smsOut_->Done()) return;
|
||||
smsOut_.reset();
|
||||
StartNextSms();
|
||||
}
|
||||
|
||||
void ExecuteSms(const std::vector<imsd::engine::SmsAction>& actions) {
|
||||
using T = imsd::engine::SmsAction::Type;
|
||||
bool inFlightFailed = false;
|
||||
for (const auto& a : actions) {
|
||||
switch (a.type) {
|
||||
case T::SendClient:
|
||||
if (!sip_.Send(a.text)) {
|
||||
if (smsOut_ && imsd::sip::Header(a.text, "Call-ID") == smsOut_->CallId()) inFlightFailed = true;
|
||||
else Log("sms: delivery report not sent: the flow to the P-CSCF is down");
|
||||
}
|
||||
break;
|
||||
case T::SendResponse:
|
||||
if (reply_) reply_(a.text);
|
||||
break;
|
||||
case T::Received: PostSmsReceived(a.received); break;
|
||||
case T::StatusReport: OnStatusReport(a.report); break;
|
||||
case T::State: OnSubmissionWord(a.id, a.state, a.reason); break;
|
||||
case T::Log: Log(a.text); break;
|
||||
}
|
||||
}
|
||||
if (inFlightFailed && smsOut_) ExecuteSms(smsOut_->OnSendFailed()); // carries no send of its own
|
||||
}
|
||||
|
||||
// A response on the client flow to a MESSAGE of ours: the message in
|
||||
// flight's, or a delivery report's (logged, nothing more to do).
|
||||
bool OnSmsResponse(const std::string& msg, int st) {
|
||||
if (smsOut_ && smsOut_->OwnsResponse(msg)) {
|
||||
ExecuteSms(smsOut_->OnResponse(msg, st, Mono()));
|
||||
AfterSms();
|
||||
return true;
|
||||
}
|
||||
if (!imsd::sip::Header(msg, "CSeq").value_or("").ends_with("MESSAGE")) return false;
|
||||
auto it = reportCallIds_.find(std::string(imsd::sip::Header(msg, "Call-ID").value_or("")));
|
||||
if (it == reportCallIds_.end()) return false;
|
||||
if (st >= 200) {
|
||||
Log(st >= 300 ? std::format("sms: delivery report refused: {}", imsd::sip::RefusalSummary(msg)) : std::format("sms: delivery report -> {}", st));
|
||||
reportCallIds_.erase(it);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// An inbound MESSAGE (TS 24.341 5.3.2.3): answered on its own channel
|
||||
// first, then what it carried — a message to the bus and its delivery
|
||||
// report on the flow, a status report, a submit report for the message
|
||||
// in flight. A set of a concatenated message to which no segment comes
|
||||
// for SmsReassemblyMaxAge is dropped.
|
||||
static constexpr double SmsReassemblyMaxAge = 1800.0;
|
||||
void OnInboundMessage(const std::string& msg) {
|
||||
DumpRaw("imsd-message-in.raw", msg);
|
||||
// a retransmission (RFC 3261 17.2.2): the same final again, nothing else
|
||||
const std::string key = imsd::engine::RecentTransactions::Key(msg);
|
||||
if (auto again = recentMessages_.Repeat(key, Mono())) {
|
||||
Log(std::format("MESSAGE retransmitted ({}): answered again, not handled again", key));
|
||||
if (reply_) reply_(*again);
|
||||
return;
|
||||
}
|
||||
auto r = imsd::engine::OnSmsMessage(ctx_, rng_, msg, reassembler_, smsOut_ ? &*smsOut_ : nullptr, Mono());
|
||||
recentMessages_.Remember(key, r.response, Mono());
|
||||
if (reply_) reply_(r.response);
|
||||
if (!r.reportCallId.empty()) reportCallIds_.insert(r.reportCallId);
|
||||
ExecuteSms(r.actions);
|
||||
AfterSms();
|
||||
}
|
||||
|
||||
// The SC's word on a message we sent (an SMS-STATUS-REPORT), matched
|
||||
// to the message that asked for it by TP-MR and recipient, a word for
|
||||
// the whole message (StatusReportBook): delivered when its last segment
|
||||
// is, still being tried, or given up on (TS 23.040 9.2.3.15's classes, a
|
||||
// reserved value read as Service Rejected). A report that matches
|
||||
// nothing is logged. The word is posted
|
||||
// after the submission's (SmsWordOrder): held while the message is the
|
||||
// one in flight.
|
||||
void OnStatusReport(const imsd::sms::StatusReport& sr) {
|
||||
using Word = imsd::engine::StatusReportBook::Word;
|
||||
const auto o = reports_.Report(sr.mr, sr.recipient.Number(), sr.status);
|
||||
switch (o.word) {
|
||||
case Word::NoMessage: Log(std::format("sms: status report for TP-MR {} to {}: no message of ours on record", sr.mr, sr.recipient.Number())); return;
|
||||
case Word::SegmentDelivered: Log(std::format("sms {}: a segment delivered (TP-MR {}); {} still to be reported", o.id, sr.mr, o.outstanding)); return;
|
||||
case Word::Delivered: OnReportWord(o.id, imsd::engine::SmsStateDelivered, imsd::sms::StatusText(sr.status)); return;
|
||||
case Word::Pending: OnReportWord(o.id, imsd::engine::SmsStateDeliveryPending, imsd::sms::StatusText(sr.status)); return;
|
||||
case Word::Failed: OnReportWord(o.id, imsd::engine::SmsStateDeliveryFailed, imsd::sms::StatusText(sr.status)); return;
|
||||
}
|
||||
}
|
||||
void OnReportWord(const std::string& id, std::string_view state, std::string_view reason) {
|
||||
const bool inFlight = smsOut_ && smsOut_->Id() == id;
|
||||
const auto post = smsOrder_.Report(id, state, reason, inFlight);
|
||||
if (post.empty()) Log(std::format("sms {}: {}: {} — held until the submission ends", id, state, reason));
|
||||
for (const auto& w : post) PostSmsState(w.id, w.state, w.reason);
|
||||
}
|
||||
// The submission's word, the message's first (§8.4): `sent`, then the
|
||||
// report's word held meanwhile; `failed`, and the message's TP-MRs are
|
||||
// forgotten — unless the SC had reported every segment delivered, when
|
||||
// the message is `sent` and `delivered` (the last submit report lost).
|
||||
void OnSubmissionWord(const std::string& id, std::string_view state, std::string_view reason) {
|
||||
const auto e = smsOrder_.Submission(id, state, reason);
|
||||
if (e.forget) reports_.ForgetMessage(id);
|
||||
for (const auto& w : e.post) PostSmsState(w.id, w.state, w.reason);
|
||||
}
|
||||
|
||||
void PostSmsReceived(const imsd::engine::SmsReceived& m) {
|
||||
auto ev = std::make_unique<Event>();
|
||||
ev->type = Event::Type::SmsReceived;
|
||||
ev->uni = imsd::engine::ReceivedSmsId(smsRun_, NowEpoch(), ++smsInSeq_);
|
||||
ev->sms = m;
|
||||
Log(std::format("sms {}: from {} via {}, {}{}", ev->uni, m.from, m.sc, m.data.empty() ? std::format("{} bytes of text", m.text.size()) : std::format("{} bytes of 8-bit data", m.data.size()),
|
||||
m.segments > 1 ? std::format(" in {} segments", m.segments) : std::string()));
|
||||
PostEvent(std::move(ev));
|
||||
}
|
||||
void PostSmsState(const std::string& id, std::string_view state, std::string_view reason) {
|
||||
Log(std::format("sms {}: {}: {}", id, state, reason));
|
||||
auto ev = std::make_unique<Event>();
|
||||
ev->type = Event::Type::SmsState;
|
||||
ev->uni = id; ev->state = std::string(state); ev->reason = std::string(reason);
|
||||
PostEvent(std::move(ev));
|
||||
}
|
||||
|
||||
void DispatchRequest(const std::string& msg) {
|
||||
std::string callid(imsd::sip::Header(msg, "Call-ID").value_or(""));
|
||||
std::size_t sp = msg.find(' ');
|
||||
|
|
@ -2441,16 +2814,18 @@ private:
|
|||
// ACK is never answered — e.g. the caller ACKing the 486/487 of a
|
||||
// call machine we already dropped
|
||||
if (method == "ACK") return;
|
||||
// MESSAGE: a short message, a status report or a submit report
|
||||
// over IP (§7.9), or a page-mode text — the engine says what it
|
||||
// was and what to answer
|
||||
if (method == "MESSAGE") {
|
||||
OnInboundMessage(msg);
|
||||
return;
|
||||
}
|
||||
// reg-event NOTIFY: log the S-CSCF's reginfo (every binding it holds
|
||||
// for the implicit set, feature tags as stored), then 200 it below.
|
||||
// MESSAGE (terminating SMS-over-IP while +g.3gpp.smsip is
|
||||
// advertised): log the whole body — the 200 acks delivery, so the
|
||||
// journal is the only place the payload survives until real SMSoIP
|
||||
// handling exists.
|
||||
if (method == "NOTIFY" || method == "MESSAGE") {
|
||||
if (method == "NOTIFY") {
|
||||
std::string_view body = imsd::sip::Body(msg);
|
||||
if (method == "MESSAGE") Log(std::format("MESSAGE from {} ({} bytes):\n{}", imsd::sip::CallerId(msg), body.size(), body));
|
||||
else if (auto ev = imsd::sip::Header(msg, "Event"); ev && ev->starts_with("reg")) {
|
||||
if (auto ev = imsd::sip::Header(msg, "Event"); ev && ev->starts_with("reg")) {
|
||||
Log(std::format("reg-event NOTIFY ({} bytes):\n{}", body.size(), body));
|
||||
if (reply_) reply_(imsd::msg::BuildResponse200(ctx_, msg));
|
||||
OnRegEventNotify(msg, body);
|
||||
|
|
@ -2657,7 +3032,7 @@ private:
|
|||
void EmitStatus(bool registrationSignal) {
|
||||
auto ev = std::make_unique<Event>();
|
||||
ev->type = registrationSignal ? Event::Type::Registration : Event::Type::Status;
|
||||
ev->status = StatusSnapshot{registered_, local_, pcscf_, ppi_, reg_.expiry, reg_.cseq};
|
||||
ev->status = StatusSnapshot{registered_, local_, pcscf_, ppi_, reg_.expiry, reg_.cseq, smsc_};
|
||||
PostEvent(std::move(ev));
|
||||
}
|
||||
void PostAdded(const CallInfo& info) {
|
||||
|
|
@ -2700,6 +3075,20 @@ constexpr const char* IntrospectionXml = R"xml(
|
|||
<signal name="CallDeleted"><arg type="s" name="callUni"/></signal>
|
||||
<signal name="RegistrationChanged"><arg type="b" name="registered"/></signal>
|
||||
</interface>
|
||||
<interface name="net.catcrafts.IMS1.Messaging">
|
||||
<method name="Send">
|
||||
<arg type="s" name="number" direction="in"/>
|
||||
<arg type="s" name="text" direction="in"/>
|
||||
<arg type="a{sv}" name="options" direction="in"/>
|
||||
<arg type="s" name="id" direction="out"/>
|
||||
</method>
|
||||
<method name="GetStatus"><arg type="a{sv}" name="status" direction="out"/></method>
|
||||
<method name="Subscribe"/>
|
||||
<signal name="Received"><arg type="s" name="id"/><arg type="a{sv}" name="message"/></signal>
|
||||
<signal name="StateChanged">
|
||||
<arg type="s" name="id"/><arg type="s" name="state"/><arg type="s" name="reason"/>
|
||||
</signal>
|
||||
</interface>
|
||||
</node>)xml";
|
||||
|
||||
void HandleMethodCall(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* method, GVariant* params, GDBusMethodInvocation* inv, gpointer) {
|
||||
|
|
@ -2756,14 +3145,65 @@ void HandleMethodCall(GDBusConnection*, const gchar*, const gchar*, const gchar*
|
|||
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.UnknownMethod", "no such method");
|
||||
}
|
||||
|
||||
// net.catcrafts.IMS1.Messaging (§8.4): Send is gated by the Messaging
|
||||
// action; GetStatus is a read.
|
||||
void HandleMessagingMethod(GDBusConnection* conn, const gchar*, const gchar*, const gchar*, const gchar* method, GVariant* params, GDBusMethodInvocation* inv, gpointer) {
|
||||
std::string_view m = method;
|
||||
if (m == "Send") {
|
||||
const gchar* number = nullptr;
|
||||
const gchar* text = nullptr;
|
||||
GVariant* options = nullptr;
|
||||
g_variant_get(params, "(&s&s@a{sv})", &number, &text, &options);
|
||||
gboolean statusReport = FALSE;
|
||||
if (options) { g_variant_lookup(options, "status-report", "b", &statusReport); g_variant_unref(options); }
|
||||
if (!TheEngine->SmsEnabled()) {
|
||||
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.NotSupported", "SMS over IP is off (SMS_OVER_IMS=1 in /etc/imsd.env enables it)");
|
||||
return;
|
||||
}
|
||||
std::string id = TheEngine->SendSms(number ? number : "", text ? text : "", statusReport == TRUE);
|
||||
SendOrigins[id] = g_dbus_method_invocation_get_sender(inv);
|
||||
g_dbus_method_invocation_return_value(inv, g_variant_new("(s)", id.c_str()));
|
||||
return;
|
||||
}
|
||||
if (m == "Subscribe") {
|
||||
SubscribeMessaging(conn, g_dbus_method_invocation_get_sender(inv));
|
||||
g_dbus_method_invocation_return_value(inv, nullptr);
|
||||
return;
|
||||
}
|
||||
if (m == "GetStatus") {
|
||||
GVariantBuilder b;
|
||||
g_variant_builder_init(&b, G_VARIANT_TYPE("a{sv}"));
|
||||
// the configuration, not the registration snapshot: an asker before
|
||||
// the first registration (a script at login, an app at start) reads
|
||||
// the truth
|
||||
g_variant_builder_add(&b, "{sv}", "enabled", g_variant_new_boolean(TheEngine->SmsEnabled() ? TRUE : FALSE));
|
||||
g_variant_builder_add(&b, "{sv}", "smsc", g_variant_new_string(StatusSnap.smsc.c_str()));
|
||||
g_variant_builder_add(&b, "{sv}", "registered", g_variant_new_boolean(StatusSnap.registered ? TRUE : FALSE));
|
||||
g_variant_builder_add(&b, "{sv}", "subscribers", g_variant_new_uint32(static_cast<guint32>(Subscribers.size())));
|
||||
g_dbus_method_invocation_return_value(inv, g_variant_new("(a{sv})", &b));
|
||||
return;
|
||||
}
|
||||
g_dbus_method_invocation_return_dbus_error(inv, "org.freedesktop.DBus.Error.UnknownMethod", "no such method");
|
||||
}
|
||||
|
||||
bool IsRead(std::string_view method) { return method == "GetStatus" || method == "GetCalls"; }
|
||||
bool IsMessagingRead(std::string_view method) { return method == "GetStatus"; }
|
||||
constexpr char ErrAccessDenied[] = "org.freedesktop.DBus.Error.AccessDenied";
|
||||
const GDBusInterfaceVTable Vtable = { imsd::bus::Gated<HandleMethodCall, IsRead, ErrAccessDenied, Log>, nullptr, nullptr, {} };
|
||||
const GDBusInterfaceVTable MessagingVtable = { imsd::bus::Gated<HandleMessagingMethod, IsMessagingRead, ErrAccessDenied, Log, imsd::bus::MessagingAction>, nullptr, nullptr, {} };
|
||||
|
||||
void OnBusAcquired(GDBusConnection* conn, const gchar*, gpointer) {
|
||||
DbusConn = conn;
|
||||
GDBusNodeInfo* node = g_dbus_node_info_new_for_xml(IntrospectionXml, nullptr);
|
||||
g_dbus_connection_register_object(conn, ObjPath, node->interfaces[0], &Vtable, nullptr, nullptr, nullptr);
|
||||
GError* err = nullptr;
|
||||
GDBusNodeInfo* node = g_dbus_node_info_new_for_xml(IntrospectionXml, &err);
|
||||
if (!node) { Log(std::format("introspection XML: {}", err ? err->message : "?")); if (err) g_error_free(err); return; }
|
||||
for (GDBusInterfaceInfo** i = node->interfaces; *i; i++) {
|
||||
const GDBusInterfaceVTable* vt = std::string_view((*i)->name) == MessagingIface ? &MessagingVtable : &Vtable;
|
||||
if (!g_dbus_connection_register_object(conn, ObjPath, *i, vt, nullptr, nullptr, &err)) {
|
||||
Log(std::format("{} not registered at {}: {}", (*i)->name, ObjPath, err ? err->message : "?"));
|
||||
if (err) { g_error_free(err); err = nullptr; }
|
||||
}
|
||||
}
|
||||
g_dbus_node_info_unref(node);
|
||||
Log(std::format("object registered at {}", ObjPath));
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue