An app could have nostrod pay an order: it called Pay of net.catcrafts.Nostro1.Checkout on the system bus, and nostrod paid from an account the user had chosen, after a dialog of its own. On 2026-11-22 the owner decided that a link takes its place. The app registers for payto links (RFC 8905), so that an app or a website can hand one to the desktop, and shows a link as its pay form filled in. The link: - The app's desktop entry takes the scheme (Exec=nostro-app %u, MimeType=x-scheme-handler/payto), and nostro-app takes an argument that is no option as a link: it overwrites it in argv and hands it to App::Open once the app has started. - ReadPaymentLink (Nostro.App:Forms) reads payto://iban/<IBAN> with the options amount, receiver-name and message, and refuses a link rather than guess at it, in a sentence of the app's own with nothing of the link in it. Among what it refuses: an IBAN whose check digits do not hold, one of the three options given twice, instruction, a comma in the amount, and a name or a message with a code point that is Unshown, or Blank and no plain space. - A link that is read waits until the accounts are read and DefaultCheckoutAccount has answered or failed, with a line on the accounts' page. Then App::TakeLink fills in the pay form, which says in a banner that a link filled it in, and with more than one account opens it under the choice of accounts that the form's From row has. A link pays nothing: the form's button sends, and polkit's dialog confirms as for any payment (design rule 12, and 14, which is new). - Unshown and Blank are the two tables the worker's Shown() works from. They move into Nostro:Utils, where the app's reader asks them too. The move is within the library. The reader holds a link's name to those two and to no more of Shown(): a name with an & is read, and the dialog shows it with a + as it does any name. The checkout: - nostrod serves one interface under one bus name. Gone are net.catcrafts.Nostro1.Checkout with its XML and its activation file, the polkit action Checkout, the module Nostro.Checkout with --product=checkout, and the worker's record of orders. That changes the published contract after a release, 0.0.0, and design rule 10 records it as the owner's decision. - DefaultCheckoutAccount and SetDefaultCheckoutAccount keep their names and signatures. The account they keep is where a link's pay form starts: nostrod's dialog for choosing it says "have pay links start from", the app's setting reads "Pay links start from", and `nostro checkout account` prints "pay links start from". - The D-Bus policy still lets nostrod own the old name: the nostrod of 0.0.0 asks for it when it starts, and the system files can be newer than the Flatpak it runs from. install.sh removes the old name's activation file. A user's checkouts.cdb is read by nothing any more, and is left where it is. - The Arch package stops installing the checkout's two files, and its pkgrel goes up to 2. Where makepkg -si finds a package of the version already built it installs that one again, which would bring the activation file back. The guide now says that pkgrel goes up with a change to what the package installs. - Bus::Interface goes too: the worker called it in two places, to tell a call to the checkout from one to the main interface. The review's own files follow. gate0 loses the build of --product=checkout, and the three lens sections that named the checkout no longer do, and ask about a link. The README has "Pay links" in place of "Checkout for apps", and AGENTS.consumer.md says what the app reads of a link. Its line on lib/json.hpp no longer gives a release: the file is of none, and the guide names its commit. The pay form and the accounts' page change only by a banner each, shown while a link is in play, which docs/screenshots/take.sh never has: the README's pictures stand. Tests: ShouldValidateForms reads and refuses links and fills the form from one. ShouldDriveTheApp opens links against a real nostrod on the fake bus: before the accounts are known, with no account, with one and with several, with the accounts known and the system bus gone, for a second user whose first connection pays their own accounts only, one that cannot be read, one whose name has an &, and through polkit's dialog to the payment. It now counts nostrod's answers to hold that the account pay links start from is read again once a connection is removed: the check it had there passed without that. ShouldHandleMoneyAndText holds the two tables at the ends of their ranges. ShouldServeEveryUser holds that nostrod serves no checkout, that the bus's policy lets an older nostrod own the old name, and the account pay links start from. ShouldRunCommands holds the CLI's wording. The review's gate0 passes at this commit: the version check, 17 tests, the builds of the CLI, the library, nostrod, the fake system, the app and its --debug-api build, and five lint runs that report nothing. tests/coverage.sh reports lines, functions and regions at 100.00%. Looked at on 2026-11-22 on the made-up system (run fake), on a desktop (KWin at a scale of 1.85). At 420x760, at --scale 3 --size 360x760 and at 1100x720 in the light look: a link's pay form under the choice of accounts, the form after a tap beside that choice, and the accounts' page while a link waits, its line above the rows that stand in for the accounts (--bank-delay 10000). At 420x760: that line above what the page says when the accounts cannot be read (--polkit deny) and above the accounts themselves (--polkit slow, the link opened in the running app), the settings' row and page for the account pay links start from, the sheet for a link that cannot be read, and with --empty the sheet for no account.
344 lines
16 KiB
C++
344 lines
16 KiB
C++
// SPDX-License-Identifier: LGPL-3.0-only
|
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
module;
|
|
|
|
#include <systemd/sd-bus.h>
|
|
#include <systemd/sd-event.h>
|
|
#include <errno.h>
|
|
#include <signal.h>
|
|
#include <spawn.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/wait.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
module Nostro:Daemon_impl;
|
|
import std;
|
|
import :Daemon;
|
|
import :Bus;
|
|
|
|
using namespace Nostro;
|
|
using namespace Nostro::Bus;
|
|
|
|
// The front holds no connector and no secret: it only learns who calls, starts that user's worker, and passes the call
|
|
// on. Each worker is a process of its own, so one user's connectors never share a process with another's, and the
|
|
// library's process-wide state (the connector list, the paths, the lock, the open tables) belongs to one user.
|
|
|
|
namespace {
|
|
struct Front;
|
|
|
|
// One user's worker: its process, and the D-Bus connection to it over a socketpair.
|
|
struct Worker {
|
|
Front* front = nullptr;
|
|
std::uint32_t uid = 0;
|
|
pid_t pid = -1;
|
|
BusPtr bus;
|
|
// Set once the connection is gone, to free it after the dispatch that noticed.
|
|
sd_event_source* reap = nullptr;
|
|
|
|
Worker() = default;
|
|
Worker(const Worker&) = delete;
|
|
Worker& operator=(const Worker&) = delete;
|
|
~Worker() {
|
|
sd_event_source_unref(reap);
|
|
}
|
|
};
|
|
|
|
struct Front {
|
|
DaemonOptions options;
|
|
sd_event* event = nullptr;
|
|
// Before the connection it is registered with, which then goes first however RunDaemon ends.
|
|
std::vector<sd_bus_vtable> vtable;
|
|
BusPtr bus;
|
|
std::map<std::uint32_t, std::unique_ptr<Worker>> workers;
|
|
std::size_t inFlight = 0;
|
|
sd_event_source* idle = nullptr;
|
|
};
|
|
|
|
// A call handed to a worker, waiting for its answer.
|
|
struct Forwarded {
|
|
Front* front = nullptr;
|
|
MessagePtr call;
|
|
};
|
|
|
|
// Refused before any worker sees the call: a caller the bus cannot name, or a uid without a login session.
|
|
struct Refused : std::runtime_error {
|
|
using std::runtime_error::runtime_error;
|
|
};
|
|
|
|
std::uint64_t Microseconds(std::chrono::seconds duration) {
|
|
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(duration).count());
|
|
}
|
|
|
|
void Touch(Front& front) {
|
|
sd_event_source_set_time_relative(front.idle, Microseconds(front.options.idle));
|
|
sd_event_source_set_enabled(front.idle, SD_EVENT_ONESHOT);
|
|
}
|
|
|
|
// Once idle with no call under way and no worker left, the front ends; D-Bus activation starts it again.
|
|
std::int32_t OnIdle(sd_event_source*, std::uint64_t, void* userdata) {
|
|
Front& front = *static_cast<Front*>(userdata);
|
|
if(front.inFlight == 0 && front.workers.empty()) {
|
|
return sd_event_exit(front.event, 0);
|
|
}
|
|
Touch(front);
|
|
return 0;
|
|
}
|
|
|
|
std::int32_t OnBusGone(sd_bus_message*, void* userdata, sd_bus_error*) {
|
|
sd_event_exit(static_cast<Front*>(userdata)->event, 0);
|
|
return 0;
|
|
}
|
|
|
|
// Calls a method of a service on the system bus and returns its answer, or throws with what it said.
|
|
template<typename... Args>
|
|
MessagePtr CallSystem(sd_bus* bus, std::string_view destination, std::string_view path, std::string_view interface, std::string_view member, std::string_view types, Args... args) {
|
|
Error error;
|
|
sd_bus_message* reply = nullptr;
|
|
const std::int32_t result = sd_bus_call_method(bus, destination.data(), path.data(), interface.data(), member.data(), &error.error, &reply, types.data(), args...);
|
|
if(result < 0) {
|
|
throw std::runtime_error(std::format("{} {}: {}", destination, member, ErrorMessage(error.error)));
|
|
}
|
|
return MessagePtr(reply);
|
|
}
|
|
|
|
// The uid behind a connection, as the bus knows it. Asked of the bus itself rather than worked out by sd-bus, which
|
|
// behaves the same on every bus implementation.
|
|
std::uint32_t CallerUid(sd_bus* bus, const std::string& sender) {
|
|
const MessagePtr reply = CallSystem(bus, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetConnectionCredentials", "s", sender.c_str());
|
|
std::optional<std::uint32_t> uid;
|
|
Enter(reply.get(), 'a', "{sv}");
|
|
while(ThrowOnSdBus(sd_bus_message_at_end(reply.get(), 0), "read the caller's credentials") == 0) {
|
|
Enter(reply.get(), 'e', "sv");
|
|
if(Read<std::string>(reply.get()) == "UnixUserID") {
|
|
Enter(reply.get(), 'v', "u");
|
|
uid = Read<std::uint32_t>(reply.get());
|
|
Leave(reply.get());
|
|
} else {
|
|
ThrowOnSdBus(sd_bus_message_skip(reply.get(), "v"), "read the caller's credentials");
|
|
}
|
|
Leave(reply.get());
|
|
}
|
|
Leave(reply.get());
|
|
if(!uid) {
|
|
throw Refused(std::format("the bus did not say which user {} is", sender));
|
|
}
|
|
return *uid;
|
|
}
|
|
|
|
// The user name logind has for `uid`: the worker keeps it beside the user's files, so a uid handed to a new user
|
|
// after the old one was deleted does not open the old one's connectors. A uid logind does not know is refused.
|
|
std::string LogindName(sd_bus* bus, std::uint32_t uid) {
|
|
std::string path;
|
|
try {
|
|
const MessagePtr user = CallSystem(bus, "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetUser", "u", uid);
|
|
path = ReadText(user.get(), 'o');
|
|
} catch(const std::runtime_error& e) {
|
|
throw Refused(std::format("nostrod serves users with a login session, and logind knows no user {} ({})", uid, e.what()));
|
|
}
|
|
const MessagePtr name = CallSystem(bus, "org.freedesktop.login1", path, "org.freedesktop.DBus.Properties", "Get", "ss", "org.freedesktop.login1.User", "Name");
|
|
Enter(name.get(), 'v', "s");
|
|
std::string text = Read<std::string>(name.get());
|
|
Leave(name.get());
|
|
return text;
|
|
}
|
|
|
|
std::int32_t OnReap(sd_event_source*, void* userdata) {
|
|
Worker& worker = *static_cast<Worker*>(userdata);
|
|
Front& front = *worker.front;
|
|
waitpid(worker.pid, nullptr, 0);
|
|
front.workers.erase(worker.uid);
|
|
Touch(front);
|
|
return 0;
|
|
}
|
|
|
|
// A worker's connection ended: it went idle, or it died. Every call it still had was failed by sd-bus before this
|
|
// signal, so all that is left is to reap the process, which cannot happen inside the connection's own dispatch.
|
|
// (sd-bus callbacks return 0 whatever happens: a negative result from one closes the connection it came on.)
|
|
std::int32_t OnWorkerGone(sd_bus_message*, void* userdata, sd_bus_error*) {
|
|
Worker& worker = *static_cast<Worker*>(userdata);
|
|
if(sd_event_add_defer(worker.front->event, &worker.reap, OnReap, &worker) >= 0) {
|
|
sd_event_source_set_enabled(worker.reap, SD_EVENT_ONESHOT);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// A socket that closes itself.
|
|
struct Descriptor {
|
|
std::int32_t fd = -1;
|
|
Descriptor() = default;
|
|
Descriptor(const Descriptor&) = delete;
|
|
Descriptor& operator=(const Descriptor&) = delete;
|
|
~Descriptor() {
|
|
if(fd != -1) {
|
|
close(fd);
|
|
}
|
|
}
|
|
};
|
|
|
|
// Starts `uid`'s worker: this executable again, as `nostrod --worker`, with its end of a socketpair as fd 3.
|
|
// posix_spawn rather than fork and exec: nothing of this process runs in the child before the exec.
|
|
std::unique_ptr<Worker> Spawn(Front& front, std::uint32_t uid, const std::string& name) {
|
|
std::array<std::int32_t, 2> ends{};
|
|
if(socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, ends.data()) == -1) {
|
|
throw std::system_error(errno, std::generic_category(), "cannot make a socket for a worker");
|
|
}
|
|
Descriptor ours;
|
|
ours.fd = ends[0];
|
|
Descriptor theirs;
|
|
theirs.fd = ends[1];
|
|
|
|
std::vector<std::string> args = {"nostrod", "--worker", std::to_string(uid), name, "--state", front.options.state.string(), "--idle", std::to_string(front.options.idle.count()), "--prompt-timeout", std::to_string(front.options.promptTimeout.count())};
|
|
// posix_spawn takes C strings.
|
|
// lint-disable-next-line no-char-pointer
|
|
std::vector<char*> argv;
|
|
for(std::string& arg : args) {
|
|
argv.push_back(arg.data());
|
|
}
|
|
argv.push_back(nullptr);
|
|
posix_spawn_file_actions_t actions;
|
|
posix_spawn_file_actions_init(&actions);
|
|
// Duplicated onto fd 3 without close-on-exec; POSIX clears the flag even when the socket already is fd 3.
|
|
posix_spawn_file_actions_adddup2(&actions, theirs.fd, 3);
|
|
pid_t pid = -1;
|
|
const std::int32_t spawned = posix_spawn(&pid, "/proc/self/exe", &actions, nullptr, argv.data(), environ);
|
|
posix_spawn_file_actions_destroy(&actions);
|
|
if(spawned != 0) {
|
|
throw std::system_error(spawned, std::generic_category(), "cannot start a worker");
|
|
}
|
|
|
|
std::unique_ptr<Worker> worker = std::make_unique<Worker>();
|
|
worker->front = &front;
|
|
worker->uid = uid;
|
|
worker->pid = pid;
|
|
sd_bus* bus = nullptr;
|
|
ThrowOnSdBus(sd_bus_new(&bus), "connect to a worker");
|
|
worker->bus.reset(bus);
|
|
ThrowOnSdBus(sd_bus_set_fd(bus, ours.fd, ours.fd), "connect to a worker");
|
|
// The connection owns the socket now.
|
|
ours.fd = -1;
|
|
ThrowOnSdBus(sd_bus_set_description(bus, std::format("worker for uid {}", uid).c_str()), "connect to a worker");
|
|
ThrowOnSdBus(sd_bus_start(bus), "connect to a worker");
|
|
ThrowOnSdBus(sd_bus_match_signal(bus, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnWorkerGone, worker.get()), "watch a worker");
|
|
ThrowOnSdBus(sd_bus_attach_event(bus, front.event, SD_EVENT_PRIORITY_NORMAL), "connect to a worker");
|
|
return worker;
|
|
}
|
|
|
|
Worker& WorkerFor(Front& front, std::uint32_t uid) {
|
|
if(const auto existing = front.workers.find(uid); existing != front.workers.end()) {
|
|
return *existing->second;
|
|
}
|
|
const std::string name = LogindName(front.bus.get(), uid);
|
|
return *front.workers.emplace(uid, Spawn(front, uid, name)).first->second;
|
|
}
|
|
|
|
// The call as the worker gets it: the same method and arguments, from the caller's unique name, which is what the
|
|
// worker asks polkit about, and allowing a password prompt only when the caller did.
|
|
MessagePtr Copy(sd_bus* to, sd_bus_message* call, const std::string& sender) {
|
|
sd_bus_message* copy = nullptr;
|
|
ThrowOnSdBus(sd_bus_message_new_method_call(to, ©, nullptr, sd_bus_message_get_path(call), sd_bus_message_get_interface(call), sd_bus_message_get_member(call)), "pass a call on");
|
|
MessagePtr owned(copy);
|
|
if(IsSensitive(Member(call))) {
|
|
ThrowOnSdBus(sd_bus_message_sensitive(copy), "pass a call on");
|
|
}
|
|
ThrowOnSdBus(sd_bus_message_rewind(call, 1), "pass a call on");
|
|
ThrowOnSdBus(sd_bus_message_copy(copy, call, 1), "pass a call on");
|
|
ThrowOnSdBus(sd_bus_message_set_sender(copy, sender.c_str()), "pass a call on");
|
|
ThrowOnSdBus(sd_bus_message_set_allow_interactive_authorization(copy, sd_bus_message_get_allow_interactive_authorization(call)), "pass a call on");
|
|
return owned;
|
|
}
|
|
|
|
// The worker's answer, as the answer to the caller.
|
|
std::int32_t OnWorkerReply(sd_bus_message* reply, void* userdata, sd_bus_error*) {
|
|
const std::unique_ptr<Forwarded> forwarded(static_cast<Forwarded*>(userdata));
|
|
Front& front = *forwarded->front;
|
|
front.inFlight--;
|
|
Touch(front);
|
|
sd_bus_message* call = forwarded->call.get();
|
|
if(sd_bus_message_is_method_error(reply, nullptr)) {
|
|
const sd_bus_error* error = sd_bus_message_get_error(reply);
|
|
// sd-bus fails a call whose worker went away, or did not answer in time, with errors of its own.
|
|
if(sd_bus_error_has_names(error, SD_BUS_ERROR_NO_REPLY, SD_BUS_ERROR_TIMEOUT, SD_BUS_ERROR_DISCONNECTED)) {
|
|
sd_bus_reply_method_errorf(call, errorFailed.data(), "nostrod's worker for you stopped before it answered (%s): what you asked for may have been carried out, check before trying again", ErrorMessage(*error).c_str());
|
|
} else {
|
|
sd_bus_reply_method_error(call, error);
|
|
}
|
|
return 0;
|
|
}
|
|
// These fail only when memory runs out; the caller's own timeout then answers for them.
|
|
sd_bus_message* answer = nullptr;
|
|
sd_bus_message_new_method_return(call, &answer);
|
|
const MessagePtr owned(answer);
|
|
sd_bus_message_rewind(reply, 1);
|
|
sd_bus_message_copy(answer, reply, 1);
|
|
sd_bus_send(nullptr, answer, nullptr);
|
|
return 0;
|
|
}
|
|
|
|
// Every method of the interface: passed on to the caller's worker, whose answer is relayed when it comes, so a
|
|
// password prompt one user leaves open holds up nobody else.
|
|
std::int32_t Forward(sd_bus_message* call, void* userdata, sd_bus_error* error) {
|
|
Front& front = *static_cast<Front*>(userdata);
|
|
Touch(front);
|
|
try {
|
|
const std::string sender = Sender(call);
|
|
Worker& worker = WorkerFor(front, CallerUid(sd_bus_message_get_bus(call), sender));
|
|
const MessagePtr copy = Copy(worker.bus.get(), call, sender);
|
|
std::unique_ptr<Forwarded> forwarded = std::make_unique<Forwarded>(&front, MessagePtr(sd_bus_message_ref(call)));
|
|
// Long enough for the prompt and then the bank, which waits out its rate limits.
|
|
ThrowOnSdBus(sd_bus_call_async(worker.bus.get(), nullptr, copy.get(), OnWorkerReply, forwarded.get(), Microseconds(front.options.promptTimeout + std::chrono::minutes(10))), "pass a call on");
|
|
// OnWorkerReply owns it now.
|
|
forwarded.release();
|
|
front.inFlight++;
|
|
return 1;
|
|
} catch(const Refused& e) {
|
|
return sd_bus_error_set(error, SD_BUS_ERROR_ACCESS_DENIED, e.what());
|
|
} catch(const std::exception& e) {
|
|
return sd_bus_error_set(error, errorFailed.data(), e.what());
|
|
}
|
|
}
|
|
|
|
// The system bus connection that serves nostrod's interface under its name, every method passed on by Forward, and
|
|
// ends the loop when the bus goes.
|
|
BusPtr Serve(Front& front) {
|
|
sd_bus* bus = nullptr;
|
|
ThrowOnSdBus(sd_bus_open_system_with_description(&bus, "nostrod"), "connect to the system bus");
|
|
BusPtr owned(bus);
|
|
ThrowOnSdBus(sd_bus_add_object_vtable(bus, nullptr, objectPath.data(), interfaceName.data(), front.vtable.data(), &front), std::format("serve {}", interfaceName));
|
|
ThrowOnSdBus(sd_bus_match_signal(bus, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnBusGone, &front), "watch the system bus");
|
|
ThrowOnSdBus(sd_bus_request_name(bus, busName.data(), 0), std::format("own {}", busName));
|
|
ThrowOnSdBus(sd_bus_attach_event(bus, front.event, SD_EVENT_PRIORITY_NORMAL), std::format("serve {}", interfaceName));
|
|
return owned;
|
|
}
|
|
}
|
|
|
|
std::int32_t Nostro::RunDaemon(const DaemonOptions& options) {
|
|
Front front;
|
|
front.options = options;
|
|
ThrowOnSdBus(sd_event_new(&front.event), "make an event loop");
|
|
// systemd stops the service with SIGTERM: the loop ends then, and everything is closed and flushed on the way out.
|
|
sigset_t terminate{};
|
|
sigemptyset(&terminate);
|
|
sigaddset(&terminate, SIGTERM);
|
|
sigprocmask(SIG_BLOCK, &terminate, nullptr);
|
|
ThrowOnSdBus(sd_event_add_signal(front.event, nullptr, SIGTERM, nullptr, nullptr), "watch for SIGTERM");
|
|
|
|
front.vtable = Vtable(methods, [](std::string_view) { return &Forward; });
|
|
front.bus = Serve(front);
|
|
ThrowOnSdBus(sd_event_add_time_relative(front.event, &front.idle, CLOCK_MONOTONIC, Microseconds(options.idle), 0, OnIdle, &front), "set the idle timer");
|
|
|
|
const std::int32_t result = sd_event_loop(front.event);
|
|
|
|
// Closing a worker's connection ends it; wait for each, so none outlives the front.
|
|
for(auto& [uid, worker] : front.workers) {
|
|
worker->bus.reset();
|
|
waitpid(worker->pid, nullptr, 0);
|
|
}
|
|
front.workers.clear();
|
|
front.bus.reset();
|
|
sd_event_source_unref(front.idle);
|
|
sd_event_unref(front.event);
|
|
ThrowOnSdBus(result, "run the event loop");
|
|
return 0;
|
|
}
|