// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // lint-disable-file no-char-pointer /* ImsdMessages.Bus:Client — the GDBus client of net.catcrafts.IMS1.Messaging, the Sync logic's transport. Every call is asynchronous and answers on the GLib main loop; the signals and the name watch feed ImsdEvents (Sync), the watch's appeared callback being where Sync subscribes. One connection: the system bus, or the session bus for `imsd --session`. */ module; #include export module ImsdMessages.Bus:Client; import std; import ImsdMessages; import :Variant; namespace ImsdMessages::Bus { constexpr const char* imsdName = "net.catcrafts.IMS1"; constexpr const char* imsdPath = "/net/catcrafts/IMS1"; constexpr const char* imsdIface = "net.catcrafts.IMS1"; constexpr const char* messagingIface = "net.catcrafts.IMS1.Messaging"; constexpr gint callTimeoutMs = 10000; // Subscribe, List and Delete sit behind imsd's polkit gate, which allows // interaction: a rule that prompts gets two minutes. constexpr gint gatedTimeoutMs = 120000; // Send sits behind the gate too, and has no bound of the client's // (GDBus: G_MAXINT): imsd waits on a prompt without one and sends the // text once the prompt lets the call through, so a Send given up on // here would be failed by Sync and be sent all the same. The call ends // with imsd's answer, or with the bus's when imsd leaves it. constexpr gint sendTimeoutMs = G_MAXINT; } export namespace ImsdMessages::Bus { class ImsdClient : public ImsdTransport { public: explicit ImsdClient(GDBusConnection* conn) : conn(conn) {} ~ImsdClient() override { Stop(); } ImsdClient(const ImsdClient&) = delete; ImsdClient& operator=(const ImsdClient&) = delete; // Installs the signal subscriptions and the name watch. void Start(ImsdEvents& e) { events = &e; messagingSub = g_dbus_connection_signal_subscribe(conn, imsdName, messagingIface, nullptr, imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnMessagingSignal, this, nullptr); baseSub = g_dbus_connection_signal_subscribe(conn, imsdName, imsdIface, "RegistrationChanged", imsdPath, nullptr, G_DBUS_SIGNAL_FLAGS_NONE, OnBaseSignal, this, nullptr); watch = g_bus_watch_name_on_connection(conn, imsdName, G_BUS_NAME_WATCHER_FLAGS_NONE, OnAppeared, OnVanished, this, nullptr); } void Stop() { if (watch) g_bus_unwatch_name(watch); if (messagingSub) g_dbus_connection_signal_unsubscribe(conn, messagingSub); if (baseSub) g_dbus_connection_signal_unsubscribe(conn, baseSub); watch = 0; messagingSub = 0; baseSub = 0; events = nullptr; } void Subscribe(Done done) override { Call("Subscribe", nullptr, nullptr, [done = std::move(done)](GVariant*, GError* err) { done(err ? std::optional(ErrorFrom(err)) : std::nullopt); }); } // The Messaging status, the subscriber's own number in it (`ppi`, as // the frozen interface gives it: imsd reads both from one snapshot, // so one call never lacks a number it has). void GetStatus(std::function done) override { Call("GetStatus", nullptr, G_VARIANT_TYPE("(a{sv})"), [done = std::move(done)](GVariant* reply, GError* err) { if (err) { done(std::unexpected(ErrorFrom(err))); return; } GVariant* dict = g_variant_get_child_value(reply, 0); Status s = StatusFromVariant(dict); g_variant_unref(dict); done(std::move(s)); }); } void List(std::function done) override { Call("List", nullptr, G_VARIANT_TYPE("(a(sa{sv}))"), [done = std::move(done)](GVariant* reply, GError* err) { if (err) { done(std::unexpected(ErrorFrom(err))); return; } std::vector out; GVariant* array = g_variant_get_child_value(reply, 0); GVariantIter it; g_variant_iter_init(&it, array); while (GVariant* item = g_variant_iter_next_value(&it)) { const gchar* id = nullptr; GVariant* dict = nullptr; g_variant_get(item, "(&s@a{sv})", &id, &dict); out.push_back(ReceivedFromVariant(id ? id : "", dict)); g_variant_unref(dict); g_variant_unref(item); } g_variant_unref(array); done(std::move(out)); }); } void Delete(std::string id, Done done) override { Call("Delete", g_variant_new("(s)", id.c_str()), nullptr, [done = std::move(done)](GVariant*, GError* err) { done(err ? std::optional(ErrorFrom(err)) : std::nullopt); }); } void Send(std::string number, std::string text, bool statusReport, std::function done) override { Call("Send", g_variant_new("(ss@a{sv})", number.c_str(), text.c_str(), SendOptions(statusReport)), G_VARIANT_TYPE("(s)"), [done = std::move(done)](GVariant* reply, GError* err) { if (err) { done(std::unexpected(ErrorFrom(err))); return; } const gchar* id = nullptr; g_variant_get(reply, "(&s)", &id); done(std::string(id ? id : "")); }); } private: // One pending call's continuation: exactly one of reply and err is // set; both are freed by OnCallDone after it ran. using Reply = std::function; struct Pending { // one call's continuation and the client that hears a throw out of it Reply reply; ImsdClient* client; }; // A call on the Messaging interface; the client hears a throw out of // the reply as a fault (OnCallDone). void Call(const char* method, GVariant* params, const GVariantType* replyType, Reply reply) { const std::string_view name = method; const bool gated = name != "GetStatus"; g_dbus_connection_call(conn, imsdName, imsdPath, messagingIface, method, params, replyType, gated ? G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION : G_DBUS_CALL_FLAGS_NONE, name == "Send" ? sendTimeoutMs : gated ? gatedTimeoutMs : callTimeoutMs, nullptr, OnCallDone, new Pending{ std::move(reply), this }); } // Every reply passes here, inside GLib's dispatch, which no try // encloses: a throw out of the continuation (a read, an allocation; // the store catches its writes) is the events' fault, not the end // of the process. static void OnCallDone(GObject* source, GAsyncResult* result, gpointer data) { std::unique_ptr pending(static_cast(data)); GError* err = nullptr; GVariant* value = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, &err); try { pending->reply(value, err); } catch (const std::exception& e) { if (pending->client->events) pending->client->events->OnFault(e.what()); } if (value) g_variant_unref(value); if (err) g_error_free(err); } // The signal handlers run inside GLib's dispatch, which no try // encloses: a throw out of them is handed to the events as a fault // and the process goes on. static void OnMessagingSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar* signal, GVariant* params, gpointer data) { ImsdClient& self = *static_cast(data); if (!self.events) return; try { const std::string_view name = signal; if (name == "Received") { const gchar* id = nullptr; GVariant* dict = nullptr; g_variant_get(params, "(&s@a{sv})", &id, &dict); const ReceivedMessage m = ReceivedFromVariant(id ? id : "", dict); g_variant_unref(dict); self.events->OnReceived(m); } else if (name == "StateChanged") { const gchar* id = nullptr; const gchar* state = nullptr; const gchar* reason = nullptr; g_variant_get(params, "(&s&s&s)", &id, &state, &reason); self.events->OnStateChanged(id ? id : "", state ? state : "", reason ? reason : ""); } } catch (const std::exception& e) { self.events->OnFault(e.what()); } } static void OnBaseSignal(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer data) { ImsdClient& self = *static_cast(data); if (!self.events) return; gboolean registered = FALSE; g_variant_get(params, "(b)", ®istered); try { self.events->OnRegistrationChanged(registered == TRUE); } catch (const std::exception& e) { self.events->OnFault(e.what()); } } // The name watch's callbacks, guarded as the replies and the signal // handlers are. static void OnAppeared(GDBusConnection*, const gchar*, const gchar*, gpointer data) { ImsdClient& self = *static_cast(data); if (!self.events) return; try { self.events->OnImsdAppeared(); } catch (const std::exception& e) { self.events->OnFault(e.what()); } } static void OnVanished(GDBusConnection*, const gchar*, gpointer data) { ImsdClient& self = *static_cast(data); if (!self.events) return; try { self.events->OnImsdVanished(); } catch (const std::exception& e) { self.events->OnFault(e.what()); } } GDBusConnection* conn; ImsdEvents* events = nullptr; guint messagingSub = 0; guint baseSub = 0; guint watch = 0; }; }