Nostro/tests/Support/FakeBus.inc

458 lines
21 KiB
PHP
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®
// A system bus for tests, included after <systemd/sd-bus.h>, <systemd/sd-id128.h>, <poll.h>, <spawn.h>,
// <sys/resource.h>, <sys/socket.h>, <sys/un.h>, <sys/wait.h>, <unistd.h> and `import std;`. It listens on a unix socket and stands in
// for the bus driver, for logind and for polkit; every other call goes to the connection that owns the name it is sent
// to, from the caller's unique name, and every answer back to whoever it is for. Each connection has a uid: one from
// this test's own process gets Bus::clientUid as it is when the connection is made, so a test plays a user by setting
// it before Client::System(); one from another process (nostrod, its workers) keeps its own. Point sd-bus at it by
// setting DBUS_SYSTEM_BUS_ADDRESS to Address() before any thread starts, so before the Bus itself.
namespace Fake {
// What polkit answers a check with.
enum class Polkit : std::uint8_t {
Allow, // authorized
Password, // needs the user's password: authorized when the call lets a dialog ask for it, a challenge if not
Deny, // refused by policy (polkit.result=no)
Dismiss, // the dialog was closed: not authorized, polkit.result=auth_self, which is how Plasma's agent answers
Absent, // no polkit on the bus: ServiceUnknown, without a message
Silent, // never answers
Slow, // authorized, a second later
};
// One CheckAuthorization as polkit got it.
struct PolkitCheck {
std::string subject;
std::string action;
std::map<std::string, std::string> details;
std::uint32_t flags = 0;
std::string cancellation;
};
class Bus {
public:
// Lock this around anything a test reads or changes while the bus runs.
std::mutex mutex;
std::uint32_t clientUid = 4242;
std::map<std::uint32_t, std::string> logindNames;
Polkit polkit = Polkit::Allow;
std::map<std::string, Polkit, std::less<>> polkitByAction;
std::vector<PolkitCheck> checks;
std::vector<std::string> cancelled;
// Credentials without the uid, as no bus sends them.
bool omitUid = false;
explicit Bus(std::filesystem::path path) : path(std::move(path)) {
listener = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
sockaddr_un address{};
address.sun_family = AF_UNIX;
std::strncpy(address.sun_path, this->path.c_str(), sizeof(address.sun_path) - 1);
if(bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 || listen(listener, 64) != 0) {
throw std::runtime_error(std::format("the fake bus cannot listen on {}", this->path.string()));
}
thread = std::thread([this] { Run(); });
}
Bus(const Bus&) = delete;
Bus& operator=(const Bus&) = delete;
~Bus() {
stop = true;
thread.join();
close(listener);
std::filesystem::remove(path);
}
static std::string Address(const std::filesystem::path& path) {
return std::format("unix:path={}", path.string());
}
// Waits until `name` is owned, or not: false when `owned` is not reached within `timeout`.
bool WaitForName(std::string_view name, bool owned = true, std::chrono::milliseconds timeout = std::chrono::seconds(20)) {
const std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now() + timeout;
while(std::chrono::steady_clock::now() < end) {
{
std::lock_guard lock(mutex);
if(names.contains(name) == owned) {
return true;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return false;
}
// Ends the connection that owns `name`, as when the bus goes away under it.
void Disconnect(std::string_view name) {
std::lock_guard lock(mutex);
dropping.emplace_back(name);
}
// The other processes connected now: nostrod, and its workers.
std::vector<pid_t> Peers() {
std::lock_guard lock(mutex);
std::vector<pid_t> peers;
for(const Connection& connection : connections) {
if(!connection.dead && connection.pid != getpid()) {
peers.push_back(connection.pid);
}
}
return peers;
}
// The last check polkit got, or an empty one.
PolkitCheck LastCheck() {
std::lock_guard lock(mutex);
return checks.empty() ? PolkitCheck() : checks.back();
}
private:
struct Connection {
sd_bus* bus = nullptr;
std::string unique;
std::uint32_t uid = 0;
pid_t pid = 0;
bool dead = false;
};
// An answer kept for later (Polkit::Slow).
struct Later {
std::chrono::steady_clock::time_point at;
std::size_t connection = 0;
sd_bus_message* call = nullptr;
};
std::filesystem::path path;
std::int32_t listener = -1;
std::thread thread;
std::atomic<bool> stop{false};
std::vector<Connection> connections;
std::map<std::string, std::size_t, std::less<>> names;
std::vector<std::string> dropping;
std::vector<Later> later;
std::uint32_t nextUnique = 1;
// sd-bus hands strings out as C strings.
// lint-disable-next-line no-char-pointer
static std::string Text(const char* text) {
return text ? std::string(text) : std::string();
}
static std::string ReadString(sd_bus_message* message) {
// lint-disable-next-line no-char-pointer
const char* value = nullptr;
sd_bus_message_read_basic(message, 's', &value);
return Text(value);
}
void Run() {
while(!stop) {
std::vector<pollfd> fds;
{
std::lock_guard lock(mutex);
for(const std::string& name : std::exchange(dropping, {})) {
if(const auto owner = names.find(name); owner != names.end()) {
Drop(owner->second);
}
}
AnswerLater();
fds.push_back(pollfd{listener, POLLIN, 0});
for(const Connection& connection : connections) {
fds.push_back(pollfd{connection.dead ? -1 : sd_bus_get_fd(connection.bus), static_cast<std::int16_t>(connection.dead ? 0 : sd_bus_get_events(connection.bus)), 0});
}
}
poll(fds.data(), fds.size(), 10);
std::lock_guard lock(mutex);
if((fds[0].revents & POLLIN) != 0) {
Accept();
}
for(std::size_t i = 0; i < connections.size(); i++) {
while(!connections[i].dead) {
sd_bus_message* message = nullptr;
const std::int32_t result = sd_bus_process(connections[i].bus, &message);
if(result < 0) {
Drop(i);
break;
}
if(message) {
Route(i, message);
sd_bus_message_unref(message);
}
if(result == 0) {
break;
}
}
}
}
std::lock_guard lock(mutex);
for(Later& answer : later) {
sd_bus_message_unref(answer.call);
}
for(std::size_t i = 0; i < connections.size(); i++) {
Drop(i);
}
}
void Drop(std::size_t i) {
if(connections[i].dead) {
return;
}
connections[i].dead = true;
sd_bus_flush_close_unref(connections[i].bus);
connections[i].bus = nullptr;
std::erase_if(names, [i](const auto& owner) { return owner.second == i; });
}
void Accept() {
const std::int32_t fd = accept4(listener, nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK);
if(fd < 0) {
return;
}
ucred peer{};
socklen_t size = sizeof(peer);
getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &peer, &size);
Connection connection;
connection.pid = peer.pid;
connection.uid = peer.pid == getpid() ? clientUid : peer.uid;
sd_bus_new(&connection.bus);
sd_bus_set_fd(connection.bus, fd, fd);
sd_id128_t id{};
sd_id128_randomize(&id);
sd_bus_set_server(connection.bus, 1, id);
sd_bus_start(connection.bus);
connections.push_back(connection);
}
std::optional<std::size_t> Owner(std::string_view name) {
if(name.starts_with(':')) {
for(std::size_t i = 0; i < connections.size(); i++) {
if(!connections[i].dead && connections[i].unique == name) {
return i;
}
}
return std::nullopt;
}
const auto owner = names.find(name);
return owner == names.end() ? std::nullopt : std::optional<std::size_t>(owner->second);
}
template<typename... Args>
void Reply(std::size_t to, sd_bus_message* call, std::string_view types, Args... args) {
sd_bus_message* reply = nullptr;
sd_bus_message_new_method_return(call, &reply);
if(!types.empty()) {
sd_bus_message_append(reply, std::string(types).c_str(), args...);
}
sd_bus_send(connections[to].bus, reply, nullptr);
sd_bus_message_unref(reply);
}
void Fail(std::size_t to, sd_bus_message* call, std::string_view name, const std::optional<std::string>& message) {
sd_bus_message* reply = nullptr;
const std::string errorName(name);
const sd_bus_error error = {errorName.c_str(), message ? message->c_str() : nullptr, 0};
sd_bus_message_new_method_error(call, &reply, &error);
sd_bus_send(connections[to].bus, reply, nullptr);
sd_bus_message_unref(reply);
}
void Route(std::size_t from, sd_bus_message* message) {
std::uint8_t type = 0;
sd_bus_message_get_type(message, &type);
const std::string destination = Text(sd_bus_message_get_destination(message));
if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.DBus") {
Driver(from, message);
} else if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.login1") {
Logind(from, message);
} else if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.PolicyKit1") {
PolicyKit(from, message);
} else if(const std::optional<std::size_t> to = Owner(destination)) {
if(type == SD_BUS_MESSAGE_METHOD_CALL) {
// A call goes on from the caller's unique name, with its own cookie, so the answer finds it again.
std::uint64_t cookie = 0;
sd_bus_message_get_cookie(message, &cookie);
sd_bus_message* copy = nullptr;
sd_bus_message_new_method_call(connections[*to].bus, &copy, destination.c_str(), sd_bus_message_get_path(message), sd_bus_message_get_interface(message), sd_bus_message_get_member(message));
sd_bus_message_rewind(message, 1);
sd_bus_message_copy(copy, message, 1);
sd_bus_message_set_sender(copy, connections[from].unique.c_str());
sd_bus_message_set_allow_interactive_authorization(copy, sd_bus_message_get_allow_interactive_authorization(message));
sd_bus_message_seal(copy, cookie, 0);
sd_bus_send(connections[*to].bus, copy, nullptr);
sd_bus_message_unref(copy);
} else {
sd_bus_send(connections[*to].bus, message, nullptr);
}
} else if(type == SD_BUS_MESSAGE_METHOD_CALL) {
Fail(from, message, SD_BUS_ERROR_SERVICE_UNKNOWN, std::format("The name {} was not provided by any .service files", destination));
}
}
void Driver(std::size_t from, sd_bus_message* call) {
const std::string member = Text(sd_bus_message_get_member(call));
if(member == "Hello") {
connections[from].unique = std::format(":1.{}", nextUnique++);
Reply(from, call, "s", connections[from].unique.c_str());
} else if(member == "RequestName") {
const std::string name = ReadString(call);
const std::optional<std::size_t> owner = Owner(name);
if(owner && *owner != from) {
Reply(from, call, "u", 3u);
return;
}
names[name] = from;
Reply(from, call, "u", 1u);
} else if(member == "GetConnectionUnixUser" || member == "GetConnectionCredentials") {
const std::optional<std::size_t> owner = Owner(ReadString(call));
const std::uint32_t uid = owner ? connections[*owner].uid : 0;
const std::uint32_t pid = owner ? static_cast<std::uint32_t>(connections[*owner].pid) : 0;
if(member == "GetConnectionUnixUser") {
Reply(from, call, "u", uid);
} else if(omitUid) {
Reply(from, call, "a{sv}", 1, "ProcessID", "u", pid);
} else {
Reply(from, call, "a{sv}", 2, "UnixUserID", "u", uid, "ProcessID", "u", pid);
}
} else {
// AddMatch, RemoveMatch, ReleaseName: done.
Reply(from, call, "");
}
}
void Logind(std::size_t from, sd_bus_message* call) {
const std::string member = Text(sd_bus_message_get_member(call));
constexpr std::string_view prefix = "/org/freedesktop/login1/user/_";
if(member == "GetUser") {
std::uint32_t uid = 0;
sd_bus_message_read_basic(call, 'u', &uid);
if(!logindNames.contains(uid)) {
Fail(from, call, "org.freedesktop.login1.NoSuchUser", std::format("No user {} known or logged in", uid));
return;
}
Reply(from, call, "o", std::format("{}{}", prefix, uid).c_str());
} else {
// Properties.Get(interface, "Name") on a user's object.
const std::string userPath = Text(sd_bus_message_get_path(call));
std::uint32_t uid = 0;
std::from_chars(userPath.data() + prefix.size(), userPath.data() + userPath.size(), uid);
Reply(from, call, "v", "s", logindNames.at(uid).c_str());
}
}
void PolicyKit(std::size_t from, sd_bus_message* call) {
if(Text(sd_bus_message_get_member(call)) == "CancelCheckAuthorization") {
cancelled.push_back(ReadString(call));
Reply(from, call, "");
return;
}
PolkitCheck check;
sd_bus_message_enter_container(call, 'r', "sa{sv}");
ReadString(call);
sd_bus_message_enter_container(call, 'a', "{sv}");
while(sd_bus_message_enter_container(call, 'e', "sv") > 0) {
ReadString(call);
sd_bus_message_enter_container(call, 'v', "s");
check.subject = ReadString(call);
sd_bus_message_exit_container(call);
sd_bus_message_exit_container(call);
}
sd_bus_message_exit_container(call);
sd_bus_message_exit_container(call);
check.action = ReadString(call);
sd_bus_message_enter_container(call, 'a', "{ss}");
while(sd_bus_message_enter_container(call, 'e', "ss") > 0) {
std::string key = ReadString(call);
check.details[std::move(key)] = ReadString(call);
sd_bus_message_exit_container(call);
}
sd_bus_message_exit_container(call);
sd_bus_message_read_basic(call, 'u', &check.flags);
check.cancellation = ReadString(call);
checks.push_back(check);
const auto chosen = polkitByAction.find(check.action);
const Polkit outcome = chosen == polkitByAction.end() ? polkit : chosen->second;
const bool prompt = (check.flags & 1) != 0;
if(outcome == Polkit::Allow || (outcome == Polkit::Password && prompt)) {
Reply(from, call, "(bba{ss})", 1, 0, 1, "polkit.result", "auth_self");
} else if(outcome == Polkit::Password) {
Reply(from, call, "(bba{ss})", 0, 1, 1, "polkit.result", "auth_self");
} else if(outcome == Polkit::Deny) {
Reply(from, call, "(bba{ss})", 0, 0, 1, "polkit.result", "no");
} else if(outcome == Polkit::Dismiss) {
Reply(from, call, "(bba{ss})", 0, 0, 1, "polkit.result", "auth_self");
} else if(outcome == Polkit::Absent) {
Fail(from, call, SD_BUS_ERROR_SERVICE_UNKNOWN, std::nullopt);
} else if(outcome == Polkit::Slow) {
later.push_back(Later{std::chrono::steady_clock::now() + std::chrono::seconds(1), from, sd_bus_message_ref(call)});
}
}
void AnswerLater() {
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
std::erase_if(later, [this, now](const Later& answer) {
if(answer.at > now) {
return false;
}
if(!connections[answer.connection].dead) {
Reply(answer.connection, answer.call, "(bba{ss})", 1, 0, 1, "polkit.result", "auth_self");
}
sd_bus_message_unref(answer.call);
return true;
});
}
};
// Whether this process is nostrod, or one of its workers, started by a test from its own executable.
inline bool IsNostrod() {
return std::getenv("NOSTRO_TEST_ROLE") != nullptr;
}
// Starts this test's own executable as nostrod with `args`: its main runs nostrod's main when IsNostrod(). The
// variables in `unset` are left out of its environment.
inline pid_t StartNostrod(std::vector<std::string> args, std::vector<std::string_view> unset = {}) {
args.insert(args.begin(), "nostrod");
// 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);
std::vector<std::string> variables;
for(std::size_t i = 0; environ[i]; i++) {
const std::string_view variable(environ[i]);
if(std::ranges::none_of(unset, [variable](std::string_view name) { return variable.starts_with(std::format("{}=", name)); })) {
variables.emplace_back(variable);
}
}
variables.emplace_back("NOSTRO_TEST_ROLE=nostrod");
// lint-disable-next-line no-char-pointer
std::vector<char*> envp;
for(std::string& variable : variables) {
envp.push_back(variable.data());
}
envp.push_back(nullptr);
pid_t pid = -1;
posix_spawn(&pid, "/proc/self/exe", nullptr, nullptr, argv.data(), envp.data());
return pid;
}
// Sets the soft limit of `resource` for process `pid`, to see what it does when it reaches it, and returns the soft
// limit it had. The hard limit stays, so the old one can be set again.
inline rlim_t Limit(pid_t pid, decltype(RLIMIT_NOFILE) resource, rlim_t soft) {
rlimit old{};
prlimit(pid, resource, nullptr, &old);
const rlimit limit{.rlim_cur = soft, .rlim_max = old.rlim_max};
prlimit(pid, resource, &limit, nullptr);
return old.rlim_cur;
}
// Waits for a process this test started, and returns how it ended: its exit status, or 128 and the signal.
inline std::int32_t Wait(pid_t pid) {
std::int32_t status = 0;
waitpid(pid, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
}