diff --git a/daemon/lokinetctl.cpp b/daemon/lokinetctl.cpp index e2d41902f..bbe2e9899 100644 --- a/daemon/lokinetctl.cpp +++ b/daemon/lokinetctl.cpp @@ -36,18 +36,18 @@ namespace int main(int argc, char* argv[]) { - cxxopts::Options options("lokinetctl", - "LokiNET is a free, open source, private, " - "decentralized, \"market based sybil resistant\" " - "and IP based onion routing network"); + cxxopts::Options options( + "lokinetctl", + "LokiNET is a free, open source, private, " + "decentralized, \"market based sybil resistant\" " + "and IP based onion routing network"); - options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())( - "h,help", "help", cxxopts::value< bool >())( - "c,config", "config file", - cxxopts::value< std::string >()->default_value( - llarp::GetDefaultConfigPath().string())) - ("dump", "dump rc file", - cxxopts::value< std::vector< std::string > >(), "FILE"); + options.add_options()("v,verbose", "Verbose", cxxopts::value())( + "h,help", "help", cxxopts::value())( + "c,config", + "config file", + cxxopts::value()->default_value(llarp::GetDefaultConfigPath().string()))( + "dump", "dump rc file", cxxopts::value>(), "FILE"); try { @@ -80,7 +80,6 @@ main(int argc, char* argv[]) return 1; } } - } catch (const cxxopts::OptionParseException& ex) { diff --git a/daemon/main.cpp b/daemon/main.cpp index 288b5c37d..403fd4bb8 100644 --- a/daemon/main.cpp +++ b/daemon/main.cpp @@ -65,7 +65,7 @@ run_main_context(std::string conffname, llarp_main_runtime_opts opts) // this is important, can downgrade from Info though llarp::LogDebug("Running from: ", fs::current_path().string()); llarp::LogInfo("Using config file: ", conffname); - ctx = llarp_main_init(conffname.c_str(), opts.isRelay); + ctx = llarp_main_init(conffname.c_str(), opts.isRelay); int code = 1; if (ctx) { @@ -103,18 +103,17 @@ main(int argc, char* argv[]) SetConsoleCtrlHandler(handle_signal_win32, TRUE); // SetUnhandledExceptionFilter(win32_signal_handler); #endif - cxxopts::Options options("lokinet", - "LokiNET is a free, open source, private, " - "decentralized, \"market based sybil resistant\" " - "and IP based onion routing network"); - options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())( - "h,help", "help", cxxopts::value< bool >())("version", "version", - cxxopts::value< bool >())( - "g,generate", "generate client config", cxxopts::value< bool >())( - "r,relay", "run as relay instead of client", cxxopts::value< bool >())( - "f,force", "overwrite", cxxopts::value< bool >())( - "c,colour", "colour output", - cxxopts::value< bool >()->default_value("true"))( + cxxopts::Options options( + "lokinet", + "LokiNET is a free, open source, private, " + "decentralized, \"market based sybil resistant\" " + "and IP based onion routing network"); + options.add_options()("v,verbose", "Verbose", cxxopts::value())( + "h,help", "help", cxxopts::value())("version", "version", cxxopts::value())( + "g,generate", "generate client config", cxxopts::value())( + "r,relay", "run as relay instead of client", cxxopts::value())( + "f,force", "overwrite", cxxopts::value())( + "c,colour", "colour output", cxxopts::value()->default_value("true"))( "b,background", "background mode (start, but do not connect to the network)", cxxopts::value())( @@ -123,7 +122,7 @@ main(int argc, char* argv[]) options.parse_positional("config"); bool genconfigOnly = false; - bool overwrite = false; + bool overwrite = false; std::string conffname; try { @@ -163,17 +162,17 @@ main(int argc, char* argv[]) opts.background = true; } - if(result.count("relay") > 0) + if (result.count("relay") > 0) { opts.isRelay = true; } - if(result.count("force") > 0) + if (result.count("force") > 0) { overwrite = true; } - if(result.count("config") > 0) + if (result.count("config") > 0) { auto arg = result["config"].as(); if (!arg.empty()) @@ -195,12 +194,10 @@ main(int argc, char* argv[]) fs::path fname = fs::path(conffname); fs::path basedir = fname.parent_path(); - if(genconfigOnly) + if (genconfigOnly) { - llarp::ensureConfig(llarp::GetDefaultDataDir(), - llarp::GetDefaultConfigPath(), - overwrite, - opts.isRelay); + llarp::ensureConfig( + llarp::GetDefaultDataDir(), llarp::GetDefaultConfigPath(), overwrite, opts.isRelay); } else { @@ -217,10 +214,8 @@ main(int argc, char* argv[]) } else { - llarp::ensureConfig(llarp::GetDefaultDataDir(), - llarp::GetDefaultConfigPath(), - overwrite, - opts.isRelay); + llarp::ensureConfig( + llarp::GetDefaultDataDir(), llarp::GetDefaultConfigPath(), overwrite, opts.isRelay); conffname = llarp::GetDefaultConfigPath().c_str(); } diff --git a/include/llarp.h b/include/llarp.h index 659a0e232..ecd5cbf6a 100644 --- a/include/llarp.h +++ b/include/llarp.h @@ -26,7 +26,7 @@ extern "C" bool background = false; bool debug = false; bool singleThreaded = false; - bool isRelay = false; + bool isRelay = false; }; /// llarp_application config @@ -139,20 +139,20 @@ extern "C" /// allocates new config and puts it into c /// return false on failure bool - llarp_config_load_file(const char *fname, struct llarp_config **c, bool isRelay); + llarp_config_load_file(const char* fname, struct llarp_config** c, bool isRelay); /// make a main context from configuration /// copies config contents - struct llarp_main * - llarp_main_init_from_config(struct llarp_config *conf, bool isRelay); + struct llarp_main* + llarp_main_init_from_config(struct llarp_config* conf, bool isRelay); /// initialize application context and load config - static struct llarp_main * - llarp_main_init(const char *fname, bool isRelay) + static struct llarp_main* + llarp_main_init(const char* fname, bool isRelay) { - struct llarp_main *m = 0; - struct llarp_config *conf = 0; - if(!llarp_config_load_file(fname, &conf, isRelay)) + struct llarp_main* m = 0; + struct llarp_config* conf = 0; + if (!llarp_config_load_file(fname, &conf, isRelay)) return 0; if (conf == NULL) return 0; @@ -162,7 +162,7 @@ extern "C" } /// initialize applicatin context with all defaults - static struct llarp_main * + static struct llarp_main* llarp_main_default_init(bool isRelay) { struct llarp_main* m; @@ -178,7 +178,7 @@ extern "C" /// (re)configure main context /// return true if (re)configuration was successful bool - llarp_main_configure(struct llarp_main *ptr, struct llarp_config *conf, bool isRelay); + llarp_main_configure(struct llarp_main* ptr, struct llarp_config* conf, bool isRelay); /// return true if this main context is running /// return false otherwise diff --git a/include/llarp.hpp b/include/llarp.hpp index d70c47e72..5a58da2d1 100644 --- a/include/llarp.hpp +++ b/include/llarp.hpp @@ -55,7 +55,7 @@ namespace llarp std::string nodedb_dir; bool - LoadConfig(const std::string &fname, bool isRelay); + LoadConfig(const std::string& fname, bool isRelay); void Close(); @@ -101,12 +101,11 @@ namespace llarp #endif private: - void SigINT(); std::string configfile; - std::unique_ptr< std::promise< void > > closeWaiter; + std::unique_ptr> closeWaiter; }; } // namespace llarp diff --git a/llarp/config/config.cpp b/llarp/config/config.cpp index 3584c870d..bd71204eb 100644 --- a/llarp/config/config.cpp +++ b/llarp/config/config.cpp @@ -20,7 +20,6 @@ namespace llarp { - // constants for config file default values constexpr int DefaultMinConnectionsForRouter = 6; constexpr int DefaultMaxConnectionsForRouter = 60; @@ -38,103 +37,93 @@ namespace llarp constexpr int DefaultNetThreads = 1; constexpr bool DefaultBlockBogons = true; - conf.defineOption("router", "job-queue-size", false, DefaultJobQueueSize, - [this](int arg) { - if (arg < 1024) - throw std::invalid_argument("job-queue-size must be 1024 or greater"); - - m_JobQueueSize = arg; - }); + conf.defineOption("router", "job-queue-size", false, DefaultJobQueueSize, [this](int arg) { + if (arg < 1024) + throw std::invalid_argument("job-queue-size must be 1024 or greater"); - conf.defineOption("router", "netid", false, DefaultNetId, - [this](std::string arg) { - if(arg.size() > NetID::size()) - throw std::invalid_argument(stringify( - "netid is too long, max length is ", NetID::size())); + m_JobQueueSize = arg; + }); - m_netId = std::move(arg); - }); + conf.defineOption("router", "netid", false, DefaultNetId, [this](std::string arg) { + if (arg.size() > NetID::size()) + throw std::invalid_argument(stringify("netid is too long, max length is ", NetID::size())); - int minConnections = (params.isRelay ? DefaultMinConnectionsForRouter - : DefaultMinConnectionsForClient); - conf.defineOption("router", "min-connections", false, minConnections, - [=](int arg) { - if (arg < minConnections) - throw std::invalid_argument(stringify("min-connections must be >= ", minConnections)); + m_netId = std::move(arg); + }); - m_minConnectedRouters = arg; - }); + int minConnections = + (params.isRelay ? DefaultMinConnectionsForRouter : DefaultMinConnectionsForClient); + conf.defineOption("router", "min-connections", false, minConnections, [=](int arg) { + if (arg < minConnections) + throw std::invalid_argument(stringify("min-connections must be >= ", minConnections)); - int maxConnections = (params.isRelay ? DefaultMaxConnectionsForRouter - : DefaultMaxConnectionsForClient); - conf.defineOption("router", "max-connections", false, maxConnections, - [=](int arg) { - if (arg < maxConnections) - throw std::invalid_argument(stringify("max-connections must be >= ", maxConnections)); + m_minConnectedRouters = arg; + }); - m_maxConnectedRouters = arg; - }); + int maxConnections = + (params.isRelay ? DefaultMaxConnectionsForRouter : DefaultMaxConnectionsForClient); + conf.defineOption("router", "max-connections", false, maxConnections, [=](int arg) { + if (arg < maxConnections) + throw std::invalid_argument(stringify("max-connections must be >= ", maxConnections)); - conf.defineOption("router", "nickname", false, "", - AssignmentAcceptor(m_nickname)); + m_maxConnectedRouters = arg; + }); - conf.defineOption("router", "data-dir", false, GetDefaultDataDir(), - [this](std::string arg) { - fs::path dir = arg; - if (not fs::exists(dir)) - throw std::runtime_error(stringify( - "Specified [router]:data-dir ", arg, " does not exist")); + conf.defineOption("router", "nickname", false, "", AssignmentAcceptor(m_nickname)); - m_dataDir = std::move(dir); - }); + conf.defineOption( + "router", "data-dir", false, GetDefaultDataDir(), [this](std::string arg) { + fs::path dir = arg; + if (not fs::exists(dir)) + throw std::runtime_error( + stringify("Specified [router]:data-dir ", arg, " does not exist")); - conf.defineOption("router", "public-address", false, "", - [this](std::string arg) { - if (not arg.empty()) - { + m_dataDir = std::move(dir); + }); - llarp::LogInfo("public ip ", arg, " size ", arg.size()); + conf.defineOption("router", "public-address", false, "", [this](std::string arg) { + if (not arg.empty()) + { + llarp::LogInfo("public ip ", arg, " size ", arg.size()); - if(arg.size() > 16) - throw std::invalid_argument(stringify("Not a valid IPv4 addr: ", arg)); + if (arg.size() > 16) + throw std::invalid_argument(stringify("Not a valid IPv4 addr: ", arg)); - // assume IPv4 - llarp::Addr a(arg); - llarp::LogInfo("setting public ipv4 ", a); - m_addrInfo.ip = *a.addr6(); - m_publicOverride = true; - } - }); + // assume IPv4 + llarp::Addr a(arg); + llarp::LogInfo("setting public ipv4 ", a); + m_addrInfo.ip = *a.addr6(); + m_publicOverride = true; + } + }); - conf.defineOption("router", "public-port", false, DefaultPublicPort, - [this](int arg) { - if (arg <= 0) - throw std::invalid_argument("public-port must be > 0"); + conf.defineOption("router", "public-port", false, DefaultPublicPort, [this](int arg) { + if (arg <= 0) + throw std::invalid_argument("public-port must be > 0"); - // Not needed to flip upside-down - this is done in llarp::Addr(const AddressInfo&) - m_ip4addr.sin_port = arg; - m_addrInfo.port = arg; - m_publicOverride = true; - }); + // Not needed to flip upside-down - this is done in llarp::Addr(const AddressInfo&) + m_ip4addr.sin_port = arg; + m_addrInfo.port = arg; + m_publicOverride = true; + }); - conf.defineOption("router", "worker-threads", false, DefaultWorkerThreads, - [this](int arg) { - if (arg <= 0) - throw std::invalid_argument("worker-threads must be > 0"); + conf.defineOption( + "router", "worker-threads", false, DefaultWorkerThreads, [this](int arg) { + if (arg <= 0) + throw std::invalid_argument("worker-threads must be > 0"); - m_workerThreads = arg; - }); + m_workerThreads = arg; + }); - conf.defineOption("router", "net-threads", false, DefaultNetThreads, - [this](int arg) { - if (arg <= 0) - throw std::invalid_argument("net-threads must be > 0"); + conf.defineOption("router", "net-threads", false, DefaultNetThreads, [this](int arg) { + if (arg <= 0) + throw std::invalid_argument("net-threads must be > 0"); - m_numNetThreads = arg; - }); + m_numNetThreads = arg; + }); - conf.defineOption("router", "block-bogons", false, DefaultBlockBogons, - AssignmentAcceptor(m_blockBogons)); + conf.defineOption( + "router", "block-bogons", false, DefaultBlockBogons, AssignmentAcceptor(m_blockBogons)); } void @@ -144,15 +133,23 @@ namespace llarp constexpr bool DefaultProfilingValue = true; - conf.defineOption("network", "profiling", false, DefaultProfilingValue, - AssignmentAcceptor(m_enableProfiling)); + conf.defineOption( + "network", + "profiling", + false, + DefaultProfilingValue, + AssignmentAcceptor(m_enableProfiling)); // TODO: this should be implied from [router]:data-dir - conf.defineOption("network", "profiles", false, m_routerProfilesFile, - AssignmentAcceptor(m_routerProfilesFile)); + conf.defineOption( + "network", + "profiles", + false, + m_routerProfilesFile, + AssignmentAcceptor(m_routerProfilesFile)); - conf.defineOption("network", "strict-connect", false, "", - AssignmentAcceptor(m_strictConnect)); + conf.defineOption( + "network", "strict-connect", false, "", AssignmentAcceptor(m_strictConnect)); // TODO: make sure this is documented... what does it mean though? conf.addUndeclaredHandler("network", [&](string_view, string_view name, string_view value) { @@ -168,16 +165,16 @@ namespace llarp // TODO: make sure this is documented // TODO: refactor to remove freehand options map - conf.defineOption("network", "upstream-dns", false, true, "", - [this](std::string arg) { - m_options.emplace("upstream-dns", std::move(arg)); - }); + conf.defineOption( + "network", "upstream-dns", false, true, "", [this](std::string arg) { + m_options.emplace("upstream-dns", std::move(arg)); + }); // TODO: make sure this is documented - conf.defineOption("network", "local-dns", false, true, "", - [this](std::string arg) { - m_options.emplace("local-dns", std::move(arg)); - }); + conf.defineOption( + "network", "local-dns", false, true, "", [this](std::string arg) { + m_options.emplace("local-dns", std::move(arg)); + }); } LinksConfig::LinkInfo @@ -216,14 +213,13 @@ namespace llarp if (info.port <= 0) throw std::invalid_argument(stringify("Invalid [bind] port specified on interface", name)); - if(name == "*") + if (name == "*") m_OutboundLink = std::move(info); else m_InboundLinks.emplace_back(std::move(info)); return true; }); - } void @@ -231,19 +227,22 @@ namespace llarp { (void)params; - - conf.addUndeclaredHandler("connect", [this](string_view section, - string_view name, - string_view value) { - fs::path file = str(value); - if (not fs::exists(file)) - throw std::runtime_error(stringify( - "Specified bootstrap file ", value, - "specified in [",section,"]:",name," does not exist")); - - routers.emplace_back(std::move(file)); - return true; - }); + conf.addUndeclaredHandler( + "connect", [this](string_view section, string_view name, string_view value) { + fs::path file = str(value); + if (not fs::exists(file)) + throw std::runtime_error(stringify( + "Specified bootstrap file ", + value, + "specified in [", + section, + "]:", + name, + " does not exist")); + + routers.emplace_back(std::move(file)); + return true; + }); } void @@ -251,13 +250,12 @@ namespace llarp { (void)params; - conf.addUndeclaredHandler("services", [this](string_view section, - string_view name, - string_view value) { - (void)section; - services.emplace_back(name, value); - return true; - }); + conf.addUndeclaredHandler( + "services", [this](string_view section, string_view name, string_view value) { + (void)section; + services.emplace_back(name, value); + return true; + }); } void @@ -268,14 +266,14 @@ namespace llarp constexpr bool DefaultRPCEnabled = true; constexpr auto DefaultRPCBindAddr = "127.0.0.1:1190"; - conf.defineOption("api", "enabled", false, DefaultRPCEnabled, - AssignmentAcceptor(m_enableRPCServer)); + conf.defineOption( + "api", "enabled", false, DefaultRPCEnabled, AssignmentAcceptor(m_enableRPCServer)); - conf.defineOption("api", "bind", false, DefaultRPCBindAddr, - AssignmentAcceptor(m_rpcBindAddr)); + conf.defineOption( + "api", "bind", false, DefaultRPCBindAddr, AssignmentAcceptor(m_rpcBindAddr)); // TODO: this was from pre-refactor: - // TODO: add pubkey to whitelist + // TODO: add pubkey to whitelist } void @@ -286,26 +284,26 @@ namespace llarp constexpr bool DefaultWhitelistRouters = false; constexpr auto DefaultLokidRPCAddr = "127.0.0.1:22023"; - conf.defineOption("lokid", "service-node-seed", false, our_identity_filename, - [this](std::string arg) { - if (not arg.empty()) - { - usingSNSeed = true; - ident_keyfile = std::move(arg); - } - }); + conf.defineOption( + "lokid", "service-node-seed", false, our_identity_filename, [this](std::string arg) { + if (not arg.empty()) + { + usingSNSeed = true; + ident_keyfile = std::move(arg); + } + }); - conf.defineOption("lokid", "enabled", false, DefaultWhitelistRouters, - AssignmentAcceptor(whitelistRouters)); + conf.defineOption( + "lokid", "enabled", false, DefaultWhitelistRouters, AssignmentAcceptor(whitelistRouters)); - conf.defineOption("lokid", "jsonrpc", false, DefaultLokidRPCAddr, - AssignmentAcceptor(lokidRPCAddr)); + conf.defineOption( + "lokid", "jsonrpc", false, DefaultLokidRPCAddr, AssignmentAcceptor(lokidRPCAddr)); - conf.defineOption("lokid", "username", false, "", - AssignmentAcceptor(lokidRPCUser)); + conf.defineOption( + "lokid", "username", false, "", AssignmentAcceptor(lokidRPCUser)); - conf.defineOption("lokid", "password", false, "", - AssignmentAcceptor(lokidRPCPassword)); + conf.defineOption( + "lokid", "password", false, "", AssignmentAcceptor(lokidRPCPassword)); } void @@ -313,11 +311,11 @@ namespace llarp { (void)params; - conf.defineOption("bootstrap", "add-node", false, true, "", - [this](std::string arg) { - // TODO: validate as router fs path - routers.emplace_back(std::move(arg)); - }); + conf.defineOption( + "bootstrap", "add-node", false, true, "", [this](std::string arg) { + // TODO: validate as router fs path + routers.emplace_back(std::move(arg)); + }); } void @@ -329,26 +327,26 @@ namespace llarp constexpr auto DefaultLogFile = "stdout"; constexpr auto DefaultLogLevel = "info"; - conf.defineOption("logging", "type", false, DefaultLogType, - [this](std::string arg) { - LogType type = LogTypeFromString(arg); - if (type == LogType::Unknown) - throw std::invalid_argument(stringify("invalid log type: ", arg)); + conf.defineOption( + "logging", "type", false, DefaultLogType, [this](std::string arg) { + LogType type = LogTypeFromString(arg); + if (type == LogType::Unknown) + throw std::invalid_argument(stringify("invalid log type: ", arg)); - m_logType = type; - }); + m_logType = type; + }); - conf.defineOption("logging", "level", false, DefaultLogLevel, - [this](std::string arg) { - nonstd::optional level = LogLevelFromString(arg); - if (not level.has_value()) - throw std::invalid_argument(stringify( "invalid log level value: ", arg)); + conf.defineOption( + "logging", "level", false, DefaultLogLevel, [this](std::string arg) { + nonstd::optional level = LogLevelFromString(arg); + if (not level.has_value()) + throw std::invalid_argument(stringify("invalid log level value: ", arg)); - m_logLevel = level.value(); - }); + m_logLevel = level.value(); + }); - conf.defineOption("logging", "file", false, DefaultLogFile, - AssignmentAcceptor(m_logFile)); + conf.defineOption( + "logging", "file", false, DefaultLogFile, AssignmentAcceptor(m_logFile)); } void @@ -360,50 +358,43 @@ namespace llarp static constexpr int HopsDefault = 4; static constexpr int PathsDefault = 6; - conf.defineOption("snapp", "keyfile", false, "", - [this](std::string arg) { - // TODO: validate as valid .loki / .snode address - m_keyfile = arg; - }); + conf.defineOption("snapp", "keyfile", false, "", [this](std::string arg) { + // TODO: validate as valid .loki / .snode address + m_keyfile = arg; + }); - conf.defineOption("snapp", "reachable", false, ReachableDefault, - AssignmentAcceptor(m_reachable)); + conf.defineOption( + "snapp", "reachable", false, ReachableDefault, AssignmentAcceptor(m_reachable)); - conf.defineOption("snapp", "hops", false, HopsDefault, - [this](int arg) { - if (arg < 1 or arg > 8) - throw std::invalid_argument("[snapp]:hops must be >= 1 and <= 8"); - }); + conf.defineOption("snapp", "hops", false, HopsDefault, [this](int arg) { + if (arg < 1 or arg > 8) + throw std::invalid_argument("[snapp]:hops must be >= 1 and <= 8"); + }); - conf.defineOption("snapp", "paths", false, PathsDefault, - [this](int arg) { - if (arg < 1 or arg > 8) - throw std::invalid_argument("[snapp]:paths must be >= 1 and <= 8"); - }); + conf.defineOption("snapp", "paths", false, PathsDefault, [this](int arg) { + if (arg < 1 or arg > 8) + throw std::invalid_argument("[snapp]:paths must be >= 1 and <= 8"); + }); - conf.defineOption("snapp", "exit-node", false, "", - [this](std::string arg) { - // TODO: validate as valid .loki / .snode address - m_exitNode = arg; - }); + conf.defineOption("snapp", "exit-node", false, "", [this](std::string arg) { + // TODO: validate as valid .loki / .snode address + m_exitNode = arg; + }); - conf.defineOption("snapp", "local-dns", false, "", - [this](std::string arg) { - // TODO: validate as IP address - m_localDNS = arg; - }); + conf.defineOption("snapp", "local-dns", false, "", [this](std::string arg) { + // TODO: validate as IP address + m_localDNS = arg; + }); - conf.defineOption("snapp", "upstream-dns", false, "", - [this](std::string arg) { - // TODO: validate as IP address - m_upstreamDNS = arg; - }); + conf.defineOption("snapp", "upstream-dns", false, "", [this](std::string arg) { + // TODO: validate as IP address + m_upstreamDNS = arg; + }); - conf.defineOption("snapp", "mapaddr", false, "", - [this](std::string arg) { - // TODO: parse / validate as loki_addr : IP addr pair - m_mapAddr = arg; - }); + conf.defineOption("snapp", "mapaddr", false, "", [this](std::string arg) { + // TODO: parse / validate as loki_addr : IP addr pair + m_mapAddr = arg; + }); conf.addUndeclaredHandler("snapp", [&](string_view, string_view name, string_view value) { if (name == "blacklist-snode") @@ -414,11 +405,10 @@ namespace llarp return false; }); - } bool - Config::Load(const char *fname, bool isRelay, fs::path defaultDataDir) + Config::Load(const char* fname, bool isRelay, fs::path defaultDataDir) { try { @@ -430,7 +420,7 @@ namespace llarp initializeConfig(conf, params); ConfigParser parser; - if(!parser.LoadFile(fname)) + if (!parser.LoadFile(fname)) { return false; } @@ -450,7 +440,7 @@ namespace llarp return true; } - catch(const std::exception& e) + catch (const std::exception& e) { LogError("Error trying to init and parse config from file: ", e.what()); return false; @@ -462,7 +452,7 @@ namespace llarp { // TODO: this seems like a random place to put this, should this be closer // to main() ? - if(Lokinet_INIT()) + if (Lokinet_INIT()) throw std::runtime_error("Can't initializeConfig() when Lokinet_INIT() == true"); router.defineConfigOptions(conf, params); @@ -478,21 +468,20 @@ namespace llarp } void - ensureConfig(const fs::path& defaultDataDir, - const fs::path& confFile, - bool overwrite, - bool asRouter) + ensureConfig( + const fs::path& defaultDataDir, const fs::path& confFile, bool overwrite, bool asRouter) { std::error_code ec; // fail to overwrite if not instructed to do so - if(fs::exists(confFile, ec) && !overwrite) + if (fs::exists(confFile, ec) && !overwrite) { LogDebug("Not creating config file; it already exists."); return; } - if (ec) throw std::runtime_error(stringify("filesystem error: ", ec)); + if (ec) + throw std::runtime_error(stringify("filesystem error: ", ec)); // create parent dir if it doesn't exist if (not fs::exists(confFile.parent_path(), ec)) @@ -500,10 +489,10 @@ namespace llarp if (not fs::create_directory(confFile.parent_path())) throw std::runtime_error(stringify("Failed to create parent directory for ", confFile)); } - if (ec) throw std::runtime_error(stringify("filesystem error: ", ec)); + if (ec) + throw std::runtime_error(stringify("filesystem error: ", ec)); - llarp::LogInfo("Attempting to create config file, asRouter: ", asRouter, - " path: ", confFile); + llarp::LogInfo("Attempting to create config file, asRouter: ", asRouter, " path: ", confFile); llarp::Config config; std::string confStr; @@ -528,123 +517,180 @@ namespace llarp void generateCommonConfigComments(ConfigDefinition& def) { - // router - def.addSectionComments("router", { - "Configuration for routing activity.", - }); - - def.addOptionComments("router", "threads", { - "The number of threads available for performing cryptographic functions.", - "The minimum is one thread, but network performance may increase with more.", - "threads. Should not exceed the number of logical CPU cores.", - }); + def.addSectionComments( + "router", + { + "Configuration for routing activity.", + }); - def.addOptionComments("router", "data-dir", { - "Optional directory for containing lokinet runtime data. This includes generated", - "private keys.", - }); + def.addOptionComments( + "router", + "threads", + { + "The number of threads available for performing cryptographic functions.", + "The minimum is one thread, but network performance may increase with more.", + "threads. Should not exceed the number of logical CPU cores.", + }); + + def.addOptionComments( + "router", + "data-dir", + { + "Optional directory for containing lokinet runtime data. This includes generated", + "private keys.", + }); // TODO: why did Kee want this, and/or what does it really do? Something about logs? - def.addOptionComments("router", "nickname", { - "Router nickname. Kee wanted it." - }); + def.addOptionComments("router", "nickname", {"Router nickname. Kee wanted it."}); - def.addOptionComments("router", "min-connections", { - "Minimum number of routers lokinet will attempt to maintain connections to.", - }); + def.addOptionComments( + "router", + "min-connections", + { + "Minimum number of routers lokinet will attempt to maintain connections to.", + }); - def.addOptionComments("router", "max-connections", { - "Maximum number (hard limit) of routers lokinet will be connected to at any time.", - }); + def.addOptionComments( + "router", + "max-connections", + { + "Maximum number (hard limit) of routers lokinet will be connected to at any time.", + }); // logging - def.addSectionComments("logging", { - "logging settings", - }); - - def.addOptionComments("logging", "level", { - "Minimum log level to print. Logging below this level will be ignored.", - "Valid log levels, in ascending order, are:", - " trace", - " debug", - " info", - " warn", - " error", - }); + def.addSectionComments( + "logging", + { + "logging settings", + }); - def.addOptionComments("logging", "type", { - "Log type (format). Valid options are:", - " file - plaintext formatting", - " json - json-formatted log statements", - " syslog - logs directed to syslog", - }); + def.addOptionComments( + "logging", + "level", + { + "Minimum log level to print. Logging below this level will be ignored.", + "Valid log levels, in ascending order, are:", + " trace", + " debug", + " info", + " warn", + " error", + }); + + def.addOptionComments( + "logging", + "type", + { + "Log type (format). Valid options are:", + " file - plaintext formatting", + " json - json-formatted log statements", + " syslog - logs directed to syslog", + }); // api - def.addSectionComments("api", { - "JSON API settings", - }); + def.addSectionComments( + "api", + { + "JSON API settings", + }); - def.addOptionComments("api", "enabled", { - "Determines whether or not the JSON API is enabled.", - }); + def.addOptionComments( + "api", + "enabled", + { + "Determines whether or not the JSON API is enabled.", + }); - def.addOptionComments("api", "bind", { - "IP address and port to bind to.", - "Recommend localhost-only for security purposes.", - }); + def.addOptionComments( + "api", + "bind", + { + "IP address and port to bind to.", + "Recommend localhost-only for security purposes.", + }); // dns - def.addSectionComments("dns", { - "DNS configuration", - }); + def.addSectionComments( + "dns", + { + "DNS configuration", + }); - def.addOptionComments("dns", "upstream", { - "Upstream resolver to use as fallback for non-loki addresses.", - "Multiple values accepted.", - }); + def.addOptionComments( + "dns", + "upstream", + { + "Upstream resolver to use as fallback for non-loki addresses.", + "Multiple values accepted.", + }); - def.addOptionComments("dns", "bind", { - "Address to bind to for handling DNS requests.", - "Multiple values accepted.", - }); + def.addOptionComments( + "dns", + "bind", + { + "Address to bind to for handling DNS requests.", + "Multiple values accepted.", + }); // bootstrap - def.addSectionComments("bootstrap", { - "Configure nodes that will bootstrap us onto the network", - }); + def.addSectionComments( + "bootstrap", + { + "Configure nodes that will bootstrap us onto the network", + }); - def.addOptionComments("bootstrap", "add-node", { - "Specify a bootstrap file containing a signed RouterContact of a service node", - "which can act as a bootstrap. Accepts multiple values.", - }); + def.addOptionComments( + "bootstrap", + "add-node", + { + "Specify a bootstrap file containing a signed RouterContact of a service node", + "which can act as a bootstrap. Accepts multiple values.", + }); // network - def.addSectionComments("network", { - "Network settings", - }); - - def.addOptionComments("network", "profiles", { - "File to contain router profiles.", - }); + def.addSectionComments( + "network", + { + "Network settings", + }); - def.addOptionComments("network", "strict-connect", { - "Public key of a router which will act as sole first-hop. This may be used to", - "provide a trusted router (consider that you are not fully anonymous with your", - "first hop).", - }); + def.addOptionComments( + "network", + "profiles", + { + "File to contain router profiles.", + }); - def.addOptionComments("network", "exit-node", { - "Public key of an exit-node.", - }); + def.addOptionComments( + "network", + "strict-connect", + { + "Public key of a router which will act as sole first-hop. This may be used to", + "provide a trusted router (consider that you are not fully anonymous with your", + "first hop).", + }); + + def.addOptionComments( + "network", + "exit-node", + { + "Public key of an exit-node.", + }); - def.addOptionComments("network", "ifname", { - "Interface name for lokinet traffic.", - }); + def.addOptionComments( + "network", + "ifname", + { + "Interface name for lokinet traffic.", + }); - def.addOptionComments("network", "ifaddr", { - "Local IP address for lokinet traffic.", - }); + def.addOptionComments( + "network", + "ifaddr", + { + "Local IP address for lokinet traffic.", + }); } std::string @@ -659,52 +705,81 @@ namespace llarp generateCommonConfigComments(def); // snapp - def.addSectionComments("snapp", { - "Snapp settings", - }); + def.addSectionComments( + "snapp", + { + "Snapp settings", + }); - def.addOptionComments("snapp", "keyfile", { - "The private key to persist address with. If not specified the address will be", - "ephemeral.", - }); + def.addOptionComments( + "snapp", + "keyfile", + { + "The private key to persist address with. If not specified the address will be", + "ephemeral.", + }); // TODO: is this redundant with / should be merged with basic client config? - def.addOptionComments("snapp", "reachable", { - "Determines whether we will publish our snapp's introset to the DHT.", - }); + def.addOptionComments( + "snapp", + "reachable", + { + "Determines whether we will publish our snapp's introset to the DHT.", + }); // TODO: merge with client conf? - def.addOptionComments("snapp", "hops", { - "Number of hops in a path. Min 1, max 8.", - }); + def.addOptionComments( + "snapp", + "hops", + { + "Number of hops in a path. Min 1, max 8.", + }); // TODO: is this actually different than client's paths min/max config? - def.addOptionComments("snapp", "paths", { - "Number of paths to maintain at any given time.", - }); + def.addOptionComments( + "snapp", + "paths", + { + "Number of paths to maintain at any given time.", + }); - def.addOptionComments("snapp", "blacklist-snode", { - "Adds a `.snode` address to the blacklist.", - }); + def.addOptionComments( + "snapp", + "blacklist-snode", + { + "Adds a `.snode` address to the blacklist.", + }); - def.addOptionComments("snapp", "exit-node", { - "Specify a `.snode` or `.loki` address to use as an exit broker.", - }); + def.addOptionComments( + "snapp", + "exit-node", + { + "Specify a `.snode` or `.loki` address to use as an exit broker.", + }); // TODO: merge with client conf? - def.addOptionComments("snapp", "local-dns", { - "Address to bind local DNS resolver to. Ex: `127.3.2.1:53`. Iif port is omitted, port", - }); + def.addOptionComments( + "snapp", + "local-dns", + { + "Address to bind local DNS resolver to. Ex: `127.3.2.1:53`. Iif port is omitted, port", + }); - def.addOptionComments("snapp", "upstream-dns", { - "Address to forward non-lokinet related queries to. If not set, lokinet DNS will reply", - "with `srvfail`.", - }); + def.addOptionComments( + "snapp", + "upstream-dns", + { + "Address to forward non-lokinet related queries to. If not set, lokinet DNS will reply", + "with `srvfail`.", + }); - def.addOptionComments("snapp", "mapaddr", { - "Permanently map a `.loki` address to an IP owned by the snapp. Example:", - "mapaddr=whatever.loki:10.0.10.10 # maps `whatever.loki` to `10.0.10.10`.", - }); + def.addOptionComments( + "snapp", + "mapaddr", + { + "Permanently map a `.loki` address to an IP owned by the snapp. Example:", + "mapaddr=whatever.loki:10.0.10.10 # maps `whatever.loki` to `10.0.10.10`.", + }); return def.generateINIConfig(true); } @@ -721,43 +796,62 @@ namespace llarp generateCommonConfigComments(def); // lokid - def.addSectionComments("lokid", { - "Lokid configuration (settings for talking to lokid", - }); + def.addSectionComments( + "lokid", + { + "Lokid configuration (settings for talking to lokid", + }); - def.addOptionComments("lokid", "enabled", { - "Whether or not we should talk to lokid. Must be enabled for staked routers.", - }); + def.addOptionComments( + "lokid", + "enabled", + { + "Whether or not we should talk to lokid. Must be enabled for staked routers.", + }); - def.addOptionComments("lokid", "jsonrpc", { - "Host and port of running lokid that we should talk to.", - }); + def.addOptionComments( + "lokid", + "jsonrpc", + { + "Host and port of running lokid that we should talk to.", + }); // TODO: doesn't appear to be used in the codebase - def.addOptionComments("lokid", "service-node-seed", { - "File containing service node's seed.", - }); + def.addOptionComments( + "lokid", + "service-node-seed", + { + "File containing service node's seed.", + }); // extra [network] options // TODO: probably better to create an [exit] section and only allow it for routers - def.addOptionComments("network", "exit", { - "Whether or not we should act as an exit node. Beware that this increases demand", - "on the server and may pose liability concerns. Enable at your own risk.", - }); + def.addOptionComments( + "network", + "exit", + { + "Whether or not we should act as an exit node. Beware that this increases demand", + "on the server and may pose liability concerns. Enable at your own risk.", + }); // TODO: define the order of precedence (e.g. is whitelist applied before blacklist?) // additionally, what's default? What if I don't whitelist anything? - def.addOptionComments("network", "exit-whitelist", { - "List of destination protocol:port pairs to whitelist, example: udp:*", - "or tcp:80. Multiple values supported.", - }); + def.addOptionComments( + "network", + "exit-whitelist", + { + "List of destination protocol:port pairs to whitelist, example: udp:*", + "or tcp:80. Multiple values supported.", + }); - def.addOptionComments("network", "exit-blacklist", { - "Blacklist of destinations (same format as whitelist).", - }); + def.addOptionComments( + "network", + "exit-blacklist", + { + "Blacklist of destinations (same format as whitelist).", + }); return def.generateINIConfig(true); } } // namespace llarp - diff --git a/llarp/config/config.hpp b/llarp/config/config.hpp index da9b4241f..36600ffe5 100644 --- a/llarp/config/config.hpp +++ b/llarp/config/config.hpp @@ -22,7 +22,7 @@ namespace llarp using Config_impl_t = llarp::ConfigParser::Config_impl_t; // TODO: don't use these maps. they're sloppy and difficult to follow - using FreehandOptions = std::unordered_multimap< std::string, std::string >; + using FreehandOptions = std::unordered_multimap; /// Small struct to gather all parameters needed for config generation to reduce the number of /// parameters that need to be passed around. @@ -59,7 +59,7 @@ namespace llarp struct NetworkConfig { - nonstd::optional< bool > m_enableProfiling; + nonstd::optional m_enableProfiling; std::string m_routerProfilesFile; std::string m_strictConnect; FreehandOptions m_options; @@ -106,7 +106,7 @@ namespace llarp struct ServicesConfig { - std::vector< std::pair< std::string, std::string > > services; + std::vector> services; void defineConfigOptions(ConfigDefinition& conf, const ConfigGenParameters& params); }; @@ -135,7 +135,7 @@ namespace llarp struct BootstrapConfig { - std::vector< std::string > routers; + std::vector routers; void defineConfigOptions(ConfigDefinition& conf, const ConfigGenParameters& params); }; @@ -195,10 +195,8 @@ namespace llarp }; void - ensureConfig(const fs::path& defaultDataDir, - const fs::path& confFile, - bool overwrite, - bool asRouter); + ensureConfig( + const fs::path& defaultDataDir, const fs::path& confFile, bool overwrite, bool asRouter); } // namespace llarp diff --git a/llarp/config/definition.cpp b/llarp/config/definition.cpp index 13833062e..64f713b4f 100644 --- a/llarp/config/definition.cpp +++ b/llarp/config/definition.cpp @@ -5,238 +5,223 @@ namespace llarp { + OptionDefinitionBase::OptionDefinitionBase( + std::string section_, std::string name_, bool required_) + : section(section_), name(name_), required(required_) + { + } + OptionDefinitionBase::OptionDefinitionBase( + std::string section_, std::string name_, bool required_, bool multiValued_) + : section(section_), name(name_), required(required_), multiValued(multiValued_) + { + } -OptionDefinitionBase::OptionDefinitionBase(std::string section_, - std::string name_, - bool required_) - : section(section_) - , name(name_) - , required(required_) -{ -} -OptionDefinitionBase::OptionDefinitionBase(std::string section_, - std::string name_, - bool required_, - bool multiValued_) - : section(section_) - , name(name_) - , required(required_) - , multiValued(multiValued_) -{ -} - -ConfigDefinition& -ConfigDefinition::defineOption(OptionDefinition_ptr def) -{ - auto sectionItr = m_definitions.find(def->section); - if (sectionItr == m_definitions.end()) - m_sectionOrdering.push_back(def->section); + ConfigDefinition& + ConfigDefinition::defineOption(OptionDefinition_ptr def) + { + auto sectionItr = m_definitions.find(def->section); + if (sectionItr == m_definitions.end()) + m_sectionOrdering.push_back(def->section); - auto& sectionDefinitions = m_definitions[def->section]; - if (sectionDefinitions.find(def->name) != sectionDefinitions.end()) - throw std::invalid_argument(stringify("definition for [", - def->section, "]:", def->name, " already exists")); + auto& sectionDefinitions = m_definitions[def->section]; + if (sectionDefinitions.find(def->name) != sectionDefinitions.end()) + throw std::invalid_argument( + stringify("definition for [", def->section, "]:", def->name, " already exists")); - m_definitionOrdering[def->section].push_back(def->name); - sectionDefinitions[def->name] = std::move(def); + m_definitionOrdering[def->section].push_back(def->name); + sectionDefinitions[def->name] = std::move(def); - return *this; -} + return *this; + } -ConfigDefinition& -ConfigDefinition::addConfigValue(string_view section, string_view name, string_view value) -{ - auto secItr = m_definitions.find(std::string(section)); - if (secItr == m_definitions.end()) + ConfigDefinition& + ConfigDefinition::addConfigValue(string_view section, string_view name, string_view value) { - // fallback to undeclared handler if available - auto undItr = m_undeclaredHandlers.find(std::string(section)); - if (undItr == m_undeclaredHandlers.end()) - throw std::invalid_argument(stringify("no declared section [", section, "]")); - else + auto secItr = m_definitions.find(std::string(section)); + if (secItr == m_definitions.end()) { - auto& handler = undItr->second; - handler(section, name, value); - return *this; + // fallback to undeclared handler if available + auto undItr = m_undeclaredHandlers.find(std::string(section)); + if (undItr == m_undeclaredHandlers.end()) + throw std::invalid_argument(stringify("no declared section [", section, "]")); + else + { + auto& handler = undItr->second; + handler(section, name, value); + return *this; + } } - } - // section was valid, get definition by name - auto& sectionDefinitions = secItr->second; - auto defItr = sectionDefinitions.find(std::string(name)); - if (defItr == sectionDefinitions.end()) - throw std::invalid_argument(stringify("no declared option [", section, "]:", name)); + // section was valid, get definition by name + auto& sectionDefinitions = secItr->second; + auto defItr = sectionDefinitions.find(std::string(name)); + if (defItr == sectionDefinitions.end()) + throw std::invalid_argument(stringify("no declared option [", section, "]:", name)); - OptionDefinition_ptr& definition = defItr->second; - definition->parseValue(std::string(value)); + OptionDefinition_ptr& definition = defItr->second; + definition->parseValue(std::string(value)); - return *this; -} - -void -ConfigDefinition::addUndeclaredHandler(const std::string& section, UndeclaredValueHandler handler) -{ - auto itr = m_undeclaredHandlers.find(section); - if (itr != m_undeclaredHandlers.end()) - throw std::logic_error(stringify("section ", section, " already has a handler")); + return *this; + } - m_undeclaredHandlers[section] = std::move(handler); -} + void + ConfigDefinition::addUndeclaredHandler(const std::string& section, UndeclaredValueHandler handler) + { + auto itr = m_undeclaredHandlers.find(section); + if (itr != m_undeclaredHandlers.end()) + throw std::logic_error(stringify("section ", section, " already has a handler")); -void -ConfigDefinition::removeUndeclaredHandler(const std::string& section) -{ - auto itr = m_undeclaredHandlers.find(section); - if (itr != m_undeclaredHandlers.end()) - m_undeclaredHandlers.erase(itr); -} + m_undeclaredHandlers[section] = std::move(handler); + } -void -ConfigDefinition::validateRequiredFields() -{ - visitSections([&](const std::string& section, const DefinitionMap&) + void + ConfigDefinition::removeUndeclaredHandler(const std::string& section) { - visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def) - { - if (def->required and def->getNumberFound() < 1) - { - throw std::invalid_argument(stringify( - "[", section, "]:", def->name, " is required but missing")); - } - - // should be handled earlier in OptionDefinition::parseValue() - assert(def->getNumberFound() <= 1 or def->multiValued); - }); - }); -} + auto itr = m_undeclaredHandlers.find(section); + if (itr != m_undeclaredHandlers.end()) + m_undeclaredHandlers.erase(itr); + } -void -ConfigDefinition::acceptAllOptions() -{ - visitSections([&](const std::string& section, const DefinitionMap&) + void + ConfigDefinition::validateRequiredFields() { - visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def) - { - def->tryAccept(); + visitSections([&](const std::string& section, const DefinitionMap&) { + visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def) { + if (def->required and def->getNumberFound() < 1) + { + throw std::invalid_argument( + stringify("[", section, "]:", def->name, " is required but missing")); + } + + // should be handled earlier in OptionDefinition::parseValue() + assert(def->getNumberFound() <= 1 or def->multiValued); + }); }); - }); -} + } -void -ConfigDefinition::addSectionComments(const std::string& section, - std::vector comments) -{ - auto& sectionComments = m_sectionComments[section]; - for (size_t i=0; itryAccept(); }); + }); } -} -void -ConfigDefinition::addOptionComments(const std::string& section, - const std::string& name, - std::vector comments) -{ - auto& defComments = m_definitionComments[section][name]; - for (size_t i=0; i comments) { - defComments.emplace_back(std::move(comments[i])); + auto& sectionComments = m_sectionComments[section]; + for (size_t i = 0; i < comments.size(); ++i) + { + sectionComments.emplace_back(std::move(comments[i])); + } } -} - -std::string -ConfigDefinition::generateINIConfig(bool useValues) -{ - std::ostringstream oss; - - int sectionsVisited = 0; - visitSections([&](const std::string& section, const DefinitionMap&) { - if (sectionsVisited > 0) - oss << "\n\n"; - - // TODO: this will create empty objects as a side effect of map's operator[] - // TODO: this also won't handle sections which have no definition - for (const std::string& comment : m_sectionComments[section]) + void + ConfigDefinition::addOptionComments( + const std::string& section, const std::string& name, std::vector comments) + { + auto& defComments = m_definitionComments[section][name]; + for (size_t i = 0; i < comments.size(); ++i) { - oss << "# " << comment << "\n"; + defComments.emplace_back(std::move(comments[i])); } + } - oss << "[" << section << "]\n"; + std::string + ConfigDefinition::generateINIConfig(bool useValues) + { + std::ostringstream oss; - visitDefinitions(section, [&](const std::string& name, const OptionDefinition_ptr& def) { - oss << "\n"; + int sectionsVisited = 0; - // TODO: as above, this will create empty objects - // TODO: as above (but more important): this won't handle definitions with no entries - // (i.e. those handled by UndeclaredValueHandler's) - for (const std::string& comment : m_definitionComments[section][name]) - { - oss << "# " << comment << "\n"; - } + visitSections([&](const std::string& section, const DefinitionMap&) { + if (sectionsVisited > 0) + oss << "\n\n"; - if (useValues and def->getNumberFound() > 0) - { - oss << name << "=" << def->valueAsString(false) << "\n"; - } - else + // TODO: this will create empty objects as a side effect of map's operator[] + // TODO: this also won't handle sections which have no definition + for (const std::string& comment : m_sectionComments[section]) { - if (not def->required) - oss << "#"; - oss << name << "=" << def->defaultValueAsString() << "\n"; + oss << "# " << comment << "\n"; } + oss << "[" << section << "]\n"; + + visitDefinitions(section, [&](const std::string& name, const OptionDefinition_ptr& def) { + oss << "\n"; + + // TODO: as above, this will create empty objects + // TODO: as above (but more important): this won't handle definitions with no entries + // (i.e. those handled by UndeclaredValueHandler's) + for (const std::string& comment : m_definitionComments[section][name]) + { + oss << "# " << comment << "\n"; + } + + if (useValues and def->getNumberFound() > 0) + { + oss << name << "=" << def->valueAsString(false) << "\n"; + } + else + { + if (not def->required) + oss << "#"; + oss << name << "=" << def->defaultValueAsString() << "\n"; + } + }); + + sectionsVisited++; }); - sectionsVisited++; - }); - - return oss.str(); -} - -const OptionDefinition_ptr& -ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) const -{ - const auto sectionItr = m_definitions.find(std::string(section)); - if (sectionItr == m_definitions.end()) - throw std::invalid_argument(stringify("No config section [", section, "]")); - - auto& sectionDefinitions = sectionItr->second; - const auto definitionItr = sectionDefinitions.find(std::string(name)); - if (definitionItr == sectionDefinitions.end()) - throw std::invalid_argument(stringify("No config item ", name, " within section ", section)); + return oss.str(); + } - return definitionItr->second; -} + const OptionDefinition_ptr& + ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) const + { + const auto sectionItr = m_definitions.find(std::string(section)); + if (sectionItr == m_definitions.end()) + throw std::invalid_argument(stringify("No config section [", section, "]")); -OptionDefinition_ptr& -ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) -{ - return const_cast( - const_cast(this)->lookupDefinitionOrThrow(section, name)); -} + auto& sectionDefinitions = sectionItr->second; + const auto definitionItr = sectionDefinitions.find(std::string(name)); + if (definitionItr == sectionDefinitions.end()) + throw std::invalid_argument(stringify("No config item ", name, " within section ", section)); -void ConfigDefinition::visitSections(SectionVisitor visitor) const -{ - for (const std::string& section : m_sectionOrdering) - { - const auto itr = m_definitions.find(section); - assert(itr != m_definitions.end()); - visitor(section, itr->second); + return definitionItr->second; } -}; -void ConfigDefinition::visitDefinitions(const std::string& section, DefVisitor visitor) const -{ - const auto& defs = m_definitions.at(section); - const auto& defOrdering = m_definitionOrdering.at(section); - for (const std::string& name : defOrdering) + + OptionDefinition_ptr& + ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) { - const auto itr = defs.find(name); - assert(itr != defs.end()); - visitor(name, itr->second); + return const_cast( + const_cast(this)->lookupDefinitionOrThrow(section, name)); } -}; -} // namespace llarp + void + ConfigDefinition::visitSections(SectionVisitor visitor) const + { + for (const std::string& section : m_sectionOrdering) + { + const auto itr = m_definitions.find(section); + assert(itr != m_definitions.end()); + visitor(section, itr->second); + } + }; + void + ConfigDefinition::visitDefinitions(const std::string& section, DefVisitor visitor) const + { + const auto& defs = m_definitions.at(section); + const auto& defOrdering = m_definitionOrdering.at(section); + for (const std::string& name : defOrdering) + { + const auto itr = defs.find(name); + assert(itr != defs.end()); + visitor(name, itr->second); + } + }; +} // namespace llarp diff --git a/llarp/config/definition.hpp b/llarp/config/definition.hpp index 95676ac48..fc88291d6 100644 --- a/llarp/config/definition.hpp +++ b/llarp/config/definition.hpp @@ -12,23 +12,19 @@ namespace llarp { - /// A base class for specifying config options and their constraints. The basic to/from string /// type functions are provided pure-virtual. The type-aware implementations which implement these /// functions are templated classes. One reason for providing a non-templated base class is so /// that they can all be mixed into the same containers (albiet as pointers). - struct OptionDefinitionBase + struct OptionDefinitionBase { - OptionDefinitionBase(std::string section_, - std::string name_, - bool required_); - OptionDefinitionBase(std::string section_, - std::string name_, - bool required_, - bool multiValued_); + OptionDefinitionBase(std::string section_, std::string name_, bool required_); + OptionDefinitionBase( + std::string section_, std::string name_, bool required_, bool multiValued_); - virtual - ~OptionDefinitionBase() {} + virtual ~OptionDefinitionBase() + { + } /// Subclasses should provide their default value as a string /// @@ -59,7 +55,8 @@ namespace llarp /// Subclassess should call their acceptor, if present. See OptionDefinition for more details. /// /// @throws if the acceptor throws or the option is required but missing - virtual void tryAccept() const = 0; + virtual void + tryAccept() const = 0; std::string section; std::string name; @@ -70,10 +67,11 @@ namespace llarp /// The primary type-aware implementation of OptionDefinitionBase, this templated class allows /// for implementations which can use the std::ostringstream and std::istringstream for to/from /// string functionality. - /// - /// Note that types (T) used as template parameters here must be used verbatim when calling - /// ConfigDefinition::getConfigValue(). Similar types such as uint32_t and int32_t cannot be mixed. - template + /// + /// Note that types (T) used as template parameters here must be used verbatim when calling + /// ConfigDefinition::getConfigValue(). Similar types such as uint32_t and int32_t cannot be + /// mixed. + template struct OptionDefinition : public OptionDefinitionBase { /// Constructor. Arguments are passed directly to OptionDefinitionBase. @@ -86,27 +84,29 @@ namespace llarp /// @param acceptor_ is an optional function whose purpose is to both validate the parsed /// input and internalize it (e.g. copy it for runtime use). The acceptor should throw /// an exception with a useful message if it is not acceptable. - OptionDefinition(std::string section_, - std::string name_, - bool required_, - nonstd::optional defaultValue_, - std::function acceptor_ = nullptr) - : OptionDefinitionBase(section_, name_, required_) - , defaultValue(defaultValue_) - , acceptor(acceptor_) + OptionDefinition( + std::string section_, + std::string name_, + bool required_, + nonstd::optional defaultValue_, + std::function acceptor_ = nullptr) + : OptionDefinitionBase(section_, name_, required_) + , defaultValue(defaultValue_) + , acceptor(acceptor_) { } /// As above, but also takes a bool value for multiValued. - OptionDefinition(std::string section_, - std::string name_, - bool required_, - bool multiValued_, - nonstd::optional defaultValue_, - std::function acceptor_ = nullptr) - : OptionDefinitionBase(section_, name_, required_, multiValued_) - , defaultValue(defaultValue_) - , acceptor(acceptor_) + OptionDefinition( + std::string section_, + std::string name_, + bool required_, + bool multiValued_, + nonstd::optional defaultValue_, + std::function acceptor_ = nullptr) + : OptionDefinitionBase(section_, name_, required_, multiValued_) + , defaultValue(defaultValue_) + , acceptor(acceptor_) { } @@ -127,15 +127,15 @@ namespace llarp /// Returns the value at the given index. /// - /// @param index + /// @param index /// @return the value at the given index, if it exists /// @throws range_error exception if index >= size T getValueAt(size_t index) const { if (index >= parsedValues.size()) - throw std::range_error(stringify( - "no value at index ", index, ", size: ", parsedValues.size())); + throw std::range_error( + stringify("no value at index ", index, ", size: ", parsedValues.size())); return parsedValues[index]; } @@ -164,10 +164,10 @@ namespace llarp { if (not multiValued and parsedValues.size() > 0) { - throw std::invalid_argument(stringify("duplicate value for ", name, - ", previous value: ", parsedValues[0])); + throw std::invalid_argument( + stringify("duplicate value for ", name, ", previous value: ", parsedValues[0])); } - + std::istringstream iss(input); T t; iss >> t; @@ -179,7 +179,6 @@ namespace llarp { parsedValues.emplace_back(std::move(t)); } - } std::string @@ -204,8 +203,12 @@ namespace llarp { if (required and parsedValues.size() == 0) { - throw std::runtime_error(stringify("cannot call tryAccept() on [", - section, "]:", name, " when required but no value available")); + throw std::runtime_error(stringify( + "cannot call tryAccept() on [", + section, + "]:", + name, + " when required but no value available")); } // don't use default value if we are multi-valued and have no value @@ -224,7 +227,7 @@ namespace llarp else { auto maybe = getValue(); - assert(maybe.has_value()); // should be guaranteed by our earlier checks + assert(maybe.has_value()); // should be guaranteed by our earlier checks // TODO: avoid copies here if possible acceptor(maybe.value()); } @@ -236,9 +239,8 @@ namespace llarp std::function acceptor; }; - using UndeclaredValueHandler - = std::function; - + using UndeclaredValueHandler = + std::function; using OptionDefinition_ptr = std::unique_ptr; @@ -253,17 +255,17 @@ namespace llarp /// /// The layout and grouping of the config options are modelled after the INI file format; each /// option has a name and is grouped under a section. Duplicate option names are allowed only if - /// they exist in a different section. The ConfigDefinition can be serialized in the INI file format - /// using the generateINIConfig() function. + /// they exist in a different section. The ConfigDefinition can be serialized in the INI file + /// format using the generateINIConfig() function. /// /// Configured values (e.g. those encountered when parsing a file) can be provided through calls /// to addConfigValue(). These take a std::string as a value, which is automatically parsed. - /// + /// /// The ConfigDefinition can be used to print out a full config string (or file), including fields /// with defaults and optionally fields which have a specified value (values provided through /// calls to addConfigValue()). - struct ConfigDefinition { - + struct ConfigDefinition + { /// Spefify the parameters and type of a configuration option. The parameters are members of /// OptionDefinitionBase; the type is inferred from OptionDefinition's template parameter T. /// @@ -278,7 +280,7 @@ namespace llarp /// Convenience function which calls defineOption with a OptionDefinition of the specified type /// and with parameters passed through to OptionDefinition's constructor. - template + template ConfigDefinition& defineOption(Params&&... args) { @@ -297,9 +299,7 @@ namespace llarp /// @return `*this` for chaining calls /// @throws if the option doesn't exist or the provided string isn't parseable ConfigDefinition& - addConfigValue(string_view section, - string_view name, - string_view value); + addConfigValue(string_view section, string_view name, string_view value); /// Get a config value. If the value hasn't been provided but a default has, the default will /// be returned. If no value and no default is provided, an empty optional will be returned. @@ -312,15 +312,16 @@ namespace llarp /// @return an optional providing the configured value, the default, or empty /// @throws std::invalid_argument if there is no such config option or the wrong type T was // provided - template - nonstd::optional getConfigValue(string_view section, string_view name) + template + nonstd::optional + getConfigValue(string_view section, string_view name) { OptionDefinition_ptr& definition = lookupDefinitionOrThrow(section, name); auto derived = dynamic_cast*>(definition.get()); if (not derived) - throw std::invalid_argument(stringify("", typeid(T).name(), - " is the incorrect type for [", section, "]:", name)); + throw std::invalid_argument( + stringify("", typeid(T).name(), " is the incorrect type for [", section, "]:", name)); return derived->getValue(); } @@ -333,7 +334,7 @@ namespace llarp /// /// @param section is the section for which any undeclared values will invoke the provided /// handler - /// @param handler + /// @param handler /// @throws if there is already a handler for this section void addUndeclaredHandler(const std::string& section, UndeclaredValueHandler handler); @@ -374,9 +375,8 @@ namespace llarp /// @param name /// @param comment void - addOptionComments(const std::string& section, - const std::string& name, - std::vector comments); + addOptionComments( + const std::string& section, const std::string& name, std::vector comments); /// Generate a config string from the current config definition, optionally using overridden /// values. The generated config will preserve insertion order of both sections and their @@ -393,15 +393,18 @@ namespace llarp generateINIConfig(bool useValues = false); private: - - OptionDefinition_ptr& lookupDefinitionOrThrow(string_view section, string_view name); - const OptionDefinition_ptr& lookupDefinitionOrThrow(string_view section, string_view name) const; + OptionDefinition_ptr& + lookupDefinitionOrThrow(string_view section, string_view name); + const OptionDefinition_ptr& + lookupDefinitionOrThrow(string_view section, string_view name) const; using SectionVisitor = std::function; - void visitSections(SectionVisitor visitor) const; + void + visitSections(SectionVisitor visitor) const; using DefVisitor = std::function; - void visitDefinitions(const std::string& section, DefVisitor visitor) const; + void + visitDefinitions(const std::string& section, DefVisitor visitor) const; SectionMap m_definitions; @@ -422,13 +425,11 @@ namespace llarp /// /// Note that this holds on to a reference; it must only be used when this is safe to do. In /// particular, a reference to a local variable may be problematic. - template + template std::function - AssignmentAcceptor(T& ref) { - return [&](T arg) mutable { - ref = std::move(arg); - }; + AssignmentAcceptor(T& ref) + { + return [&](T arg) mutable { ref = std::move(arg); }; } -} // namespace llarp - +} // namespace llarp diff --git a/llarp/config/ini.cpp b/llarp/config/ini.cpp index 42abf02e3..694b6ff3b 100644 --- a/llarp/config/ini.cpp +++ b/llarp/config/ini.cpp @@ -145,8 +145,7 @@ namespace llarp } void - ConfigParser::IterAll( - std::function< void(string_view, const SectionValues_t&) > visit) + ConfigParser::IterAll(std::function visit) { for (const auto& item : m_Config) visit(item.first, item.second); @@ -154,8 +153,7 @@ namespace llarp bool ConfigParser::VisitSection( - const char* name, - std::function< bool(const SectionValues_t& sect) > visit) const + const char* name, std::function visit) const { // m_Config is effectively: // unordered_map< string, unordered_multimap< string, string >> diff --git a/llarp/config/ini.hpp b/llarp/config/ini.hpp index 836bd4c01..28cad23a1 100644 --- a/llarp/config/ini.hpp +++ b/llarp/config/ini.hpp @@ -12,8 +12,8 @@ namespace llarp { struct ConfigParser { - using SectionValues_t = std::unordered_multimap< std::string, std::string >; - using Config_impl_t = std::unordered_map< std::string, SectionValues_t >; + using SectionValues_t = std::unordered_multimap; + using Config_impl_t = std::unordered_map; /// clear parser void Clear(); @@ -32,13 +32,12 @@ namespace llarp /// iterate all sections and thier values void - IterAll(std::function< void(string_view, const SectionValues_t&) > visit); + IterAll(std::function visit); /// visit a section in config read only by name /// return false if no section or value propagated from visitor bool - VisitSection(const char* name, - std::function< bool(const SectionValues_t&) > visit) const; + VisitSection(const char* name, std::function visit) const; private: bool diff --git a/llarp/config/key_manager.cpp b/llarp/config/key_manager.cpp index 91be19e6d..d4f4b2ec9 100644 --- a/llarp/config/key_manager.cpp +++ b/llarp/config/key_manager.cpp @@ -34,9 +34,9 @@ namespace llarp fs::path root = config.router.m_dataDir; // TODO: use fs::path, or at least support windows-style separators - m_rcPath = root / our_rc_filename; - m_idKeyPath = root / our_identity_filename; - m_encKeyPath = root / our_enc_key_filename; + m_rcPath = root / our_rc_filename; + m_idKeyPath = root / our_identity_filename; + m_encKeyPath = root / our_enc_key_filename; m_transportKeyPath = root / our_transport_key_filename; m_usingLokid = config.lokid.whitelistRouters; @@ -183,8 +183,9 @@ namespace llarp bool KeyManager::loadOrCreateKey( - const fs::path& filepath, llarp::SecretKey& key, - std::function< void(llarp::SecretKey& key) > keygen) + const fs::path& filepath, + llarp::SecretKey& key, + std::function keygen) { fs::path path(filepath); std::error_code ec; diff --git a/llarp/config/key_manager.hpp b/llarp/config/key_manager.hpp index 2393ea702..4cbfdee58 100644 --- a/llarp/config/key_manager.hpp +++ b/llarp/config/key_manager.hpp @@ -87,8 +87,10 @@ namespace llarp /// /// @param keygen is a function that will generate the key if needed static bool - loadOrCreateKey(const fs::path& filepath, llarp::SecretKey& key, - std::function< void(llarp::SecretKey& key) > keygen); + loadOrCreateKey( + const fs::path& filepath, + llarp::SecretKey& key, + std::function keygen); /// Requests the identity key from lokid via HTTP (curl) bool diff --git a/llarp/constants/files.hpp b/llarp/constants/files.hpp index 3a5803c5a..292cc8239 100644 --- a/llarp/constants/files.hpp +++ b/llarp/constants/files.hpp @@ -13,8 +13,7 @@ namespace llarp constexpr auto nodedb_dirname = "nodedb"; - inline - fs::path + inline fs::path GetDefaultDataDir() { #ifdef _WIN32 @@ -25,19 +24,16 @@ namespace llarp return homedir / ".lokinet/"; } - inline - fs::path + inline fs::path GetDefaultConfigFilename() { return "lokinet.ini"; } - inline - fs::path + inline fs::path GetDefaultConfigPath() { return GetDefaultDataDir() / GetDefaultConfigFilename(); } } // namespace llarp - diff --git a/llarp/context.cpp b/llarp/context.cpp index 9267a850c..104739df7 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -30,13 +30,11 @@ namespace llarp bool Context::Configure(bool isRelay, nonstd::optional dataDir) { - fs::path defaultDataDir = dataDir.has_value() - ? dataDir.value() - : GetDefaultDataDir(); + fs::path defaultDataDir = dataDir.has_value() ? dataDir.value() : GetDefaultDataDir(); - if(configfile.size()) + if (configfile.size()) { - if(!config->Load(configfile.c_str(), isRelay, defaultDataDir)) + if (!config->Load(configfile.c_str(), isRelay, defaultDataDir)) { config.release(); llarp::LogError("failed to load config file ", configfile); @@ -45,12 +43,11 @@ namespace llarp } auto threads = config->router.m_workerThreads; - if(threads <= 0) + if (threads <= 0) threads = 1; - worker = std::make_shared< llarp::thread::ThreadPool >(threads, 1024, - "llarp-worker"); + worker = std::make_shared(threads, 1024, "llarp-worker"); auto jobQueueSize = config->router.m_JobQueueSize; - if(jobQueueSize < 1024) + if (jobQueueSize < 1024) jobQueueSize = 1024; logic = std::make_shared(jobQueueSize); @@ -214,7 +211,7 @@ namespace llarp } bool - Context::LoadConfig(const std::string &fname, bool isRelay) + Context::LoadConfig(const std::string& fname, bool isRelay) { config = std::make_unique(); configfile = fname; @@ -281,23 +278,23 @@ extern "C" delete conf; } - struct llarp_main * - llarp_main_init_from_config(struct llarp_config *conf, bool isRelay) + struct llarp_main* + llarp_main_init_from_config(struct llarp_config* conf, bool isRelay) { if (conf == nullptr) return nullptr; - llarp_main *m = new llarp_main(conf); - if(m->ctx->Configure(isRelay, {})) + llarp_main* m = new llarp_main(conf); + if (m->ctx->Configure(isRelay, {})) return m; delete m; return nullptr; } bool - llarp_config_load_file(const char *fname, struct llarp_config **conf, bool isRelay) + llarp_config_load_file(const char* fname, struct llarp_config** conf, bool isRelay) { - llarp_config *c = new llarp_config(); - if(c->impl.Load(fname, isRelay, {})) + llarp_config* c = new llarp_config(); + if (c->impl.Load(fname, isRelay, {})) { *conf = c; return true; @@ -434,7 +431,7 @@ extern "C" } bool - llarp_main_configure(struct llarp_main *ptr, struct llarp_config *conf, bool isRelay) + llarp_main_configure(struct llarp_main* ptr, struct llarp_config* conf, bool isRelay) { if (ptr == nullptr || conf == nullptr) return false; diff --git a/llarp/nodedb.cpp b/llarp/nodedb.cpp index 14c970074..dcc749ff5 100644 --- a/llarp/nodedb.cpp +++ b/llarp/nodedb.cpp @@ -467,7 +467,7 @@ llarp_nodedb::ensure_dir(const fs::path& nodedbDir) // perhaps cpp17::fs is just as screwed-up // attempting to create a folder with no name // what does this mean...? - if(!ch) + if (!ch) continue; fs::path sub = nodedbDir / std::string(&ch, 1); diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index f645cf868..9e7cc22d8 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -373,17 +373,18 @@ namespace llarp Router::FromConfig(Config* conf) { // Set netid before anything else - if(!conf->router.m_netId.empty() - && strcmp(conf->router.m_netId.c_str(), llarp::DEFAULT_NETID)) + if (!conf->router.m_netId.empty() && strcmp(conf->router.m_netId.c_str(), llarp::DEFAULT_NETID)) { - const auto &netid = conf->router.m_netId; - llarp::LogWarn("!!!! you have manually set netid to be '", netid, - "' which does not equal '", llarp::DEFAULT_NETID, - "' you will run as a different network, good luck " - "and don't forget: something something MUH traffic " - "shape correlation !!!!"); - NetID::DefaultValue() = - NetID(reinterpret_cast< const byte_t * >(netid.c_str())); + const auto& netid = conf->router.m_netId; + llarp::LogWarn( + "!!!! you have manually set netid to be '", + netid, + "' which does not equal '", + llarp::DEFAULT_NETID, + "' you will run as a different network, good luck " + "and don't forget: something something MUH traffic " + "shape correlation !!!!"); + NetID::DefaultValue() = NetID(reinterpret_cast(netid.c_str())); // reset netid in our rc _rc.netID = llarp::NetID(); } @@ -392,16 +393,14 @@ namespace llarp m_OutboundPort = conf->links.m_OutboundLink.port; // Router config _rc.SetNick(conf->router.m_nickname); - _outboundSessionMaker.maxConnectedRouters = - conf->router.m_maxConnectedRouters; - _outboundSessionMaker.minConnectedRouters = - conf->router.m_minConnectedRouters; + _outboundSessionMaker.maxConnectedRouters = conf->router.m_maxConnectedRouters; + _outboundSessionMaker.minConnectedRouters = conf->router.m_minConnectedRouters; encryption_keyfile = conf->router.m_dataDir / our_enc_key_filename; - our_rc_file = conf->router.m_dataDir / our_rc_filename; - transport_keyfile = conf->router.m_dataDir / our_transport_key_filename; - addrInfo = conf->router.m_addrInfo; - publicOverride = conf->router.m_publicOverride; - ip4addr = conf->router.m_ip4addr; + our_rc_file = conf->router.m_dataDir / our_rc_filename; + transport_keyfile = conf->router.m_dataDir / our_transport_key_filename; + addrInfo = conf->router.m_addrInfo; + publicOverride = conf->router.m_publicOverride; + ip4addr = conf->router.m_ip4addr; RouterContact::BlockBogons = conf->router.m_blockBogons; @@ -414,17 +413,17 @@ namespace llarp lokidRPCPassword = conf->lokid.lokidRPCPassword; // TODO: add config flag for "is service node" - if(conf->links.m_InboundLinks.size()) + if (conf->links.m_InboundLinks.size()) { m_isServiceNode = true; } std::set strictConnectPubkeys; - if(!conf->network.m_strictConnect.empty()) + if (!conf->network.m_strictConnect.empty()) { - const auto &val = conf->network.m_strictConnect; - if(IsServiceNode()) + const auto& val = conf->network.m_strictConnect; + if (IsServiceNode()) { llarp::LogError("cannot use strict-connect option as service node"); return false; @@ -453,8 +452,8 @@ namespace llarp } std::vector configRouters = conf->connect.routers; - configRouters.insert(configRouters.end(), conf->bootstrap.routers.begin(), - conf->bootstrap.routers.end()); + configRouters.insert( + configRouters.end(), conf->bootstrap.routers.begin(), conf->bootstrap.routers.end()); // if our conf had no bootstrap files specified, try the default location of // /bootstrap.signed. If this isn't present, leave a useful error message @@ -479,7 +478,7 @@ namespace llarp bool isListFile = false; { std::ifstream inf(router.c_str(), std::ios::binary); - if(inf.is_open()) + if (inf.is_open()) { const char ch = inf.get(); isListFile = ch == 'l'; @@ -539,10 +538,11 @@ namespace llarp } // create inbound links, if we are a service node - for(const LinksConfig::LinkInfo &serverConfig : conf->links.m_InboundLinks) + for (const LinksConfig::LinkInfo& serverConfig : conf->links.m_InboundLinks) { auto server = iwp::NewInboundLink( - m_keyManager, util::memFn(&AbstractRouter::rc, this), + m_keyManager, + util::memFn(&AbstractRouter::rc, this), util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this), util::memFn(&AbstractRouter::Sign, this), util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker), @@ -554,7 +554,7 @@ namespace llarp const std::string& key = serverConfig.interface; int af = serverConfig.addressFamily; uint16_t port = serverConfig.port; - if(!server->Configure(netloop(), key, af, port)) + if (!server->Configure(netloop(), key, af, port)) { LogError("failed to bind inbound link on ", key, " port ", port); return false; @@ -563,16 +563,16 @@ namespace llarp } // Network config - if(conf->network.m_enableProfiling.has_value()) + if (conf->network.m_enableProfiling.has_value()) { - if(not conf->network.m_enableProfiling.value()) + if (not conf->network.m_enableProfiling.value()) { routerProfiling().Disable(); LogWarn("router profiling explicitly disabled"); } } - if(!conf->network.m_routerProfilesFile.empty()) + if (!conf->network.m_routerProfilesFile.empty()) { routerProfilesFile = conf->network.m_routerProfilesFile; routerProfiling().Load(routerProfilesFile.c_str()); @@ -581,7 +581,7 @@ namespace llarp // API config enableRPCServer = conf->api.m_enableRPCServer; - rpcBindAddr = conf->api.m_rpcBindAddr; + rpcBindAddr = conf->api.m_rpcBindAddr; // Services config for (const auto& service : conf->services.services) @@ -1228,15 +1228,13 @@ namespace llarp util::memFn(&AbstractRouter::rc, this), util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this), util::memFn(&AbstractRouter::Sign, this), - util::memFn(&IOutboundSessionMaker::OnSessionEstablished, - &_outboundSessionMaker), + util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker), util::memFn(&AbstractRouter::CheckRenegotiateValid, this), - util::memFn(&IOutboundSessionMaker::OnConnectTimeout, - &_outboundSessionMaker), + util::memFn(&IOutboundSessionMaker::OnConnectTimeout, &_outboundSessionMaker), util::memFn(&AbstractRouter::SessionClosed, this), util::memFn(&AbstractRouter::PumpLL, this)); - if(!link) + if (!link) return false; const auto afs = {AF_INET, AF_INET6}; diff --git a/llarp/service/config.cpp b/llarp/service/config.cpp index 2c6750fbd..7df8ce1f6 100644 --- a/llarp/service/config.cpp +++ b/llarp/service/config.cpp @@ -12,14 +12,13 @@ namespace llarp ConfigParser parser; if (!parser.LoadFile(fname)) return false; - parser.IterAll( - [&](string_view name, const ConfigParser::SectionValues_t& section) { - Config::section_t values; - values.first.assign(name.begin(), name.end()); - for(const auto& item : section) - values.second.emplace_back(item.first, item.second); - services.emplace_back(values); - }); + parser.IterAll([&](string_view name, const ConfigParser::SectionValues_t& section) { + Config::section_t values; + values.first.assign(name.begin(), name.end()); + for (const auto& item : section) + values.second.emplace_back(item.first, item.second); + services.emplace_back(values); + }); return services.size() > 0; } diff --git a/llarp/util/logging/file_logger.hpp b/llarp/util/logging/file_logger.hpp index 86c43817e..43dd51e36 100644 --- a/llarp/util/logging/file_logger.hpp +++ b/llarp/util/logging/file_logger.hpp @@ -50,7 +50,7 @@ namespace llarp virtual void ImmediateFlush() override; - using Lines_t = thread::Queue< std::string >; + using Lines_t = thread::Queue; protected: Lines_t m_Lines; diff --git a/llarp/util/logging/logger.cpp b/llarp/util/logging/logger.cpp index 6ad0d1bec..f516ef6a5 100644 --- a/llarp/util/logging/logger.cpp +++ b/llarp/util/logging/logger.cpp @@ -33,10 +33,14 @@ namespace llarp LogType LogTypeFromString(const std::string& str) { - if (str == "unknown") return LogType::Unknown; - else if (str == "file") return LogType::File; - else if (str == "json") return LogType::Json; - else if (str == "syslog") return LogType::Syslog; + if (str == "unknown") + return LogType::Unknown; + else if (str == "file") + return LogType::File; + else if (str == "json") + return LogType::Json; + else if (str == "syslog") + return LogType::Syslog; return LogType::Unknown; } @@ -93,11 +97,12 @@ namespace llarp } void - LogContext::Initialize(LogLevel level, - LogType type, - const std::string& file, - const std::string& nickname, - std::shared_ptr threadpool) + LogContext::Initialize( + LogLevel level, + LogType type, + const std::string& file, + const std::string& nickname, + std::shared_ptr threadpool) { SetLogLevel(level); nodeName = nickname; @@ -112,8 +117,8 @@ namespace llarp logfile = ::fopen(file.c_str(), "a"); if (not logfile) { - throw std::runtime_error(stringify( - "could not open logfile ", file, ", errno: ", strerror(errno))); + throw std::runtime_error( + stringify("could not open logfile ", file, ", errno: ", strerror(errno))); } } @@ -129,7 +134,7 @@ namespace llarp std::cout << std::flush; LogContext::Instance().logStream = - std::make_unique< FileLogStream >(threadpool, logfile, 100ms, true); + std::make_unique(threadpool, logfile, 100ms, true); } else { @@ -141,8 +146,8 @@ namespace llarp LogInfo("Switching logger to JSON with file: ", file); std::cout << std::flush; - LogContext::Instance().logStream = std::make_unique< JSONLogStream >( - threadpool, logfile, 100ms, logfile != stdout); + LogContext::Instance().logStream = + std::make_unique(threadpool, logfile, 100ms, logfile != stdout); break; case LogType::Syslog: if (logfile) @@ -157,10 +162,9 @@ namespace llarp #else LogInfo("Switching logger to syslog"); std::cout << std::flush; - LogContext::Instance().logStream = std::make_unique< SysLogStream >(); + LogContext::Instance().logStream = std::make_unique(); #endif break; - } } diff --git a/llarp/util/logging/logger.hpp b/llarp/util/logging/logger.hpp index d81ab70a8..394a25738 100644 --- a/llarp/util/logging/logger.hpp +++ b/llarp/util/logging/logger.hpp @@ -16,7 +16,8 @@ namespace llarp Json, Syslog, }; - LogType LogTypeFromString(const std::string&); + LogType + LogTypeFromString(const std::string&); struct LogContext { @@ -51,11 +52,12 @@ namespace llarp /// @param nickname is a tag to add to each log statement /// @param threadpool is a threadpool where I/O can offloaded void - Initialize(LogLevel level, - LogType type, - const std::string& file, - const std::string& nickname, - std::shared_ptr threadpool); + Initialize( + LogLevel level, + LogType type, + const std::string& file, + const std::string& nickname, + std::shared_ptr threadpool); }; void diff --git a/llarp/util/str.cpp b/llarp/util/str.cpp index 08c6db548..83462ff06 100644 --- a/llarp/util/str.cpp +++ b/llarp/util/str.cpp @@ -91,7 +91,7 @@ namespace llarp next = str.find_first_of(delimiter, last); if (next > last) { - splits.push_back(str.substr(last, next-last)); + splits.push_back(str.substr(last, next - last)); last = next; @@ -103,7 +103,6 @@ namespace llarp { break; } - } return splits; diff --git a/llarp/util/str.hpp b/llarp/util/str.hpp index 13540b017..6677ec3cf 100644 --- a/llarp/util/str.hpp +++ b/llarp/util/str.hpp @@ -30,14 +30,15 @@ namespace llarp string_view TrimWhitespace(string_view str); - template - std::string stringify(T&&... stuff) + template + std::string + stringify(T&&... stuff) { std::ostringstream o; -#ifdef __cpp_fold_expressions +#ifdef __cpp_fold_expressions (o << ... << std::forward(stuff)); #else - (void) std::initializer_list{(o << std::forward(stuff), 0)...}; + (void)std::initializer_list{(o << std::forward(stuff), 0)...}; #endif return o.str(); }