formatting

pull/2232/head
dr7ana 4 months ago
parent 2d3e68a759
commit b733415e68

@ -10,7 +10,7 @@ AllowShortCaseLabelsOnASingleLine: 'false'
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: 'false'
AllowShortLoopsOnASingleLine: 'false'
ColumnLimit: 100
ColumnLimit: 120
KeepEmptyLinesAtTheStartOfBlocks: 'false'
NamespaceIndentation: All
PenaltyBreakString: '3'

@ -42,8 +42,7 @@ bootstrap URLs.
int main(int argc, char* argv[])
{
const std::unordered_map<std::string, std::string> bootstrap_urls = {
{"lokinet", "https://seed.lokinet.org/lokinet.signed"},
{"testnet", "https://seed.lokinet.org/testnet.signed"}};
{"lokinet", "https://seed.lokinet.org/lokinet.signed"}, {"testnet", "https://seed.lokinet.org/testnet.signed"}};
std::string bootstrap_url = bootstrap_urls.at("lokinet");
fs::path outputfile{llarp::GetDefaultBootstrap()};
@ -75,8 +74,7 @@ int main(int argc, char* argv[])
std::cout << "fetching " << bootstrap_url << std::endl;
cpr::Response resp =
#ifdef _WIN32
cpr::Get(
cpr::Url{bootstrap_url}, cpr::Header{{"User-Agent", std::string{llarp::VERSION_FULL}}});
cpr::Get(cpr::Url{bootstrap_url}, cpr::Header{{"User-Agent", std::string{llarp::VERSION_FULL}}});
#else
cpr::Get(
cpr::Url{bootstrap_url},
@ -85,8 +83,7 @@ int main(int argc, char* argv[])
#endif
if (resp.status_code != 200)
{
return fail(
"failed to fetch '" + bootstrap_url + "' HTTP " + std::to_string(resp.status_code));
return fail("failed to fetch '" + bootstrap_url + "' HTTP " + std::to_string(resp.status_code));
}
const auto& data = resp.text;

@ -103,33 +103,23 @@ int main(int argc, char* argv[])
// flags: boolean values in command_line_options struct
cli.add_flag("-v,--verbose", options.verbose, "Verbose");
cli.add_flag(
"--add,--up", options.vpnUp, "Map VPN connection to exit node [--up is deprecated]");
cli.add_flag(
"--remove,--down",
options.vpnDown,
"Unmap VPN connection to exit node [--down is deprecated]");
cli.add_flag("--add,--up", options.vpnUp, "Map VPN connection to exit node [--up is deprecated]");
cli.add_flag("--remove,--down", options.vpnDown, "Unmap VPN connection to exit node [--down is deprecated]");
cli.add_flag("--status", options.printStatus, "Print VPN status and exit");
cli.add_flag("-k,--kill", options.killDaemon, "Kill lokinet daemon");
// options: string values in command_line_options struct
cli.add_option("--exit", options.exitAddress, "Specify exit node address")
->capture_default_str();
cli.add_option("--exit", options.exitAddress, "Specify exit node address")->capture_default_str();
cli.add_option("--endpoint", options.endpoint, "Endpoint to use")->capture_default_str();
cli.add_option("--token,--auth", options.token, "Exit auth token to use")
->capture_default_str();
cli.add_option("--token,--auth", options.token, "Exit auth token to use")->capture_default_str();
cli.add_option("--range", options.range, "IP range to map exit to")->capture_default_str();
cli.add_option(
"--swap", options.swapExits, "Exit addresses to swap mapped connection to [old] [new]")
cli.add_option("--swap", options.swapExits, "Exit addresses to swap mapped connection to [old] [new]")
->expected(2)
->capture_default_str();
// options: oxenmq values in command_line_options struct
cli.add_option("--rpc", options.rpc, "Specify RPC URL for lokinet")->capture_default_str();
cli.add_option(
"--log-level",
options.logLevel,
"Log verbosity level, see log levels for accepted values")
cli.add_option("--log-level", options.logLevel, "Log verbosity level, see log levels for accepted values")
->type_name("LEVEL")
->capture_default_str();
@ -156,8 +146,8 @@ int main(int argc, char* argv[])
cli.exit(e);
};
int numCommands = options.vpnUp + options.vpnDown + options.printStatus + options.killDaemon
+ (not options.swapExits.empty());
int numCommands =
options.vpnUp + options.vpnDown + options.printStatus + options.killDaemon + (not options.swapExits.empty());
switch (numCommands)
{
@ -166,8 +156,7 @@ int main(int argc, char* argv[])
case 1:
break;
default:
return exit_error(
3, "Only one of --add/--remove/--swap/--status/--kill may be specified");
return exit_error(3, "Only one of --add/--remove/--swap/--status/--kill may be specified");
}
if (options.vpnUp and options.exitAddress.empty())
@ -204,8 +193,7 @@ int main(int argc, char* argv[])
if (not maybe_halt)
return exit_error("Call to llarp.halt failed");
if (auto err_it = maybe_halt->find("error");
err_it != maybe_halt->end() and not err_it.value().is_null())
if (auto err_it = maybe_halt->find("error"); err_it != maybe_halt->end() and not err_it.value().is_null())
{
return exit_error("{}", err_it.value().dump());
}
@ -220,8 +208,7 @@ int main(int argc, char* argv[])
try
{
const auto& ep =
maybe_status->at("result").at("services").at(options.endpoint).at("exitMap");
const auto& ep = maybe_status->at("result").at("services").at(options.endpoint).at("exitMap");
if (ep.empty())
{
@ -251,8 +238,7 @@ int main(int argc, char* argv[])
if (not maybe_swap)
return exit_error("Failed to swap exit node connections");
if (auto err_it = maybe_swap->find("error");
err_it != maybe_swap->end() and not err_it.value().is_null())
if (auto err_it = maybe_swap->find("error"); err_it != maybe_swap->end() and not err_it.value().is_null())
{
return exit_error("{}", err_it.value().dump());
}
@ -269,8 +255,7 @@ int main(int argc, char* argv[])
if (not maybe_result)
return exit_error("Could not add exit");
if (auto err_it = maybe_result->find("error");
err_it != maybe_result->end() and not err_it.value().is_null())
if (auto err_it = maybe_result->find("error"); err_it != maybe_result->end() and not err_it.value().is_null())
{
return exit_error("{}", err_it.value().dump());
}
@ -286,8 +271,7 @@ int main(int argc, char* argv[])
if (not maybe_down)
return exit_error("Failed to unmap exit node connection");
if (auto err_it = maybe_down->find("error");
err_it != maybe_down->end() and not err_it.value().is_null())
if (auto err_it = maybe_down->find("error"); err_it != maybe_down->end() and not err_it.value().is_null())
{
return exit_error("{}", err_it.value().dump());
}

@ -60,8 +60,7 @@ namespace
// operational function definitions
int lokinet_main(int, char**);
void handle_signal(int sig);
static void run_main_context(
std::optional<fs::path> confFile, const llarp::RuntimeOptions opts);
static void run_main_context(std::optional<fs::path> confFile, const llarp::RuntimeOptions opts);
// variable declarations
static auto logcat = llarp::log::Cat("main");
@ -75,8 +74,7 @@ namespace
if (ctx)
ctx->loop->call([sig] { ctx->HandleSignal(sig); });
else
std::cerr << "Received signal " << sig << ", but have no context yet. Ignoring!"
<< std::endl;
std::cerr << "Received signal " << sig << ", but have no context yet. Ignoring!" << std::endl;
}
// Windows specific code
@ -260,8 +258,7 @@ namespace
const auto flags =
(MINIDUMP_TYPE)(MiniDumpWithFullMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithHandleData | MiniDumpWithUnloadedModules | MiniDumpWithThreadInfo);
const std::string fname =
fmt::format("C:\\ProgramData\\lokinet\\crash-{}.dump", llarp::time_now_ms().count());
const std::string fname = fmt::format("C:\\ProgramData\\lokinet\\crash-{}.dump", llarp::time_now_ms().count());
HANDLE hDumpFile;
SYSTEMTIME stLocalTime;
@ -269,19 +266,12 @@ namespace
MINIDUMP_EXCEPTION_INFORMATION ExpParam{};
hDumpFile = CreateFile(
fname.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ,
0,
CREATE_ALWAYS,
0,
0);
fname.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
ExpParam.ExceptionPointers = pExceptionPointers;
ExpParam.ClientPointers = TRUE;
MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, flags, &ExpParam, NULL, NULL);
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, flags, &ExpParam, NULL, NULL);
return 1;
}
@ -295,8 +285,7 @@ namespace
case SERVICE_CONTROL_STOP:
// tell service we are stopping
llarp::log::debug(logcat, "Windows service controller gave SERVICE_CONTROL_STOP");
llarp::sys::service_manager->system_changed_our_state(
llarp::sys::ServiceState::Stopping);
llarp::sys::service_manager->system_changed_our_state(llarp::sys::ServiceState::Stopping);
handle_signal(SIGINT);
return;
@ -359,15 +348,11 @@ namespace
// flags: boolean values in command_line_options struct
cli.add_flag("--version", options.version, "Lokinet version");
cli.add_flag("-g,--generate", options.generate, "Generate default configuration and exit");
cli.add_flag(
"-r,--router",
options.router,
"Run lokinet in routing mode instead of client-only mode");
cli.add_flag("-r,--router", options.router, "Run lokinet in routing mode instead of client-only mode");
cli.add_flag("-f,--force", options.overwrite, "Force writing config even if file exists");
// options: string
cli.add_option(
"config,--config", options.configPath, "Path to lokinet.ini configuration file")
cli.add_option("config,--config", options.configPath, "Path to lokinet.ini configuration file")
->capture_default_str();
if constexpr (llarp::platform::is_windows)
@ -442,8 +427,7 @@ namespace
}
catch (std::exception& ex)
{
llarp::log::error(
logcat, "cannot generate config at {}: {}", *configFile, ex.what());
llarp::log::error(logcat, "cannot generate config at {}: {}", *configFile, ex.what());
return 1;
}
}
@ -459,8 +443,7 @@ namespace
}
catch (std::exception& ex)
{
llarp::log::error(
logcat, "cannot check if ", *configFile, " exists: ", ex.what());
llarp::log::error(logcat, "cannot check if ", *configFile, " exists: ", ex.what());
return 1;
}
}
@ -470,10 +453,7 @@ namespace
try
{
llarp::ensure_config(
llarp::GetDefaultDataDir(),
llarp::GetDefaultConfigPath(),
options.overwrite,
opts.isSNode);
llarp::GetDefaultDataDir(), llarp::GetDefaultConfigPath(), options.overwrite, opts.isSNode);
}
catch (std::exception& ex)
{
@ -648,8 +628,7 @@ int main(int argc, char* argv[])
}
else
{
llarp::log::critical(
logcat, "Error launching service: {}", std::system_category().message(error));
llarp::log::critical(logcat, "Error launching service: {}", std::system_category().message(error));
return 1;
}
#endif

@ -27,8 +27,7 @@ extern "C"
/// set a custom logger function; it is safe (and often desirable) to call this before calling
/// initializing lokinet via lokinet_context_new.
void EXPORT
lokinet_set_syncing_logger(lokinet_logger_func func, lokinet_logger_sync sync, void* context);
void EXPORT lokinet_set_syncing_logger(lokinet_logger_func func, lokinet_logger_sync sync, void* context);
/// shortcut for calling `lokinet_set_syncing_logger` with a NULL sync
void EXPORT lokinet_set_logger(lokinet_logger_func func, void* context);

@ -36,10 +36,7 @@ extern "C"
/// do a srv lookup on host for service
/// caller MUST call lokinet_srv_lookup_done when they are done handling the result
int EXPORT lokinet_srv_lookup(
char* host,
char* service,
struct lokinet_srv_lookup_result* result,
struct lokinet_context* ctx);
char* host, char* service, struct lokinet_srv_lookup_result* result, struct lokinet_context* ctx);
/// a hook function to handle each srv record in a srv lookup result
/// passes in NULL when we are at the end of iteration
@ -50,8 +47,8 @@ extern "C"
/// iterate over each srv record in a lookup result
/// user is passes into hook and called for each result and then with NULL as the result on the
/// end of iteration
void EXPORT lokinet_for_each_srv_record(
struct lokinet_srv_lookup_result* result, lokinet_srv_record_iterator iter, void* user);
void EXPORT
lokinet_for_each_srv_record(struct lokinet_srv_lookup_result* result, lokinet_srv_record_iterator iter, void* user);
/// free internal members of a srv lookup result after use of the result
void EXPORT lokinet_srv_lookup_done(struct lokinet_srv_lookup_result* result);

@ -41,8 +41,8 @@ extern "C"
/// set stream accepter filter
/// passes user parameter into stream filter as void *
/// returns stream id
int EXPORT lokinet_inbound_stream_filter(
lokinet_stream_filter acceptFilter, void* user, struct lokinet_context* context);
int EXPORT
lokinet_inbound_stream_filter(lokinet_stream_filter acceptFilter, void* user, struct lokinet_context* context);
/// simple stream acceptor
/// simple variant of lokinet_inbound_stream_filter that maps port to localhost:port

@ -27,14 +27,10 @@ extern "C"
/// flow acceptor hook, return 0 success, return nonzero with errno on failure
typedef int (*lokinet_udp_flow_filter)(
void* userdata,
const struct lokinet_udp_flowinfo* remote_address,
void** flow_userdata,
int* timeout_seconds);
void* userdata, const struct lokinet_udp_flowinfo* remote_address, void** flow_userdata, int* timeout_seconds);
/// callback to make a new outbound flow
typedef void(lokinet_udp_create_flow_func)(
void* userdata, void** flow_userdata, int* timeout_seconds);
typedef void(lokinet_udp_create_flow_func)(void* userdata, void** flow_userdata, int* timeout_seconds);
/// hook function for handling packets
typedef void (*lokinet_udp_flow_recv_func)(
@ -100,10 +96,7 @@ extern "C"
///
/// @returns 0 on success and non zero errno on fail
int EXPORT lokinet_udp_flow_send(
const struct lokinet_udp_flowinfo* remote,
const void* ptr,
size_t len,
struct lokinet_context* ctx);
const struct lokinet_udp_flowinfo* remote, const void* ptr, size_t len, struct lokinet_context* ctx);
/// @brief close a bound udp socket
/// closes all flows immediately

@ -6,28 +6,23 @@
extern "C"
{
JNIEXPORT jobject JNICALL
Java_network_loki_lokinet_LokinetConfig_Obtain(JNIEnv* env, jclass, jstring dataDir)
JNIEXPORT jobject JNICALL Java_network_loki_lokinet_LokinetConfig_Obtain(JNIEnv* env, jclass, jstring dataDir)
{
auto conf = VisitStringAsStringView<llarp::Config*>(
env, dataDir, [](std::string_view val) -> llarp::Config* {
return new llarp::Config{val};
});
env, dataDir, [](std::string_view val) -> llarp::Config* { return new llarp::Config{val}; });
if (conf == nullptr)
return nullptr;
return env->NewDirectByteBuffer(conf, sizeof(llarp::Config));
}
JNIEXPORT void JNICALL
Java_network_loki_lokinet_LokinetConfig_Free(JNIEnv* env, jclass, jobject buf)
JNIEXPORT void JNICALL Java_network_loki_lokinet_LokinetConfig_Free(JNIEnv* env, jclass, jobject buf)
{
auto ptr = FromBuffer<llarp::Config>(env, buf);
delete ptr;
}
JNIEXPORT jboolean JNICALL
Java_network_loki_lokinet_LokinetConfig_Load(JNIEnv* env, jobject self)
JNIEXPORT jboolean JNICALL Java_network_loki_lokinet_LokinetConfig_Load(JNIEnv* env, jobject self)
{
auto conf = GetImpl<llarp::Config>(env, self);
if (conf == nullptr)
@ -39,8 +34,7 @@ extern "C"
return JNI_FALSE;
}
JNIEXPORT jboolean JNICALL
Java_network_loki_lokinet_LokinetConfig_Save(JNIEnv* env, jobject self)
JNIEXPORT jboolean JNICALL Java_network_loki_lokinet_LokinetConfig_Save(JNIEnv* env, jobject self)
{
auto conf = GetImpl<llarp::Config>(env, self);
if (conf == nullptr)

@ -15,8 +15,7 @@ extern "C"
return env->NewDirectByteBuffer(ptr, sizeof(llarp::Context));
}
JNIEXPORT void JNICALL
Java_network_loki_lokinet_LokinetDaemon_Free(JNIEnv* env, jclass, jobject buf)
JNIEXPORT void JNICALL Java_network_loki_lokinet_LokinetDaemon_Free(JNIEnv* env, jclass, jobject buf)
{
auto ptr = FromBuffer<llarp::Context>(env, buf);
delete ptr;
@ -44,8 +43,7 @@ extern "C"
return JNI_TRUE;
}
JNIEXPORT jint JNICALL
Java_network_loki_lokinet_LokinetDaemon_Mainloop(JNIEnv* env, jobject self)
JNIEXPORT jint JNICALL Java_network_loki_lokinet_LokinetDaemon_Mainloop(JNIEnv* env, jobject self)
{
auto ptr = GetImpl<llarp::Context>(env, self);
if (ptr == nullptr)
@ -54,15 +52,13 @@ extern "C"
return ptr->Run(opts);
}
JNIEXPORT jboolean JNICALL
Java_network_loki_lokinet_LokinetDaemon_IsRunning(JNIEnv* env, jobject self)
JNIEXPORT jboolean JNICALL Java_network_loki_lokinet_LokinetDaemon_IsRunning(JNIEnv* env, jobject self)
{
auto ptr = GetImpl<llarp::Context>(env, self);
return (ptr != nullptr && ptr->IsUp()) ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jboolean JNICALL
Java_network_loki_lokinet_LokinetDaemon_Stop(JNIEnv* env, jobject self)
JNIEXPORT jboolean JNICALL Java_network_loki_lokinet_LokinetDaemon_Stop(JNIEnv* env, jobject self)
{
auto ptr = GetImpl<llarp::Context>(env, self);
if (ptr == nullptr)
@ -74,23 +70,20 @@ extern "C"
return ptr->IsUp() ? JNI_FALSE : JNI_TRUE;
}
JNIEXPORT void JNICALL
Java_network_loki_lokinet_LokinetDaemon_InjectVPNFD(JNIEnv* env, jobject self)
JNIEXPORT void JNICALL Java_network_loki_lokinet_LokinetDaemon_InjectVPNFD(JNIEnv* env, jobject self)
{
if (auto ptr = GetImpl<llarp::Context>(env, self))
ptr->androidFD = GetObjectMemberAsInt<int>(env, self, "m_FD");
}
JNIEXPORT jint JNICALL
Java_network_loki_lokinet_LokinetDaemon_GetUDPSocket(JNIEnv* env, jobject self)
JNIEXPORT jint JNICALL Java_network_loki_lokinet_LokinetDaemon_GetUDPSocket(JNIEnv* env, jobject self)
{
if (auto ptr = GetImpl<llarp::Context>(env, self); ptr and ptr->router)
return ptr->router->outbound_socket();
return -1;
}
JNIEXPORT jstring JNICALL
Java_network_loki_lokinet_LokinetDaemon_DetectFreeRange(JNIEnv* env, jclass)
JNIEXPORT jstring JNICALL Java_network_loki_lokinet_LokinetDaemon_DetectFreeRange(JNIEnv* env, jclass)
{
std::string rangestr{};
if (auto maybe = llarp::net::Platform::Default_ptr()->FindFreeRange())
@ -100,8 +93,7 @@ extern "C"
return env->NewStringUTF(rangestr.c_str());
}
JNIEXPORT jstring JNICALL
Java_network_loki_lokinet_LokinetDaemon_DumpStatus(JNIEnv* env, jobject self)
JNIEXPORT jstring JNICALL Java_network_loki_lokinet_LokinetDaemon_DumpStatus(JNIEnv* env, jobject self)
{
std::string status{};
if (auto ptr = GetImpl<llarp::Context>(env, self))

@ -13,8 +13,7 @@ extern "C"
* Method: Obtain
* Signature: (Ljava/lang/String;)Ljava/nio/ByteBuffer;
*/
JNIEXPORT jobject JNICALL
Java_network_loki_lokinet_LokinetConfig_Obtain(JNIEnv*, jclass, jstring);
JNIEXPORT jobject JNICALL Java_network_loki_lokinet_LokinetConfig_Obtain(JNIEnv*, jclass, jstring);
/*
* Class: network_loki_lokinet_LokinetConfig
@ -42,8 +41,8 @@ extern "C"
* Method: AddDefaultValue
* Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_network_loki_lokinet_LokinetConfig_AddDefaultValue(
JNIEnv*, jobject, jstring, jstring, jstring);
JNIEXPORT void JNICALL
Java_network_loki_lokinet_LokinetConfig_AddDefaultValue(JNIEnv*, jobject, jstring, jstring, jstring);
#ifdef __cplusplus
}

@ -27,8 +27,7 @@ extern "C"
* Method: Configure
* Signature: (Lnetwork/loki/lokinet/LokinetConfig;)Z
*/
JNIEXPORT jboolean JNICALL
Java_network_loki_lokinet_LokinetDaemon_Configure(JNIEnv*, jobject, jobject);
JNIEXPORT jboolean JNICALL Java_network_loki_lokinet_LokinetDaemon_Configure(JNIEnv*, jobject, jobject);
/*
* Class: network_loki_lokinet_LokinetDaemon
@ -70,8 +69,7 @@ extern "C"
* Method: DetectFreeRange
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_network_loki_lokinet_LokinetDaemon_DetectFreeRange(JNIEnv*, jclass);
JNIEXPORT jstring JNICALL Java_network_loki_lokinet_LokinetDaemon_DetectFreeRange(JNIEnv*, jclass);
/*
* Class: network_loki_lokinet_LokinetDaemon

@ -48,8 +48,7 @@ extern "C"
* Method: WritePkt
* Signature: (Ljava/nio/ByteBuffer;)Z
*/
JNIEXPORT jboolean JNICALL
Java_network_loki_lokinet_LokinetVPN_WritePkt(JNIEnv*, jobject, jobject);
JNIEXPORT jboolean JNICALL Java_network_loki_lokinet_LokinetVPN_WritePkt(JNIEnv*, jobject, jobject);
/*
* Class: network_loki_lokinet_LokinetVPN

@ -13,16 +13,14 @@ extern "C"
* Method: getABICompiledWith
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_network_loki_lokinet_Lokinet_1JNI_getABICompiledWith(JNIEnv*, jclass);
JNIEXPORT jstring JNICALL Java_network_loki_lokinet_Lokinet_1JNI_getABICompiledWith(JNIEnv*, jclass);
/*
* Class: network_loki_lokinet_Lokinet_JNI
* Method: startLokinet
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_network_loki_lokinet_Lokinet_1JNI_startLokinet(JNIEnv*, jclass, jstring);
JNIEXPORT jstring JNICALL Java_network_loki_lokinet_Lokinet_1JNI_startLokinet(JNIEnv*, jclass, jstring);
JNIEXPORT jstring JNICALL Java_network_loki_lokinet_Lokinet_1JNI_getIfAddr(JNIEnv*, jclass);
@ -35,16 +33,14 @@ extern "C"
*/
JNIEXPORT void JNICALL Java_network_loki_lokinet_Lokinet_1JNI_stopLokinet(JNIEnv*, jclass);
JNIEXPORT void JNICALL
Java_network_loki_lokinet_Lokinet_1JNI_setVPNFileDescriptor(JNIEnv*, jclass, jint, jint);
JNIEXPORT void JNICALL Java_network_loki_lokinet_Lokinet_1JNI_setVPNFileDescriptor(JNIEnv*, jclass, jint, jint);
/*
* Class: network_loki_lokinet_Lokinet_JNI
* Method: onNetworkStateChanged
* Signature: (Z)V
*/
JNIEXPORT void JNICALL
Java_network_loki_lokinet_Lokinet_1JNI_onNetworkStateChanged(JNIEnv*, jclass, jboolean);
JNIEXPORT void JNICALL Java_network_loki_lokinet_Lokinet_1JNI_onNetworkStateChanged(JNIEnv*, jclass, jboolean);
#ifdef __cplusplus
}

@ -83,13 +83,7 @@ static int netlink_send(int p_socket, int p_request)
struct sockaddr_nl l_addr;
memset(&l_addr, 0, sizeof(l_addr));
l_addr.nl_family = AF_NETLINK;
return (sendto(
p_socket,
&l_data.m_hdr,
l_data.m_hdr.nlmsg_len,
0,
(struct sockaddr*)&l_addr,
sizeof(l_addr)));
return (sendto(p_socket, &l_data.m_hdr, l_data.m_hdr.nlmsg_len, 0, (struct sockaddr*)&l_addr, sizeof(l_addr)));
}
static int netlink_recv(int p_socket, void* p_buffer, size_t p_len)
@ -257,11 +251,9 @@ static size_t calcAddrLen(sa_family_t p_family, int p_dataSize)
case AF_INET6:
return sizeof(struct sockaddr_in6);
case AF_PACKET:
return maxSize(
sizeof(struct sockaddr_ll), offsetof(struct sockaddr_ll, sll_addr) + p_dataSize);
return maxSize(sizeof(struct sockaddr_ll), offsetof(struct sockaddr_ll, sll_addr) + p_dataSize);
default:
return maxSize(
sizeof(struct sockaddr), offsetof(struct sockaddr, sa_data) + p_dataSize);
return maxSize(sizeof(struct sockaddr), offsetof(struct sockaddr, sa_data) + p_dataSize);
}
}
@ -335,8 +327,7 @@ static int interpretLink(struct nlmsghdr* p_hdr, struct ifaddrs** p_resultList)
}
}
struct ifaddrs* l_entry =
malloc(sizeof(struct ifaddrs) + sizeof(int) + l_nameSize + l_addrSize + l_dataSize);
struct ifaddrs* l_entry = malloc(sizeof(struct ifaddrs) + sizeof(int) + l_nameSize + l_addrSize + l_dataSize);
if (l_entry == NULL)
{
return -1;
@ -444,8 +435,7 @@ static int interpretAddr(struct nlmsghdr* p_hdr, struct ifaddrs** p_resultList,
{
case IFA_ADDRESS:
case IFA_LOCAL:
if ((l_info->ifa_family == AF_INET || l_info->ifa_family == AF_INET6)
&& !l_addedNetmask)
if ((l_info->ifa_family == AF_INET || l_info->ifa_family == AF_INET6) && !l_addedNetmask)
{ // make room for netmask
l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize));
l_addedNetmask = 1;
@ -490,8 +480,7 @@ static int interpretAddr(struct nlmsghdr* p_hdr, struct ifaddrs** p_resultList,
case IFA_LOCAL:
{
size_t l_addrLen = calcAddrLen(l_info->ifa_family, l_rtaDataSize);
makeSockaddr(
l_info->ifa_family, (struct sockaddr*)l_addr, l_rtaData, l_rtaDataSize);
makeSockaddr(l_info->ifa_family, (struct sockaddr*)l_addr, l_rtaData, l_rtaDataSize);
if (l_info->ifa_family == AF_INET6)
{
if (IN6_IS_ADDR_LINKLOCAL((struct in6_addr*)l_rtaData)
@ -538,12 +527,10 @@ static int interpretAddr(struct nlmsghdr* p_hdr, struct ifaddrs** p_resultList,
}
}
if (l_entry->ifa_addr
&& (l_entry->ifa_addr->sa_family == AF_INET || l_entry->ifa_addr->sa_family == AF_INET6))
if (l_entry->ifa_addr && (l_entry->ifa_addr->sa_family == AF_INET || l_entry->ifa_addr->sa_family == AF_INET6))
{
unsigned l_maxPrefix = (l_entry->ifa_addr->sa_family == AF_INET ? 32 : 128);
unsigned l_prefix =
(l_info->ifa_prefixlen > l_maxPrefix ? l_maxPrefix : l_info->ifa_prefixlen);
unsigned l_prefix = (l_info->ifa_prefixlen > l_maxPrefix ? l_maxPrefix : l_info->ifa_prefixlen);
char l_mask[16] = {0};
unsigned i;
for (i = 0; i < (l_prefix / 8); ++i)
@ -555,8 +542,7 @@ static int interpretAddr(struct nlmsghdr* p_hdr, struct ifaddrs** p_resultList,
l_mask[i] = 0xff << (8 - (l_prefix % 8));
}
makeSockaddr(
l_entry->ifa_addr->sa_family, (struct sockaddr*)l_addr, l_mask, l_maxPrefix / 8);
makeSockaddr(l_entry->ifa_addr->sa_family, (struct sockaddr*)l_addr, l_mask, l_maxPrefix / 8);
l_entry->ifa_netmask = (struct sockaddr*)l_addr;
}
@ -572,8 +558,7 @@ static int interpretLinks(int p_socket, NetlinkList* p_netlinkList, struct ifadd
{
unsigned int l_nlsize = p_netlinkList->m_size;
struct nlmsghdr* l_hdr;
for (l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize);
l_hdr = NLMSG_NEXT(l_hdr, l_nlsize))
for (l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize))
{
if ((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket)
{
@ -598,16 +583,14 @@ static int interpretLinks(int p_socket, NetlinkList* p_netlinkList, struct ifadd
return l_numLinks;
}
static int interpretAddrs(
int p_socket, NetlinkList* p_netlinkList, struct ifaddrs** p_resultList, int p_numLinks)
static int interpretAddrs(int p_socket, NetlinkList* p_netlinkList, struct ifaddrs** p_resultList, int p_numLinks)
{
pid_t l_pid = getpid();
for (; p_netlinkList; p_netlinkList = p_netlinkList->m_next)
{
unsigned int l_nlsize = p_netlinkList->m_size;
struct nlmsghdr* l_hdr;
for (l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize);
l_hdr = NLMSG_NEXT(l_hdr, l_nlsize))
for (l_hdr = p_netlinkList->m_data; NLMSG_OK(l_hdr, l_nlsize); l_hdr = NLMSG_NEXT(l_hdr, l_nlsize))
{
if ((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket)
{

@ -7,11 +7,7 @@ NSString* error_domain = @"org.lokinet";
// Receiving an incoming packet, presumably from libunbound. NB: this is called from the libuv
// event loop.
static void on_request(
uv_udp_t* socket,
ssize_t nread,
const uv_buf_t* buf,
const struct sockaddr* addr,
unsigned flags)
uv_udp_t* socket, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags)
{
(void)flags;
if (nread < 0)
@ -98,8 +94,7 @@ static void alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* b
int ret = uv_udp_bind(&request_socket, (const struct sockaddr*)&recv_addr, UV_UDP_REUSEADDR);
if (ret < 0)
{
NSString* errstr =
[NSString stringWithFormat:@"Failed to start DNS trampoline: %s", uv_strerror(ret)];
NSString* errstr = [NSString stringWithFormat:@"Failed to start DNS trampoline: %s", uv_strerror(ret)];
NSError* err = [NSError errorWithDomain:error_domain code:ret userInfo:@{@"Error": errstr}];
NSLog(@"%@", err);
return completionHandler(err);
@ -132,13 +127,8 @@ static void alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* b
}
uv_udp_send_t* uvsend = malloc(sizeof(uv_udp_send_t));
uvsend->data = (__bridge_retained void*)datagrams;
int ret = uv_udp_send(
uvsend,
&strongSelf->request_socket,
buffers,
buf_count,
&strongSelf->reply_addr,
on_sent);
int ret =
uv_udp_send(uvsend, &strongSelf->request_socket, buffers, buf_count, &strongSelf->reply_addr, on_sent);
free(buffers);
if (ret < 0)
NSLog(@"Error returning DNS responses to unbound: %s", uv_strerror(ret));

@ -22,11 +22,9 @@
- (void)startTunnelWithOptions:(NSDictionary<NSString*, NSObject*>*)options
completionHandler:(void (^)(NSError* error))completionHandler;
- (void)stopTunnelWithReason:(NEProviderStopReason)reason
completionHandler:(void (^)(void))completionHandler;
- (void)stopTunnelWithReason:(NEProviderStopReason)reason completionHandler:(void (^)(void))completionHandler;
- (void)handleAppMessage:(NSData*)messageData
completionHandler:(void (^)(NSData* responseData))completionHandler;
- (void)handleAppMessage:(NSData*)messageData completionHandler:(void (^)(NSData* responseData))completionHandler;
- (void)readPackets;
@ -61,9 +59,8 @@ static void start_packet_reader(void* ctx)
static void add_ipv4_route(const char* addr, const char* netmask, void* ctx)
{
NSLog(@"Adding IPv4 route %s:%s to packet tunnel", addr, netmask);
NEIPv4Route* route =
[[NEIPv4Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
subnetMask:[NSString stringWithUTF8String:netmask]];
NEIPv4Route* route = [[NEIPv4Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
subnetMask:[NSString stringWithUTF8String:netmask]];
LLARPPacketTunnel* t = (__bridge LLARPPacketTunnel*)ctx;
for (NEIPv4Route* r in t->settings.IPv4Settings.includedRoutes)
@ -71,8 +68,7 @@ static void add_ipv4_route(const char* addr, const char* netmask, void* ctx)
[r.destinationSubnetMask isEqualToString:route.destinationSubnetMask])
return; // Already in the settings, nothing to add.
t->settings.IPv4Settings.includedRoutes =
[t->settings.IPv4Settings.includedRoutes arrayByAddingObject:route];
t->settings.IPv4Settings.includedRoutes = [t->settings.IPv4Settings.includedRoutes arrayByAddingObject:route];
[t updateNetworkSettings];
}
@ -80,13 +76,11 @@ static void add_ipv4_route(const char* addr, const char* netmask, void* ctx)
static void del_ipv4_route(const char* addr, const char* netmask, void* ctx)
{
NSLog(@"Removing IPv4 route %s:%s to packet tunnel", addr, netmask);
NEIPv4Route* route =
[[NEIPv4Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
subnetMask:[NSString stringWithUTF8String:netmask]];
NEIPv4Route* route = [[NEIPv4Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
subnetMask:[NSString stringWithUTF8String:netmask]];
LLARPPacketTunnel* t = (__bridge LLARPPacketTunnel*)ctx;
NSMutableArray<NEIPv4Route*>* routes =
[NSMutableArray arrayWithArray:t->settings.IPv4Settings.includedRoutes];
NSMutableArray<NEIPv4Route*>* routes = [NSMutableArray arrayWithArray:t->settings.IPv4Settings.includedRoutes];
for (size_t i = 0; i < routes.count; i++)
{
if ([routes[i].destinationAddress isEqualToString:route.destinationAddress] &&
@ -106,9 +100,8 @@ static void del_ipv4_route(const char* addr, const char* netmask, void* ctx)
static void add_ipv6_route(const char* addr, int prefix, void* ctx)
{
NEIPv6Route* route =
[[NEIPv6Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
networkPrefixLength:[NSNumber numberWithInt:prefix]];
NEIPv6Route* route = [[NEIPv6Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
networkPrefixLength:[NSNumber numberWithInt:prefix]];
LLARPPacketTunnel* t = (__bridge LLARPPacketTunnel*)ctx;
for (NEIPv6Route* r in t->settings.IPv6Settings.includedRoutes)
@ -116,26 +109,22 @@ static void add_ipv6_route(const char* addr, int prefix, void* ctx)
[r.destinationNetworkPrefixLength isEqualToNumber:route.destinationNetworkPrefixLength])
return; // Already in the settings, nothing to add.
t->settings.IPv6Settings.includedRoutes =
[t->settings.IPv6Settings.includedRoutes arrayByAddingObject:route];
t->settings.IPv6Settings.includedRoutes = [t->settings.IPv6Settings.includedRoutes arrayByAddingObject:route];
[t updateNetworkSettings];
}
static void del_ipv6_route(const char* addr, int prefix, void* ctx)
{
NEIPv6Route* route =
[[NEIPv6Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
networkPrefixLength:[NSNumber numberWithInt:prefix]];
NEIPv6Route* route = [[NEIPv6Route alloc] initWithDestinationAddress:[NSString stringWithUTF8String:addr]
networkPrefixLength:[NSNumber numberWithInt:prefix]];
LLARPPacketTunnel* t = (__bridge LLARPPacketTunnel*)ctx;
NSMutableArray<NEIPv6Route*>* routes =
[NSMutableArray arrayWithArray:t->settings.IPv6Settings.includedRoutes];
NSMutableArray<NEIPv6Route*>* routes = [NSMutableArray arrayWithArray:t->settings.IPv6Settings.includedRoutes];
for (size_t i = 0; i < routes.count; i++)
{
if ([routes[i].destinationAddress isEqualToString:route.destinationAddress] &&
[routes[i].destinationNetworkPrefixLength
isEqualToNumber:route.destinationNetworkPrefixLength])
[routes[i].destinationNetworkPrefixLength isEqualToNumber:route.destinationNetworkPrefixLength])
{
[routes removeObjectAtIndex:i];
i--;
@ -201,8 +190,7 @@ static void del_default_route(void* ctx)
- (void)startTunnelWithOptions:(NSDictionary<NSString*, NSObject*>*)options
completionHandler:(void (^)(NSError*))completionHandler
{
NSString* default_bootstrap = [NSBundle.mainBundle pathForResource:@"bootstrap"
ofType:@"signed"];
NSString* default_bootstrap = [NSBundle.mainBundle pathForResource:@"bootstrap" ofType:@"signed"];
NSString* home = NSHomeDirectory();
llarp_apple_config conf = {
@ -223,10 +211,9 @@ static void del_default_route(void* ctx)
lokinet = llarp_apple_init(&conf);
if (!lokinet)
{
NSError* init_failure =
[NSError errorWithDomain:error_domain
code:500
userInfo:@{@"Error": @"Failed to initialize lokinet"}];
NSError* init_failure = [NSError errorWithDomain:error_domain
code:500
userInfo:@{@"Error": @"Failed to initialize lokinet"}];
NSLog(@"%@", [init_failure localizedDescription]);
return completionHandler(init_failure);
}
@ -265,9 +252,8 @@ static void del_default_route(void* ctx)
NWHostEndpoint* upstreamdns_ep;
if (strlen(conf.upstream_dns))
upstreamdns_ep =
[NWHostEndpoint endpointWithHostname:[NSString stringWithUTF8String:conf.upstream_dns]
port:@(conf.upstream_dns_port).stringValue];
upstreamdns_ep = [NWHostEndpoint endpointWithHostname:[NSString stringWithUTF8String:conf.upstream_dns]
port:@(conf.upstream_dns_port).stringValue];
NEIPv4Settings* ipv4 = [[NEIPv4Settings alloc] initWithAddresses:@[ip] subnetMasks:@[mask]];
tun_route4 = [[NEIPv4Route alloc] initWithDestinationAddress:ip subnetMask:mask];
@ -276,10 +262,8 @@ static void del_default_route(void* ctx)
NSString* ip6 = [NSString stringWithUTF8String:conf.tunnel_ipv6_ip];
NSNumber* ip6_prefix = [NSNumber numberWithUnsignedInt:conf.tunnel_ipv6_prefix];
NEIPv6Settings* ipv6 = [[NEIPv6Settings alloc] initWithAddresses:@[ip6]
networkPrefixLengths:@[ip6_prefix]];
tun_route6 = [[NEIPv6Route alloc] initWithDestinationAddress:ip6
networkPrefixLength:ip6_prefix];
NEIPv6Settings* ipv6 = [[NEIPv6Settings alloc] initWithAddresses:@[ip6] networkPrefixLengths:@[ip6_prefix]];
tun_route6 = [[NEIPv6Route alloc] initWithDestinationAddress:ip6 networkPrefixLength:ip6_prefix];
ipv6.includedRoutes = @[tun_route6];
settings.IPv6Settings = ipv6;
@ -295,14 +279,12 @@ static void del_default_route(void* ctx)
if (!strongSelf)
return completionHandler(nil);
int start_ret =
llarp_apple_start(strongSelf->lokinet, (__bridge void*)strongSelf);
int start_ret = llarp_apple_start(strongSelf->lokinet, (__bridge void*)strongSelf);
if (start_ret != 0)
{
NSError* start_failure =
[NSError errorWithDomain:error_domain
code:start_ret
userInfo:@{@"Error": @"Failed to start lokinet"}];
NSError* start_failure = [NSError errorWithDomain:error_domain
code:start_ret
userInfo:@{@"Error": @"Failed to start lokinet"}];
NSLog(@"%@", start_failure);
lokinet = nil;
return completionHandler(start_failure);
@ -314,25 +296,22 @@ static void del_default_route(void* ctx)
upstreamdns_ep,
dns_tramp_ip,
dns_trampoline_port);
NWUDPSession* upstreamdns =
[strongSelf createUDPSessionThroughTunnelToEndpoint:upstreamdns_ep
fromEndpoint:nil];
NWUDPSession* upstreamdns = [strongSelf createUDPSessionThroughTunnelToEndpoint:upstreamdns_ep
fromEndpoint:nil];
strongSelf->dns_tramp = [LLARPDNSTrampoline alloc];
[strongSelf->dns_tramp
startWithUpstreamDns:upstreamdns
listenIp:dns_tramp_ip
listenPort:dns_trampoline_port
uvLoop:llarp_apple_get_uv_loop(strongSelf->lokinet)
completionHandler:^(NSError* error) {
if (error)
NSLog(@"Error starting dns trampoline: %@", error);
return completionHandler(error);
}];
[strongSelf->dns_tramp startWithUpstreamDns:upstreamdns
listenIp:dns_tramp_ip
listenPort:dns_trampoline_port
uvLoop:llarp_apple_get_uv_loop(strongSelf->lokinet)
completionHandler:^(NSError* error) {
if (error)
NSLog(@"Error starting dns trampoline: %@", error);
return completionHandler(error);
}];
}];
}
- (void)stopTunnelWithReason:(NEProviderStopReason)reason
completionHandler:(void (^)(void))completionHandler
- (void)stopTunnelWithReason:(NEProviderStopReason)reason completionHandler:(void (^)(void))completionHandler
{
if (lokinet)
{
@ -342,8 +321,7 @@ static void del_default_route(void* ctx)
completionHandler();
}
- (void)handleAppMessage:(NSData*)messageData
completionHandler:(void (^)(NSData* responseData))completionHandler
- (void)handleAppMessage:(NSData*)messageData completionHandler:(void (^)(NSData* responseData))completionHandler
{
NSData* response = [NSData dataWithBytesNoCopy:"ok" length:3 freeWhenDone:NO];
completionHandler(response);

@ -69,17 +69,14 @@ void* llarp_apple_init(llarp_apple_config* appleconf)
if (addr.size() > 15 || mask.size() > 15)
throw std::runtime_error{"Unexpected non-IPv4 tunnel range configured"};
std::strncpy(appleconf->tunnel_ipv4_ip, addr.c_str(), sizeof(appleconf->tunnel_ipv4_ip));
std::strncpy(
appleconf->tunnel_ipv4_netmask, mask.c_str(), sizeof(appleconf->tunnel_ipv4_netmask));
std::strncpy(appleconf->tunnel_ipv4_netmask, mask.c_str(), sizeof(appleconf->tunnel_ipv4_netmask));
// TODO: in the future we want to do this properly with our pubkey (see issue #1705), but
// that's going to take a bit more work because we currently can't *get* the (usually)
// ephemeral pubkey at this stage of lokinet configuration. So for now we just stick our
// IPv4 address into it until #1705 gets implemented.
llarp::huint128_t ipv6{
llarp::uint128_t{0xfd2e'6c6f'6b69'0000, llarp::net::TruncateV6(range.addr).h}};
std::strncpy(
appleconf->tunnel_ipv6_ip, ipv6.ToString().c_str(), sizeof(appleconf->tunnel_ipv6_ip));
llarp::huint128_t ipv6{llarp::uint128_t{0xfd2e'6c6f'6b69'0000, llarp::net::TruncateV6(range.addr).h}};
std::strncpy(appleconf->tunnel_ipv6_ip, ipv6.ToString().c_str(), sizeof(appleconf->tunnel_ipv6_ip));
appleconf->tunnel_ipv6_prefix = 48;
appleconf->upstream_dns[0] = '\0';
@ -95,9 +92,7 @@ void* llarp_apple_init(llarp_apple_config* appleconf)
#ifdef MACOS_SYSTEM_EXTENSION
std::strncpy(
appleconf->dns_bind_ip,
config->dns.m_bind.front().hostString().c_str(),
sizeof(appleconf->dns_bind_ip));
appleconf->dns_bind_ip, config->dns.m_bind.front().hostString().c_str(), sizeof(appleconf->dns_bind_ip));
#endif
// If no explicit bootstrap then set the system default one included with the app bundle
@ -126,8 +121,7 @@ int llarp_apple_start(void* lokinet, void* callback_context)
inst->context.callback_context = callback_context;
inst->context.m_PacketWriter = [inst, callback_context](
int af_family, void* data, size_t size) {
inst->context.m_PacketWriter = [inst, callback_context](int af_family, void* data, size_t size) {
inst->packet_writer(af_family, data, size, callback_context);
return true;
};

@ -20,11 +20,10 @@ namespace llarp::apple
}
std::shared_ptr<llarp::handlers::TunEndpoint> tun;
router->hidden_service_context().ForEachService(
[&tun](const auto& /*name*/, const auto ep) {
tun = std::dynamic_pointer_cast<llarp::handlers::TunEndpoint>(ep);
return !tun;
});
router->hidden_service_context().ForEachService([&tun](const auto& /*name*/, const auto ep) {
tun = std::dynamic_pointer_cast<llarp::handlers::TunEndpoint>(ep);
return !tun;
});
if (!tun)
{

@ -30,8 +30,7 @@ namespace llarp::apple
void delete_route_via_interface(vpn::NetworkInterface& vpn, IPRange range) override;
std::vector<oxen::quic::Address> get_non_interface_gateways(
vpn::NetworkInterface& /*vpn*/) override
std::vector<oxen::quic::Address> get_non_interface_gateways(vpn::NetworkInterface& /*vpn*/) override
{
// We can't get this on mac from our sandbox, but we don't actually need it because we
// ignore the gateway for AddRoute/DelRoute anyway, so just return a zero IP.

@ -8,10 +8,7 @@
namespace llarp::apple
{
VPNInterface::VPNInterface(
Context& ctx,
packet_write_callback packet_writer,
on_readable_callback on_readable,
Router* router)
Context& ctx, packet_write_callback packet_writer, on_readable_callback on_readable, Router* router)
: vpn::NetworkInterface{{}},
m_PacketWriter{std::move(packet_writer)},
m_OnReadable{std::move(on_readable)},

@ -10,18 +10,14 @@ namespace llarp::apple
{
struct Context;
class VPNInterface final : public vpn::NetworkInterface,
public std::enable_shared_from_this<VPNInterface>
class VPNInterface final : public vpn::NetworkInterface, public std::enable_shared_from_this<VPNInterface>
{
public:
using packet_write_callback = std::function<bool(int af_family, void* data, int size)>;
using on_readable_callback = std::function<void(VPNInterface&)>;
explicit VPNInterface(
Context& ctx,
packet_write_callback packet_writer,
on_readable_callback on_readable,
Router* router);
Context& ctx, packet_write_callback packet_writer, on_readable_callback on_readable, Router* router);
// Method to call when a packet has arrived to deliver the packet to lokinet
bool OfferReadPacket(const llarp_buffer_t& buf);

@ -16,8 +16,7 @@ namespace llarp::apple
_read_cb{std::move(on_readable)}
{}
std::shared_ptr<vpn::NetworkInterface> VPNPlatform::ObtainInterface(
vpn::InterfaceInfo, Router* router)
std::shared_ptr<vpn::NetworkInterface> VPNPlatform::ObtainInterface(vpn::InterfaceInfo, Router* router)
{
return std::make_shared<VPNInterface>(_context, _packet_writer, _read_cb, router);
}

@ -17,8 +17,7 @@ namespace llarp::apple
llarp_route_callbacks route_callbacks,
void* callback_context);
std::shared_ptr<vpn::NetworkInterface> ObtainInterface(
vpn::InterfaceInfo, Router*) override;
std::shared_ptr<vpn::NetworkInterface> ObtainInterface(vpn::InterfaceInfo, Router*) override;
vpn::AbstractRouteManager& RouteManager() override
{

@ -81,8 +81,7 @@ namespace llarp
return btlp.view();
}
void BootstrapList::populate_bootstraps(
std::vector<fs::path> paths, const fs::path& def, bool load_fallbacks)
void BootstrapList::populate_bootstraps(std::vector<fs::path> paths, const fs::path& def, bool load_fallbacks)
{
for (const auto& f : paths)
{
@ -94,10 +93,7 @@ namespace llarp
if (empty())
{
log::debug(
logcat,
"BootstrapRC list empty; looking for default BootstrapRC from file at path:{}",
def);
log::debug(logcat, "BootstrapRC list empty; looking for default BootstrapRC from file at path:{}", def);
read_from_file(def);
}
@ -118,8 +114,7 @@ namespace llarp
if (auto itr = fallbacks.find(RouterContact::ACTIVE_NETID); itr != fallbacks.end())
{
log::critical(
logcat, "Loading {} default fallback bootstrap router(s)!", itr->second.size());
log::critical(logcat, "Loading {} default fallback bootstrap router(s)!", itr->second.size());
merge(itr->second);
}
@ -153,8 +148,7 @@ namespace llarp
auto content = util::file_to_string(fpath);
result = bt_decode(content);
log::critical(
logcat, "{}uccessfully loaded BootstrapRC file at path:{}", result ? "S" : "Un", fpath);
log::critical(logcat, "{}uccessfully loaded BootstrapRC file at path:{}", result ? "S" : "Un", fpath);
_curr = begin();
return result;

@ -27,8 +27,7 @@ namespace llarp
std::string_view bt_encode() const;
void populate_bootstraps(
std::vector<fs::path> paths, const fs::path& def, bool load_fallbacks);
void populate_bootstraps(std::vector<fs::path> paths, const fs::path& def, bool load_fallbacks);
bool read_from_file(const fs::path& fpath);
@ -54,8 +53,7 @@ namespace llarp
void randomize()
{
if (size() > 1)
_curr =
std::next(begin(), std::uniform_int_distribution<size_t>{0, size() - 1}(csrng));
_curr = std::next(begin(), std::uniform_int_distribution<size_t>{0, size() - 1}(csrng));
}
void clear_list()

@ -10,8 +10,7 @@ namespace llarp
{
std::unordered_map<std::string, BootstrapList> fallbacks;
for (const auto& [network, bootstrap] :
std::initializer_list<std::pair<std::string, std::string_view>>{
for (const auto& [network, bootstrap] : std::initializer_list<std::pair<std::string, std::string_view>>{
//
})
{

@ -32,20 +32,18 @@ namespace llarp
};
} // namespace
void RouterConfig::define_config_options(
ConfigDefinition& conf, const ConfigGenParameters& params)
void RouterConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
{
constexpr Default DefaultJobQueueSize{1024 * 8};
constexpr Default DefaultWorkerThreads{0};
constexpr Default DefaultBlockBogons{true};
conf.define_option<int>(
"router", "job-queue-size", DefaultJobQueueSize, Hidden, [this](int arg) {
if (arg < 1024)
throw std::invalid_argument("job-queue-size must be 1024 or greater");
conf.define_option<int>("router", "job-queue-size", DefaultJobQueueSize, Hidden, [this](int arg) {
if (arg < 1024)
throw std::invalid_argument("job-queue-size must be 1024 or greater");
job_que_size = arg;
});
job_que_size = arg;
});
conf.define_option<std::string>(
"router",
@ -57,8 +55,7 @@ namespace llarp
},
[this](std::string arg) {
if (arg.size() > NETID_SIZE)
throw std::invalid_argument{
fmt::format("netid is too long, max length is {}", NETID_SIZE)};
throw std::invalid_argument{fmt::format("netid is too long, max length is {}", NETID_SIZE)};
net_id = std::move(arg);
});
@ -73,8 +70,8 @@ namespace llarp
},
[=](int arg) {
if (arg < CLIENT_ROUTER_CONNECTIONS)
throw std::invalid_argument{fmt::format(
"Client relay connections must be >= {}", CLIENT_ROUTER_CONNECTIONS)};
throw std::invalid_argument{
fmt::format("Client relay connections must be >= {}", CLIENT_ROUTER_CONNECTIONS)};
client_router_connections = arg;
});
@ -87,9 +84,7 @@ namespace llarp
"Minimum number of routers lokinet will attempt to maintain connections to.",
},
[=](int) {
log::warning(
logcat,
"Router min-connections is deprecated; use relay-connections for clients");
log::warning(logcat, "Router min-connections is deprecated; use relay-connections for clients");
});
conf.define_option<int>(
@ -100,9 +95,7 @@ namespace llarp
"Maximum number (hard limit) of routers lokinet will be connected to at any time.",
},
[=](int) {
log::warning(
logcat,
"Router max-connections is deprecated; use relay-connections for clients");
log::warning(logcat, "Router max-connections is deprecated; use relay-connections for clients");
});
conf.define_option<std::string>("router", "nickname", Deprecated);
@ -119,8 +112,7 @@ namespace llarp
if (arg.empty())
throw std::invalid_argument("[router]:data-dir is empty");
if (not fs::exists(arg))
throw std::runtime_error{
fmt::format("Specified [router]:data-dir {} does not exist", arg)};
throw std::runtime_error{fmt::format("Specified [router]:data-dir {} does not exist", arg)};
data_dir = std::move(arg);
});
@ -178,14 +170,9 @@ namespace llarp
// Hidden option because this isn't something that should ever be turned off occasionally
// when doing dev/testing work.
conf.define_option<bool>(
"router",
"block-bogons",
DefaultBlockBogons,
Hidden,
assignment_acceptor(block_bogons));
"router", "block-bogons", DefaultBlockBogons, Hidden, assignment_acceptor(block_bogons));
constexpr auto relative_to_datadir =
"An absolute path is used as-is, otherwise relative to 'data-dir'.";
constexpr auto relative_to_datadir = "An absolute path is used as-is, otherwise relative to 'data-dir'.";
conf.define_option<std::string>(
"router",
@ -244,8 +231,7 @@ namespace llarp
is_relay = params.is_relay;
}
void NetworkConfig::define_config_options(
ConfigDefinition& conf, const ConfigGenParameters& params)
void NetworkConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
{
(void)params;
@ -256,22 +242,13 @@ namespace llarp
static constexpr Default PathsDefault{6};
static constexpr Default IP6RangeDefault{"fd00::"};
conf.define_option<std::string>(
"network", "type", Default{"tun"}, Hidden, assignment_acceptor(endpoint_type));
conf.define_option<std::string>("network", "type", Default{"tun"}, Hidden, assignment_acceptor(endpoint_type));
conf.define_option<bool>(
"network",
"save-profiles",
SaveProfilesDefault,
Hidden,
assignment_acceptor(save_profiles));
"network", "save-profiles", SaveProfilesDefault, Hidden, assignment_acceptor(save_profiles));
conf.define_option<bool>(
"network",
"profiling",
ProfilingValueDefault,
Hidden,
assignment_acceptor(enable_profiling));
"network", "profiling", ProfilingValueDefault, Hidden, assignment_acceptor(enable_profiling));
conf.define_option<std::string>("network", "profiles", Deprecated);
@ -369,8 +346,7 @@ namespace llarp
},
[this](fs::path arg) {
if (not fs::exists(arg))
throw std::invalid_argument{
fmt::format("cannot load auth file {}: file does not exist", arg)};
throw std::invalid_argument{fmt::format("cannot load auth file {}: file does not exist", arg)};
auth_files.emplace(std::move(arg));
});
conf.define_option<std::string>(
@ -381,9 +357,7 @@ namespace llarp
"How to interpret the contents of an auth file.",
"Possible values: hashes, plaintext",
},
[this](std::string arg) {
auth_file_type = service::parse_auth_file_type(std::move(arg));
});
[this](std::string arg) { auth_file_type = service::parse_auth_file_type(std::move(arg)); });
conf.define_option<std::string>(
"network",
@ -511,8 +485,7 @@ namespace llarp
}
else if (not range.FromString(arg.substr(pos + 1)))
{
throw std::invalid_argument(
"[network]:exit-node invalid ip range for exit provided");
throw std::invalid_argument("[network]:exit-node invalid ip range for exit provided");
}
if (pos != std::string::npos)
{
@ -527,8 +500,7 @@ namespace llarp
if (arg != "null" and not exit.FromString(arg))
{
throw std::invalid_argument{
fmt::format("[network]:exit-node bad address: {}", arg)};
throw std::invalid_argument{fmt::format("[network]:exit-node bad address: {}", arg)};
}
exit_map.Insert(range, exit);
});
@ -618,8 +590,7 @@ namespace llarp
[this](std::string arg) {
if (not if_addr.FromString(arg))
{
throw std::invalid_argument{
fmt::format("[network]:ifaddr invalid value: '{}'", arg)};
throw std::invalid_argument{fmt::format("[network]:ifaddr invalid value: '{}'", arg)};
}
});
@ -647,8 +618,7 @@ namespace llarp
}
base_ipv6_addr = huint128_t{};
if (not base_ipv6_addr->FromString(arg))
throw std::invalid_argument{
fmt::format("[network]:ip6-range invalid value: '{}'", arg)};
throw std::invalid_argument{fmt::format("[network]:ip6-range invalid value: '{}'", arg)};
});
// TODO: could be useful for snodes in the future, but currently only implemented for
@ -672,8 +642,7 @@ namespace llarp
const auto pos = arg.find(":");
if (pos == std::string::npos)
{
throw std::invalid_argument{
fmt::format("[endpoint]:mapaddr invalid entry: {}", arg)};
throw std::invalid_argument{fmt::format("[endpoint]:mapaddr invalid entry: {}", arg)};
}
std::string addrstr = arg.substr(0, pos);
std::string ipstr = arg.substr(pos + 1);
@ -682,20 +651,17 @@ namespace llarp
huint32_t ipv4;
if (not ipv4.FromString(ipstr))
{
throw std::invalid_argument{
fmt::format("[endpoint]:mapaddr invalid ip: {}", ipstr)};
throw std::invalid_argument{fmt::format("[endpoint]:mapaddr invalid ip: {}", ipstr)};
}
ip = net::ExpandV4(ipv4);
}
if (not addr.FromString(addrstr))
{
throw std::invalid_argument{
fmt::format("[endpoint]:mapaddr invalid addresss: {}", addrstr)};
throw std::invalid_argument{fmt::format("[endpoint]:mapaddr invalid addresss: {}", addrstr)};
}
if (map_addrs.find(ip) != map_addrs.end())
{
throw std::invalid_argument{
fmt::format("[endpoint]:mapaddr ip already mapped: {}", ipstr)};
throw std::invalid_argument{fmt::format("[endpoint]:mapaddr ip already mapped: {}", ipstr)};
}
map_addrs[ip] = addr;
});
@ -753,8 +719,7 @@ namespace llarp
},
[this](int val) {
if (val <= 0)
throw std::invalid_argument{
"invalid path alignment timeout: " + std::to_string(val) + " <= 0"};
throw std::invalid_argument{"invalid path alignment timeout: " + std::to_string(val) + " <= 0"};
path_alignment_timeout = std::chrono::seconds{val};
});
@ -832,8 +797,7 @@ namespace llarp
"dns",
"l3-intercept",
Default{
platform::is_windows or platform::is_android
or (platform::is_macos and not platform::is_apple_sysex)},
platform::is_windows or platform::is_android or (platform::is_macos and not platform::is_apple_sysex)},
Comment{"Intercept all dns traffic (udp/53) going into our lokinet network interface "
"instead of binding a local udp socket"},
assignment_acceptor(raw));
@ -872,14 +836,12 @@ namespace llarp
"dns",
"add-hosts",
ClientOnly,
Comment{
"Add a hosts file to the dns resolver", "For use with client side dns filtering"},
Comment{"Add a hosts file to the dns resolver", "For use with client side dns filtering"},
[=](fs::path path) {
if (path.empty())
return;
if (not fs::exists(path))
throw std::invalid_argument{
fmt::format("cannot add hosts file {} as it does not exist", path)};
throw std::invalid_argument{fmt::format("cannot add hosts file {} as it does not exist", path)};
hostfiles.emplace_back(std::move(path));
});
@ -897,13 +859,10 @@ namespace llarp
// forward the rest to libunbound
conf.add_undeclared_handler(
"dns", [this](auto, std::string_view key, std::string_view val) {
extra_opts.emplace(key, val);
});
"dns", [this](auto, std::string_view key, std::string_view val) { extra_opts.emplace(key, val); });
}
void LinksConfig::define_config_options(
ConfigDefinition& conf, const ConfigGenParameters& params)
void LinksConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
{
conf.add_section_comments(
"bind",
@ -1023,15 +982,9 @@ namespace llarp
});
conf.define_option<std::string>(
"bind",
"inbound",
RelayOnly,
MultiValue,
Hidden,
[this, parse_addr_for_link](const std::string& arg) {
"bind", "inbound", RelayOnly, MultiValue, Hidden, [this, parse_addr_for_link](const std::string& arg) {
if (using_new_api)
throw std::runtime_error{
"USE THE NEW API -- SPECIFY LOCAL ADDRESS UNDER [LISTEN]"};
throw std::runtime_error{"USE THE NEW API -- SPECIFY LOCAL ADDRESS UNDER [LISTEN]"};
if (auto a = parse_addr_for_link(arg); a and a->is_addressable())
{
@ -1047,63 +1000,60 @@ namespace llarp
conf.define_option<std::string>("bind", "outbound", MultiValue, Deprecated, Hidden);
conf.add_undeclared_handler(
"bind", [this](std::string_view, std::string_view key, std::string_view val) {
if (using_new_api)
throw std::runtime_error{
"USE THE NEW API -- SPECIFY LOCAL ADDRESS UNDER [LISTEN]"};
conf.add_undeclared_handler("bind", [this](std::string_view, std::string_view key, std::string_view val) {
if (using_new_api)
throw std::runtime_error{"USE THE NEW API -- SPECIFY LOCAL ADDRESS UNDER [LISTEN]"};
log::warning(logcat, "Please update your config to use [bind]:listen instead");
log::warning(logcat, "Please update your config to use [bind]:listen instead");
uint16_t port{0};
uint16_t port{0};
if (auto rv = llarp::parse_int<uint16_t>(val, port); not rv)
throw std::runtime_error{
"Could not parse port; stop using this deprecated handler"};
if (auto rv = llarp::parse_int<uint16_t>(val, port); not rv)
throw std::runtime_error{"Could not parse port; stop using this deprecated handler"};
port = port == 0 ? DEFAULT_LISTEN_PORT : port;
port = port == 0 ? DEFAULT_LISTEN_PORT : port;
// special case: wildcard for outbound
if (key == "*")
{
log::warning(
logcat,
"Wildcat address referencing port {} is referencing deprecated outbound "
"config "
"options; use [bind]:listen instead",
port);
return;
}
// special case: wildcard for outbound
if (key == "*")
{
log::warning(
logcat,
"Wildcat address referencing port {} is referencing deprecated outbound "
"config "
"options; use [bind]:listen instead",
port);
return;
}
oxen::quic::Address temp;
oxen::quic::Address temp;
try
{
temp = oxen::quic::Address{std::string{key}, port};
}
catch (const std::exception& e)
{
throw std::runtime_error{fmt::format(
"Could not parse address {}; please update your config to use "
"[bind]:listen "
"instead: {}",
key,
e.what())};
}
try
{
temp = oxen::quic::Address{std::string{key}, port};
}
catch (const std::exception& e)
{
throw std::runtime_error{fmt::format(
"Could not parse address {}; please update your config to use "
"[bind]:listen "
"instead: {}",
key,
e.what())};
}
if (not temp.is_addressable())
{
throw std::runtime_error{fmt::format(
"Invalid address: {}; stop using this deprecated handler, update your "
"config to "
"use "
"[bind]:listen instead PLEASE",
temp)};
}
if (not temp.is_addressable())
{
throw std::runtime_error{fmt::format(
"Invalid address: {}; stop using this deprecated handler, update your "
"config to "
"use "
"[bind]:listen instead PLEASE",
temp)};
}
listen_addr = std::move(temp);
using_user_value = true;
});
listen_addr = std::move(temp);
using_user_value = true;
});
}
void ApiConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
@ -1152,8 +1102,7 @@ namespace llarp
// TODO: add pubkey to whitelist
}
void LokidConfig::define_config_options(
ConfigDefinition& conf, const ConfigGenParameters& params)
void LokidConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
{
(void)params;
conf.define_option<bool>(
@ -1162,9 +1111,7 @@ namespace llarp
Default{false},
Hidden,
RelayOnly,
Comment{
"Development option: set to true to disable reachability testing when using ",
"testnet"},
Comment{"Development option: set to true to disable reachability testing when using ", "testnet"},
assignment_acceptor(disable_testing));
conf.define_option<std::string>(
@ -1200,8 +1147,7 @@ namespace llarp
conf.define_option<std::string>("lokid", "service-node-seed", Deprecated);
}
void BootstrapConfig::define_config_options(
ConfigDefinition& conf, const ConfigGenParameters& params)
void BootstrapConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
{
(void)params;
@ -1233,13 +1179,11 @@ namespace llarp
});
}
void LoggingConfig::define_config_options(
ConfigDefinition& conf, const ConfigGenParameters& params)
void LoggingConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
{
(void)params;
constexpr Default DefaultLogType{
platform::is_android or platform::is_apple ? "system" : "print"};
constexpr Default DefaultLogType{platform::is_android or platform::is_apple ? "system" : "print"};
constexpr Default DefaultLogFile{""};
const Default DefaultLogLevel{params.is_relay ? "warn" : "info"};
@ -1283,8 +1227,7 @@ namespace llarp
});
}
void PeerSelectionConfig::define_config_options(
ConfigDefinition& conf, const ConfigGenParameters& params)
void PeerSelectionConfig::define_config_options(ConfigDefinition& conf, const ConfigGenParameters& params)
{
(void)params;
@ -1301,8 +1244,7 @@ namespace llarp
}
else if (arg > 32 or arg < 4)
{
throw std::invalid_argument{
"[paths]:unique-range-size must be between 4 and 32"};
throw std::invalid_argument{"[paths]:unique-range-size must be between 4 and 32"};
}
unique_hop_netmask = arg;
},
@ -1318,9 +1260,7 @@ namespace llarp
"exclude-country",
ClientOnly,
MultiValue,
[=](std::string arg) {
m_ExcludeCountries.emplace(lowercase_ascii_string(std::move(arg)));
},
[=](std::string arg) { m_ExcludeCountries.emplace(lowercase_ascii_string(std::move(arg))); },
Comment{
"Exclude a country given its 2 letter country code from being used in path builds.",
"For example:",
@ -1352,8 +1292,7 @@ namespace llarp
return std::make_unique<ConfigGenParameters_impl>();
}
Config::Config(std::optional<fs::path> datadir)
: data_dir{datadir ? std::move(*datadir) : fs::current_path()}
Config::Config(std::optional<fs::path> datadir) : data_dir{datadir ? std::move(*datadir) : fs::current_path()}
{}
constexpr auto GetOverridesDir = [](auto datadir) -> fs::path { return datadir / "conf.d"; };
@ -1385,11 +1324,10 @@ namespace llarp
if (not parser.load_file(f.path()))
throw std::runtime_error{"cannot load '" + f.path().u8string() + "'"};
parser.iter_all_sections(
[&](std::string_view section, const SectionValues& values) {
for (const auto& [k, v] : values)
conf.add_config_value(section, k, v);
});
parser.iter_all_sections([&](std::string_view section, const SectionValues& values) {
for (const auto& [k, v] : values)
conf.add_config_value(section, k, v);
});
}
}
}
@ -1399,8 +1337,7 @@ namespace llarp
additional.emplace_back(std::array<std::string, 3>{section, key, val});
}
bool Config::load_config_data(
std::string_view ini, std::optional<fs::path> filename, bool isRelay)
bool Config::load_config_data(std::string_view ini, std::optional<fs::path> filename, bool isRelay)
{
auto params = make_gen_params();
params->is_relay = isRelay;
@ -1508,11 +1445,7 @@ namespace llarp
fs::create_directory(parent);
}
llarp::LogInfo(
"Attempting to create config file for ",
(asRouter ? "router" : "client"),
" at ",
confFile);
llarp::LogInfo("Attempting to create config file for ", (asRouter ? "router" : "client"), " at ", confFile);
llarp::Config config{dataDir};
std::string confStr;
@ -1528,8 +1461,7 @@ namespace llarp
}
catch (const std::exception& e)
{
throw std::runtime_error{
fmt::format("Failed to write config data to {}: {}", confFile, e.what())};
throw std::runtime_error{fmt::format("Failed to write config data to {}: {}", confFile, e.what())};
}
llarp::LogInfo("Generated new config ", confFile);

@ -274,10 +274,7 @@ namespace llarp
/// @return true on success, false otherwise
bool load_default_config(bool isRelay);
bool load_config_data(
std::string_view ini,
std::optional<fs::path> fname = std::nullopt,
bool isRelay = false);
bool load_config_data(std::string_view ini, std::optional<fs::path> fname = std::nullopt, bool isRelay = false);
void load_overrides(ConfigDefinition& conf) const;

@ -30,9 +30,8 @@ namespace llarp
def->name,
MultiValue,
Hidden,
[deprecated = def->deprecated,
relay = relay,
opt = "[" + def->section + "]:" + def->name](std::string_view) {
[deprecated = def->deprecated, relay = relay, opt = "[" + def->section + "]:" + def->name](
std::string_view) {
LogWarn(
"*** WARNING: The config option ",
opt,
@ -50,8 +49,7 @@ namespace llarp
auto [it, added] = definitions[section].try_emplace(std::string{def->name}, std::move(def));
if (!added)
throw std::invalid_argument{
fmt::format("definition for [{}]:{} already exists", def->section, def->name)};
throw std::invalid_argument{fmt::format("definition for [{}]:{} already exists", def->section, def->name)};
definition_ordering[section].push_back(it->first);
@ -100,8 +98,7 @@ namespace llarp
return *this;
}
void ConfigDefinition::add_undeclared_handler(
const std::string& section, UndeclaredValueHandler handler)
void ConfigDefinition::add_undeclared_handler(const std::string& section, UndeclaredValueHandler handler)
{
auto itr = undeclared_handlers.find(section);
if (itr != undeclared_handlers.end())
@ -120,32 +117,28 @@ namespace llarp
void ConfigDefinition::validate_required_fields()
{
visit_sections([&](const std::string& section, const DefinitionMap&) {
visit_definitions(
section, [&](const std::string&, const std::unique_ptr<OptionDefinitionBase>& def) {
if (def->required and def->get_number_found() < 1)
{
throw std::invalid_argument{
fmt::format("[{}]:{} is required but missing", section, def->name)};
}
// should be handled earlier in OptionDefinition::parse_value()
assert(def->get_number_found() <= 1 or def->multi_valued);
});
visit_definitions(section, [&](const std::string&, const std::unique_ptr<OptionDefinitionBase>& def) {
if (def->required and def->get_number_found() < 1)
{
throw std::invalid_argument{fmt::format("[{}]:{} is required but missing", section, def->name)};
}
// should be handled earlier in OptionDefinition::parse_value()
assert(def->get_number_found() <= 1 or def->multi_valued);
});
});
}
void ConfigDefinition::accept_all_options()
{
visit_sections([this](const std::string& section, const DefinitionMap&) {
visit_definitions(
section, [](const std::string&, const std::unique_ptr<OptionDefinitionBase>& def) {
def->try_accept();
});
visit_definitions(section, [](const std::string&, const std::unique_ptr<OptionDefinitionBase>& def) {
def->try_accept();
});
});
}
void ConfigDefinition::add_section_comments(
const std::string& section, std::vector<std::string> comments)
void ConfigDefinition::add_section_comments(const std::string& section, std::vector<std::string> comments)
{
auto& sectionComments = section_comments[section];
for (auto& c : comments)
@ -160,9 +153,7 @@ namespace llarp
defComments = std::move(comments);
else
defComments.insert(
defComments.end(),
std::make_move_iterator(comments.begin()),
std::make_move_iterator(comments.end()));
defComments.end(), std::make_move_iterator(comments.begin()), std::make_move_iterator(comments.end()));
}
std::string ConfigDefinition::generate_ini_config(bool useValues)
@ -176,42 +167,39 @@ namespace llarp
std::string sect_str;
auto sect_append = std::back_inserter(sect_str);
visit_definitions(
section,
[&](const std::string& name, const std::unique_ptr<OptionDefinitionBase>& def) {
bool has_comment = false;
// 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 : definition_comments[section][name])
{
fmt::format_to(sect_append, "\n# {}", comment);
has_comment = true;
}
if (useValues and def->get_number_found() > 0)
{
for (const auto& val : def->values_as_string())
fmt::format_to(sect_append, "\n{}={}", name, val);
*sect_append = '\n';
}
else if (not def->hidden)
{
if (auto defaults = def->default_values_as_string(); not defaults.empty())
for (const auto& val : defaults)
fmt::format_to(
sect_append, "\n{}{}={}", def->required ? "" : "#", name, val);
else
// We have no defaults so we append it as "#opt-name=" so that we show
// the option name, and make it simple to uncomment and edit to the
// desired value.
fmt::format_to(sect_append, "\n#{}=", name);
*sect_append = '\n';
}
else if (has_comment)
*sect_append = '\n';
});
visit_definitions(section, [&](const std::string& name, const std::unique_ptr<OptionDefinitionBase>& def) {
bool has_comment = false;
// 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 : definition_comments[section][name])
{
fmt::format_to(sect_append, "\n# {}", comment);
has_comment = true;
}
if (useValues and def->get_number_found() > 0)
{
for (const auto& val : def->values_as_string())
fmt::format_to(sect_append, "\n{}={}", name, val);
*sect_append = '\n';
}
else if (not def->hidden)
{
if (auto defaults = def->default_values_as_string(); not defaults.empty())
for (const auto& val : defaults)
fmt::format_to(sect_append, "\n{}{}={}", def->required ? "" : "#", name, val);
else
// We have no defaults so we append it as "#opt-name=" so that we show
// the option name, and make it simple to uncomment and edit to the
// desired value.
fmt::format_to(sect_append, "\n#{}=", name);
*sect_append = '\n';
}
else if (has_comment)
*sect_append = '\n';
});
if (sect_str.empty())
return; // Skip sections with no options
@ -246,8 +234,7 @@ namespace llarp
auto& sectionDefinitions = sectionItr->second;
const auto definitionItr = sectionDefinitions.find(std::string(name));
if (definitionItr == sectionDefinitions.end())
throw std::invalid_argument{
fmt::format("No config item {} within section {}", name, section)};
throw std::invalid_argument{fmt::format("No config item {} within section {}", name, section)};
return definitionItr->second;
}

@ -76,8 +76,7 @@ namespace llarp
struct Comment
{
std::vector<std::string> comments;
explicit Comment(std::initializer_list<std::string> comments)
: comments{std::move(comments)}
explicit Comment(std::initializer_list<std::string> comments) : comments{std::move(comments)}
{}
};
@ -110,9 +109,9 @@ namespace llarp
constexpr bool is_default_array<U&> = is_default_array<remove_cvref_t<U>>;
template <typename T, typename Option>
constexpr bool is_option = std::is_base_of_v<flag::opt, remove_cvref_t<Option>>
or std::is_same_v<Comment, Option> or is_default<Option> or is_default_array<Option>
or std::is_invocable_v<remove_cvref_t<Option>, T>;
constexpr bool is_option =
std::is_base_of_v<flag::opt, remove_cvref_t<Option>> or std::is_same_v<Comment, Option>
or is_default<Option> or is_default_array<Option> or std::is_invocable_v<remove_cvref_t<Option>, T>;
} // namespace config
/// A base class for specifying config options and their constraints. The basic to/from string
@ -195,23 +194,16 @@ namespace llarp
/// tagged options or an invocable acceptor validate and internalize input (e.g. copy it for
/// runtime use). The acceptor should throw an exception with a useful message if it is not
/// acceptable. Parameters may be passed in any order.
template <
typename... Options,
std::enable_if_t<(config::is_option<T, Options> && ...), int> = 0>
template <typename... Options, std::enable_if_t<(config::is_option<T, Options> && ...), int> = 0>
OptionDefinition(std::string section_, std::string name_, Options&&... opts)
: OptionDefinitionBase(section_, name_, opts...)
{
constexpr bool has_default =
((config::is_default_array<Options> || config::is_default<Options>) || ...);
constexpr bool has_default = ((config::is_default_array<Options> || config::is_default<Options>) || ...);
constexpr bool has_required =
(std::is_same_v<config::remove_cvref_t<Options>, config::flag::REQUIRED> || ...);
constexpr bool has_hidden =
(std::is_same_v<config::remove_cvref_t<Options>, config::flag::HIDDEN> || ...);
static_assert(
not(has_default and has_required),
"Default{...} and Required are mutually exclusive");
static_assert(
not(has_hidden and has_required), "Hidden and Required are mutually exclusive");
constexpr bool has_hidden = (std::is_same_v<config::remove_cvref_t<Options>, config::flag::HIDDEN> || ...);
static_assert(not(has_default and has_required), "Default{...} and Required are mutually exclusive");
static_assert(not(has_hidden and has_required), "Hidden and Required are mutually exclusive");
(extract_default(std::forward<Options>(opts)), ...);
(extract_acceptor(std::forward<Options>(opts)), ...);
@ -325,8 +317,7 @@ namespace llarp
T t;
iss >> t;
if (iss.fail())
throw std::invalid_argument{
fmt::format("{} is not a valid {}", input, typeid(T).name())};
throw std::invalid_argument{fmt::format("{} is not a valid {}", input, typeid(T).name())};
return t;
}
}
@ -357,9 +348,7 @@ namespace llarp
if (required and parsed_values.empty())
{
throw std::runtime_error{fmt::format(
"cannot call try_accept() on [{}]:{} when required but no value available",
section,
name)};
"cannot call try_accept() on [{}]:{} when required but no value available", section, name)};
}
if (acceptor)
@ -395,8 +384,8 @@ namespace llarp
template <>
bool OptionDefinition<bool>::from_string(const std::string& input);
using UndeclaredValueHandler = std::function<void(
std::string_view section, std::string_view name, std::string_view value)>;
using UndeclaredValueHandler =
std::function<void(std::string_view section, std::string_view name, std::string_view value)>;
// map of k:v pairs
using DefinitionMap = std::unordered_map<std::string, std::unique_ptr<OptionDefinitionBase>>;
@ -439,8 +428,7 @@ namespace llarp
template <typename T, typename... Params>
ConfigDefinition& define_option(Params&&... args)
{
return define_option(
std::make_unique<OptionDefinition<T>>(std::forward<Params>(args)...));
return define_option(std::make_unique<OptionDefinition<T>>(std::forward<Params>(args)...));
}
/// Specify a config value for the given section and name. The value should be a valid
@ -455,8 +443,7 @@ namespace llarp
/// @param name is the name of the value
/// @return `*this` for chaining calls
/// @throws if the option doesn't exist or the provided string isn't parseable
ConfigDefinition& add_config_value(
std::string_view section, std::string_view name, std::string_view value);
ConfigDefinition& add_config_value(std::string_view section, std::string_view name, std::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
@ -473,13 +460,12 @@ namespace llarp
template <typename T>
std::optional<T> get_config_value(std::string_view section, std::string_view name)
{
std::unique_ptr<OptionDefinitionBase>& definition =
lookup_definition_or_throw(section, name);
std::unique_ptr<OptionDefinitionBase>& definition = lookup_definition_or_throw(section, name);
auto derived = dynamic_cast<const OptionDefinition<T>*>(definition.get());
if (not derived)
throw std::invalid_argument{fmt::format(
"{} is the incorrect type for [{}]:{}", typeid(T).name(), section, name)};
throw std::invalid_argument{
fmt::format("{} is the incorrect type for [{}]:{}", typeid(T).name(), section, name)};
return derived->getValue();
}
@ -562,8 +548,7 @@ namespace llarp
using SectionVisitor = std::function<void(const std::string&, const DefinitionMap&)>;
void visit_sections(SectionVisitor visitor) const;
using DefVisitor =
std::function<void(const std::string&, const std::unique_ptr<OptionDefinitionBase>&)>;
using DefVisitor = std::function<void(const std::string&, const std::unique_ptr<OptionDefinitionBase>&)>;
void visit_definitions(const std::string& section, DefVisitor visitor) const;
SectionMap definitions;

@ -109,16 +109,14 @@ namespace llarp
if (k.empty())
{
throw std::runtime_error(
fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
throw std::runtime_error(fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
}
LogDebug(_filename, ": [", sectName, "]:", k, "=", v);
_config[std::string{sectName}].emplace(k, v);
}
else // malformed?
{
throw std::runtime_error(
fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
throw std::runtime_error(fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
}
}
return true;
@ -177,30 +175,26 @@ namespace llarp
if (k.empty())
{
throw std::runtime_error(
fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
throw std::runtime_error(fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
}
LogDebug(_filename, ": [", sectName, "]:", k, "=", v);
_config[std::string{sectName}].emplace(k, v);
}
else // malformed?
{
throw std::runtime_error(
fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
throw std::runtime_error(fmt::format("{} invalid line ({}): '{}'", _filename, lineno, line));
}
}
return true;
}
void ConfigParser::iter_all_sections(
std::function<void(std::string_view, const SectionValues&)> visit)
void ConfigParser::iter_all_sections(std::function<void(std::string_view, const SectionValues&)> visit)
{
for (const auto& item : _config)
visit(item.first, item.second);
}
bool ConfigParser::visit_section(
const char* name, std::function<bool(const SectionValues& sect)> visit) const
bool ConfigParser::visit_section(const char* name, std::function<bool(const SectionValues& sect)> visit) const
{
// m_Config is effectively:
// unordered_map< string, unordered_multimap< string, string >>
@ -212,8 +206,7 @@ namespace llarp
return visit(itr->second);
}
void ConfigParser::add_override(
fs::path fpath, std::string section, std::string key, std::string value)
void ConfigParser::add_override(fs::path fpath, std::string section, std::string key, std::string value)
{
auto& data = _overrides[fpath];
data[section].emplace(key, value);

@ -86,8 +86,7 @@ namespace llarp
auto enckey_gen = [](llarp::SecretKey& key) { llarp::crypto::encryption_keygen(key); };
if (not keygen(enckey_path, encryption_key, enckey_gen))
{
log::critical(
logcat, "KeyManager::keygen failed to generate encryption key line:{}", __LINE__);
log::critical(logcat, "KeyManager::keygen failed to generate encryption key line:{}", __LINE__);
return false;
}
@ -99,8 +98,7 @@ namespace llarp
if (not keygen(transkey_path, transport_key, transkey_gen))
{
log::critical(
logcat, "KeyManager::keygen failed to generate transport key line:{}", __LINE__);
log::critical(logcat, "KeyManager::keygen failed to generate transport key line:{}", __LINE__);
return false;
}
@ -114,8 +112,7 @@ namespace llarp
if (not keygen(idkey_path, identity_key, idkey_gen))
{
log::critical(
logcat, "KeyManager::keygen failed to generate identity key line:{}", __LINE__);
log::critical(logcat, "KeyManager::keygen failed to generate identity key line:{}", __LINE__);
return false;
}
}
@ -186,8 +183,7 @@ namespace llarp
return true;
}
bool KeyManager::keygen(
fs::path path, llarp::SecretKey& key, std::function<void(llarp::SecretKey& key)> keygen)
bool KeyManager::keygen(fs::path path, llarp::SecretKey& key, std::function<void(llarp::SecretKey& key)> keygen)
{
if (not fs::exists(path))
{

@ -74,10 +74,7 @@ namespace llarp
/// Load the key at a given filepath or create it
///
/// @param keygen is a function that will generate the key if needed
static bool keygen(
fs::path filepath,
llarp::SecretKey& key,
std::function<void(llarp::SecretKey& key)> keygen);
static bool keygen(fs::path filepath, llarp::SecretKey& key, std::function<void(llarp::SecretKey& key)> keygen);
};
} // namespace llarp

@ -41,11 +41,7 @@ namespace llarp::consensus
else
{
LogWarn(
"Have not received ",
name,
" pings for a long time: ",
fminutes{elapsed}.count(),
" minutes");
"Have not received ", name, " pings for a long time: ", fminutes{elapsed}.count(), " minutes");
}
LogWarn(
"Please check your ",
@ -68,14 +64,12 @@ namespace llarp::consensus
last.last_test = now;
}
std::optional<RouterID> reachability_testing::next_random(
Router* router, const time_point_t& now, bool requeue)
std::optional<RouterID> reachability_testing::next_random(Router* router, const time_point_t& now, bool requeue)
{
if (next_general_test > now)
return std::nullopt;
next_general_test = now
+ std::chrono::duration_cast<time_point_t::duration>(
fseconds(TESTING_INTERVAL(llarp::csrng)));
next_general_test =
now + std::chrono::duration_cast<time_point_t::duration>(fseconds(TESTING_INTERVAL(llarp::csrng)));
// Pull the next element off the queue, but skip ourself, any that are no longer registered,
// and any that are currently known to be failing (those are queued for testing separately).

@ -28,8 +28,7 @@ namespace llarp::consensus
{
constexpr bool operator()(const T& lhs, const T& rhs) const
{
return std::greater<std::tuple_element_t<N, T>>{}(
std::get<N>(lhs), std::get<N>(rhs));
return std::greater<std::tuple_element_t<N, T>>{}(std::get<N>(lhs), std::get<N>(rhs));
}
};
@ -101,8 +100,7 @@ namespace llarp::consensus
// after 10s then back off linearly by an additional 10s up to a max testing interval of
// 2m30s, until we get a successful response.
using FailingPK = std::tuple<RouterID, time_point_t, int>;
std::priority_queue<FailingPK, std::vector<FailingPK>, detail::nth_greater<FailingPK, 1>>
failing_queue;
std::priority_queue<FailingPK, std::vector<FailingPK>, detail::nth_greater<FailingPK, 1>> failing_queue;
std::unordered_set<RouterID> failing;
// Track the last time *this node* was tested by other network nodes; used to detect and

@ -23,8 +23,7 @@ namespace llarp::path
/// spacing frequency at which we try to build paths for introductions
constexpr std::chrono::milliseconds INTRO_PATH_SPREAD = DEFAULT_LIFETIME / INTRO_SPREAD_SLICES;
/// how long away from expiration in millseconds do we consider an intro to become stale
constexpr std::chrono::milliseconds INTRO_STALE_THRESHOLD =
DEFAULT_LIFETIME - INTRO_PATH_SPREAD;
constexpr std::chrono::milliseconds INTRO_STALE_THRESHOLD = DEFAULT_LIFETIME - INTRO_PATH_SPREAD;
/// Minimum paths to keep around for intros; mainly used at startup (the
/// spread, above, should be able to maintain more than this number of paths
/// normally once things are going).

@ -71,9 +71,7 @@ namespace llarp
std::shared_ptr<NodeDB> Context::makeNodeDB()
{
return std::make_shared<NodeDB>(
nodedb_dirname,
[r = router.get()](auto call) { r->queue_disk_io(std::move(call)); },
router.get());
nodedb_dirname, [r = router.get()](auto call) { r->queue_disk_io(std::move(call)); }, router.get());
}
std::shared_ptr<Router> Context::makeRouter(const EventLoop_ptr& loop)

@ -42,11 +42,7 @@ namespace llarp
}
static bool dh(
uint8_t* out,
const uint8_t* client_pk,
const uint8_t* server_pk,
const uint8_t* themPub,
const uint8_t* usSec)
uint8_t* out, const uint8_t* client_pk, const uint8_t* server_pk, const uint8_t* themPub, const uint8_t* usSec)
{
llarp::SharedSecret shared;
crypto_generichash_state h;
@ -63,39 +59,33 @@ namespace llarp
return true;
}
static bool dh_client_priv(
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
static bool dh_client_priv(llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
{
llarp::SharedSecret dh_result;
if (dh(dh_result, sk.toPublic(), pk, pk.data(), sk))
{
return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32)
!= -1;
return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32) != -1;
}
llarp::LogWarn("crypto::dh_client - dh failed");
return false;
}
static bool dh_server_priv(
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
static bool dh_server_priv(llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
{
llarp::SharedSecret dh_result;
if (dh(dh_result, pk, sk.toPublic(), pk.data(), sk))
{
return crypto_generichash_blake2b(
shared.data(), 32, n.data(), n.size(), dh_result.data(), 32)
!= -1;
return crypto_generichash_blake2b(shared.data(), 32, n.data(), n.size(), dh_result.data(), 32) != -1;
}
llarp::LogWarn("crypto::dh_server - dh failed");
return false;
}
static bool dh_server_priv(
uint8_t* shared, const uint8_t* pk, const uint8_t* sk, const uint8_t* nonce)
static bool dh_server_priv(uint8_t* shared, const uint8_t* pk, const uint8_t* sk, const uint8_t* nonce)
{
llarp::SharedSecret dh_result;
@ -153,11 +143,7 @@ namespace llarp
// do a round of chacha for and return the nonce xor the given xor_factor
SymmNonce crypto::onion(
unsigned char* buf,
size_t size,
const SharedSecret& k,
const SymmNonce& nonce,
const SymmNonce& xor_factor)
unsigned char* buf, size_t size, const SharedSecret& k, const SymmNonce& nonce, const SymmNonce& xor_factor)
{
if (!crypto::xchacha20(buf, size, k, nonce))
throw std::runtime_error{"chacha failed during onion step"};
@ -165,37 +151,30 @@ namespace llarp
return nonce ^ xor_factor;
}
bool crypto::dh_client(
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
bool crypto::dh_client(llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
{
return dh_client_priv(shared, pk, sk, n);
}
/// path dh relay side
bool crypto::dh_server(
llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
bool crypto::dh_server(llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const SymmNonce& n)
{
return dh_server_priv(shared, pk, sk, n);
}
bool crypto::dh_server(
uint8_t* shared_secret,
const uint8_t* other_pk,
const uint8_t* local_pk,
const uint8_t* nonce)
uint8_t* shared_secret, const uint8_t* other_pk, const uint8_t* local_pk, const uint8_t* nonce)
{
return dh_server_priv(shared_secret, other_pk, local_pk, nonce);
}
bool crypto::shorthash(ShortHash& result, uint8_t* buf, size_t size)
{
return crypto_generichash_blake2b(result.data(), ShortHash::SIZE, buf, size, nullptr, 0)
!= -1;
return crypto_generichash_blake2b(result.data(), ShortHash::SIZE, buf, size, nullptr, 0) != -1;
}
bool crypto::hmac(uint8_t* result, uint8_t* buf, size_t size, const SharedSecret& secret)
{
return crypto_generichash_blake2b(result, HMACSIZE, buf, size, secret.data(), HMACSECSIZE)
!= -1;
return crypto_generichash_blake2b(result, HMACSIZE, buf, size, secret.data(), HMACSECSIZE) != -1;
}
static bool hash(uint8_t* result, const llarp_buffer_t& buff)
@ -325,19 +304,14 @@ namespace llarp
// n = H(b)
// h = make_point(n)
ShortHash n;
return -1
!= crypto_generichash_blake2b(
n.data(), ShortHash::SIZE, buf.data(), buf.size(), nullptr, 0)
return -1 != crypto_generichash_blake2b(n.data(), ShortHash::SIZE, buf.data(), buf.size(), nullptr, 0)
&& -1 != crypto_core_ed25519_from_uniform(out.data(), n.data());
}
static AlignedBuffer<32> zero;
bool crypto::derive_subkey(
PubKey& out_pubkey,
const PubKey& root_pubkey,
uint64_t key_n,
const AlignedBuffer<32>* hash)
PubKey& out_pubkey, const PubKey& root_pubkey, uint64_t key_n, const AlignedBuffer<32>* hash)
{
// scalar h = H( BLIND-STRING || root_pubkey || key_n )
AlignedBuffer<32> h;
@ -353,10 +327,7 @@ namespace llarp
}
bool crypto::derive_subkey_private(
PrivateKey& out_key,
const SecretKey& root_key,
uint64_t key_n,
const AlignedBuffer<32>* hash)
PrivateKey& out_key, const SecretKey& root_key, uint64_t key_n, const AlignedBuffer<32>* hash)
{
// Derives a private subkey from a root key.
//
@ -414,9 +385,7 @@ namespace llarp
std::array<byte_t, 64> buf;
std::copy(h.begin(), h.end(), buf.begin());
std::copy(a.signingHash(), a.signingHash() + 32, buf.begin() + 32);
return -1
!= crypto_generichash_blake2b(
out_key.signingHash(), 32, buf.data(), buf.size(), nullptr, 0);
return -1 != crypto_generichash_blake2b(out_key.signingHash(), 32, buf.data(), buf.size(), nullptr, 0);
return true;
}
@ -463,13 +432,11 @@ namespace llarp
crypto_scalarmult_curve25519_base(d + 32, d);
}
bool crypto::pqe_encrypt(
PQCipherBlock& ciphertext, SharedSecret& sharedkey, const PQPubKey& pubkey)
bool crypto::pqe_encrypt(PQCipherBlock& ciphertext, SharedSecret& sharedkey, const PQPubKey& pubkey)
{
return crypto_kem_enc(ciphertext.data(), sharedkey.data(), pubkey.data()) != -1;
}
bool crypto::pqe_decrypt(
const PQCipherBlock& ciphertext, SharedSecret& sharedkey, const byte_t* secretkey)
bool crypto::pqe_decrypt(const PQCipherBlock& ciphertext, SharedSecret& sharedkey, const byte_t* secretkey)
{
return crypto_kem_dec(sharedkey.data(), ciphertext.data(), secretkey) != -1;
}

@ -36,11 +36,7 @@ namespace llarp
bool dh_client(SharedSecret&, const PubKey&, const SecretKey&, const SymmNonce&);
/// path dh relay side
bool dh_server(SharedSecret&, const PubKey&, const SecretKey&, const SymmNonce&);
bool dh_server(
uint8_t* shared_secret,
const uint8_t* other_pk,
const uint8_t* local_pk,
const uint8_t* nonce);
bool dh_server(uint8_t* shared_secret, const uint8_t* other_pk, const uint8_t* local_pk, const uint8_t* nonce);
/// blake2b 256 bit
bool shorthash(ShortHash&, uint8_t*, size_t size);
/// blake2s 256 bit hmac
@ -61,18 +57,12 @@ namespace llarp
/// derive sub keys for public keys. hash is really only intended for
/// testing ands key_n if given.
bool derive_subkey(
PubKey& derived,
const PubKey& root,
uint64_t key_n,
const AlignedBuffer<32>* hash = nullptr);
PubKey& derived, const PubKey& root, uint64_t key_n, const AlignedBuffer<32>* hash = nullptr);
/// derive sub keys for private keys. hash is really only intended for
/// testing ands key_n if given.
bool derive_subkey_private(
PrivateKey& derived,
const SecretKey& root,
uint64_t key_n,
const AlignedBuffer<32>* hash = nullptr);
PrivateKey& derived, const SecretKey& root, uint64_t key_n, const AlignedBuffer<32>* hash = nullptr);
/// randomize buffer
void randomize(uint8_t* buf, size_t len);

@ -149,8 +149,7 @@ namespace llarp
using PQKeyPair = AlignedBuffer<PQ_KEYPAIRSIZE>;
/// PKE(result, publickey, secretkey, nonce)
using path_dh_func =
bool (*)(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&);
using path_dh_func = bool (*)(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&);
/// SH(result, body)
using shorthash_func = bool (*)(ShortHash&, const llarp_buffer_t&);

@ -92,11 +92,9 @@ namespace llarp::dht
}
if (nodes.size() == N)
{
std::transform(
nodes.begin(),
nodes.end(),
std::inserter(result, result.end()),
[](const auto& a) { return a.first; });
std::transform(nodes.begin(), nodes.end(), std::inserter(result, result.end()), [](const auto& a) {
return a.first;
});
return true;
}
@ -114,8 +112,7 @@ namespace llarp::dht
return result.size() == expecting;
}
bool FindCloseExcluding(
const Key_t& target, Key_t& result, const std::set<Key_t>& exclude) const
bool FindCloseExcluding(const Key_t& target, Key_t& result, const std::set<Key_t>& exclude) const
{
Key_t maxdist;
maxdist.Fill(0xff);
@ -139,10 +136,7 @@ namespace llarp::dht
}
bool GetManyNearExcluding(
const Key_t& target,
std::set<Key_t>& result,
size_t N,
const std::set<Key_t>& exclude) const
const Key_t& target, std::set<Key_t>& result, size_t N, const std::set<Key_t>& exclude) const
{
std::set<Key_t> s(exclude.begin(), exclude.end());

@ -36,8 +36,7 @@ namespace llarp
bool operator==(const MessageHeader& other) const
{
return id == other.id && fields == other.fields && qd_count == other.qd_count
&& an_count == other.an_count && ns_count == other.ns_count
&& ar_count == other.ar_count;
&& an_count == other.an_count && ns_count == other.ns_count && ar_count == other.ar_count;
}
};

@ -95,8 +95,8 @@ namespace llarp::dns
auto in_pos = in.data();
for (size_t i = 0; i < 64; i += 4)
{
if (not(oxenc::is_hex_digit(name[i]) and name[i + 1] == '.'
and oxenc::is_hex_digit(name[i + 2]) and name[i + 3] == '.'))
if (not(oxenc::is_hex_digit(name[i]) and name[i + 1] == '.' and oxenc::is_hex_digit(name[i + 2])
and name[i + 3] == '.'))
return std::nullopt;
// Flip the nybbles because the smallest one is first

@ -9,16 +9,12 @@ namespace llarp::dns
static auto logcat = log::Cat("dns");
Question::Question(Question&& other)
: qname(std::move(other.qname)),
qtype(std::move(other.qtype)),
qclass(std::move(other.qclass))
: qname(std::move(other.qname)), qtype(std::move(other.qtype)), qclass(std::move(other.qclass))
{}
Question::Question(const Question& other)
: qname(other.qname), qtype(other.qtype), qclass(other.qclass)
Question::Question(const Question& other) : qname(other.qname), qtype(other.qtype), qclass(other.qclass)
{}
Question::Question(std::string name, QType_t type)
: qname{std::move(name)}, qtype{type}, qclass{qClassIN}
Question::Question(std::string name, QType_t type) : qname{std::move(name)}, qtype{type}, qclass{qClassIN}
{
if (qname.empty())
throw std::invalid_argument{"qname cannot be empty"};
@ -105,8 +101,7 @@ namespace llarp::dns
bool Question::HasTLD(const std::string& tld) const
{
return qname.find(tld) != std::string::npos
&& qname.rfind(tld) == (qname.size() - tld.size()) - 1;
return qname.find(tld) != std::string::npos && qname.rfind(tld) == (qname.size() - tld.size()) - 1;
}
std::string Question::ToString() const

@ -7,11 +7,7 @@ namespace llarp::dns
static auto logcat = log::Cat("dns");
ResourceRecord::ResourceRecord(const ResourceRecord& other)
: rr_name(other.rr_name),
rr_type(other.rr_type),
rr_class(other.rr_class),
ttl(other.ttl),
rData(other.rData)
: rr_name(other.rr_name), rr_type(other.rr_type), rr_class(other.rr_class), ttl(other.ttl), rData(other.rData)
{}
ResourceRecord::ResourceRecord(ResourceRecord&& other)
@ -23,11 +19,7 @@ namespace llarp::dns
{}
ResourceRecord::ResourceRecord(std::string name, RRType_t type, RR_RData_t data)
: rr_name{std::move(name)},
rr_type{type},
rr_class{qClassIN},
ttl{1},
rData{std::move(data)}
: rr_name{std::move(name)}, rr_type{type}, rr_class{qClassIN}, ttl{1}, rData{std::move(data)}
{}
bool ResourceRecord::Encode(llarp_buffer_t* buf) const
@ -94,12 +86,7 @@ namespace llarp::dns
std::string ResourceRecord::ToString() const
{
return fmt::format(
"[RR name={} type={} class={} ttl={} rdata-size={}]",
rr_name,
rr_type,
rr_class,
ttl,
rData.size());
"[RR name={} type={} class={} ttl={} rdata-size={}]", rr_name, rr_type, rr_class, ttl, rData.size());
}
bool ResourceRecord::HasCNameForTLD(const std::string& tld) const

@ -14,10 +14,7 @@ namespace llarp::dns::sd
{
void Platform::set_resolver(unsigned int if_ndx, llarp::SockAddr dns, bool global)
{
linux::DBUS _dbus{
"org.freedesktop.resolve1",
"/org/freedesktop/resolve1",
"org.freedesktop.resolve1.Manager"};
linux::DBUS _dbus{"org.freedesktop.resolve1", "/org/freedesktop/resolve1", "org.freedesktop.resolve1.Manager"};
// This passing address by bytes and using two separate calls for ipv4/ipv6 is gross, but
// the alternative is to build up a bunch of crap with va_args, which is slightly more
// gross.

@ -18,6 +18,5 @@ namespace llarp::dns
void set_resolver(unsigned int if_index, llarp::SockAddr dns, bool global) override;
};
} // namespace sd
using SD_Platform_t =
std::conditional_t<llarp::platform::has_systemd, sd::Platform, Null_Platform>;
using SD_Platform_t = std::conditional_t<llarp::platform::has_systemd, sd::Platform, Null_Platform>;
} // namespace llarp::dns

@ -35,17 +35,14 @@ namespace llarp::dns
SockAddr m_LocalAddr;
public:
explicit UDPReader(Server& dns, const EventLoop_ptr& loop, llarp::SockAddr bindaddr)
: m_DNS{dns}
explicit UDPReader(Server& dns, const EventLoop_ptr& loop, llarp::SockAddr bindaddr) : m_DNS{dns}
{
m_udp = loop->make_udp([&](auto&, SockAddr src, llarp::OwnedBuffer buf) {
if (src == m_LocalAddr)
return;
if (not m_DNS.MaybeHandlePacket(
shared_from_this(), m_LocalAddr, src, std::move(buf)))
if (not m_DNS.MaybeHandlePacket(shared_from_this(), m_LocalAddr, src, std::move(buf)))
{
log::warning(
logcat, "did not handle dns packet from {} to {}", src, m_LocalAddr);
log::warning(logcat, "did not handle dns packet from {} to {}", src, m_LocalAddr);
}
});
m_udp->listen(bindaddr);
@ -172,8 +169,7 @@ namespace llarp::dns
if (auto err = ub_ctx_set_fwd(m_ctx, str.c_str()))
{
throw std::runtime_error{
fmt::format("cannot use {} as upstream dns: {}", str, ub_strerror(err))};
throw std::runtime_error{fmt::format("cannot use {} as upstream dns: {}", str, ub_strerror(err))};
}
}
@ -203,8 +199,7 @@ namespace llarp::dns
if constexpr (platform::is_apple)
{
if (dns.hostString() == "127.0.0.1"
and dns.getPort() == apple::dns_trampoline_port)
if (dns.hostString() == "127.0.0.1" and dns.getPort() == apple::dns_trampoline_port)
{
// macOS is stupid: the default (0.0.0.0) fails with "send failed: Can't
// assign requested address" when unbound tries to connect to the localhost
@ -251,8 +246,8 @@ namespace llarp::dns
if (fd == -1)
#endif
{
throw std::invalid_argument{fmt::format(
"Failed to create UDP socket for unbound: {}", strerror(errno))};
throw std::invalid_argument{
fmt::format("Failed to create UDP socket for unbound: {}", strerror(errno))};
}
#ifdef _WIN32
@ -263,8 +258,8 @@ namespace llarp::dns
if (0 != bind(fd, static_cast<const sockaddr*>(addr), addr.sockaddr_len()))
{
CLOSE(fd);
throw std::invalid_argument{fmt::format(
"Failed to bind UDP socket for unbound: {}", strerror(errno))};
throw std::invalid_argument{
fmt::format("Failed to bind UDP socket for unbound: {}", strerror(errno))};
}
struct sockaddr_storage sas;
auto* sa = reinterpret_cast<struct sockaddr*>(&sas);
@ -274,8 +269,8 @@ namespace llarp::dns
#undef CLOSE
if (rc != 0)
{
throw std::invalid_argument{fmt::format(
"Failed to query UDP port for unbound: {}", strerror(errno))};
throw std::invalid_argument{
fmt::format("Failed to query UDP port for unbound: {}", strerror(errno))};
}
addr = SockAddr{*sa};
}
@ -308,8 +303,7 @@ namespace llarp::dns
llarp::DnsConfig m_conf;
public:
explicit Resolver(const EventLoop_ptr& loop, llarp::DnsConfig conf)
: m_Loop{loop}, m_conf{std::move(conf)}
explicit Resolver(const EventLoop_ptr& loop, llarp::DnsConfig conf) : m_Loop{loop}, m_conf{std::move(conf)}
{
Up(m_conf);
}
@ -337,8 +331,7 @@ namespace llarp::dns
void Up(const llarp::DnsConfig& conf)
{
if (m_ctx)
throw std::logic_error{
"Internal error: attempt to Up() dns server multiple times"};
throw std::logic_error{"Internal error: attempt to Up() dns server multiple times"};
m_ctx = ::ub_ctx_create();
// set libunbound settings
@ -354,8 +347,7 @@ namespace llarp::dns
const auto str = file.u8string();
if (auto ret = ub_ctx_hosts(m_ctx, str.c_str()))
{
throw std::runtime_error{
fmt::format("Failed to add host file {}: {}", file, ub_strerror(ret))};
throw std::runtime_error{fmt::format("Failed to add host file {}: {}", file, ub_strerror(ret))};
}
}
@ -456,11 +448,7 @@ namespace llarp::dns
// no questions, send fail
if (query.questions.empty())
{
log::info(
logcat,
"dns from {} to {} has empty query questions, sending failure reply",
from,
to);
log::info(logcat, "dns from {} to {} has empty query questions, sending failure reply", from, to);
tmp->Cancel();
return true;
}
@ -512,18 +500,9 @@ namespace llarp::dns
#endif
const auto& q = query.questions[0];
if (auto err = ub_resolve_async(
m_ctx,
q.Name().c_str(),
q.qtype,
q.qclass,
tmp.get(),
&Resolver::Callback,
nullptr))
m_ctx, q.Name().c_str(), q.qtype, q.qclass, tmp.get(), &Resolver::Callback, nullptr))
{
log::warning(
logcat,
"failed to send upstream query with libunbound: {}",
ub_strerror(err));
log::warning(logcat, "failed to send upstream query with libunbound: {}", ub_strerror(err));
tmp->Cancel();
}
else
@ -543,20 +522,18 @@ namespace llarp::dns
auto parent_ptr = parent.lock();
if (parent_ptr)
{
parent_ptr->call([self = shared_from_this(),
parent_ptr = std::move(parent_ptr),
buf = replyBuf.copy()] {
log::trace(
logcat,
"forwarding dns response from libunbound to userland (resolverAddr: {}, "
"askerAddr: {})",
self->resolverAddr,
self->askerAddr);
self->src->SendTo(
self->askerAddr, self->resolverAddr, OwnedBuffer::copy_from(buf));
// remove query
parent_ptr->RemovePending(self);
});
parent_ptr->call(
[self = shared_from_this(), parent_ptr = std::move(parent_ptr), buf = replyBuf.copy()] {
log::trace(
logcat,
"forwarding dns response from libunbound to userland (resolverAddr: {}, "
"askerAddr: {})",
self->resolverAddr,
self->askerAddr);
self->src->SendTo(self->askerAddr, self->resolverAddr, OwnedBuffer::copy_from(buf));
// remove query
parent_ptr->RemovePending(self);
});
}
else
log::error(logcat, "no parent");
@ -600,8 +577,7 @@ namespace llarp::dns
return plat;
}
std::shared_ptr<PacketSource_Base> Server::MakePacketSourceOn(
const llarp::SockAddr& addr, const llarp::DnsConfig&)
std::shared_ptr<PacketSource_Base> Server::MakePacketSourceOn(const llarp::SockAddr& addr, const llarp::DnsConfig&)
{
return std::make_shared<UDPReader>(*this, m_Loop, addr);
}
@ -691,10 +667,7 @@ namespace llarp::dns
}
bool Server::MaybeHandlePacket(
std::shared_ptr<PacketSource_Base> ptr,
const SockAddr& to,
const SockAddr& from,
llarp::OwnedBuffer buf)
std::shared_ptr<PacketSource_Base> ptr, const SockAddr& to, const SockAddr& from, llarp::OwnedBuffer buf)
{
// dont process to prevent feedback loop
if (ptr->WouldLoop(to, from))
@ -706,8 +679,7 @@ namespace llarp::dns
auto maybe = MaybeParseDNSMessage(buf);
if (not maybe)
{
log::warning(
logcat, "invalid dns message format from {} to dns listener on {}", from, to);
log::warning(logcat, "invalid dns message format from {} to dns listener on {}", from, to);
return false;
}
@ -734,20 +706,10 @@ namespace llarp::dns
{
if (auto res_ptr = resolver.lock())
{
log::trace(
logcat,
"check resolver {} for dns from {} to {}",
res_ptr->ResolverName(),
from,
to);
log::trace(logcat, "check resolver {} for dns from {} to {}", res_ptr->ResolverName(), from, to);
if (res_ptr->MaybeHookDNS(ptr, msg, to, from))
{
log::trace(
logcat,
"resolver {} handling dns from {} to {}",
res_ptr->ResolverName(),
from,
to);
log::trace(logcat, "resolver {} handling dns from {} to {}", res_ptr->ResolverName(), from, to);
return true;
}
}

@ -74,8 +74,7 @@ namespace llarp::dns
public:
explicit PacketSource_Wrapper(
std::weak_ptr<PacketSource_Base> wrapped,
std::function<void(net::IPPacket)> write_packet)
std::weak_ptr<PacketSource_Base> wrapped, std::function<void(net::IPPacket)> write_packet)
: m_Wrapped{wrapped}, m_WritePacket{write_packet}
{}
@ -117,10 +116,7 @@ namespace llarp::dns
public:
explicit QueryJob(
std::shared_ptr<PacketSource_Base> source,
const Message& query,
const SockAddr& to_,
const SockAddr& from_)
std::shared_ptr<PacketSource_Base> source, const Message& query, const SockAddr& to_, const SockAddr& from_)
: QueryJob_Base{query}, src{source}, resolver{to_}, asker{from_}
{}
@ -248,8 +244,7 @@ namespace llarp::dns
private:
const unsigned int m_NetIfIndex;
std::set<std::shared_ptr<Resolver_Base>, ComparePtr<std::shared_ptr<Resolver_Base>>>
m_OwnedResolvers;
std::set<std::shared_ptr<Resolver_Base>, ComparePtr<std::shared_ptr<Resolver_Base>>> m_OwnedResolvers;
std::set<std::weak_ptr<Resolver_Base>, CompareWeakPtr<Resolver_Base>> m_Resolvers;
std::vector<std::weak_ptr<PacketSource_Base>> m_PacketSources;

@ -75,15 +75,13 @@ namespace llarp::dns
if (not parse_int(splits[1], priority))
{
log::warning(
logcat, "SRV record failed to parse \"{}\" as uint16_t (priority)", splits[1]);
log::warning(logcat, "SRV record failed to parse \"{}\" as uint16_t (priority)", splits[1]);
return false;
}
if (not parse_int(splits[2], weight))
{
log::warning(
logcat, "SRV record failed to parse \"{}\" as uint16_t (weight)", splits[2]);
log::warning(logcat, "SRV record failed to parse \"{}\" as uint16_t (weight)", splits[2]);
return false;
}
@ -112,8 +110,7 @@ namespace llarp::dns
if (not bencode_discard(buf))
return false;
byte_t* end = buf->cur;
std::string_view srvString{
reinterpret_cast<char*>(begin), static_cast<std::size_t>(end - begin)};
std::string_view srvString{reinterpret_cast<char*>(begin), static_cast<std::size_t>(end - begin)};
try
{
SRVTuple tuple{};
@ -130,10 +127,6 @@ namespace llarp::dns
util::StatusObject SRVData::ExtractStatus() const
{
return util::StatusObject{
{"proto", service_proto},
{"priority", priority},
{"weight", weight},
{"port", port},
{"target", target}};
{"proto", service_proto}, {"priority", priority}, {"weight", weight}, {"port", port}, {"target", target}};
}
} // namespace llarp::dns

@ -91,9 +91,8 @@ namespace std
{
const std::hash<std::string> h_str{};
const std::hash<uint16_t> h_port{};
return h_str(data.service_proto) ^ (h_str(data.target) << 3)
^ (h_port(data.priority) << 5) ^ (h_port(data.weight) << 7)
^ (h_port(data.port) << 9);
return h_str(data.service_proto) ^ (h_str(data.target) << 3) ^ (h_port(data.priority) << 5)
^ (h_port(data.weight) << 7) ^ (h_port(data.port) << 9);
}
};
} // namespace std

@ -104,11 +104,9 @@ namespace llarp
virtual link::TunnelManager* GetQUICTunnel() = 0;
virtual std::optional<AddressVariant_t> GetEndpointWithConvoTag(
service::ConvoTag tag) const = 0;
virtual std::optional<AddressVariant_t> GetEndpointWithConvoTag(service::ConvoTag tag) const = 0;
virtual std::optional<service::ConvoTag> GetBestConvoTagFor(
AddressVariant_t addr) const = 0;
virtual std::optional<service::ConvoTag> GetBestConvoTagFor(AddressVariant_t addr) const = 0;
virtual bool EnsurePathTo(
AddressVariant_t addr,
@ -123,9 +121,7 @@ namespace llarp
/// lookup srv records async
virtual void LookupServiceAsync(
std::string name,
std::string service,
std::function<void(std::vector<dns::SRVData>)> resultHandler) = 0;
std::string name, std::string service, std::function<void(std::vector<dns::SRVData>)> resultHandler) = 0;
virtual void MarkAddressOutbound(service::Address remote) = 0;
};

@ -37,11 +37,7 @@ namespace llarp
[[maybe_unused]] T&&... args)
{
if (cat_logger)
cat_logger->log(
log::detail::spdlog_sloc(location),
log::Level::trace,
fmt,
std::forward<T>(args)...);
cat_logger->log(log::detail::spdlog_sloc(location), log::Level::trace, fmt, std::forward<T>(args)...);
}
namespace vpn
@ -146,19 +142,14 @@ namespace llarp
{
auto repeater = make_repeater();
auto& r = *repeater; // reference *before* we pass ownership into the lambda below
r.start(
repeat,
[repeater = std::move(repeater),
owner = std::move(owner),
f = std::move(f)]() mutable {
if (auto ptr = owner.lock())
f();
else
repeater
.reset(); // Trigger timer removal on tied object destruction (we
r.start(repeat, [repeater = std::move(repeater), owner = std::move(owner), f = std::move(f)]() mutable {
if (auto ptr = owner.lock())
f();
else
repeater.reset(); // Trigger timer removal on tied object destruction (we
// should be the only thing holding the repeater; ideally it
// would be a unique_ptr, but std::function says nuh-uh).
});
});
}
/// Calls a function and synchronously obtains its return value. If called from within the
@ -220,8 +211,7 @@ namespace llarp
}
virtual bool add_network_interface(
std::shared_ptr<vpn::NetworkInterface> netif,
std::function<void(net::IPPacket)> packetHandler) = 0;
std::shared_ptr<vpn::NetworkInterface> netif, std::function<void(net::IPPacket)> packetHandler) = 0;
virtual bool add_ticker(std::function<void(void)> ticker) = 0;
@ -231,8 +221,7 @@ namespace llarp
virtual const net::Platform* Net_ptr() const;
using UDPReceiveFunc =
std::function<void(UDPHandle&, SockAddr src, llarp::OwnedBuffer buf)>;
using UDPReceiveFunc = std::function<void(UDPHandle&, SockAddr src, llarp::OwnedBuffer buf)>;
// Constructs a UDP socket that can be used for sending and/or receiving
virtual std::shared_ptr<UDPHandle> make_udp(UDPReceiveFunc on_recv) = 0;

@ -22,8 +22,7 @@ namespace llarp::uv
std::shared_ptr<uvw::AsyncHandle> async;
public:
UVWakeup(uvw::Loop& loop, std::function<void()> callback)
: async{loop.resource<uvw::AsyncHandle>()}
UVWakeup(uvw::Loop& loop, std::function<void()> callback) : async{loop.resource<uvw::AsyncHandle>()}
{
async->on<uvw::AsyncEvent>([f = std::move(callback)](auto&, auto&) { f(); });
}
@ -159,8 +158,7 @@ namespace llarp::uv
std::make_shared<llarp::uv::UDPHandle>(*m_Impl, std::move(on_recv)));
}
static void setup_oneshot_timer(
uvw::Loop& loop, llarp_time_t delay, std::function<void()> callback)
static void setup_oneshot_timer(uvw::Loop& loop, llarp_time_t delay, std::function<void()> callback)
{
auto timer = loop.resource<uvw::TimerHandle>();
timer->on<uvw::TimerEvent>([f = std::move(callback)](const auto&, auto& timer) {
@ -222,8 +220,7 @@ namespace llarp::uv
}
bool Loop::add_network_interface(
std::shared_ptr<llarp::vpn::NetworkInterface> netif,
std::function<void(llarp::net::IPPacket)> handler)
std::shared_ptr<llarp::vpn::NetworkInterface> netif, std::function<void(llarp::net::IPPacket)> handler)
{
#ifdef __linux__
using event_t = uvw::PollEvent;
@ -239,20 +236,20 @@ namespace llarp::uv
if (!handle)
return false;
handle->on<event_t>([netif = std::move(netif), handler = std::move(handler)](
const event_t&, [[maybe_unused]] auto& handle) {
for (auto pkt = netif->ReadNextPacket(); true; pkt = netif->ReadNextPacket())
{
if (pkt.empty())
return;
if (handler)
handler(std::move(pkt));
// on windows/apple, vpn packet io does not happen as an io action that wakes up the
// event loop thus, we must manually wake up the event loop when we get a packet on
// our interface. on linux/android this is a nop
netif->MaybeWakeUpperLayers();
}
});
handle->on<event_t>(
[netif = std::move(netif), handler = std::move(handler)](const event_t&, [[maybe_unused]] auto& handle) {
for (auto pkt = netif->ReadNextPacket(); true; pkt = netif->ReadNextPacket())
{
if (pkt.empty())
return;
if (handler)
handler(std::move(pkt));
// on windows/apple, vpn packet io does not happen as an io action that wakes up the
// event loop thus, we must manually wake up the event loop when we get a packet on
// our interface. on linux/android this is a nop
netif->MaybeWakeUpperLayers();
}
});
#ifdef __linux__
handle->start(uvw::PollHandle::Event::READABLE);
@ -295,8 +292,7 @@ namespace llarp::uv
});
}
llarp::uv::UDPHandle::UDPHandle(uvw::Loop& loop, ReceiveFunc rf)
: llarp::UDPHandle{std::move(rf)}
llarp::uv::UDPHandle::UDPHandle(uvw::Loop& loop, ReceiveFunc rf) : llarp::UDPHandle{std::move(rf)}
{
reset_handle(loop);
}

@ -23,10 +23,7 @@ namespace llarp::exit
/// send close to all exit sessions and remove all sessions
void stop();
void add_exit_endpoint(
const std::string& name,
const NetworkConfig& networkConfig,
const DnsConfig& dnsConfig);
void add_exit_endpoint(const std::string& name, const NetworkConfig& networkConfig, const DnsConfig& dnsConfig);
bool obtain_new_exit(const PubKey& remote, const PathID_t& path, bool permitInternet);

@ -90,8 +90,7 @@ namespace llarp::exit
// p->AddObtainExitHandler(util::memFn(&BaseSession::HandleGotExit, this));
// TODO: add callback here
if (p->obtain_exit(
exit_key, std::is_same_v<decltype(p), ExitSession> ? 1 : 0, p->TXID().bt_encode()))
if (p->obtain_exit(exit_key, std::is_same_v<decltype(p), ExitSession> ? 1 : 0, p->TXID().bt_encode()))
log::info(logcat, "Asking {} for exit", exit_router);
else
log::warning(logcat, "Failed to send exit request");
@ -170,8 +169,7 @@ namespace llarp::exit
return path::PathBuilder::Stop();
}
bool BaseSession::HandleTraffic(
std::shared_ptr<path::Path>, const llarp_buffer_t&, uint64_t, service::ProtocolType)
bool BaseSession::HandleTraffic(std::shared_ptr<path::Path>, const llarp_buffer_t&, uint64_t, service::ProtocolType)
{
// const service::ConvoTag tag{path->RXID().as_array()};
@ -196,8 +194,7 @@ namespace llarp::exit
return false;
}
bool BaseSession::HandleTrafficDrop(
std::shared_ptr<path::Path> p, const PathID_t& path, uint64_t s)
bool BaseSession::HandleTrafficDrop(std::shared_ptr<path::Path> p, const PathID_t& path, uint64_t s)
{
llarp::LogError("dropped traffic on exit ", exit_router, " S=", s, " P=", path);
p->EnterState(path::PathStatus::IGNORE, router->now());

@ -24,8 +24,7 @@ namespace llarp
using SessionReadyFunc = std::function<void(std::shared_ptr<BaseSession>)>;
/// a persisting exit session with an exit router
struct BaseSession : public llarp::path::PathBuilder,
public std::enable_shared_from_this<BaseSession>
struct BaseSession : public llarp::path::PathBuilder, public std::enable_shared_from_this<BaseSession>
{
BaseSession(
const llarp::RouterID& exitRouter,
@ -104,16 +103,12 @@ namespace llarp
llarp::SecretKey exit_key;
std::function<bool(const llarp_buffer_t&)> packet_write_func;
bool HandleTrafficDrop(
std::shared_ptr<path::Path> p, const llarp::PathID_t& path, uint64_t s);
bool HandleTrafficDrop(std::shared_ptr<path::Path> p, const llarp::PathID_t& path, uint64_t s);
bool HandleGotExit(std::shared_ptr<path::Path> p, llarp_time_t b);
bool HandleTraffic(
std::shared_ptr<path::Path> p,
const llarp_buffer_t& buf,
uint64_t seqno,
service::ProtocolType t);
std::shared_ptr<path::Path> p, const llarp_buffer_t& buf, uint64_t seqno, service::ProtocolType t);
private:
std::set<RouterID> snode_blacklist;

@ -31,8 +31,7 @@ namespace llarp::handlers
resultHandler({});
}
std::optional<EndpointBase::AddressVariant_t> ExitEndpoint::GetEndpointWithConvoTag(
service::ConvoTag tag) const
std::optional<EndpointBase::AddressVariant_t> ExitEndpoint::GetEndpointWithConvoTag(service::ConvoTag tag) const
{
for (const auto& [pathID, pk] : paths)
{
@ -94,8 +93,7 @@ namespace llarp::handlers
{
if (not itr->second->LooksDead(Now()))
{
return router->send_data_message(
itr->second->router_id(), std::move(payload));
return router->send_data_message(itr->second->router_id(), std::move(payload));
}
}
@ -103,9 +101,7 @@ namespace llarp::handlers
return false;
ObtainSNodeSession(
*rid,
[pkt = std::move(payload)](
std::shared_ptr<llarp::exit::BaseSession> session) mutable {
*rid, [pkt = std::move(payload)](std::shared_ptr<llarp::exit::BaseSession> session) mutable {
if (session and session->IsReady())
{
session->send_packet_to_remote(std::move(pkt));
@ -118,9 +114,7 @@ namespace llarp::handlers
}
bool ExitEndpoint::EnsurePathTo(
AddressVariant_t addr,
std::function<void(std::optional<service::ConvoTag>)> hook,
llarp_time_t)
AddressVariant_t addr, std::function<void(std::optional<service::ConvoTag>)> hook, llarp_time_t)
{
if (std::holds_alternative<service::Address>(addr))
return false;
@ -128,20 +122,19 @@ namespace llarp::handlers
{
if (snode_keys.count(PubKey{*rid}) or router->PathToRouterAllowed(*rid))
{
ObtainSNodeSession(
*rid, [hook, routerID = *rid](std::shared_ptr<exit::BaseSession> session) {
if (session and session->IsReady())
ObtainSNodeSession(*rid, [hook, routerID = *rid](std::shared_ptr<exit::BaseSession> session) {
if (session and session->IsReady())
{
if (auto path = session->GetPathByRouter(routerID))
{
if (auto path = session->GetPathByRouter(routerID))
{
hook(service::ConvoTag{path->RXID().as_array()});
}
else
hook(std::nullopt);
hook(service::ConvoTag{path->RXID().as_array()});
}
else
hook(std::nullopt);
});
}
else
hook(std::nullopt);
});
}
else
{
@ -206,8 +199,7 @@ namespace llarp::handlers
return true;
}
bool ExitEndpoint::HandleHookedDNSMessage(
dns::Message msg, std::function<void(dns::Message)> reply)
bool ExitEndpoint::HandleHookedDNSMessage(dns::Message msg, std::function<void(dns::Message)> reply)
{
if (msg.questions[0].qtype == dns::qTypePTR)
{
@ -336,8 +328,7 @@ namespace llarp::handlers
return router->now();
}
bool ExitEndpoint::VisitEndpointsFor(
const PubKey& pk, std::function<bool(exit::Endpoint* const)> visit) const
bool ExitEndpoint::VisitEndpointsFor(const PubKey& pk, std::function<bool(exit::Endpoint* const)> visit) const
{
for (auto [itr, end] = active_exits.equal_range(pk); itr != end; ++itr)
{
@ -383,15 +374,10 @@ namespace llarp::handlers
continue;
}
}
auto tryFlushingTraffic =
[this, buf = std::move(buf), pk](exit::Endpoint* const ep) -> bool {
auto tryFlushingTraffic = [this, buf = std::move(buf), pk](exit::Endpoint* const ep) -> bool {
if (!ep->QueueInboundTraffic(buf._buf, service::ProtocolType::TrafficV4))
{
LogWarn(
Name(),
" dropped inbound traffic for session ",
pk,
" as we are overloaded (probably)");
LogWarn(Name(), " dropped inbound traffic for session ", pk, " as we are overloaded (probably)");
// continue iteration
return true;
}
@ -401,11 +387,7 @@ namespace llarp::handlers
if (!VisitEndpointsFor(pk, tryFlushingTraffic))
{
// we may have all dead sessions, wtf now?
LogWarn(
Name(),
" dropped inbound traffic for session ",
pk,
" as we have no working endpoints");
LogWarn(Name(), " dropped inbound traffic for session ", pk, " as we have no working endpoints");
}
}
@ -454,8 +436,7 @@ namespace llarp::handlers
GetRouter()->loop()->add_ticker([this] { Flush(); });
#ifndef _WIN32
resolver = std::make_shared<dns::Server>(
router->loop(), dns_conf, if_nametoindex(if_name.c_str()));
resolver = std::make_shared<dns::Server>(router->loop(), dns_conf, if_nametoindex(if_name.c_str()));
resolver->Start();
#endif
@ -744,8 +725,7 @@ namespace llarp::handlers
// mark it as such so we don't make an outbound session to them
snode_keys.emplace(pk.as_array());
}
active_exits.emplace(
pk, std::make_unique<exit::Endpoint>(pk, handler, !wantInternet, ip, this));
active_exits.emplace(pk, std::make_unique<exit::Endpoint>(pk, handler, !wantInternet, ip, this));
paths[path] = pk;

@ -35,8 +35,7 @@ namespace llarp::handlers
ExitEndpoint(std::string name, Router* r);
~ExitEndpoint() override;
std::optional<AddressVariant_t> GetEndpointWithConvoTag(
service::ConvoTag tag) const override;
std::optional<AddressVariant_t> GetEndpointWithConvoTag(service::ConvoTag tag) const override;
std::optional<service::ConvoTag> GetBestConvoTagFor(AddressVariant_t addr) const override;
@ -63,8 +62,7 @@ namespace llarp::handlers
std::string Name() const;
bool VisitEndpointsFor(
const PubKey& pk, std::function<bool(exit::Endpoint* const)> visit) const;
bool VisitEndpointsFor(const PubKey& pk, std::function<bool(exit::Endpoint* const)> visit) const;
util::StatusObject ExtractStatus() const;
@ -75,9 +73,7 @@ namespace llarp::handlers
bool HandleHookedDNSMessage(dns::Message msg, std::function<void(dns::Message)>);
void LookupServiceAsync(
std::string name,
std::string service,
std::function<void(std::vector<dns::SRVData>)> handler) override;
std::string name, std::string service, std::function<void(std::vector<dns::SRVData>)> handler) override;
bool AllocateNewExit(const PubKey pk, const PathID_t& path, bool permitInternet);
@ -187,8 +183,8 @@ namespace llarp::handlers
// std::shared_ptr<link::TunnelManager> tunnel_manager;
using PacketQueue_t = std::
priority_queue<net::IPPacket, std::vector<net::IPPacket>, net::IPPacket::CompareOrder>;
using PacketQueue_t =
std::priority_queue<net::IPPacket, std::vector<net::IPPacket>, net::IPPacket::CompareOrder>;
/// internet to llarp packet queue
PacketQueue_t inet_to_network;

@ -9,16 +9,12 @@
namespace llarp::handlers
{
struct NullEndpoint final : public llarp::service::Endpoint,
public std::enable_shared_from_this<NullEndpoint>
struct NullEndpoint final : public llarp::service::Endpoint, public std::enable_shared_from_this<NullEndpoint>
{
NullEndpoint(Router* r, llarp::service::Context* parent)
: llarp::service::Endpoint{r, parent},
m_PacketRouter{new vpn::EgresPacketRouter{[](auto from, auto pkt) {
: llarp::service::Endpoint{r, parent}, m_PacketRouter{new vpn::EgresPacketRouter{[](auto from, auto pkt) {
var::visit(
[&pkt](auto&& from) {
LogError("unhandled traffic from: ", from, " of ", pkt.size(), " bytes");
},
[&pkt](auto&& from) { LogError("unhandled traffic from: ", from, " of ", pkt.size(), " bytes"); },
from);
}}}
{
@ -26,10 +22,7 @@ namespace llarp::handlers
}
bool HandleInboundPacket(
const service::ConvoTag tag,
const llarp_buffer_t& buf,
service::ProtocolType t,
uint64_t) override
const service::ConvoTag tag, const llarp_buffer_t& buf, service::ProtocolType t, uint64_t) override
{
LogTrace("Inbound ", t, " packet (", buf.sz, "B) on convo ", tag);
if (t == service::ProtocolType::Control)
@ -99,8 +92,7 @@ namespace llarp::handlers
return {0};
}
std::optional<std::variant<service::Address, RouterID>> ObtainAddrForIP(
huint128_t) const override
std::optional<std::variant<service::Address, RouterID>> ObtainAddrForIP(huint128_t) const override
{
return std::nullopt;
}

@ -52,8 +52,7 @@ namespace llarp::handlers
llarp::DnsConfig m_Config;
public:
explicit DnsInterceptor(
std::function<void(net::IPPacket)> reply, net::ipaddr_t our_ip, llarp::DnsConfig conf)
explicit DnsInterceptor(std::function<void(net::IPPacket)> reply, net::ipaddr_t our_ip, llarp::DnsConfig conf)
: m_Reply{std::move(reply)}, m_OurIP{std::move(our_ip)}, m_Config{std::move(conf)}
{}
@ -131,8 +130,8 @@ namespace llarp::handlers
TunEndpoint::TunEndpoint(Router* r, service::Context* parent) : service::Endpoint{r, parent}
{
m_PacketRouter = std::make_shared<vpn::PacketRouter>(
[this](net::IPPacket pkt) { HandleGotUserPacket(std::move(pkt)); });
m_PacketRouter =
std::make_shared<vpn::PacketRouter>([this](net::IPPacket pkt) { HandleGotUserPacket(std::move(pkt)); });
}
void TunEndpoint::SetupDNS()
@ -147,8 +146,7 @@ namespace llarp::handlers
auto dns_pkt_src = dns->PacketSource;
if (const auto& reply = pkt.reply)
dns_pkt_src = std::make_shared<dns::PacketSource_Wrapper>(dns_pkt_src, reply);
if (dns->MaybeHandlePacket(
std::move(dns_pkt_src), pkt.dst(), pkt.src(), *pkt.L4OwnedBuffer()))
if (dns->MaybeHandlePacket(std::move(dns_pkt_src), pkt.dst(), pkt.src(), *pkt.L4OwnedBuffer()))
return;
HandleGotUserPacket(std::move(pkt));
@ -178,15 +176,14 @@ namespace llarp::handlers
if (platform::is_windows)
{
auto dns_io = vpn->create_packet_io(0, localaddr);
router()->loop()->add_ticker(
[r = router(), dns_io, handler = m_PacketRouter]() {
net::IPPacket pkt = dns_io->ReadNextPacket();
while (not pkt.empty())
{
handler->HandleIPPacket(std::move(pkt));
pkt = dns_io->ReadNextPacket();
}
});
router()->loop()->add_ticker([r = router(), dns_io, handler = m_PacketRouter]() {
net::IPPacket pkt = dns_io->ReadNextPacket();
while (not pkt.empty())
{
handler->HandleIPPacket(std::move(pkt));
pkt = dns_io->ReadNextPacket();
}
});
m_RawDNS = dns_io;
}
}
@ -270,8 +267,7 @@ namespace llarp::handlers
if (conf.auth_type == service::AuthType::FILE)
{
_auth_policy =
service::make_file_auth_policy(router(), conf.auth_files, conf.auth_file_type);
_auth_policy = service::make_file_auth_policy(router(), conf.auth_files, conf.auth_file_type);
}
else if (conf.auth_type != service::AuthType::NONE)
{
@ -282,12 +278,7 @@ namespace llarp::handlers
method = *conf.auth_method;
}
auto auth = std::make_shared<rpc::EndpointAuthRPC>(
url,
method,
conf.auth_whitelist,
conf.auth_static_tokens,
router()->lmq(),
shared_from_this());
url, method, conf.auth_whitelist, conf.auth_static_tokens, router()->lmq(), shared_from_this());
auth->Start();
_auth_policy = std::move(auth);
}
@ -366,15 +357,10 @@ namespace llarp::handlers
{
if (shouldLoadFile)
{
LogInfo(
Name(),
" address map file ",
file,
" does not exist, so we won't load it");
LogInfo(Name(), " address map file ", file, " does not exist, so we won't load it");
}
else
LogInfo(
Name(), " address map file ", file, " not loaded because it's stale");
LogInfo(Name(), " address map file ", file, " not loaded because it's stale");
}
if (not data.empty())
{
@ -441,11 +427,7 @@ namespace llarp::handlers
}
else
{
LogInfo(
Name(),
" skipping loading addr map at ",
file,
" as it does not currently exist");
LogInfo(Name(), " skipping loading addr map at ", file, " as it does not currently exist");
}
}
@ -483,8 +465,7 @@ namespace llarp::handlers
return msg;
}
std::optional<std::variant<service::Address, RouterID>> TunEndpoint::ObtainAddrForIP(
huint128_t ip) const
std::optional<std::variant<service::Address, RouterID>> TunEndpoint::ObtainAddrForIP(huint128_t ip) const
{
auto itr = m_IPToAddr.find(ip);
if (itr == m_IPToAddr.end())
@ -495,16 +476,13 @@ namespace llarp::handlers
return service::Address{itr->second.as_array()};
}
bool TunEndpoint::HandleHookedDNSMessage(
dns::Message msg, std::function<void(dns::Message)> reply)
bool TunEndpoint::HandleHookedDNSMessage(dns::Message msg, std::function<void(dns::Message)> reply)
{
auto ReplyToSNodeDNSWhenReady = [this, reply](RouterID snode, auto msg, bool isV6) -> bool {
return EnsurePathToSNode(
snode,
[this, snode, msg, reply, isV6](
const RouterID&,
std::shared_ptr<exit::BaseSession> s,
[[maybe_unused]] service::ConvoTag tag) {
const RouterID&, std::shared_ptr<exit::BaseSession> s, [[maybe_unused]] service::ConvoTag tag) {
SendDNSReply(snode, s, msg, reply, isV6);
});
};
@ -652,25 +630,23 @@ namespace llarp::handlers
{
// mx record
service::Address addr;
if (addr.FromString(qname, ".loki") || addr.FromString(qname, ".snode")
|| is_random_snode(msg) || is_localhost_loki(msg))
if (addr.FromString(qname, ".loki") || addr.FromString(qname, ".snode") || is_random_snode(msg)
|| is_localhost_loki(msg))
{
msg.AddMXReply(qname, 1);
}
else if (service::is_valid_name(ons_name))
{
lookup_name(
ons_name,
[msg, ons_name, reply](std::string name_result, bool success) mutable {
if (success)
{
msg.AddMXReply(name_result, 1);
}
else
msg.AddNXReply();
lookup_name(ons_name, [msg, ons_name, reply](std::string name_result, bool success) mutable {
if (success)
{
msg.AddMXReply(name_result, 1);
}
else
msg.AddNXReply();
reply(msg);
});
reply(msg);
});
return true;
}
@ -694,9 +670,8 @@ namespace llarp::handlers
const auto subdomain = msg.questions[0].Subdomains();
if (subdomain == "exit" and HasExit())
{
_exit_map.ForEachEntry([&msg](const auto&, const auto& exit) {
msg.AddCNAMEReply(exit.ToString(), 1);
});
_exit_map.ForEachEntry(
[&msg](const auto&, const auto& exit) { msg.AddCNAMEReply(exit.ToString(), 1); });
}
else
{
@ -707,8 +682,7 @@ namespace llarp::handlers
{
size_t counter = 0;
context->ForEachService(
[&](const std::string&,
const std::shared_ptr<service::Endpoint>& service) -> bool {
[&](const std::string&, const std::shared_ptr<service::Endpoint>& service) -> bool {
const service::Address addr = service->GetIdentity().pub.Addr();
msg.AddCNAMEReply(addr.ToString(), 1);
++counter;
@ -736,8 +710,7 @@ namespace llarp::handlers
if (auto random = router()->GetRandomGoodRouter())
{
msg.AddCNAMEReply(random->ToString(), 1);
return ReplyToSNodeDNSWhenReady(
*random, std::make_shared<dns::Message>(msg), isV6);
return ReplyToSNodeDNSWhenReady(*random, std::make_shared<dns::Message>(msg), isV6);
}
msg.AddNXReply();
@ -752,9 +725,8 @@ namespace llarp::handlers
{
if (HasExit())
{
_exit_map.ForEachEntry([&msg](const auto&, const auto& exit) {
msg.AddCNAMEReply(exit.ToString());
});
_exit_map.ForEachEntry(
[&msg](const auto&, const auto& exit) { msg.AddCNAMEReply(exit.ToString()); });
msg.AddINReply(ip, isV6);
}
else
@ -792,8 +764,7 @@ namespace llarp::handlers
}
else
{
return ReplyToSNodeDNSWhenReady(
addr.as_array(), std::make_shared<dns::Message>(msg), isV6);
return ReplyToSNodeDNSWhenReady(addr.as_array(), std::make_shared<dns::Message>(msg), isV6);
}
}
else if (service::is_valid_name(ons_name))
@ -850,9 +821,7 @@ namespace llarp::handlers
return true;
}
LookupServiceAsync(
name,
srv_for,
[reply, msg = std::make_shared<dns::Message>(std::move(msg))](auto records) {
name, srv_for, [reply, msg = std::make_shared<dns::Message>(std::move(msg))](auto records) {
if (records.empty())
{
msg->AddNXReply();
@ -918,8 +887,7 @@ namespace llarp::handlers
auto itr = m_IPToAddr.find(ip);
if (itr != m_IPToAddr.end())
{
llarp::LogWarn(
ip, " already mapped to ", service::Address(itr->second.as_array()).ToString());
llarp::LogWarn(ip, " already mapped to ", service::Address(itr->second.as_array()).ToString());
return false;
}
llarp::LogInfo(Name() + " map ", addr.ToString(), " to ", ip);
@ -1007,8 +975,8 @@ namespace llarp::handlers
return false;
}
m_OurIPv6 = llarp::huint128_t{
llarp::uint128_t{0xfd2e'6c6f'6b69'0000, llarp::net::TruncateV6(m_OurRange.addr).h}};
m_OurIPv6 =
llarp::huint128_t{llarp::uint128_t{0xfd2e'6c6f'6b69'0000, llarp::net::TruncateV6(m_OurRange.addr).h}};
if constexpr (not llarp::platform::is_apple)
{
@ -1083,8 +1051,7 @@ namespace llarp::handlers
}
std::optional<service::Address> TunEndpoint::ObtainExitAddressFor(
huint128_t ip,
std::function<service::Address(std::unordered_set<service::Address>)> exitSelectionStrat)
huint128_t ip, std::function<service::Address(std::unordered_set<service::Address>)> exitSelectionStrat)
{
// is it already mapped? return the mapping
if (auto itr = m_ExitIPToExitAddress.find(ip); itr != m_ExitIPToExitAddress.end())
@ -1099,8 +1066,7 @@ namespace llarp::handlers
{
// in the event the exit's range is a bogon range, make sure the ip is located in that
// range to allow it
if ((is_bogon and net.IsBogonRange(entry.first) and entry.first.Contains(ip))
or entry.first.Contains(ip))
if ((is_bogon and net.IsBogonRange(entry.first) and entry.first.Contains(ip)) or entry.first.Contains(ip))
candidates.emplace(entry.second);
}
// no candidates? bail.
@ -1176,8 +1142,7 @@ namespace llarp::handlers
EnsurePathToService(
addr,
[pkt, extra_cb, this](
service::Address addr, service::OutboundContext* ctx) mutable {
[pkt, extra_cb, this](service::Address addr, service::OutboundContext* ctx) mutable {
if (ctx)
{
if (extra_cb)
@ -1201,8 +1166,7 @@ namespace llarp::handlers
else
{
to = service::Address{itr->second.as_array()};
type = _state->is_exit_enabled and src != m_OurIP ? service::ProtocolType::Exit
: pkt.ServiceProtocol();
type = _state->is_exit_enabled and src != m_OurIP ? service::ProtocolType::Exit : pkt.ServiceProtocol();
}
// prepare packet for insertion into network
@ -1235,8 +1199,7 @@ namespace llarp::handlers
{
var::visit(
[this](auto&& addr) {
LogWarn(
Name(), " failed to ensure path to ", addr, " no convo tag found");
LogWarn(Name(), " failed to ensure path to ", addr, " no convo tag found");
},
to);
}
@ -1248,9 +1211,7 @@ namespace llarp::handlers
else
{
var::visit(
[this](auto&& addr) {
LogWarn(Name(), " failed to send to ", addr, ", SendToOrQueue failed");
},
[this](auto&& addr) { LogWarn(Name(), " failed to send to ", addr, ", SendToOrQueue failed"); },
to);
}
},
@ -1269,10 +1230,7 @@ namespace llarp::handlers
}
bool TunEndpoint::HandleInboundPacket(
const service::ConvoTag tag,
const llarp_buffer_t& buf,
service::ProtocolType t,
uint64_t seqno)
const service::ConvoTag tag, const llarp_buffer_t& buf, service::ProtocolType t, uint64_t seqno)
{
LogTrace("Inbound ", t, " packet (", buf.sz, "B) on convo ", tag);
if (t == service::ProtocolType::QUIC)
@ -1376,8 +1334,7 @@ namespace llarp::handlers
return true;
}
bool TunEndpoint::HandleWriteIPPacket(
const llarp_buffer_t& b, huint128_t src, huint128_t dst, uint64_t seqno)
bool TunEndpoint::HandleWriteIPPacket(const llarp_buffer_t& b, huint128_t src, huint128_t dst, uint64_t seqno)
{
ManagedBuffer buf(b);
WritePacket write;
@ -1446,11 +1403,7 @@ namespace llarp::handlers
m_AddrToIP[ident] = nextIP;
m_IPToAddr[nextIP] = ident;
m_SNodes[ident] = snode;
var::visit(
[&](auto&& remote) {
llarp::LogInfo(Name(), " mapped ", remote, " to ", nextIP);
},
addr);
var::visit([&](auto&& remote) { llarp::LogInfo(Name(), " mapped ", remote, " to ", nextIP); }, addr);
MarkIPActive(nextIP);
return nextIP;
}

@ -77,8 +77,7 @@ namespace llarp::handlers
bool ShouldHookDNSMessage(const dns::Message& msg) const;
bool HandleHookedDNSMessage(
dns::Message query, std::function<void(dns::Message)> sendreply);
bool HandleHookedDNSMessage(dns::Message query, std::function<void(dns::Message)> sendreply);
void TickTun(llarp_time_t now);
@ -106,14 +105,10 @@ namespace llarp::handlers
/// overrides Endpoint
bool HandleInboundPacket(
const service::ConvoTag tag,
const llarp_buffer_t& pkt,
service::ProtocolType t,
uint64_t seqno) override;
const service::ConvoTag tag, const llarp_buffer_t& pkt, service::ProtocolType t, uint64_t seqno) override;
/// handle inbound traffic
bool HandleWriteIPPacket(
const llarp_buffer_t& buf, huint128_t src, huint128_t dst, uint64_t seqno);
bool HandleWriteIPPacket(const llarp_buffer_t& buf, huint128_t src, huint128_t dst, uint64_t seqno);
/// we got a packet from the user
void HandleGotUserPacket(llarp::net::IPPacket pkt);
@ -150,8 +145,7 @@ namespace llarp::handlers
bool ShouldAllowTraffic(const net::IPPacket& pkt) const;
/// get a key for ip address
std::optional<std::variant<service::Address, RouterID>> ObtainAddrForIP(
huint128_t ip) const override;
std::optional<std::variant<service::Address, RouterID>> ObtainAddrForIP(huint128_t ip) const override;
bool HasAddress(const AlignedBuffer<32>& addr) const
{
@ -206,8 +200,7 @@ namespace llarp::handlers
/// return std::nullopt if we cannot route this address to an exit
std::optional<service::Address> ObtainExitAddressFor(
huint128_t ip,
std::function<service::Address(std::unordered_set<service::Address>)>
exitSelectionStrat = nullptr);
std::function<service::Address(std::unordered_set<service::Address>)> exitSelectionStrat = nullptr);
template <typename Addr_t, typename Endpoint_t>
void SendDNSReply(

@ -12,8 +12,7 @@ namespace llarp
_introset_nodes = std::make_unique<dht::Bucket<dht::ISNode>>(_local_key, llarp::randint);
}
std::optional<service::EncryptedIntroSet> Contacts::get_introset_by_location(
const dht::Key_t& key) const
std::optional<service::EncryptedIntroSet> Contacts::get_introset_by_location(const dht::Key_t& key) const
{
std::optional<service::EncryptedIntroSet> enc = std::nullopt;
@ -27,8 +26,7 @@ namespace llarp
util::StatusObject Contacts::ExtractStatus() const
{
util::StatusObject obj{
{"services", _introset_nodes->ExtractStatus()}, {"local_key", _local_key.ToHex()}};
util::StatusObject obj{{"services", _introset_nodes->ExtractStatus()}, {"local_key", _local_key.ToHex()}};
return obj;
}

@ -24,8 +24,7 @@ namespace llarp
public:
Contacts(Router& r);
std::optional<service::EncryptedIntroSet> get_introset_by_location(
const dht::Key_t& key) const;
std::optional<service::EncryptedIntroSet> get_introset_by_location(const dht::Key_t& key) const;
// TODO: rename every ExtractStatus function to be uniformly snake cased
util::StatusObject ExtractStatus() const;

@ -26,8 +26,7 @@ namespace llarp::quic
auto peer = client.peer();
LogTrace(peer.ip, ":", peer.port, " → lokinet ", buffer_printer{data});
// Steal the buffer from the DataEvent's unique_ptr<char[]>:
stream->append_buffer(
reinterpret_cast<const std::byte*>(event.data.release()), event.length);
stream->append_buffer(reinterpret_cast<const std::byte*>(event.data.release()), event.length);
if (stream->used() >= tunnel::PAUSE_SIZE)
{
LogDebug(
@ -39,8 +38,7 @@ namespace llarp::quic
auto client = s.data<uvw::TCPHandle>();
if (s.used() < tunnel::PAUSE_SIZE)
{
LogDebug(
"quic tunnel is no longer congested; resuming tcp connection reading");
LogDebug("quic tunnel is no longer congested; resuming tcp connection reading");
client->read();
return true;
}
@ -102,9 +100,7 @@ namespace llarp::quic
// This fires sometime after we call `close()` to signal that the close is done.
if (auto stream = c.data<Stream>())
{
LogInfo(
"Local TCP connection closed, closing associated quic stream ",
stream->id());
LogInfo("Local TCP connection closed, closing associated quic stream ", stream->id());
stream->close();
stream->data(nullptr);
}
@ -259,16 +255,15 @@ namespace llarp::quic
return false;
}
auto lokinet_addr =
var::visit([](auto&& remote) { return remote.ToString(); }, *remote);
auto lokinet_addr = var::visit([](auto&& remote) { return remote.ToString(); }, *remote);
auto tunnel_to = allow_connection(lokinet_addr, port);
if (not tunnel_to)
return false;
LogInfo("quic stream from ", lokinet_addr, " to ", port, " tunnelling to ", *tunnel_to);
auto tcp = get_loop()->resource<uvw::TCPHandle>();
[[maybe_unused]] auto error_handler = tcp->once<uvw::ErrorEvent>(
[&stream, to = *tunnel_to](const uvw::ErrorEvent&, uvw::TCPHandle&) {
[[maybe_unused]] auto error_handler =
tcp->once<uvw::ErrorEvent>([&stream, to = *tunnel_to](const uvw::ErrorEvent&, uvw::TCPHandle&) {
LogWarn("Failed to connect to ", to, ", shutting down quic stream");
stream.close(tunnel::ERROR_CONNECT);
});
@ -336,8 +331,7 @@ namespace llarp::quic
incoming_handlers_.erase(id);
}
std::optional<SockAddr> TunnelManager::allow_connection(
std::string_view lokinet_addr, uint16_t port)
std::optional<SockAddr> TunnelManager::allow_connection(std::string_view lokinet_addr, uint16_t port)
{
for (auto& [id, handler] : incoming_handlers_)
{
@ -359,12 +353,7 @@ namespace llarp::quic
return std::nullopt;
}
}
LogWarn(
"Incoming quic connection from ",
lokinet_addr,
" to ",
port,
" declined by all handlers");
LogWarn("Incoming quic connection from ", lokinet_addr, " to ", port, " declined by all handlers");
return std::nullopt;
}
@ -378,10 +367,7 @@ namespace llarp::quic
// Finds the first unused key in `map`, starting at `start` and wrapping back to 0 if we hit the
// end. Requires an unsigned int type for the key. Requires nullopt if the map is completely
// full, otherwise returns the free key.
template <
typename K,
typename V,
typename = std::enable_if_t<std::is_integral_v<K> && std::is_unsigned_v<K>>>
template <typename K, typename V, typename = std::enable_if_t<std::is_integral_v<K> && std::is_unsigned_v<K>>>
static std::optional<K> find_unused_key(std::map<K, V>& map, K start)
{
if (map.size() == std::numeric_limits<K>::max())
@ -450,37 +436,35 @@ namespace llarp::quic
// ahead with establishing the quic connection.
auto tcp_tunnel = get_loop()->resource<uvw::TCPHandle>();
const char* failed = nullptr;
auto err_handler =
tcp_tunnel->once<uvw::ErrorEvent>([&failed](auto& evt, auto&) { failed = evt.what(); });
auto err_handler = tcp_tunnel->once<uvw::ErrorEvent>([&failed](auto& evt, auto&) { failed = evt.what(); });
tcp_tunnel->bind(*bind_addr.operator const sockaddr*());
tcp_tunnel->on<uvw::ListenEvent>(
[this](const uvw::ListenEvent&, uvw::TCPHandle& tcp_tunnel) {
auto client = tcp_tunnel.loop().resource<uvw::TCPHandle>();
tcp_tunnel.accept(*client);
// Freeze the connection (after accepting) because we may need to stall it until a
// stream becomes available; flush_pending_incoming will unfreeze it.
client->stop();
auto pport = tcp_tunnel.data<uint16_t>();
if (pport)
tcp_tunnel->on<uvw::ListenEvent>([this](const uvw::ListenEvent&, uvw::TCPHandle& tcp_tunnel) {
auto client = tcp_tunnel.loop().resource<uvw::TCPHandle>();
tcp_tunnel.accept(*client);
// Freeze the connection (after accepting) because we may need to stall it until a
// stream becomes available; flush_pending_incoming will unfreeze it.
client->stop();
auto pport = tcp_tunnel.data<uint16_t>();
if (pport)
{
if (auto it = client_tunnels_.find(*pport); it != client_tunnels_.end())
{
if (auto it = client_tunnels_.find(*pport); it != client_tunnels_.end())
{
it->second.pending_incoming.emplace(std::move(client));
flush_pending_incoming(it->second);
return;
}
tcp_tunnel.data(nullptr);
it->second.pending_incoming.emplace(std::move(client));
flush_pending_incoming(it->second);
return;
}
client->close();
});
tcp_tunnel.data(nullptr);
}
client->close();
});
tcp_tunnel->listen();
tcp_tunnel->erase(err_handler);
if (failed)
{
tcp_tunnel->close();
throw std::runtime_error{fmt::format(
"Failed to bind/listen local TCP tunnel socket on {}: {}", bind_addr, failed)};
throw std::runtime_error{
fmt::format("Failed to bind/listen local TCP tunnel socket on {}: {}", bind_addr, failed)};
}
auto bound = tcp_tunnel->sock();
@ -490,8 +474,7 @@ namespace llarp::quic
if (auto p = find_unused_key(client_tunnels_, next_pseudo_port_))
pport = *p;
else
throw std::runtime_error{
"Unable to open an outgoing quic connection: too many existing connections"};
throw std::runtime_error{"Unable to open an outgoing quic connection: too many existing connections"};
(next_pseudo_port_ = pport)++;
LogInfo("Bound TCP tunnel ", saddr, " for quic client :", pport);
@ -520,12 +503,9 @@ namespace llarp::quic
// name, then we have to build a path to that address.
service_endpoint_.LookupNameAsync(
remote_addr,
[this,
after_path = std::move(after_path),
pport = pport,
remote_addr = std::move(remote_addr)](auto maybe_remote) {
if (not continue_connecting(
pport, (bool)maybe_remote, "endpoint ONS lookup", remote_addr))
[this, after_path = std::move(after_path), pport = pport, remote_addr = std::move(remote_addr)](
auto maybe_remote) {
if (not continue_connecting(pport, (bool)maybe_remote, "endpoint ONS lookup", remote_addr))
return;
service_endpoint_.MarkAddressOutbound(*maybe_remote);
service_endpoint_.EnsurePathTo(*maybe_remote, after_path, open_timeout);
@ -580,8 +560,7 @@ namespace llarp::quic
}
}
void TunnelManager::make_client(
const SockAddr& remote, std::pair<const uint16_t, ClientTunnel>& row)
void TunnelManager::make_client(const SockAddr& remote, std::pair<const uint16_t, ClientTunnel>& row)
{
assert(remote.getPort() > 0);
auto& [pport, tunnel] = row;
@ -615,12 +594,10 @@ namespace llarp::quic
{
auto str = conn.open_stream(
[tcp_client](auto&&... args) {
initial_client_data_handler(
*tcp_client, std::forward<decltype(args)>(args)...);
initial_client_data_handler(*tcp_client, std::forward<decltype(args)>(args)...);
},
[tcp_client](auto&&... args) {
initial_client_close_handler(
*tcp_client, std::forward<decltype(args)>(args)...);
initial_client_close_handler(*tcp_client, std::forward<decltype(args)>(args)...);
});
available--;
}
@ -685,8 +662,7 @@ namespace llarp::quic
}
else
{
LogWarn(
"Incoming quic to a quic::Client without an active quic::Connection; dropping");
LogWarn("Incoming quic to a quic::Client without an active quic::Connection; dropping");
return;
}
}

@ -193,10 +193,7 @@ namespace llarp::link
// bool pport_wrapped_ = false;
bool continue_connecting(
uint16_t pseudo_port,
bool step_success,
std::string_view step_name,
std::string_view addr);
uint16_t pseudo_port, bool step_success, std::string_view step_name, std::string_view addr);
void make_client(const SockAddr& remote, std::pair<const uint16_t, ClientTunnel>& row);

@ -8,14 +8,11 @@ namespace llarp::linux
{}
dbus_call_exception::dbus_call_exception(std::string meth, int err)
: std::runtime_error{
"failed to call dbus function '" + meth + "': " + std::string{strerror(-err)}}
: std::runtime_error{"failed to call dbus function '" + meth + "': " + std::string{strerror(-err)}}
{}
DBUS::DBUS(std::string _interface, std::string _instance, std::string _call)
: m_interface{std::move(_interface)},
m_instance{std::move(_instance)},
m_call{std::move(_call)}
: m_interface{std::move(_interface)}, m_instance{std::move(_instance)}, m_call{std::move(_call)}
{
sd_bus* bus{nullptr};
if (auto err = sd_bus_open_system(&bus); err < 0)

@ -39,8 +39,7 @@ namespace llarp::sys
{
if (m_Context and m_Context->router and not m_disable)
{
auto status =
fmt::format("WATCHDOG=1\nSTATUS={}", m_Context->router->status_line());
auto status = fmt::format("WATCHDOG=1\nSTATUS={}", m_Context->router->status_line());
::sd_notify(0, status.c_str());
}
}

@ -159,10 +159,7 @@ namespace
// set flow remote address
std::string addrstr = var::visit([](auto&& from) { return from.ToString(); }, from);
std::copy_n(
addrstr.data(),
std::min(addrstr.size(), sizeof(flow_addr.remote_host)),
flow_addr.remote_host);
std::copy_n(addrstr.data(), std::min(addrstr.size(), sizeof(flow_addr.remote_host)), flow_addr.remote_host);
// set socket id
flow_addr.socket_id = m_SocketID;
// get source port
@ -233,8 +230,7 @@ struct lokinet_context
});
}
std::weak_ptr<llarp::service::Endpoint> weak{ep};
auto udp = std::make_shared<UDPHandler>(
next_socket_id(), exposePort, filter, recv, timeout, user, weak);
auto udp = std::make_shared<UDPHandler>(next_socket_id(), exposePort, filter, recv, timeout, user, weak);
auto id = udp->m_SocketID;
std::promise<bool> result;
@ -273,11 +269,10 @@ struct lokinet_context
{
udp->KillAllFlows();
// remove packet handler
impl->router->loop()->call(
[ep = udp->m_Endpoint.lock(), localport = llarp::ToHost(udp->m_LocalPort)]() {
if (auto pkt = ep->EgresPacketRouter())
pkt->RemoveUDPHandler(localport);
});
impl->router->loop()->call([ep = udp->m_Endpoint.lock(), localport = llarp::ToHost(udp->m_LocalPort)]() {
if (auto pkt = ep->EgresPacketRouter())
pkt->RemoveUDPHandler(localport);
});
}
}
@ -317,10 +312,7 @@ namespace
void stream_okay(lokinet_stream_result* result, std::string host, int port, int stream_id)
{
stream_error(result, 0);
std::copy_n(
host.c_str(),
std::min(host.size(), sizeof(result->local_address) - 1),
result->local_address);
std::copy_n(host.c_str(), std::min(host.size(), sizeof(result->local_address) - 1), result->local_address);
result->local_port = port;
result->stream_id = stream_id;
}
@ -451,8 +443,7 @@ extern "C"
return strdup(addrStr.c_str());
}
int EXPORT
lokinet_add_bootstrap_rc(const char* data, size_t datalen, struct lokinet_context* ctx)
int EXPORT lokinet_add_bootstrap_rc(const char* data, size_t datalen, struct lokinet_context* ctx)
{
if (data == nullptr or datalen == 0)
return -3;
@ -584,10 +575,7 @@ extern "C"
}
void EXPORT lokinet_outbound_stream(
struct lokinet_stream_result* result,
const char* remote,
const char* local,
struct lokinet_context* ctx)
struct lokinet_stream_result* result, const char* remote, const char* local, struct lokinet_context* ctx)
{
if (ctx == nullptr)
{
@ -633,47 +621,41 @@ extern "C"
stream_error(result, EINVAL);
return;
}
auto call = [&promise,
ctx,
result,
router = ctx->impl->router,
remotehost,
remoteport,
endpoint,
localAddr]() {
auto ep = ctx->endpoint();
if (ep == nullptr)
{
stream_error(result, ENOTSUP);
promise.set_value();
return;
}
auto* quic = ep->GetQUICTunnel();
if (quic == nullptr)
{
stream_error(result, ENOTSUP);
auto call =
[&promise, ctx, result, router = ctx->impl->router, remotehost, remoteport, endpoint, localAddr]() {
auto ep = ctx->endpoint();
if (ep == nullptr)
{
stream_error(result, ENOTSUP);
promise.set_value();
return;
}
auto* quic = ep->GetQUICTunnel();
if (quic == nullptr)
{
stream_error(result, ENOTSUP);
promise.set_value();
return;
}
try
{
auto [addr, id] = quic->open(
remotehost, remoteport, [](auto) {}, localAddr);
auto [host, port] = split_host_port(addr.ToString());
ctx->outbound_stream(id);
stream_okay(result, host, port, id);
}
catch (std::exception& ex)
{
std::cout << ex.what() << std::endl;
stream_error(result, ECANCELED);
}
catch (int err)
{
stream_error(result, err);
}
promise.set_value();
return;
}
try
{
auto [addr, id] = quic->open(
remotehost, remoteport, [](auto) {}, localAddr);
auto [host, port] = split_host_port(addr.ToString());
ctx->outbound_stream(id);
stream_okay(result, host, port, id);
}
catch (std::exception& ex)
{
std::cout << ex.what() << std::endl;
stream_error(result, ECANCELED);
}
catch (int err)
{
stream_error(result, err);
}
promise.set_value();
};
};
ctx->impl->CallSafe([call]() {
// we dont want the mainloop to die in case setting the value on the promise fails
@ -689,8 +671,7 @@ extern "C"
auto future = promise.get_future();
try
{
if (auto status = future.wait_for(std::chrono::seconds{10});
status == std::future_status::ready)
if (auto status = future.wait_for(std::chrono::seconds{10}); status == std::future_status::ready)
{
future.get();
}
@ -711,8 +692,8 @@ extern "C"
return lokinet_inbound_stream_filter(&accept_port, (void*)new std::uintptr_t{port}, ctx);
}
int EXPORT lokinet_inbound_stream_filter(
lokinet_stream_filter acceptFilter, void* user, struct lokinet_context* ctx)
int EXPORT
lokinet_inbound_stream_filter(lokinet_stream_filter acceptFilter, void* user, struct lokinet_context* ctx)
{
if (acceptFilter == nullptr)
{
@ -731,9 +712,8 @@ extern "C"
ctx->impl->CallSafe([ctx, acceptFilter, user, &promise]() {
auto ep = ctx->endpoint();
auto* quic = ep->GetQUICTunnel();
auto id = quic->listen(
[acceptFilter, user](
auto remoteAddr, auto port) -> std::optional<llarp::SockAddr> {
auto id =
quic->listen([acceptFilter, user](auto remoteAddr, auto port) -> std::optional<llarp::SockAddr> {
std::string remote{remoteAddr};
if (auto result = acceptFilter(remote.c_str(), port, user))
{
@ -806,11 +786,8 @@ extern "C"
{}
}
int EXPORT lokinet_srv_lookup(
char* host,
char* service,
struct lokinet_srv_lookup_result* result,
struct lokinet_context* ctx)
int EXPORT
lokinet_srv_lookup(char* host, char* service, struct lokinet_srv_lookup_result* result, struct lokinet_context* ctx)
{
if (result == nullptr or ctx == nullptr or host == nullptr or service == nullptr)
return -1;
@ -821,8 +798,8 @@ extern "C"
return result->internal->LookupSRV(host, service, ctx);
}
void EXPORT lokinet_for_each_srv_record(
struct lokinet_srv_lookup_result* result, lokinet_srv_record_iterator iter, void* user)
void EXPORT
lokinet_for_each_srv_record(struct lokinet_srv_lookup_result* result, lokinet_srv_record_iterator iter, void* user)
{
if (result and result->internal)
{
@ -851,15 +828,14 @@ extern "C"
struct lokinet_udp_bind_result* result,
struct lokinet_context* ctx)
{
if (filter == nullptr or recv == nullptr or timeout == nullptr or result == nullptr
or ctx == nullptr)
if (filter == nullptr or recv == nullptr or timeout == nullptr or result == nullptr or ctx == nullptr)
return EINVAL;
auto lock = ctx->acquire();
if (auto ep = ctx->endpoint())
{
if (auto maybe = ctx->make_udp_handler(
ep, llarp::net::port_t::from_host(exposedPort), filter, recv, timeout, user))
if (auto maybe =
ctx->make_udp_handler(ep, llarp::net::port_t::from_host(exposedPort), filter, recv, timeout, user))
{
result->socket_id = *maybe;
return 0;
@ -877,13 +853,9 @@ extern "C"
}
int EXPORT lokinet_udp_flow_send(
const struct lokinet_udp_flowinfo* remote,
const void* ptr,
size_t len,
struct lokinet_context* ctx)
const struct lokinet_udp_flowinfo* remote, const void* ptr, size_t len, struct lokinet_context* ctx)
{
if (remote == nullptr or remote->remote_port == 0 or ptr == nullptr or len == 0
or ctx == nullptr)
if (remote == nullptr or remote->remote_port == 0 or ptr == nullptr or len == 0 or ctx == nullptr)
return EINVAL;
std::shared_ptr<llarp::EndpointBase> ep;
llarp::nuint16_t srcport{0};
@ -954,8 +926,7 @@ extern "C"
{
// check for pre existing flow
auto lock = ctx->acquire();
if (auto itr = ctx->udp_sockets.find(remote->socket_id);
itr != ctx->udp_sockets.end())
if (auto itr = ctx->udp_sockets.find(remote->socket_id); itr != ctx->udp_sockets.end())
{
auto& udp = itr->second;
if (udp->m_Flows.count(*maybe))
@ -973,9 +944,7 @@ extern "C"
{
ep->MarkAddressOutbound(*addr);
auto res = ep->EnsurePathTo(
*addr,
[&gotten](auto result) { gotten.set_value(result.has_value()); },
5s);
*addr, [&gotten](auto result) { gotten.set_value(result.has_value()); }, 5s);
if (not res)
{
gotten.set_value(false);
@ -989,8 +958,7 @@ extern "C"
create_flow(user, &flow_data, &flow_timeoutseconds);
{
auto lock = ctx->acquire();
if (auto itr = ctx->udp_sockets.find(remote->socket_id);
itr != ctx->udp_sockets.end())
if (auto itr = ctx->udp_sockets.find(remote->socket_id); itr != ctx->udp_sockets.end())
{
itr->second->AddFlow(*maybe, *remote, flow_data, flow_timeoutseconds);
return 0;
@ -1004,8 +972,7 @@ extern "C"
return EINVAL;
}
void EXPORT
lokinet_set_syncing_logger(lokinet_logger_func func, lokinet_logger_sync sync, void* user)
void EXPORT lokinet_set_syncing_logger(lokinet_logger_func func, lokinet_logger_sync sync, void* user)
{
llarp::log::clear_sinks();
llarp::log::add_sink(std::make_shared<llarp::logging::CallbackSink_mt>(func, sync, user));

@ -10,8 +10,7 @@ namespace llarp
inline auto INVALID_ORDER = "INVALID ORDER"sv;
inline auto INSUFFICIENT_NODES = "INSUFFICIENT NODES"sv;
inline static std::string serialize(
const dht::Key_t& location, bool is_relayed, uint64_t order)
inline static std::string serialize(const dht::Key_t& location, bool is_relayed, uint64_t order)
{
oxenc::bt_dict_producer btdp;
@ -75,8 +74,7 @@ namespace llarp
inline auto INSUFFICIENT = "INSUFFICIENT NODES"sv;
inline auto INVALID_ORDER = "INVALID ORDER"sv;
inline static std::string serialize(
std::string introset, uint64_t relay_order, uint64_t is_relayed)
inline static std::string serialize(std::string introset, uint64_t relay_order, uint64_t is_relayed)
{
oxenc::bt_dict_producer btdp;

@ -25,10 +25,8 @@ namespace llarp
btdp.append("E", flag);
btdp.append("T", tx_id);
if (not crypto::sign(
reinterpret_cast<uint8_t*>(sig.data()), sk, to_usv(btdp.view())))
throw std::runtime_error{
"Error: ObtainExitMessage failed to sign and serialize contents!"};
if (not crypto::sign(reinterpret_cast<uint8_t*>(sig.data()), sk, to_usv(btdp.view())))
throw std::runtime_error{"Error: ObtainExitMessage failed to sign and serialize contents!"};
}
btlp.append(sig.data());
@ -74,10 +72,8 @@ namespace llarp
btdp.append("P", path_id);
btdp.append("T", tx_id);
if (not crypto::sign(
reinterpret_cast<uint8_t*>(sig.data()), sk, to_usv(btdp.view())))
throw std::runtime_error{
"Error: UpdateExitMessage failed to sign and serialize contents!"};
if (not crypto::sign(reinterpret_cast<uint8_t*>(sig.data()), sk, to_usv(btdp.view())))
throw std::runtime_error{"Error: UpdateExitMessage failed to sign and serialize contents!"};
}
btlp.append(sig.data());
@ -124,10 +120,8 @@ namespace llarp
btdp.append("T", tx_id);
btdp.append("Y", nonce);
if (not crypto::sign(
reinterpret_cast<uint8_t*>(sig.data()), sk, to_usv(btdp.view())))
throw std::runtime_error{
"Error: CloseExitMessage failed to sign and serialize contents!"};
if (not crypto::sign(reinterpret_cast<uint8_t*>(sig.data()), sk, to_usv(btdp.view())))
throw std::runtime_error{"Error: CloseExitMessage failed to sign and serialize contents!"};
}
btlp.append(sig.data());
@ -148,8 +142,7 @@ namespace llarp
btdp.append("Y", nonce);
if (crypto::sign(reinterpret_cast<uint8_t*>(sig.data()), sk, to_usv(btdp.view())))
throw std::runtime_error{
"Error: CloseExitMessage response failed to sign and serialize contents!"};
throw std::runtime_error{"Error: CloseExitMessage response failed to sign and serialize contents!"};
}
btlp.append(sig.data());

@ -96,8 +96,7 @@ namespace llarp
namespace FetchRIDMessage
{
inline constexpr auto INVALID_REQUEST =
"Invalid relay ID requested to relay response from."sv;
inline constexpr auto INVALID_REQUEST = "Invalid relay ID requested to relay response from."sv;
inline static std::string serialize(const RouterID& source)
{

@ -49,8 +49,7 @@ namespace llarp
// methods we do not want to inherit onwards from AbstractSerializable
void bt_encode(oxenc::bt_dict_producer&) const final
{
throw std::runtime_error{
"Error: Link messages should not encode directly to a bt list producer!"};
throw std::runtime_error{"Error: Link messages should not encode directly to a bt list producer!"};
}
};
} // namespace llarp

@ -28,8 +28,7 @@ namespace llarp
// generate nonceXOR value self->hop->pathKey
ShortHash hash;
crypto::shorthash(hash, hop.shared.data(), hop.shared.size());
hop.nonceXOR =
hash.data(); // nonceXOR is 24 bytes, ShortHash is 32; this will truncate
hop.nonceXOR = hash.data(); // nonceXOR is 24 bytes, ShortHash is 32; this will truncate
hop.upstream = nextHop;
}
@ -67,10 +66,7 @@ namespace llarp
// encrypt hop_info (mutates in-place)
if (!crypto::xchacha20(
reinterpret_cast<unsigned char*>(hop_info.data()),
hop_info.size(),
shared,
outer_nonce))
reinterpret_cast<unsigned char*>(hop_info.data()), hop_info.size(), shared, outer_nonce))
{
log::warning(path_cat, "Hop info encryption failed!");
throw std::runtime_error{"Hop info encryption failed"};

@ -116,8 +116,7 @@ namespace llarp
SockAddr addr(m_ipAddress);
const auto* addr6 = static_cast<const sockaddr_in6*>(addr);
const uint8_t* raw = addr6->sin6_addr.s6_addr;
return IPRange::V4MappedRange().Contains(
ipaddr_ipv4_bits(raw[12], raw[13], raw[14], raw[15]));
return IPRange::V4MappedRange().Contains(ipaddr_ipv4_bits(raw[12], raw[13], raw[14], raw[15]));
}
std::string IpAddress::ToString() const

@ -27,8 +27,8 @@ namespace llarp::net
void ipv6_header::FlowLabel(llarp::nuint32_t label)
{
// the ipv6 flow label is the last 20 bits in the first 32 bits of the header
preamble.flowlabel = (htonl(ipv6_flowlabel_mask) & label.n)
| (preamble.flowlabel & htonl(~ipv6_flowlabel_mask));
preamble.flowlabel =
(htonl(ipv6_flowlabel_mask) & label.n) | (preamble.flowlabel & htonl(~ipv6_flowlabel_mask));
};
std::string IPProtocolName(IPProtocol proto)
@ -38,8 +38,7 @@ namespace llarp::net
return ent->p_name;
}
throw std::invalid_argument{
"cannot determine protocol name for ip proto '"
+ std::to_string(static_cast<int>(proto)) + "'"};
"cannot determine protocol name for ip proto '" + std::to_string(static_cast<int>(proto)) + "'"};
}
IPProtocol ParseIPProtocol(std::string data)
@ -135,8 +134,7 @@ namespace llarp::net
{
case IPProtocol::TCP:
case IPProtocol::UDP:
return nuint16_t{
*reinterpret_cast<const uint16_t*>(data() + (Header()->ihl * 4) + 2)};
return nuint16_t{*reinterpret_cast<const uint16_t*>(data() + (Header()->ihl * 4) + 2)};
default:
return std::nullopt;
}
@ -213,14 +211,10 @@ namespace llarp::net
#define SUB32CS(x) ((uint32_t)((~x) & 0xFFff) + (uint32_t)((~x) >> 16))
static nuint16_t deltaIPv4Checksum(
nuint16_t old_sum,
nuint32_t old_src_ip,
nuint32_t old_dst_ip,
nuint32_t new_src_ip,
nuint32_t new_dst_ip)
nuint16_t old_sum, nuint32_t old_src_ip, nuint32_t old_dst_ip, nuint32_t new_src_ip, nuint32_t new_dst_ip)
{
uint32_t sum = uint32_t(old_sum.n) + ADD32CS(old_src_ip.n) + ADD32CS(old_dst_ip.n)
+ SUB32CS(new_src_ip.n) + SUB32CS(new_dst_ip.n);
uint32_t sum = uint32_t(old_sum.n) + ADD32CS(old_src_ip.n) + ADD32CS(old_dst_ip.n) + SUB32CS(new_src_ip.n)
+ SUB32CS(new_dst_ip.n);
// only need to do it 2 times to be sure
// proof: 0xFFff + 0xFFff = 0x1FFfe -> 0xFFff
@ -247,8 +241,8 @@ namespace llarp::net
* that'd suck for 32bit cpus */
#define ADDN128CS(x) (ADD32CS(x[0]) + ADD32CS(x[1]) + ADD32CS(x[2]) + ADD32CS(x[3]))
#define SUBN128CS(x) (SUB32CS(x[0]) + SUB32CS(x[1]) + SUB32CS(x[2]) + SUB32CS(x[3]))
uint32_t sum = uint32_t(old_sum.n) + ADDN128CS(old_src_ip) + ADDN128CS(old_dst_ip)
+ SUBN128CS(new_src_ip) + SUBN128CS(new_dst_ip);
uint32_t sum = uint32_t(old_sum.n) + ADDN128CS(old_src_ip) + ADDN128CS(old_dst_ip) + SUBN128CS(new_src_ip)
+ SUBN128CS(new_dst_ip);
#undef ADDN128CS
#undef SUBN128CS
@ -312,13 +306,7 @@ namespace llarp::net
}
static void deltaChecksumIPv4UDP(
byte_t* pld,
size_t psz,
size_t fragoff,
nuint32_t oSrcIP,
nuint32_t oDstIP,
nuint32_t nSrcIP,
nuint32_t nDstIP)
byte_t* pld, size_t psz, size_t fragoff, nuint32_t oSrcIP, nuint32_t oDstIP, nuint32_t nSrcIP, nuint32_t nDstIP)
{
if (fragoff > 6 || psz < 6 + 2)
return;
@ -415,8 +403,7 @@ namespace llarp::net
hdr->daddr = nDstIP.n;
}
void IPPacket::UpdateIPv6Address(
huint128_t src, huint128_t dst, std::optional<nuint32_t> flowlabel)
void IPPacket::UpdateIPv6Address(huint128_t src, huint128_t dst, std::optional<nuint32_t> flowlabel)
{
const size_t ihs = 4 + 4 + 16 + 16;
const auto sz = size();
@ -593,8 +580,7 @@ namespace llarp::net
return std::nullopt;
const uint8_t* ptr = data() + ((hdr->ihl * 4) + l4_HeaderSize);
return std::make_pair(
reinterpret_cast<const char*>(ptr), std::distance(ptr, data() + size()));
return std::make_pair(reinterpret_cast<const char*>(ptr), std::distance(ptr, data() + size()));
}
namespace
@ -606,8 +592,7 @@ namespace llarp::net
net::port_t dstport,
std::vector<byte_t> udp_data)
{
constexpr auto pkt_overhead =
constants::udp_header_bytes + constants::ip_header_min_bytes;
constexpr auto pkt_overhead = constants::udp_header_bytes + constants::ip_header_min_bytes;
net::IPPacket pkt{udp_data.size() + pkt_overhead};
auto* hdr = pkt.Header();
@ -628,8 +613,7 @@ namespace llarp::net
ptr += 2;
std::memcpy(ptr, &dstport.n, 2);
ptr += 2;
oxenc::write_host_as_big(
static_cast<uint16_t>(udp_data.size() + constants::udp_header_bytes), ptr);
oxenc::write_host_as_big(static_cast<uint16_t>(udp_data.size() + constants::udp_header_bytes), ptr);
ptr += 2;
oxenc::write_host_as_big(uint16_t{0}, ptr); // checksum
ptr += 2;

@ -134,11 +134,7 @@ namespace llarp::net
static constexpr size_t MinSize = 20;
[[deprecated("deprecated because of llarp_buffer_t")]] static IPPacket UDP(
nuint32_t srcaddr,
nuint16_t srcport,
nuint32_t dstaddr,
nuint16_t dstport,
const llarp_buffer_t& data)
nuint32_t srcaddr, nuint16_t srcport, nuint32_t dstaddr, nuint16_t dstport, const llarp_buffer_t& data)
{
return make_udp(srcaddr, srcport, dstaddr, dstport, data.copy());
}
@ -326,8 +322,7 @@ namespace llarp::net
void UpdateIPv4Address(nuint32_t src, nuint32_t dst);
void UpdateIPv6Address(
huint128_t src, huint128_t dst, std::optional<nuint32_t> flowlabel = std::nullopt);
void UpdateIPv6Address(huint128_t src, huint128_t dst, std::optional<nuint32_t> flowlabel = std::nullopt);
/// set addresses to zero and recacluate checksums
void ZeroAddresses(std::optional<nuint32_t> flowlabel = std::nullopt);

@ -23,8 +23,7 @@ namespace llarp
const auto* start = buf->cur;
if (not bencode_discard(buf))
return false;
std::string_view data{
reinterpret_cast<const char*>(start), static_cast<size_t>(buf->cur - start)};
std::string_view data{reinterpret_cast<const char*>(start), static_cast<size_t>(buf->cur - start)};
std::string str;
try
{

@ -38,8 +38,7 @@ namespace llarp
explicit IPRange(std::string _range)
{
if (not FromString(_range))
throw std::invalid_argument{
"IP string '{}' cannot be parsed as IP range"_format(_range)};
throw std::invalid_argument{"IP string '{}' cannot be parsed as IP range"_format(_range)};
}
static constexpr IPRange V4MappedRange()
@ -49,15 +48,12 @@ namespace llarp
static constexpr IPRange FromIPv4(byte_t a, byte_t b, byte_t c, byte_t d, byte_t mask)
{
return IPRange{
net::ExpandV4(ipaddr_ipv4_bits(a, b, c, d)), netmask_ipv6_bits(mask + 96)};
return IPRange{net::ExpandV4(ipaddr_ipv4_bits(a, b, c, d)), netmask_ipv6_bits(mask + 96)};
}
static inline IPRange FromIPv4(net::ipv4addr_t addr, net::ipv4addr_t netmask)
{
return IPRange{
net::ExpandV4(llarp::net::ToHost(addr)),
netmask_ipv6_bits(bits::count_bits(netmask) + 96)};
return IPRange{net::ExpandV4(llarp::net::ToHost(addr)), netmask_ipv6_bits(bits::count_bits(netmask) + 96)};
}
/// return true if this iprange is in the IPv4 mapping range for containing ipv4 addresses
@ -118,8 +114,8 @@ namespace llarp
/// get the highest address on this range
constexpr huint128_t HighestAddr() const
{
return (addr & netmask_bits)
+ (huint128_t{1} << (128 - bits::count_bits_128(netmask_bits.h))) - huint128_t{1};
return (addr & netmask_bits) + (huint128_t{1} << (128 - bits::count_bits_128(netmask_bits.h)))
- huint128_t{1};
}
bool operator<(const IPRange& other) const

@ -115,15 +115,13 @@ namespace llarp
// Attempts to guess a good default public network address from the system's public IP
// addresses; the returned Address (if set) will have its port set to the given value.
virtual std::optional<oxen::quic::Address> get_best_public_address(
bool ipv4, uint16_t port) const = 0;
virtual std::optional<oxen::quic::Address> get_best_public_address(bool ipv4, uint16_t port) const = 0;
virtual std::optional<IPRange> FindFreeRange() const = 0;
virtual std::optional<std::string> FindFreeTun() const = 0;
virtual std::optional<SockAddr> GetInterfaceAddr(
std::string_view ifname, int af = AF_INET) const = 0;
virtual std::optional<SockAddr> GetInterfaceAddr(std::string_view ifname, int af = AF_INET) const = 0;
inline std::optional<huint128_t> GetInterfaceIPv6Address(std::string_view ifname) const
{
@ -216,11 +214,9 @@ inline bool operator==(const sockaddr& a, const sockaddr& b)
switch (a.sa_family)
{
case AF_INET:
return reinterpret_cast<const sockaddr_in&>(a)
== reinterpret_cast<const sockaddr_in&>(b);
return reinterpret_cast<const sockaddr_in&>(a) == reinterpret_cast<const sockaddr_in&>(b);
case AF_INET6:
return reinterpret_cast<const sockaddr_in6&>(a)
== reinterpret_cast<const sockaddr_in6&>(b);
return reinterpret_cast<const sockaddr_in6&>(a) == reinterpret_cast<const sockaddr_in6&>(b);
default:
return false;
}

@ -8,8 +8,7 @@ namespace llarp
/// get a netmask with the higest numset bits set
constexpr huint128_t _netmask_ipv6_bits(uint32_t numset)
{
return (128 - numset) ? (huint128_t{1} << numset) | _netmask_ipv6_bits(numset + 1)
: huint128_t{0};
return (128 - numset) ? (huint128_t{1} << numset) | _netmask_ipv6_bits(numset + 1) : huint128_t{0};
}
constexpr huint128_t netmask_ipv6_bits(uint32_t numset)

@ -229,10 +229,8 @@ namespace llarp
inline constexpr bool IsToStringFormattable<net::port_t> = true;
using nuint16_t /* [[deprecated("use llarp::net::port_t instead")]] */ = llarp::net::port_t;
using nuint32_t /* [[deprecated("use llarp::net::ipv4addr_t instead")]] */ =
llarp::net::ipv4addr_t;
using nuint128_t /* [[deprecated("use llarp::net::ipv6addr_t instead")]] */ =
llarp::net::ipv6addr_t;
using nuint32_t /* [[deprecated("use llarp::net::ipv4addr_t instead")]] */ = llarp::net::ipv4addr_t;
using nuint128_t /* [[deprecated("use llarp::net::ipv6addr_t instead")]] */ = llarp::net::ipv6addr_t;
template <typename UInt_t>
/* [[deprecated("use llarp::net::ToNet instead")]] */ inline llarp::nuint_t<UInt_t> ToNet(
@ -248,8 +246,7 @@ namespace llarp
return llarp::net::ToHost(x);
}
/* [[deprecated("use llarp::net::ToHost instead")]] */ inline net::ipv4addr_t xhtonl(
huint32_t x)
/* [[deprecated("use llarp::net::ToHost instead")]] */ inline net::ipv4addr_t xhtonl(huint32_t x)
{
return ToNet(x);
}

@ -46,13 +46,11 @@ namespace llarp::net
}
});
if (ifname.empty())
throw std::runtime_error{
"we have no ipv4 loopback interface for some ungodly reason"};
throw std::runtime_error{"we have no ipv4 loopback interface for some ungodly reason"};
return ifname;
}
std::optional<oxen::quic::Address> get_best_public_address(
bool ipv4, uint16_t port) const override
std::optional<oxen::quic::Address> get_best_public_address(bool ipv4, uint16_t port) const override
{
std::optional<oxen::quic::Address> found;
@ -80,8 +78,7 @@ namespace llarp::net
if (i and i->ifa_addr and i->ifa_addr->sa_family == AF_INET)
{
ipv4addr_t addr{reinterpret_cast<sockaddr_in*>(i->ifa_addr)->sin_addr.s_addr};
ipv4addr_t mask{
reinterpret_cast<sockaddr_in*>(i->ifa_netmask)->sin_addr.s_addr};
ipv4addr_t mask{reinterpret_cast<sockaddr_in*>(i->ifa_netmask)->sin_addr.s_addr};
currentRanges.emplace_back(IPRange::FromIPv4(addr, mask));
}
});

@ -170,8 +170,7 @@ namespace llarp
SockAddr::operator const sockaddr*() const
{
return isIPv4() ? reinterpret_cast<const sockaddr*>(&addr4)
: reinterpret_cast<const sockaddr*>(&addr6);
return isIPv4() ? reinterpret_cast<const sockaddr*>(&addr4) : reinterpret_cast<const sockaddr*>(&addr6);
}
SockAddr::operator const sockaddr_in*() const
@ -250,8 +249,7 @@ namespace llarp
if (splits.size() == 2)
{
if (not allow_port)
throw std::runtime_error{
fmt::format("invalid ip address (port not allowed here): {}", str)};
throw std::runtime_error{fmt::format("invalid ip address (port not allowed here): {}", str)};
uint16_t port;
if (not parse_int(splits[1], port))
throw std::runtime_error{fmt::format("{} is not a valid port", splits[1])};

@ -145,8 +145,7 @@ namespace llarp::net
}
catch (...)
{
log::critical(
net_cat, "Error: TrafficPolicy failed to populate with bt encoded contents");
log::critical(net_cat, "Error: TrafficPolicy failed to populate with bt encoded contents");
}
}
@ -204,17 +203,14 @@ namespace llarp::net
util::StatusObject TrafficPolicy::ExtractStatus() const
{
std::vector<util::StatusObject> rangesStatus;
std::transform(
ranges.begin(), ranges.end(), std::back_inserter(rangesStatus), [](const auto& range) {
return range.ToString();
});
std::transform(ranges.begin(), ranges.end(), std::back_inserter(rangesStatus), [](const auto& range) {
return range.ToString();
});
std::vector<util::StatusObject> protosStatus;
std::transform(
protocols.begin(),
protocols.end(),
std::back_inserter(protosStatus),
[](const auto& proto) { return proto.ExtractStatus(); });
std::transform(protocols.begin(), protocols.end(), std::back_inserter(protosStatus), [](const auto& proto) {
return proto.ExtractStatus();
});
return util::StatusObject{{"ranges", rangesStatus}, {"protocols", protosStatus}};
}

@ -34,8 +34,7 @@ namespace llarp::net
{
ptr = std::make_unique<byte_t[]>(sz);
addr = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(ptr.get());
err = GetAdaptersAddresses(
af, GAA_FLAG_INCLUDE_GATEWAYS | GAA_FLAG_INCLUDE_PREFIX, nullptr, addr, &sz);
err = GetAdaptersAddresses(af, GAA_FLAG_INCLUDE_GATEWAYS | GAA_FLAG_INCLUDE_PREFIX, nullptr, addr, &sz);
} while (err == ERROR_BUFFER_OVERFLOW and ++tries < 4);
if (err != ERROR_SUCCESS)
@ -83,10 +82,7 @@ namespace llarp::net
return;
LogDebug(fmt::format(
"visit adapter looking for '{}': '{}' idx={}",
ip,
adapter->AdapterName,
adapter->IfIndex));
"visit adapter looking for '{}': '{}' idx={}", ip, adapter->AdapterName, adapter->IfIndex));
if (adapter_has_ip(adapter, ip))
{
found = adapter->IfIndex;
@ -96,8 +92,7 @@ namespace llarp::net
return found;
}
std::optional<llarp::SockAddr> GetInterfaceAddr(
std::string_view name, int af) const override
std::optional<llarp::SockAddr> GetInterfaceAddr(std::string_view name, int af) const override
{
std::optional<SockAddr> found;
iter_adapters([name = std::string{name}, af, &found, this](auto* a) {
@ -138,8 +133,7 @@ namespace llarp::net
SockAddr saddr{*addr->Address.lpSockaddr};
currentRanges.emplace_back(
saddr.asIPv6(),
ipaddr_netmask_bits(
addr->OnLinkPrefixLength, addr->Address.lpSockaddr->sa_family));
ipaddr_netmask_bits(addr->OnLinkPrefixLength, addr->Address.lpSockaddr->sa_family));
}
});
@ -171,8 +165,7 @@ namespace llarp::net
SockAddr saddr{*addr->Address.lpSockaddr};
cur.addrs.emplace_back(
saddr.asIPv6(),
ipaddr_netmask_bits(
addr->OnLinkPrefixLength, addr->Address.lpSockaddr->sa_family));
ipaddr_netmask_bits(addr->OnLinkPrefixLength, addr->Address.lpSockaddr->sa_family));
}
if (auto* addr = a->FirstGatewayAddress)
{

@ -10,13 +10,10 @@ namespace llarp::path
return make_onion_payload(
nonce,
path_id,
ustring_view{
reinterpret_cast<const unsigned char*>(inner_payload.data()),
inner_payload.size()});
ustring_view{reinterpret_cast<const unsigned char*>(inner_payload.data()), inner_payload.size()});
}
std::string make_onion_payload(
const SymmNonce& nonce, const PathID_t& path_id, const ustring_view& inner_payload)
std::string make_onion_payload(const SymmNonce& nonce, const PathID_t& path_id, const ustring_view& inner_payload)
{
oxenc::bt_dict_producer next_dict;
next_dict.append("NONCE", nonce.ToView());

@ -15,10 +15,7 @@ namespace llarp::path
std::weak_ptr<PathSet> pathset,
PathRole startingRoles,
std::string shortName)
: path_set{std::move(pathset)},
router{*rtr},
_role{startingRoles},
_short_name{std::move(shortName)}
: path_set{std::move(pathset)}, router{*rtr}, _role{startingRoles}, _short_name{std::move(shortName)}
{
hops.resize(h.size());
size_t hsz = h.size();
@ -47,43 +44,31 @@ namespace llarp::path
EnterState(PathStatus::BUILDING, parent->Now());
}
bool Path::obtain_exit(
SecretKey sk, uint64_t flag, std::string tx_id, std::function<void(std::string)> func)
bool Path::obtain_exit(SecretKey sk, uint64_t flag, std::string tx_id, std::function<void(std::string)> func)
{
return send_path_control_message(
"obtain_exit",
ObtainExitMessage::sign_and_serialize(sk, flag, std::move(tx_id)),
std::move(func));
"obtain_exit", ObtainExitMessage::sign_and_serialize(sk, flag, std::move(tx_id)), std::move(func));
}
bool Path::close_exit(SecretKey sk, std::string tx_id, std::function<void(std::string)> func)
{
return send_path_control_message(
"close_exit",
CloseExitMessage::sign_and_serialize(sk, std::move(tx_id)),
std::move(func));
"close_exit", CloseExitMessage::sign_and_serialize(sk, std::move(tx_id)), std::move(func));
}
bool Path::find_intro(
const dht::Key_t& location,
bool is_relayed,
uint64_t order,
std::function<void(std::string)> func)
const dht::Key_t& location, bool is_relayed, uint64_t order, std::function<void(std::string)> func)
{
return send_path_control_message(
"find_intro",
FindIntroMessage::serialize(location, is_relayed, order),
std::move(func));
"find_intro", FindIntroMessage::serialize(location, is_relayed, order), std::move(func));
}
bool Path::find_name(std::string name, std::function<void(std::string)> func)
{
return send_path_control_message(
"find_name", FindNameMessage::serialize(std::move(name)), std::move(func));
return send_path_control_message("find_name", FindNameMessage::serialize(std::move(name)), std::move(func));
}
bool Path::send_path_control_message(
std::string method, std::string body, std::function<void(std::string)> func)
bool Path::send_path_control_message(std::string method, std::string body, std::function<void(std::string)> func)
{
oxenc::bt_dict_producer btdp;
btdp.append("BODY", body);
@ -98,11 +83,7 @@ namespace llarp::path
for (const auto& hop : hops)
{
nonce = crypto::onion(
reinterpret_cast<unsigned char*>(payload.data()),
payload.size(),
hop.shared,
nonce,
hop.nonceXOR);
reinterpret_cast<unsigned char*>(payload.data()), payload.size(), hop.shared, nonce, hop.nonceXOR);
}
auto outer_payload = make_onion_payload(nonce, TXID(), payload);
@ -134,8 +115,7 @@ namespace llarp::path
}
catch (const std::exception& e)
{
log::warning(
path_cat, "Error parsing path control message response: {}", e.what());
log::warning(path_cat, "Error parsing path control message response: {}", e.what());
response_cb(messages::ERROR_RESPONSE);
return;
}
@ -203,8 +183,7 @@ namespace llarp::path
std::string Path::HopsString() const
{
std::string hops_str;
hops_str.reserve(
hops.size() * 62); // 52 for the pkey, 6 for .snode, 4 for the ' -> ' joiner
hops_str.reserve(hops.size() * 62); // 52 for the pkey, 6 for .snode, 4 for the ' -> ' joiner
for (const auto& hop : hops)
{
if (!hops.empty())
@ -291,10 +270,9 @@ namespace llarp::path
std::vector<util::StatusObject> hopsObj;
std::transform(
hops.begin(),
hops.end(),
std::back_inserter(hopsObj),
[](const auto& hop) -> util::StatusObject { return hop.ExtractStatus(); });
hops.begin(), hops.end(), std::back_inserter(hopsObj), [](const auto& hop) -> util::StatusObject {
return hop.ExtractStatus();
});
obj["hops"] = hopsObj;
switch (_status)

@ -143,14 +143,10 @@ namespace llarp
uint64_t order = 0,
std::function<void(std::string)> func = nullptr);
bool close_exit(
SecretKey sk, std::string tx_id, std::function<void(std::string)> func = nullptr);
bool close_exit(SecretKey sk, std::string tx_id, std::function<void(std::string)> func = nullptr);
bool obtain_exit(
SecretKey sk,
uint64_t flag,
std::string tx_id,
std::function<void(std::string)> func = nullptr);
SecretKey sk, uint64_t flag, std::string tx_id, std::function<void(std::string)> func = nullptr);
/// sends a control request along a path
///
@ -161,9 +157,7 @@ namespace llarp
/// func is called with a bt-encoded response string (if applicable), and
/// a timeout flag (if set, response string will be empty)
bool send_path_control_message(
std::string method,
std::string body,
std::function<void(std::string)> func = nullptr) override;
std::string method, std::string body, std::function<void(std::string)> func = nullptr) override;
bool IsReady() const;
@ -228,8 +222,7 @@ namespace llarp
/// comparision for equal endpoints
struct endpoint_comparator
{
bool operator()(
const std::shared_ptr<Path>& left, const std::shared_ptr<Path>& right) const
bool operator()(const std::shared_ptr<Path>& left, const std::shared_ptr<Path>& right) const
{
return left && right && left->Endpoint() == left->Endpoint();
}

@ -92,8 +92,7 @@ namespace llarp::path
return false;
}
std::shared_ptr<TransitHop> PathContext::GetTransitHop(
const RouterID& rid, const PathID_t& path_id)
std::shared_ptr<TransitHop> PathContext::GetTransitHop(const RouterID& rid, const PathID_t& path_id)
{
if (auto itr = transit_hops.find({rid, path_id}); itr != transit_hops.end())
return itr->second;
@ -109,8 +108,7 @@ namespace llarp::path
return nullptr;
}
bool PathContext::TransitHopPreviousIsRouter(
const PathID_t& path_id, const RouterID& otherRouter)
bool PathContext::TransitHopPreviousIsRouter(const PathID_t& path_id, const RouterID& otherRouter)
{
return transit_hops.count({otherRouter, path_id});
}

@ -90,8 +90,7 @@ namespace llarp
// generate nonceXOR value self->hop->pathKey
ShortHash hash;
crypto::shorthash(hash, hop.shared.data(), hop.shared.size());
hop.nonceXOR =
hash.data(); // nonceXOR is 24 bytes, ShortHash is 32; this will truncate
hop.nonceXOR = hash.data(); // nonceXOR is 24 bytes, ShortHash is 32; this will truncate
hop.upstream = nextHop;
}
@ -128,11 +127,7 @@ namespace llarp
}
// encrypt hop_info (mutates in-place)
if (!crypto::xchacha20(
reinterpret_cast<uint8_t*>(hop_info.data()),
hop_info.size(),
shared,
outer_nonce))
if (!crypto::xchacha20(reinterpret_cast<uint8_t*>(hop_info.data()), hop_info.size(), shared, outer_nonce))
{
log::error(path_cat, "Hop info encryption failed!");
throw std::runtime_error{"Hop info encrypttion failed"};
@ -189,8 +184,7 @@ namespace llarp
TickPaths(router);
if (build_stats.attempts > 50)
{
if (build_stats.SuccessRatio() <= BuildStats::MinGoodRatio
&& now - last_warn_time > 5s)
if (build_stats.SuccessRatio() <= BuildStats::MinGoodRatio && now - last_warn_time > 5s)
{
LogWarn(Name(), " has a low path build success. ", build_stats);
last_warn_time = now;
@ -208,9 +202,7 @@ namespace llarp
_paths.begin(),
_paths.end(),
std::back_inserter(obj["paths"]),
[](const auto& item) -> util::StatusObject {
return item.second->ExtractStatus();
});
[](const auto& item) -> util::StatusObject { return item.second->ExtractStatus(); });
return obj;
}
@ -334,8 +326,7 @@ namespace llarp
}
else
{
auto filter = [&hops, r = router, endpointRC, pathConfig, exclude](
const RemoteRC& rc) -> bool {
auto filter = [&hops, r = router, endpointRC, pathConfig, exclude](const RemoteRC& rc) -> bool {
const auto& rid = rc.router_id();
if (exclude.count(rid))
@ -407,15 +398,9 @@ namespace llarp
std::string path_shortName = "[path " + router->ShortName() + "-";
path_shortName = path_shortName + std::to_string(router->NextPathBuildNumber()) + "]";
auto path = std::make_shared<path::Path>(
router, hops, GetWeak(), roles, std::move(path_shortName));
auto path = std::make_shared<path::Path>(router, hops, GetWeak(), roles, std::move(path_shortName));
log::info(
path_cat,
"{} building path -> {} : {}",
Name(),
path->short_name(),
path->HopsString());
log::info(path_cat, "{} building path -> {} : {}", Name(), path->short_name(), path->HopsString());
oxenc::bt_list_producer frames;
std::vector<std::string> frame_str(path::MAX_LEN);
@ -441,8 +426,7 @@ namespace llarp
i--;
bool lastHop = (i == (n_hops - 1));
const auto& nextHop =
lastHop ? path_hops[i].rc.router_id() : path_hops[i + 1].rc.router_id();
const auto& nextHop = lastHop ? path_hops[i].rc.router_id() : path_hops[i + 1].rc.router_id();
PathBuildMessage::setup_hop_keys(path_hops[i], nextHop);
frame_str[i] = PathBuildMessage::serialize(path_hops[i]);
@ -520,16 +504,12 @@ namespace llarp
}
catch (const std::exception& e)
{
log::warning(
path_cat, "Exception caught parsing path build response: {}", e.what());
log::warning(path_cat, "Exception caught parsing path build response: {}", e.what());
}
};
if (not router->send_control_message(
path->upstream(),
"path_build",
std::move(frames).str(),
std::move(response_cb)))
path->upstream(), "path_build", std::move(frames).str(), std::move(response_cb)))
{
log::warning(path_cat, "Error sending path_build control message");
path->EnterState(path::PathStatus::FAILED, router->now());
@ -555,8 +535,7 @@ namespace llarp
{
static constexpr std::chrono::milliseconds MaxBuildInterval = 30s;
// linear backoff
build_interval_limit =
std::min(PATH_BUILD_RATE + build_interval_limit, MaxBuildInterval);
build_interval_limit = std::min(PATH_BUILD_RATE + build_interval_limit, MaxBuildInterval);
LogWarn(Name(), " build interval is now ", ToString(build_interval_limit));
}

@ -244,8 +244,7 @@ namespace llarp::path
auto itr = _paths.begin();
while (itr != _paths.end())
{
if (itr->second->Status() == PathStatus::ESTABLISHED
&& itr->second->SupportsAnyRoles(roles))
if (itr->second->Status() == PathStatus::ESTABLISHED && itr->second->SupportsAnyRoles(roles))
++count;
++itr;
}
@ -273,12 +272,7 @@ namespace llarp::path
const auto RXID = path->RXID(); // PathID
if (not _paths.emplace(std::make_pair(upstream, RXID), path).second)
{
LogError(
Name(),
" failed to add own path, duplicate info wtf? upstream=",
upstream,
" rxid=",
RXID);
LogError(Name(), " failed to add own path, duplicate info wtf? upstream=", upstream, " rxid=", RXID);
}
}

@ -171,22 +171,17 @@ namespace llarp
virtual void BlacklistSNode(const RouterID) = 0;
std::shared_ptr<Path> GetEstablishedPathClosestTo(
RouterID router,
std::unordered_set<RouterID> excluding = {},
PathRole roles = ePathRoleAny) const;
RouterID router, std::unordered_set<RouterID> excluding = {}, PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> PickEstablishedPath(PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> PickRandomEstablishedPath(PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> GetPathByRouter(
RouterID router, PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> GetPathByRouter(RouterID router, PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> GetNewestPathByRouter(
RouterID router, PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> GetNewestPathByRouter(RouterID router, PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> GetRandomPathByRouter(
RouterID router, PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> GetRandomPathByRouter(RouterID router, PathRole roles = ePathRoleAny) const;
std::shared_ptr<Path> GetPathByID(PathID_t id) const;

@ -7,12 +7,7 @@ namespace llarp::path
{
std::string TransitHopInfo::ToString() const
{
return fmt::format(
"[TransitHopInfo tx={} rx={} upstream={} downstream={}]",
txID,
rxID,
upstream,
downstream);
return fmt::format("[TransitHopInfo tx={} rx={} upstream={} downstream={}]", txID, rxID, upstream, downstream);
}
TransitHop::TransitHop() : AbstractHopHandler{}
@ -29,8 +24,7 @@ namespace llarp::path
{
if (randomize)
nonce.Randomize();
nonce = crypto::onion(
reinterpret_cast<unsigned char*>(data.data()), data.size(), pathKey, nonce, nonceXOR);
nonce = crypto::onion(reinterpret_cast<unsigned char*>(data.data()), data.size(), pathKey, nonce, nonceXOR);
}
std::string TransitHop::onion_and_payload(
@ -43,8 +37,7 @@ namespace llarp::path
return path::make_onion_payload(nref, next_id, payload);
}
bool TransitHop::send_path_control_message(
std::string, std::string, std::function<void(std::string)>)
bool TransitHop::send_path_control_message(std::string, std::string, std::function<void(std::string)>)
{
// TODO: if we want terminal/pivot hops to be able to *initiate* a request rather than
// simply responding/reacting to the client end's requests, this will need
@ -107,8 +100,7 @@ namespace llarp::path
std::string TransitHop::ToString() const
{
return fmt::format(
"[TransitHop {} started={} lifetime={}", info, started.count(), lifetime.count());
return fmt::format("[TransitHop {} started={} lifetime={}", info, started.count(), lifetime.count());
}
void TransitHop::Stop()

@ -63,9 +63,7 @@ namespace llarp
void onion(std::string& data, SymmNonce& nonce, bool randomize = false) const;
std::string onion_and_payload(
std::string& payload,
PathID_t next_id,
std::optional<SymmNonce> nonce = std::nullopt) const;
std::string& payload, PathID_t next_id, std::optional<SymmNonce> nonce = std::nullopt) const;
PathID_t RXID() const override
{
@ -116,9 +114,7 @@ namespace llarp
/// func is called with a bt-encoded response string (if applicable), and
/// a timeout flag (if set, response string will be empty)
bool send_path_control_message(
std::string method,
std::string body,
std::function<void(std::string)> func) override;
std::string method, std::string body, std::function<void(std::string)> func) override;
void QueueDestroySelf(Router* r);

@ -65,8 +65,7 @@ namespace llarp
bool RouterProfile::IsGood(uint64_t chances) const
{
if (connectTimeoutCount > chances)
return connectTimeoutCount < connectGoodCount
&& (pathSuccessCount * chances) > pathFailCount;
return connectTimeoutCount < connectGoodCount && (pathSuccessCount * chances) > pathFailCount;
return (pathSuccessCount * chances) > pathFailCount;
}

@ -152,8 +152,7 @@ namespace llarp
{
if (next_gw and current_gateway)
{
log::info(
logcat, "default gateway changed from {} to {}", *current_gateway, *next_gw);
log::info(logcat, "default gateway changed from {} to {}", *current_gateway, *next_gw);
current_gateway = next_gw;
router.Thaw();
refresh_all_routes();
@ -191,8 +190,7 @@ namespace llarp
{
if (not is_enabled())
{
log::warning(
logcat, "RoutePoker coming up, but route poking is disabled by config");
log::warning(logcat, "RoutePoker coming up, but route poking is disabled by config");
}
else if (not current_gateway)
{
@ -209,8 +207,7 @@ namespace llarp
route.add_blackhole();
// explicit route pokes for first hops
router.for_each_connection(
[this](link::Connection conn) { add_route(conn.conn->remote()); });
router.for_each_connection([this](link::Connection conn) { add_route(conn.conn->remote()); });
add_route(router.link_manager().local());
// add default route
@ -227,8 +224,7 @@ namespace llarp
void RoutePoker::put_down()
{
// unpoke routes for first hops
router.for_each_connection(
[this](link::Connection conn) { delete_route(conn.conn->remote()); });
router.for_each_connection([this](link::Connection conn) { delete_route(conn.conn->remote()); });
if (is_enabled() and is_up)
{
vpn::AbstractRouteManager& route = router.vpn_platform()->RouteManager();

@ -49,8 +49,7 @@ namespace llarp
if (ipv4_port.size() != 6)
throw std::runtime_error{
"Invalid RC address: expected 6-byte IPv4 IP/port, got {}"_format(
ipv4_port.size())};
"Invalid RC address: expected 6-byte IPv4 IP/port, got {}"_format(ipv4_port.size())};
sockaddr_in s4;
s4.sin_family = AF_INET;
@ -67,8 +66,7 @@ namespace llarp
{
if (ipv6_port->size() != 18)
throw std::runtime_error{
"Invalid RC address: expected 18-byte IPv6 IP/port, got {}"_format(
ipv6_port->size())};
"Invalid RC address: expected 18-byte IPv6 IP/port, got {}"_format(ipv6_port->size())};
sockaddr_in6 s6{};
s6.sin6_family = AF_INET6;
@ -94,8 +92,7 @@ namespace llarp
auto pubkey = btdc.require<std::string_view>("p");
if (pubkey.size() != 32)
throw std::runtime_error{
"Invalid RC pubkey: expected 32 bytes, got {}"_format(pubkey.size())};
throw std::runtime_error{"Invalid RC pubkey: expected 32 bytes, got {}"_format(pubkey.size())};
std::memcpy(_router_id.data(), pubkey.data(), 32);
_timestamp = rc_time{std::chrono::seconds{btdc.require<uint64_t>("t")}};
@ -103,8 +100,7 @@ namespace llarp
auto ver = btdc.require<ustring_view>("v");
if (ver.size() != 3)
throw std::runtime_error{
"Invalid RC router version: received {} bytes (!= 3)"_format(ver.size())};
throw std::runtime_error{"Invalid RC router version: received {} bytes (!= 3)"_format(ver.size())};
for (int i = 0; i < 3; i++)
_router_version[i] = ver[i];

@ -137,9 +137,8 @@ namespace llarp
bool operator==(const RouterContact& other) const
{
return _router_id == other._router_id and _addr == other._addr
and _addr6 == other._addr6 and _timestamp == other._timestamp
and _router_version == other._router_version;
return _router_id == other._router_id and _addr == other._addr and _addr6 == other._addr6
and _timestamp == other._timestamp and _router_version == other._router_version;
}
bool operator<(const RouterContact& other) const
@ -226,9 +225,9 @@ namespace llarp
bool operator==(const LocalRC& other) const
{
return _router_id == other._router_id and _addr == other._addr
and _addr6 == other._addr6 and _timestamp == other._timestamp
and _router_version == other._router_version and _signature == other._signature;
return _router_id == other._router_id and _addr == other._addr and _addr6 == other._addr6
and _timestamp == other._timestamp and _router_version == other._router_version
and _signature == other._signature;
}
/// Mutators for the private member attributes. Calling on the mutators

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save