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 int
main(int argc, char* argv[]) main(int argc, char* argv[])
{ {
cxxopts::Options options("lokinetctl", cxxopts::Options options(
"LokiNET is a free, open source, private, " "lokinetctl",
"decentralized, \"market based sybil resistant\" " "LokiNET is a free, open source, private, "
"and IP based onion routing network"); "decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())( options.add_options()("v,verbose", "Verbose", cxxopts::value<bool>())(
"h,help", "help", cxxopts::value< bool >())( "h,help", "help", cxxopts::value<bool>())(
"c,config", "config file", "c,config",
cxxopts::value< std::string >()->default_value( "config file",
llarp::GetDefaultConfigPath().string())) cxxopts::value<std::string>()->default_value(llarp::GetDefaultConfigPath().string()))(
("dump", "dump rc file", "dump", "dump rc file", cxxopts::value<std::vector<std::string>>(), "FILE");
cxxopts::value< std::vector< std::string > >(), "FILE");
try try
{ {
@ -80,7 +80,6 @@ main(int argc, char* argv[])
return 1; return 1;
} }
} }
} }
catch (const cxxopts::OptionParseException& ex) catch (const cxxopts::OptionParseException& ex)
{ {

@ -65,7 +65,7 @@ run_main_context(std::string conffname, llarp_main_runtime_opts opts)
// this is important, can downgrade from Info though // this is important, can downgrade from Info though
llarp::LogDebug("Running from: ", fs::current_path().string()); llarp::LogDebug("Running from: ", fs::current_path().string());
llarp::LogInfo("Using config file: ", conffname); 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; int code = 1;
if (ctx) if (ctx)
{ {
@ -103,18 +103,17 @@ main(int argc, char* argv[])
SetConsoleCtrlHandler(handle_signal_win32, TRUE); SetConsoleCtrlHandler(handle_signal_win32, TRUE);
// SetUnhandledExceptionFilter(win32_signal_handler); // SetUnhandledExceptionFilter(win32_signal_handler);
#endif #endif
cxxopts::Options options("lokinet", cxxopts::Options options(
"LokiNET is a free, open source, private, " "lokinet",
"decentralized, \"market based sybil resistant\" " "LokiNET is a free, open source, private, "
"and IP based onion routing network"); "decentralized, \"market based sybil resistant\" "
options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())( "and IP based onion routing network");
"h,help", "help", cxxopts::value< bool >())("version", "version", options.add_options()("v,verbose", "Verbose", cxxopts::value<bool>())(
cxxopts::value< bool >())( "h,help", "help", cxxopts::value<bool>())("version", "version", cxxopts::value<bool>())(
"g,generate", "generate client config", cxxopts::value< bool >())( "g,generate", "generate client config", cxxopts::value<bool>())(
"r,relay", "run as relay instead of client", cxxopts::value< bool >())( "r,relay", "run as relay instead of client", cxxopts::value<bool>())(
"f,force", "overwrite", cxxopts::value< bool >())( "f,force", "overwrite", cxxopts::value<bool>())(
"c,colour", "colour output", "c,colour", "colour output", cxxopts::value<bool>()->default_value("true"))(
cxxopts::value< bool >()->default_value("true"))(
"b,background", "b,background",
"background mode (start, but do not connect to the network)", "background mode (start, but do not connect to the network)",
cxxopts::value<bool>())( cxxopts::value<bool>())(
@ -123,7 +122,7 @@ main(int argc, char* argv[])
options.parse_positional("config"); options.parse_positional("config");
bool genconfigOnly = false; bool genconfigOnly = false;
bool overwrite = false; bool overwrite = false;
std::string conffname; std::string conffname;
try try
{ {
@ -163,17 +162,17 @@ main(int argc, char* argv[])
opts.background = true; opts.background = true;
} }
if(result.count("relay") > 0) if (result.count("relay") > 0)
{ {
opts.isRelay = true; opts.isRelay = true;
} }
if(result.count("force") > 0) if (result.count("force") > 0)
{ {
overwrite = true; overwrite = true;
} }
if(result.count("config") > 0) if (result.count("config") > 0)
{ {
auto arg = result["config"].as<std::string>(); auto arg = result["config"].as<std::string>();
if (!arg.empty()) if (!arg.empty())
@ -195,12 +194,10 @@ main(int argc, char* argv[])
fs::path fname = fs::path(conffname); fs::path fname = fs::path(conffname);
fs::path basedir = fname.parent_path(); fs::path basedir = fname.parent_path();
if(genconfigOnly) if (genconfigOnly)
{ {
llarp::ensureConfig(llarp::GetDefaultDataDir(), llarp::ensureConfig(
llarp::GetDefaultConfigPath(), llarp::GetDefaultDataDir(), llarp::GetDefaultConfigPath(), overwrite, opts.isRelay);
overwrite,
opts.isRelay);
} }
else else
{ {
@ -217,10 +214,8 @@ main(int argc, char* argv[])
} }
else else
{ {
llarp::ensureConfig(llarp::GetDefaultDataDir(), llarp::ensureConfig(
llarp::GetDefaultConfigPath(), llarp::GetDefaultDataDir(), llarp::GetDefaultConfigPath(), overwrite, opts.isRelay);
overwrite,
opts.isRelay);
conffname = llarp::GetDefaultConfigPath().c_str(); conffname = llarp::GetDefaultConfigPath().c_str();
} }

@ -26,7 +26,7 @@ extern "C"
bool background = false; bool background = false;
bool debug = false; bool debug = false;
bool singleThreaded = false; bool singleThreaded = false;
bool isRelay = false; bool isRelay = false;
}; };
/// llarp_application config /// llarp_application config
@ -139,20 +139,20 @@ extern "C"
/// allocates new config and puts it into c /// allocates new config and puts it into c
/// return false on failure /// return false on failure
bool 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 /// make a main context from configuration
/// copies config contents /// copies config contents
struct llarp_main * struct llarp_main*
llarp_main_init_from_config(struct llarp_config *conf, bool isRelay); llarp_main_init_from_config(struct llarp_config* conf, bool isRelay);
/// initialize application context and load config /// initialize application context and load config
static struct llarp_main * static struct llarp_main*
llarp_main_init(const char *fname, bool isRelay) llarp_main_init(const char* fname, bool isRelay)
{ {
struct llarp_main *m = 0; struct llarp_main* m = 0;
struct llarp_config *conf = 0; struct llarp_config* conf = 0;
if(!llarp_config_load_file(fname, &conf, isRelay)) if (!llarp_config_load_file(fname, &conf, isRelay))
return 0; return 0;
if (conf == NULL) if (conf == NULL)
return 0; return 0;
@ -162,7 +162,7 @@ extern "C"
} }
/// initialize applicatin context with all defaults /// initialize applicatin context with all defaults
static struct llarp_main * static struct llarp_main*
llarp_main_default_init(bool isRelay) llarp_main_default_init(bool isRelay)
{ {
struct llarp_main* m; struct llarp_main* m;
@ -178,7 +178,7 @@ extern "C"
/// (re)configure main context /// (re)configure main context
/// return true if (re)configuration was successful /// return true if (re)configuration was successful
bool 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 true if this main context is running
/// return false otherwise /// return false otherwise

@ -55,7 +55,7 @@ namespace llarp
std::string nodedb_dir; std::string nodedb_dir;
bool bool
LoadConfig(const std::string &fname, bool isRelay); LoadConfig(const std::string& fname, bool isRelay);
void void
Close(); Close();
@ -101,12 +101,11 @@ namespace llarp
#endif #endif
private: private:
void void
SigINT(); SigINT();
std::string configfile; std::string configfile;
std::unique_ptr< std::promise< void > > closeWaiter; std::unique_ptr<std::promise<void>> closeWaiter;
}; };
} // namespace llarp } // namespace llarp

File diff suppressed because it is too large Load Diff

@ -22,7 +22,7 @@ namespace llarp
using Config_impl_t = llarp::ConfigParser::Config_impl_t; using Config_impl_t = llarp::ConfigParser::Config_impl_t;
// TODO: don't use these maps. they're sloppy and difficult to follow // 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 /// Small struct to gather all parameters needed for config generation to reduce the number of
/// parameters that need to be passed around. /// parameters that need to be passed around.
@ -59,7 +59,7 @@ namespace llarp
struct NetworkConfig struct NetworkConfig
{ {
nonstd::optional< bool > m_enableProfiling; nonstd::optional<bool> m_enableProfiling;
std::string m_routerProfilesFile; std::string m_routerProfilesFile;
std::string m_strictConnect; std::string m_strictConnect;
FreehandOptions m_options; FreehandOptions m_options;
@ -106,7 +106,7 @@ namespace llarp
struct ServicesConfig struct ServicesConfig
{ {
std::vector< std::pair< std::string, std::string > > services; std::vector<std::pair<std::string, std::string>> services;
void void
defineConfigOptions(ConfigDefinition& conf, const ConfigGenParameters& params); defineConfigOptions(ConfigDefinition& conf, const ConfigGenParameters& params);
}; };
@ -135,7 +135,7 @@ namespace llarp
struct BootstrapConfig struct BootstrapConfig
{ {
std::vector< std::string > routers; std::vector<std::string> routers;
void void
defineConfigOptions(ConfigDefinition& conf, const ConfigGenParameters& params); defineConfigOptions(ConfigDefinition& conf, const ConfigGenParameters& params);
}; };
@ -195,10 +195,8 @@ namespace llarp
}; };
void void
ensureConfig(const fs::path& defaultDataDir, ensureConfig(
const fs::path& confFile, const fs::path& defaultDataDir, const fs::path& confFile, bool overwrite, bool asRouter);
bool overwrite,
bool asRouter);
} // namespace llarp } // namespace llarp

@ -5,238 +5,223 @@
namespace llarp 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_, ConfigDefinition&
std::string name_, ConfigDefinition::defineOption(OptionDefinition_ptr def)
bool required_) {
: section(section_) auto sectionItr = m_definitions.find(def->section);
, name(name_) if (sectionItr == m_definitions.end())
, required(required_) m_sectionOrdering.push_back(def->section);
{
}
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);
auto& sectionDefinitions = m_definitions[def->section]; auto& sectionDefinitions = m_definitions[def->section];
if (sectionDefinitions.find(def->name) != sectionDefinitions.end()) if (sectionDefinitions.find(def->name) != sectionDefinitions.end())
throw std::invalid_argument(stringify("definition for [", throw std::invalid_argument(
def->section, "]:", def->name, " already exists")); stringify("definition for [", def->section, "]:", def->name, " already exists"));
m_definitionOrdering[def->section].push_back(def->name); m_definitionOrdering[def->section].push_back(def->name);
sectionDefinitions[def->name] = std::move(def); sectionDefinitions[def->name] = std::move(def);
return *this; return *this;
} }
ConfigDefinition& ConfigDefinition&
ConfigDefinition::addConfigValue(string_view section, string_view name, string_view value) ConfigDefinition::addConfigValue(string_view section, string_view name, string_view value)
{
auto secItr = m_definitions.find(std::string(section));
if (secItr == m_definitions.end())
{ {
// fallback to undeclared handler if available auto secItr = m_definitions.find(std::string(section));
auto undItr = m_undeclaredHandlers.find(std::string(section)); if (secItr == m_definitions.end())
if (undItr == m_undeclaredHandlers.end())
throw std::invalid_argument(stringify("no declared section [", section, "]"));
else
{ {
auto& handler = undItr->second; // fallback to undeclared handler if available
handler(section, name, value); auto undItr = m_undeclaredHandlers.find(std::string(section));
return *this; 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 // section was valid, get definition by name
auto& sectionDefinitions = secItr->second; auto& sectionDefinitions = secItr->second;
auto defItr = sectionDefinitions.find(std::string(name)); auto defItr = sectionDefinitions.find(std::string(name));
if (defItr == sectionDefinitions.end()) if (defItr == sectionDefinitions.end())
throw std::invalid_argument(stringify("no declared option [", section, "]:", name)); throw std::invalid_argument(stringify("no declared option [", section, "]:", name));
OptionDefinition_ptr& definition = defItr->second; OptionDefinition_ptr& definition = defItr->second;
definition->parseValue(std::string(value)); definition->parseValue(std::string(value));
return *this; 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"));
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 m_undeclaredHandlers[section] = std::move(handler);
ConfigDefinition::removeUndeclaredHandler(const std::string& section) }
{
auto itr = m_undeclaredHandlers.find(section);
if (itr != m_undeclaredHandlers.end())
m_undeclaredHandlers.erase(itr);
}
void void
ConfigDefinition::validateRequiredFields() ConfigDefinition::removeUndeclaredHandler(const std::string& section)
{
visitSections([&](const std::string& section, const DefinitionMap&)
{ {
visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def) auto itr = m_undeclaredHandlers.find(section);
{ if (itr != m_undeclaredHandlers.end())
if (def->required and def->getNumberFound() < 1) m_undeclaredHandlers.erase(itr);
{ }
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 void
ConfigDefinition::acceptAllOptions() ConfigDefinition::validateRequiredFields()
{
visitSections([&](const std::string& section, const DefinitionMap&)
{ {
visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def) visitSections([&](const std::string& section, const DefinitionMap&) {
{ visitDefinitions(section, [&](const std::string&, const OptionDefinition_ptr& def) {
def->tryAccept(); 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 void
ConfigDefinition::addSectionComments(const std::string& section, ConfigDefinition::acceptAllOptions()
std::vector<std::string> comments)
{
auto& sectionComments = m_sectionComments[section];
for (size_t i=0; i<comments.size(); ++i)
{ {
sectionComments.emplace_back(std::move(comments[i])); visitSections([&](const std::string& section, const DefinitionMap&) {
visitDefinitions(
section, [&](const std::string&, const OptionDefinition_ptr& def) { def->tryAccept(); });
});
} }
}
void void
ConfigDefinition::addOptionComments(const std::string& section, ConfigDefinition::addSectionComments(
const std::string& name, const std::string& section, std::vector<std::string> comments)
std::vector<std::string> comments)
{
auto& defComments = m_definitionComments[section][name];
for (size_t i=0; i<comments.size(); ++i)
{ {
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&) { void
if (sectionsVisited > 0) ConfigDefinition::addOptionComments(
oss << "\n\n"; const std::string& section, const std::string& name, std::vector<std::string> comments)
{
// TODO: this will create empty objects as a side effect of map's operator[] auto& defComments = m_definitionComments[section][name];
// TODO: this also won't handle sections which have no definition for (size_t i = 0; i < comments.size(); ++i)
for (const std::string& comment : m_sectionComments[section])
{ {
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) { int sectionsVisited = 0;
oss << "\n";
// TODO: as above, this will create empty objects visitSections([&](const std::string& section, const DefinitionMap&) {
// TODO: as above (but more important): this won't handle definitions with no entries if (sectionsVisited > 0)
// (i.e. those handled by UndeclaredValueHandler's) oss << "\n\n";
for (const std::string& comment : m_definitionComments[section][name])
{
oss << "# " << comment << "\n";
}
if (useValues and def->getNumberFound() > 0) // 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
oss << name << "=" << def->valueAsString(false) << "\n"; for (const std::string& comment : m_sectionComments[section])
}
else
{ {
if (not def->required) oss << "# " << comment << "\n";
oss << "#";
oss << name << "=" << def->defaultValueAsString() << "\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();
}); }
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 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& auto& sectionDefinitions = sectionItr->second;
ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name) const auto definitionItr = sectionDefinitions.find(std::string(name));
{ if (definitionItr == sectionDefinitions.end())
return const_cast<OptionDefinition_ptr&>( throw std::invalid_argument(stringify("No config item ", name, " within section ", section));
const_cast<const ConfigDefinition*>(this)->lookupDefinitionOrThrow(section, name));
}
void ConfigDefinition::visitSections(SectionVisitor visitor) const return definitionItr->second;
{
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 OptionDefinition_ptr&
{ ConfigDefinition::lookupDefinitionOrThrow(string_view section, string_view name)
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); return const_cast<OptionDefinition_ptr&>(
assert(itr != defs.end()); const_cast<const ConfigDefinition*>(this)->lookupDefinitionOrThrow(section, name));
visitor(name, itr->second);
} }
};
} // 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

@ -12,23 +12,19 @@
namespace llarp namespace llarp
{ {
/// A base class for specifying config options and their constraints. The basic to/from string /// 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 /// 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 /// 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). /// that they can all be mixed into the same containers (albiet as pointers).
struct OptionDefinitionBase struct OptionDefinitionBase
{ {
OptionDefinitionBase(std::string section_, OptionDefinitionBase(std::string section_, std::string name_, bool required_);
std::string name_, OptionDefinitionBase(
bool required_); std::string section_, std::string name_, bool required_, bool multiValued_);
OptionDefinitionBase(std::string section_,
std::string name_,
bool required_,
bool multiValued_);
virtual virtual ~OptionDefinitionBase()
~OptionDefinitionBase() {} {
}
/// Subclasses should provide their default value as a string /// 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. /// Subclassess should call their acceptor, if present. See OptionDefinition for more details.
/// ///
/// @throws if the acceptor throws or the option is required but missing /// @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 section;
std::string name; std::string name;
@ -70,10 +67,11 @@ namespace llarp
/// The primary type-aware implementation of OptionDefinitionBase, this templated class allows /// 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 /// for implementations which can use the std::ostringstream and std::istringstream for to/from
/// string functionality. /// string functionality.
/// ///
/// Note that types (T) used as template parameters here must be used verbatim when calling /// 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. /// ConfigDefinition::getConfigValue(). Similar types such as uint32_t and int32_t cannot be
template<typename T> /// mixed.
template <typename T>
struct OptionDefinition : public OptionDefinitionBase struct OptionDefinition : public OptionDefinitionBase
{ {
/// Constructor. Arguments are passed directly to 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 /// @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 /// 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. /// an exception with a useful message if it is not acceptable.
OptionDefinition(std::string section_, OptionDefinition(
std::string name_, std::string section_,
bool required_, std::string name_,
nonstd::optional<T> defaultValue_, bool required_,
std::function<void(T)> acceptor_ = nullptr) nonstd::optional<T> defaultValue_,
: OptionDefinitionBase(section_, name_, required_) std::function<void(T)> acceptor_ = nullptr)
, defaultValue(defaultValue_) : OptionDefinitionBase(section_, name_, required_)
, acceptor(acceptor_) , defaultValue(defaultValue_)
, acceptor(acceptor_)
{ {
} }
/// As above, but also takes a bool value for multiValued. /// As above, but also takes a bool value for multiValued.
OptionDefinition(std::string section_, OptionDefinition(
std::string name_, std::string section_,
bool required_, std::string name_,
bool multiValued_, bool required_,
nonstd::optional<T> defaultValue_, bool multiValued_,
std::function<void(T)> acceptor_ = nullptr) nonstd::optional<T> defaultValue_,
: OptionDefinitionBase(section_, name_, required_, multiValued_) std::function<void(T)> acceptor_ = nullptr)
, defaultValue(defaultValue_) : OptionDefinitionBase(section_, name_, required_, multiValued_)
, acceptor(acceptor_) , defaultValue(defaultValue_)
, acceptor(acceptor_)
{ {
} }
@ -127,15 +127,15 @@ namespace llarp
/// Returns the value at the given index. /// Returns the value at the given index.
/// ///
/// @param index /// @param index
/// @return the value at the given index, if it exists /// @return the value at the given index, if it exists
/// @throws range_error exception if index >= size /// @throws range_error exception if index >= size
T T
getValueAt(size_t index) const getValueAt(size_t index) const
{ {
if (index >= parsedValues.size()) if (index >= parsedValues.size())
throw std::range_error(stringify( throw std::range_error(
"no value at index ", index, ", size: ", parsedValues.size())); stringify("no value at index ", index, ", size: ", parsedValues.size()));
return parsedValues[index]; return parsedValues[index];
} }
@ -164,10 +164,10 @@ namespace llarp
{ {
if (not multiValued and parsedValues.size() > 0) if (not multiValued and parsedValues.size() > 0)
{ {
throw std::invalid_argument(stringify("duplicate value for ", name, throw std::invalid_argument(
", previous value: ", parsedValues[0])); stringify("duplicate value for ", name, ", previous value: ", parsedValues[0]));
} }
std::istringstream iss(input); std::istringstream iss(input);
T t; T t;
iss >> t; iss >> t;
@ -179,7 +179,6 @@ namespace llarp
{ {
parsedValues.emplace_back(std::move(t)); parsedValues.emplace_back(std::move(t));
} }
} }
std::string std::string
@ -204,8 +203,12 @@ namespace llarp
{ {
if (required and parsedValues.size() == 0) if (required and parsedValues.size() == 0)
{ {
throw std::runtime_error(stringify("cannot call tryAccept() on [", throw std::runtime_error(stringify(
section, "]:", name, " when required but no value available")); "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 // don't use default value if we are multi-valued and have no value
@ -224,7 +227,7 @@ namespace llarp
else else
{ {
auto maybe = getValue(); 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 // TODO: avoid copies here if possible
acceptor(maybe.value()); acceptor(maybe.value());
} }
@ -236,9 +239,8 @@ namespace llarp
std::function<void(T)> acceptor; std::function<void(T)> acceptor;
}; };
using UndeclaredValueHandler using UndeclaredValueHandler =
= std::function<void(string_view section, string_view name, string_view value)>; std::function<void(string_view section, string_view name, string_view value)>;
using OptionDefinition_ptr = std::unique_ptr<OptionDefinitionBase>; using OptionDefinition_ptr = std::unique_ptr<OptionDefinitionBase>;
@ -253,17 +255,17 @@ namespace llarp
/// ///
/// The layout and grouping of the config options are modelled after the INI file format; each /// 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 /// 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 /// they exist in a different section. The ConfigDefinition can be serialized in the INI file
/// using the generateINIConfig() function. /// format using the generateINIConfig() function.
/// ///
/// Configured values (e.g. those encountered when parsing a file) can be provided through calls /// 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. /// 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 /// 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 /// with defaults and optionally fields which have a specified value (values provided through
/// calls to addConfigValue()). /// calls to addConfigValue()).
struct ConfigDefinition { struct ConfigDefinition
{
/// Spefify the parameters and type of a configuration option. The parameters are members of /// 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. /// 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 /// Convenience function which calls defineOption with a OptionDefinition of the specified type
/// and with parameters passed through to OptionDefinition's constructor. /// and with parameters passed through to OptionDefinition's constructor.
template<typename T, typename... Params> template <typename T, typename... Params>
ConfigDefinition& ConfigDefinition&
defineOption(Params&&... args) defineOption(Params&&... args)
{ {
@ -297,9 +299,7 @@ namespace llarp
/// @return `*this` for chaining calls /// @return `*this` for chaining calls
/// @throws if the option doesn't exist or the provided string isn't parseable /// @throws if the option doesn't exist or the provided string isn't parseable
ConfigDefinition& ConfigDefinition&
addConfigValue(string_view section, addConfigValue(string_view section, string_view name, string_view value);
string_view name,
string_view value);
/// Get a config value. If the value hasn't been provided but a default has, the default will /// 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. /// 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 /// @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 /// @throws std::invalid_argument if there is no such config option or the wrong type T was
// provided // provided
template<typename T> template <typename T>
nonstd::optional<T> getConfigValue(string_view section, string_view name) nonstd::optional<T>
getConfigValue(string_view section, string_view name)
{ {
OptionDefinition_ptr& definition = lookupDefinitionOrThrow(section, name); OptionDefinition_ptr& definition = lookupDefinitionOrThrow(section, name);
auto derived = dynamic_cast<const OptionDefinition<T>*>(definition.get()); auto derived = dynamic_cast<const OptionDefinition<T>*>(definition.get());
if (not derived) if (not derived)
throw std::invalid_argument(stringify("", typeid(T).name(), throw std::invalid_argument(
" is the incorrect type for [", section, "]:", name)); stringify("", typeid(T).name(), " is the incorrect type for [", section, "]:", name));
return derived->getValue(); return derived->getValue();
} }
@ -333,7 +334,7 @@ namespace llarp
/// ///
/// @param section is the section for which any undeclared values will invoke the provided /// @param section is the section for which any undeclared values will invoke the provided
/// handler /// handler
/// @param handler /// @param handler
/// @throws if there is already a handler for this section /// @throws if there is already a handler for this section
void void
addUndeclaredHandler(const std::string& section, UndeclaredValueHandler handler); addUndeclaredHandler(const std::string& section, UndeclaredValueHandler handler);
@ -374,9 +375,8 @@ namespace llarp
/// @param name /// @param name
/// @param comment /// @param comment
void void
addOptionComments(const std::string& section, addOptionComments(
const std::string& name, const std::string& section, const std::string& name, std::vector<std::string> comments);
std::vector<std::string> comments);
/// Generate a config string from the current config definition, optionally using overridden /// 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 /// values. The generated config will preserve insertion order of both sections and their
@ -393,15 +393,18 @@ namespace llarp
generateINIConfig(bool useValues = false); generateINIConfig(bool useValues = false);
private: private:
OptionDefinition_ptr&
OptionDefinition_ptr& lookupDefinitionOrThrow(string_view section, string_view name); lookupDefinitionOrThrow(string_view section, string_view name);
const OptionDefinition_ptr& lookupDefinitionOrThrow(string_view section, string_view name) const; const OptionDefinition_ptr&
lookupDefinitionOrThrow(string_view section, string_view name) const;
using SectionVisitor = std::function<void(const std::string&, const DefinitionMap&)>; 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&)>; 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; 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 /// 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. /// particular, a reference to a local variable may be problematic.
template<typename T> template <typename T>
std::function<void(T)> std::function<void(T)>
AssignmentAcceptor(T& ref) { AssignmentAcceptor(T& ref)
return [&](T arg) mutable { {
ref = std::move(arg); return [&](T arg) mutable { ref = std::move(arg); };
};
} }
} // namespace llarp } // namespace llarp

@ -145,8 +145,7 @@ namespace llarp
} }
void void
ConfigParser::IterAll( ConfigParser::IterAll(std::function<void(string_view, const SectionValues_t&)> visit)
std::function< void(string_view, const SectionValues_t&) > visit)
{ {
for (const auto& item : m_Config) for (const auto& item : m_Config)
visit(item.first, item.second); visit(item.first, item.second);
@ -154,8 +153,7 @@ namespace llarp
bool bool
ConfigParser::VisitSection( ConfigParser::VisitSection(
const char* name, const char* name, std::function<bool(const SectionValues_t& sect)> visit) const
std::function< bool(const SectionValues_t& sect) > visit) const
{ {
// m_Config is effectively: // m_Config is effectively:
// unordered_map< string, unordered_multimap< string, string >> // unordered_map< string, unordered_multimap< string, string >>

@ -12,8 +12,8 @@ namespace llarp
{ {
struct ConfigParser struct ConfigParser
{ {
using SectionValues_t = std::unordered_multimap< std::string, std::string >; using SectionValues_t = std::unordered_multimap<std::string, std::string>;
using Config_impl_t = std::unordered_map< std::string, SectionValues_t >; using Config_impl_t = std::unordered_map<std::string, SectionValues_t>;
/// clear parser /// clear parser
void void
Clear(); Clear();
@ -32,13 +32,12 @@ namespace llarp
/// iterate all sections and thier values /// iterate all sections and thier values
void 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 /// visit a section in config read only by name
/// return false if no section or value propagated from visitor /// return false if no section or value propagated from visitor
bool bool
VisitSection(const char* name, VisitSection(const char* name, std::function<bool(const SectionValues_t&)> visit) const;
std::function< bool(const SectionValues_t&) > visit) const;
private: private:
bool bool

@ -34,9 +34,9 @@ namespace llarp
fs::path root = config.router.m_dataDir; fs::path root = config.router.m_dataDir;
// TODO: use fs::path, or at least support windows-style separators // TODO: use fs::path, or at least support windows-style separators
m_rcPath = root / our_rc_filename; m_rcPath = root / our_rc_filename;
m_idKeyPath = root / our_identity_filename; m_idKeyPath = root / our_identity_filename;
m_encKeyPath = root / our_enc_key_filename; m_encKeyPath = root / our_enc_key_filename;
m_transportKeyPath = root / our_transport_key_filename; m_transportKeyPath = root / our_transport_key_filename;
m_usingLokid = config.lokid.whitelistRouters; m_usingLokid = config.lokid.whitelistRouters;
@ -183,8 +183,9 @@ namespace llarp
bool bool
KeyManager::loadOrCreateKey( KeyManager::loadOrCreateKey(
const fs::path& filepath, llarp::SecretKey& key, const fs::path& filepath,
std::function< void(llarp::SecretKey& key) > keygen) llarp::SecretKey& key,
std::function<void(llarp::SecretKey& key)> keygen)
{ {
fs::path path(filepath); fs::path path(filepath);
std::error_code ec; std::error_code ec;

@ -87,8 +87,10 @@ namespace llarp
/// ///
/// @param keygen is a function that will generate the key if needed /// @param keygen is a function that will generate the key if needed
static bool static bool
loadOrCreateKey(const fs::path& filepath, llarp::SecretKey& key, loadOrCreateKey(
std::function< void(llarp::SecretKey& key) > keygen); const fs::path& filepath,
llarp::SecretKey& key,
std::function<void(llarp::SecretKey& key)> keygen);
/// Requests the identity key from lokid via HTTP (curl) /// Requests the identity key from lokid via HTTP (curl)
bool bool

@ -13,8 +13,7 @@ namespace llarp
constexpr auto nodedb_dirname = "nodedb"; constexpr auto nodedb_dirname = "nodedb";
inline inline fs::path
fs::path
GetDefaultDataDir() GetDefaultDataDir()
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -25,19 +24,16 @@ namespace llarp
return homedir / ".lokinet/"; return homedir / ".lokinet/";
} }
inline inline fs::path
fs::path
GetDefaultConfigFilename() GetDefaultConfigFilename()
{ {
return "lokinet.ini"; return "lokinet.ini";
} }
inline inline fs::path
fs::path
GetDefaultConfigPath() GetDefaultConfigPath()
{ {
return GetDefaultDataDir() / GetDefaultConfigFilename(); return GetDefaultDataDir() / GetDefaultConfigFilename();
} }
} // namespace llarp } // namespace llarp

@ -30,13 +30,11 @@ namespace llarp
bool bool
Context::Configure(bool isRelay, nonstd::optional<fs::path> dataDir) Context::Configure(bool isRelay, nonstd::optional<fs::path> dataDir)
{ {
fs::path defaultDataDir = dataDir.has_value() fs::path defaultDataDir = dataDir.has_value() ? dataDir.value() : GetDefaultDataDir();
? 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(); config.release();
llarp::LogError("failed to load config file ", configfile); llarp::LogError("failed to load config file ", configfile);
@ -45,12 +43,11 @@ namespace llarp
} }
auto threads = config->router.m_workerThreads; auto threads = config->router.m_workerThreads;
if(threads <= 0) if (threads <= 0)
threads = 1; threads = 1;
worker = std::make_shared< llarp::thread::ThreadPool >(threads, 1024, worker = std::make_shared<llarp::thread::ThreadPool>(threads, 1024, "llarp-worker");
"llarp-worker");
auto jobQueueSize = config->router.m_JobQueueSize; auto jobQueueSize = config->router.m_JobQueueSize;
if(jobQueueSize < 1024) if (jobQueueSize < 1024)
jobQueueSize = 1024; jobQueueSize = 1024;
logic = std::make_shared<Logic>(jobQueueSize); logic = std::make_shared<Logic>(jobQueueSize);
@ -214,7 +211,7 @@ namespace llarp
} }
bool bool
Context::LoadConfig(const std::string &fname, bool isRelay) Context::LoadConfig(const std::string& fname, bool isRelay)
{ {
config = std::make_unique<Config>(); config = std::make_unique<Config>();
configfile = fname; configfile = fname;
@ -281,23 +278,23 @@ extern "C"
delete conf; delete conf;
} }
struct llarp_main * struct llarp_main*
llarp_main_init_from_config(struct llarp_config *conf, bool isRelay) llarp_main_init_from_config(struct llarp_config* conf, bool isRelay)
{ {
if (conf == nullptr) if (conf == nullptr)
return nullptr; return nullptr;
llarp_main *m = new llarp_main(conf); llarp_main* m = new llarp_main(conf);
if(m->ctx->Configure(isRelay, {})) if (m->ctx->Configure(isRelay, {}))
return m; return m;
delete m; delete m;
return nullptr; return nullptr;
} }
bool 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(); llarp_config* c = new llarp_config();
if(c->impl.Load(fname, isRelay, {})) if (c->impl.Load(fname, isRelay, {}))
{ {
*conf = c; *conf = c;
return true; return true;
@ -434,7 +431,7 @@ extern "C"
} }
bool 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) if (ptr == nullptr || conf == nullptr)
return false; return false;

@ -467,7 +467,7 @@ llarp_nodedb::ensure_dir(const fs::path& nodedbDir)
// perhaps cpp17::fs is just as screwed-up // perhaps cpp17::fs is just as screwed-up
// attempting to create a folder with no name // attempting to create a folder with no name
// what does this mean...? // what does this mean...?
if(!ch) if (!ch)
continue; continue;
fs::path sub = nodedbDir / std::string(&ch, 1); fs::path sub = nodedbDir / std::string(&ch, 1);

@ -373,17 +373,18 @@ namespace llarp
Router::FromConfig(Config* conf) Router::FromConfig(Config* conf)
{ {
// Set netid before anything else // Set netid before anything else
if(!conf->router.m_netId.empty() if (!conf->router.m_netId.empty() && strcmp(conf->router.m_netId.c_str(), llarp::DEFAULT_NETID))
&& strcmp(conf->router.m_netId.c_str(), llarp::DEFAULT_NETID))
{ {
const auto &netid = conf->router.m_netId; const auto& netid = conf->router.m_netId;
llarp::LogWarn("!!!! you have manually set netid to be '", netid, llarp::LogWarn(
"' which does not equal '", llarp::DEFAULT_NETID, "!!!! you have manually set netid to be '",
"' you will run as a different network, good luck " netid,
"and don't forget: something something MUH traffic " "' which does not equal '",
"shape correlation !!!!"); llarp::DEFAULT_NETID,
NetID::DefaultValue() = "' you will run as a different network, good luck "
NetID(reinterpret_cast< const byte_t * >(netid.c_str())); "and don't forget: something something MUH traffic "
"shape correlation !!!!");
NetID::DefaultValue() = NetID(reinterpret_cast<const byte_t*>(netid.c_str()));
// reset netid in our rc // reset netid in our rc
_rc.netID = llarp::NetID(); _rc.netID = llarp::NetID();
} }
@ -392,16 +393,14 @@ namespace llarp
m_OutboundPort = conf->links.m_OutboundLink.port; m_OutboundPort = conf->links.m_OutboundLink.port;
// Router config // Router config
_rc.SetNick(conf->router.m_nickname); _rc.SetNick(conf->router.m_nickname);
_outboundSessionMaker.maxConnectedRouters = _outboundSessionMaker.maxConnectedRouters = conf->router.m_maxConnectedRouters;
conf->router.m_maxConnectedRouters; _outboundSessionMaker.minConnectedRouters = conf->router.m_minConnectedRouters;
_outboundSessionMaker.minConnectedRouters =
conf->router.m_minConnectedRouters;
encryption_keyfile = conf->router.m_dataDir / our_enc_key_filename; encryption_keyfile = conf->router.m_dataDir / our_enc_key_filename;
our_rc_file = conf->router.m_dataDir / our_rc_filename; our_rc_file = conf->router.m_dataDir / our_rc_filename;
transport_keyfile = conf->router.m_dataDir / our_transport_key_filename; transport_keyfile = conf->router.m_dataDir / our_transport_key_filename;
addrInfo = conf->router.m_addrInfo; addrInfo = conf->router.m_addrInfo;
publicOverride = conf->router.m_publicOverride; publicOverride = conf->router.m_publicOverride;
ip4addr = conf->router.m_ip4addr; ip4addr = conf->router.m_ip4addr;
RouterContact::BlockBogons = conf->router.m_blockBogons; RouterContact::BlockBogons = conf->router.m_blockBogons;
@ -414,17 +413,17 @@ namespace llarp
lokidRPCPassword = conf->lokid.lokidRPCPassword; lokidRPCPassword = conf->lokid.lokidRPCPassword;
// TODO: add config flag for "is service node" // TODO: add config flag for "is service node"
if(conf->links.m_InboundLinks.size()) if (conf->links.m_InboundLinks.size())
{ {
m_isServiceNode = true; m_isServiceNode = true;
} }
std::set<RouterID> strictConnectPubkeys; std::set<RouterID> strictConnectPubkeys;
if(!conf->network.m_strictConnect.empty()) if (!conf->network.m_strictConnect.empty())
{ {
const auto &val = conf->network.m_strictConnect; const auto& val = conf->network.m_strictConnect;
if(IsServiceNode()) if (IsServiceNode())
{ {
llarp::LogError("cannot use strict-connect option as service node"); llarp::LogError("cannot use strict-connect option as service node");
return false; return false;
@ -453,8 +452,8 @@ namespace llarp
} }
std::vector<fs::path> configRouters = conf->connect.routers; std::vector<fs::path> configRouters = conf->connect.routers;
configRouters.insert(configRouters.end(), conf->bootstrap.routers.begin(), configRouters.insert(
conf->bootstrap.routers.end()); configRouters.end(), conf->bootstrap.routers.begin(), conf->bootstrap.routers.end());
// if our conf had no bootstrap files specified, try the default location of // 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 // <DATA_DIR>/bootstrap.signed. If this isn't present, leave a useful error message
@ -479,7 +478,7 @@ namespace llarp
bool isListFile = false; bool isListFile = false;
{ {
std::ifstream inf(router.c_str(), std::ios::binary); std::ifstream inf(router.c_str(), std::ios::binary);
if(inf.is_open()) if (inf.is_open())
{ {
const char ch = inf.get(); const char ch = inf.get();
isListFile = ch == 'l'; isListFile = ch == 'l';
@ -539,10 +538,11 @@ namespace llarp
} }
// create inbound links, if we are a service node // 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( 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::HandleRecvLinkMessageBuffer, this),
util::memFn(&AbstractRouter::Sign, this), util::memFn(&AbstractRouter::Sign, this),
util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker), util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker),
@ -554,7 +554,7 @@ namespace llarp
const std::string& key = serverConfig.interface; const std::string& key = serverConfig.interface;
int af = serverConfig.addressFamily; int af = serverConfig.addressFamily;
uint16_t port = serverConfig.port; 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); LogError("failed to bind inbound link on ", key, " port ", port);
return false; return false;
@ -563,16 +563,16 @@ namespace llarp
} }
// Network config // 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(); routerProfiling().Disable();
LogWarn("router profiling explicitly disabled"); LogWarn("router profiling explicitly disabled");
} }
} }
if(!conf->network.m_routerProfilesFile.empty()) if (!conf->network.m_routerProfilesFile.empty())
{ {
routerProfilesFile = conf->network.m_routerProfilesFile; routerProfilesFile = conf->network.m_routerProfilesFile;
routerProfiling().Load(routerProfilesFile.c_str()); routerProfiling().Load(routerProfilesFile.c_str());
@ -581,7 +581,7 @@ namespace llarp
// API config // API config
enableRPCServer = conf->api.m_enableRPCServer; enableRPCServer = conf->api.m_enableRPCServer;
rpcBindAddr = conf->api.m_rpcBindAddr; rpcBindAddr = conf->api.m_rpcBindAddr;
// Services config // Services config
for (const auto& service : conf->services.services) for (const auto& service : conf->services.services)
@ -1228,15 +1228,13 @@ namespace llarp
util::memFn(&AbstractRouter::rc, this), util::memFn(&AbstractRouter::rc, this),
util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this), util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this),
util::memFn(&AbstractRouter::Sign, this), util::memFn(&AbstractRouter::Sign, this),
util::memFn(&IOutboundSessionMaker::OnSessionEstablished, util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker),
&_outboundSessionMaker),
util::memFn(&AbstractRouter::CheckRenegotiateValid, this), util::memFn(&AbstractRouter::CheckRenegotiateValid, this),
util::memFn(&IOutboundSessionMaker::OnConnectTimeout, util::memFn(&IOutboundSessionMaker::OnConnectTimeout, &_outboundSessionMaker),
&_outboundSessionMaker),
util::memFn(&AbstractRouter::SessionClosed, this), util::memFn(&AbstractRouter::SessionClosed, this),
util::memFn(&AbstractRouter::PumpLL, this)); util::memFn(&AbstractRouter::PumpLL, this));
if(!link) if (!link)
return false; return false;
const auto afs = {AF_INET, AF_INET6}; const auto afs = {AF_INET, AF_INET6};

@ -12,14 +12,13 @@ namespace llarp
ConfigParser parser; ConfigParser parser;
if (!parser.LoadFile(fname)) if (!parser.LoadFile(fname))
return false; return false;
parser.IterAll( parser.IterAll([&](string_view name, const ConfigParser::SectionValues_t& section) {
[&](string_view name, const ConfigParser::SectionValues_t& section) { Config::section_t values;
Config::section_t values; values.first.assign(name.begin(), name.end());
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);
values.second.emplace_back(item.first, item.second); services.emplace_back(values);
services.emplace_back(values); });
});
return services.size() > 0; return services.size() > 0;
} }

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

@ -33,10 +33,14 @@ namespace llarp
LogType LogType
LogTypeFromString(const std::string& str) LogTypeFromString(const std::string& str)
{ {
if (str == "unknown") return LogType::Unknown; if (str == "unknown")
else if (str == "file") return LogType::File; return LogType::Unknown;
else if (str == "json") return LogType::Json; else if (str == "file")
else if (str == "syslog") return LogType::Syslog; return LogType::File;
else if (str == "json")
return LogType::Json;
else if (str == "syslog")
return LogType::Syslog;
return LogType::Unknown; return LogType::Unknown;
} }
@ -93,11 +97,12 @@ namespace llarp
} }
void void
LogContext::Initialize(LogLevel level, LogContext::Initialize(
LogType type, LogLevel level,
const std::string& file, LogType type,
const std::string& nickname, const std::string& file,
std::shared_ptr<thread::ThreadPool> threadpool) const std::string& nickname,
std::shared_ptr<thread::ThreadPool> threadpool)
{ {
SetLogLevel(level); SetLogLevel(level);
nodeName = nickname; nodeName = nickname;
@ -112,8 +117,8 @@ namespace llarp
logfile = ::fopen(file.c_str(), "a"); logfile = ::fopen(file.c_str(), "a");
if (not logfile) if (not logfile)
{ {
throw std::runtime_error(stringify( throw std::runtime_error(
"could not open logfile ", file, ", errno: ", strerror(errno))); stringify("could not open logfile ", file, ", errno: ", strerror(errno)));
} }
} }
@ -129,7 +134,7 @@ namespace llarp
std::cout << std::flush; std::cout << std::flush;
LogContext::Instance().logStream = LogContext::Instance().logStream =
std::make_unique< FileLogStream >(threadpool, logfile, 100ms, true); std::make_unique<FileLogStream>(threadpool, logfile, 100ms, true);
} }
else else
{ {
@ -141,8 +146,8 @@ namespace llarp
LogInfo("Switching logger to JSON with file: ", file); LogInfo("Switching logger to JSON with file: ", file);
std::cout << std::flush; std::cout << std::flush;
LogContext::Instance().logStream = std::make_unique< JSONLogStream >( LogContext::Instance().logStream =
threadpool, logfile, 100ms, logfile != stdout); std::make_unique<JSONLogStream>(threadpool, logfile, 100ms, logfile != stdout);
break; break;
case LogType::Syslog: case LogType::Syslog:
if (logfile) if (logfile)
@ -157,10 +162,9 @@ namespace llarp
#else #else
LogInfo("Switching logger to syslog"); LogInfo("Switching logger to syslog");
std::cout << std::flush; std::cout << std::flush;
LogContext::Instance().logStream = std::make_unique< SysLogStream >(); LogContext::Instance().logStream = std::make_unique<SysLogStream>();
#endif #endif
break; break;
} }
} }

@ -16,7 +16,8 @@ namespace llarp
Json, Json,
Syslog, Syslog,
}; };
LogType LogTypeFromString(const std::string&); LogType
LogTypeFromString(const std::string&);
struct LogContext struct LogContext
{ {
@ -51,11 +52,12 @@ namespace llarp
/// @param nickname is a tag to add to each log statement /// @param nickname is a tag to add to each log statement
/// @param threadpool is a threadpool where I/O can offloaded /// @param threadpool is a threadpool where I/O can offloaded
void void
Initialize(LogLevel level, Initialize(
LogType type, LogLevel level,
const std::string& file, LogType type,
const std::string& nickname, const std::string& file,
std::shared_ptr<thread::ThreadPool> threadpool); const std::string& nickname,
std::shared_ptr<thread::ThreadPool> threadpool);
}; };
void void

@ -91,7 +91,7 @@ namespace llarp
next = str.find_first_of(delimiter, last); next = str.find_first_of(delimiter, last);
if (next > last) if (next > last)
{ {
splits.push_back(str.substr(last, next-last)); splits.push_back(str.substr(last, next - last));
last = next; last = next;
@ -103,7 +103,6 @@ namespace llarp
{ {
break; break;
} }
} }
return splits; return splits;

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

Loading…
Cancel
Save