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",
"LokiNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
cxxopts::Options options(
"lokinetctl",
"LokiNET is a free, open source, private, "
"decentralized, \"market based sybil resistant\" "
"and IP based onion routing network");
options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())(
"h,help", "help", cxxopts::value< bool >())(
"c,config", "config file",
cxxopts::value< std::string >()->default_value(
llarp::GetDefaultConfigPath().string()))
("dump", "dump rc file",
cxxopts::value< std::vector< std::string > >(), "FILE");
options.add_options()("v,verbose", "Verbose", cxxopts::value<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)
{

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

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

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

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

@ -12,23 +12,19 @@
namespace llarp
{
/// A base class for specifying config options and their constraints. The basic to/from string
/// type functions are provided pure-virtual. The type-aware implementations which implement these
/// functions are templated classes. One reason for providing a non-templated base class is so
/// that they can all be mixed into the same containers (albiet as pointers).
struct OptionDefinitionBase
struct OptionDefinitionBase
{
OptionDefinitionBase(std::string section_,
std::string name_,
bool required_);
OptionDefinitionBase(std::string section_,
std::string name_,
bool required_,
bool multiValued_);
OptionDefinitionBase(std::string section_, std::string name_, bool required_);
OptionDefinitionBase(
std::string section_, std::string name_, bool required_, bool multiValued_);
virtual
~OptionDefinitionBase() {}
virtual ~OptionDefinitionBase()
{
}
/// Subclasses should provide their default value as a string
///
@ -59,7 +55,8 @@ namespace llarp
/// Subclassess should call their acceptor, if present. See OptionDefinition for more details.
///
/// @throws if the acceptor throws or the option is required but missing
virtual void tryAccept() const = 0;
virtual void
tryAccept() const = 0;
std::string section;
std::string name;
@ -70,10 +67,11 @@ namespace llarp
/// The primary type-aware implementation of OptionDefinitionBase, this templated class allows
/// for implementations which can use the std::ostringstream and std::istringstream for to/from
/// string functionality.
///
/// Note that types (T) used as template parameters here must be used verbatim when calling
/// ConfigDefinition::getConfigValue(). Similar types such as uint32_t and int32_t cannot be mixed.
template<typename T>
///
/// 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>
struct OptionDefinition : public OptionDefinitionBase
{
/// Constructor. Arguments are passed directly to OptionDefinitionBase.
@ -86,27 +84,29 @@ namespace llarp
/// @param acceptor_ is an optional function whose purpose is to both validate the parsed
/// input and internalize it (e.g. copy it for runtime use). The acceptor should throw
/// an exception with a useful message if it is not acceptable.
OptionDefinition(std::string section_,
std::string name_,
bool required_,
nonstd::optional<T> defaultValue_,
std::function<void(T)> acceptor_ = nullptr)
: OptionDefinitionBase(section_, name_, required_)
, defaultValue(defaultValue_)
, acceptor(acceptor_)
OptionDefinition(
std::string section_,
std::string name_,
bool required_,
nonstd::optional<T> defaultValue_,
std::function<void(T)> acceptor_ = nullptr)
: OptionDefinitionBase(section_, name_, required_)
, defaultValue(defaultValue_)
, acceptor(acceptor_)
{
}
/// As above, but also takes a bool value for multiValued.
OptionDefinition(std::string section_,
std::string name_,
bool required_,
bool multiValued_,
nonstd::optional<T> defaultValue_,
std::function<void(T)> acceptor_ = nullptr)
: OptionDefinitionBase(section_, name_, required_, multiValued_)
, defaultValue(defaultValue_)
, acceptor(acceptor_)
OptionDefinition(
std::string section_,
std::string name_,
bool required_,
bool multiValued_,
nonstd::optional<T> defaultValue_,
std::function<void(T)> acceptor_ = nullptr)
: OptionDefinitionBase(section_, name_, required_, multiValued_)
, defaultValue(defaultValue_)
, acceptor(acceptor_)
{
}
@ -127,15 +127,15 @@ namespace llarp
/// Returns the value at the given index.
///
/// @param index
/// @param index
/// @return the value at the given index, if it exists
/// @throws range_error exception if index >= size
T
getValueAt(size_t index) const
{
if (index >= parsedValues.size())
throw std::range_error(stringify(
"no value at index ", index, ", size: ", parsedValues.size()));
throw std::range_error(
stringify("no value at index ", index, ", size: ", parsedValues.size()));
return parsedValues[index];
}
@ -164,10 +164,10 @@ namespace llarp
{
if (not multiValued and parsedValues.size() > 0)
{
throw std::invalid_argument(stringify("duplicate value for ", name,
", previous value: ", parsedValues[0]));
throw std::invalid_argument(
stringify("duplicate value for ", name, ", previous value: ", parsedValues[0]));
}
std::istringstream iss(input);
T t;
iss >> t;
@ -179,7 +179,6 @@ namespace llarp
{
parsedValues.emplace_back(std::move(t));
}
}
std::string
@ -204,8 +203,12 @@ namespace llarp
{
if (required and parsedValues.size() == 0)
{
throw std::runtime_error(stringify("cannot call tryAccept() on [",
section, "]:", name, " when required but no value available"));
throw std::runtime_error(stringify(
"cannot call tryAccept() on [",
section,
"]:",
name,
" when required but no value available"));
}
// don't use default value if we are multi-valued and have no value
@ -224,7 +227,7 @@ namespace llarp
else
{
auto maybe = getValue();
assert(maybe.has_value()); // should be guaranteed by our earlier checks
assert(maybe.has_value()); // should be guaranteed by our earlier checks
// TODO: avoid copies here if possible
acceptor(maybe.value());
}
@ -236,9 +239,8 @@ namespace llarp
std::function<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,17 +255,17 @@ namespace llarp
///
/// The layout and grouping of the config options are modelled after the INI file format; each
/// option has a name and is grouped under a section. Duplicate option names are allowed only if
/// they exist in a different section. The ConfigDefinition can be serialized in the INI file format
/// using the generateINIConfig() function.
/// they exist in a different section. The ConfigDefinition can be serialized in the INI file
/// format using the generateINIConfig() function.
///
/// Configured values (e.g. those encountered when parsing a file) can be provided through calls
/// to addConfigValue(). These take a std::string as a value, which is automatically parsed.
///
///
/// The ConfigDefinition can be used to print out a full config string (or file), including fields
/// with defaults and optionally fields which have a specified value (values provided through
/// calls to addConfigValue()).
struct ConfigDefinition {
struct ConfigDefinition
{
/// Spefify the parameters and type of a configuration option. The parameters are members of
/// OptionDefinitionBase; the type is inferred from OptionDefinition's template parameter T.
///
@ -278,7 +280,7 @@ namespace llarp
/// Convenience function which calls defineOption with a OptionDefinition of the specified type
/// and with parameters passed through to OptionDefinition's constructor.
template<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();
}
@ -333,7 +334,7 @@ namespace llarp
///
/// @param section is the section for which any undeclared values will invoke the provided
/// handler
/// @param handler
/// @param handler
/// @throws if there is already a handler for this section
void
addUndeclaredHandler(const std::string& section, UndeclaredValueHandler handler);
@ -374,9 +375,8 @@ namespace llarp
/// @param name
/// @param comment
void
addOptionComments(const std::string& section,
const std::string& name,
std::vector<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
} // 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

@ -34,9 +34,9 @@ namespace llarp
fs::path root = config.router.m_dataDir;
// TODO: use fs::path, or at least support windows-style separators
m_rcPath = root / our_rc_filename;
m_idKeyPath = root / our_identity_filename;
m_encKeyPath = root / our_enc_key_filename;
m_rcPath = root / our_rc_filename;
m_idKeyPath = root / our_identity_filename;
m_encKeyPath = root / our_enc_key_filename;
m_transportKeyPath = root / our_transport_key_filename;
m_usingLokid = config.lokid.whitelistRouters;
@ -183,8 +183,9 @@ namespace llarp
bool
KeyManager::loadOrCreateKey(
const fs::path& filepath, llarp::SecretKey& key,
std::function< void(llarp::SecretKey& key) > keygen)
const fs::path& filepath,
llarp::SecretKey& key,
std::function<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))
if (!conf->router.m_netId.empty() && strcmp(conf->router.m_netId.c_str(), llarp::DEFAULT_NETID))
{
const auto &netid = conf->router.m_netId;
llarp::LogWarn("!!!! you have manually set netid to be '", netid,
"' which does not equal '", llarp::DEFAULT_NETID,
"' you will run as a different network, good luck "
"and don't forget: something something MUH traffic "
"shape correlation !!!!");
NetID::DefaultValue() =
NetID(reinterpret_cast< const byte_t * >(netid.c_str()));
const auto& netid = conf->router.m_netId;
llarp::LogWarn(
"!!!! you have manually set netid to be '",
netid,
"' which does not equal '",
llarp::DEFAULT_NETID,
"' you will run as a different network, good luck "
"and don't forget: something something MUH traffic "
"shape correlation !!!!");
NetID::DefaultValue() = NetID(reinterpret_cast<const byte_t*>(netid.c_str()));
// reset netid in our rc
_rc.netID = llarp::NetID();
}
@ -392,16 +393,14 @@ namespace llarp
m_OutboundPort = conf->links.m_OutboundLink.port;
// Router config
_rc.SetNick(conf->router.m_nickname);
_outboundSessionMaker.maxConnectedRouters =
conf->router.m_maxConnectedRouters;
_outboundSessionMaker.minConnectedRouters =
conf->router.m_minConnectedRouters;
_outboundSessionMaker.maxConnectedRouters = conf->router.m_maxConnectedRouters;
_outboundSessionMaker.minConnectedRouters = conf->router.m_minConnectedRouters;
encryption_keyfile = conf->router.m_dataDir / our_enc_key_filename;
our_rc_file = conf->router.m_dataDir / our_rc_filename;
transport_keyfile = conf->router.m_dataDir / our_transport_key_filename;
addrInfo = conf->router.m_addrInfo;
publicOverride = conf->router.m_publicOverride;
ip4addr = conf->router.m_ip4addr;
our_rc_file = conf->router.m_dataDir / our_rc_filename;
transport_keyfile = conf->router.m_dataDir / our_transport_key_filename;
addrInfo = conf->router.m_addrInfo;
publicOverride = conf->router.m_publicOverride;
ip4addr = conf->router.m_ip4addr;
RouterContact::BlockBogons = conf->router.m_blockBogons;
@ -414,17 +413,17 @@ namespace llarp
lokidRPCPassword = conf->lokid.lokidRPCPassword;
// TODO: add config flag for "is service node"
if(conf->links.m_InboundLinks.size())
if (conf->links.m_InboundLinks.size())
{
m_isServiceNode = true;
}
std::set<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());
@ -581,7 +581,7 @@ namespace llarp
// API config
enableRPCServer = conf->api.m_enableRPCServer;
rpcBindAddr = conf->api.m_rpcBindAddr;
rpcBindAddr = conf->api.m_rpcBindAddr;
// Services config
for (const auto& service : conf->services.services)
@ -1228,15 +1228,13 @@ namespace llarp
util::memFn(&AbstractRouter::rc, this),
util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this),
util::memFn(&AbstractRouter::Sign, this),
util::memFn(&IOutboundSessionMaker::OnSessionEstablished,
&_outboundSessionMaker),
util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker),
util::memFn(&AbstractRouter::CheckRenegotiateValid, this),
util::memFn(&IOutboundSessionMaker::OnConnectTimeout,
&_outboundSessionMaker),
util::memFn(&IOutboundSessionMaker::OnConnectTimeout, &_outboundSessionMaker),
util::memFn(&AbstractRouter::SessionClosed, this),
util::memFn(&AbstractRouter::PumpLL, this));
if(!link)
if (!link)
return false;
const auto afs = {AF_INET, AF_INET6};

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

@ -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,11 +97,12 @@ namespace llarp
}
void
LogContext::Initialize(LogLevel level,
LogType type,
const std::string& file,
const std::string& nickname,
std::shared_ptr<thread::ThreadPool> threadpool)
LogContext::Initialize(
LogLevel level,
LogType type,
const std::string& file,
const std::string& nickname,
std::shared_ptr<thread::ThreadPool> threadpool)
{
SetLogLevel(level);
nodeName = nickname;
@ -112,8 +117,8 @@ namespace llarp
logfile = ::fopen(file.c_str(), "a");
if (not logfile)
{
throw std::runtime_error(stringify(
"could not open logfile ", file, ", errno: ", strerror(errno)));
throw std::runtime_error(
stringify("could not open logfile ", file, ", errno: ", strerror(errno)));
}
}
@ -129,7 +134,7 @@ namespace llarp
std::cout << std::flush;
LogContext::Instance().logStream =
std::make_unique< FileLogStream >(threadpool, logfile, 100ms, true);
std::make_unique<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,11 +52,12 @@ namespace llarp
/// @param nickname is a tag to add to each log statement
/// @param threadpool is a threadpool where I/O can offloaded
void
Initialize(LogLevel level,
LogType type,
const std::string& file,
const std::string& nickname,
std::shared_ptr<thread::ThreadPool> threadpool);
Initialize(
LogLevel level,
LogType type,
const std::string& file,
const std::string& nickname,
std::shared_ptr<thread::ThreadPool> threadpool);
};
void

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