Re-apply clang-format rules after rebasing

pull/1186/head
Stephen Shelton 4 years ago
parent 3a1c727b9b
commit de8e44ba21
No known key found for this signature in database
GPG Key ID: EE4BADACCE8B631C

@ -36,18 +36,18 @@ namespace
int
main(int argc, char* argv[])
{
cxxopts::Options options("lokinetctl",
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<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");
try
{
@ -80,7 +80,6 @@ main(int argc, char* argv[])
return 1;
}
}
}
catch (const cxxopts::OptionParseException& ex)
{

@ -103,18 +103,17 @@ main(int argc, char* argv[])
SetConsoleCtrlHandler(handle_signal_win32, TRUE);
// SetUnhandledExceptionFilter(win32_signal_handler);
#endif
cxxopts::Options options("lokinet",
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"))(
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"))(
"b,background",
"background mode (start, but do not connect to the network)",
cxxopts::value<bool>())(
@ -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<std::string>();
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();
}

@ -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

@ -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<std::promise<void>> closeWaiter;
};
} // namespace llarp

@ -20,7 +20,6 @@
namespace llarp
{
// constants for config file default values
constexpr int DefaultMinConnectionsForRouter = 6;
constexpr int DefaultMaxConnectionsForRouter = 60;
@ -38,64 +37,56 @@ namespace llarp
constexpr int DefaultNetThreads = 1;
constexpr bool DefaultBlockBogons = true;
conf.defineOption<int>("router", "job-queue-size", false, DefaultJobQueueSize,
[this](int arg) {
conf.defineOption<int>("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<std::string>("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()));
conf.defineOption<std::string>("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_netId = std::move(arg);
});
int minConnections = (params.isRelay ? DefaultMinConnectionsForRouter
: DefaultMinConnectionsForClient);
conf.defineOption<int>("router", "min-connections", false, minConnections,
[=](int arg) {
int minConnections =
(params.isRelay ? DefaultMinConnectionsForRouter : DefaultMinConnectionsForClient);
conf.defineOption<int>("router", "min-connections", false, minConnections, [=](int arg) {
if (arg < minConnections)
throw std::invalid_argument(stringify("min-connections must be >= ", minConnections));
m_minConnectedRouters = arg;
});
int maxConnections = (params.isRelay ? DefaultMaxConnectionsForRouter
: DefaultMaxConnectionsForClient);
conf.defineOption<int>("router", "max-connections", false, maxConnections,
[=](int arg) {
int maxConnections =
(params.isRelay ? DefaultMaxConnectionsForRouter : DefaultMaxConnectionsForClient);
conf.defineOption<int>("router", "max-connections", false, maxConnections, [=](int arg) {
if (arg < maxConnections)
throw std::invalid_argument(stringify("max-connections must be >= ", maxConnections));
m_maxConnectedRouters = arg;
});
conf.defineOption<std::string>("router", "nickname", false, "",
AssignmentAcceptor(m_nickname));
conf.defineOption<std::string>("router", "nickname", false, "", AssignmentAcceptor(m_nickname));
conf.defineOption<std::string>("router", "data-dir", false, GetDefaultDataDir(),
[this](std::string arg) {
conf.defineOption<std::string>(
"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"));
throw std::runtime_error(
stringify("Specified [router]:data-dir ", arg, " does not exist"));
m_dataDir = std::move(dir);
});
conf.defineOption<std::string>("router", "public-address", false, "",
[this](std::string arg) {
conf.defineOption<std::string>("router", "public-address", false, "", [this](std::string arg) {
if (not arg.empty())
{
llarp::LogInfo("public ip ", arg, " size ", arg.size());
if(arg.size() > 16)
if (arg.size() > 16)
throw std::invalid_argument(stringify("Not a valid IPv4 addr: ", arg));
// assume IPv4
@ -106,8 +97,7 @@ namespace llarp
}
});
conf.defineOption<int>("router", "public-port", false, DefaultPublicPort,
[this](int arg) {
conf.defineOption<int>("router", "public-port", false, DefaultPublicPort, [this](int arg) {
if (arg <= 0)
throw std::invalid_argument("public-port must be > 0");
@ -117,24 +107,23 @@ namespace llarp
m_publicOverride = true;
});
conf.defineOption<int>("router", "worker-threads", false, DefaultWorkerThreads,
[this](int arg) {
conf.defineOption<int>(
"router", "worker-threads", false, DefaultWorkerThreads, [this](int arg) {
if (arg <= 0)
throw std::invalid_argument("worker-threads must be > 0");
m_workerThreads = arg;
});
conf.defineOption<int>("router", "net-threads", false, DefaultNetThreads,
[this](int arg) {
conf.defineOption<int>("router", "net-threads", false, DefaultNetThreads, [this](int arg) {
if (arg <= 0)
throw std::invalid_argument("net-threads must be > 0");
m_numNetThreads = arg;
});
conf.defineOption<bool>("router", "block-bogons", false, DefaultBlockBogons,
AssignmentAcceptor(m_blockBogons));
conf.defineOption<bool>(
"router", "block-bogons", false, DefaultBlockBogons, AssignmentAcceptor(m_blockBogons));
}
void
@ -144,15 +133,23 @@ namespace llarp
constexpr bool DefaultProfilingValue = true;
conf.defineOption<bool>("network", "profiling", false, DefaultProfilingValue,
conf.defineOption<bool>(
"network",
"profiling",
false,
DefaultProfilingValue,
AssignmentAcceptor(m_enableProfiling));
// TODO: this should be implied from [router]:data-dir
conf.defineOption<std::string>("network", "profiles", false, m_routerProfilesFile,
conf.defineOption<std::string>(
"network",
"profiles",
false,
m_routerProfilesFile,
AssignmentAcceptor(m_routerProfilesFile));
conf.defineOption<std::string>("network", "strict-connect", false, "",
AssignmentAcceptor(m_strictConnect));
conf.defineOption<std::string>(
"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,14 +165,14 @@ namespace llarp
// TODO: make sure this is documented
// TODO: refactor to remove freehand options map
conf.defineOption<std::string>("network", "upstream-dns", false, true, "",
[this](std::string arg) {
conf.defineOption<std::string>(
"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<std::string>("network", "local-dns", false, true, "",
[this](std::string arg) {
conf.defineOption<std::string>(
"network", "local-dns", false, true, "", [this](std::string arg) {
m_options.emplace("local-dns", std::move(arg));
});
}
@ -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,15 +227,18 @@ namespace llarp
{
(void)params;
conf.addUndeclaredHandler("connect", [this](string_view section,
string_view name,
string_view value) {
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"));
"Specified bootstrap file ",
value,
"specified in [",
section,
"]:",
name,
" does not exist"));
routers.emplace_back(std::move(file));
return true;
@ -251,9 +250,8 @@ namespace llarp
{
(void)params;
conf.addUndeclaredHandler("services", [this](string_view section,
string_view name,
string_view value) {
conf.addUndeclaredHandler(
"services", [this](string_view section, string_view name, string_view value) {
(void)section;
services.emplace_back(name, value);
return true;
@ -268,11 +266,11 @@ namespace llarp
constexpr bool DefaultRPCEnabled = true;
constexpr auto DefaultRPCBindAddr = "127.0.0.1:1190";
conf.defineOption<bool>("api", "enabled", false, DefaultRPCEnabled,
AssignmentAcceptor(m_enableRPCServer));
conf.defineOption<bool>(
"api", "enabled", false, DefaultRPCEnabled, AssignmentAcceptor(m_enableRPCServer));
conf.defineOption<std::string>("api", "bind", false, DefaultRPCBindAddr,
AssignmentAcceptor(m_rpcBindAddr));
conf.defineOption<std::string>(
"api", "bind", false, DefaultRPCBindAddr, AssignmentAcceptor(m_rpcBindAddr));
// TODO: this was from pre-refactor:
// TODO: add pubkey to whitelist
@ -286,8 +284,8 @@ namespace llarp
constexpr bool DefaultWhitelistRouters = false;
constexpr auto DefaultLokidRPCAddr = "127.0.0.1:22023";
conf.defineOption<std::string>("lokid", "service-node-seed", false, our_identity_filename,
[this](std::string arg) {
conf.defineOption<std::string>(
"lokid", "service-node-seed", false, our_identity_filename, [this](std::string arg) {
if (not arg.empty())
{
usingSNSeed = true;
@ -295,17 +293,17 @@ namespace llarp
}
});
conf.defineOption<bool>("lokid", "enabled", false, DefaultWhitelistRouters,
AssignmentAcceptor(whitelistRouters));
conf.defineOption<bool>(
"lokid", "enabled", false, DefaultWhitelistRouters, AssignmentAcceptor(whitelistRouters));
conf.defineOption<std::string>("lokid", "jsonrpc", false, DefaultLokidRPCAddr,
AssignmentAcceptor(lokidRPCAddr));
conf.defineOption<std::string>(
"lokid", "jsonrpc", false, DefaultLokidRPCAddr, AssignmentAcceptor(lokidRPCAddr));
conf.defineOption<std::string>("lokid", "username", false, "",
AssignmentAcceptor(lokidRPCUser));
conf.defineOption<std::string>(
"lokid", "username", false, "", AssignmentAcceptor(lokidRPCUser));
conf.defineOption<std::string>("lokid", "password", false, "",
AssignmentAcceptor(lokidRPCPassword));
conf.defineOption<std::string>(
"lokid", "password", false, "", AssignmentAcceptor(lokidRPCPassword));
}
void
@ -313,8 +311,8 @@ namespace llarp
{
(void)params;
conf.defineOption<std::string>("bootstrap", "add-node", false, true, "",
[this](std::string arg) {
conf.defineOption<std::string>(
"bootstrap", "add-node", false, true, "", [this](std::string arg) {
// TODO: validate as router fs path
routers.emplace_back(std::move(arg));
});
@ -329,8 +327,8 @@ namespace llarp
constexpr auto DefaultLogFile = "stdout";
constexpr auto DefaultLogLevel = "info";
conf.defineOption<std::string>("logging", "type", false, DefaultLogType,
[this](std::string arg) {
conf.defineOption<std::string>(
"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));
@ -338,17 +336,17 @@ namespace llarp
m_logType = type;
});
conf.defineOption<std::string>("logging", "level", false, DefaultLogLevel,
[this](std::string arg) {
conf.defineOption<std::string>(
"logging", "level", false, DefaultLogLevel, [this](std::string arg) {
nonstd::optional<LogLevel> level = LogLevelFromString(arg);
if (not level.has_value())
throw std::invalid_argument(stringify( "invalid log level value: ", arg));
throw std::invalid_argument(stringify("invalid log level value: ", arg));
m_logLevel = level.value();
});
conf.defineOption<std::string>("logging", "file", false, DefaultLogFile,
AssignmentAcceptor(m_logFile));
conf.defineOption<std::string>(
"logging", "file", false, DefaultLogFile, AssignmentAcceptor(m_logFile));
}
void
@ -360,47 +358,40 @@ namespace llarp
static constexpr int HopsDefault = 4;
static constexpr int PathsDefault = 6;
conf.defineOption<std::string>("snapp", "keyfile", false, "",
[this](std::string arg) {
conf.defineOption<std::string>("snapp", "keyfile", false, "", [this](std::string arg) {
// TODO: validate as valid .loki / .snode address
m_keyfile = arg;
});
conf.defineOption<bool>("snapp", "reachable", false, ReachableDefault,
AssignmentAcceptor(m_reachable));
conf.defineOption<bool>(
"snapp", "reachable", false, ReachableDefault, AssignmentAcceptor(m_reachable));
conf.defineOption<int>("snapp", "hops", false, HopsDefault,
[this](int arg) {
conf.defineOption<int>("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<int>("snapp", "paths", false, PathsDefault,
[this](int arg) {
conf.defineOption<int>("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<std::string>("snapp", "exit-node", false, "",
[this](std::string arg) {
conf.defineOption<std::string>("snapp", "exit-node", false, "", [this](std::string arg) {
// TODO: validate as valid .loki / .snode address
m_exitNode = arg;
});
conf.defineOption<std::string>("snapp", "local-dns", false, "",
[this](std::string arg) {
conf.defineOption<std::string>("snapp", "local-dns", false, "", [this](std::string arg) {
// TODO: validate as IP address
m_localDNS = arg;
});
conf.defineOption<std::string>("snapp", "upstream-dns", false, "",
[this](std::string arg) {
conf.defineOption<std::string>("snapp", "upstream-dns", false, "", [this](std::string arg) {
// TODO: validate as IP address
m_upstreamDNS = arg;
});
conf.defineOption<std::string>("snapp", "mapaddr", false, "",
[this](std::string arg) {
conf.defineOption<std::string>("snapp", "mapaddr", false, "", [this](std::string arg) {
// TODO: parse / validate as loki_addr : IP addr pair
m_mapAddr = arg;
});
@ -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,42 +517,58 @@ namespace llarp
void
generateCommonConfigComments(ConfigDefinition& def)
{
// router
def.addSectionComments("router", {
def.addSectionComments(
"router",
{
"Configuration for routing activity.",
});
def.addOptionComments("router", "threads", {
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", {
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", {
def.addOptionComments(
"router",
"min-connections",
{
"Minimum number of routers lokinet will attempt to maintain connections to.",
});
def.addOptionComments("router", "max-connections", {
def.addOptionComments(
"router",
"max-connections",
{
"Maximum number (hard limit) of routers lokinet will be connected to at any time.",
});
// logging
def.addSectionComments("logging", {
def.addSectionComments(
"logging",
{
"logging settings",
});
def.addOptionComments("logging", "level", {
def.addOptionComments(
"logging",
"level",
{
"Minimum log level to print. Logging below this level will be ignored.",
"Valid log levels, in ascending order, are:",
" trace",
@ -573,7 +578,10 @@ namespace llarp
" error",
});
def.addOptionComments("logging", "type", {
def.addOptionComments(
"logging",
"type",
{
"Log type (format). Valid options are:",
" file - plaintext formatting",
" json - json-formatted log statements",
@ -581,68 +589,106 @@ namespace llarp
});
// api
def.addSectionComments("api", {
def.addSectionComments(
"api",
{
"JSON API settings",
});
def.addOptionComments("api", "enabled", {
def.addOptionComments(
"api",
"enabled",
{
"Determines whether or not the JSON API is enabled.",
});
def.addOptionComments("api", "bind", {
def.addOptionComments(
"api",
"bind",
{
"IP address and port to bind to.",
"Recommend localhost-only for security purposes.",
});
// dns
def.addSectionComments("dns", {
def.addSectionComments(
"dns",
{
"DNS configuration",
});
def.addOptionComments("dns", "upstream", {
def.addOptionComments(
"dns",
"upstream",
{
"Upstream resolver to use as fallback for non-loki addresses.",
"Multiple values accepted.",
});
def.addOptionComments("dns", "bind", {
def.addOptionComments(
"dns",
"bind",
{
"Address to bind to for handling DNS requests.",
"Multiple values accepted.",
});
// bootstrap
def.addSectionComments("bootstrap", {
def.addSectionComments(
"bootstrap",
{
"Configure nodes that will bootstrap us onto the network",
});
def.addOptionComments("bootstrap", "add-node", {
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", {
def.addSectionComments(
"network",
{
"Network settings",
});
def.addOptionComments("network", "profiles", {
def.addOptionComments(
"network",
"profiles",
{
"File to contain router profiles.",
});
def.addOptionComments("network", "strict-connect", {
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", {
def.addOptionComments(
"network",
"exit-node",
{
"Public key of an exit-node.",
});
def.addOptionComments("network", "ifname", {
def.addOptionComments(
"network",
"ifname",
{
"Interface name for lokinet traffic.",
});
def.addOptionComments("network", "ifaddr", {
def.addOptionComments(
"network",
"ifaddr",
{
"Local IP address for lokinet traffic.",
});
}
@ -659,49 +705,78 @@ namespace llarp
generateCommonConfigComments(def);
// snapp
def.addSectionComments("snapp", {
def.addSectionComments(
"snapp",
{
"Snapp settings",
});
def.addOptionComments("snapp", "keyfile", {
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", {
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", {
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", {
def.addOptionComments(
"snapp",
"paths",
{
"Number of paths to maintain at any given time.",
});
def.addOptionComments("snapp", "blacklist-snode", {
def.addOptionComments(
"snapp",
"blacklist-snode",
{
"Adds a `.snode` address to the blacklist.",
});
def.addOptionComments("snapp", "exit-node", {
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", {
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", {
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", {
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`.",
});
@ -721,38 +796,58 @@ namespace llarp
generateCommonConfigComments(def);
// lokid
def.addSectionComments("lokid", {
def.addSectionComments(
"lokid",
{
"Lokid configuration (settings for talking to lokid",
});
def.addOptionComments("lokid", "enabled", {
def.addOptionComments(
"lokid",
"enabled",
{
"Whether or not we should talk to lokid. Must be enabled for staked routers.",
});
def.addOptionComments("lokid", "jsonrpc", {
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", {
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", {
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", {
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", {
def.addOptionComments(
"network",
"exit-blacklist",
{
"Blacklist of destinations (same format as whitelist).",
});
@ -760,4 +855,3 @@ namespace llarp
}
} // namespace llarp

@ -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<std::string, std::string>;
/// 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<bool> 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<std::pair<std::string, std::string>> services;
void
defineConfigOptions(ConfigDefinition& conf, const ConfigGenParameters& params);
};
@ -135,7 +135,7 @@ namespace llarp
struct BootstrapConfig
{
std::vector< std::string > routers;
std::vector<std::string> 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

@ -5,47 +5,38 @@
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)
{
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"));
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);
return *this;
}
}
ConfigDefinition&
ConfigDefinition::addConfigValue(string_view section, string_view name, string_view value)
{
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())
{
@ -71,83 +62,77 @@ ConfigDefinition::addConfigValue(string_view section, string_view name, string_v
definition->parseValue(std::string(value));
return *this;
}
}
void
ConfigDefinition::addUndeclaredHandler(const std::string& section, UndeclaredValueHandler 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"));
m_undeclaredHandlers[section] = std::move(handler);
}
}
void
ConfigDefinition::removeUndeclaredHandler(const std::string& section)
{
void
ConfigDefinition::removeUndeclaredHandler(const std::string& section)
{
auto itr = m_undeclaredHandlers.find(section);
if (itr != m_undeclaredHandlers.end())
m_undeclaredHandlers.erase(itr);
}
}
void
ConfigDefinition::validateRequiredFields()
{
visitSections([&](const std::string& section, const DefinitionMap&)
{
visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def)
void
ConfigDefinition::validateRequiredFields()
{
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"));
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::acceptAllOptions()
{
visitSections([&](const std::string& section, const DefinitionMap&)
{
visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def)
void
ConfigDefinition::acceptAllOptions()
{
def->tryAccept();
});
visitSections([&](const std::string& section, const DefinitionMap&) {
visitDefinitions(
section, [&](const std::string&, const OptionDefinition_ptr& def) { def->tryAccept(); });
});
}
}
void
ConfigDefinition::addSectionComments(const std::string& section,
std::vector<std::string> comments)
{
void
ConfigDefinition::addSectionComments(
const std::string& section, std::vector<std::string> comments)
{
auto& sectionComments = m_sectionComments[section];
for (size_t i=0; i<comments.size(); ++i)
for (size_t i = 0; i < comments.size(); ++i)
{
sectionComments.emplace_back(std::move(comments[i]));
}
}
}
void
ConfigDefinition::addOptionComments(const std::string& section,
const std::string& name,
std::vector<std::string> comments)
{
void
ConfigDefinition::addOptionComments(
const std::string& section, const std::string& name, std::vector<std::string> comments)
{
auto& defComments = m_definitionComments[section][name];
for (size_t i=0; i<comments.size(); ++i)
for (size_t i = 0; i < comments.size(); ++i)
{
defComments.emplace_back(std::move(comments[i]));
}
}
}
std::string
ConfigDefinition::generateINIConfig(bool useValues)
{
std::string
ConfigDefinition::generateINIConfig(bool useValues)
{
std::ostringstream oss;
int sectionsVisited = 0;
@ -186,18 +171,17 @@ ConfigDefinition::generateINIConfig(bool useValues)
oss << "#";
oss << name << "=" << def->defaultValueAsString() << "\n";
}
});
sectionsVisited++;
});
return oss.str();
}
}
const OptionDefinition_ptr&
ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) const
{
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, "]"));
@ -208,26 +192,28 @@ ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name)
throw std::invalid_argument(stringify("No config item ", name, " within section ", section));
return definitionItr->second;
}
}
OptionDefinition_ptr&
ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name)
{
OptionDefinition_ptr&
ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name)
{
return const_cast<OptionDefinition_ptr&>(
const_cast<const ConfigDefinition*>(this)->lookupDefinitionOrThrow(section, name));
}
}
void ConfigDefinition::visitSections(SectionVisitor visitor) const
{
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
{
};
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)
@ -236,7 +222,6 @@ void ConfigDefinition::visitDefinitions(const std::string& section, DefVisitor v
assert(itr != defs.end());
visitor(name, itr->second);
}
};
};
} // namespace llarp

@ -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
{
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;
@ -72,8 +69,9 @@ namespace llarp
/// 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<typename T>
/// ConfigDefinition::getConfigValue(). Similar types such as uint32_t and int32_t cannot be
/// mixed.
template <typename T>
struct OptionDefinition : public OptionDefinitionBase
{
/// Constructor. Arguments are passed directly to OptionDefinitionBase.
@ -86,7 +84,8 @@ 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_,
OptionDefinition(
std::string section_,
std::string name_,
bool required_,
nonstd::optional<T> defaultValue_,
@ -98,7 +97,8 @@ namespace llarp
}
/// As above, but also takes a bool value for multiValued.
OptionDefinition(std::string section_,
OptionDefinition(
std::string section_,
std::string name_,
bool required_,
bool multiValued_,
@ -134,8 +134,8 @@ namespace llarp
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,8 +164,8 @@ 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);
@ -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
@ -236,9 +239,8 @@ namespace llarp
std::function<void(T)> acceptor;
};
using UndeclaredValueHandler
= std::function<void(string_view section, string_view name, string_view value)>;
using UndeclaredValueHandler =
std::function<void(string_view section, string_view name, string_view value)>;
using OptionDefinition_ptr = std::unique_ptr<OptionDefinitionBase>;
@ -253,8 +255,8 @@ 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.
@ -262,8 +264,8 @@ namespace llarp
/// 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<typename T, typename... Params>
template <typename T, typename... Params>
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<typename T>
nonstd::optional<T> getConfigValue(string_view section, string_view name)
template <typename T>
nonstd::optional<T>
getConfigValue(string_view section, string_view name)
{
OptionDefinition_ptr& definition = lookupDefinitionOrThrow(section, name);
auto derived = dynamic_cast<const OptionDefinition<T>*>(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();
}
@ -374,9 +375,8 @@ namespace llarp
/// @param name
/// @param comment
void
addOptionComments(const std::string& section,
const std::string& name,
std::vector<std::string> comments);
addOptionComments(
const std::string& section, const std::string& name, std::vector<std::string> 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(const std::string&, const DefinitionMap&)>;
void visitSections(SectionVisitor visitor) const;
void
visitSections(SectionVisitor visitor) const;
using DefVisitor = std::function<void(const std::string&, const OptionDefinition_ptr&)>;
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<typename T>
template <typename T>
std::function<void(T)>
AssignmentAcceptor(T& ref) {
return [&](T arg) mutable {
ref = std::move(arg);
};
AssignmentAcceptor(T& ref)
{
return [&](T arg) mutable { ref = std::move(arg); };
}
} // namespace llarp

@ -145,8 +145,7 @@ namespace llarp
}
void
ConfigParser::IterAll(
std::function< void(string_view, const SectionValues_t&) > visit)
ConfigParser::IterAll(std::function<void(string_view, const SectionValues_t&)> 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<bool(const SectionValues_t& sect)> visit) const
{
// m_Config is effectively:
// unordered_map< string, unordered_multimap< string, string >>

@ -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<std::string, std::string>;
using Config_impl_t = std::unordered_map<std::string, SectionValues_t>;
/// 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<void(string_view, const SectionValues_t&)> 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<bool(const SectionValues_t&)> visit) const;
private:
bool

@ -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<void(llarp::SecretKey& key)> keygen)
{
fs::path path(filepath);
std::error_code ec;

@ -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<void(llarp::SecretKey& key)> keygen);
/// Requests the identity key from lokid via HTTP (curl)
bool

@ -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

@ -30,13 +30,11 @@ namespace llarp
bool
Context::Configure(bool isRelay, nonstd::optional<fs::path> 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<llarp::thread::ThreadPool>(threads, 1024, "llarp-worker");
auto jobQueueSize = config->router.m_JobQueueSize;
if(jobQueueSize < 1024)
if (jobQueueSize < 1024)
jobQueueSize = 1024;
logic = std::make_shared<Logic>(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<Config>();
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;

@ -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);

@ -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))
{
const auto &netid = conf->router.m_netId;
llarp::LogWarn("!!!! you have manually set netid to be '", netid,
"' which does not equal '", 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()));
NetID::DefaultValue() = NetID(reinterpret_cast<const byte_t*>(netid.c_str()));
// reset netid in our rc
_rc.netID = llarp::NetID();
}
@ -392,10 +393,8 @@ 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;
@ -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<RouterID> 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<fs::path> 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
// <DATA_DIR>/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());
@ -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};

@ -12,11 +12,10 @@ namespace llarp
ConfigParser parser;
if (!parser.LoadFile(fname))
return false;
parser.IterAll(
[&](string_view name, const ConfigParser::SectionValues_t& section) {
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)
for (const auto& item : section)
values.second.emplace_back(item.first, item.second);
services.emplace_back(values);
});

@ -50,7 +50,7 @@ namespace llarp
virtual void
ImmediateFlush() override;
using Lines_t = thread::Queue< std::string >;
using Lines_t = thread::Queue<std::string>;
protected:
Lines_t m_Lines;

@ -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,7 +97,8 @@ namespace llarp
}
void
LogContext::Initialize(LogLevel level,
LogContext::Initialize(
LogLevel level,
LogType type,
const std::string& file,
const std::string& 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<FileLogStream>(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<JSONLogStream>(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<SysLogStream>();
#endif
break;
}
}

@ -16,7 +16,8 @@ namespace llarp
Json,
Syslog,
};
LogType LogTypeFromString(const std::string&);
LogType
LogTypeFromString(const std::string&);
struct LogContext
{
@ -51,7 +52,8 @@ 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,
Initialize(
LogLevel level,
LogType type,
const std::string& file,
const std::string& nickname,

@ -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;

@ -30,14 +30,15 @@ namespace llarp
string_view
TrimWhitespace(string_view str);
template<typename... T>
std::string stringify(T&&... stuff)
template <typename... T>
std::string
stringify(T&&... stuff)
{
std::ostringstream o;
#ifdef __cpp_fold_expressions
(o << ... << std::forward<T>(stuff));
#else
(void) std::initializer_list<int>{(o << std::forward<T>(stuff), 0)...};
(void)std::initializer_list<int>{(o << std::forward<T>(stuff), 0)...};
#endif
return o.str();
}

Loading…
Cancel
Save