// SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // lint-disable-file no-char-pointer /* imsd-messages — the SMS app for imsd's Messaging interface (net.catcrafts.IMS1.Messaging on the system bus). This is the executable. It owns the session-bus name (one instance; a later launch forwards to it), opens the database, connects the GDBus client to the Sync logic and the notifier, and runs the GLib main loop. A --send errand takes no name and imports nothing. Modes: imsd-messages the app (the window arrives with the UI milestone) imsd-messages --daemon resident without a window: imports and notifies; beside a running instance it ends at once imsd-messages --headless --daemon with a log line per event (the ssh smoke test) imsd-messages --send N TEXT sends one text; exits once imsd has sent or failed it imsd-messages --quit asks the running instance to exit imsd-messages sms:+316... forwards a conversation to a running instance --session talks to `imsd --session` on the session bus; --data-dir and --country override the database directory and the default country code. */ #include #include import std; import Crafter.DB; import ImsdMessages; import ImsdMessages.Bus; using namespace ImsdMessages; namespace fs = std::filesystem; namespace { struct Options { bool daemon = false; bool headless = false; bool session = false; bool quit = false; bool version = false; bool help = false; std::optional> send; std::optional uri; std::optional dataDir; std::string country; std::string error; }; Options Parse(std::span args) { Options o; for (std::size_t i = 0; i < args.size(); ++i) { const std::string_view a = args[i]; if (a == "--daemon") o.daemon = true; else if (a == "--headless") o.daemon = o.headless = true; else if (a == "--session") o.session = true; else if (a == "--quit") o.quit = true; else if (a == "--version") o.version = true; else if (a == "--help" || a == "-h") o.help = true; else if (a == "--send" && i + 2 < args.size()) { o.send = std::pair(args[i + 1], args[i + 2]); o.daemon = o.headless = true; i += 2; } else if (a == "--data-dir" && i + 1 < args.size()) o.dataDir = fs::path(args[++i]); else if (a == "--country" && i + 1 < args.size()) o.country = args[++i]; else if (a.starts_with("sms:")) o.uri = std::string(a); else o.error = std::format("unknown argument: {}", a); } if (o.send && DialledNumber(o.send->first).empty()) o.error = "--send: NUMBER is empty"; // What goes over D-Bus goes as strings, which are UTF-8: GLib would put // its own text in the place of bytes in another encoding — imsd would // send that text, and a forwarded link would name nobody. const auto utf8 = [](const std::string& s) { return g_utf8_validate(s.data(), static_cast(s.size()), nullptr) != FALSE; }; if (o.send && !(utf8(o.send->first) && utf8(o.send->second))) o.error = "--send: NUMBER and TEXT have to be UTF-8"; if (o.uri && !utf8(*o.uri)) o.error = "the sms: link has to be UTF-8"; // A country code as the ITU's length rule reads one (none begins with 0, // and CountryCodeOf gives it back from a number that begins with it): a // completed key is made of it as it is, and read by that rule. if (!o.country.empty() && (o.country.front() == '0' || CountryCodeOf(std::format("+{}0000000", o.country)) != o.country)) o.error = "--country: not a country code (one to three digits, without its +)"; if (o.send && o.quit) o.error = "--send and --quit do not go together"; if (o.send && o.uri) o.error = "--send and an sms: link do not go together"; return o; } void Log(std::string_view line) { std::println("imsd-messages: {}", line); std::fflush(stdout); } fs::path DefaultDataDir() { const gchar* xdg = g_get_user_data_dir(); return fs::path(xdg ? xdg : ".") / "imsd-messages"; } // What the daemon does with Sync's events: log, notify, and run the // --send errand to its end. class Shell : public SyncListener { public: Shell(bool verbose, Bus::Notifier& notifier, GMainLoop* loop) : verbose(verbose), notifier(notifier), loop(loop) {} ~Shell() { if (refreshTimer) g_source_remove(refreshTimer); } Shell(const Shell&) = delete; Shell& operator=(const Shell&) = delete; Sync* sync = nullptr; std::optional> send; SendErrand errand; // the --send errand's rule (Sync's); the loop, the clock and the log are here std::int32_t exitCode = 0; void OnStatus(const AppStatus& s) override { if (verbose) { const std::string banner = BannerText(s); Log(std::format("status: imsd {} enabled {} registered {} subscribed {}{}{}", s.imsdPresent ? "up" : "down", s.enabled, s.registered, s.subscribed, s.subscribeDenied ? " (subscribe refused)" : s.subscribeFailed ? " (subscribe failed)" : "", banner.empty() ? "" : std::format(" — {}", banner))); } // What failed against a present imsd is tried again every 30 s. if (sync && sync->RefreshWanted() && !refreshTimer) refreshTimer = g_timeout_add_seconds(30, OnRefresh, this); // The errand sends once GetStatus has answered, which gives the // subscriber's country code for the key (the number itself goes as // dialled), and lets imsd judge the rest: imsd answers a Send to its // caller, subscribed or not, so a refused or unregistered errand // ends with imsd's own reason. if (send && sync && errand.SendDue(s)) End(errand.Sent(sync->Send(NormalizeNumber(send->first, sync->CountryCode()), DialledNumber(send->first), send->second, true))); } // A signalled text the store refused: it is in no list and may be in // no store, imsd's included, so the notification is where it shows. void OnUnstored(const Message& m) override { Log(verbose ? std::format("received {} from {}: not stored, held until there is room ({} byte(s))", m.imsdId, m.conversation, m.text.size()) : std::string("a received text could not be stored: held until there is room")); notifier.Notify(m); } void OnImported(const Message& m) override { if (verbose) Log(std::format("received {} from {}: {} ({} byte(s), segments {})", m.imsdId, m.conversation, m.read ? "read" : "unread", m.text.size(), m.segments)); if (!m.read) notifier.Notify(m); } void OnMessageChanged(const Message& m) override { if (verbose) Log(std::format("message {} ({}): {}{}{}", m.id, m.imsdId.empty() ? "no imsd id yet" : m.imsdId, StateCaption(m.state), m.stateReason.empty() ? "" : " — ", m.stateReason)); // The errand's message: imsd's word for the submission ends it — sent // (0), or failed (1); a status report's word follows sent (imsd's // order) — as does the app's own failure (imsd refused the Send, or // stopped), a Failed too. if (send) End(errand.Changed(m)); } void OnLog(std::string_view line) override { Log(line); } // SIGINT or SIGTERM: an errand still waiting reports no final state (2), // not the sent it never saw; a resident instance says why it stops (a // session bus closing under it sends SIGTERM too, GDBus's exit-on-close). void OnSignal() { if (send) End(errand.NoFinalState("interrupted before a final state")); else Log("stopping: SIGINT or SIGTERM"); g_main_loop_quit(loop); } // The --send errand's clock, the 60 s source's: for imsd to be ready // and to take the text (SendErrand's TimedOut). void OnTimeout() { End(errand.TimedOut("60 s")); } private: // The errand's end, once (the rule's): the exit code, the log line, the // loop's end. void End(std::optional end) { if (!end) return; exitCode = end->code; Log(std::format("--send: {}{}{}", end->caption, end->reason.empty() ? "" : ": ", end->reason)); g_main_loop_quit(loop); } // Every 30 s while a refresh is wanted: the source keeps itself, since a // refresh whose cause stands (the store refusing again, told once) arms // no status; OnStatus arms it only while none runs. static gboolean OnRefresh(gpointer data) { Shell& self = *static_cast(data); if (self.sync && self.sync->RefreshWanted()) { self.sync->Refresh(); if (self.sync->RefreshWanted()) return G_SOURCE_CONTINUE; } self.refreshTimer = 0; return G_SOURCE_REMOVE; } bool verbose; Bus::Notifier& notifier; GMainLoop* loop; guint refreshTimer = 0; }; gboolean OnQuitSignal(gpointer data) { static_cast(data)->OnSignal(); return G_SOURCE_REMOVE; } gboolean OnSendTimeout(gpointer data) { static_cast(data)->OnTimeout(); return G_SOURCE_REMOVE; } } int main(int argc, char** argv) { const Options o = Parse(std::span(argv + 1, static_cast(argc > 0 ? argc - 1 : 0))); if (!o.error.empty()) { Log(o.error); return 2; } if (o.version) { std::println("imsd-messages {} (glib {})", version, Bus::glibVersion); return 0; } if (o.help) { std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [sms:NUMBER] [--version]"); return 0; } GError* err = nullptr; GDBusConnection* session = g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &err); if (err) { Log(std::format("no session bus ({}): one instance is not enforced and notifications are off", err->message)); g_clear_error(&err); } GMainLoop* loop = g_main_loop_new(nullptr, FALSE); Bus::Instance instance(session, { .activate = [] { Log("activated (the window comes with the UI milestone)"); }, .open = [](std::vector uris) { Log(std::format("open {} (the window comes with the UI milestone)", uris.empty() ? std::string_view("no link") : std::string_view(uris.front()))); }, .quit = [loop] { g_main_loop_quit(loop); }, }); // A send errand is a client of its own: it neither owns the name nor // forwards to the instance that does. const std::optional owning = session && !o.send ? std::optional(instance.Own()) : std::nullopt; // The name could not be taken, and nobody is shown to hold it: this // process cannot be the instance and knows of none. It says so and // fails, whatever it was asked for. if (owning == Bus::Instance::Owning::Failed) { Log(std::format("could not take the name {} on the session bus: {}", Bus::appId, instance.Failure())); return 1; } if (owning == Bus::Instance::Owning::Taken) { if (o.quit) return Bus::Instance::ForwardQuit(session) ? 0 : 1; // A second --daemon (a login entry beside the running instance) has // nothing to add, and a forwarded Activate would ask for the window; // the smoke test says it ran nothing. if (o.daemon && !o.uri) { Log(o.headless ? "already running: the smoke test ran nothing" : "already running"); return o.headless ? 1 : 0; } const bool forwarded = o.uri ? Bus::Instance::ForwardOpen(session, *o.uri) : Bus::Instance::ForwardActivate(session); Log(forwarded ? "already running: forwarded" : "another instance owns the name but did not answer"); return forwarded ? 0 : 1; } if (o.quit) { Log("not running"); return 0; } const fs::path dataDir = o.dataDir.value_or(DefaultDataDir()); std::optional store; try { store.emplace(dataDir); } catch (const Crafter::DB::LockedError& e) { Log(std::format("another imsd-messages holds {}: {}", dataDir.string(), e.what())); return 1; } catch (const std::exception& e) { Log(std::format("cannot open the database in {}: {}", dataDir.string(), e.what())); return 1; } GDBusConnection* bus = g_bus_get_sync(o.session ? G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM, nullptr, &err); if (err) { Log(std::format("no {} bus: {}", o.session ? "session" : "system", err->message)); g_clear_error(&err); return 1; } Bus::Notifier notifier(session); notifier.onOpen = [](const std::string& conversation) { Log(std::format("notification tapped for {} (the window comes with the UI milestone)", conversation)); }; if (o.headless) notifier.onLog = Log; Shell shell(o.headless, notifier, loop); shell.send = o.send; Bus::ImsdClient client(bus); Sync sync(*store, client, shell, o.country); // The errand runs beside the instance that owns the user's store (with // a --data-dir of its own): imsd's texts are that instance's to import. if (o.send) sync.LeaveTexts(); shell.sync = &sync; Log(std::format("{} {}; database {}; imsd on the {} bus; notifications {}", version, o.send ? "sending one text" : o.daemon ? "resident" : "starting", dataDir.string(), o.session ? "session" : "system", notifier.Enabled() ? "on" : "off")); client.Start(sync); g_unix_signal_add(SIGINT, OnQuitSignal, &shell); g_unix_signal_add(SIGTERM, OnQuitSignal, &shell); if (o.send) g_timeout_add_seconds(60, OnSendTimeout, &shell); g_main_loop_run(loop); client.Stop(); store->Flush(); if (session) g_dbus_connection_flush_sync(session, nullptr, nullptr); // a forwarded quit's reply, still queued, goes out before the exit g_main_loop_unref(loop); return shell.exitCode; }