Nostro/implementations/nostrod.cpp

63 lines
2.9 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®
// nostrod: the daemon that holds the connectors (Nostro:Daemon). This file only reads the command line:
// nostrod [--state <dir>] [--idle <seconds>] [--prompt-timeout <seconds>]
// nostrod --worker <uid> <name> ... what the daemon starts for one user, with its socket as fd 3
// Without --state the users' directories go below $XDG_DATA_HOME (which Flatpak points into the app's own data), or
// ~/.local/share.
import std;
import Nostro;
// main's signature is C's; past it the arguments are string views.
// lint-disable-next-line no-char-pointer
int main(int argc, char* argv[]) {
const std::vector<std::string_view> args(argv + 1, argv + argc);
try {
const auto value = [&args](std::size_t index) {
if(index >= args.size()) {
throw std::invalid_argument(std::format("{} needs a value", args[index - 1]));
}
return args[index];
};
const auto number = [](std::string_view text) {
std::uint32_t count = 0;
const std::from_chars_result result = std::from_chars(text.data(), text.data() + text.size(), count);
if(result.ec != std::errc() || result.ptr != text.data() + text.size()) {
throw std::invalid_argument(std::format("'{}' is not a whole number", text));
}
return count;
};
Nostro::DaemonOptions options;
// getenv answers with a char*, null when the variable is not set.
// lint-disable-next-line no-char-pointer
const char* const dataHome = std::getenv("XDG_DATA_HOME");
// lint-disable-next-line no-char-pointer
const char* const home = std::getenv("HOME");
options.state = dataHome ? std::filesystem::path(dataHome) : std::filesystem::path(home ? home : "/") / ".local/share";
std::optional<std::pair<std::uint32_t, std::string>> worker;
for(std::size_t i = 0; i < args.size(); i++) {
if(args[i] == "--state") {
options.state = value(++i);
} else if(args[i] == "--idle") {
options.idle = std::chrono::seconds(number(value(++i)));
} else if(args[i] == "--prompt-timeout") {
options.promptTimeout = std::chrono::seconds(number(value(++i)));
} else if(args[i] == "--worker") {
const std::uint32_t uid = number(value(++i));
worker = std::pair{uid, std::string(value(++i))};
} else {
throw std::invalid_argument(std::format("unknown argument '{}'", args[i]));
}
}
if(worker) {
return Nostro::RunWorker(3, worker->first, worker->second, options);
}
return Nostro::RunDaemon(options);
} catch(const std::exception& e) {
std::println(std::cerr, "nostrod: {}", e.what());
return 1;
}
}