Replace cxxopts with CLI11

- Simiplifies CLI code for future modification
- filesystem library linked in cmake check_for_std_filesystem file
pull/2107/head
dan 1 year ago
parent bf0dc52df7
commit dc7f3cee22

6
.gitmodules vendored

@ -1,9 +1,6 @@
[submodule "external/nlohmann"] [submodule "external/nlohmann"]
path = external/nlohmann path = external/nlohmann
url = https://github.com/nlohmann/json.git url = https://github.com/nlohmann/json.git
[submodule "external/cxxopts"]
path = external/cxxopts
url = https://github.com/jarro2783/cxxopts.git
[submodule "external/ghc-filesystem"] [submodule "external/ghc-filesystem"]
path = external/ghc-filesystem path = external/ghc-filesystem
url = https://github.com/gulrak/filesystem.git url = https://github.com/gulrak/filesystem.git
@ -39,3 +36,6 @@
[submodule "gui"] [submodule "gui"]
path = gui path = gui
url = https://github.com/oxen-io/lokinet-gui.git url = https://github.com/oxen-io/lokinet-gui.git
[submodule "external/CLI11"]
path = external/CLI11
url = https://github.com/CLIUtils/CLI11.git

@ -47,5 +47,5 @@ else()
set(GHC_FILESYSTEM_WITH_INSTALL OFF CACHE INTERNAL "") set(GHC_FILESYSTEM_WITH_INSTALL OFF CACHE INTERNAL "")
add_subdirectory(external/ghc-filesystem) add_subdirectory(external/ghc-filesystem)
target_link_libraries(filesystem INTERFACE ghc_filesystem) target_link_libraries(filesystem INTERFACE ghc_filesystem)
target_compile_definitions(filesystem INTERFACE USE_GHC_FILESYSTEM) target_compile_definitions(filesystem INTERFACE USE_GHC_FILESYSTEM CLI11_HAS_FILESYSTEM=0)
endif() endif()

@ -1,12 +1,15 @@
#include <oxenmq/oxenmq.h> #include <oxenmq/oxenmq.h>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <fmt/core.h> #include <fmt/core.h>
#include <cxxopts.hpp>
#include <future> #include <future>
#include <vector> #include <vector>
#include <array> #include <array>
#include <llarp/net/net.hpp> #include <llarp/net/net.hpp>
#include <CLI/App.hpp>
#include <CLI/Formatter.hpp>
#include <CLI/Config.hpp>
#ifdef _WIN32 #ifdef _WIN32
// add the unholy windows headers for iphlpapi // add the unholy windows headers for iphlpapi
#include <winsock2.h> #include <winsock2.h>
@ -53,25 +56,28 @@ OMQ_Request(
namespace namespace
{ {
template <typename T>
constexpr bool is_optional = false; struct command_line_options
template <typename T>
constexpr bool is_optional<std::optional<T>> = true;
// Extracts a value from a cxxopts result and assigns it into `value` if present. The value can
// either be a plain value or a std::optional. If not present, `value` is not touched.
template <typename T>
void
extract_option(const cxxopts::ParseResult& r, const std::string& name, T& value)
{
if (r.count(name))
{ {
if constexpr (is_optional<T>) // bool options
value = r[name].as<typename T::value_type>(); bool verbose = false;
else bool help = false;
value = r[name].as<T>(); bool vpnUp = false;
} bool vpnDown = false;
} bool printStatus = false;
bool killDaemon = false;
// string options
std::string exitAddress;
std::string rpc;
std::string endpoint = "default";
std::string token;
std::optional<std::string> range;
// oxenmq
oxenmq::address rpcURL{"tcp://127.0.0.1:1190"};
oxenmq::LogLevel logLevel = oxenmq::LogLevel::warn;
};
// Takes a code, prints a message, and returns the code. Intended use is: // Takes a code, prints a message, and returns the code. Intended use is:
// return exit_error(1, "blah: {}", 42); // return exit_error(1, "blah: {}", 42);
@ -98,119 +104,104 @@ namespace
int int
main(int argc, char* argv[]) main(int argc, char* argv[])
{ {
cxxopts::Options opts("lokinet-vpn", "LokiNET vpn control utility"); CLI::App cli{"lokiNET vpn control utility", "lokinet-vpn"};
command_line_options options{};
// clang-format off
opts.add_options() // flags: boolean values in command_line_options struct
("v,verbose", "Verbose", cxxopts::value<bool>()) cli.add_flag("v,--verbose", options.verbose, "Verbose");
("h,help", "help", cxxopts::value<bool>()) cli.add_flag("--up", options.vpnUp, "Put VPN up");
("kill", "kill the daemon", cxxopts::value<bool>()) cli.add_flag("--down", options.vpnDown, "Put VPN down");
("up", "put vpn up", cxxopts::value<bool>()) cli.add_flag("--status", options.printStatus, "Print VPN status and exit");
("down", "put vpn down", cxxopts::value<bool>()) cli.add_flag("k,--kill", options.killDaemon, "Kill lokinet daemon");
("exit", "specify exit node address", cxxopts::value<std::string>())
("rpc", "rpc url for lokinet", cxxopts::value<std::string>()) // options: string values in command_line_options struct
("endpoint", "endpoint to use", cxxopts::value<std::string>()) cli.add_option("--exit", options.exitAddress, "Specify exit node address")->capture_default_str();
("token", "exit auth token to use", cxxopts::value<std::string>()) cli.add_option("--endpoint", options.endpoint, "Endpoint to use")->capture_default_str();
("auth", "exit auth token to use", cxxopts::value<std::string>()) cli.add_option("--token", options.token, "Exit auth token to use")->capture_default_str();
("status", "print status and exit", cxxopts::value<bool>())
("range", "ip range to map", cxxopts::value<std::string>()) // options: oxenmq values in command_line_options struct
; cli.add_option("--rpc", options.rpc, "Specify RPC URL for lokinet")->capture_default_str();
// clang-format on cli.add_option(
oxenmq::address rpcURL("tcp://127.0.0.1:1190"); "--log-level", options.logLevel, "Log verbosity level, see log levels for accepted values")
std::string exitAddress; ->type_name("LEVEL")
std::string endpoint = "default"; ->capture_default_str();
std::string token;
std::optional<std::string> range;
oxenmq::LogLevel logLevel = oxenmq::LogLevel::warn;
bool goUp = false;
bool goDown = false;
bool printStatus = false;
bool killDaemon = false;
try try
{ {
const auto result = opts.parse(argc, argv); cli.parse(argc, argv);
}
if (result.count("help") > 0) catch (const CLI::ParseError& e)
{ {
std::cout << opts.help() << std::endl; return cli.exit(e);
return 0;
} }
if (result.count("verbose") > 0) try
{ {
logLevel = oxenmq::LogLevel::debug; if (options.verbose)
} options.logLevel = oxenmq::LogLevel::debug;
goUp = result.count("up") > 0;
goDown = result.count("down") > 0;
printStatus = result.count("status") > 0;
killDaemon = result.count("kill") > 0;
extract_option(result, "rpc", rpcURL);
extract_option(result, "exit", exitAddress);
extract_option(result, "endpoint", endpoint);
extract_option(result, "token", token);
extract_option(result, "auth", token);
extract_option(result, "range", range);
} }
catch (const cxxopts::option_not_exists_exception& ex) catch (const CLI::OptionNotFound& e)
{ {
return exit_error(2, "{}\n{}", ex.what(), opts.help()); cli.exit(e);
} }
catch (std::exception& ex) catch (const CLI::Error& e)
{ {
return exit_error(2, "{}", ex.what()); cli.exit(e);
} };
int num_commands = goUp + goDown + printStatus + killDaemon; int numCommands = options.vpnUp + options.vpnDown + options.printStatus + options.killDaemon;
if (num_commands == 0) switch (numCommands)
{
case 0:
return exit_error(3, "One of --up/--down/--status/--kill must be specified"); return exit_error(3, "One of --up/--down/--status/--kill must be specified");
if (num_commands != 1) case 1:
return exit_error(3, "Only one of --up/--down/--status/--kill may be specified"); return exit_error(3, "Only one of --up/--down/--status/--kill may be specified");
default:
break;
}
if (goUp and exitAddress.empty()) if (options.vpnUp and options.exitAddress.empty())
return exit_error("no exit address provided"); return exit_error("No exit address provided, must specify --exit <address>");
oxenmq::OxenMQ omq{ oxenmq::OxenMQ omq{
[](oxenmq::LogLevel lvl, const char* file, int line, std::string msg) { [](oxenmq::LogLevel lvl, const char* file, int line, std::string msg) {
std::cout << lvl << " [" << file << ":" << line << "] " << msg << std::endl; std::cout << lvl << " [" << file << ":" << line << "] " << msg << std::endl;
}, },
logLevel}; options.logLevel};
omq.start(); omq.start();
std::promise<bool> connectPromise; std::promise<bool> connectPromise;
const auto connID = omq.connect_remote( const auto connectionID = omq.connect_remote(
rpcURL, options.rpc,
[&connectPromise](auto) { connectPromise.set_value(true); }, [&connectPromise](auto) { connectPromise.set_value(true); },
[&connectPromise](auto, std::string_view msg) { [&connectPromise](auto, std::string_view msg) {
std::cout << "failed to connect to lokinet RPC: " << msg << std::endl; std::cout << "Failed to connect to lokinet RPC: " << msg << std::endl;
connectPromise.set_value(false); connectPromise.set_value(false);
}); });
auto ftr = connectPromise.get_future(); auto ftr = connectPromise.get_future();
if (not ftr.get()) if (not ftr.get())
{
return 1; return 1;
}
if (killDaemon) if (options.killDaemon)
{ {
if (not OMQ_Request(omq, connID, "llarp.halt")) if (not OMQ_Request(omq, connectionID, "llarp.halt"))
return exit_error("call to llarp.halt failed"); return exit_error("Call to llarp.halt failed");
return 0; return 0;
} }
if (printStatus) if (options.printStatus)
{ {
const auto maybe_status = OMQ_Request(omq, connID, "llarp.status"); const auto maybe_status = OMQ_Request(omq, connectionID, "llarp.status");
if (not maybe_status) if (not maybe_status)
return exit_error("call to llarp.status failed"); return exit_error("call to llarp.status failed");
try try
{ {
const auto& ep = maybe_status->at("result").at("services").at(endpoint); const auto& ep = maybe_status->at("result").at("services").at(options.endpoint);
const auto exitMap = ep.at("exitMap"); const auto exitMap = ep.at("exitMap");
if (exitMap.empty()) if (exitMap.empty())
{ {
@ -230,13 +221,13 @@ main(int argc, char* argv[])
} }
return 0; return 0;
} }
if (goUp) if (options.vpnUp)
{ {
nlohmann::json opts{{"exit", exitAddress}, {"token", token}}; nlohmann::json opts{{"exit", options.exitAddress}, {"token", options.token}};
if (range) if (options.range)
opts["range"] = *range; opts["range"] = *options.range;
auto maybe_result = OMQ_Request(omq, connID, "llarp.exit", std::move(opts)); auto maybe_result = OMQ_Request(omq, connectionID, "llarp.exit", std::move(opts));
if (not maybe_result) if (not maybe_result)
return exit_error("could not add exit"); return exit_error("could not add exit");
@ -247,12 +238,12 @@ main(int argc, char* argv[])
return exit_error("{}", err_it.value()); return exit_error("{}", err_it.value());
} }
} }
if (goDown) if (options.vpnDown)
{ {
nlohmann::json opts{{"unmap", true}}; nlohmann::json opts{{"unmap", true}};
if (range) if (options.range)
opts["range"] = *range; opts["range"] = *options.range;
if (not OMQ_Request(omq, connID, "llarp.exit", std::move(opts))) if (not OMQ_Request(omq, connectionID, "llarp.exit", std::move(opts)))
return exit_error("failed to unmap exit"); return exit_error("failed to unmap exit");
} }

@ -15,29 +15,58 @@
#include <csignal> #include <csignal>
#include <cxxopts.hpp>
#include <string> #include <string>
#include <iostream> #include <iostream>
#include <thread>
#include <future> #include <future>
int #include <CLI/App.hpp>
lokinet_main(int, char**); #include <CLI/Formatter.hpp>
#include <CLI/Config.hpp>
#ifdef _WIN32 namespace
extern "C" LONG FAR PASCAL {
win32_signal_handler(EXCEPTION_POINTERS*); struct command_line_options
extern "C" VOID FAR PASCAL {
win32_daemon_entry(DWORD, LPTSTR*); // bool options
bool help = false;
bool version = false;
bool generate = false;
bool router = false;
bool force = false;
bool configOnly = false;
bool overwrite = false;
VOID // string options
insert_description(); std::string configPath;
#endif // windows options
bool win_install = false;
bool win_remove = false;
};
// windows-specific function declarations
int
startWinsock();
void
install_win32_daemon();
void
uninstall_win32_daemon();
// operational function definitions
int
lokinet_main(int, char**);
void
handle_signal(int sig);
static void
run_main_context(std::optional<fs::path> confFile, const llarp::RuntimeOptions opts);
// variable declarations
static auto logcat = llarp::log::Cat("main"); static auto logcat = llarp::log::Cat("main");
std::shared_ptr<llarp::Context> ctx; std::shared_ptr<llarp::Context> ctx;
std::promise<int> exit_code; std::promise<int> exit_code;
// operational function definitions
void void
handle_signal(int sig) handle_signal(int sig)
{ {
@ -48,7 +77,23 @@ handle_signal(int sig)
std::cerr << "Received signal " << sig << ", but have no context yet. Ignoring!" << std::endl; std::cerr << "Received signal " << sig << ", but have no context yet. Ignoring!" << std::endl;
} }
// Windows specific code
#ifdef _WIN32 #ifdef _WIN32
extern "C" LONG FAR PASCAL
win32_signal_handler(EXCEPTION_POINTERS*);
extern "C" VOID FAR PASCAL
win32_daemon_entry(DWORD, LPTSTR*);
VOID
insert_description();
extern "C" BOOL FAR PASCAL
handle_signal_win32(DWORD fdwCtrlType)
{
UNREFERENCED_PARAMETER(fdwCtrlType);
handle_signal(SIGINT);
return TRUE; // probably unreachable
};
int int
startWinsock() startWinsock()
{ {
@ -64,14 +109,6 @@ startWinsock()
return 0; return 0;
} }
extern "C" BOOL FAR PASCAL
handle_signal_win32(DWORD fdwCtrlType)
{
UNREFERENCED_PARAMETER(fdwCtrlType);
handle_signal(SIGINT);
return TRUE; // probably unreachable
}
void void
install_win32_daemon() install_win32_daemon()
{ {
@ -221,76 +258,6 @@ uninstall_win32_daemon()
CloseServiceHandle(schService); CloseServiceHandle(schService);
CloseServiceHandle(schSCManager); CloseServiceHandle(schSCManager);
} }
#endif
/// this sets up, configures and runs the main context
static void
run_main_context(std::optional<fs::path> confFile, const llarp::RuntimeOptions opts)
{
llarp::LogInfo(fmt::format("starting up {} {}", llarp::VERSION_FULL, llarp::RELEASE_MOTTO));
try
{
std::shared_ptr<llarp::Config> conf;
if (confFile)
{
llarp::LogInfo("Using config file: ", *confFile);
conf = std::make_shared<llarp::Config>(confFile->parent_path());
}
else
{
conf = std::make_shared<llarp::Config>(llarp::GetDefaultDataDir());
}
if (not conf->Load(confFile, opts.isSNode))
{
llarp::LogError("failed to parse configuration");
exit_code.set_value(1);
return;
}
ctx = std::make_shared<llarp::Context>();
ctx->Configure(std::move(conf));
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
#ifndef _WIN32
signal(SIGHUP, handle_signal);
signal(SIGUSR1, handle_signal);
#endif
try
{
ctx->Setup(opts);
}
catch (llarp::util::bind_socket_error& ex)
{
llarp::LogError(fmt::format("{}, is lokinet already running? 🤔", ex.what()));
exit_code.set_value(1);
return;
}
catch (std::exception& ex)
{
llarp::LogError(fmt::format("failed to start up lokinet: {}", ex.what()));
exit_code.set_value(1);
return;
}
llarp::util::SetThreadName("llarp-mainloop");
auto result = ctx->Run(opts);
exit_code.set_value(result);
}
catch (std::exception& e)
{
llarp::LogError("Fatal: caught exception while running: ", e.what());
exit_code.set_exception(std::current_exception());
}
catch (...)
{
llarp::LogError("Fatal: caught non-standard exception while running");
exit_code.set_exception(std::current_exception());
}
}
#ifdef _WIN32
/// minidump generation for windows jizz /// minidump generation for windows jizz
/// will make a coredump when there is an unhandled exception /// will make a coredump when there is an unhandled exception
@ -326,46 +293,57 @@ GenerateDump(EXCEPTION_POINTERS* pExceptionPointers)
return 1; return 1;
} }
#endif VOID FAR PASCAL
SvcCtrlHandler(DWORD dwCtrl)
int
main(int argc, char* argv[])
{ {
// Set up a default, stderr logging for very early logging; we'll replace this later once we read // Handle the requested control code.
// the desired log info from config.
llarp::log::add_sink(llarp::log::Type::Print, "stderr");
llarp::log::reset_level(llarp::log::Level::info);
llarp::logRingBuffer = std::make_shared<llarp::log::RingBufferSink>(100); switch (dwCtrl)
llarp::log::add_sink(llarp::logRingBuffer, llarp::log::DEFAULT_PATTERN_MONO); {
case SERVICE_CONTROL_STOP:
// tell service we are stopping
llarp::log::debug(logcat, "Windows service controller gave SERVICE_CONTROL_STOP");
llarp::sys::service_manager->system_changed_our_state(llarp::sys::ServiceState::Stopping);
handle_signal(SIGINT);
return;
#ifndef _WIN32 case SERVICE_CONTROL_INTERROGATE:
return lokinet_main(argc, argv); // report status
#else llarp::log::debug(logcat, "Got win32 service interrogate signal");
SERVICE_TABLE_ENTRY DispatchTable[] = { llarp::sys::service_manager->report_changed_state();
{strdup("lokinet"), (LPSERVICE_MAIN_FUNCTION)win32_daemon_entry}, {NULL, NULL}}; return;
// Try first to run as a service; if this works it fires off to win32_daemon_entry and doesn't default:
// return until the service enters STOPPED state. llarp::log::debug(logcat, "Got win32 unhandled signal {}", dwCtrl);
if (StartServiceCtrlDispatcher(DispatchTable)) break;
return 0; }
}
auto error = GetLastError(); // The win32 daemon entry point is where we go when invoked as a windows service; we do the
// required service dance and then pretend we were invoked via main().
VOID FAR PASCAL
win32_daemon_entry(DWORD, LPTSTR* argv)
{
// Register the handler function for the service
auto* svc = dynamic_cast<llarp::sys::SVC_Manager*>(llarp::sys::service_manager);
svc->handle = RegisterServiceCtrlHandler("lokinet", SvcCtrlHandler);
// We'll get this error if not invoked as a service, which is fine: we can just run directly if (svc->handle == nullptr)
if (error == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
{ {
llarp::sys::service_manager->disable(); llarp::LogError("failed to register daemon control handler");
return lokinet_main(argc, argv); return;
} }
else
{ // we hard code the args to lokinet_main.
llarp::log::critical( // we yoink argv[0] (lokinet.exe path) and pass in the new args.
logcat, "Error launching service: {}", std::system_category().message(error)); std::array args = {
return 1; reinterpret_cast<char*>(argv[0]),
reinterpret_cast<char*>(strdup("c:\\programdata\\lokinet\\lokinet.ini")),
reinterpret_cast<char*>(0)};
lokinet_main(args.size() - 1, args.data());
} }
#endif #endif
}
int int
lokinet_main(int argc, char** argv) lokinet_main(int argc, char** argv)
@ -382,98 +360,86 @@ lokinet_main(int argc, char** argv)
SetConsoleCtrlHandler(handle_signal_win32, TRUE); SetConsoleCtrlHandler(handle_signal_win32, TRUE);
#endif #endif
cxxopts::Options options( CLI::App cli{
"lokinet", "LokiNET is a free, open source, private, decentralized, market-based sybil resistant and "
"LokiNET is a free, open source, private, " "IP "
"decentralized, \"market based sybil resistant\" " "based onion routing network",
"and IP based onion routing network"); "lokinet"};
// clang-format off command_line_options options{};
options.add_options()
#ifdef _WIN32 // flags: boolean values in command_line_options struct
("install", "install win32 daemon to SCM", cxxopts::value<bool>()) cli.add_flag("--version", options.version, "Lokinet version");
("remove", "remove win32 daemon from SCM", cxxopts::value<bool>()) cli.add_flag("g,--generate", options.generate, "Generate default configuration and exit");
#endif cli.add_flag(
("h,help", "print this help message", cxxopts::value<bool>()) "r,--router", options.router, "Run lokinet in routing mode instead of client-only mode");
("version", "print version string", cxxopts::value<bool>()) cli.add_flag("f,--force", options.force, "Force writing config even if file exists");
("g,generate", "generate default configuration and exit", cxxopts::value<bool>())
("r,router", "run in routing mode instead of client only mode", cxxopts::value<bool>()) // options: string
("f,force", "force writing config even if it already exists", cxxopts::value<bool>()) cli.add_option("--config", options.configPath, "Path to lokinet.ini configuration file")
("config", "path to lokinet.ini configuration file", cxxopts::value<std::string>()) ->capture_default_str();
;
// clang-format on if constexpr (llarp::platform::is_windows)
options.parse_positional("config");
bool genconfigOnly = false;
bool overwrite = false;
std::optional<fs::path> configFile;
try
{ {
auto result = options.parse(argc, argv); cli.add_flag("--install", options.win_install, "Install win32 daemon to SCM");
cli.add_flag("--remove", options.win_remove, "Remove win32 daemon from SCM");
}
if (result.count("help")) try
{ {
std::cout << options.help() << std::endl; cli.parse(argc, argv);
return 0;
} }
if (result.count("version")) catch (const CLI::ParseError& e)
{
return cli.exit(e);
}
std::optional<fs::path> configFile;
try
{
if (options.version)
{ {
std::cout << llarp::VERSION_FULL << std::endl; std::cout << llarp::VERSION_FULL << std::endl;
return 0; return 0;
} }
#ifdef _WIN32
if (result.count("install")) if constexpr (llarp::platform::is_windows)
{
if (options.win_install)
{ {
install_win32_daemon(); install_win32_daemon();
return 0; return 0;
} }
if (options.win_remove)
if (result.count("remove"))
{ {
uninstall_win32_daemon(); uninstall_win32_daemon();
return 0; return 0;
} }
#endif
if (result.count("generate") > 0)
{
genconfigOnly = true;
} }
if (result.count("router") > 0) if (options.configOnly)
{ {
opts.isSNode = true; configFile = options.configPath;
} }
if (result.count("force") > 0)
{
overwrite = true;
} }
catch (const CLI::OptionNotFound& e)
if (result.count("config") > 0)
{
auto arg = result["config"].as<std::string>();
if (!arg.empty())
{ {
configFile = arg; cli.exit(e);
}
} }
} catch (const CLI::Error& e)
catch (const cxxopts::option_not_exists_exception& ex)
{ {
std::cerr << ex.what(); cli.exit(e);
std::cout << options.help() << std::endl; };
return 1;
}
if (configFile.has_value()) if (configFile.has_value())
{ {
// when we have an explicit filepath // when we have an explicit filepath
fs::path basedir = configFile->parent_path(); fs::path basedir = configFile->parent_path();
if (genconfigOnly) if (options.configOnly)
{ {
try try
{ {
llarp::ensureConfig(basedir, *configFile, overwrite, opts.isSNode); llarp::ensureConfig(basedir, *configFile, options.overwrite, opts.isSNode);
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
@ -503,7 +469,10 @@ lokinet_main(int argc, char** argv)
try try
{ {
llarp::ensureConfig( llarp::ensureConfig(
llarp::GetDefaultDataDir(), llarp::GetDefaultConfigPath(), overwrite, opts.isSNode); llarp::GetDefaultDataDir(),
llarp::GetDefaultConfigPath(),
options.overwrite,
opts.isSNode);
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
@ -513,10 +482,8 @@ lokinet_main(int argc, char** argv)
configFile = llarp::GetDefaultConfigPath(); configFile = llarp::GetDefaultConfigPath();
} }
if (genconfigOnly) if (options.configOnly)
{
return 0; return 0;
}
#ifdef _WIN32 #ifdef _WIN32
SetUnhandledExceptionFilter(&GenerateDump); SetUnhandledExceptionFilter(&GenerateDump);
@ -588,55 +555,111 @@ lokinet_main(int argc, char** argv)
return code; return code;
} }
#ifdef _WIN32 // this sets up, configures and runs the main context
static void
VOID FAR PASCAL run_main_context(std::optional<fs::path> confFile, const llarp::RuntimeOptions opts)
SvcCtrlHandler(DWORD dwCtrl)
{ {
// Handle the requested control code. llarp::LogInfo(fmt::format("starting up {} {}", llarp::VERSION_FULL, llarp::RELEASE_MOTTO));
try
switch (dwCtrl)
{ {
case SERVICE_CONTROL_STOP: std::shared_ptr<llarp::Config> conf;
// tell service we are stopping if (confFile)
llarp::log::debug(logcat, "Windows service controller gave SERVICE_CONTROL_STOP"); {
llarp::sys::service_manager->system_changed_our_state(llarp::sys::ServiceState::Stopping); llarp::LogInfo("Using config file: ", *confFile);
handle_signal(SIGINT); conf = std::make_shared<llarp::Config>(confFile->parent_path());
}
else
{
conf = std::make_shared<llarp::Config>(llarp::GetDefaultDataDir());
}
if (not conf->Load(confFile, opts.isSNode))
{
llarp::LogError("failed to parse configuration");
exit_code.set_value(1);
return; return;
}
case SERVICE_CONTROL_INTERROGATE: ctx = std::make_shared<llarp::Context>();
// report status ctx->Configure(std::move(conf));
llarp::log::debug(logcat, "Got win32 service interrogate signal");
llarp::sys::service_manager->report_changed_state(); signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
#ifndef _WIN32
signal(SIGHUP, handle_signal);
signal(SIGUSR1, handle_signal);
#endif
try
{
ctx->Setup(opts);
}
catch (llarp::util::bind_socket_error& ex)
{
llarp::LogError(fmt::format("{}, is lokinet already running? 🤔", ex.what()));
exit_code.set_value(1);
return; return;
}
catch (std::exception& ex)
{
llarp::LogError(fmt::format("failed to start up lokinet: {}", ex.what()));
exit_code.set_value(1);
return;
}
llarp::util::SetThreadName("llarp-mainloop");
default: auto result = ctx->Run(opts);
llarp::log::debug(logcat, "Got win32 unhandled signal {}", dwCtrl); exit_code.set_value(result);
break; }
catch (std::exception& e)
{
llarp::LogError("Fatal: caught exception while running: ", e.what());
exit_code.set_exception(std::current_exception());
}
catch (...)
{
llarp::LogError("Fatal: caught non-standard exception while running");
exit_code.set_exception(std::current_exception());
} }
} }
// The win32 daemon entry point is where we go when invoked as a windows service; we do the required } // namespace
// service dance and then pretend we were invoked via main().
VOID FAR PASCAL int
win32_daemon_entry(DWORD, LPTSTR* argv) main(int argc, char* argv[])
{ {
// Register the handler function for the service // Set up a default, stderr logging for very early logging; we'll replace this later once we read
auto* svc = dynamic_cast<llarp::sys::SVC_Manager*>(llarp::sys::service_manager); // the desired log info from config.
svc->handle = RegisterServiceCtrlHandler("lokinet", SvcCtrlHandler); llarp::log::add_sink(llarp::log::Type::Print, "stderr");
llarp::log::reset_level(llarp::log::Level::info);
if (svc->handle == nullptr) llarp::logRingBuffer = std::make_shared<llarp::log::RingBufferSink>(100);
llarp::log::add_sink(llarp::logRingBuffer, llarp::log::DEFAULT_PATTERN_MONO);
#ifndef _WIN32
return lokinet_main(argc, argv);
#else
SERVICE_TABLE_ENTRY DispatchTable[] = {
{strdup("lokinet"), (LPSERVICE_MAIN_FUNCTION)win32_daemon_entry}, {NULL, NULL}};
// Try first to run as a service; if this works it fires off to win32_daemon_entry and doesn't
// return until the service enters STOPPED state.
if (StartServiceCtrlDispatcher(DispatchTable))
return 0;
auto error = GetLastError();
// We'll get this error if not invoked as a service, which is fine: we can just run directly
if (error == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
{ {
llarp::LogError("failed to register daemon control handler"); llarp::sys::service_manager->disable();
return; return lokinet_main(argc, argv);
} }
else
// we hard code the args to lokinet_main. {
// we yoink argv[0] (lokinet.exe path) and pass in the new args. llarp::log::critical(
std::array args = { logcat, "Error launching service: {}", std::system_category().message(error));
reinterpret_cast<char*>(argv[0]), return 1;
reinterpret_cast<char*>(strdup("c:\\programdata\\lokinet\\lokinet.ini")),
reinterpret_cast<char*>(0)};
lokinet_main(args.size() - 1, args.data());
} }
#endif #endif
}

1
external/CLI11 vendored

@ -0,0 +1 @@
Subproject commit 4c7c8ddc45d2ef74584e5cd945f7a4d27c987748

@ -26,7 +26,6 @@ if(SUBMODULE_CHECK)
message(STATUS "Checking submodules") message(STATUS "Checking submodules")
check_submodule(nlohmann) check_submodule(nlohmann)
check_submodule(cxxopts)
check_submodule(ghc-filesystem) check_submodule(ghc-filesystem)
check_submodule(oxen-logging fmt spdlog) check_submodule(oxen-logging fmt spdlog)
check_submodule(pybind11) check_submodule(pybind11)
@ -36,6 +35,7 @@ if(SUBMODULE_CHECK)
check_submodule(uvw) check_submodule(uvw)
check_submodule(cpr) check_submodule(cpr)
check_submodule(ngtcp2) check_submodule(ngtcp2)
check_submodule(CLI11)
endif() endif()
endif() endif()
@ -78,7 +78,7 @@ if(WITH_HIVE)
add_subdirectory(pybind11 EXCLUDE_FROM_ALL) add_subdirectory(pybind11 EXCLUDE_FROM_ALL)
endif() endif()
add_subdirectory(cxxopts EXCLUDE_FROM_ALL) system_or_submodule(CLI11 CLI11 CLI11>=2.2.0 CLI11)
if(WITH_PEERSTATS) if(WITH_PEERSTATS)
add_library(sqlite_orm INTERFACE) add_library(sqlite_orm INTERFACE)

1
external/cxxopts vendored

@ -1 +0,0 @@
Subproject commit c74846a891b3cc3bfa992d588b1295f528d43039

@ -1,7 +1,7 @@
directory for git submodules directory for git submodules
* CLI11: cli argument parser
* cpr: curl for people, used by lokinet-bootstrap toolchain (to be removed) * cpr: curl for people, used by lokinet-bootstrap toolchain (to be removed)
* cxxopts: cli argument parser (to be removed)
* ghc-filesystem: `std::filesystem` shim lib for older platforms (like macos) * ghc-filesystem: `std::filesystem` shim lib for older platforms (like macos)
* ngtcp2: quic implementation * ngtcp2: quic implementation
* nlohmann: json parser * nlohmann: json parser

@ -278,7 +278,7 @@ endif()
target_link_libraries(lokinet-amalgum PRIVATE libunbound) target_link_libraries(lokinet-amalgum PRIVATE libunbound)
target_link_libraries(lokinet-amalgum PUBLIC target_link_libraries(lokinet-amalgum PUBLIC
cxxopts CLI11
oxenc::oxenc oxenc::oxenc
lokinet-platform lokinet-platform
lokinet-config lokinet-config

@ -14,7 +14,10 @@
#include <llarp/util/service_manager.hpp> #include <llarp/util/service_manager.hpp>
#include <cxxopts.hpp> #include <CLI/App.hpp>
#include <CLI/Formatter.hpp>
#include <CLI/Config.hpp>
#include <csignal> #include <csignal>
#include <stdexcept> #include <stdexcept>

Loading…
Cancel
Save