Nostro/implementations/Nostro-Daemon.cpp

354 lines
17 KiB
C++
Raw Normal View History

2026-11-01 18:35:23 +01:00
// 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 Nostro.Checkout;
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 connections, so the connection each is registered with goes first however RunDaemon ends.
std::vector<sd_bus_vtable> vtable;
std::vector<sd_bus_vtable> checkoutVtable;
BusPtr bus;
// Checkout::busName, with net.catcrafts.Nostro1.Checkout alone, on a connection of its own: an app allowed to
// talk to that name and no other (a Flatpak's --system-talk-name) may call its owner's unique name too, and this
// one serves nothing else.
BusPtr checkout;
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, &copy, 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());
}
}
// A system bus connection that serves `interface` under `name`, every method passed on by Forward, and ends the
// loop when the bus goes.
BusPtr Serve(Front& front, std::string_view description, std::string_view name, std::string_view interface, std::vector<sd_bus_vtable>& vtable) {
sd_bus* bus = nullptr;
ThrowOnSdBus(sd_bus_open_system_with_description(&bus, description.data()), "connect to the system bus");
BusPtr owned(bus);
ThrowOnSdBus(sd_bus_add_object_vtable(bus, nullptr, objectPath.data(), interface.data(), vtable.data(), &front), std::format("serve {}", interface));
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, name.data(), 0), std::format("own {}", name));
ThrowOnSdBus(sd_bus_attach_event(bus, front.event, SD_EVENT_PRIORITY_NORMAL), std::format("serve {}", interface));
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.checkoutVtable = Vtable(checkoutMethods, [](std::string_view) { return &Forward; });
// The main name last: systemd counts the service as started once it is owned, and by then both are.
front.checkout = Serve(front, "nostrod checkout", Checkout::busName, Checkout::interfaceName, front.checkoutVtable);
front.bus = Serve(front, "nostrod", busName, interfaceName, front.vtable);
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();
front.checkout.reset();
sd_event_source_unref(front.idle);
sd_event_unref(front.event);
ThrowOnSdBus(result, "run the event loop");
return 0;
}