From 273270916ea33b096753c5ad316f46a8268761bd Mon Sep 17 00:00:00 2001 From: Stephen Shelton Date: Tue, 7 Apr 2020 12:38:56 -0600 Subject: [PATCH] The Great Wall of Blame This commit reflects changes to clang-format rules. Unfortunately, these rule changes create a massive change to the codebase, which causes an apparent rewrite of git history. Git blame's --ignore-rev flag can be used to ignore this commit when attempting to `git blame` some code. --- daemon/lokinetctl.cpp | 74 +- daemon/main.cpp | 166 +- include/llarp.h | 102 +- include/llarp.hpp | 28 +- include/llarp/string.h | 2 +- include/tuntap.h | 69 +- jni/lokinet_config.cpp | 15 +- jni/lokinet_daemon.cpp | 59 +- jni/lokinet_jni_common.hpp | 43 +- jni/lokinet_jni_vpnio.hpp | 50 +- jni/lokinet_vpn.cpp | 57 +- jni/network_loki_lokinet_LokinetConfig.h | 6 +- jni/network_loki_lokinet_LokinetDaemon.h | 14 +- jni/network_loki_lokinet_LokinetVPN.h | 14 +- jni/network_loki_lokinet_Lokinet_JNI.h | 17 +- libabyss/include/abyss/client.hpp | 21 +- libabyss/include/abyss/http.hpp | 2 +- libabyss/include/abyss/md5.hpp | 13 +- libabyss/include/abyss/server.hpp | 10 +- libabyss/main.cpp | 40 +- libabyss/src/client.cpp | 181 +-- libabyss/src/http.cpp | 10 +- libabyss/src/md5.cpp | 32 +- libabyss/src/server.cpp | 203 ++- llarp/android/ifaddrs.c | 373 +++-- llarp/android/ifaddrs.h | 16 +- llarp/bootstrap.cpp | 4 +- llarp/bootstrap.hpp | 2 +- llarp/config/config.cpp | 247 ++- llarp/config/config.hpp | 43 +- llarp/config/ini.cpp | 58 +- llarp/config/ini.hpp | 11 +- llarp/config/key_manager.cpp | 115 +- llarp/config/key_manager.hpp | 8 +- llarp/consensus/table.hpp | 2 +- llarp/constants/link_layer.hpp | 4 +- llarp/constants/path.hpp | 6 +- llarp/constants/version.h | 3 +- llarp/constants/version.hpp | 10 +- llarp/context.cpp | 236 ++- llarp/crypto/constants.hpp | 22 +- llarp/crypto/crypto.hpp | 76 +- llarp/crypto/crypto_libsodium.cpp | 230 ++- llarp/crypto/crypto_libsodium.hpp | 70 +- llarp/crypto/crypto_noop.hpp | 67 +- llarp/crypto/encrypted.hpp | 24 +- llarp/crypto/encrypted_frame.cpp | 47 +- llarp/crypto/encrypted_frame.hpp | 29 +- llarp/crypto/types.cpp | 36 +- llarp/crypto/types.hpp | 124 +- llarp/dht/bucket.hpp | 102 +- llarp/dht/context.cpp | 291 ++-- llarp/dht/context.hpp | 95 +- llarp/dht/dht.cpp | 21 +- llarp/dht/dht.h | 3 +- llarp/dht/explorenetworkjob.cpp | 15 +- llarp/dht/explorenetworkjob.hpp | 10 +- llarp/dht/key.hpp | 14 +- llarp/dht/localrouterlookup.cpp | 27 +- llarp/dht/localrouterlookup.hpp | 4 +- llarp/dht/localserviceaddresslookup.cpp | 26 +- llarp/dht/localserviceaddresslookup.hpp | 11 +- llarp/dht/localtaglookup.cpp | 16 +- llarp/dht/localtaglookup.hpp | 4 +- llarp/dht/message.cpp | 63 +- llarp/dht/message.hpp | 10 +- llarp/dht/messages/consensus.hpp | 2 +- llarp/dht/messages/findintro.cpp | 54 +- llarp/dht/messages/findintro.hpp | 15 +- llarp/dht/messages/findrouter.cpp | 90 +- llarp/dht/messages/findrouter.hpp | 10 +- llarp/dht/messages/gotintro.cpp | 71 +- llarp/dht/messages/gotintro.hpp | 20 +- llarp/dht/messages/gotrouter.cpp | 72 +- llarp/dht/messages/gotrouter.hpp | 40 +- llarp/dht/messages/pubintro.cpp | 120 +- llarp/dht/messages/pubintro.hpp | 23 +- llarp/dht/publishservicejob.cpp | 42 +- llarp/dht/publishservicejob.hpp | 25 +- llarp/dht/recursiverouterlookup.cpp | 35 +- llarp/dht/recursiverouterlookup.hpp | 13 +- llarp/dht/serviceaddresslookup.cpp | 33 +- llarp/dht/serviceaddresslookup.hpp | 16 +- llarp/dht/taglookup.cpp | 16 +- llarp/dht/taglookup.hpp | 13 +- llarp/dht/tx.hpp | 30 +- llarp/dht/txholder.hpp | 129 +- llarp/dht/txowner.hpp | 4 +- llarp/dns/dns.hpp | 26 +- llarp/dns/message.cpp | 125 +- llarp/dns/message.hpp | 18 +- llarp/dns/name.cpp | 58 +- llarp/dns/question.cpp | 12 +- llarp/dns/question.hpp | 5 +- llarp/dns/rr.cpp | 24 +- llarp/dns/rr.hpp | 8 +- llarp/dns/serialize.cpp | 16 +- llarp/dns/serialize.hpp | 4 +- llarp/dns/server.cpp | 100 +- llarp/dns/server.hpp | 31 +- llarp/ev/ev.cpp | 83 +- llarp/ev/ev.h | 109 +- llarp/ev/ev.hpp | 203 ++- llarp/ev/ev_libuv.cpp | 341 ++-- llarp/ev/ev_libuv.hpp | 25 +- llarp/ev/ev_win32.cpp | 75 +- llarp/ev/ev_win32.hpp | 9 +- llarp/ev/pipe.cpp | 9 +- llarp/ev/vpnio.cpp | 8 +- llarp/ev/vpnio.hpp | 4 +- llarp/exit/context.cpp | 35 +- llarp/exit/context.hpp | 27 +- llarp/exit/endpoint.cpp | 75 +- llarp/exit/endpoint.hpp | 19 +- llarp/exit/exit_messages.cpp | 211 ++- llarp/exit/exit_messages.hpp | 16 +- llarp/exit/policy.cpp | 22 +- llarp/exit/policy.hpp | 6 +- llarp/exit/session.cpp | 128 +- llarp/exit/session.hpp | 73 +- llarp/handlers/exit.cpp | 378 ++--- llarp/handlers/exit.hpp | 53 +- llarp/handlers/null.hpp | 12 +- llarp/handlers/tun.cpp | 594 ++++--- llarp/handlers/tun.hpp | 144 +- llarp/hook/ihook.hpp | 4 +- llarp/hook/shell.cpp | 68 +- llarp/iwp/iwp.cpp | 40 +- llarp/iwp/iwp.hpp | 30 +- llarp/iwp/linklayer.cpp | 52 +- llarp/iwp/linklayer.hpp | 35 +- llarp/iwp/message_buffer.cpp | 69 +- llarp/iwp/message_buffer.hpp | 25 +- llarp/iwp/session.cpp | 385 +++-- llarp/iwp/session.hpp | 32 +- llarp/link/factory.cpp | 10 +- llarp/link/factory.hpp | 14 +- llarp/link/i_link_manager.hpp | 29 +- llarp/link/link_manager.cpp | 170 +- llarp/link/link_manager.hpp | 42 +- llarp/link/server.cpp | 228 ++- llarp/link/server.hpp | 96 +- llarp/link/session.hpp | 14 +- llarp/linux/netns.cpp | 120 +- llarp/messages/dht_immediate.cpp | 41 +- llarp/messages/dht_immediate.hpp | 4 +- llarp/messages/discard.hpp | 30 +- llarp/messages/link_intro.cpp | 72 +- llarp/messages/link_intro.hpp | 4 +- llarp/messages/link_message.hpp | 4 +- llarp/messages/link_message_parser.cpp | 29 +- llarp/messages/link_message_parser.hpp | 2 +- llarp/messages/relay.cpp | 60 +- llarp/messages/relay.hpp | 4 +- llarp/messages/relay_commit.cpp | 248 +-- llarp/messages/relay_commit.hpp | 28 +- llarp/messages/relay_status.cpp | 114 +- llarp/messages/relay_status.hpp | 57 +- llarp/net/address_info.cpp | 84 +- llarp/net/address_info.hpp | 2 +- llarp/net/exit_info.cpp | 31 +- llarp/net/exit_info.hpp | 16 +- llarp/net/ip.cpp | 196 +-- llarp/net/ip.hpp | 17 +- llarp/net/ip_range_map.hpp | 40 +- llarp/net/net.cpp | 258 +-- llarp/net/net.hpp | 24 +- llarp/net/net_addr.cpp | 168 +- llarp/net/net_addr.hpp | 18 +- llarp/net/net_int.cpp | 14 +- llarp/net/net_int.hpp | 36 +- llarp/net/uint128.hpp | 41 +- llarp/nodedb.cpp | 247 ++- llarp/nodedb.hpp | 100 +- llarp/path/ihophandler.cpp | 14 +- llarp/path/ihophandler.hpp | 23 +- llarp/path/path.cpp | 346 ++-- llarp/path/path.hpp | 128 +- llarp/path/path_context.cpp | 137 +- llarp/path/path_context.hpp | 36 +- llarp/path/path_types.hpp | 4 +- llarp/path/pathbuilder.cpp | 223 ++- llarp/path/pathbuilder.hpp | 26 +- llarp/path/pathset.cpp | 135 +- llarp/path/pathset.hpp | 50 +- llarp/path/transit_hop.cpp | 166 +- llarp/path/transit_hop.hpp | 65 +- llarp/pow.cpp | 16 +- llarp/pow.hpp | 6 +- llarp/profiling.cpp | 90 +- llarp/profiling.hpp | 27 +- llarp/router/abstractrouter.hpp | 84 +- llarp/router/i_gossiper.hpp | 4 +- llarp/router/i_outbound_message_handler.hpp | 11 +- llarp/router/i_outbound_session_maker.hpp | 15 +- llarp/router/i_rc_lookup_handler.hpp | 19 +- llarp/router/outbound_message_handler.cpp | 167 +- llarp/router/outbound_message_handler.hpp | 66 +- llarp/router/outbound_session_maker.cpp | 127 +- llarp/router/outbound_session_maker.hpp | 67 +- llarp/router/rc_gossiper.cpp | 35 +- llarp/router/rc_gossiper.hpp | 14 +- llarp/router/rc_lookup_handler.cpp | 175 +- llarp/router/rc_lookup_handler.hpp | 71 +- llarp/router/router.cpp | 565 ++++--- llarp/router/router.hpp | 129 +- llarp/router_contact.cpp | 177 +-- llarp/router_contact.hpp | 74 +- llarp/router_id.cpp | 2 +- llarp/router_id.hpp | 10 +- llarp/router_version.cpp | 68 +- llarp/router_version.hpp | 13 +- llarp/routing/dht_message.cpp | 22 +- llarp/routing/dht_message.hpp | 2 +- llarp/routing/handler.hpp | 35 +- llarp/routing/message_parser.cpp | 46 +- llarp/routing/message_parser.hpp | 9 +- llarp/routing/path_confirm_message.cpp | 26 +- llarp/routing/path_confirm_message.hpp | 6 +- llarp/routing/path_latency_message.cpp | 26 +- llarp/routing/path_latency_message.hpp | 4 +- llarp/routing/path_transfer_message.cpp | 30 +- llarp/routing/path_transfer_message.hpp | 3 +- llarp/routing/transfer_traffic_message.cpp | 27 +- llarp/routing/transfer_traffic_message.hpp | 8 +- llarp/rpc/rpc.cpp | 141 +- llarp/rpc/rpc.hpp | 4 +- llarp/service/address.cpp | 32 +- llarp/service/address.hpp | 20 +- llarp/service/async_key_exchange.cpp | 29 +- llarp/service/async_key_exchange.hpp | 27 +- llarp/service/config.cpp | 17 +- llarp/service/config.hpp | 7 +- llarp/service/context.cpp | 116 +- llarp/service/context.hpp | 24 +- llarp/service/endpoint.cpp | 596 ++++--- llarp/service/endpoint.hpp | 103 +- llarp/service/endpoint_state.cpp | 77 +- llarp/service/endpoint_state.hpp | 35 +- llarp/service/endpoint_types.hpp | 40 +- llarp/service/endpoint_util.cpp | 61 +- llarp/service/endpoint_util.hpp | 14 +- llarp/service/handler.hpp | 20 +- .../service/hidden_service_address_lookup.cpp | 28 +- .../service/hidden_service_address_lookup.hpp | 19 +- llarp/service/identity.cpp | 80 +- llarp/service/identity.hpp | 9 +- llarp/service/info.cpp | 37 +- llarp/service/info.hpp | 18 +- llarp/service/intro.cpp | 26 +- llarp/service/intro.hpp | 9 +- llarp/service/intro_set.cpp | 143 +- llarp/service/intro_set.hpp | 21 +- llarp/service/lookup.cpp | 6 +- llarp/service/lookup.hpp | 8 +- llarp/service/outbound_context.cpp | 282 ++-- llarp/service/outbound_context.hpp | 23 +- llarp/service/pendingbuffer.hpp | 5 +- llarp/service/protocol.cpp | 272 ++-- llarp/service/protocol.hpp | 35 +- llarp/service/router_lookup_job.hpp | 6 +- llarp/service/sendcontext.cpp | 58 +- llarp/service/sendcontext.hpp | 17 +- llarp/service/session.cpp | 3 +- llarp/service/session.hpp | 7 +- llarp/service/tag.hpp | 16 +- llarp/service/tag_lookup_job.cpp | 17 +- llarp/service/tag_lookup_job.hpp | 14 +- llarp/service/vanity.hpp | 2 +- llarp/simulation/sim_context.cpp | 14 +- llarp/simulation/sim_context.hpp | 8 +- llarp/tooling/dht_event.hpp | 28 +- llarp/tooling/path_event.hpp | 27 +- llarp/tooling/rc_event.hpp | 10 +- llarp/tooling/router_event.hpp | 5 +- llarp/tooling/router_hive.cpp | 88 +- llarp/tooling/router_hive.hpp | 41 +- llarp/util/aligned.hpp | 26 +- llarp/util/bencode.cpp | 40 +- llarp/util/bencode.h | 3 +- llarp/util/bencode.hpp | 195 ++- llarp/util/bits.hpp | 19 +- llarp/util/buffer.cpp | 29 +- llarp/util/buffer.hpp | 72 +- llarp/util/codel.hpp | 75 +- llarp/util/compare_ptr.hpp | 4 +- llarp/util/copy_or_nullptr.hpp | 10 +- llarp/util/decaying_hashset.hpp | 15 +- llarp/util/encode.cpp | 6 +- llarp/util/encode.hpp | 102 +- llarp/util/endian.hpp | 38 +- llarp/util/fs.cpp | 52 +- llarp/util/fs.hpp | 30 +- llarp/util/json.cpp | 13 +- llarp/util/logging/android_logger.cpp | 13 +- llarp/util/logging/android_logger.hpp | 8 +- llarp/util/logging/file_logger.cpp | 55 +- llarp/util/logging/file_logger.hpp | 27 +- llarp/util/logging/json_logger.cpp | 18 +- llarp/util/logging/json_logger.hpp | 15 +- llarp/util/logging/logger.cpp | 5 +- llarp/util/logging/logger.hpp | 23 +- llarp/util/logging/logger_internal.cpp | 5 +- llarp/util/logging/logger_internal.hpp | 8 +- llarp/util/logging/logger_syslog.hpp | 8 +- llarp/util/logging/loglevel.cpp | 23 +- llarp/util/logging/loglevel.hpp | 2 +- llarp/util/logging/logstream.hpp | 18 +- llarp/util/logging/ostream_logger.cpp | 19 +- llarp/util/logging/ostream_logger.hpp | 8 +- llarp/util/logging/syslog_logger.cpp | 14 +- llarp/util/logging/win32_logger.cpp | 47 +- llarp/util/logging/win32_logger.hpp | 11 +- llarp/util/lokinet_init.c | 12 +- llarp/util/mem.cpp | 18 +- llarp/util/mem.h | 2 +- llarp/util/mem.hpp | 36 +- llarp/util/meta/memfn.hpp | 48 +- llarp/util/meta/traits.hpp | 52 +- llarp/util/printer.cpp | 79 +- llarp/util/printer.hpp | 376 +++-- llarp/util/str.cpp | 18 +- llarp/util/str.hpp | 2 +- llarp/util/thread/annotations.hpp | 33 +- llarp/util/thread/barrier.hpp | 6 +- llarp/util/thread/logic.cpp | 39 +- llarp/util/thread/logic.hpp | 11 +- llarp/util/thread/queue.hpp | 231 ++- llarp/util/thread/queue_manager.cpp | 193 +-- llarp/util/thread/queue_manager.hpp | 17 +- llarp/util/thread/thread_pool.cpp | 61 +- llarp/util/thread/thread_pool.hpp | 13 +- llarp/util/thread/threading.cpp | 6 +- llarp/util/thread/threading.hpp | 40 +- llarp/util/thread/threadpool.cpp | 32 +- llarp/util/thread/threadpool.h | 33 +- llarp/util/time.cpp | 40 +- llarp/util/time.hpp | 6 +- llarp/util/types.hpp | 2 +- llarp/win32/win32_inet.c | 140 +- llarp/win32/win32_intrnl.c | 1409 +++++++++-------- pybind/common.hpp | 38 +- pybind/llarp/config.cpp | 56 +- pybind/llarp/context.cpp | 48 +- pybind/llarp/crypto/types.cpp | 6 +- pybind/llarp/dht/dht_types.cpp | 9 +- pybind/llarp/handlers/pyhandler.cpp | 4 +- pybind/llarp/handlers/pyhandler.hpp | 44 +- pybind/llarp/path/path_hop_config.cpp | 6 +- pybind/llarp/path/path_types.cpp | 2 +- pybind/llarp/router_contact.cpp | 2 +- pybind/llarp/router_id.cpp | 18 +- pybind/llarp/service/address.cpp | 8 +- pybind/llarp/tooling/router_event.cpp | 41 +- pybind/llarp/tooling/router_hive.cpp | 4 +- 355 files changed, 10755 insertions(+), 11130 deletions(-) diff --git a/daemon/lokinetctl.cpp b/daemon/lokinetctl.cpp index 6dfd7360b..98fc3ab4b 100644 --- a/daemon/lokinetctl.cpp +++ b/daemon/lokinetctl.cpp @@ -14,15 +14,15 @@ namespace { bool - dumpRc(const std::vector< std::string >& files) + dumpRc(const std::vector& files) { nlohmann::json result; - for(const auto& file : files) + for (const auto& file : files) { llarp::RouterContact rc; const bool ret = rc.Read(file.c_str()); - if(ret) + if (ret) { result[file] = rc.ToJson(); } @@ -40,10 +40,10 @@ namespace size_t curlCallback(void* contents, size_t size, size_t nmemb, void* userp) noexcept { - auto* str = static_cast< std::string* >(userp); + auto* str = static_cast(userp); size_t realsize = size * nmemb; - char* asChar = static_cast< char* >(contents); + char* asChar = static_cast(contents); std::copy(asChar, asChar + realsize, std::back_inserter(*str)); @@ -57,13 +57,13 @@ namespace curl_global_init(CURL_GLOBAL_ALL); llarp::Config config; - if(!config.Load(configFile.c_str())) + if (!config.Load(configFile.c_str())) { llarp::LogError("Failed to load from config file: ", configFile); return false; } - if(!config.api.enableRPCServer()) + if (!config.api.enableRPCServer()) { llarp::LogError("Config does not have RPC enabled"); return false; @@ -71,18 +71,15 @@ namespace std::string address = config.api.rpcBindAddr() + "/jsonrpc"; - const nlohmann::json request{{"method", command}, - {"params", nlohmann::json::object()}, - {"id", "foo"}}; + const nlohmann::json request{ + {"method", command}, {"params", nlohmann::json::object()}, {"id", "foo"}}; const std::string requestStr = request.dump(); - std::unique_ptr< curl_slist, void (*)(curl_slist*) > chunk( - curl_slist_append(nullptr, "content-type: application/json"), - &curl_slist_free_all); + std::unique_ptr chunk( + curl_slist_append(nullptr, "content-type: application/json"), &curl_slist_free_all); - std::unique_ptr< CURL, void (*)(CURL*) > curl(curl_easy_init(), - &curl_easy_cleanup); + std::unique_ptr curl(curl_easy_init(), &curl_easy_cleanup); curl_easy_setopt(curl.get(), CURLOPT_URL, address.c_str()); curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, requestStr.c_str()); curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDSIZE, requestStr.size()); @@ -93,7 +90,7 @@ namespace curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &result); auto res = curl_easy_perform(curl.get()); - if(res != CURLE_OK) + if (res != CURLE_OK) { llarp::LogError("Failed to curl endpoint, ", curl_easy_strerror(res)); return false; @@ -109,66 +106,65 @@ namespace int main(int argc, char* argv[]) { - cxxopts::Options options("lokinetctl", - "LokiNET is a free, open source, private, " - "decentralized, \"market based sybil resistant\" " - "and IP based onion routing network"); - - options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())( - "h,help", "help", cxxopts::value< bool >())( - "c,config", "config file", - cxxopts::value< std::string >()->default_value( - llarp::GetDefaultConfigPath().string())) + cxxopts::Options options( + "lokinetctl", + "LokiNET is a free, open source, private, " + "decentralized, \"market based sybil resistant\" " + "and IP based onion routing network"); + + options.add_options()("v,verbose", "Verbose", cxxopts::value())( + "h,help", "help", cxxopts::value())( + "c,config", + "config file", + cxxopts::value()->default_value(llarp::GetDefaultConfigPath().string())) #ifdef WITH_CURL - ("j,jsonrpc", "hit json rpc endpoint", cxxopts::value< std::string >()) + ("j,jsonrpc", "hit json rpc endpoint", cxxopts::value()) #endif - ("dump", "dump rc file", - cxxopts::value< std::vector< std::string > >(), "FILE"); + ("dump", "dump rc file", cxxopts::value>(), "FILE"); try { const auto result = options.parse(argc, argv); - if(result.count("verbose") > 0) + if (result.count("verbose") > 0) { SetLogLevel(llarp::eLogDebug); llarp::LogContext::Instance().logStream = - std::make_unique< llarp::OStreamLogStream >(true, std::cerr); + std::make_unique(true, std::cerr); llarp::LogDebug("debug logging activated"); } else { SetLogLevel(llarp::eLogError); llarp::LogContext::Instance().logStream = - std::make_unique< llarp::OStreamLogStream >(true, std::cerr); + std::make_unique(true, std::cerr); } - if(result.count("help") > 0) + if (result.count("help") > 0) { std::cout << options.help() << std::endl; return 0; } - if(result.count("dump") > 0) + if (result.count("dump") > 0) { - if(!dumpRc(result["dump"].as< std::vector< std::string > >())) + if (!dumpRc(result["dump"].as>())) { return 1; } } #ifdef WITH_CURL - if(result.count("jsonrpc") > 0) + if (result.count("jsonrpc") > 0) { - if(!executeJsonRpc(result["jsonrpc"].as< std::string >(), - result["config"].as< std::string >())) + if (!executeJsonRpc(result["jsonrpc"].as(), result["config"].as())) { return 1; } } #endif } - catch(const cxxopts::OptionParseException& ex) + catch (const cxxopts::OptionParseException& ex) { std::cerr << ex.what() << std::endl; std::cout << options.help() << std::endl; diff --git a/daemon/main.cpp b/daemon/main.cpp index a97b42758..ee56fc2ba 100644 --- a/daemon/main.cpp +++ b/daemon/main.cpp @@ -17,16 +17,16 @@ #define wmin(x, y) (((x) < (y)) ? (x) : (y)) #define MIN wmin extern "C" LONG FAR PASCAL -win32_signal_handler(EXCEPTION_POINTERS *); +win32_signal_handler(EXCEPTION_POINTERS*); #endif -struct llarp_main *ctx = 0; -std::promise< int > exit_code; +struct llarp_main* ctx = 0; +std::promise exit_code; void handle_signal(int sig) { - if(ctx) + if (ctx) { llarp_main_signal(ctx, sig); } @@ -39,7 +39,7 @@ startWinsock() WSADATA wsockd; int err; err = ::WSAStartup(MAKEWORD(2, 2), &wsockd); - if(err) + if (err) { perror("Failed to start Windows Sockets"); return err; @@ -64,9 +64,9 @@ run_main_context(std::string conffname, llarp_main_runtime_opts opts) // this is important, can downgrade from Info though llarp::LogDebug("Running from: ", fs::current_path().string()); llarp::LogInfo("Using config file: ", conffname); - ctx = llarp_main_init(conffname.c_str()); + ctx = llarp_main_init(conffname.c_str()); int code = 1; - if(ctx) + if (ctx) { signal(SIGINT, handle_signal); signal(SIGTERM, handle_signal); @@ -75,101 +75,100 @@ run_main_context(std::string conffname, llarp_main_runtime_opts opts) #endif code = llarp_main_setup(ctx); llarp::util::SetThreadName("llarp-mainloop"); - if(code == 0) + if (code == 0) code = llarp_main_run(ctx, opts); } exit_code.set_value(code); } int -main(int argc, char *argv[]) +main(int argc, char* argv[]) { auto result = Lokinet_INIT(); - if(result) + if (result) { return result; } llarp_main_runtime_opts opts; - const char *singleThreadVar = getenv("LLARP_SHADOW"); - if(singleThreadVar && std::string(singleThreadVar) == "1") + const char* singleThreadVar = getenv("LLARP_SHADOW"); + if (singleThreadVar && std::string(singleThreadVar) == "1") { opts.singleThreaded = true; } #ifdef _WIN32 - if(startWinsock()) + if (startWinsock()) return -1; SetConsoleCtrlHandler(handle_signal_win32, TRUE); // SetUnhandledExceptionFilter(win32_signal_handler); #endif - cxxopts::Options options("lokinet", - "LokiNET is a free, open source, private, " - "decentralized, \"market based sybil resistant\" " - "and IP based onion routing network"); - options.add_options()("v,verbose", "Verbose", cxxopts::value< bool >())( - "h,help", "help", cxxopts::value< bool >())("version", "version", - cxxopts::value< bool >())( - "g,generate", "generate client config", cxxopts::value< bool >())( - "r,router", "generate router config", cxxopts::value< bool >())( - "f,force", "overwrite", cxxopts::value< bool >())( - "c,colour", "colour output", - cxxopts::value< bool >()->default_value("true"))( + cxxopts::Options options( + "lokinet", + "LokiNET is a free, open source, private, " + "decentralized, \"market based sybil resistant\" " + "and IP based onion routing network"); + options.add_options()("v,verbose", "Verbose", cxxopts::value())( + "h,help", "help", cxxopts::value())("version", "version", cxxopts::value())( + "g,generate", "generate client config", cxxopts::value())( + "r,router", "generate router config", cxxopts::value())( + "f,force", "overwrite", cxxopts::value())( + "c,colour", "colour output", cxxopts::value()->default_value("true"))( "b,background", "background mode (start, but do not connect to the network)", - cxxopts::value< bool >())("config", "path to configuration file", - cxxopts::value< std::string >()); + cxxopts::value())( + "config", "path to configuration file", cxxopts::value()); options.parse_positional("config"); bool genconfigOnly = false; - bool asRouter = false; - bool overWrite = false; + bool asRouter = false; + bool overWrite = false; std::string conffname; try { auto result = options.parse(argc, argv); - if(result.count("verbose") > 0) + if (result.count("verbose") > 0) { SetLogLevel(llarp::eLogDebug); llarp::LogDebug("debug logging activated"); } - if(!result["colour"].as< bool >()) + if (!result["colour"].as()) { llarp::LogContext::Instance().logStream = - std::make_unique< llarp::OStreamLogStream >(false, std::cerr); + std::make_unique(false, std::cerr); } - if(result.count("help")) + if (result.count("help")) { std::cout << options.help() << std::endl; return 0; } - if(result.count("version")) + if (result.count("version")) { std::cout << llarp_version() << std::endl; return 0; } - if(result.count("generate") > 0) + if (result.count("generate") > 0) { genconfigOnly = true; } - if(result.count("background") > 0) + if (result.count("background") > 0) { opts.background = true; } - if(result.count("force") > 0) + if (result.count("force") > 0) { overWrite = true; } - if(result.count("router") > 0) + if (result.count("router") > 0) { asRouter = true; // we should generate and exit (docker needs this, so we don't write a @@ -177,52 +176,50 @@ main(int argc, char *argv[]) genconfigOnly = true; } - if(result.count("config") > 0) + if (result.count("config") > 0) { - auto arg = result["config"].as< std::string >(); - if(!arg.empty()) + auto arg = result["config"].as(); + if (!arg.empty()) { conffname = arg; } } } - catch(const cxxopts::option_not_exists_exception &ex) + catch (const cxxopts::option_not_exists_exception& ex) { std::cerr << ex.what(); std::cout << options.help() << std::endl; return 1; } - if(!conffname.empty()) + if (!conffname.empty()) { // when we have an explicit filepath - fs::path fname = fs::path(conffname); + fs::path fname = fs::path(conffname); fs::path basedir = fname.parent_path(); - if(!basedir.empty()) + if (!basedir.empty()) { std::error_code ec; - if(!fs::create_directories(basedir, ec)) + if (!fs::create_directories(basedir, ec)) { - if(ec) + if (ec) { - llarp::LogError("failed to create '", basedir.string(), - "': ", ec.message()); + llarp::LogError("failed to create '", basedir.string(), "': ", ec.message()); return 1; } } } - if(genconfigOnly) + if (genconfigOnly) { - if(!llarp_ensure_config(conffname.c_str(), basedir.string().c_str(), - overWrite, asRouter)) + if (!llarp_ensure_config(conffname.c_str(), basedir.string().c_str(), overWrite, asRouter)) return 1; } else { std::error_code ec; - if(!fs::exists(fname, ec)) + if (!fs::exists(fname, ec)) { llarp::LogError("Config file not found ", conffname); return 1; @@ -237,12 +234,11 @@ main(int argc, char *argv[]) std::error_code ec; // These paths are guaranteed to exist - $APPDATA or $HOME // so only create .lokinet/* - if(!fs::create_directory(basepath, ec)) + if (!fs::create_directory(basepath, ec)) { - if(ec) + if (ec) { - llarp::LogError("failed to create '", basepath.string(), - "': ", ec.message()); + llarp::LogError("failed to create '", basepath.string(), "': ", ec.message()); return 1; } } @@ -250,13 +246,13 @@ main(int argc, char *argv[]) auto fpath = llarp::GetDefaultConfigPath(); // if using default INI file, we're create it even if you don't ask us too - if(!llarp_ensure_config(fpath.string().c_str(), basepath.string().c_str(), - overWrite, asRouter)) + if (!llarp_ensure_config( + fpath.string().c_str(), basepath.string().c_str(), overWrite, asRouter)) return 1; conffname = fpath.string(); } - if(genconfigOnly) + if (genconfigOnly) { return 0; } @@ -266,33 +262,33 @@ main(int argc, char *argv[]) do { // do periodic non lokinet related tasks here - if(ctx != nullptr) + if (ctx != nullptr) { auto ctx_pp = llarp::Context::Get(ctx); - if(ctx_pp != nullptr) + if (ctx_pp != nullptr) { - if(ctx_pp->IsUp() and not ctx_pp->LooksAlive()) + if (ctx_pp->IsUp() and not ctx_pp->LooksAlive()) { - for(const auto &wtf : {"you have been visited by the mascott of the " - "deadlocked router.", - "⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣀⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠄⠄⠄⠄", - "⠄⠄⠄⠄⠄⢀⣀⣀⡀⠄⠄⠄⡠⢲⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠄⠄", - "⠄⠄⠄⠔⣈⣀⠄⢔⡒⠳⡴⠊⠄⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⣿⣿⣧⠄⠄", - "⠄⢜⡴⢑⠖⠊⢐⣤⠞⣩⡇⠄⠄⠄⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠄⠝⠛⠋⠐", - "⢸⠏⣷⠈⠄⣱⠃⠄⢠⠃⠐⡀⠄⠄⠄⠄⠙⠻⢿⣿⣿⣿⣿⣿⣿⣿⡿⠛⠸⠄⠄⠄⠄", - "⠈⣅⠞⢁⣿⢸⠘⡄⡆⠄⠄⠈⠢⡀⠄⠄⠄⠄⠄⠄⠉⠙⠛⠛⠛⠉⠉⡀⠄⠡⢀⠄⣀", - "⠄⠙⡎⣹⢸⠄⠆⢘⠁⠄⠄⠄⢸⠈⠢⢄⡀⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠃⠄⠄⠄⠄⠄", - "⠄⠄⠑⢿⠈⢆⠘⢼⠄⠄⠄⠄⠸⢐⢾⠄⡘⡏⠲⠆⠠⣤⢤⢤⡤⠄⣖⡇⠄⠄⠄⠄⠄", - "⣴⣶⣿⣿⣣⣈⣢⣸⠄⠄⠄⠄⡾⣷⣾⣮⣤⡏⠁⠘⠊⢠⣷⣾⡛⡟⠈⠄⠄⠄⠄⠄⠄", - "⣿⣿⣿⣿⣿⠉⠒⢽⠄⠄⠄⠄⡇⣿⣟⣿⡇⠄⠄⠄⠄⢸⣻⡿⡇⡇⠄⠄⠄⠄⠄⠄⠄", - "⠻⣿⣿⣿⣿⣄⠰⢼⠄⠄⠄⡄⠁⢻⣍⣯⠃⠄⠄⠄⠄⠈⢿⣻⠃⠈⡆⡄⠄⠄⠄⠄⠄", - "⠄⠙⠿⠿⠛⣿⣶⣤⡇⠄⠄⢣⠄⠄⠈⠄⢠⠂⠄⠁⠄⡀⠄⠄⣀⠔⢁⠃⠄⠄⠄⠄⠄", - "⠄⠄⠄⠄⠄⣿⣿⣿⣿⣾⠢⣖⣶⣦⣤⣤⣬⣤⣤⣤⣴⣶⣶⡏⠠⢃⠌⠄⠄⠄⠄⠄⠄", - "⠄⠄⠄⠄⠄⠿⠿⠟⠛⡹⠉⠛⠛⠿⠿⣿⣿⣿⣿⣿⡿⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄", - "⠠⠤⠤⠄⠄⣀⠄⠄⠄⠑⠠⣤⣀⣀⣀⡘⣿⠿⠙⠻⡍⢀⡈⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄", - "⠄⠄⠄⠄⠄⠄⠑⠠⣠⣴⣾⣿⣿⣿⣿⣿⣿⣇⠉⠄⠻⣿⣷⣄⡀⠄⠄⠄⠄⠄⠄⠄⠄", - "file a bug report now or be cursed with this " - "annoying image in your syslog for all time."}) + for (const auto& wtf : {"you have been visited by the mascott of the " + "deadlocked router.", + "⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣀⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠄⠄⠄⠄", + "⠄⠄⠄⠄⠄⢀⣀⣀⡀⠄⠄⠄⡠⢲⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⡀⠄⠄", + "⠄⠄⠄⠔⣈⣀⠄⢔⡒⠳⡴⠊⠄⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠿⣿⣿⣧⠄⠄", + "⠄⢜⡴⢑⠖⠊⢐⣤⠞⣩⡇⠄⠄⠄⠙⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣆⠄⠝⠛⠋⠐", + "⢸⠏⣷⠈⠄⣱⠃⠄⢠⠃⠐⡀⠄⠄⠄⠄⠙⠻⢿⣿⣿⣿⣿⣿⣿⣿⡿⠛⠸⠄⠄⠄⠄", + "⠈⣅⠞⢁⣿⢸⠘⡄⡆⠄⠄⠈⠢⡀⠄⠄⠄⠄⠄⠄⠉⠙⠛⠛⠛⠉⠉⡀⠄⠡⢀⠄⣀", + "⠄⠙⡎⣹⢸⠄⠆⢘⠁⠄⠄⠄⢸⠈⠢⢄⡀⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠃⠄⠄⠄⠄⠄", + "⠄⠄⠑⢿⠈⢆⠘⢼⠄⠄⠄⠄⠸⢐⢾⠄⡘⡏⠲⠆⠠⣤⢤⢤⡤⠄⣖⡇⠄⠄⠄⠄⠄", + "⣴⣶⣿⣿⣣⣈⣢⣸⠄⠄⠄⠄⡾⣷⣾⣮⣤⡏⠁⠘⠊⢠⣷⣾⡛⡟⠈⠄⠄⠄⠄⠄⠄", + "⣿⣿⣿⣿⣿⠉⠒⢽⠄⠄⠄⠄⡇⣿⣟⣿⡇⠄⠄⠄⠄⢸⣻⡿⡇⡇⠄⠄⠄⠄⠄⠄⠄", + "⠻⣿⣿⣿⣿⣄⠰⢼⠄⠄⠄⡄⠁⢻⣍⣯⠃⠄⠄⠄⠄⠈⢿⣻⠃⠈⡆⡄⠄⠄⠄⠄⠄", + "⠄⠙⠿⠿⠛⣿⣶⣤⡇⠄⠄⢣⠄⠄⠈⠄⢠⠂⠄⠁⠄⡀⠄⠄⣀⠔⢁⠃⠄⠄⠄⠄⠄", + "⠄⠄⠄⠄⠄⣿⣿⣿⣿⣾⠢⣖⣶⣦⣤⣤⣬⣤⣤⣤⣴⣶⣶⡏⠠⢃⠌⠄⠄⠄⠄⠄⠄", + "⠄⠄⠄⠄⠄⠿⠿⠟⠛⡹⠉⠛⠛⠿⠿⣿⣿⣿⣿⣿⡿⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄", + "⠠⠤⠤⠄⠄⣀⠄⠄⠄⠑⠠⣤⣀⣀⣀⡘⣿⠿⠙⠻⡍⢀⡈⠂⠄⠄⠄⠄⠄⠄⠄⠄⠄", + "⠄⠄⠄⠄⠄⠄⠑⠠⣠⣴⣾⣿⣿⣿⣿⣿⣿⣇⠉⠄⠻⣿⣷⣄⡀⠄⠄⠄⠄⠄⠄⠄⠄", + "file a bug report now or be cursed with this " + "annoying image in your syslog for all time."}) { LogError(wtf); } @@ -300,14 +296,14 @@ main(int argc, char *argv[]) } } } - } while(ftr.wait_for(std::chrono::seconds(1)) != std::future_status::ready); + } while (ftr.wait_for(std::chrono::seconds(1)) != std::future_status::ready); main_thread.join(); const auto code = ftr.get(); #ifdef _WIN32 ::WSACleanup(); #endif - if(ctx) + if (ctx) { llarp_main_free(ctx); } diff --git a/include/llarp.h b/include/llarp.h index a50300cee..9b6ff2f17 100644 --- a/include/llarp.h +++ b/include/llarp.h @@ -15,8 +15,7 @@ extern "C" /// if basedir is not nullptr then use basedir as an absolute /// base path for all files in config bool - llarp_ensure_config(const char *, const char *, bool overwrite, - bool asrouter); + llarp_ensure_config(const char*, const char*, bool overwrite, bool asrouter); /// llarp application context for C api struct llarp_main; @@ -24,8 +23,8 @@ extern "C" /// runtime options for main context from cli struct llarp_main_runtime_opts { - bool background = false; - bool debug = false; + bool background = false; + bool debug = false; bool singleThreaded = false; }; @@ -33,12 +32,12 @@ extern "C" struct llarp_config; /// get default config for current platform - struct llarp_config * + struct llarp_config* llarp_default_config(); /// free previously allocated configuration void - llarp_config_free(struct llarp_config *); + llarp_config_free(struct llarp_config*); /// packet writer to send packets to lokinet internals struct llarp_vpn_writer_pipe; @@ -52,18 +51,18 @@ extern "C" struct llarp_vpn_io { /// private implementation - void *impl; + void* impl; /// user data - void *user; + void* user; /// hook set by user called by lokinet core when lokinet is done with the /// vpn io - void (*closed)(struct llarp_vpn_io *); + void (*closed)(struct llarp_vpn_io*); /// hook set by user called from lokinet core after attempting to inject /// into endpoint passed a bool set to true if we were injected otherwise /// set to false - void (*injected)(struct llarp_vpn_io *, bool); + void (*injected)(struct llarp_vpn_io*, bool); /// hook set by user called every event loop tick - void (*tick)(struct llarp_vpn_io *); + void (*tick)(struct llarp_vpn_io*); }; /// info about the network interface that we give to lokinet core @@ -80,88 +79,87 @@ extern "C" /// initialize llarp_vpn_io private implementation /// returns false if either parameter is nullptr bool - llarp_vpn_io_init(struct llarp_main *m, struct llarp_vpn_io *io); + llarp_vpn_io_init(struct llarp_main* m, struct llarp_vpn_io* io); /// get the packet pipe for writing IP packets to lokinet internals /// returns nullptr if llarp_vpn_io is nullptr or not initialized - struct llarp_vpn_pkt_writer * - llarp_vpn_io_packet_writer(struct llarp_vpn_io *io); + struct llarp_vpn_pkt_writer* + llarp_vpn_io_packet_writer(struct llarp_vpn_io* io); /// get the packet pipe for reading IP packets from lokinet internals /// returns nullptr if llarp_vpn_io is nullptr or not initialized - struct llarp_vpn_pkt_reader * - llarp_vpn_io_packet_reader(struct llarp_vpn_io *io); + struct llarp_vpn_pkt_reader* + llarp_vpn_io_packet_reader(struct llarp_vpn_io* io); /// blocking read on packet reader from lokinet internals /// returns -1 on error, returns size of packet read /// thread safe ssize_t - llarp_vpn_io_readpkt(struct llarp_vpn_pkt_reader *r, unsigned char *dst, - size_t dstlen); + llarp_vpn_io_readpkt(struct llarp_vpn_pkt_reader* r, unsigned char* dst, size_t dstlen); /// blocking write on packet writer to lokinet internals /// returns false if we can't write this packet /// return true if we wrote this packet /// thread safe bool - llarp_vpn_io_writepkt(struct llarp_vpn_pkt_writer *w, unsigned char *pktbuf, - size_t pktlen); + llarp_vpn_io_writepkt(struct llarp_vpn_pkt_writer* w, unsigned char* pktbuf, size_t pktlen); /// close vpn io and free private implementation after done /// operation is async and calls llarp_vpn_io.closed after fully closed /// after fully closed the llarp_vpn_io MUST be re-initialized by /// llarp_vpn_io_init if it is to be used again void - llarp_vpn_io_close_async(struct llarp_vpn_io *io); + llarp_vpn_io_close_async(struct llarp_vpn_io* io); /// get the default endpoint's name for injection - const char * - llarp_main_get_default_endpoint_name(struct llarp_main *m); + const char* + llarp_main_get_default_endpoint_name(struct llarp_main* m); /// give main context a vpn io for mobile when it is reader to do io with /// associated info tries to give the vpn io to endpoint with name epName a /// deferred call to llarp_vpn_io.injected is queued unconditionally /// thread safe bool - llarp_main_inject_vpn_by_name(struct llarp_main *m, const char *epName, - struct llarp_vpn_io *io, - struct llarp_vpn_ifaddr_info info); + llarp_main_inject_vpn_by_name( + struct llarp_main* m, + const char* epName, + struct llarp_vpn_io* io, + struct llarp_vpn_ifaddr_info info); /// give main context a vpn io on its default endpoint static bool - llarp_main_inject_default_vpn(struct llarp_main *m, struct llarp_vpn_io *io, - struct llarp_vpn_ifaddr_info info) + llarp_main_inject_default_vpn( + struct llarp_main* m, struct llarp_vpn_io* io, struct llarp_vpn_ifaddr_info info) { - return llarp_main_inject_vpn_by_name( - m, llarp_main_get_default_endpoint_name(m), io, info); + return llarp_main_inject_vpn_by_name(m, llarp_main_get_default_endpoint_name(m), io, info); } /// load config from file by name /// allocates new config and puts it into c /// return false on failure bool - llarp_config_load_file(const char *fname, struct llarp_config **c); + llarp_config_load_file(const char* fname, struct llarp_config** c); /// loads config from file by name /// uses already allocated config /// return false on failure bool - llarp_config_read_file(struct llarp_config *c, const char *f); + llarp_config_read_file(struct llarp_config* c, const char* f); /// make a main context from configuration /// copies config contents - struct llarp_main * - llarp_main_init_from_config(struct llarp_config *conf); + struct llarp_main* + llarp_main_init_from_config(struct llarp_config* conf); /// initialize application context and load config - static struct llarp_main * - llarp_main_init(const char *fname) + static struct llarp_main* + llarp_main_init(const char* fname) { - struct llarp_main *m = 0; - struct llarp_config *conf = 0; - if(!llarp_config_load_file(fname, &conf)) + struct llarp_main* m = 0; + struct llarp_config* conf = 0; + if (!llarp_config_load_file(fname, &conf)) return 0; - if(conf == NULL) + if (conf == NULL) return 0; m = llarp_main_init_from_config(conf); llarp_config_free(conf); @@ -169,13 +167,13 @@ extern "C" } /// initialize applicatin context with all defaults - static struct llarp_main * + static struct llarp_main* llarp_main_default_init() { - struct llarp_main *m; - struct llarp_config *conf; + struct llarp_main* m; + struct llarp_config* conf; conf = llarp_default_config(); - if(conf == 0) + if (conf == 0) return 0; m = llarp_main_init_from_config(conf); llarp_config_free(conf); @@ -185,36 +183,36 @@ extern "C" /// (re)configure main context /// return true if (re)configuration was successful bool - llarp_main_configure(struct llarp_main *ptr, struct llarp_config *conf); + llarp_main_configure(struct llarp_main* ptr, struct llarp_config* conf); /// return true if this main context is running /// return false otherwise bool - llarp_main_is_running(struct llarp_main *ptr); + llarp_main_is_running(struct llarp_main* ptr); /// handle signal for main context void - llarp_main_signal(struct llarp_main *ptr, int sig); + llarp_main_signal(struct llarp_main* ptr, int sig); /// setup main context, returns 0 on success int - llarp_main_setup(struct llarp_main *ptr); + llarp_main_setup(struct llarp_main* ptr); /// run main context, returns 0 on success, blocks until program end int - llarp_main_run(struct llarp_main *ptr, struct llarp_main_runtime_opts opts); + llarp_main_run(struct llarp_main* ptr, struct llarp_main_runtime_opts opts); /// tell main context to stop and wait for complete stop /// after calling this you can call llarp_main_free safely void - llarp_main_stop(struct llarp_main *ptr); + llarp_main_stop(struct llarp_main* ptr); /// free main context and end all operations void - llarp_main_free(struct llarp_main *ptr); + llarp_main_free(struct llarp_main* ptr); /// get version string - const char * + const char* llarp_version(); /// return sizeof(llarp_main); for jni diff --git a/include/llarp.hpp b/include/llarp.hpp index ca136a65e..1d3394cd6 100644 --- a/include/llarp.hpp +++ b/include/llarp.hpp @@ -39,23 +39,23 @@ namespace llarp struct Context { /// get context from main pointer - static std::shared_ptr< Context > - Get(llarp_main *); + static std::shared_ptr + Get(llarp_main*); Context() = default; - std::unique_ptr< Crypto > crypto; - std::unique_ptr< CryptoManager > cryptoManager; - std::unique_ptr< AbstractRouter > router; - std::shared_ptr< thread::ThreadPool > worker; - std::shared_ptr< Logic > logic; - std::unique_ptr< Config > config; - std::unique_ptr< llarp_nodedb > nodedb; + std::unique_ptr crypto; + std::unique_ptr cryptoManager; + std::unique_ptr router; + std::shared_ptr worker; + std::shared_ptr logic; + std::unique_ptr config; + std::unique_ptr nodedb; llarp_ev_loop_ptr mainloop; std::string nodedb_dir; bool - LoadConfig(const std::string &fname); + LoadConfig(const std::string& fname); void Close(); @@ -93,16 +93,16 @@ namespace llarp /// return true if queued for calling /// return false if not queued for calling bool - CallSafe(std::function< void(void) > f); + CallSafe(std::function f); #ifdef LOKINET_HIVE void - InjectHive(tooling::RouterHive *hive); + InjectHive(tooling::RouterHive* hive); #endif private: void - SetPIDFile(const std::string &fname); + SetPIDFile(const std::string& fname); bool WritePIDFile() const; @@ -118,7 +118,7 @@ namespace llarp std::string configfile; std::string pidfile; - std::unique_ptr< std::promise< void > > closeWaiter; + std::unique_ptr> closeWaiter; }; } // namespace llarp diff --git a/include/llarp/string.h b/include/llarp/string.h index a6ca6f342..69c4a7a82 100644 --- a/include/llarp/string.h +++ b/include/llarp/string.h @@ -9,7 +9,7 @@ size_t INLINE strnlen(const char* str, size_t sz) { size_t slen = 0; - while(sz-- && str[slen]) + while (sz-- && str[slen]) slen++; return slen; } diff --git a/include/tuntap.h b/include/tuntap.h index 169b265ff..cf827b9d5 100644 --- a/include/tuntap.h +++ b/include/tuntap.h @@ -144,9 +144,9 @@ extern "C" struct device { /** set me on ios and android to block on a promise for the fd */ - int (*obtain_fd)(struct device *); + int (*obtain_fd)(struct device*); /** user data */ - void *user; + void* user; t_tun tun_fd; int ctrl_sock; int flags; /* ifr.ifr_flags on Unix */ @@ -166,7 +166,7 @@ extern "C" }; /* User definable log callback */ - typedef void (*t_tuntap_log)(int, int, const char *, const char *); + typedef void (*t_tuntap_log)(int, int, const char*, const char*); TUNTAP_EXPORT t_tuntap_log __tuntap_log; #ifndef LOG_TAG @@ -176,90 +176,89 @@ extern "C" #define tuntap_log(lvl, msg) __tuntap_log(lvl, __LINE__, LOG_TAG, msg) /* Portable "public" functions */ - TUNTAP_EXPORT struct device * + TUNTAP_EXPORT struct device* tuntap_init(void); TUNTAP_EXPORT int tuntap_version(void); TUNTAP_EXPORT void - tuntap_destroy(struct device *); + tuntap_destroy(struct device*); TUNTAP_EXPORT void - tuntap_release(struct device *); + tuntap_release(struct device*); TUNTAP_EXPORT int - tuntap_start(struct device *, int, int); - TUNTAP_EXPORT char * - tuntap_get_ifname(struct device *); + tuntap_start(struct device*, int, int); + TUNTAP_EXPORT char* + tuntap_get_ifname(struct device*); TUNTAP_EXPORT int - tuntap_set_ifname(struct device *, const char *); + tuntap_set_ifname(struct device*, const char*); TUNTAP_EXPORT int - tuntap_set_descr(struct device *, const char *); + tuntap_set_descr(struct device*, const char*); TUNTAP_EXPORT int - tuntap_up(struct device *); + tuntap_up(struct device*); TUNTAP_EXPORT int - tuntap_down(struct device *); + tuntap_down(struct device*); TUNTAP_EXPORT int - tuntap_get_mtu(struct device *); + tuntap_get_mtu(struct device*); TUNTAP_EXPORT int - tuntap_set_mtu(struct device *, int); + tuntap_set_mtu(struct device*, int); /** set ip address and netmask */ TUNTAP_EXPORT int - tuntap_set_ip(struct device *, const char *srcaddr, const char *dstaddr, - int netmask); + tuntap_set_ip(struct device*, const char* srcaddr, const char* dstaddr, int netmask); // TUNTAP_EXPORT int tuntap_set_ip_old(struct device *, const char // *, int); /*TUNTAP_EXPORT int tuntap_set_ip_old(struct device *, const char * *, int);*/ TUNTAP_EXPORT int - tuntap_read(struct device *, void *, size_t); + tuntap_read(struct device*, void*, size_t); TUNTAP_EXPORT int - tuntap_write(struct device *, void *, size_t); + tuntap_write(struct device*, void*, size_t); TUNTAP_EXPORT int - tuntap_get_readable(struct device *); + tuntap_get_readable(struct device*); TUNTAP_EXPORT int - tuntap_set_nonblocking(struct device *dev, int); + tuntap_set_nonblocking(struct device* dev, int); TUNTAP_EXPORT int - tuntap_set_debug(struct device *dev, int); + tuntap_set_debug(struct device* dev, int); /* Logging functions */ TUNTAP_EXPORT void tuntap_log_set_cb(t_tuntap_log cb); void - tuntap_log_default(int, int, const char *, const char *); + tuntap_log_default(int, int, const char*, const char*); void - tuntap_log_hexdump(void *, size_t); + tuntap_log_hexdump(void*, size_t); void - tuntap_log_chksum(void *, int); + tuntap_log_chksum(void*, int); /* OS specific functions */ int - tuntap_sys_start(struct device *, int, int); + tuntap_sys_start(struct device*, int, int); void - tuntap_sys_destroy(struct device *); + tuntap_sys_destroy(struct device*); int - tuntap_sys_set_ipv4(struct device *, t_tun_in_addr *, uint32_t); + tuntap_sys_set_ipv4(struct device*, t_tun_in_addr*, uint32_t); #if defined(Windows) int - tuntap_sys_set_dns(struct device *dev, t_tun_in_addr *s, uint32_t mask); + tuntap_sys_set_dns(struct device* dev, t_tun_in_addr* s, uint32_t mask); #endif #if defined(FreeBSD) int - tuntap_sys_set_ipv4_tap(struct device *, t_tun_in_addr *, uint32_t); + tuntap_sys_set_ipv4_tap(struct device*, t_tun_in_addr*, uint32_t); int - tuntap_sys_set_ipv4_tun(struct device *dev, t_tun_in_addr *s4, - t_tun_in_addr *s4dest, uint32_t bits, int netmask); + tuntap_sys_set_ipv4_tun( + struct device* dev, t_tun_in_addr* s4, t_tun_in_addr* s4dest, uint32_t bits, int netmask); #endif int - tuntap_sys_set_ipv6(struct device *, t_tun_in6_addr *, uint32_t); + tuntap_sys_set_ipv6(struct device*, t_tun_in6_addr*, uint32_t); int - tuntap_sys_set_ifname(struct device *, const char *, size_t); + tuntap_sys_set_ifname(struct device*, const char*, size_t); int - tuntap_sys_set_descr(struct device *, const char *, size_t); + tuntap_sys_set_descr(struct device*, const char*, size_t); #ifdef __cplusplus } diff --git a/jni/lokinet_config.cpp b/jni/lokinet_config.cpp index c73cdee3c..5a8651b54 100644 --- a/jni/lokinet_config.cpp +++ b/jni/lokinet_config.cpp @@ -8,7 +8,7 @@ extern "C" Java_network_loki_lokinet_LokinetConfig_Obtain(JNIEnv* env, jclass) { llarp_config* conf = llarp_default_config(); - if(conf == nullptr) + if (conf == nullptr) return nullptr; return env->NewDirectByteBuffer(conf, llarp_config_size()); } @@ -16,20 +16,19 @@ extern "C" JNIEXPORT void JNICALL Java_network_loki_lokinet_LokinetConfig_Free(JNIEnv* env, jclass, jobject buf) { - llarp_config_free(FromBuffer< llarp_config >(env, buf)); + llarp_config_free(FromBuffer(env, buf)); } JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetConfig_Load(JNIEnv* env, jobject self, - jstring fname) + Java_network_loki_lokinet_LokinetConfig_Load(JNIEnv* env, jobject self, jstring fname) { - llarp_config* conf = GetImpl< llarp_config >(env, self); - if(conf == nullptr) + llarp_config* conf = GetImpl(env, self); + if (conf == nullptr) return JNI_FALSE; - return VisitStringAsStringView< jboolean >( + return VisitStringAsStringView( env, fname, [conf](llarp::string_view val) -> jboolean { const auto filename = llarp::string_view_string(val); - if(llarp_config_read_file(conf, filename.c_str())) + if (llarp_config_read_file(conf, filename.c_str())) return JNI_TRUE; return JNI_FALSE; }); diff --git a/jni/lokinet_daemon.cpp b/jni/lokinet_daemon.cpp index 8db0324fb..8463c508a 100644 --- a/jni/lokinet_daemon.cpp +++ b/jni/lokinet_daemon.cpp @@ -6,78 +6,73 @@ extern "C" { JNIEXPORT jobject JNICALL - Java_network_loki_lokinet_LokinetDaemon_Obtain(JNIEnv *env, jclass) + Java_network_loki_lokinet_LokinetDaemon_Obtain(JNIEnv* env, jclass) { - llarp_main *ptr = llarp_main_default_init(); - if(ptr == nullptr) + llarp_main* ptr = llarp_main_default_init(); + if (ptr == nullptr) return nullptr; return env->NewDirectByteBuffer(ptr, llarp_main_size()); } JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetDaemon_Free(JNIEnv *env, jclass, jobject buf) + Java_network_loki_lokinet_LokinetDaemon_Free(JNIEnv* env, jclass, jobject buf) { - llarp_main *ptr = FromBuffer< llarp_main >(env, buf); + llarp_main* ptr = FromBuffer(env, buf); llarp_main_free(ptr); } JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_Configure(JNIEnv *env, jobject self, - jobject conf) + Java_network_loki_lokinet_LokinetDaemon_Configure(JNIEnv* env, jobject self, jobject conf) { - llarp_main *ptr = GetImpl< llarp_main >(env, self); - llarp_config *config = GetImpl< llarp_config >(env, conf); - if(ptr == nullptr || config == nullptr) + llarp_main* ptr = GetImpl(env, self); + llarp_config* config = GetImpl(env, conf); + if (ptr == nullptr || config == nullptr) return JNI_FALSE; - if(llarp_main_configure(ptr, config)) + if (llarp_main_configure(ptr, config)) return JNI_TRUE; return llarp_main_setup(ptr) == 0 ? JNI_TRUE : JNI_FALSE; } JNIEXPORT jint JNICALL - Java_network_loki_lokinet_LokinetDaemon_Mainloop(JNIEnv *env, jobject self) + Java_network_loki_lokinet_LokinetDaemon_Mainloop(JNIEnv* env, jobject self) { static llarp_main_runtime_opts opts; - llarp_main *ptr = GetImpl< llarp_main >(env, self); - if(ptr == nullptr) + llarp_main* ptr = GetImpl(env, self); + if (ptr == nullptr) return -1; return llarp_main_run(ptr, opts); } JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_IsRunning(JNIEnv *env, jobject self) + Java_network_loki_lokinet_LokinetDaemon_IsRunning(JNIEnv* env, jobject self) { - llarp_main *ptr = GetImpl< llarp_main >(env, self); - return (ptr != nullptr && llarp_main_is_running(ptr)) ? JNI_TRUE - : JNI_FALSE; + llarp_main* ptr = GetImpl(env, self); + return (ptr != nullptr && llarp_main_is_running(ptr)) ? JNI_TRUE : JNI_FALSE; } JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_Stop(JNIEnv *env, jobject self) + Java_network_loki_lokinet_LokinetDaemon_Stop(JNIEnv* env, jobject self) { - llarp_main *ptr = GetImpl< llarp_main >(env, self); - if(ptr == nullptr) + llarp_main* ptr = GetImpl(env, self); + if (ptr == nullptr) return JNI_FALSE; - if(not llarp_main_is_running(ptr)) + if (not llarp_main_is_running(ptr)) return JNI_FALSE; llarp_main_stop(ptr); return llarp_main_is_running(ptr) ? JNI_FALSE : JNI_TRUE; } JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_InjectVPN(JNIEnv *env, jobject self, - jobject vpn) + Java_network_loki_lokinet_LokinetDaemon_InjectVPN(JNIEnv* env, jobject self, jobject vpn) { - llarp_main *ptr = GetImpl< llarp_main >(env, self); - lokinet_jni_vpnio *impl = GetImpl< lokinet_jni_vpnio >(env, vpn); - if(ptr == nullptr || impl == nullptr) + llarp_main* ptr = GetImpl(env, self); + lokinet_jni_vpnio* impl = GetImpl(env, vpn); + if (ptr == nullptr || impl == nullptr) return JNI_FALSE; - if(impl->info.netmask == 0) + if (impl->info.netmask == 0) return JNI_FALSE; - if(not impl->Init(ptr)) + if (not impl->Init(ptr)) return JNI_FALSE; - return llarp_main_inject_default_vpn(ptr, &impl->io, impl->info) - ? JNI_TRUE - : JNI_FALSE; + return llarp_main_inject_default_vpn(ptr, &impl->io, impl->info) ? JNI_TRUE : JNI_FALSE; } } \ No newline at end of file diff --git a/jni/lokinet_jni_common.hpp b/jni/lokinet_jni_common.hpp index 4ddea9095..04be43226 100644 --- a/jni/lokinet_jni_common.hpp +++ b/jni/lokinet_jni_common.hpp @@ -7,21 +7,19 @@ /// visit string as native bytes /// jvm uses some unholy encoding internally so we convert it to utf-8 -template < typename T, typename V > +template static T VisitStringAsStringView(JNIEnv* env, jobject str, V visit) { const jclass stringClass = env->GetObjectClass(str); - const jmethodID getBytes = - env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B"); + const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B"); const jstring charsetName = env->NewStringUTF("UTF-8"); - const jbyteArray stringJbytes = - (jbyteArray)env->CallObjectMethod(str, getBytes, charsetName); + const jbyteArray stringJbytes = (jbyteArray)env->CallObjectMethod(str, getBytes, charsetName); env->DeleteLocalRef(charsetName); const size_t length = env->GetArrayLength(stringJbytes); - jbyte* pBytes = env->GetByteArrayElements(stringJbytes, NULL); + jbyte* pBytes = env->GetByteArrayElements(stringJbytes, NULL); T result = visit(llarp::string_view((const char*)pBytes, length)); @@ -32,54 +30,53 @@ VisitStringAsStringView(JNIEnv* env, jobject str, V visit) } /// cast jni buffer to T * -template < typename T > +template static T* FromBuffer(JNIEnv* env, jobject o) { - if(o == nullptr) + if (o == nullptr) return nullptr; - return static_cast< T* >(env->GetDirectBufferAddress(o)); + return static_cast(env->GetDirectBufferAddress(o)); } /// get T * from object member called membername -template < typename T > +template static T* FromObjectMember(JNIEnv* env, jobject self, const char* membername) { - jclass cl = env->GetObjectClass(self); - jfieldID name = env->GetFieldID(cl, membername, "Ljava/nio/Buffer;"); + jclass cl = env->GetObjectClass(self); + jfieldID name = env->GetFieldID(cl, membername, "Ljava/nio/Buffer;"); jobject buffer = env->GetObjectField(self, name); - return FromBuffer< T >(env, buffer); + return FromBuffer(env, buffer); } /// visit object string member called membername as bytes -template < typename T, typename V > +template static T -VisitObjectMemberStringAsStringView(JNIEnv* env, jobject self, - const char* membername, V v) +VisitObjectMemberStringAsStringView(JNIEnv* env, jobject self, const char* membername, V v) { - jclass cl = env->GetObjectClass(self); + jclass cl = env->GetObjectClass(self); jfieldID name = env->GetFieldID(cl, membername, "Ljava/lang/String;"); - jobject str = env->GetObjectField(self, name); - return VisitStringAsStringView< T, V >(env, str, v); + jobject str = env->GetObjectField(self, name); + return VisitStringAsStringView(env, str, v); } /// get object member int called membername -template < typename Int_t > +template Int_t GetObjectMemberAsInt(JNIEnv* env, jobject self, const char* membername) { - jclass cl = env->GetObjectClass(self); + jclass cl = env->GetObjectClass(self); jfieldID name = env->GetFieldID(cl, membername, "I"); return env->GetIntField(self, name); } /// get implementation on jni type -template < typename T > +template T* GetImpl(JNIEnv* env, jobject self) { - return FromObjectMember< T >(env, self, "impl"); + return FromObjectMember(env, self, "impl"); } #endif \ No newline at end of file diff --git a/jni/lokinet_jni_vpnio.hpp b/jni/lokinet_jni_vpnio.hpp index 30ca9f9b6..beb1b767c 100644 --- a/jni/lokinet_jni_vpnio.hpp +++ b/jni/lokinet_jni_vpnio.hpp @@ -12,22 +12,22 @@ namespace lokinet { struct VPNIO { - static VPNIO * - Get(llarp_vpn_io *vpn) + static VPNIO* + Get(llarp_vpn_io* vpn) { - return static_cast< VPNIO * >(vpn->user); + return static_cast(vpn->user); } virtual ~VPNIO() = default; llarp_vpn_io io; llarp_vpn_ifaddr_info info{{0}, {0}, 0}; - std::unique_ptr< std::promise< void > > closeWaiter; + std::unique_ptr> closeWaiter; void Closed() { - if(closeWaiter) + if (closeWaiter) closeWaiter->set_value(); } @@ -42,23 +42,23 @@ namespace lokinet VPNIO() { - io.impl = nullptr; - io.user = this; - io.closed = [](llarp_vpn_io *vpn) { VPNIO::Get(vpn)->Closed(); }; - io.injected = [](llarp_vpn_io *vpn, bool good) { - VPNIO *ptr = VPNIO::Get(vpn); - if(good) + io.impl = nullptr; + io.user = this; + io.closed = [](llarp_vpn_io* vpn) { VPNIO::Get(vpn)->Closed(); }; + io.injected = [](llarp_vpn_io* vpn, bool good) { + VPNIO* ptr = VPNIO::Get(vpn); + if (good) ptr->InjectSuccess(); else ptr->InjectFail(); }; - io.tick = [](llarp_vpn_io *vpn) { VPNIO::Get(vpn)->Tick(); }; + io.tick = [](llarp_vpn_io* vpn) { VPNIO::Get(vpn)->Tick(); }; } bool - Init(llarp_main *ptr) + Init(llarp_main* ptr) { - if(Ready()) + if (Ready()) return false; return llarp_vpn_io_init(ptr, &io); } @@ -72,44 +72,44 @@ namespace lokinet void Close() { - if(not Ready()) + if (not Ready()) return; - if(closeWaiter) + if (closeWaiter) return; - closeWaiter = std::make_unique< std::promise< void > >(); + closeWaiter = std::make_unique>(); llarp_vpn_io_close_async(&io); closeWaiter->get_future().wait(); closeWaiter.reset(); io.impl = nullptr; } - llarp_vpn_pkt_reader * + llarp_vpn_pkt_reader* Reader() { return llarp_vpn_io_packet_reader(&io); } - llarp_vpn_pkt_writer * + llarp_vpn_pkt_writer* Writer() { return llarp_vpn_io_packet_writer(&io); } ssize_t - ReadPacket(void *dst, size_t len) + ReadPacket(void* dst, size_t len) { - if(not Ready()) + if (not Ready()) return -1; - unsigned char *buf = (unsigned char *)dst; + unsigned char* buf = (unsigned char*)dst; return llarp_vpn_io_readpkt(Reader(), buf, len); } bool - WritePacket(void *pkt, size_t len) + WritePacket(void* pkt, size_t len) { - if(not Ready()) + if (not Ready()) return false; - unsigned char *buf = (unsigned char *)pkt; + unsigned char* buf = (unsigned char*)pkt; return llarp_vpn_io_writepkt(Writer(), buf, len); } diff --git a/jni/lokinet_vpn.cpp b/jni/lokinet_vpn.cpp index 6febc606c..073f47551 100644 --- a/jni/lokinet_vpn.cpp +++ b/jni/lokinet_vpn.cpp @@ -6,81 +6,78 @@ extern "C" { JNIEXPORT jint JNICALL - Java_network_loki_lokinet_LokinetVPN_PacketSize(JNIEnv *, jclass) + Java_network_loki_lokinet_LokinetVPN_PacketSize(JNIEnv*, jclass) { return llarp::net::IPPacket::MaxSize; } JNIEXPORT jobject JNICALL - Java_network_loki_lokinet_LokinetVPN_Alloc(JNIEnv *env, jclass) + Java_network_loki_lokinet_LokinetVPN_Alloc(JNIEnv* env, jclass) { - lokinet_jni_vpnio *vpn = new lokinet_jni_vpnio(); + lokinet_jni_vpnio* vpn = new lokinet_jni_vpnio(); return env->NewDirectByteBuffer(vpn, sizeof(lokinet_jni_vpnio)); } JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetVPN_Free(JNIEnv *env, jclass, jobject buf) + Java_network_loki_lokinet_LokinetVPN_Free(JNIEnv* env, jclass, jobject buf) { - lokinet_jni_vpnio *vpn = FromBuffer< lokinet_jni_vpnio >(env, buf); - if(vpn == nullptr) + lokinet_jni_vpnio* vpn = FromBuffer(env, buf); + if (vpn == nullptr) return; delete vpn; } JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetVPN_Stop(JNIEnv *env, jobject self) + Java_network_loki_lokinet_LokinetVPN_Stop(JNIEnv* env, jobject self) { - lokinet_jni_vpnio *vpn = GetImpl< lokinet_jni_vpnio >(env, self); - if(vpn) + lokinet_jni_vpnio* vpn = GetImpl(env, self); + if (vpn) { vpn->Close(); } } JNIEXPORT jint JNICALL - Java_network_loki_lokinet_LokinetVPN_ReadPkt(JNIEnv *env, jobject self, - jobject pkt) + Java_network_loki_lokinet_LokinetVPN_ReadPkt(JNIEnv* env, jobject self, jobject pkt) { - lokinet_jni_vpnio *vpn = GetImpl< lokinet_jni_vpnio >(env, self); - if(vpn == nullptr) + lokinet_jni_vpnio* vpn = GetImpl(env, self); + if (vpn == nullptr) return -1; - void *pktbuf = env->GetDirectBufferAddress(pkt); - auto pktlen = env->GetDirectBufferCapacity(pkt); - if(pktbuf == nullptr) + void* pktbuf = env->GetDirectBufferAddress(pkt); + auto pktlen = env->GetDirectBufferCapacity(pkt); + if (pktbuf == nullptr) return -1; return vpn->ReadPacket(pktbuf, pktlen); } JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetVPN_WritePkt(JNIEnv *env, jobject self, - jobject pkt) + Java_network_loki_lokinet_LokinetVPN_WritePkt(JNIEnv* env, jobject self, jobject pkt) { - lokinet_jni_vpnio *vpn = GetImpl< lokinet_jni_vpnio >(env, self); - if(vpn == nullptr) + lokinet_jni_vpnio* vpn = GetImpl(env, self); + if (vpn == nullptr) return false; - void *pktbuf = env->GetDirectBufferAddress(pkt); - auto pktlen = env->GetDirectBufferCapacity(pkt); - if(pktbuf == nullptr) + void* pktbuf = env->GetDirectBufferAddress(pkt); + auto pktlen = env->GetDirectBufferCapacity(pkt); + if (pktbuf == nullptr) return false; return vpn->WritePacket(pktbuf, pktlen); } JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetVPN_SetInfo(JNIEnv *env, jobject self, - jobject info) + Java_network_loki_lokinet_LokinetVPN_SetInfo(JNIEnv* env, jobject self, jobject info) { - lokinet_jni_vpnio *vpn = GetImpl< lokinet_jni_vpnio >(env, self); - if(vpn == nullptr) + lokinet_jni_vpnio* vpn = GetImpl(env, self); + if (vpn == nullptr) return; - VisitObjectMemberStringAsStringView< bool >( + VisitObjectMemberStringAsStringView( env, info, "ifaddr", [vpn](llarp::string_view val) -> bool { vpn->SetIfAddr(val); return true; }); - VisitObjectMemberStringAsStringView< bool >( + VisitObjectMemberStringAsStringView( env, info, "ifname", [vpn](llarp::string_view val) -> bool { vpn->SetIfName(val); return true; }); - vpn->info.netmask = GetObjectMemberAsInt< uint8_t >(env, info, "netmask"); + vpn->info.netmask = GetObjectMemberAsInt(env, info, "netmask"); } } \ No newline at end of file diff --git a/jni/network_loki_lokinet_LokinetConfig.h b/jni/network_loki_lokinet_LokinetConfig.h index f39b87542..7496155d3 100644 --- a/jni/network_loki_lokinet_LokinetConfig.h +++ b/jni/network_loki_lokinet_LokinetConfig.h @@ -14,7 +14,7 @@ extern "C" * Signature: ()Ljava/nio/Buffer; */ JNIEXPORT jobject JNICALL - Java_network_loki_lokinet_LokinetConfig_Obtain(JNIEnv *, jclass); + Java_network_loki_lokinet_LokinetConfig_Obtain(JNIEnv*, jclass); /* * Class: network_loki_lokinet_LokinetConfig @@ -22,7 +22,7 @@ extern "C" * Signature: (Ljava/nio/Buffer;)V */ JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetConfig_Free(JNIEnv *, jclass, jobject); + Java_network_loki_lokinet_LokinetConfig_Free(JNIEnv*, jclass, jobject); /* * Class: network_loki_lokinet_LokinetConfig @@ -30,7 +30,7 @@ extern "C" * Signature: (Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetConfig_Load(JNIEnv *, jobject, jstring); + Java_network_loki_lokinet_LokinetConfig_Load(JNIEnv*, jobject, jstring); #ifdef __cplusplus } diff --git a/jni/network_loki_lokinet_LokinetDaemon.h b/jni/network_loki_lokinet_LokinetDaemon.h index 400807bb6..3b23a9f70 100644 --- a/jni/network_loki_lokinet_LokinetDaemon.h +++ b/jni/network_loki_lokinet_LokinetDaemon.h @@ -14,7 +14,7 @@ extern "C" * Signature: ()Ljava/nio/Buffer; */ JNIEXPORT jobject JNICALL - Java_network_loki_lokinet_LokinetDaemon_Obtain(JNIEnv *, jclass); + Java_network_loki_lokinet_LokinetDaemon_Obtain(JNIEnv*, jclass); /* * Class: network_loki_lokinet_LokinetDaemon @@ -22,7 +22,7 @@ extern "C" * Signature: (Ljava/nio/Buffer;)V */ JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetDaemon_Free(JNIEnv *, jclass, jobject); + Java_network_loki_lokinet_LokinetDaemon_Free(JNIEnv*, jclass, jobject); /* * Class: network_loki_lokinet_LokinetDaemon @@ -30,7 +30,7 @@ extern "C" * Signature: (Lnetwork/loki/lokinet/LokinetConfig;)Z */ JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_Configure(JNIEnv *, jobject, jobject); + Java_network_loki_lokinet_LokinetDaemon_Configure(JNIEnv*, jobject, jobject); /* * Class: network_loki_lokinet_LokinetDaemon @@ -38,7 +38,7 @@ extern "C" * Signature: ()I */ JNIEXPORT jint JNICALL - Java_network_loki_lokinet_LokinetDaemon_Mainloop(JNIEnv *, jobject); + Java_network_loki_lokinet_LokinetDaemon_Mainloop(JNIEnv*, jobject); /* * Class: network_loki_lokinet_LokinetDaemon @@ -46,7 +46,7 @@ extern "C" * Signature: ()Z */ JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_IsRunning(JNIEnv *, jobject); + Java_network_loki_lokinet_LokinetDaemon_IsRunning(JNIEnv*, jobject); /* * Class: network_loki_lokinet_LokinetDaemon @@ -54,7 +54,7 @@ extern "C" * Signature: ()Z */ JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_Stop(JNIEnv *, jobject); + Java_network_loki_lokinet_LokinetDaemon_Stop(JNIEnv*, jobject); /* * Class: network_loki_lokinet_LokinetDaemon @@ -62,7 +62,7 @@ extern "C" * Signature: (Lnetwork/loki/lokinet/LokinetVPN;)Z */ JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetDaemon_InjectVPN(JNIEnv *, jobject, jobject); + Java_network_loki_lokinet_LokinetDaemon_InjectVPN(JNIEnv*, jobject, jobject); #ifdef __cplusplus } diff --git a/jni/network_loki_lokinet_LokinetVPN.h b/jni/network_loki_lokinet_LokinetVPN.h index 0aca1654f..a3a56a8e4 100644 --- a/jni/network_loki_lokinet_LokinetVPN.h +++ b/jni/network_loki_lokinet_LokinetVPN.h @@ -14,7 +14,7 @@ extern "C" * Signature: ()I */ JNIEXPORT jint JNICALL - Java_network_loki_lokinet_LokinetVPN_PacketSize(JNIEnv *, jclass); + Java_network_loki_lokinet_LokinetVPN_PacketSize(JNIEnv*, jclass); /* * Class: network_loki_lokinet_LokinetVPN @@ -22,7 +22,7 @@ extern "C" * Signature: ()Ljava/nio/Buffer; */ JNIEXPORT jobject JNICALL - Java_network_loki_lokinet_LokinetVPN_Alloc(JNIEnv *, jclass); + Java_network_loki_lokinet_LokinetVPN_Alloc(JNIEnv*, jclass); /* * Class: network_loki_lokinet_LokinetVPN @@ -30,7 +30,7 @@ extern "C" * Signature: (Ljava/nio/Buffer;)V */ JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetVPN_Free(JNIEnv *, jclass, jobject); + Java_network_loki_lokinet_LokinetVPN_Free(JNIEnv*, jclass, jobject); /* * Class: network_loki_lokinet_LokinetVPN @@ -38,7 +38,7 @@ extern "C" * Signature: ()V */ JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetVPN_Stop(JNIEnv *, jobject); + Java_network_loki_lokinet_LokinetVPN_Stop(JNIEnv*, jobject); /* * Class: network_loki_lokinet_LokinetVPN @@ -46,7 +46,7 @@ extern "C" * Signature: (Ljava/nio/ByteBuffer;)I */ JNIEXPORT jint JNICALL - Java_network_loki_lokinet_LokinetVPN_ReadPkt(JNIEnv *, jobject, jobject); + Java_network_loki_lokinet_LokinetVPN_ReadPkt(JNIEnv*, jobject, jobject); /* * Class: network_loki_lokinet_LokinetVPN @@ -54,7 +54,7 @@ extern "C" * Signature: (Ljava/nio/ByteBuffer;)Z */ JNIEXPORT jboolean JNICALL - Java_network_loki_lokinet_LokinetVPN_WritePkt(JNIEnv *, jobject, jobject); + Java_network_loki_lokinet_LokinetVPN_WritePkt(JNIEnv*, jobject, jobject); /* * Class: network_loki_lokinet_LokinetVPN @@ -62,7 +62,7 @@ extern "C" * Signature: (Lnetwork/loki/lokinet/LokinetVPN/VPNInfo;)V */ JNIEXPORT void JNICALL - Java_network_loki_lokinet_LokinetVPN_SetInfo(JNIEnv *, jobject, jobject); + Java_network_loki_lokinet_LokinetVPN_SetInfo(JNIEnv*, jobject, jobject); #ifdef __cplusplus } #endif diff --git a/jni/network_loki_lokinet_Lokinet_JNI.h b/jni/network_loki_lokinet_Lokinet_JNI.h index 94b8d964b..c94eed445 100644 --- a/jni/network_loki_lokinet_Lokinet_JNI.h +++ b/jni/network_loki_lokinet_Lokinet_JNI.h @@ -14,7 +14,7 @@ extern "C" * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_getABICompiledWith(JNIEnv *, jclass); + Java_network_loki_lokinet_Lokinet_1JNI_getABICompiledWith(JNIEnv*, jclass); /* * Class: network_loki_lokinet_Lokinet_JNI @@ -22,14 +22,13 @@ extern "C" * Signature: (Ljava/lang/String;)Ljava/lang/String; */ JNIEXPORT jstring JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_startLokinet(JNIEnv *, jclass, - jstring); + Java_network_loki_lokinet_Lokinet_1JNI_startLokinet(JNIEnv*, jclass, jstring); JNIEXPORT jstring JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_getIfAddr(JNIEnv *, jclass); + Java_network_loki_lokinet_Lokinet_1JNI_getIfAddr(JNIEnv*, jclass); JNIEXPORT jint JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_getIfRange(JNIEnv *, jclass); + Java_network_loki_lokinet_Lokinet_1JNI_getIfRange(JNIEnv*, jclass); /* * Class: network_loki_lokinet_Lokinet_JNI @@ -37,11 +36,10 @@ extern "C" * Signature: ()V */ JNIEXPORT void JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_stopLokinet(JNIEnv *, jclass); + Java_network_loki_lokinet_Lokinet_1JNI_stopLokinet(JNIEnv*, jclass); JNIEXPORT void JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_setVPNFileDescriptor(JNIEnv *, jclass, - jint, jint); + Java_network_loki_lokinet_Lokinet_1JNI_setVPNFileDescriptor(JNIEnv*, jclass, jint, jint); /* * Class: network_loki_lokinet_Lokinet_JNI @@ -49,8 +47,7 @@ extern "C" * Signature: (Z)V */ JNIEXPORT void JNICALL - Java_network_loki_lokinet_Lokinet_1JNI_onNetworkStateChanged(JNIEnv *, jclass, - jboolean); + Java_network_loki_lokinet_Lokinet_1JNI_onNetworkStateChanged(JNIEnv*, jclass, jboolean); #ifdef __cplusplus } diff --git a/libabyss/include/abyss/client.hpp b/libabyss/include/abyss/client.hpp index e1b97a349..103f921b3 100644 --- a/libabyss/include/abyss/client.hpp +++ b/libabyss/include/abyss/client.hpp @@ -19,10 +19,10 @@ namespace abyss namespace http { using RPC_Method_t = std::string; - using RPC_Params = nlohmann::json; + using RPC_Params = nlohmann::json; using RPC_Response = nlohmann::json; - using Headers_t = std::unordered_multimap< std::string, std::string >; - using Response = RequestHeader; + using Headers_t = std::unordered_multimap; + using Response = RequestHeader; struct ConnImpl; /// jsonrpc response handler for client @@ -60,7 +60,7 @@ namespace abyss /// jsonrpc client struct JSONRPC { - using HandlerFactory = std::function< IRPCClientHandler*(ConnImpl*) >; + using HandlerFactory = std::function; JSONRPC(); ~JSONRPC(); @@ -73,8 +73,7 @@ namespace abyss /// must be called after RunAsync returns true /// queue a call for rpc void - QueueRPC(RPC_Method_t method, RPC_Params params, - HandlerFactory createHandler); + QueueRPC(RPC_Method_t method, RPC_Params params, HandlerFactory createHandler); /// drop all pending calls on the floor void @@ -99,9 +98,7 @@ namespace abyss struct Call { Call(RPC_Method_t&& m, RPC_Params&& p, HandlerFactory&& f) - : method(std::move(m)) - , params(std::move(p)) - , createHandler(std::move(f)) + : method(std::move(m)), params(std::move(p)), createHandler(std::move(f)) { } RPC_Method_t method; @@ -118,11 +115,11 @@ namespace abyss static void OnTick(llarp_tcp_connecter* connect); - std::atomic< bool > m_Run; + std::atomic m_Run; llarp_tcp_connecter m_connect; llarp_ev_loop_ptr m_Loop; - std::deque< Call > m_PendingCalls; - std::list< std::unique_ptr< IRPCClientHandler > > m_Conns; + std::deque m_PendingCalls; + std::list> m_Conns; }; } // namespace http } // namespace abyss diff --git a/libabyss/include/abyss/http.hpp b/libabyss/include/abyss/http.hpp index fe386c3d4..9313f07a8 100644 --- a/libabyss/include/abyss/http.hpp +++ b/libabyss/include/abyss/http.hpp @@ -12,7 +12,7 @@ namespace abyss { struct RequestHeader { - using Headers_t = std::unordered_multimap< std::string, std::string >; + using Headers_t = std::unordered_multimap; Headers_t Headers; std::string Method; std::string Path; diff --git a/libabyss/include/abyss/md5.hpp b/libabyss/include/abyss/md5.hpp index d3c741e2c..6f6dc98bf 100644 --- a/libabyss/include/abyss/md5.hpp +++ b/libabyss/include/abyss/md5.hpp @@ -21,18 +21,17 @@ struct MD5 static std::string SumHex(const std::string& str) { - std::array< uint8_t, 16 > digest; + std::array digest; auto dist = str.size(); MD5 m; m.Update((const unsigned char*)str.c_str(), dist); m.Final(digest.data()); std::string hex; - std::for_each(digest.begin(), digest.end(), - [&hex](const unsigned char& ch) { - char tmpbuf[4] = {0}; - std::snprintf(tmpbuf, sizeof(tmpbuf), "%.2x", ch); - hex += std::string(tmpbuf); - }); + std::for_each(digest.begin(), digest.end(), [&hex](const unsigned char& ch) { + char tmpbuf[4] = {0}; + std::snprintf(tmpbuf, sizeof(tmpbuf), "%.2x", ch); + hex += std::string(tmpbuf); + }); return hex; } }; diff --git a/libabyss/include/abyss/server.hpp b/libabyss/include/abyss/server.hpp index 2c3192610..158d91053 100644 --- a/libabyss/include/abyss/server.hpp +++ b/libabyss/include/abyss/server.hpp @@ -24,7 +24,7 @@ namespace abyss struct IRPCHandler { using Method_t = std::string; - using Params = nlohmann::json; + using Params = nlohmann::json; using Response = nlohmann::json; IRPCHandler(ConnImpl* impl); @@ -51,8 +51,8 @@ namespace abyss virtual ~BaseReqHandler(); bool - ServeAsync(llarp_ev_loop_ptr loop, std::shared_ptr< llarp::Logic > logic, - const sockaddr* bindaddr); + ServeAsync( + llarp_ev_loop_ptr loop, std::shared_ptr logic, const sockaddr* bindaddr); void RemoveConn(IRPCHandler* handler); @@ -82,9 +82,9 @@ namespace abyss OnAccept(struct llarp_tcp_acceptor*, struct llarp_tcp_conn*); llarp_ev_loop_ptr m_loop; - std::shared_ptr< llarp::Logic > m_Logic; + std::shared_ptr m_Logic; llarp_tcp_acceptor m_acceptor; - std::list< std::unique_ptr< IRPCHandler > > m_Conns; + std::list> m_Conns; llarp_time_t m_ReqTimeout; }; } // namespace httpd diff --git a/libabyss/main.cpp b/libabyss/main.cpp index cae073ce2..ede2978a0 100644 --- a/libabyss/main.cpp +++ b/libabyss/main.cpp @@ -13,7 +13,7 @@ struct DemoHandler : public abyss::httpd::IRPCHandler { } - nonstd::optional< Response > + nonstd::optional HandleJSONRPC(Method_t method, const Params& /*params*/) override { llarp::LogInfo("method: ", method); @@ -23,14 +23,14 @@ struct DemoHandler : public abyss::httpd::IRPCHandler struct DemoCall : public abyss::http::IRPCClientHandler { - std::function< void(void) > m_Callback; - std::shared_ptr< llarp::Logic > m_Logic; - - DemoCall(abyss::http::ConnImpl* impl, std::shared_ptr< llarp::Logic > logic, - std::function< void(void) > callback) - : abyss::http::IRPCClientHandler(impl) - , m_Callback(callback) - , m_Logic(logic) + std::function m_Callback; + std::shared_ptr m_Logic; + + DemoCall( + abyss::http::ConnImpl* impl, + std::shared_ptr logic, + std::function callback) + : abyss::http::IRPCClientHandler(impl), m_Callback(callback), m_Logic(logic) { llarp::LogInfo("new call"); } @@ -57,9 +57,9 @@ struct DemoCall : public abyss::http::IRPCClientHandler struct DemoClient : public abyss::http::JSONRPC { llarp_ev_loop_ptr m_Loop; - std::shared_ptr< llarp::Logic > m_Logic; + std::shared_ptr m_Logic; - DemoClient(llarp_ev_loop_ptr l, std::shared_ptr< llarp::Logic > logic) + DemoClient(llarp_ev_loop_ptr l, std::shared_ptr logic) : abyss::http::JSONRPC(), m_Loop(std::move(l)), m_Logic(logic) { } @@ -73,8 +73,10 @@ struct DemoClient : public abyss::http::JSONRPC void DoDemoRequest() { - QueueRPC("test", nlohmann::json::object(), - std::bind(&DemoClient::NewConn, this, std::placeholders::_1)); + QueueRPC( + "test", + nlohmann::json::object(), + std::bind(&DemoClient::NewConn, this, std::placeholders::_1)); Flush(); } }; @@ -104,7 +106,7 @@ main(ABSL_ATTRIBUTE_UNUSED int argc, ABSL_ATTRIBUTE_UNUSED char* argv[]) WSADATA wsockd; int err; err = ::WSAStartup(MAKEWORD(2, 2), &wsockd); - if(err) + if (err) { perror("Failed to start Windows Sockets"); return err; @@ -118,18 +120,18 @@ main(ABSL_ATTRIBUTE_UNUSED int argc, ABSL_ATTRIBUTE_UNUSED char* argv[]) // Now that libuv is the single non-Windows event loop impl, we can // go back to using the normal function llarp_ev_loop_ptr loop = llarp_make_ev_loop(); - auto logic = std::make_shared< llarp::Logic >(); + auto logic = std::make_shared(); sockaddr_in addr; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - addr.sin_port = htons(1222); - addr.sin_family = AF_INET; + addr.sin_port = htons(1222); + addr.sin_family = AF_INET; DemoServer serv; DemoClient client(loop, logic); llarp::Addr a(addr); - while(true) + while (true) { llarp::LogInfo("bind to ", a); - if(serv.ServeAsync(loop, logic, a)) + if (serv.ServeAsync(loop, logic, a)) { client.RunAsync(loop, a.ToString()); client.DoDemoRequest(); diff --git a/libabyss/src/client.cpp b/libabyss/src/client.cpp index a5e712ca5..c4ae340ee 100644 --- a/libabyss/src/client.cpp +++ b/libabyss/src/client.cpp @@ -17,7 +17,7 @@ namespace abyss nlohmann::json m_RequestBody; Headers_t m_SendHeaders; IRPCClientHandler* handler; - std::unique_ptr< json::IParser > m_BodyParser; + std::unique_ptr m_BodyParser; nlohmann::json m_Response; uint16_t m_AuthTries; bool m_ShouldAuth; @@ -32,9 +32,12 @@ namespace abyss State state; - ConnImpl(llarp_tcp_conn* conn, JSONRPC* parent, - const RPC_Method_t& method, const RPC_Params& params, - JSONRPC::HandlerFactory factory) + ConnImpl( + llarp_tcp_conn* conn, + JSONRPC* parent, + const RPC_Method_t& method, + const RPC_Params& params, + JSONRPC::HandlerFactory factory) : m_Conn(conn) , m_Parent(parent) , m_RequestBody(nlohmann::json::object()) @@ -43,17 +46,17 @@ namespace abyss , m_ShouldAuth(false) , state(eInitial) { - conn->user = this; + conn->user = this; conn->closed = &ConnImpl::OnClosed; - conn->read = &ConnImpl::OnRead; - conn->tick = &ConnImpl::OnTick; + conn->read = &ConnImpl::OnRead; + conn->tick = &ConnImpl::OnTick; handler = factory(this); m_RequestBody["jsonrpc"] = "2.0"; - llarp::AlignedBuffer< 8 > p; + llarp::AlignedBuffer<8> p; p.Randomize(); - m_RequestBody["id"] = p.ToHex(); + m_RequestBody["id"] = p.ToHex(); m_RequestBody["method"] = method; m_RequestBody["params"] = params; } @@ -62,15 +65,15 @@ namespace abyss OnClosed(llarp_tcp_conn* conn) { llarp::LogDebug("connection closed"); - ConnImpl* self = static_cast< ConnImpl* >(conn->user); - self->state = eCloseMe; + ConnImpl* self = static_cast(conn->user); + self->state = eCloseMe; } static void OnRead(llarp_tcp_conn* conn, const llarp_buffer_t& buf) { - ConnImpl* self = static_cast< ConnImpl* >(conn->user); - if(!self->ProcessRead((const char*)buf.base, buf.sz)) + ConnImpl* self = static_cast(conn->user); + if (!self->ProcessRead((const char*)buf.base, buf.sz)) { self->CloseError("on read failed"); } @@ -85,13 +88,13 @@ namespace abyss ProcessStatusLine(string_view line) { auto idx = line.find_first_of(' '); - if(idx == string_view::npos) + if (idx == string_view::npos) return false; string_view codePart = line.substr(1 + idx); - idx = codePart.find_first_of(' '); + idx = codePart.find_first_of(' '); - if(idx == string_view::npos) + if (idx == string_view::npos) return false; return HandleStatusCode(codePart.substr(0, idx)); } @@ -108,9 +111,9 @@ namespace abyss bool HandleStatusCode(string_view code) { - if(code == string_view("200")) + if (code == string_view("200")) return true; - if(code == string_view("401")) + if (code == string_view("401")) { m_ShouldAuth = true; return true; @@ -122,21 +125,21 @@ namespace abyss RetryWithAuth(const std::string& auth) { m_ShouldAuth = false; - auto idx = auth.find_first_of(' '); - if(idx == std::string::npos) + auto idx = auth.find_first_of(' '); + if (idx == std::string::npos) return false; std::istringstream info(auth.substr(1 + idx)); - std::unordered_map< std::string, std::string > opts; + std::unordered_map opts; std::string part; - while(std::getline(info, part, ',')) + while (std::getline(info, part, ',')) { idx = part.find_first_of('='); - if(idx == std::string::npos) + if (idx == std::string::npos) return false; std::string k = part.substr(0, idx); std::string val; ++idx; - while(idx < part.size()) + while (idx < part.size()) { const char ch = part.at(idx); val += ch; @@ -146,48 +149,43 @@ namespace abyss } auto itr = opts.find("algorithm"); - if(itr != opts.end() && itr->second == "MD5-sess") + if (itr != opts.end() && itr->second == "MD5-sess") return false; std::stringstream authgen; auto strip = [&opts](const std::string& name) -> std::string { std::string val; - std::for_each(opts[name].begin(), opts[name].end(), - [&val](const char& ch) { - if(ch != '"') - val += ch; - }); + std::for_each(opts[name].begin(), opts[name].end(), [&val](const char& ch) { + if (ch != '"') + val += ch; + }); return val; }; - const auto realm = strip("realm"); - const auto nonce = strip("nonce"); - const auto qop = strip("qop"); + const auto realm = strip("realm"); + const auto nonce = strip("nonce"); + const auto qop = strip("qop"); std::string nonceCount = "0000000" + std::to_string(m_AuthTries); - std::string str = - m_Parent->username + ":" + realm + ":" + m_Parent->password; + std::string str = m_Parent->username + ":" + realm + ":" + m_Parent->password; std::string h1 = MD5::SumHex(str); - str = "POST:/json_rpc"; + str = "POST:/json_rpc"; std::string h2 = MD5::SumHex(str); - llarp::AlignedBuffer< 8 > n; + llarp::AlignedBuffer<8> n; n.Randomize(); std::string cnonce = n.ToHex(); - str = h1 + ":" + nonce + ":" + nonceCount + ":" + cnonce + ":" + qop - + ":" + h2; + str = h1 + ":" + nonce + ":" + nonceCount + ":" + cnonce + ":" + qop + ":" + h2; auto responseH = MD5::SumHex(str); - authgen << "Digest username=\"" << m_Parent->username + "\", realm=\"" - << realm - << "\", uri=\"/json_rpc\", algorithm=MD5, qop=auth, nonce=\"" - << nonce << "\", response=\"" << responseH - << "\", nc=" << nonceCount << ", cnonce=\"" << cnonce << "\""; - for(const auto& opt : opts) + authgen << "Digest username=\"" << m_Parent->username + "\", realm=\"" << realm + << "\", uri=\"/json_rpc\", algorithm=MD5, qop=auth, nonce=\"" << nonce + << "\", response=\"" << responseH << "\", nc=" << nonceCount << ", cnonce=\"" + << cnonce << "\""; + for (const auto& opt : opts) { - if(opt.first == "algorithm" || opt.first == "realm" - || opt.first == "qop" || opt.first == "nonce" - || opt.first == "stale") + if (opt.first == "algorithm" || opt.first == "realm" || opt.first == "qop" + || opt.first == "nonce" || opt.first == "stale") continue; authgen << ", " << opt.first << "=" << opt.second; } @@ -202,14 +200,14 @@ namespace abyss ProcessBody(const char* buf, size_t sz) { // we got 401 ? - if(m_ShouldAuth && m_AuthTries < 9) + if (m_ShouldAuth && m_AuthTries < 9) { m_AuthTries++; auto range = Header.Headers.equal_range("www-authenticate"); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { - if(RetryWithAuth(itr->second)) + if (RetryWithAuth(itr->second)) return true; else ++itr; @@ -217,19 +215,19 @@ namespace abyss return false; } // init parser - if(m_BodyParser == nullptr) + if (m_BodyParser == nullptr) { size_t contentSize = 0; - auto itr = Header.Headers.find("content-length"); + auto itr = Header.Headers.find("content-length"); // no content-length header - if(itr == Header.Headers.end()) + if (itr == Header.Headers.end()) return false; contentSize = std::stoul(itr->second); m_BodyParser.reset(json::MakeParser(contentSize)); } - if(m_BodyParser && m_BodyParser->FeedData(buf, sz)) + if (m_BodyParser && m_BodyParser->FeedData(buf, sz)) { - switch(m_BodyParser->Parse(m_Response)) + switch (m_BodyParser->Parse(m_Response)) { case json::IParser::eNeedData: return true; @@ -251,30 +249,30 @@ namespace abyss bool ProcessRead(const char* buf, size_t sz) { - if(state == eInitial) + if (state == eInitial) return true; - if(!sz) + if (!sz) return true; bool done = false; - while(state < eReadResponseBody) + while (state < eReadResponseBody) { const char* end = strstr(buf, "\r\n"); - if(!end) + if (!end) return false; string_view line(buf, end - buf); - switch(state) + switch (state) { case eReadStatusLine: - if(!ProcessStatusLine(line)) + if (!ProcessStatusLine(line)) return false; sz -= line.size() + (2 * sizeof(char)); state = eReadResponseHeader; break; case eReadResponseHeader: - if(!ProcessHeaderLine(line, done)) + if (!ProcessHeaderLine(line, done)) return false; sz -= line.size() + (2 * sizeof(char)); - if(done) + if (done) state = eReadResponseBody; break; default: @@ -283,7 +281,7 @@ namespace abyss buf = end + (2 * sizeof(char)); end = strstr(buf, "\r\n"); } - if(state == eReadResponseBody) + if (state == eReadResponseBody) return ProcessBody(buf, sz); return state == eCloseMe; } @@ -298,7 +296,7 @@ namespace abyss CloseError(const char* msg) { LogError("CloseError: ", msg); - if(handler) + if (handler) handler->HandleError(); handler = nullptr; Close(); @@ -307,7 +305,7 @@ namespace abyss void Close() { - if(m_Conn) + if (m_Conn) llarp_tcp_conn_close(m_Conn); m_Conn = nullptr; } @@ -327,13 +325,12 @@ namespace abyss m_SendHeaders.emplace("Accept", "application/json"); std::stringstream request; request << "POST /json_rpc HTTP/1.1\r\n"; - for(const auto& item : m_SendHeaders) + for (const auto& item : m_SendHeaders) request << item.first << ": " << item.second << "\r\n"; request << "\r\n" << body; std::string buf = request.str(); - if(!llarp_tcp_conn_async_write(m_Conn, - llarp_buffer_t(buf.c_str(), buf.size()))) + if (!llarp_tcp_conn_async_write(m_Conn, llarp_buffer_t(buf.c_str(), buf.size()))) { CloseError("failed to write request"); return; @@ -348,9 +345,9 @@ namespace abyss { /// close idle connections auto itr = m_Conns.begin(); - while(itr != m_Conns.end()) + while (itr != m_Conns.end()) { - if((*itr)->ShouldClose()) + if ((*itr)->ShouldClose()) { (*itr)->Close(); itr = m_Conns.erase(itr); @@ -361,7 +358,7 @@ namespace abyss // open at most 10 connections size_t numCalls = std::min(m_PendingCalls.size(), (size_t)10UL); llarp::LogDebug("tick connect to rpc ", numCalls, " times"); - while(numCalls--) + while (numCalls--) { llarp_tcp_async_try_connect(m_Loop.get(), &m_connect); } @@ -380,13 +377,13 @@ namespace abyss void IRPCClientHandler::Close() const { - if(m_Impl) + if (m_Impl) m_Impl->Close(); } IRPCClientHandler::~IRPCClientHandler() { - if(m_Impl) + if (m_Impl) delete m_Impl; } @@ -400,12 +397,10 @@ namespace abyss } void - JSONRPC::QueueRPC(RPC_Method_t method, RPC_Params params, - HandlerFactory createHandler) + JSONRPC::QueueRPC(RPC_Method_t method, RPC_Params params, HandlerFactory createHandler) { - if(m_Run) - m_PendingCalls.emplace_back(std::move(method), std::move(params), - std::move(createHandler)); + if (m_Run) + m_PendingCalls.emplace_back(std::move(method), std::move(params), std::move(createHandler)); } bool @@ -414,17 +409,17 @@ namespace abyss strncpy(m_connect.remote, remote.c_str(), sizeof(m_connect.remote) - 1); // TODO: ipv6 m_connect.connected = &JSONRPC::OnConnected; - m_connect.error = &JSONRPC::OnConnectFail; - m_connect.user = this; - m_connect.af = AF_INET; - m_Loop = std::move(loop); + m_connect.error = &JSONRPC::OnConnectFail; + m_connect.user = this; + m_connect.af = AF_INET; + m_Loop = std::move(loop); return true; } void JSONRPC::OnConnectFail(llarp_tcp_connecter* tcp) { - JSONRPC* self = static_cast< JSONRPC* >(tcp->user); + JSONRPC* self = static_cast(tcp->user); llarp::LogError("failed to connect to RPC, dropped all pending calls"); self->DropAllCalls(); } @@ -432,7 +427,7 @@ namespace abyss void JSONRPC::OnConnected(llarp_tcp_connecter* tcp, llarp_tcp_conn* conn) { - JSONRPC* self = static_cast< JSONRPC* >(tcp->user); + JSONRPC* self = static_cast(tcp->user); llarp::LogDebug("connected to RPC"); self->Connected(conn); } @@ -440,14 +435,14 @@ namespace abyss void JSONRPC::Connected(llarp_tcp_conn* conn) { - if(!m_Run) + if (!m_Run) { llarp_tcp_conn_close(conn); return; } - auto& front = m_PendingCalls.front(); - ConnImpl* connimpl = new ConnImpl(conn, this, front.method, front.params, - front.createHandler); + auto& front = m_PendingCalls.front(); + ConnImpl* connimpl = + new ConnImpl(conn, this, front.method, front.params, front.createHandler); m_PendingCalls.pop_front(); m_Conns.emplace_back(connimpl->handler); connimpl->SendRequest(); @@ -463,9 +458,9 @@ namespace abyss void JSONRPC::DropAllCalls() { - while(m_PendingCalls.size()) + while (m_PendingCalls.size()) { - auto& front = m_PendingCalls.front(); + auto& front = m_PendingCalls.front(); IRPCClientHandler* h = front.createHandler(nullptr); h->HandleError(); delete h; diff --git a/libabyss/src/http.cpp b/libabyss/src/http.cpp index 99150ba8c..d58bce2fb 100644 --- a/libabyss/src/http.cpp +++ b/libabyss/src/http.cpp @@ -7,26 +7,26 @@ namespace abyss bool HeaderReader::ProcessHeaderLine(string_view line, bool& done) { - if(line.size() == 0) + if (line.size() == 0) { done = true; return true; } auto idx = line.find_first_of(':'); - if(idx == string_view::npos) + if (idx == string_view::npos) return false; string_view header = line.substr(0, idx); - string_view val = line.substr(1 + idx); + string_view val = line.substr(1 + idx); // to lowercase std::string lowerHeader; lowerHeader.reserve(header.size()); auto itr = header.begin(); - while(itr != header.end()) + while (itr != header.end()) { lowerHeader += std::tolower(*itr); ++itr; } - if(ShouldProcessHeader(lowerHeader)) + if (ShouldProcessHeader(lowerHeader)) { val = val.substr(val.find_first_not_of(' ')); // llarp::str() here for gcc 5 compat diff --git a/libabyss/src/md5.cpp b/libabyss/src/md5.cpp index 775b91346..5106760ff 100644 --- a/libabyss/src/md5.cpp +++ b/libabyss/src/md5.cpp @@ -4,15 +4,13 @@ using UINT4 = uint32_t; /* forward declaration */ void -Transform(uint32_t *buf, uint32_t *in); +Transform(uint32_t* buf, uint32_t* in); static unsigned char PADDING[64] = { - 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; /* F, G and H are basic MD5 functions: selection, majority, parity */ #define F(x, y, z) (((x) & (y)) | ((~x) & (z))) @@ -63,7 +61,7 @@ MD5::MD5() } void -MD5::Update(const unsigned char *inBuf, uint32_t inLen) +MD5::Update(const unsigned char* inBuf, uint32_t inLen) { UINT4 input[16]; int mdi; @@ -72,20 +70,20 @@ MD5::Update(const unsigned char *inBuf, uint32_t inLen) mdi = (int)((this->i[0] >> 3) & 0x3F); /* update number of bits */ - if((this->i[0] + ((UINT4)inLen << 3)) < this->i[0]) + if ((this->i[0] + ((UINT4)inLen << 3)) < this->i[0]) this->i[1]++; this->i[0] += ((UINT4)inLen << 3); this->i[1] += ((UINT4)inLen >> 29); - while(inLen--) + while (inLen--) { /* add new character to buffer, increment mdi */ in[mdi++] = *inBuf++; /* transform if necessary */ - if(mdi == 0x40) + if (mdi == 0x40) { - for(unsigned int j = 0, jj = 0; j < 16; j++, jj += 4) + for (unsigned int j = 0, jj = 0; j < 16; j++, jj += 4) { input[j] = (((UINT4)in[jj + 3]) << 24) | (((UINT4)in[jj + 2]) << 16) | (((UINT4)in[jj + 1]) << 8) | ((UINT4)in[jj]); @@ -97,7 +95,7 @@ MD5::Update(const unsigned char *inBuf, uint32_t inLen) } void -MD5::Final(uint8_t *digest) +MD5::Final(uint8_t* digest) { UINT4 input[16]; int mdi; @@ -115,7 +113,7 @@ MD5::Final(uint8_t *digest) this->Update(PADDING, padLen); /* append length in bits and transform */ - for(unsigned int j = 0, jj = 0; j < 14; j++, jj += 4) + for (unsigned int j = 0, jj = 0; j < 14; j++, jj += 4) { input[j] = (((UINT4)in[jj + 3]) << 24) | (((UINT4)in[jj + 2]) << 16) | (((UINT4)in[jj + 1]) << 8) | ((UINT4)in[jj]); @@ -123,9 +121,9 @@ MD5::Final(uint8_t *digest) Transform(this->buf, input); /* store buffer in digest */ - for(unsigned int j = 0, jj = 0; j < 4; j++, jj += 4) + for (unsigned int j = 0, jj = 0; j < 4; j++, jj += 4) { - digest[jj] = (unsigned char)(this->buf[j] & 0xFF); + digest[jj] = (unsigned char)(this->buf[j] & 0xFF); digest[jj + 1] = (unsigned char)((this->buf[j] >> 8) & 0xFF); digest[jj + 2] = (unsigned char)((this->buf[j] >> 16) & 0xFF); digest[jj + 3] = (unsigned char)((this->buf[j] >> 24) & 0xFF); @@ -135,7 +133,7 @@ MD5::Final(uint8_t *digest) /* Basic MD5 step. Transform buf based on in. */ void -Transform(UINT4 *buf, UINT4 *in) +Transform(UINT4* buf, UINT4* in) { UINT4 a = buf[0], b = buf[1], c = buf[2], d = buf[3]; diff --git a/libabyss/src/server.cpp b/libabyss/src/server.cpp index d7e4bc5c3..3335b1010 100644 --- a/libabyss/src/server.cpp +++ b/libabyss/src/server.cpp @@ -23,7 +23,7 @@ namespace abyss llarp_time_t m_LastActive; llarp_time_t m_ReadTimeout; bool m_Bad; - std::unique_ptr< json::IParser > m_BodyParser; + std::unique_ptr m_BodyParser; nlohmann::json m_Request; enum HTTPState @@ -42,16 +42,16 @@ namespace abyss ConnImpl(BaseReqHandler* p, llarp_tcp_conn* c, llarp_time_t readtimeout) : _conn(c), _parent(p) { - handler = nullptr; - m_LastActive = p->now(); + handler = nullptr; + m_LastActive = p->now(); m_ReadTimeout = readtimeout; // set up tcp members - _conn->user = this; - _conn->read = &ConnImpl::OnRead; - _conn->tick = &ConnImpl::OnTick; + _conn->user = this; + _conn->read = &ConnImpl::OnRead; + _conn->tick = &ConnImpl::OnTick; _conn->closed = &ConnImpl::OnClosed; - m_Bad = false; - m_State = eReadHTTPMethodLine; + m_Bad = false; + m_State = eReadHTTPMethodLine; } ~ConnImpl() = default; @@ -60,14 +60,14 @@ namespace abyss FeedLine(std::string& line) { bool done = false; - switch(m_State) + switch (m_State) { case eReadHTTPMethodLine: return ProcessMethodLine(line); case eReadHTTPHeaders: - if(!ProcessHeaderLine(line, done)) + if (!ProcessHeaderLine(line, done)) return false; - if(done) + if (done) m_State = eReadHTTPBody; return true; default: @@ -79,15 +79,15 @@ namespace abyss ProcessMethodLine(string_view line) { auto idx = line.find_first_of(' '); - if(idx == string_view::npos) + if (idx == string_view::npos) return false; Header.Method = std::string(line.substr(0, idx)); - line = line.substr(idx + 1); - idx = line.find_first_of(' '); - if(idx == string_view::npos) + line = line.substr(idx + 1); + idx = line.find_first_of(' '); + if (idx == string_view::npos) return false; Header.Path = std::string(line.substr(0, idx)); - m_State = eReadHTTPHeaders; + m_State = eReadHTTPHeaders; return true; } @@ -95,119 +95,110 @@ namespace abyss ShouldProcessHeader(const string_view& name) const { // TODO: header whitelist - return name == string_view("content-type") - || name == string_view("content-length") + return name == string_view("content-type") || name == string_view("content-length") || name == string_view("host"); } bool - WriteResponseSimple(int code, const std::string& msg, - const char* contentType, const char* content) + WriteResponseSimple( + int code, const std::string& msg, const char* contentType, const char* content) { - char buf[512] = {0}; + char buf[512] = {0}; size_t contentLength = strlen(content); - int sz = snprintf(buf, sizeof(buf), - "HTTP/1.0 %d %s\r\nContent-Type: " - "%s\r\nContent-Length: %zu\r\n\r\n", - code, msg.c_str(), contentType, contentLength); - if(sz <= 0) + int sz = snprintf( + buf, + sizeof(buf), + "HTTP/1.0 %d %s\r\nContent-Type: " + "%s\r\nContent-Length: %zu\r\n\r\n", + code, + msg.c_str(), + contentType, + contentLength); + if (sz <= 0) return false; - if(!llarp_tcp_conn_async_write(_conn, llarp_buffer_t(buf, sz))) + if (!llarp_tcp_conn_async_write(_conn, llarp_buffer_t(buf, sz))) return false; m_State = eWriteHTTPBody; - return llarp_tcp_conn_async_write( - _conn, llarp_buffer_t(content, contentLength)); + return llarp_tcp_conn_async_write(_conn, llarp_buffer_t(content, contentLength)); } bool FeedBody(const char* buf, size_t sz) { - if(Header.Method != "POST") + if (Header.Method != "POST") { - return WriteResponseSimple(405, "Method Not Allowed", "text/plain", - "nope"); + return WriteResponseSimple(405, "Method Not Allowed", "text/plain", "nope"); } { auto itr = Header.Headers.find("content-type"); - if(itr == Header.Headers.end()) + if (itr == Header.Headers.end()) { - return WriteResponseSimple(415, "Unsupported Media Type", - "text/plain", - "no content type provided"); + return WriteResponseSimple( + 415, "Unsupported Media Type", "text/plain", "no content type provided"); } - else if(itr->second != string_view("application/json")) + else if (itr->second != string_view("application/json")) { - return WriteResponseSimple(415, "Unsupported Media Type", - "text/plain", - "this does not look like jsonrpc 2.0"); + return WriteResponseSimple( + 415, "Unsupported Media Type", "text/plain", "this does not look like jsonrpc 2.0"); } } // initialize body parser - if(m_BodyParser == nullptr) + if (m_BodyParser == nullptr) { auto itr = Header.Headers.find("content-length"); - if(itr == Header.Headers.end()) + if (itr == Header.Headers.end()) { - return WriteResponseSimple(400, "Bad Request", "text/plain", - "no content length"); + return WriteResponseSimple(400, "Bad Request", "text/plain", "no content length"); } ssize_t contentLength = std::stoll(itr->second); - if(contentLength <= 0) + if (contentLength <= 0) { - return WriteResponseSimple(400, "Bad Request", "text/plain", - "bad content length"); + return WriteResponseSimple(400, "Bad Request", "text/plain", "bad content length"); } else { m_BodyParser.reset(json::MakeParser(contentLength)); } itr = Header.Headers.find("host"); - if(itr == Header.Headers.end()) + if (itr == Header.Headers.end()) { - return WriteResponseSimple(400, "Bad Request", "text/plain", - "no host header provided"); + return WriteResponseSimple(400, "Bad Request", "text/plain", "no host header provided"); } - if(not handler->ValidateHost(itr->second)) + if (not handler->ValidateHost(itr->second)) { - return WriteResponseSimple(400, "Bad Request", "text/plain", - "invalid host header"); + return WriteResponseSimple(400, "Bad Request", "text/plain", "invalid host header"); } } - if(!m_BodyParser->FeedData(buf, sz)) + if (!m_BodyParser->FeedData(buf, sz)) { - return WriteResponseSimple(400, "Bad Request", "text/plain", - "invalid body size"); + return WriteResponseSimple(400, "Bad Request", "text/plain", "invalid body size"); } - switch(m_BodyParser->Parse(m_Request)) + switch (m_BodyParser->Parse(m_Request)) { case json::IParser::eNeedData: return true; case json::IParser::eParseError: - return WriteResponseSimple(400, "Bad Request", "text/plain", - "bad json object"); + return WriteResponseSimple(400, "Bad Request", "text/plain", "bad json object"); case json::IParser::eDone: - if(m_Request.is_object() && m_Request.count("params") - && m_Request.count("method") && m_Request.count("id") - && m_Request["id"].is_string() && m_Request["method"].is_string() - && m_Request["params"].is_object()) + if (m_Request.is_object() && m_Request.count("params") && m_Request.count("method") + && m_Request.count("id") && m_Request["id"].is_string() + && m_Request["method"].is_string() && m_Request["params"].is_object()) { nlohmann::json response; response["jsonrpc"] = "2.0"; - response["id"] = m_Request["id"].get< std::string >(); - auto value = handler->HandleJSONRPC( - m_Request["method"].get< std::string >(), - m_Request["params"]); + response["id"] = m_Request["id"].get(); + auto value = handler->HandleJSONRPC( + m_Request["method"].get(), m_Request["params"]); - if(!value.is_null()) + if (!value.is_null()) response["result"] = std::move(value); return WriteResponseJSON(response); } - return WriteResponseSimple(500, "internal error", "text/plain", - "nope"); + return WriteResponseSimple(500, "internal error", "text/plain", "nope"); default: return false; } @@ -217,43 +208,42 @@ namespace abyss WriteResponseJSON(const nlohmann::json& response) { std::string responseStr = response.dump(); - return WriteResponseSimple(200, "OK", "application/json", - responseStr.c_str()); + return WriteResponseSimple(200, "OK", "application/json", responseStr.c_str()); } bool ProcessRead(const char* buf, size_t sz) { llarp::LogDebug("http read ", sz, " bytes"); - if(m_Bad) + if (m_Bad) { return false; } - if(!sz) + if (!sz) return true; - bool done = false; + bool done = false; m_LastActive = _parent->now(); - if(m_State < eReadHTTPBody) + if (m_State < eReadHTTPBody) { const char* end = strstr(buf, "\r\n"); - while(end) + while (end) { string_view line(buf, end - buf); - switch(m_State) + switch (m_State) { case eReadHTTPMethodLine: - if(!ProcessMethodLine(line)) + if (!ProcessMethodLine(line)) return false; sz -= line.size() + (2 * sizeof(char)); break; case eReadHTTPHeaders: - if(!ProcessHeaderLine(line, done)) + if (!ProcessHeaderLine(line, done)) return false; sz -= line.size() + (2 * sizeof(char)); - if(done) + if (done) m_State = eReadHTTPBody; break; default: @@ -263,7 +253,7 @@ namespace abyss end = strstr(buf, "\r\n"); } } - if(m_State == eReadHTTPBody) + if (m_State == eReadHTTPBody) return FeedBody(buf, sz); return false; } @@ -271,8 +261,8 @@ namespace abyss static void OnRead(llarp_tcp_conn* conn, const llarp_buffer_t& buf) { - ConnImpl* self = static_cast< ConnImpl* >(conn->user); - if(!self->ProcessRead((const char*)buf.base, buf.sz)) + ConnImpl* self = static_cast(conn->user); + if (!self->ProcessRead((const char*)buf.base, buf.sz)) self->MarkBad(); } @@ -280,22 +270,22 @@ namespace abyss OnClosed(llarp_tcp_conn* conn) { llarp::LogDebug("connection closed"); - ConnImpl* self = static_cast< ConnImpl* >(conn->user); - self->_conn = nullptr; - self->m_State = eCloseMe; + ConnImpl* self = static_cast(conn->user); + self->_conn = nullptr; + self->m_State = eCloseMe; } static void OnTick(llarp_tcp_conn* conn) { - ConnImpl* self = static_cast< ConnImpl* >(conn->user); + ConnImpl* self = static_cast(conn->user); self->Tick(); } void Tick() { - if(m_Bad) + if (m_Bad) Close(); } @@ -309,14 +299,13 @@ namespace abyss bool ShouldClose(llarp_time_t now) const { - return now - m_LastActive > m_ReadTimeout || m_Bad - || m_State == eCloseMe; + return now - m_LastActive > m_ReadTimeout || m_Bad || m_State == eCloseMe; } void Close() { - if(_conn) + if (_conn) { llarp_tcp_conn_close(_conn); _conn = nullptr; @@ -340,21 +329,19 @@ namespace abyss return m_Impl->ShouldClose(now); } - BaseReqHandler::BaseReqHandler(llarp_time_t reqtimeout) - : m_ReqTimeout(reqtimeout) + BaseReqHandler::BaseReqHandler(llarp_time_t reqtimeout) : m_ReqTimeout(reqtimeout) { m_acceptor.accepted = &BaseReqHandler::OnAccept; - m_acceptor.user = this; - m_acceptor.tick = &OnTick; - m_acceptor.closed = nullptr; + m_acceptor.user = this; + m_acceptor.tick = &OnTick; + m_acceptor.closed = nullptr; } bool - BaseReqHandler::ServeAsync(llarp_ev_loop_ptr loop, - std::shared_ptr< llarp::Logic > logic, - const sockaddr* bindaddr) + BaseReqHandler::ServeAsync( + llarp_ev_loop_ptr loop, std::shared_ptr logic, const sockaddr* bindaddr) { - m_loop = loop; + m_loop = loop; m_Logic = logic; return llarp_tcp_serve(m_loop.get(), &m_acceptor, bindaddr); } @@ -362,7 +349,7 @@ namespace abyss void BaseReqHandler::OnTick(llarp_tcp_acceptor* tcp) { - BaseReqHandler* self = static_cast< BaseReqHandler* >(tcp->user); + BaseReqHandler* self = static_cast(tcp->user); self->Tick(); } @@ -371,10 +358,10 @@ namespace abyss BaseReqHandler::Tick() { auto _now = now(); - auto itr = m_Conns.begin(); - while(itr != m_Conns.end()) + auto itr = m_Conns.begin(); + while (itr != m_Conns.end()) { - if((*itr)->ShouldClose(_now)) + if ((*itr)->ShouldClose(_now)) itr = m_Conns.erase(itr); else ++itr; @@ -394,10 +381,10 @@ namespace abyss void BaseReqHandler::OnAccept(llarp_tcp_acceptor* acceptor, llarp_tcp_conn* conn) { - BaseReqHandler* self = static_cast< BaseReqHandler* >(acceptor->user); - ConnImpl* connimpl = new ConnImpl(self, conn, self->m_ReqTimeout); + BaseReqHandler* self = static_cast(acceptor->user); + ConnImpl* connimpl = new ConnImpl(self, conn, self->m_ReqTimeout); IRPCHandler* rpcHandler = self->CreateHandler(connimpl); - if(rpcHandler == nullptr) + if (rpcHandler == nullptr) { connimpl->Close(); delete connimpl; diff --git a/llarp/android/ifaddrs.c b/llarp/android/ifaddrs.c index 83c644da1..f0bd83c00 100644 --- a/llarp/android/ifaddrs.c +++ b/llarp/android/ifaddrs.c @@ -38,8 +38,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. typedef struct NetlinkList { - struct NetlinkList *m_next; - struct nlmsghdr *m_data; + struct NetlinkList* m_next; + struct nlmsghdr* m_data; unsigned int m_size; } NetlinkList; @@ -47,7 +47,7 @@ static int netlink_socket(void) { int l_socket = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE); - if(l_socket < 0) + if (l_socket < 0) { return -1; } @@ -55,7 +55,7 @@ netlink_socket(void) struct sockaddr_nl l_addr; memset(&l_addr, 0, sizeof(l_addr)); l_addr.nl_family = AF_NETLINK; - if(bind(l_socket, (struct sockaddr *)&l_addr, sizeof(l_addr)) < 0) + if (bind(l_socket, (struct sockaddr*)&l_addr, sizeof(l_addr)) < 0) { close(l_socket); return -1; @@ -75,48 +75,53 @@ netlink_send(int p_socket, int p_request) memset(&l_data, 0, sizeof(l_data)); - l_data.m_hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)); - l_data.m_hdr.nlmsg_type = p_request; - l_data.m_hdr.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; - l_data.m_hdr.nlmsg_pid = 0; - l_data.m_hdr.nlmsg_seq = p_socket; + l_data.m_hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtgenmsg)); + l_data.m_hdr.nlmsg_type = p_request; + l_data.m_hdr.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; + l_data.m_hdr.nlmsg_pid = 0; + l_data.m_hdr.nlmsg_seq = p_socket; l_data.m_msg.rtgen_family = AF_UNSPEC; 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) +netlink_recv(int p_socket, void* p_buffer, size_t p_len) { struct msghdr l_msg; struct iovec l_iov = {p_buffer, p_len}; struct sockaddr_nl l_addr; - for(;;) + for (;;) { - l_msg.msg_name = (void *)&l_addr; - l_msg.msg_namelen = sizeof(l_addr); - l_msg.msg_iov = &l_iov; - l_msg.msg_iovlen = 1; - l_msg.msg_control = NULL; + l_msg.msg_name = (void*)&l_addr; + l_msg.msg_namelen = sizeof(l_addr); + l_msg.msg_iov = &l_iov; + l_msg.msg_iovlen = 1; + l_msg.msg_control = NULL; l_msg.msg_controllen = 0; - l_msg.msg_flags = 0; - int l_result = recvmsg(p_socket, &l_msg, 0); + l_msg.msg_flags = 0; + int l_result = recvmsg(p_socket, &l_msg, 0); - if(l_result < 0) + if (l_result < 0) { - if(errno == EINTR) + if (errno == EINTR) { continue; } return -2; } - if(l_msg.msg_flags & MSG_TRUNC) + if (l_msg.msg_flags & MSG_TRUNC) { // buffer was too small return -1; } @@ -124,49 +129,47 @@ netlink_recv(int p_socket, void *p_buffer, size_t p_len) } } -static struct nlmsghdr * -getNetlinkResponse(int p_socket, int *p_size, int *p_done) +static struct nlmsghdr* +getNetlinkResponse(int p_socket, int* p_size, int* p_done) { - size_t l_size = 4096; - void *l_buffer = NULL; + size_t l_size = 4096; + void* l_buffer = NULL; - for(;;) + for (;;) { free(l_buffer); l_buffer = malloc(l_size); - if(l_buffer == NULL) + if (l_buffer == NULL) { return NULL; } int l_read = netlink_recv(p_socket, l_buffer, l_size); - *p_size = l_read; - if(l_read == -2) + *p_size = l_read; + if (l_read == -2) { free(l_buffer); return NULL; } - if(l_read >= 0) + if (l_read >= 0) { pid_t l_pid = getpid(); - struct nlmsghdr *l_hdr; - for(l_hdr = (struct nlmsghdr *)l_buffer; - NLMSG_OK(l_hdr, (unsigned int)l_read); - l_hdr = (struct nlmsghdr *)NLMSG_NEXT(l_hdr, l_read)) + struct nlmsghdr* l_hdr; + for (l_hdr = (struct nlmsghdr*)l_buffer; NLMSG_OK(l_hdr, (unsigned int)l_read); + l_hdr = (struct nlmsghdr*)NLMSG_NEXT(l_hdr, l_read)) { - if((pid_t)l_hdr->nlmsg_pid != l_pid - || (int)l_hdr->nlmsg_seq != p_socket) + if ((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) { continue; } - if(l_hdr->nlmsg_type == NLMSG_DONE) + if (l_hdr->nlmsg_type == NLMSG_DONE) { *p_done = 1; break; } - if(l_hdr->nlmsg_type == NLMSG_ERROR) + if (l_hdr->nlmsg_type == NLMSG_ERROR) { free(l_buffer); return NULL; @@ -179,11 +182,11 @@ getNetlinkResponse(int p_socket, int *p_size, int *p_done) } } -static NetlinkList * -newListItem(struct nlmsghdr *p_data, unsigned int p_size) +static NetlinkList* +newListItem(struct nlmsghdr* p_data, unsigned int p_size) { - NetlinkList *l_item = malloc(sizeof(NetlinkList)); - if(l_item == NULL) + NetlinkList* l_item = malloc(sizeof(NetlinkList)); + if (l_item == NULL) { return NULL; } @@ -195,46 +198,46 @@ newListItem(struct nlmsghdr *p_data, unsigned int p_size) } static void -freeResultList(NetlinkList *p_list) +freeResultList(NetlinkList* p_list) { - NetlinkList *l_cur; - while(p_list) + NetlinkList* l_cur; + while (p_list) { - l_cur = p_list; + l_cur = p_list; p_list = p_list->m_next; free(l_cur->m_data); free(l_cur); } } -static NetlinkList * +static NetlinkList* getResultList(int p_socket, int p_request) { - if(netlink_send(p_socket, p_request) < 0) + if (netlink_send(p_socket, p_request) < 0) { return NULL; } - NetlinkList *l_list = NULL; - NetlinkList *l_end = NULL; + NetlinkList* l_list = NULL; + NetlinkList* l_end = NULL; int l_size; int l_done = 0; - while(!l_done) + while (!l_done) { - struct nlmsghdr *l_hdr = getNetlinkResponse(p_socket, &l_size, &l_done); - if(!l_hdr) + struct nlmsghdr* l_hdr = getNetlinkResponse(p_socket, &l_size, &l_done); + if (!l_hdr) { // error freeResultList(l_list); return NULL; } - NetlinkList *l_item = newListItem(l_hdr, l_size); - if(!l_item) + NetlinkList* l_item = newListItem(l_hdr, l_size); + if (!l_item) { freeResultList(l_list); return NULL; } - if(!l_list) + if (!l_list) { l_list = l_item; } @@ -256,36 +259,34 @@ maxSize(size_t a, size_t b) static size_t calcAddrLen(sa_family_t p_family, int p_dataSize) { - switch(p_family) + switch (p_family) { case AF_INET: return sizeof(struct sockaddr_in); 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); } } static void -makeSockaddr(sa_family_t p_family, struct sockaddr *p_dest, void *p_data, - size_t p_size) +makeSockaddr(sa_family_t p_family, struct sockaddr* p_dest, void* p_data, size_t p_size) { - switch(p_family) + switch (p_family) { case AF_INET: - memcpy(&((struct sockaddr_in *)p_dest)->sin_addr, p_data, p_size); + memcpy(&((struct sockaddr_in*)p_dest)->sin_addr, p_data, p_size); break; case AF_INET6: - memcpy(&((struct sockaddr_in6 *)p_dest)->sin6_addr, p_data, p_size); + memcpy(&((struct sockaddr_in6*)p_dest)->sin6_addr, p_data, p_size); break; case AF_PACKET: - memcpy(((struct sockaddr_ll *)p_dest)->sll_addr, p_data, p_size); - ((struct sockaddr_ll *)p_dest)->sll_halen = p_size; + memcpy(((struct sockaddr_ll*)p_dest)->sll_addr, p_data, p_size); + ((struct sockaddr_ll*)p_dest)->sll_halen = p_size; break; default: memcpy(p_dest->sa_data, p_data, p_size); @@ -295,16 +296,16 @@ makeSockaddr(sa_family_t p_family, struct sockaddr *p_dest, void *p_data, } static void -addToEnd(struct ifaddrs **p_resultList, struct ifaddrs *p_entry) +addToEnd(struct ifaddrs** p_resultList, struct ifaddrs* p_entry) { - if(!*p_resultList) + if (!*p_resultList) { *p_resultList = p_entry; } else { - struct ifaddrs *l_cur = *p_resultList; - while(l_cur->ifa_next) + struct ifaddrs* l_cur = *p_resultList; + while (l_cur->ifa_next) { l_cur = l_cur->ifa_next; } @@ -313,23 +314,22 @@ addToEnd(struct ifaddrs **p_resultList, struct ifaddrs *p_entry) } static int -interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList) +interpretLink(struct nlmsghdr* p_hdr, struct ifaddrs** p_resultList) { - struct ifinfomsg *l_info = (struct ifinfomsg *)NLMSG_DATA(p_hdr); + struct ifinfomsg* l_info = (struct ifinfomsg*)NLMSG_DATA(p_hdr); size_t l_nameSize = 0; size_t l_addrSize = 0; size_t l_dataSize = 0; size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg)); - struct rtattr *l_rta; - for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); - l_rta = RTA_NEXT(l_rta, l_rtaSize)) + struct rtattr* l_rta; + for (l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { - void *l_rtaData = RTA_DATA(l_rta); + void* l_rtaData = RTA_DATA(l_rta); (void)l_rtaData; size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); - switch(l_rta->rta_type) + switch (l_rta->rta_type) { case IFLA_ADDRESS: case IFLA_BROADCAST: @@ -346,19 +346,19 @@ 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); - if(l_entry == NULL) + struct ifaddrs* l_entry = + malloc(sizeof(struct ifaddrs) + sizeof(int) + l_nameSize + l_addrSize + l_dataSize); + if (l_entry == NULL) { return -1; } memset(l_entry, 0, sizeof(struct ifaddrs)); l_entry->ifa_name = ""; - char *l_index = ((char *)l_entry) + sizeof(struct ifaddrs); - char *l_name = l_index + sizeof(int); - char *l_addr = l_name + l_nameSize; - char *l_data = l_addr + l_addrSize; + char* l_index = ((char*)l_entry) + sizeof(struct ifaddrs); + char* l_name = l_index + sizeof(int); + char* l_addr = l_name + l_nameSize; + char* l_data = l_addr + l_addrSize; // save the interface index so we can look it up when handling the addresses. memcpy(l_index, &l_info->ifi_index, sizeof(int)); @@ -366,28 +366,26 @@ interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList) l_entry->ifa_flags = l_info->ifi_flags; l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifinfomsg)); - for(l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); - l_rta = RTA_NEXT(l_rta, l_rtaSize)) + for (l_rta = IFLA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { - void *l_rtaData = RTA_DATA(l_rta); + void* l_rtaData = RTA_DATA(l_rta); size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); - switch(l_rta->rta_type) + switch (l_rta->rta_type) { case IFLA_ADDRESS: case IFLA_BROADCAST: { size_t l_addrLen = calcAddrLen(AF_PACKET, l_rtaDataSize); - makeSockaddr(AF_PACKET, (struct sockaddr *)l_addr, l_rtaData, - l_rtaDataSize); - ((struct sockaddr_ll *)l_addr)->sll_ifindex = l_info->ifi_index; - ((struct sockaddr_ll *)l_addr)->sll_hatype = l_info->ifi_type; - if(l_rta->rta_type == IFLA_ADDRESS) + makeSockaddr(AF_PACKET, (struct sockaddr*)l_addr, l_rtaData, l_rtaDataSize); + ((struct sockaddr_ll*)l_addr)->sll_ifindex = l_info->ifi_index; + ((struct sockaddr_ll*)l_addr)->sll_hatype = l_info->ifi_type; + if (l_rta->rta_type == IFLA_ADDRESS) { - l_entry->ifa_addr = (struct sockaddr *)l_addr; + l_entry->ifa_addr = (struct sockaddr*)l_addr; } else { - l_entry->ifa_broadaddr = (struct sockaddr *)l_addr; + l_entry->ifa_broadaddr = (struct sockaddr*)l_addr; } l_addr += NLMSG_ALIGN(l_addrLen); break; @@ -395,7 +393,7 @@ interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList) case IFLA_IFNAME: strncpy(l_name, l_rtaData, l_rtaDataSize); l_name[l_rtaDataSize] = '\0'; - l_entry->ifa_name = l_name; + l_entry->ifa_name = l_name; break; case IFLA_STATS: memcpy(l_data, l_rtaData, l_rtaDataSize); @@ -410,17 +408,17 @@ interpretLink(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList) return 0; } -static struct ifaddrs * -findInterface(int p_index, struct ifaddrs **p_links, int p_numLinks) +static struct ifaddrs* +findInterface(int p_index, struct ifaddrs** p_links, int p_numLinks) { - int l_num = 0; - struct ifaddrs *l_cur = *p_links; - while(l_cur && l_num < p_numLinks) + int l_num = 0; + struct ifaddrs* l_cur = *p_links; + while (l_cur && l_num < p_numLinks) { - char *l_indexPtr = ((char *)l_cur) + sizeof(struct ifaddrs); + char* l_indexPtr = ((char*)l_cur) + sizeof(struct ifaddrs); int l_index; memcpy(&l_index, l_indexPtr, sizeof(int)); - if(l_index == p_index) + if (l_index == p_index) { return l_cur; } @@ -432,14 +430,12 @@ findInterface(int p_index, struct ifaddrs **p_links, int p_numLinks) } static int -interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, - int p_numLinks) +interpretAddr(struct nlmsghdr* p_hdr, struct ifaddrs** p_resultList, int p_numLinks) { - struct ifaddrmsg *l_info = (struct ifaddrmsg *)NLMSG_DATA(p_hdr); - struct ifaddrs *l_interface = - findInterface(l_info->ifa_index, p_resultList, p_numLinks); + struct ifaddrmsg* l_info = (struct ifaddrmsg*)NLMSG_DATA(p_hdr); + struct ifaddrs* l_interface = findInterface(l_info->ifa_index, p_resultList, p_numLinks); - if(l_info->ifa_family == AF_PACKET) + if (l_info->ifa_family == AF_PACKET) { return 0; } @@ -450,28 +446,24 @@ interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, int l_addedNetmask = 0; size_t l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg)); - struct rtattr *l_rta; - for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); - l_rta = RTA_NEXT(l_rta, l_rtaSize)) + struct rtattr* l_rta; + for (l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { - void *l_rtaData = RTA_DATA(l_rta); + void* l_rtaData = RTA_DATA(l_rta); (void)l_rtaData; size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); - switch(l_rta->rta_type) + switch (l_rta->rta_type) { 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_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize)); l_addedNetmask = 1; } case IFA_BROADCAST: - l_addrSize += - NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize)); + l_addrSize += NLMSG_ALIGN(calcAddrLen(l_info->ifa_family, l_rtaDataSize)); break; case IFA_LABEL: l_nameSize += NLMSG_ALIGN(l_rtaSize + 1); @@ -481,71 +473,68 @@ interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, } } - struct ifaddrs *l_entry = - malloc(sizeof(struct ifaddrs) + l_nameSize + l_addrSize); - if(l_entry == NULL) + struct ifaddrs* l_entry = malloc(sizeof(struct ifaddrs) + l_nameSize + l_addrSize); + if (l_entry == NULL) { return -1; } memset(l_entry, 0, sizeof(struct ifaddrs)); l_entry->ifa_name = (l_interface ? l_interface->ifa_name : ""); - char *l_name = ((char *)l_entry) + sizeof(struct ifaddrs); - char *l_addr = l_name + l_nameSize; + char* l_name = ((char*)l_entry) + sizeof(struct ifaddrs); + char* l_addr = l_name + l_nameSize; l_entry->ifa_flags = l_info->ifa_flags; - if(l_interface) + if (l_interface) { l_entry->ifa_flags |= l_interface->ifa_flags; } l_rtaSize = NLMSG_PAYLOAD(p_hdr, sizeof(struct ifaddrmsg)); - for(l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); - l_rta = RTA_NEXT(l_rta, l_rtaSize)) + for (l_rta = IFA_RTA(l_info); RTA_OK(l_rta, l_rtaSize); l_rta = RTA_NEXT(l_rta, l_rtaSize)) { - void *l_rtaData = RTA_DATA(l_rta); + void* l_rtaData = RTA_DATA(l_rta); size_t l_rtaDataSize = RTA_PAYLOAD(l_rta); - switch(l_rta->rta_type) + switch (l_rta->rta_type) { case IFA_ADDRESS: case IFA_BROADCAST: 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); - if(l_info->ifa_family == AF_INET6) + 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) - || IN6_IS_ADDR_MC_LINKLOCAL((struct in6_addr *)l_rtaData)) + if (IN6_IS_ADDR_LINKLOCAL((struct in6_addr*)l_rtaData) + || IN6_IS_ADDR_MC_LINKLOCAL((struct in6_addr*)l_rtaData)) { - ((struct sockaddr_in6 *)l_addr)->sin6_scope_id = l_info->ifa_index; + ((struct sockaddr_in6*)l_addr)->sin6_scope_id = l_info->ifa_index; } } - if(l_rta->rta_type == IFA_ADDRESS) + if (l_rta->rta_type == IFA_ADDRESS) { // apparently in a point-to-point network IFA_ADDRESS contains the // dest address and IFA_LOCAL contains the local address - if(l_entry->ifa_addr) + if (l_entry->ifa_addr) { - l_entry->ifa_dstaddr = (struct sockaddr *)l_addr; + l_entry->ifa_dstaddr = (struct sockaddr*)l_addr; } else { - l_entry->ifa_addr = (struct sockaddr *)l_addr; + l_entry->ifa_addr = (struct sockaddr*)l_addr; } } - else if(l_rta->rta_type == IFA_LOCAL) + else if (l_rta->rta_type == IFA_LOCAL) { - if(l_entry->ifa_addr) + if (l_entry->ifa_addr) { l_entry->ifa_dstaddr = l_entry->ifa_addr; } - l_entry->ifa_addr = (struct sockaddr *)l_addr; + l_entry->ifa_addr = (struct sockaddr*)l_addr; } else { - l_entry->ifa_broadaddr = (struct sockaddr *)l_addr; + l_entry->ifa_broadaddr = (struct sockaddr*)l_addr; } l_addr += NLMSG_ALIGN(l_addrLen); break; @@ -553,35 +542,31 @@ interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, case IFA_LABEL: strncpy(l_name, l_rtaData, l_rtaDataSize); l_name[l_rtaDataSize] = '\0'; - l_entry->ifa_name = l_name; + l_entry->ifa_name = l_name; break; default: break; } } - 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) + for (i = 0; i < (l_prefix / 8); ++i) { l_mask[i] = 0xff; } - if(l_prefix % 8) + if (l_prefix % 8) { l_mask[i] = 0xff << (8 - (l_prefix % 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; + makeSockaddr(l_entry->ifa_addr->sa_family, (struct sockaddr*)l_addr, l_mask, l_maxPrefix / 8); + l_entry->ifa_netmask = (struct sockaddr*)l_addr; } addToEnd(p_resultList, l_entry); @@ -589,31 +574,30 @@ interpretAddr(struct nlmsghdr *p_hdr, struct ifaddrs **p_resultList, } static int -interpretLinks(int p_socket, NetlinkList *p_netlinkList, - struct ifaddrs **p_resultList) +interpretLinks(int p_socket, NetlinkList* p_netlinkList, struct ifaddrs** p_resultList) { int l_numLinks = 0; - pid_t l_pid = getpid(); - for(; p_netlinkList; p_netlinkList = p_netlinkList->m_next) + 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)) + 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)) { - if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) + if ((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) { continue; } - if(l_hdr->nlmsg_type == NLMSG_DONE) + if (l_hdr->nlmsg_type == NLMSG_DONE) { break; } - if(l_hdr->nlmsg_type == RTM_NEWLINK) + if (l_hdr->nlmsg_type == RTM_NEWLINK) { - if(interpretLink(l_hdr, p_resultList) == -1) + if (interpretLink(l_hdr, p_resultList) == -1) { return -1; } @@ -625,30 +609,30 @@ interpretLinks(int p_socket, NetlinkList *p_netlinkList, } static int -interpretAddrs(int p_socket, NetlinkList *p_netlinkList, - struct ifaddrs **p_resultList, int p_numLinks) +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) + 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)) + 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)) { - if((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) + if ((pid_t)l_hdr->nlmsg_pid != l_pid || (int)l_hdr->nlmsg_seq != p_socket) { continue; } - if(l_hdr->nlmsg_type == NLMSG_DONE) + if (l_hdr->nlmsg_type == NLMSG_DONE) { break; } - if(l_hdr->nlmsg_type == RTM_NEWADDR) + if (l_hdr->nlmsg_type == RTM_NEWADDR) { - if(interpretAddr(l_hdr, p_resultList, p_numLinks) == -1) + if (interpretAddr(l_hdr, p_resultList, p_numLinks) == -1) { return -1; } @@ -659,39 +643,38 @@ interpretAddrs(int p_socket, NetlinkList *p_netlinkList, } int -getifaddrs(struct ifaddrs **ifap) +getifaddrs(struct ifaddrs** ifap) { - if(!ifap) + if (!ifap) { return -1; } *ifap = NULL; int l_socket = netlink_socket(); - if(l_socket < 0) + if (l_socket < 0) { return -1; } - NetlinkList *l_linkResults = getResultList(l_socket, RTM_GETLINK); - if(!l_linkResults) + NetlinkList* l_linkResults = getResultList(l_socket, RTM_GETLINK); + if (!l_linkResults) { close(l_socket); return -1; } - NetlinkList *l_addrResults = getResultList(l_socket, RTM_GETADDR); - if(!l_addrResults) + NetlinkList* l_addrResults = getResultList(l_socket, RTM_GETADDR); + if (!l_addrResults) { close(l_socket); freeResultList(l_linkResults); return -1; } - int l_result = 0; + int l_result = 0; int l_numLinks = interpretLinks(l_socket, l_linkResults, ifap); - if(l_numLinks == -1 - || interpretAddrs(l_socket, l_addrResults, ifap, l_numLinks) == -1) + if (l_numLinks == -1 || interpretAddrs(l_socket, l_addrResults, ifap, l_numLinks) == -1) { l_result = -1; } @@ -703,13 +686,13 @@ getifaddrs(struct ifaddrs **ifap) } void -freeifaddrs(struct ifaddrs *ifa) +freeifaddrs(struct ifaddrs* ifa) { - struct ifaddrs *l_cur; - while(ifa) + struct ifaddrs* l_cur; + while (ifa) { l_cur = ifa; - ifa = ifa->ifa_next; + ifa = ifa->ifa_next; free(l_cur); } } diff --git a/llarp/android/ifaddrs.h b/llarp/android/ifaddrs.h index 9ff61469e..73d3d2877 100644 --- a/llarp/android/ifaddrs.h +++ b/llarp/android/ifaddrs.h @@ -28,13 +28,13 @@ struct ifaddrs { - struct ifaddrs *ifa_next; - char *ifa_name; + struct ifaddrs* ifa_next; + char* ifa_name; unsigned int ifa_flags; - struct sockaddr *ifa_addr; - struct sockaddr *ifa_netmask; - struct sockaddr *ifa_dstaddr; - void *ifa_data; + struct sockaddr* ifa_addr; + struct sockaddr* ifa_netmask; + struct sockaddr* ifa_dstaddr; + void* ifa_data; }; /* @@ -49,9 +49,9 @@ struct ifaddrs __BEGIN_DECLS extern int -getifaddrs(struct ifaddrs **ifap); +getifaddrs(struct ifaddrs** ifap); extern void -freeifaddrs(struct ifaddrs *ifa); +freeifaddrs(struct ifaddrs* ifa); __END_DECLS #endif diff --git a/llarp/bootstrap.cpp b/llarp/bootstrap.cpp index 8addcac44..a5fb3ad17 100644 --- a/llarp/bootstrap.cpp +++ b/llarp/bootstrap.cpp @@ -14,10 +14,10 @@ namespace llarp { return bencode_read_list( [&](llarp_buffer_t* b, bool more) -> bool { - if(more) + if (more) { RouterContact rc; - if(not rc.BDecode(b)) + if (not rc.BDecode(b)) return false; emplace(std::move(rc)); } diff --git a/llarp/bootstrap.hpp b/llarp/bootstrap.hpp index 7f3108cc4..affd4bb7e 100644 --- a/llarp/bootstrap.hpp +++ b/llarp/bootstrap.hpp @@ -6,7 +6,7 @@ namespace llarp { - struct BootstrapList final : public std::set< RouterContact > + struct BootstrapList final : public std::set { bool BDecode(llarp_buffer_t* buf); diff --git a/llarp/config/config.cpp b/llarp/config/config.cpp index 32aa359a4..be5cbee6a 100644 --- a/llarp/config/config.cpp +++ b/llarp/config/config.cpp @@ -19,7 +19,7 @@ namespace llarp { - const char * + const char* lokinetEnv(string_view suffix) { std::string env; @@ -32,41 +32,41 @@ namespace llarp std::string fromEnv(string_view val, string_view envNameSuffix) { - if(const char *ptr = lokinetEnv(envNameSuffix)) + if (const char* ptr = lokinetEnv(envNameSuffix)) return ptr; return {val.begin(), val.end()}; } int - fromEnv(const int &val, string_view envNameSuffix) + fromEnv(const int& val, string_view envNameSuffix) { - if(const char *ptr = lokinetEnv(envNameSuffix)) + if (const char* ptr = lokinetEnv(envNameSuffix)) return std::atoi(ptr); return val; } uint16_t - fromEnv(const uint16_t &val, string_view envNameSuffix) + fromEnv(const uint16_t& val, string_view envNameSuffix) { - if(const char *ptr = lokinetEnv(envNameSuffix)) + if (const char* ptr = lokinetEnv(envNameSuffix)) return std::atoi(ptr); return val; } size_t - fromEnv(const size_t &val, string_view envNameSuffix) + fromEnv(const size_t& val, string_view envNameSuffix) { - if(const char *ptr = lokinetEnv(envNameSuffix)) + if (const char* ptr = lokinetEnv(envNameSuffix)) return std::atoll(ptr); return val; } - nonstd::optional< bool > - fromEnv(const nonstd::optional< bool > &val, string_view envNameSuffix) + nonstd::optional + fromEnv(const nonstd::optional& val, string_view envNameSuffix) { - if(const char *ptr = lokinetEnv(envNameSuffix)) + if (const char* ptr = lokinetEnv(envNameSuffix)) return IsTrueValue(ptr); return val; @@ -78,14 +78,14 @@ namespace llarp return std::atoi(val.data()); } - nonstd::optional< bool > + nonstd::optional setOptBool(string_view val) { - if(IsTrueValue(val)) + if (IsTrueValue(val)) { return true; } - else if(IsFalseValue(val)) + else if (IsFalseValue(val)) { return false; } @@ -95,23 +95,23 @@ namespace llarp void RouterConfig::fromSection(string_view key, string_view val) { - if(key == "job-queue-size") + if (key == "job-queue-size") { auto sval = svtoi(val); - if(sval >= 1024) + if (sval >= 1024) { m_JobQueueSize = sval; LogInfo("Set job queue size to ", m_JobQueueSize); } } - if(key == "default-protocol") + if (key == "default-protocol") { m_DefaultLinkProto = str(val); LogInfo("overriding default link protocol to '", val, "'"); } - if(key == "netid") + if (key == "netid") { - if(val.size() <= NetID::size()) + if (val.size() <= NetID::size()) { m_netId = str(val); LogInfo("setting netid to '", val, "'"); @@ -121,77 +121,77 @@ namespace llarp llarp::LogError("invalid netid '", val, "', is too long"); } } - if(key == "max-connections") + if (key == "max-connections") { auto ival = svtoi(val); - if(ival > 0) + if (ival > 0) { m_maxConnectedRouters = ival; LogInfo("max connections set to ", m_maxConnectedRouters); } } - if(key == "min-connections") + if (key == "min-connections") { auto ival = svtoi(val); - if(ival > 0) + if (ival > 0) { m_minConnectedRouters = ival; LogInfo("min connections set to ", m_minConnectedRouters); } } - if(key == "nickname") + if (key == "nickname") { m_nickname = str(val); // set logger name here LogContext::Instance().nodeName = nickname(); LogInfo("nickname set"); } - if(key == "encryption-privkey") + if (key == "encryption-privkey") { m_encryptionKeyfile = str(val); LogDebug("encryption key set to ", m_encryptionKeyfile); } - if(key == "contact-file") + if (key == "contact-file") { m_ourRcFile = str(val); LogDebug("rc file set to ", m_ourRcFile); } - if(key == "transport-privkey") + if (key == "transport-privkey") { m_transportKeyfile = str(val); LogDebug("transport key set to ", m_transportKeyfile); } - if((key == "identity-privkey" || key == "ident-privkey")) + if ((key == "identity-privkey" || key == "ident-privkey")) { m_identKeyfile = str(val); LogDebug("identity key set to ", m_identKeyfile); } - if(key == "public-address" || key == "public-ip") + if (key == "public-address" || key == "public-ip") { llarp::LogInfo("public ip ", val, " size ", val.size()); - if(val.size() < 17) + if (val.size() < 17) { // assume IPv4 llarp::Addr a(val); llarp::LogInfo("setting public ipv4 ", a); - m_addrInfo.ip = *a.addr6(); + m_addrInfo.ip = *a.addr6(); m_publicOverride = true; } } - if(key == "public-port") + if (key == "public-port") { llarp::LogInfo("Setting public port ", val); int p = svtoi(val); // Not needed to flip upside-down - this is done in llarp::Addr(const // AddressInfo&) m_ip4addr.sin_port = p; - m_addrInfo.port = p; - m_publicOverride = true; + m_addrInfo.port = p; + m_publicOverride = true; } - if(key == "worker-threads" || key == "threads") + if (key == "worker-threads" || key == "threads") { m_workerThreads = svtoi(val); - if(m_workerThreads <= 0) + if (m_workerThreads <= 0) { LogWarn("worker threads invalid value: '", val, "' defaulting to 1"); m_workerThreads = 1; @@ -201,10 +201,10 @@ namespace llarp LogDebug("set to use ", m_workerThreads, " worker threads"); } } - if(key == "net-threads") + if (key == "net-threads") { m_numNetThreads = svtoi(val); - if(m_numNetThreads <= 0) + if (m_numNetThreads <= 0) { LogWarn("net threads invalid value: '", val, "' defaulting to 1"); m_numNetThreads = 1; @@ -214,7 +214,7 @@ namespace llarp LogDebug("set to use ", m_numNetThreads, " net threads"); } } - if(key == "block-bogons") + if (key == "block-bogons") { m_blockBogons = setOptBool(val); } @@ -223,16 +223,16 @@ namespace llarp void NetworkConfig::fromSection(string_view key, string_view val) { - if(key == "profiling") + if (key == "profiling") { m_enableProfiling = setOptBool(val); } - else if(key == "profiles") + else if (key == "profiles") { m_routerProfilesFile = str(val); llarp::LogInfo("setting profiles to ", routerProfilesFile()); } - else if(key == "strict-connect") + else if (key == "strict-connect") { m_strictConnect = str(val); } @@ -245,7 +245,7 @@ namespace llarp void NetdbConfig::fromSection(string_view key, string_view val) { - if(key == "dir") + if (key == "dir") { m_nodedbDir = str(val); } @@ -254,12 +254,12 @@ namespace llarp void DnsConfig::fromSection(string_view key, string_view val) { - if(key == "upstream") + if (key == "upstream") { llarp::LogInfo("add upstream resolver ", val); netConfig.emplace("upstream-dns", str(val)); // str() for gcc 5 compat } - if(key == "bind") + if (key == "bind") { llarp::LogInfo("set local dns to ", val); netConfig.emplace("local-dns", str(val)); // str() for gcc 5 compat @@ -271,13 +271,13 @@ namespace llarp { uint16_t proto = 0; - std::unordered_set< std::string > parsed_opts; + std::unordered_set parsed_opts; std::string::size_type idx; static constexpr char delimiter = ','; do { idx = val.find_first_of(delimiter); - if(idx != string_view::npos) + if (idx != string_view::npos) { parsed_opts.emplace(TrimWhitespace(val.substr(0, idx))); val.remove_prefix(idx + 1); @@ -286,17 +286,17 @@ namespace llarp { parsed_opts.emplace(TrimWhitespace(val)); } - } while(idx != string_view::npos); - std::unordered_set< std::string > opts; + } while (idx != string_view::npos); + std::unordered_set opts; /// for each option - for(const auto &item : parsed_opts) + for (const auto& item : parsed_opts) { /// see if it's a number auto port = std::atoi(item.c_str()); - if(port > 0) + if (port > 0) { /// set port - if(proto == 0) + if (proto == 0) { proto = port; } @@ -307,10 +307,10 @@ namespace llarp } } - if(key == "*") + if (key == "*") { - m_OutboundLink = std::make_tuple( - "*", AF_INET, fromEnv(proto, "OUTBOUND_PORT"), std::move(opts)); + m_OutboundLink = + std::make_tuple("*", AF_INET, fromEnv(proto, "OUTBOUND_PORT"), std::move(opts)); } else { @@ -334,7 +334,7 @@ namespace llarp void SystemConfig::fromSection(string_view key, string_view val) { - if(key == "pidfile") + if (key == "pidfile") { pidfile = str(val); } @@ -343,15 +343,15 @@ namespace llarp void ApiConfig::fromSection(string_view key, string_view val) { - if(key == "enabled") + if (key == "enabled") { m_enableRPCServer = IsTrueValue(val); } - if(key == "bind") + if (key == "bind") { m_rpcBindAddr = str(val); } - if(key == "authkey") + if (key == "authkey") { // TODO: add pubkey to whitelist } @@ -360,24 +360,24 @@ namespace llarp void LokidConfig::fromSection(string_view key, string_view val) { - if(key == "service-node-seed") + if (key == "service-node-seed") { - usingSNSeed = true; + usingSNSeed = true; ident_keyfile = std::string{val}; } - if(key == "enabled") + if (key == "enabled") { whitelistRouters = IsTrueValue(val); } - if(key == "jsonrpc" || key == "addr") + if (key == "jsonrpc" || key == "addr") { lokidRPCAddr = str(val); } - if(key == "username") + if (key == "username") { lokidRPCUser = str(val); } - if(key == "password") + if (key == "password") { lokidRPCPassword = str(val); } @@ -386,7 +386,7 @@ namespace llarp void BootstrapConfig::fromSection(string_view key, string_view val) { - if(key == "add-node") + if (key == "add-node") { routers.emplace_back(val.begin(), val.end()); } @@ -395,71 +395,71 @@ namespace llarp void LoggingConfig::fromSection(string_view key, string_view val) { - if(key == "type" && val == "syslog") + if (key == "type" && val == "syslog") { // TODO(despair): write event log syslog class #if defined(_WIN32) LogError("syslog not supported on win32"); #else LogInfo("Switching to syslog"); - LogContext::Instance().logStream = std::make_unique< SysLogStream >(); + LogContext::Instance().logStream = std::make_unique(); #endif } - if(key == "level") + if (key == "level") { const auto maybe = LogLevelFromString(str(val)); - if(not maybe.has_value()) + if (not maybe.has_value()) { LogError("bad log level: ", val); return; } - const LogLevel lvl = maybe.value(); + const LogLevel lvl = maybe.value(); LogContext::Instance().runtimeLevel = lvl; LogInfo("Log level set to ", LogLevelToName(lvl)); } - if(key == "type" && val == "json") + if (key == "type" && val == "json") { m_LogJSON = true; } - if(key == "file") + if (key == "file") { LogInfo("open log file: ", val); std::string fname{val}; - FILE *const logfile = ::fopen(fname.c_str(), "a"); - if(logfile) + FILE* const logfile = ::fopen(fname.c_str(), "a"); + if (logfile) { m_LogFile = logfile; LogInfo("will log to file ", val); } - else if(errno) + else if (errno) { LogError("could not open log file at '", val, "': ", strerror(errno)); errno = 0; } else { - LogError("failed to open log file at '", val, - "' for an unknown reason, bailing tf out kbai"); + LogError( + "failed to open log file at '", val, "' for an unknown reason, bailing tf out kbai"); ::abort(); } } } - template < typename Section, typename Config > + template Section - find_section(Config &c, const std::string &name) + find_section(Config& c, const std::string& name) { Section ret; - auto visitor = [&ret](const ConfigParser::Section_t §ion) -> bool { - for(const auto &sec : section) + auto visitor = [&ret](const ConfigParser::Section_t& section) -> bool { + for (const auto& sec : section) { ret.fromSection(sec.first, sec.second); } return true; }; - if(c.VisitSection(name.c_str(), visitor)) + if (c.VisitSection(name.c_str(), visitor)) { return ret; } @@ -468,10 +468,10 @@ namespace llarp } bool - Config::Load(const char *fname) + Config::Load(const char* fname) { ConfigParser parser; - if(!parser.LoadFile(fname)) + if (!parser.LoadFile(fname)) { return false; } @@ -483,7 +483,7 @@ namespace llarp Config::LoadFromStr(string_view str) { ConfigParser parser; - if(!parser.LoadFromStr(str)) + if (!parser.LoadFromStr(str)) { return false; } @@ -492,22 +492,22 @@ namespace llarp } bool - Config::parse(const ConfigParser &parser) + Config::parse(const ConfigParser& parser) { - if(Lokinet_INIT()) + if (Lokinet_INIT()) return false; - router = find_section< RouterConfig >(parser, "router"); - network = find_section< NetworkConfig >(parser, "network"); - connect = find_section< ConnectConfig >(parser, "connect"); - netdb = find_section< NetdbConfig >(parser, "netdb"); - dns = find_section< DnsConfig >(parser, "dns"); - links = find_section< LinksConfig >(parser, "bind"); - services = find_section< ServicesConfig >(parser, "services"); - system = find_section< SystemConfig >(parser, "system"); - api = find_section< ApiConfig >(parser, "api"); - lokid = find_section< LokidConfig >(parser, "lokid"); - bootstrap = find_section< BootstrapConfig >(parser, "bootstrap"); - logging = find_section< LoggingConfig >(parser, "logging"); + router = find_section(parser, "router"); + network = find_section(parser, "network"); + connect = find_section(parser, "connect"); + netdb = find_section(parser, "netdb"); + dns = find_section(parser, "dns"); + links = find_section(parser, "bind"); + services = find_section(parser, "services"); + system = find_section(parser, "system"); + api = find_section(parser, "api"); + lokid = find_section(parser, "lokid"); + bootstrap = find_section(parser, "bootstrap"); + logging = find_section(parser, "logging"); return true; } @@ -533,24 +533,23 @@ namespace llarp /// fname should be a relative path (from CWD) or absolute path to the config /// file extern "C" bool -llarp_ensure_config(const char *fname, const char *basedir, bool overwrite, - bool asRouter) +llarp_ensure_config(const char* fname, const char* basedir, bool overwrite, bool asRouter) { - if(Lokinet_INIT()) + if (Lokinet_INIT()) return false; std::error_code ec; - if(fs::exists(fname, ec) && !overwrite) + if (fs::exists(fname, ec) && !overwrite) { return true; } - if(ec) + if (ec) { llarp::LogError(ec); return false; } std::string basepath; - if(basedir) + if (basedir) { basepath = basedir; #ifndef _WIN32 @@ -563,14 +562,14 @@ llarp_ensure_config(const char *fname, const char *basedir, bool overwrite, llarp::LogInfo("Attempting to create config file ", fname); // abort if config already exists - if(!asRouter) + if (!asRouter) { - if(fs::exists(fname, ec) && !overwrite) + if (fs::exists(fname, ec) && !overwrite) { llarp::LogError(fname, " currently exists, please use -f to overwrite"); return true; } - if(ec) + if (ec) { llarp::LogError(ec); return false; @@ -578,16 +577,15 @@ llarp_ensure_config(const char *fname, const char *basedir, bool overwrite, } // write fname ini - auto optional_f = - llarp::util::OpenFileStream< std::ofstream >(fname, std::ios::binary); - if(!optional_f || !optional_f.value().is_open()) + auto optional_f = llarp::util::OpenFileStream(fname, std::ios::binary); + if (!optional_f || !optional_f.value().is_open()) { llarp::LogError("failed to open ", fname, " for writing"); return false; } - auto &f = optional_f.value(); + auto& f = optional_f.value(); llarp_generic_ensure_config(f, basepath, asRouter); - if(asRouter) + if (asRouter) { llarp_ensure_router_config(f, basepath); } @@ -600,8 +598,7 @@ llarp_ensure_config(const char *fname, const char *basedir, bool overwrite, } void -llarp_generic_ensure_config(std::ofstream &f, std::string basepath, - bool isRouter) +llarp_generic_ensure_config(std::ofstream& f, std::string basepath, bool isRouter) { f << "# this configuration was auto generated with 'sane' defaults\n"; f << "# change these values as desired\n"; @@ -618,8 +615,7 @@ llarp_generic_ensure_config(std::ofstream &f, std::string basepath, f << "# encryption key for onion routing\n"; f << "encryption-privkey=" << basepath << "encryption.private\n"; f << std::endl; - f << "# uncomment following line to set router nickname to 'lokinet'" - << std::endl; + f << "# uncomment following line to set router nickname to 'lokinet'" << std::endl; f << "#nickname=lokinet\n"; const auto limits = isRouter ? llarp::limits::snode : llarp::limits::client; @@ -695,7 +691,7 @@ llarp_generic_ensure_config(std::ofstream &f, std::string basepath, } void -llarp_ensure_router_config(std::ofstream &f, std::string basepath) +llarp_ensure_router_config(std::ofstream& f, std::string basepath) { f << "# lokid settings (disabled by default)\n"; f << "[lokid]\n"; @@ -720,7 +716,7 @@ llarp_ensure_router_config(std::ofstream &f, std::string basepath) f << "[bind]\n"; // get ifname std::string ifname; - if(llarp::GetBestNetIF(ifname, AF_INET)) + if (llarp::GetBestNetIF(ifname, AF_INET)) { f << ifname << "=1090\n"; } @@ -734,19 +730,18 @@ llarp_ensure_router_config(std::ofstream &f, std::string basepath) } bool -llarp_ensure_client_config(std::ofstream &f, std::string basepath) +llarp_ensure_client_config(std::ofstream& f, std::string basepath) { // write snapp-example.ini const std::string snappExample_fpath = basepath + "snapp-example.ini"; { - auto stream = llarp::util::OpenFileStream< std::ofstream >( - snappExample_fpath, std::ios::binary); - if(!stream) + auto stream = llarp::util::OpenFileStream(snappExample_fpath, std::ios::binary); + if (!stream) { return false; } - auto &example_f = stream.value(); - if(example_f.is_open()) + auto& example_f = stream.value(); + if (example_f.is_open()) { // pick ip // don't revert me diff --git a/llarp/config/config.hpp b/llarp/config/config.hpp index 1a9a9563a..a5d754350 100644 --- a/llarp/config/config.hpp +++ b/llarp/config/config.hpp @@ -29,8 +29,8 @@ namespace llarp fromEnv(const uint16_t& val, string_view envNameSuffix); size_t fromEnv(const size_t& val, string_view envNameSuffix); - nonstd::optional< bool > - fromEnv(const nonstd::optional< bool >& val, string_view envNameSuffix); + nonstd::optional + fromEnv(const nonstd::optional& val, string_view envNameSuffix); class RouterConfig { @@ -55,7 +55,7 @@ namespace llarp // long term identity key std::string m_identKeyfile = "identity.key"; - nonstd::optional< bool > m_blockBogons; + nonstd::optional m_blockBogons; bool m_publicOverride = false; struct sockaddr_in m_ip4addr; @@ -95,10 +95,10 @@ namespace llarp class NetworkConfig { public: - using NetConfig = std::unordered_multimap< std::string, std::string >; + using NetConfig = std::unordered_multimap; public: - nonstd::optional< bool > m_enableProfiling; + nonstd::optional m_enableProfiling; std::string m_routerProfilesFile = "profiles.dat"; std::string m_strictConnect; NetConfig m_netConfig; @@ -131,7 +131,7 @@ namespace llarp struct DnsConfig { - std::unordered_multimap< std::string, std::string > netConfig; + std::unordered_multimap netConfig; void fromSection(string_view key, string_view val); @@ -140,14 +140,14 @@ namespace llarp class LinksConfig { public: - static constexpr int Interface = 0; + static constexpr int Interface = 0; static constexpr int AddressFamily = 1; - static constexpr int Port = 2; - static constexpr int Options = 3; + static constexpr int Port = 2; + static constexpr int Options = 3; - using ServerOptions = std::unordered_set< std::string >; - using LinkInfo = std::tuple< std::string, int, uint16_t, ServerOptions >; - using Links = std::vector< LinkInfo >; + using ServerOptions = std::unordered_set; + using LinkInfo = std::tuple; + using Links = std::vector; public: LinkInfo m_OutboundLink; @@ -166,7 +166,7 @@ namespace llarp struct ConnectConfig { - std::vector< std::string > routers; + std::vector routers; void fromSection(string_view key, string_view val); @@ -174,7 +174,7 @@ namespace llarp struct ServicesConfig { - std::vector< std::pair< std::string, std::string > > services; + std::vector> services; void fromSection(string_view key, string_view val); }; @@ -190,7 +190,7 @@ namespace llarp class ApiConfig { public: - bool m_enableRPCServer = false; + bool m_enableRPCServer = false; std::string m_rpcBindAddr = "127.0.0.1:1190"; public: @@ -205,9 +205,9 @@ namespace llarp struct LokidConfig { - bool usingSNSeed = false; - bool whitelistRouters = false; - fs::path ident_keyfile = "identity.key"; + bool usingSNSeed = false; + bool whitelistRouters = false; + fs::path ident_keyfile = "identity.key"; std::string lokidRPCAddr = "127.0.0.1:22023"; std::string lokidRPCUser; std::string lokidRPCPassword; @@ -218,14 +218,14 @@ namespace llarp struct BootstrapConfig { - std::vector< std::string > routers; + std::vector routers; void fromSection(string_view key, string_view val); }; struct LoggingConfig { - bool m_LogJSON = false; + bool m_LogJSON = false; FILE* m_LogFile = stdout; void @@ -271,8 +271,7 @@ namespace llarp } // namespace llarp void -llarp_generic_ensure_config(std::ofstream& f, std::string basepath, - bool isRouter); +llarp_generic_ensure_config(std::ofstream& f, std::string basepath, bool isRouter); void llarp_ensure_router_config(std::ofstream& f, std::string basepath); diff --git a/llarp/config/ini.cpp b/llarp/config/ini.cpp index 90401b703..0f6ef740e 100644 --- a/llarp/config/ini.cpp +++ b/llarp/config/ini.cpp @@ -15,12 +15,12 @@ namespace llarp std::string name{fname}; { std::ifstream f(name, std::ios::in | std::ios::binary); - if(!f.is_open()) + if (!f.is_open()) return false; f.seekg(0, std::ios::end); m_Data.resize(f.tellg()); f.seekg(0, std::ios::beg); - if(m_Data.size() == 0) + if (m_Data.size() == 0) return false; f.read(m_Data.data(), m_Data.size()); } @@ -47,23 +47,23 @@ namespace llarp static bool whitespace(char ch) { - return std::isspace(static_cast< unsigned char >(ch)) != 0; + return std::isspace(static_cast(ch)) != 0; } bool ConfigParser::Parse() { - std::list< string_view > lines; + std::list lines; { auto itr = m_Data.begin(); // split into lines - while(itr != m_Data.end()) + while (itr != m_Data.end()) { auto beg = itr; - while(itr != m_Data.end() && *itr != '\n' && *itr != '\r') + while (itr != m_Data.end() && *itr != '\n' && *itr != '\r') ++itr; lines.emplace_back(std::addressof(*beg), std::distance(beg, itr)); - if(itr == m_Data.end()) + if (itr == m_Data.end()) break; ++itr; } @@ -71,60 +71,60 @@ namespace llarp string_view sectName; size_t lineno = 0; - for(const auto& line : lines) + for (const auto& line : lines) { lineno++; string_view realLine; auto comment = line.find_first_of(';'); - if(comment == string_view::npos) + if (comment == string_view::npos) comment = line.find_first_of('#'); - if(comment == string_view::npos) + if (comment == string_view::npos) realLine = line; else realLine = line.substr(0, comment); // blank or commented line? - if(realLine.size() == 0) + if (realLine.size() == 0) continue; // find delimiters auto sectOpenPos = realLine.find_first_of('['); auto sectClosPos = realLine.find_first_of(']'); - auto kvDelim = realLine.find_first_of('='); - if(sectOpenPos != string_view::npos && sectClosPos != string_view::npos - && kvDelim == string_view::npos) + auto kvDelim = realLine.find_first_of('='); + if (sectOpenPos != string_view::npos && sectClosPos != string_view::npos + && kvDelim == string_view::npos) { // section header // clamp whitespaces ++sectOpenPos; - while(whitespace(realLine[sectOpenPos]) && sectOpenPos != sectClosPos) + while (whitespace(realLine[sectOpenPos]) && sectOpenPos != sectClosPos) ++sectOpenPos; --sectClosPos; - while(whitespace(realLine[sectClosPos]) && sectClosPos != sectOpenPos) + while (whitespace(realLine[sectClosPos]) && sectClosPos != sectOpenPos) --sectClosPos; // set section name sectName = realLine.substr(sectOpenPos, sectClosPos); } - else if(kvDelim != string_view::npos) + else if (kvDelim != string_view::npos) { // key value pair string_view::size_type k_start = 0; - string_view::size_type k_end = kvDelim; + string_view::size_type k_end = kvDelim; string_view::size_type v_start = kvDelim + 1; - string_view::size_type v_end = realLine.size() - 1; + string_view::size_type v_end = realLine.size() - 1; // clamp whitespaces - while(whitespace(realLine[k_start]) && k_start != kvDelim) + while (whitespace(realLine[k_start]) && k_start != kvDelim) ++k_start; - while(whitespace(realLine[k_end - 1]) && k_end != k_start) + while (whitespace(realLine[k_end - 1]) && k_end != k_start) --k_end; - while(whitespace(realLine[v_start]) && v_start != v_end) + while (whitespace(realLine[v_start]) && v_start != v_end) ++v_start; - while(whitespace(realLine[v_end])) + while (whitespace(realLine[v_end])) --v_end; // sect.k = v string_view k = realLine.substr(k_start, k_end - k_start); string_view v = realLine.substr(v_start, 1 + (v_end - v_start)); - if(k.size() == 0 || v.size() == 0) + if (k.size() == 0 || v.size() == 0) { LogError(m_FileName, " invalid line (", lineno, "): '", line, "'"); return false; @@ -143,20 +143,18 @@ namespace llarp } void - ConfigParser::IterAll( - std::function< void(string_view, const Section_t&) > visit) + ConfigParser::IterAll(std::function visit) { - for(const auto& item : m_Config) + for (const auto& item : m_Config) visit(item.first, item.second); } bool ConfigParser::VisitSection( - const char* name, - std::function< bool(const Section_t& sect) > visit) const + const char* name, std::function visit) const { auto itr = m_Config.find(name); - if(itr == m_Config.end()) + if (itr == m_Config.end()) return false; return visit(itr->second); } diff --git a/llarp/config/ini.hpp b/llarp/config/ini.hpp index 41352c724..0e611264d 100644 --- a/llarp/config/ini.hpp +++ b/llarp/config/ini.hpp @@ -12,8 +12,8 @@ namespace llarp { struct ConfigParser { - using Section_t = std::unordered_multimap< std::string, std::string >; - using Config_impl_t = std::unordered_map< std::string, Section_t >; + using Section_t = std::unordered_multimap; + using Config_impl_t = std::unordered_map; /// clear parser void Clear(); @@ -32,19 +32,18 @@ namespace llarp /// iterate all sections and thier values void - IterAll(std::function< void(string_view, const Section_t&) > visit); + IterAll(std::function visit); /// visit a section in config read only by name /// return false if no section or value propagated from visitor bool - VisitSection(const char* name, - std::function< bool(const Section_t&) > visit) const; + VisitSection(const char* name, std::function visit) const; private: bool Parse(); - std::vector< char > m_Data; + std::vector m_Data; Config_impl_t m_Config; std::string m_FileName; }; diff --git a/llarp/config/key_manager.cpp b/llarp/config/key_manager.cpp index b4c847791..b69b48534 100644 --- a/llarp/config/key_manager.cpp +++ b/llarp/config/key_manager.cpp @@ -14,8 +14,8 @@ static size_t curl_RecvIdentKey(char* ptr, size_t, size_t nmemb, void* userdata) { - for(size_t idx = 0; idx < nmemb; idx++) - static_cast< std::vector< char >* >(userdata)->push_back(ptr[idx]); + for (size_t idx = 0; idx < nmemb; idx++) + static_cast*>(userdata)->push_back(ptr[idx]); return nmemb; } @@ -28,22 +28,22 @@ namespace llarp bool KeyManager::initialize(const llarp::Config& config, bool genIfAbsent) { - if(m_initialized) + if (m_initialized) return false; - m_rcPath = config.router.ourRcFile(); - m_idKeyPath = config.router.identKeyfile(); - m_encKeyPath = config.router.encryptionKeyfile(); + m_rcPath = config.router.ourRcFile(); + m_idKeyPath = config.router.identKeyfile(); + m_encKeyPath = config.router.encryptionKeyfile(); m_transportKeyPath = config.router.transportKeyfile(); - m_usingLokid = config.lokid.whitelistRouters; - m_lokidRPCAddr = config.lokid.lokidRPCAddr; - m_lokidRPCUser = config.lokid.lokidRPCUser; + m_usingLokid = config.lokid.whitelistRouters; + m_lokidRPCAddr = config.lokid.lokidRPCAddr; + m_lokidRPCUser = config.lokid.lokidRPCUser; m_lokidRPCPassword = config.lokid.lokidRPCPassword; RouterContact rc; bool exists = rc.Read(m_rcPath.c_str()); - if(not exists and not genIfAbsent) + if (not exists and not genIfAbsent) { LogError("Could not read RouterContact at path ", m_rcPath); return false; @@ -56,19 +56,21 @@ namespace llarp // if our RC file can't be verified, assume it is out of date (e.g. uses // older encryption) and needs to be regenerated. before doing so, backup // files that will be overwritten - if(exists and m_needBackup) + if (exists and m_needBackup) { - if(!genIfAbsent) + if (!genIfAbsent) { LogError("Our RouterContact ", m_rcPath, " is invalid or out of date"); return false; } else { - LogWarn("Our RouterContact ", m_rcPath, - " seems out of date, backing up and regenerating private keys"); + LogWarn( + "Our RouterContact ", + m_rcPath, + " seems out of date, backing up and regenerating private keys"); - if(!backupKeyFilesByMoving()) + if (!backupKeyFilesByMoving()) { LogError( "Could not mv some key files, please ensure key files" @@ -78,19 +80,19 @@ namespace llarp } } - if(not m_usingLokid) + if (not m_usingLokid) { // load identity key or create if needed auto identityKeygen = [](llarp::SecretKey& key) { // TODO: handle generating from service node seed llarp::CryptoManager::instance()->identity_keygen(key); }; - if(not loadOrCreateKey(m_idKeyPath, identityKey, identityKeygen)) + if (not loadOrCreateKey(m_idKeyPath, identityKey, identityKeygen)) return false; } else { - if(not loadIdentityFromLokid()) + if (not loadIdentityFromLokid()) return false; } @@ -98,7 +100,7 @@ namespace llarp auto encryptionKeygen = [](llarp::SecretKey& key) { llarp::CryptoManager::instance()->encryption_keygen(key); }; - if(not loadOrCreateKey(m_encKeyPath, encryptionKey, encryptionKeygen)) + if (not loadOrCreateKey(m_encKeyPath, encryptionKey, encryptionKeygen)) return false; // TODO: transport key (currently done in LinkLayer) @@ -106,7 +108,7 @@ namespace llarp key.Zero(); CryptoManager::instance()->encryption_keygen(key); }; - if(not loadOrCreateKey(m_transportKeyPath, transportKey, transportKeygen)) + if (not loadOrCreateKey(m_transportKeyPath, transportKey, transportKeygen)) return false; m_initialized = true; @@ -117,13 +119,13 @@ namespace llarp KeyManager::backupFileByMoving(const std::string& filepath) { auto findFreeBackupFilename = [](const fs::path& filepath) { - for(int i = 0; i < 9; i++) + for (int i = 0; i < 9; i++) { std::string ext("." + std::to_string(i) + ".bak"); fs::path newPath = filepath; newPath += ext; - if(not fs::exists(newPath)) + if (not fs::exists(newPath)) return newPath; } return fs::path(); @@ -131,31 +133,29 @@ namespace llarp std::error_code ec; bool exists = fs::exists(filepath, ec); - if(ec) + if (ec) { - LogError("Could not determine status of file ", filepath, ": ", - ec.message()); + LogError("Could not determine status of file ", filepath, ": ", ec.message()); return false; } - if(not exists) + if (not exists) { LogInfo("File ", filepath, " doesn't exist; no backup needed"); return true; } fs::path newFilepath = findFreeBackupFilename(filepath); - if(newFilepath.empty()) + if (newFilepath.empty()) { LogWarn("Could not find an appropriate backup filename for", filepath); return false; } - LogInfo("Backing up (moving) key file ", filepath, " to ", newFilepath, - "..."); + LogInfo("Backing up (moving) key file ", filepath, " to ", newFilepath, "..."); fs::rename(filepath, newFilepath, ec); - if(ec) + if (ec) { LogError("Failed to move key file ", ec.message()); return false; @@ -167,12 +167,11 @@ namespace llarp bool KeyManager::backupKeyFilesByMoving() const { - std::vector< std::string > files = {m_rcPath, m_idKeyPath, m_encKeyPath, - m_transportKeyPath}; + std::vector files = {m_rcPath, m_idKeyPath, m_encKeyPath, m_transportKeyPath}; - for(auto& filepath : files) + for (auto& filepath : files) { - if(not backupFileByMoving(filepath)) + if (not backupFileByMoving(filepath)) return false; } @@ -181,14 +180,15 @@ namespace llarp bool KeyManager::loadOrCreateKey( - const std::string& filepath, llarp::SecretKey& key, - std::function< void(llarp::SecretKey& key) > keygen) + const std::string& filepath, + llarp::SecretKey& key, + std::function keygen) { fs::path path(filepath); std::error_code ec; - if(!fs::exists(path, ec)) + if (!fs::exists(path, ec)) { - if(ec) + if (ec) { LogError("Error checking key", filepath, ec.message()); return false; @@ -197,7 +197,7 @@ namespace llarp LogInfo("Generating new key", filepath); keygen(key); - if(!key.SaveToFile(filepath.c_str())) + if (!key.SaveToFile(filepath.c_str())) { LogError("Failed to save new key"); return false; @@ -216,7 +216,7 @@ namespace llarp return false; #else CURL* curl = curl_easy_init(); - if(curl) + if (curl) { bool ret = false; std::stringstream ss; @@ -230,11 +230,10 @@ namespace llarp list = curl_slist_append(list, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); - nlohmann::json request = {{"id", "0"}, - {"jsonrpc", "2.0"}, - {"method", "get_service_node_privkey"}}; - const auto data = request.dump(); - std::vector< char > resp; + nlohmann::json request = { + {"id", "0"}, {"jsonrpc", "2.0"}, {"method", "get_service_node_privkey"}}; + const auto data = request.dump(); + std::vector resp; curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.size()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); @@ -243,24 +242,23 @@ namespace llarp resp.clear(); LogInfo("Getting Identity Keys from lokid..."); - if(curl_easy_perform(curl) == CURLE_OK) + if (curl_easy_perform(curl) == CURLE_OK) { try { auto j = nlohmann::json::parse(resp); - if(not j.is_object()) + if (not j.is_object()) return false; const auto itr = j.find("result"); - if(itr == j.end()) + if (itr == j.end()) return false; - if(not itr->is_object()) + if (not itr->is_object()) return false; - const auto k = - (*itr)["service_node_ed25519_privkey"].get< std::string >(); - if(k.size() != (identityKey.size() * 2)) + const auto k = (*itr)["service_node_ed25519_privkey"].get(); + if (k.size() != (identityKey.size() * 2)) { - if(k.empty()) + if (k.empty()) { LogError("lokid gave no identity key"); } @@ -270,9 +268,9 @@ namespace llarp } return false; } - if(not HexDecode(k.c_str(), identityKey.data(), identityKey.size())) + if (not HexDecode(k.c_str(), identityKey.data(), identityKey.size())) return false; - if(CryptoManager::instance()->check_identity_privkey(identityKey)) + if (CryptoManager::instance()->check_identity_privkey(identityKey)) { ret = true; } @@ -281,7 +279,7 @@ namespace llarp LogError("lokid gave bogus identity key"); } } - catch(nlohmann::json::exception& ex) + catch (nlohmann::json::exception& ex) { LogError("Bad response from lokid: ", ex.what()); } @@ -290,10 +288,9 @@ namespace llarp { LogError("failed to get identity keys"); } - if(ret) + if (ret) { - LogInfo("Got Identity Keys from lokid: ", - RouterID(seckey_topublic(identityKey))); + LogInfo("Got Identity Keys from lokid: ", RouterID(seckey_topublic(identityKey))); } curl_easy_cleanup(curl); curl_slist_free_all(list); diff --git a/llarp/config/key_manager.hpp b/llarp/config/key_manager.hpp index 6bdfdca77..9c81deacc 100644 --- a/llarp/config/key_manager.hpp +++ b/llarp/config/key_manager.hpp @@ -74,7 +74,7 @@ namespace llarp std::atomic_bool m_initialized; std::atomic_bool m_needBackup; - bool m_usingLokid = false; + bool m_usingLokid = false; std::string m_lokidRPCAddr = "127.0.0.1:22023"; std::string m_lokidRPCUser; std::string m_lokidRPCPassword; @@ -87,8 +87,10 @@ namespace llarp /// /// @param keygen is a function that will generate the key if needed static bool - loadOrCreateKey(const std::string& filepath, llarp::SecretKey& key, - std::function< void(llarp::SecretKey& key) > keygen); + loadOrCreateKey( + const std::string& filepath, + llarp::SecretKey& key, + std::function keygen); /// Requests the identity key from lokid via HTTP (curl) bool diff --git a/llarp/consensus/table.hpp b/llarp/consensus/table.hpp index cfd6bbd02..b16f32a84 100644 --- a/llarp/consensus/table.hpp +++ b/llarp/consensus/table.hpp @@ -9,7 +9,7 @@ namespace llarp namespace consensus { /// consensus table - struct Table : public std::vector< RouterID > + struct Table : public std::vector { ShortHash CalculateHash() const; diff --git a/llarp/constants/link_layer.hpp b/llarp/constants/link_layer.hpp index 5637d6a55..c1231665e 100644 --- a/llarp/constants/link_layer.hpp +++ b/llarp/constants/link_layer.hpp @@ -5,7 +5,7 @@ #include -constexpr size_t MAX_LINK_MSG_SIZE = 8192; +constexpr size_t MAX_LINK_MSG_SIZE = 8192; static constexpr auto DefaultLinkSessionLifetime = 1min; -constexpr size_t MaxSendQueueSize = 1024; +constexpr size_t MaxSendQueueSize = 1024; #endif diff --git a/llarp/constants/path.hpp b/llarp/constants/path.hpp index b95aed8f1..d81281abe 100644 --- a/llarp/constants/path.hpp +++ b/llarp/constants/path.hpp @@ -20,11 +20,9 @@ namespace llarp /// default path lifetime in ms constexpr std::chrono::milliseconds default_lifetime = 20min; /// minimum into lifetime we will advertise - constexpr std::chrono::milliseconds min_intro_lifetime = - default_lifetime / 2; + constexpr std::chrono::milliseconds min_intro_lifetime = default_lifetime / 2; /// spacing frequency at which we try to build paths for introductions - constexpr std::chrono::milliseconds intro_path_spread = - default_lifetime / 5; + constexpr std::chrono::milliseconds intro_path_spread = default_lifetime / 5; /// 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). diff --git a/llarp/constants/version.h b/llarp/constants/version.h index 3434517c6..30893701e 100644 --- a/llarp/constants/version.h +++ b/llarp/constants/version.h @@ -13,8 +13,7 @@ #endif #if defined(_WIN32) && defined(RC_INVOKED) -#define LLARP_VERSION \ - LLARP_VERSION_MAJOR, LLARP_VERSION_MINOR, LLARP_VERSION_PATCH, 0 +#define LLARP_VERSION LLARP_VERSION_MAJOR, LLARP_VERSION_MINOR, LLARP_VERSION_PATCH, 0 #define MAKE_TRIPLET(X, Y, Z) TRIPLET_CAT(X, ., Y, ., Z) #define TRIPLET_CAT(X, D1, Y, D2, Z) X##D1##Y##D2##Z diff --git a/llarp/constants/version.hpp b/llarp/constants/version.hpp index 2b8d4a60b..2cdfc7760 100644 --- a/llarp/constants/version.hpp +++ b/llarp/constants/version.hpp @@ -6,11 +6,11 @@ namespace llarp { // Given a full lokinet version of: lokinet-1.2.3-abc these are: - extern const std::array< uint16_t, 3 > VERSION; // [1, 2, 3] - extern const std::array< uint64_t, 4 > ROUTER_VERSION; // [proto, 1, 2, 3] - extern const char* const VERSION_STR; // "1.2.3" - extern const char* const VERSION_TAG; // "abc" - extern const char* const VERSION_FULL; // "lokinet-1.2.3-abc" + extern const std::array VERSION; // [1, 2, 3] + extern const std::array ROUTER_VERSION; // [proto, 1, 2, 3] + extern const char* const VERSION_STR; // "1.2.3" + extern const char* const VERSION_TAG; // "abc" + extern const char* const VERSION_FULL; // "lokinet-1.2.3-abc" extern const char* const RELEASE_MOTTO; extern const char* const DEFAULT_NETID; diff --git a/llarp/context.cpp b/llarp/context.cpp index ca31bc15f..da3bdc8bf 100644 --- a/llarp/context.cpp +++ b/llarp/context.cpp @@ -15,14 +15,14 @@ #include #include -#if(__FreeBSD__) || (__OpenBSD__) || (__NetBSD__) +#if (__FreeBSD__) || (__OpenBSD__) || (__NetBSD__) #include #endif namespace llarp { bool - Context::CallSafe(std::function< void(void) > f) + Context::CallSafe(std::function f) { return logic && LogicCall(logic, f); } @@ -31,9 +31,9 @@ namespace llarp Context::Configure() { // llarp::LogInfo("loading config at ", configfile); - if(configfile.size()) + if (configfile.size()) { - if(!config->Load(configfile.c_str())) + if (!config->Load(configfile.c_str())) { config.release(); llarp::LogError("failed to load config file ", configfile); @@ -42,19 +42,18 @@ namespace llarp } // System config - if(!config->system.pidfile.empty()) + if (!config->system.pidfile.empty()) { SetPIDFile(config->system.pidfile); } auto threads = config->router.workerThreads(); - if(threads <= 0) + if (threads <= 0) threads = 1; - worker = std::make_shared< llarp::thread::ThreadPool >(threads, 1024, - "llarp-worker"); + worker = std::make_shared(threads, 1024, "llarp-worker"); auto jobQueueSize = config->router.jobQueueSize(); - if(jobQueueSize < 1024) + if (jobQueueSize < 1024) jobQueueSize = 1024; - logic = std::make_shared< Logic >(jobQueueSize); + logic = std::make_shared(jobQueueSize); nodedb_dir = config->netdb.nodedbDir(); @@ -62,7 +61,7 @@ namespace llarp } void - Context::SetPIDFile(const std::string &fname) + Context::SetPIDFile(const std::string& fname) { pidfile = fname; } @@ -82,7 +81,7 @@ namespace llarp int Context::LoadDatabase() { - if(!llarp_nodedb::ensure_dir(nodedb_dir.c_str())) + if (!llarp_nodedb::ensure_dir(nodedb_dir.c_str())) { llarp::LogError("nodedb_dir is incorrect"); return 0; @@ -95,20 +94,20 @@ namespace llarp { llarp::LogInfo(llarp::VERSION_FULL, " ", llarp::RELEASE_MOTTO); llarp::LogInfo("starting up"); - if(mainloop == nullptr) + if (mainloop == nullptr) mainloop = llarp_make_ev_loop(); logic->set_event_loop(mainloop.get()); mainloop->set_logic(logic); - crypto = std::make_unique< sodium::CryptoLibSodium >(); - cryptoManager = std::make_unique< CryptoManager >(crypto.get()); + crypto = std::make_unique(); + cryptoManager = std::make_unique(crypto.get()); - router = std::make_unique< Router >(worker, mainloop, logic); + router = std::make_unique(worker, mainloop, logic); - nodedb = std::make_unique< llarp_nodedb >(router->diskworker(), nodedb_dir); + nodedb = std::make_unique(router->diskworker(), nodedb_dir); - if(!router->Configure(config.get(), nodedb.get())) + if (!router->Configure(config.get(), nodedb.get())) { llarp::LogError("Failed to configure router"); return 1; @@ -117,7 +116,7 @@ namespace llarp // must be done after router is made so we can use its disk io worker // must also be done after configure so that netid is properly set if it // is provided by config - if(!this->LoadDatabase()) + if (!this->LoadDatabase()) return 1; return 0; @@ -126,21 +125,21 @@ namespace llarp int Context::Run(llarp_main_runtime_opts opts) { - if(router == nullptr) + if (router == nullptr) { // we are not set up so we should die llarp::LogError("cannot run non configured context"); return 1; } - if(!WritePIDFile()) + if (!WritePIDFile()) return 1; // run - if(!router->StartJsonRpc()) + if (!router->StartJsonRpc()) return 1; - if(!opts.background) + if (!opts.background) { - if(!router->Run()) + if (!router->Run()) return 2; } @@ -148,7 +147,7 @@ namespace llarp llarp::LogInfo("running mainloop"); llarp_ev_loop_run_single_process(mainloop, logic); - if(closeWaiter) + if (closeWaiter) { // inform promise if called by CloseAsync closeWaiter->set_value(); @@ -160,16 +159,16 @@ namespace llarp Context::CloseAsync() { /// already closing - if(closeWaiter) + if (closeWaiter) return; - if(CallSafe(std::bind(&Context::HandleSignal, this, SIGTERM))) - closeWaiter = std::make_unique< std::promise< void > >(); + if (CallSafe(std::bind(&Context::HandleSignal, this, SIGTERM))) + closeWaiter = std::make_unique>(); } void Context::Wait() { - if(closeWaiter) + if (closeWaiter) { closeWaiter->get_future().wait(); closeWaiter.reset(); @@ -179,7 +178,7 @@ namespace llarp bool Context::WritePIDFile() const { - if(pidfile.size()) + if (pidfile.size()) { std::ofstream f(pidfile); f << std::to_string(getpid()); @@ -192,13 +191,13 @@ namespace llarp void Context::RemovePIDFile() const { - if(pidfile.size()) + if (pidfile.size()) { fs::path f = pidfile; std::error_code ex; - if(fs::exists(f, ex)) + if (fs::exists(f, ex)) { - if(!ex) + if (!ex) fs::remove(f); } } @@ -207,39 +206,38 @@ namespace llarp void Context::HandleSignal(int sig) { - if(sig == SIGINT || sig == SIGTERM) + if (sig == SIGINT || sig == SIGTERM) { SigINT(); } // TODO(despair): implement hot-reloading config on NT #ifndef _WIN32 - if(sig == SIGHUP) + if (sig == SIGHUP) { llarp::LogInfo("SIGHUP"); - if(router) + if (router) { router->hiddenServiceContext().ForEachService( - [](const std::string &name, - const llarp::service::Endpoint_ptr &ep) -> bool { + [](const std::string& name, const llarp::service::Endpoint_ptr& ep) -> bool { ep->ResetInternalState(); llarp::LogInfo("Reset internal state for ", name); return true; }); router->PumpLL(); Config newconfig; - if(!newconfig.Load(configfile.c_str())) + if (!newconfig.Load(configfile.c_str())) { llarp::LogError("failed to load config file ", configfile); return; } // validate config - if(!router->ValidateConfig(&newconfig)) + if (!router->ValidateConfig(&newconfig)) { llarp::LogWarn("new configuration is invalid"); return; } // reconfigure - if(!router->Reconfigure(&newconfig)) + if (!router->Reconfigure(&newconfig)) { llarp::LogError("Failed to reconfigure so we will stop."); router->Stop(); @@ -254,14 +252,14 @@ namespace llarp void Context::SigINT() { - if(router) + if (router) { /// async stop router on sigint router->Stop(); } else { - if(logic) + if (logic) logic->stop(); llarp_ev_loop_stop(mainloop); Close(); @@ -272,7 +270,7 @@ namespace llarp Context::Close() { llarp::LogDebug("stop workers"); - if(worker) + if (worker) worker->stop(); llarp::LogDebug("free config"); @@ -294,16 +292,16 @@ namespace llarp } bool - Context::LoadConfig(const std::string &fname) + Context::LoadConfig(const std::string& fname) { - config = std::make_unique< Config >(); + config = std::make_unique(); configfile = fname; return Configure(); } #ifdef LOKINET_HIVE void - Context::InjectHive(tooling::RouterHive *hive) + Context::InjectHive(tooling::RouterHive* hive) { router->hive = hive; } @@ -312,9 +310,9 @@ namespace llarp struct llarp_main { - llarp_main(llarp_config *conf); + llarp_main(llarp_config* conf); ~llarp_main() = default; - std::shared_ptr< llarp::Context > ctx; + std::shared_ptr ctx; }; struct llarp_config @@ -322,18 +320,18 @@ struct llarp_config llarp::Config impl; llarp_config() = default; - llarp_config(const llarp_config *other) : impl(other->impl) + llarp_config(const llarp_config* other) : impl(other->impl) { } }; namespace llarp { - llarp_config * + llarp_config* Config::Copy() const { - llarp_config *ptr = new llarp_config(); - ptr->impl = *this; + llarp_config* ptr = new llarp_config(); + ptr->impl = *this; return ptr; } } // namespace llarp @@ -352,10 +350,10 @@ extern "C" return sizeof(llarp_config); } - struct llarp_config * + struct llarp_config* llarp_default_config() { - llarp_config *conf = new llarp_config(); + llarp_config* conf = new llarp_config(); #ifdef ANDROID // put andrid config overrides here #endif @@ -366,37 +364,37 @@ extern "C" } void - llarp_config_free(struct llarp_config *conf) + llarp_config_free(struct llarp_config* conf) { - if(conf) + if (conf) delete conf; } - struct llarp_main * - llarp_main_init_from_config(struct llarp_config *conf) + struct llarp_main* + llarp_main_init_from_config(struct llarp_config* conf) { - if(conf == nullptr) + if (conf == nullptr) return nullptr; - llarp_main *m = new llarp_main(conf); - if(m->ctx->Configure()) + llarp_main* m = new llarp_main(conf); + if (m->ctx->Configure()) return m; delete m; return nullptr; } bool - llarp_config_read_file(struct llarp_config *conf, const char *fname) + llarp_config_read_file(struct llarp_config* conf, const char* fname) { - if(conf == nullptr) + if (conf == nullptr) return false; return conf->impl.Load(fname); } bool - llarp_config_load_file(const char *fname, struct llarp_config **conf) + llarp_config_load_file(const char* fname, struct llarp_config** conf) { - llarp_config *c = new llarp_config(); - if(c->impl.Load(fname)) + llarp_config* c = new llarp_config(); + if (c->impl.Load(fname)) { *conf = c; return true; @@ -407,137 +405,135 @@ extern "C" } void - llarp_main_signal(struct llarp_main *ptr, int sig) + llarp_main_signal(struct llarp_main* ptr, int sig) { - LogicCall(ptr->ctx->logic, - std::bind(&llarp::Context::HandleSignal, ptr->ctx.get(), sig)); + LogicCall(ptr->ctx->logic, std::bind(&llarp::Context::HandleSignal, ptr->ctx.get(), sig)); } int - llarp_main_setup(struct llarp_main *ptr) + llarp_main_setup(struct llarp_main* ptr) { return ptr->ctx->Setup(); } int - llarp_main_run(struct llarp_main *ptr, struct llarp_main_runtime_opts opts) + llarp_main_run(struct llarp_main* ptr, struct llarp_main_runtime_opts opts) { return ptr->ctx->Run(opts); } - const char * + const char* llarp_version() { return llarp::VERSION_FULL; } ssize_t - llarp_vpn_io_readpkt(struct llarp_vpn_pkt_reader *r, unsigned char *dst, - size_t dstlen) + llarp_vpn_io_readpkt(struct llarp_vpn_pkt_reader* r, unsigned char* dst, size_t dstlen) { - if(r == nullptr) + if (r == nullptr) return -1; - if(not r->queue.enabled()) + if (not r->queue.enabled()) return -1; - auto pkt = r->queue.popFront(); - ManagedBuffer mbuf = pkt.ConstBuffer(); - const llarp_buffer_t &buf = mbuf; - if(buf.sz > dstlen || buf.sz == 0) + auto pkt = r->queue.popFront(); + ManagedBuffer mbuf = pkt.ConstBuffer(); + const llarp_buffer_t& buf = mbuf; + if (buf.sz > dstlen || buf.sz == 0) return -1; std::copy_n(buf.base, buf.sz, dst); return buf.sz; } bool - llarp_vpn_io_writepkt(struct llarp_vpn_pkt_writer *w, unsigned char *pktbuf, - size_t pktlen) + llarp_vpn_io_writepkt(struct llarp_vpn_pkt_writer* w, unsigned char* pktbuf, size_t pktlen) { - if(pktlen == 0 || pktbuf == nullptr) + if (pktlen == 0 || pktbuf == nullptr) return false; - if(w == nullptr) + if (w == nullptr) return false; llarp_vpn_pkt_queue::Packet_t pkt; llarp_buffer_t buf(pktbuf, pktlen); - if(not pkt.Load(buf)) + if (not pkt.Load(buf)) return false; - return w->queue.pushBack(std::move(pkt)) - == llarp::thread::QueueReturn::Success; + return w->queue.pushBack(std::move(pkt)) == llarp::thread::QueueReturn::Success; } bool - llarp_main_inject_vpn_by_name(struct llarp_main *ptr, const char *name, - struct llarp_vpn_io *io, - struct llarp_vpn_ifaddr_info info) + llarp_main_inject_vpn_by_name( + struct llarp_main* ptr, + const char* name, + struct llarp_vpn_io* io, + struct llarp_vpn_ifaddr_info info) { - if(name == nullptr || io == nullptr) + if (name == nullptr || io == nullptr) return false; - if(ptr == nullptr || ptr->ctx == nullptr || ptr->ctx->router == nullptr) + if (ptr == nullptr || ptr->ctx == nullptr || ptr->ctx->router == nullptr) return false; auto ep = ptr->ctx->router->hiddenServiceContext().GetEndpointByName(name); return ep && ep->InjectVPN(io, info); } void - llarp_vpn_io_close_async(struct llarp_vpn_io *io) + llarp_vpn_io_close_async(struct llarp_vpn_io* io) { - if(io == nullptr || io->impl == nullptr) + if (io == nullptr || io->impl == nullptr) return; - static_cast< llarp_vpn_io_impl * >(io->impl)->AsyncClose(); + static_cast(io->impl)->AsyncClose(); } bool - llarp_vpn_io_init(struct llarp_main *ptr, struct llarp_vpn_io *io) + llarp_vpn_io_init(struct llarp_main* ptr, struct llarp_vpn_io* io) { - if(io == nullptr || ptr == nullptr) + if (io == nullptr || ptr == nullptr) return false; - llarp_vpn_io_impl *impl = new llarp_vpn_io_impl(ptr, io); - io->impl = impl; + llarp_vpn_io_impl* impl = new llarp_vpn_io_impl(ptr, io); + io->impl = impl; return true; } - struct llarp_vpn_pkt_writer * - llarp_vpn_io_packet_writer(struct llarp_vpn_io *io) + struct llarp_vpn_pkt_writer* + llarp_vpn_io_packet_writer(struct llarp_vpn_io* io) { - if(io == nullptr || io->impl == nullptr) + if (io == nullptr || io->impl == nullptr) return nullptr; - llarp_vpn_io_impl *vpn = static_cast< llarp_vpn_io_impl * >(io->impl); + llarp_vpn_io_impl* vpn = static_cast(io->impl); return &vpn->writer; } - struct llarp_vpn_pkt_reader * - llarp_vpn_io_packet_reader(struct llarp_vpn_io *io) + struct llarp_vpn_pkt_reader* + llarp_vpn_io_packet_reader(struct llarp_vpn_io* io) { - if(io == nullptr || io->impl == nullptr) + if (io == nullptr || io->impl == nullptr) return nullptr; - llarp_vpn_io_impl *vpn = static_cast< llarp_vpn_io_impl * >(io->impl); + llarp_vpn_io_impl* vpn = static_cast(io->impl); return &vpn->reader; } void - llarp_main_free(struct llarp_main *ptr) + llarp_main_free(struct llarp_main* ptr) { delete ptr; } - const char * - llarp_main_get_default_endpoint_name(struct llarp_main *) + const char* + llarp_main_get_default_endpoint_name(struct llarp_main*) { return "default"; } void - llarp_main_stop(struct llarp_main *ptr) + llarp_main_stop(struct llarp_main* ptr) { - if(ptr == nullptr) + if (ptr == nullptr) return; ptr->ctx->CloseAsync(); ptr->ctx->Wait(); } bool - llarp_main_configure(struct llarp_main *ptr, struct llarp_config *conf) + llarp_main_configure(struct llarp_main* ptr, struct llarp_config* conf) { - if(ptr == nullptr || conf == nullptr) + if (ptr == nullptr || conf == nullptr) return false; // give new config ptr->ctx->config.reset(new llarp::Config(conf->impl)); @@ -545,13 +541,13 @@ extern "C" } bool - llarp_main_is_running(struct llarp_main *ptr) + llarp_main_is_running(struct llarp_main* ptr) { return ptr && ptr->ctx->router && ptr->ctx->router->IsRunning(); } } -llarp_main::llarp_main(llarp_config *conf) +llarp_main::llarp_main(llarp_config* conf) : ctx(new llarp::Context()) { @@ -560,10 +556,10 @@ llarp_main::llarp_main(llarp_config *conf) namespace llarp { - std::shared_ptr< Context > - Context::Get(llarp_main *m) + std::shared_ptr + Context::Get(llarp_main* m) { - if(m == nullptr || m->ctx == nullptr) + if (m == nullptr || m->ctx == nullptr) return nullptr; return m->ctx; } diff --git a/llarp/crypto/constants.hpp b/llarp/crypto/constants.hpp index d0331f279..b5101f05c 100644 --- a/llarp/crypto/constants.hpp +++ b/llarp/crypto/constants.hpp @@ -5,21 +5,21 @@ #include -static constexpr uint32_t PUBKEYSIZE = 32; -static constexpr uint32_t SECKEYSIZE = 64; -static constexpr uint32_t NONCESIZE = 24; +static constexpr uint32_t PUBKEYSIZE = 32; +static constexpr uint32_t SECKEYSIZE = 64; +static constexpr uint32_t NONCESIZE = 24; static constexpr uint32_t SHAREDKEYSIZE = 32; -static constexpr uint32_t HASHSIZE = 64; +static constexpr uint32_t HASHSIZE = 64; static constexpr uint32_t SHORTHASHSIZE = 32; -static constexpr uint32_t HMACSECSIZE = 32; -static constexpr uint32_t SIGSIZE = 64; -static constexpr uint32_t TUNNONCESIZE = 32; -static constexpr uint32_t HMACSIZE = 32; -static constexpr uint32_t PATHIDSIZE = 16; +static constexpr uint32_t HMACSECSIZE = 32; +static constexpr uint32_t SIGSIZE = 64; +static constexpr uint32_t TUNNONCESIZE = 32; +static constexpr uint32_t HMACSIZE = 32; +static constexpr uint32_t PATHIDSIZE = 16; static constexpr uint32_t PQ_CIPHERTEXTSIZE = crypto_kem_CIPHERTEXTBYTES; -static constexpr uint32_t PQ_PUBKEYSIZE = crypto_kem_PUBLICKEYBYTES; -static constexpr uint32_t PQ_SECRETKEYSIZE = crypto_kem_SECRETKEYBYTES; +static constexpr uint32_t PQ_PUBKEYSIZE = crypto_kem_PUBLICKEYBYTES; +static constexpr uint32_t PQ_SECRETKEYSIZE = crypto_kem_SECRETKEYBYTES; static constexpr uint32_t PQ_KEYPAIRSIZE = (PQ_SECRETKEYSIZE + PQ_PUBKEYSIZE); #endif diff --git a/llarp/crypto/crypto.hpp b/llarp/crypto/crypto.hpp index 096b57515..400e6bb64 100644 --- a/llarp/crypto/crypto.hpp +++ b/llarp/crypto/crypto.hpp @@ -26,83 +26,77 @@ namespace llarp /// xchacha symmetric cipher virtual bool - xchacha20(const llarp_buffer_t &, const SharedSecret &, - const TunnelNonce &) = 0; + xchacha20(const llarp_buffer_t&, const SharedSecret&, const TunnelNonce&) = 0; /// xchacha symmetric cipher (multibuffer) virtual bool - xchacha20_alt(const llarp_buffer_t &, const llarp_buffer_t &, - const SharedSecret &, const byte_t *) = 0; + xchacha20_alt( + const llarp_buffer_t&, const llarp_buffer_t&, const SharedSecret&, const byte_t*) = 0; /// path dh creator's side virtual bool - dh_client(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) = 0; + dh_client(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) = 0; /// path dh relay side virtual bool - dh_server(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) = 0; + dh_server(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) = 0; /// transport dh client side virtual bool - transport_dh_client(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) = 0; + transport_dh_client(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) = 0; /// transport dh server side virtual bool - transport_dh_server(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) = 0; + transport_dh_server(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) = 0; /// blake2b 256 bit virtual bool - shorthash(ShortHash &, const llarp_buffer_t &) = 0; + shorthash(ShortHash&, const llarp_buffer_t&) = 0; /// blake2s 256 bit "hmac" (keyed hash) virtual bool - hmac(byte_t *, const llarp_buffer_t &, const SharedSecret &) = 0; + hmac(byte_t*, const llarp_buffer_t&, const SharedSecret&) = 0; /// ed25519 sign virtual bool - sign(Signature &, const SecretKey &, const llarp_buffer_t &) = 0; + sign(Signature&, const SecretKey&, const llarp_buffer_t&) = 0; /// ed25519 sign (custom with derived keys) virtual bool - sign(Signature &, const PrivateKey &, const llarp_buffer_t &) = 0; + sign(Signature&, const PrivateKey&, const llarp_buffer_t&) = 0; /// ed25519 verify virtual bool - verify(const PubKey &, const llarp_buffer_t &, const Signature &) = 0; + verify(const PubKey&, const llarp_buffer_t&, const Signature&) = 0; /// derive sub keys for public keys virtual bool - derive_subkey(PubKey &, const PubKey &, uint64_t, - const AlignedBuffer< 32 > * = nullptr) = 0; + derive_subkey(PubKey&, const PubKey&, uint64_t, const AlignedBuffer<32>* = nullptr) = 0; /// derive sub keys for private keys virtual bool - derive_subkey_private(PrivateKey &, const SecretKey &, uint64_t, - const AlignedBuffer< 32 > * = nullptr) = 0; + derive_subkey_private( + PrivateKey&, const SecretKey&, uint64_t, const AlignedBuffer<32>* = nullptr) = 0; /// seed to secretkey virtual bool - seed_to_secretkey(llarp::SecretKey &, const llarp::IdentitySecret &) = 0; + seed_to_secretkey(llarp::SecretKey&, const llarp::IdentitySecret&) = 0; /// randomize buffer virtual void - randomize(const llarp_buffer_t &) = 0; + randomize(const llarp_buffer_t&) = 0; /// randomizer memory virtual void - randbytes(byte_t *, size_t) = 0; + randbytes(byte_t*, size_t) = 0; /// generate signing keypair virtual void - identity_keygen(SecretKey &) = 0; + identity_keygen(SecretKey&) = 0; /// generate encryption keypair virtual void - encryption_keygen(SecretKey &) = 0; + encryption_keygen(SecretKey&) = 0; /// generate post quantum encrytion key virtual void - pqe_keygen(PQKeyPair &) = 0; + pqe_keygen(PQKeyPair&) = 0; /// post quantum decrypt (buffer, sharedkey_dst, sec) virtual bool - pqe_decrypt(const PQCipherBlock &, SharedSecret &, const byte_t *) = 0; + pqe_decrypt(const PQCipherBlock&, SharedSecret&, const byte_t*) = 0; /// post quantum encrypt (buffer, sharedkey_dst, pub) virtual bool - pqe_encrypt(PQCipherBlock &, SharedSecret &, const PQPubKey &) = 0; + pqe_encrypt(PQCipherBlock&, SharedSecret&, const PQPubKey&) = 0; virtual bool - check_identity_privkey(const SecretKey &) = 0; + check_identity_privkey(const SecretKey&) = 0; }; inline Crypto::~Crypto() = default; @@ -111,24 +105,24 @@ namespace llarp uint64_t randint(); - const byte_t * - seckey_topublic(const SecretKey &secret); + const byte_t* + seckey_topublic(const SecretKey& secret); - const byte_t * - pq_keypair_to_public(const PQKeyPair &keypair); + const byte_t* + pq_keypair_to_public(const PQKeyPair& keypair); - const byte_t * - pq_keypair_to_secret(const PQKeyPair &keypair); + const byte_t* + pq_keypair_to_secret(const PQKeyPair& keypair); struct CryptoManager { private: - static Crypto *m_crypto; + static Crypto* m_crypto; - Crypto *m_prevCrypto; + Crypto* m_prevCrypto; public: - CryptoManager(Crypto *crypto) : m_prevCrypto(m_crypto) + CryptoManager(Crypto* crypto) : m_prevCrypto(m_crypto) { m_crypto = crypto; } @@ -138,13 +132,13 @@ namespace llarp m_crypto = m_prevCrypto; } - static Crypto * + static Crypto* instance() { #ifdef NDEBUG return m_crypto; #else - if(m_crypto) + if (m_crypto) return m_crypto; assert(false && "Cryptomanager::instance() was undefined"); diff --git a/llarp/crypto/crypto_libsodium.cpp b/llarp/crypto/crypto_libsodium.cpp index eb5e7eacd..b7eb38032 100644 --- a/llarp/crypto/crypto_libsodium.cpp +++ b/llarp/crypto/crypto_libsodium.cpp @@ -23,13 +23,16 @@ namespace llarp namespace sodium { static bool - dh(llarp::SharedSecret &out, const PubKey &client_pk, - const PubKey &server_pk, const uint8_t *themPub, const SecretKey &usSec) + dh(llarp::SharedSecret& out, + const PubKey& client_pk, + const PubKey& server_pk, + const uint8_t* themPub, + const SecretKey& usSec) { llarp::SharedSecret shared; crypto_generichash_state h; - if(crypto_scalarmult_curve25519(shared.data(), usSec.data(), themPub)) + if (crypto_scalarmult_curve25519(shared.data(), usSec.data(), themPub)) { return false; } @@ -42,15 +45,14 @@ namespace llarp } static bool - dh_client_priv(llarp::SharedSecret &shared, const PubKey &pk, - const SecretKey &sk, const TunnelNonce &n) + dh_client_priv( + llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n) { llarp::SharedSecret dh_result; - if(dh(dh_result, sk.toPublic(), pk, pk.data(), sk)) + if (dh(dh_result, sk.toPublic(), pk, pk.data(), sk)) { - return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, - dh_result.data(), 32) + return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32) != -1; } llarp::LogWarn("crypto::dh_client - dh failed"); @@ -58,14 +60,13 @@ namespace llarp } static bool - dh_server_priv(llarp::SharedSecret &shared, const PubKey &pk, - const SecretKey &sk, const TunnelNonce &n) + dh_server_priv( + llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n) { llarp::SharedSecret dh_result; - if(dh(dh_result, pk, sk.toPublic(), pk.data(), sk)) + if (dh(dh_result, pk, sk.toPublic(), pk.data(), sk)) { - return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, - dh_result.data(), 32) + return crypto_generichash_blake2b(shared.data(), 32, n.data(), 32, dh_result.data(), 32) != -1; } llarp::LogWarn("crypto::dh_server - dh failed"); @@ -74,12 +75,12 @@ namespace llarp CryptoLibSodium::CryptoLibSodium() { - if(sodium_init() == -1) + if (sodium_init() == -1) { throw std::runtime_error("sodium_init() returned -1"); } - char *avx2 = std::getenv("AVX2_FORCE_DISABLE"); - if(avx2 && std::string(avx2) == "1") + char* avx2 = std::getenv("AVX2_FORCE_DISABLE"); + if (avx2 && std::string(avx2) == "1") { ntru_init(1); } @@ -88,97 +89,84 @@ namespace llarp ntru_init(0); } int seed = 0; - randombytes(reinterpret_cast< unsigned char * >(&seed), sizeof(seed)); + randombytes(reinterpret_cast(&seed), sizeof(seed)); srand(seed); } bool - CryptoLibSodium::xchacha20(const llarp_buffer_t &buff, - const SharedSecret &k, const TunnelNonce &n) + CryptoLibSodium::xchacha20( + const llarp_buffer_t& buff, const SharedSecret& k, const TunnelNonce& n) { - return crypto_stream_xchacha20_xor(buff.base, buff.base, buff.sz, - n.data(), k.data()) - == 0; + return crypto_stream_xchacha20_xor(buff.base, buff.base, buff.sz, n.data(), k.data()) == 0; } bool - CryptoLibSodium::xchacha20_alt(const llarp_buffer_t &out, - const llarp_buffer_t &in, - const SharedSecret &k, const byte_t *n) + CryptoLibSodium::xchacha20_alt( + const llarp_buffer_t& out, const llarp_buffer_t& in, const SharedSecret& k, const byte_t* n) { - if(in.sz > out.sz) + if (in.sz > out.sz) return false; - return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, k.data()) - == 0; + return crypto_stream_xchacha20_xor(out.base, in.base, in.sz, n, k.data()) == 0; } bool - CryptoLibSodium::dh_client(llarp::SharedSecret &shared, const PubKey &pk, - const SecretKey &sk, const TunnelNonce &n) + CryptoLibSodium::dh_client( + llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n) { return dh_client_priv(shared, pk, sk, n); } /// path dh relay side bool - CryptoLibSodium::dh_server(llarp::SharedSecret &shared, const PubKey &pk, - const SecretKey &sk, const TunnelNonce &n) + CryptoLibSodium::dh_server( + llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n) { return dh_server_priv(shared, pk, sk, n); } /// transport dh client side bool - CryptoLibSodium::transport_dh_client(llarp::SharedSecret &shared, - const PubKey &pk, const SecretKey &sk, - const TunnelNonce &n) + CryptoLibSodium::transport_dh_client( + llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n) { return dh_client_priv(shared, pk, sk, n); } /// transport dh server side bool - CryptoLibSodium::transport_dh_server(llarp::SharedSecret &shared, - const PubKey &pk, const SecretKey &sk, - const TunnelNonce &n) + CryptoLibSodium::transport_dh_server( + llarp::SharedSecret& shared, const PubKey& pk, const SecretKey& sk, const TunnelNonce& n) { return dh_server_priv(shared, pk, sk, n); } bool - CryptoLibSodium::shorthash(ShortHash &result, const llarp_buffer_t &buff) + CryptoLibSodium::shorthash(ShortHash& result, const llarp_buffer_t& buff) { - return crypto_generichash_blake2b(result.data(), ShortHash::SIZE, - buff.base, buff.sz, nullptr, 0) + return crypto_generichash_blake2b( + result.data(), ShortHash::SIZE, buff.base, buff.sz, nullptr, 0) != -1; } bool - CryptoLibSodium::hmac(byte_t *result, const llarp_buffer_t &buff, - const SharedSecret &secret) + CryptoLibSodium::hmac(byte_t* result, const llarp_buffer_t& buff, const SharedSecret& secret) { - return crypto_generichash_blake2b(result, HMACSIZE, buff.base, buff.sz, - secret.data(), HMACSECSIZE) + return crypto_generichash_blake2b( + result, HMACSIZE, buff.base, buff.sz, secret.data(), HMACSECSIZE) != -1; } static bool - hash(uint8_t *result, const llarp_buffer_t &buff) + hash(uint8_t* result, const llarp_buffer_t& buff) { - return crypto_generichash_blake2b(result, HASHSIZE, buff.base, buff.sz, - nullptr, 0) - != -1; + return crypto_generichash_blake2b(result, HASHSIZE, buff.base, buff.sz, nullptr, 0) != -1; } bool - CryptoLibSodium::sign(Signature &sig, const SecretKey &secret, - const llarp_buffer_t &buf) + CryptoLibSodium::sign(Signature& sig, const SecretKey& secret, const llarp_buffer_t& buf) { - return crypto_sign_detached(sig.data(), nullptr, buf.base, buf.sz, - secret.data()) - != -1; + return crypto_sign_detached(sig.data(), nullptr, buf.base, buf.sz, secret.data()) != -1; } bool - CryptoLibSodium::sign(Signature &sig, const PrivateKey &privkey, - const llarp_buffer_t &buf) + CryptoLibSodium::sign(Signature& sig, const PrivateKey& privkey, const llarp_buffer_t& buf) { PubKey pubkey; @@ -222,35 +210,32 @@ namespace llarp } bool - CryptoLibSodium::verify(const PubKey &pub, const llarp_buffer_t &buf, - const Signature &sig) + CryptoLibSodium::verify(const PubKey& pub, const llarp_buffer_t& buf, const Signature& sig) { - return crypto_sign_verify_detached(sig.data(), buf.base, buf.sz, - pub.data()) - != -1; + return crypto_sign_verify_detached(sig.data(), buf.base, buf.sz, pub.data()) != -1; } /// clamp a 32 byte ec point static void - clamp_ed25519(byte_t *out) + clamp_ed25519(byte_t* out) { out[0] &= 248; out[31] &= 127; out[31] |= 64; } - template < typename K > + template static K - clamp(const K &p) + clamp(const K& p) { K out = p; clamp_ed25519(out); return out; } - template < typename K > + template static bool - is_clamped(const K &key) + is_clamped(const K& key) { K other(key); clamp_ed25519(other.data()); @@ -262,11 +247,12 @@ namespace llarp "can't in the and by be or then before so just face it this text hurts " "to read? lokinet yolo!"; - template < typename K > - static bool make_scalar(AlignedBuffer< 32 > &out, const K &k, uint64_t i) + template + static bool + make_scalar(AlignedBuffer<32>& out, const K& k, uint64_t i) { // b = BLIND-STRING || k || i - std::array< byte_t, 160 + K::SIZE + sizeof(uint64_t) > buf; + std::array buf; std::copy(derived_key_hash_str, derived_key_hash_str + 160, buf.begin()); std::copy(k.begin(), k.end(), buf.begin() + 160); htole64buf(buf.data() + 160 + K::SIZE, i); @@ -274,38 +260,39 @@ namespace llarp // h = make_point(n) ShortHash n; return -1 - != crypto_generichash_blake2b(n.data(), ShortHash::SIZE, buf.data(), - buf.size(), nullptr, 0) + != 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; + static AlignedBuffer<32> zero; bool - CryptoLibSodium::derive_subkey(PubKey &out_pubkey, - const PubKey &root_pubkey, uint64_t key_n, - const AlignedBuffer< 32 > *hash) + CryptoLibSodium::derive_subkey( + 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; - if(hash) + AlignedBuffer<32> h; + if (hash) h = *hash; - else if(not make_scalar(h, root_pubkey, key_n)) + else if (not make_scalar(h, root_pubkey, key_n)) { LogError("cannot make scalar"); return false; } - return 0 - == crypto_scalarmult_ed25519(out_pubkey.data(), h.data(), - root_pubkey.data()); + return 0 == crypto_scalarmult_ed25519(out_pubkey.data(), h.data(), root_pubkey.data()); } bool - CryptoLibSodium::derive_subkey_private(PrivateKey &out_key, - const SecretKey &root_key, - uint64_t key_n, - const AlignedBuffer< 32 > *hash) + CryptoLibSodium::derive_subkey_private( + PrivateKey& out_key, + const SecretKey& root_key, + uint64_t key_n, + const AlignedBuffer<32>* hash) { // Derives a private subkey from a root key. // @@ -339,10 +326,10 @@ namespace llarp // const auto root_pubkey = root_key.toPublic(); - AlignedBuffer< 32 > h; - if(hash) + AlignedBuffer<32> h; + if (hash) h = *hash; - else if(not make_scalar(h, root_pubkey, key_n)) + else if (not make_scalar(h, root_pubkey, key_n)) { LogError("cannot make scalar"); return false; @@ -353,45 +340,42 @@ namespace llarp h[31] |= 64; PrivateKey a; - if(!root_key.toPrivate(a)) + if (!root_key.toPrivate(a)) return false; // a' = ha crypto_core_ed25519_scalar_mul(out_key.data(), h.data(), a.data()); // s' = H(h || s) - std::array< byte_t, 64 > buf; + std::array 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); + != crypto_generichash_blake2b( + out_key.signingHash(), 32, buf.data(), buf.size(), nullptr, 0); return true; } bool - CryptoLibSodium::seed_to_secretkey(llarp::SecretKey &secret, - const llarp::IdentitySecret &seed) + CryptoLibSodium::seed_to_secretkey(llarp::SecretKey& secret, const llarp::IdentitySecret& seed) { - return crypto_sign_ed25519_seed_keypair(secret.data() + 32, secret.data(), - seed.data()) - != -1; + return crypto_sign_ed25519_seed_keypair(secret.data() + 32, secret.data(), seed.data()) != -1; } void - CryptoLibSodium::randomize(const llarp_buffer_t &buff) + CryptoLibSodium::randomize(const llarp_buffer_t& buff) { - randombytes((unsigned char *)buff.base, buff.sz); + randombytes((unsigned char*)buff.base, buff.sz); } void - CryptoLibSodium::randbytes(byte_t *ptr, size_t sz) + CryptoLibSodium::randbytes(byte_t* ptr, size_t sz) { - randombytes((unsigned char *)ptr, sz); + randombytes((unsigned char*)ptr, sz); } void - CryptoLibSodium::identity_keygen(llarp::SecretKey &keys) + CryptoLibSodium::identity_keygen(llarp::SecretKey& keys) { PubKey pk; int result = crypto_sign_keypair(pk.data(), keys.data()); @@ -405,20 +389,20 @@ namespace llarp } bool - CryptoLibSodium::check_identity_privkey(const llarp::SecretKey &keys) + CryptoLibSodium::check_identity_privkey(const llarp::SecretKey& keys) { - AlignedBuffer< crypto_sign_SEEDBYTES > seed; + AlignedBuffer seed; llarp::PubKey pk; llarp::SecretKey sk; - if(crypto_sign_ed25519_sk_to_seed(seed.data(), keys.data()) == -1) + if (crypto_sign_ed25519_sk_to_seed(seed.data(), keys.data()) == -1) return false; - if(crypto_sign_seed_keypair(pk.data(), sk.data(), seed.data()) == -1) + if (crypto_sign_seed_keypair(pk.data(), sk.data(), seed.data()) == -1) return false; return keys.toPublic() == pk && sk == keys; } void - CryptoLibSodium::encryption_keygen(llarp::SecretKey &keys) + CryptoLibSodium::encryption_keygen(llarp::SecretKey& keys) { auto d = keys.data(); randbytes(d, 32); @@ -426,44 +410,40 @@ namespace llarp } bool - CryptoLibSodium::pqe_encrypt(PQCipherBlock &ciphertext, - SharedSecret &sharedkey, - const PQPubKey &pubkey) + CryptoLibSodium::pqe_encrypt( + PQCipherBlock& ciphertext, SharedSecret& sharedkey, const PQPubKey& pubkey) { - return crypto_kem_enc(ciphertext.data(), sharedkey.data(), pubkey.data()) - != -1; + return crypto_kem_enc(ciphertext.data(), sharedkey.data(), pubkey.data()) != -1; } bool - CryptoLibSodium::pqe_decrypt(const PQCipherBlock &ciphertext, - SharedSecret &sharedkey, - const byte_t *secretkey) + CryptoLibSodium::pqe_decrypt( + const PQCipherBlock& ciphertext, SharedSecret& sharedkey, const byte_t* secretkey) { - return crypto_kem_dec(sharedkey.data(), ciphertext.data(), secretkey) - != -1; + return crypto_kem_dec(sharedkey.data(), ciphertext.data(), secretkey) != -1; } void - CryptoLibSodium::pqe_keygen(PQKeyPair &keypair) + CryptoLibSodium::pqe_keygen(PQKeyPair& keypair) { auto d = keypair.data(); crypto_kem_keypair(d + PQ_SECRETKEYSIZE, d); } } // namespace sodium - const byte_t * - seckey_topublic(const SecretKey &sec) + const byte_t* + seckey_topublic(const SecretKey& sec) { return sec.data() + 32; } - const byte_t * - pq_keypair_to_public(const PQKeyPair &k) + const byte_t* + pq_keypair_to_public(const PQKeyPair& k) { return k.data() + PQ_SECRETKEYSIZE; } - const byte_t * - pq_keypair_to_secret(const PQKeyPair &k) + const byte_t* + pq_keypair_to_secret(const PQKeyPair& k) { return k.data(); } @@ -472,7 +452,7 @@ namespace llarp randint() { uint64_t i; - randombytes((byte_t *)&i, sizeof(i)); + randombytes((byte_t*)&i, sizeof(i)); return i; } diff --git a/llarp/crypto/crypto_libsodium.hpp b/llarp/crypto/crypto_libsodium.hpp index a9b32d108..f9b648695 100644 --- a/llarp/crypto/crypto_libsodium.hpp +++ b/llarp/crypto/crypto_libsodium.hpp @@ -15,89 +15,91 @@ namespace llarp /// xchacha symmetric cipher bool - xchacha20(const llarp_buffer_t &, const SharedSecret &, - const TunnelNonce &) override; + xchacha20(const llarp_buffer_t&, const SharedSecret&, const TunnelNonce&) override; /// xchacha symmetric cipher (multibuffer) bool - xchacha20_alt(const llarp_buffer_t &, const llarp_buffer_t &, - const SharedSecret &, const byte_t *) override; + xchacha20_alt( + const llarp_buffer_t&, + const llarp_buffer_t&, + const SharedSecret&, + const byte_t*) override; /// path dh creator's side bool - dh_client(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) override; + dh_client(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override; /// path dh relay side bool - dh_server(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) override; + dh_server(SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override; /// transport dh client side bool - transport_dh_client(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) override; + transport_dh_client( + SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override; /// transport dh server side bool - transport_dh_server(SharedSecret &, const PubKey &, const SecretKey &, - const TunnelNonce &) override; + transport_dh_server( + SharedSecret&, const PubKey&, const SecretKey&, const TunnelNonce&) override; /// blake2b 256 bit bool - shorthash(ShortHash &, const llarp_buffer_t &) override; + shorthash(ShortHash&, const llarp_buffer_t&) override; /// blake2s 256 bit hmac bool - hmac(byte_t *, const llarp_buffer_t &, const SharedSecret &) override; + hmac(byte_t*, const llarp_buffer_t&, const SharedSecret&) override; /// ed25519 sign bool - sign(Signature &, const SecretKey &, const llarp_buffer_t &) override; + sign(Signature&, const SecretKey&, const llarp_buffer_t&) override; /// ed25519 sign (custom with derived keys) bool - sign(Signature &, const PrivateKey &, const llarp_buffer_t &) override; + sign(Signature&, const PrivateKey&, const llarp_buffer_t&) override; /// ed25519 verify bool - verify(const PubKey &, const llarp_buffer_t &, - const Signature &) override; + verify(const PubKey&, const llarp_buffer_t&, const Signature&) override; /// derive sub keys for public keys. hash is really only intended for /// testing and overrides key_n if given. bool - derive_subkey(PubKey &derived, const PubKey &root, uint64_t key_n, - const AlignedBuffer< 32 > *hash = nullptr) override; + derive_subkey( + PubKey& derived, + const PubKey& root, + uint64_t key_n, + const AlignedBuffer<32>* hash = nullptr) override; /// derive sub keys for private keys. hash is really only intended for /// testing and overrides key_n if given. bool - derive_subkey_private(PrivateKey &derived, const SecretKey &root, - uint64_t key_n, - const AlignedBuffer< 32 > *hash = nullptr) override; + derive_subkey_private( + PrivateKey& derived, + const SecretKey& root, + uint64_t key_n, + const AlignedBuffer<32>* hash = nullptr) override; /// seed to secretkey bool - seed_to_secretkey(llarp::SecretKey &, - const llarp::IdentitySecret &) override; + seed_to_secretkey(llarp::SecretKey&, const llarp::IdentitySecret&) override; /// randomize buffer void - randomize(const llarp_buffer_t &) override; + randomize(const llarp_buffer_t&) override; /// randomizer memory void - randbytes(byte_t *, size_t) override; + randbytes(byte_t*, size_t) override; /// generate signing keypair void - identity_keygen(SecretKey &) override; + identity_keygen(SecretKey&) override; /// generate encryption keypair void - encryption_keygen(SecretKey &) override; + encryption_keygen(SecretKey&) override; /// generate post quantum encrytion key void - pqe_keygen(PQKeyPair &) override; + pqe_keygen(PQKeyPair&) override; /// post quantum decrypt (buffer, sharedkey_dst, sec) bool - pqe_decrypt(const PQCipherBlock &, SharedSecret &, - const byte_t *) override; + pqe_decrypt(const PQCipherBlock&, SharedSecret&, const byte_t*) override; /// post quantum encrypt (buffer, sharedkey_dst, pub) bool - pqe_encrypt(PQCipherBlock &, SharedSecret &, const PQPubKey &) override; + pqe_encrypt(PQCipherBlock&, SharedSecret&, const PQPubKey&) override; bool - check_identity_privkey(const SecretKey &) override; + check_identity_privkey(const SecretKey&) override; }; } // namespace sodium diff --git a/llarp/crypto/crypto_noop.hpp b/llarp/crypto/crypto_noop.hpp index c6566f32e..a2f496dae 100644 --- a/llarp/crypto/crypto_noop.hpp +++ b/llarp/crypto/crypto_noop.hpp @@ -11,9 +11,9 @@ namespace llarp struct NoOpCrypto final : public Crypto { private: - std::atomic< uint64_t > m_value; + std::atomic m_value; - static constexpr byte_t MAX_BYTE = std::numeric_limits< byte_t >::max(); + static constexpr byte_t MAX_BYTE = std::numeric_limits::max(); public: NoOpCrypto() : m_value(0) @@ -23,17 +23,19 @@ namespace llarp ~NoOpCrypto() override = default; bool - xchacha20(const llarp_buffer_t &, const SharedSecret &, - const TunnelNonce &) override + xchacha20(const llarp_buffer_t&, const SharedSecret&, const TunnelNonce&) override { return true; } bool - xchacha20_alt(const llarp_buffer_t &out, const llarp_buffer_t &in, - const SharedSecret &, const byte_t *) override + xchacha20_alt( + const llarp_buffer_t& out, + const llarp_buffer_t& in, + const SharedSecret&, + const byte_t*) override { - if(in.sz > out.sz) + if (in.sz > out.sz) { return false; } @@ -43,42 +45,40 @@ namespace llarp } bool - dh_client(SharedSecret &shared, const PubKey &pk, const SecretKey &, - const TunnelNonce &) override + dh_client(SharedSecret& shared, const PubKey& pk, const SecretKey&, const TunnelNonce&) override { std::copy_n(pk.begin(), pk.size(), shared.begin()); return true; } bool - dh_server(SharedSecret &shared, const PubKey &pk, const SecretKey &, - const TunnelNonce &) override + dh_server(SharedSecret& shared, const PubKey& pk, const SecretKey&, const TunnelNonce&) override { std::copy_n(pk.begin(), pk.size(), shared.begin()); return true; } bool - transport_dh_client(SharedSecret &shared, const PubKey &pk, - const SecretKey &, const TunnelNonce &) override + transport_dh_client( + SharedSecret& shared, const PubKey& pk, const SecretKey&, const TunnelNonce&) override { std::copy_n(pk.begin(), pk.size(), shared.begin()); return true; } bool - transport_dh_server(SharedSecret &shared, const PubKey &pk, - const SecretKey &, const TunnelNonce &) override + transport_dh_server( + SharedSecret& shared, const PubKey& pk, const SecretKey&, const TunnelNonce&) override { std::copy_n(pk.begin(), pk.size(), shared.begin()); return true; } bool - shorthash(ShortHash &out, const llarp_buffer_t &buff) override + shorthash(ShortHash& out, const llarp_buffer_t& buff) override { // copy the first 32 bytes of the buffer - if(buff.sz < out.size()) + if (buff.sz < out.size()) { std::copy_n(buff.begin(), buff.sz, out.begin()); std::fill(out.begin() + buff.sz, out.end(), 0); @@ -91,9 +91,9 @@ namespace llarp } bool - hmac(byte_t *out, const llarp_buffer_t &buff, const SharedSecret &) override + hmac(byte_t* out, const llarp_buffer_t& buff, const SharedSecret&) override { - if(buff.sz < HMACSIZE) + if (buff.sz < HMACSIZE) { std::copy_n(buff.begin(), buff.sz, out); std::fill(out + buff.sz, out + (HMACSIZE - buff.sz), 0); @@ -106,89 +106,86 @@ namespace llarp } bool - sign(Signature &sig, const SecretKey &, const llarp_buffer_t &) override + sign(Signature& sig, const SecretKey&, const llarp_buffer_t&) override { std::fill(sig.begin(), sig.end(), 0); return true; } bool - sign(Signature &sig, const PrivateKey &, const llarp_buffer_t &) override + sign(Signature& sig, const PrivateKey&, const llarp_buffer_t&) override { std::fill(sig.begin(), sig.end(), 0); return true; } bool - verify(const PubKey &, const llarp_buffer_t &, const Signature &) override + verify(const PubKey&, const llarp_buffer_t&, const Signature&) override { return true; } bool - seed_to_secretkey(SecretKey &key, const IdentitySecret &secret) override + seed_to_secretkey(SecretKey& key, const IdentitySecret& secret) override { static_assert(SecretKey::SIZE == (2 * IdentitySecret::SIZE), ""); std::copy(secret.begin(), secret.end(), key.begin()); - std::copy(secret.begin(), secret.end(), - key.begin() + IdentitySecret::SIZE); + std::copy(secret.begin(), secret.end(), key.begin() + IdentitySecret::SIZE); return true; } void - randomize(const llarp_buffer_t &buff) override + randomize(const llarp_buffer_t& buff) override { std::iota(buff.begin(), buff.end(), m_value.load() % MAX_BYTE); m_value += buff.sz; } void - randbytes(byte_t *ptr, size_t sz) override + randbytes(byte_t* ptr, size_t sz) override { std::iota(ptr, ptr + sz, m_value.load() % MAX_BYTE); m_value += sz; } void - identity_keygen(SecretKey &key) override + identity_keygen(SecretKey& key) override { std::iota(key.begin(), key.end(), m_value.load() % MAX_BYTE); m_value += key.size(); } void - encryption_keygen(SecretKey &key) override + encryption_keygen(SecretKey& key) override { std::iota(key.begin(), key.end(), m_value.load() % MAX_BYTE); m_value += key.size(); } void - pqe_keygen(PQKeyPair &pair) override + pqe_keygen(PQKeyPair& pair) override { std::iota(pair.begin(), pair.end(), m_value.load() % MAX_BYTE); m_value += pair.size(); } bool - pqe_decrypt(const PQCipherBlock &block, SharedSecret &secret, - const byte_t *) override + pqe_decrypt(const PQCipherBlock& block, SharedSecret& secret, const byte_t*) override { std::copy_n(block.begin(), SharedSecret::SIZE, secret.begin()); return true; } bool - pqe_encrypt(PQCipherBlock &block, SharedSecret &secret, - const PQPubKey &) override + pqe_encrypt(PQCipherBlock& block, SharedSecret& secret, const PQPubKey&) override { std::copy_n(secret.begin(), SharedSecret::SIZE, block.begin()); return true; } bool - check_identity_privkey(const SecretKey &) override + check_identity_privkey(const SecretKey&) override { return true; } diff --git a/llarp/crypto/encrypted.hpp b/llarp/crypto/encrypted.hpp index 285c2eb96..fca2a72df 100644 --- a/llarp/crypto/encrypted.hpp +++ b/llarp/crypto/encrypted.hpp @@ -13,12 +13,12 @@ namespace llarp { /// encrypted buffer base type - template < size_t bufsz = MAX_LINK_MSG_SIZE > + template struct Encrypted { Encrypted(Encrypted&& other) { - _sz = std::move(other._sz); + _sz = std::move(other._sz); _buf = std::move(other._buf); UpdateBuffer(); } @@ -42,10 +42,10 @@ namespace llarp Encrypted(const byte_t* buf, size_t sz) { - if(sz <= bufsz) + if (sz <= bufsz) { _sz = sz; - if(buf) + if (buf) memcpy(_buf.data(), buf, sz); else _buf.Zero(); @@ -86,7 +86,7 @@ namespace llarp Encrypted& operator=(const llarp_buffer_t& buf) { - if(buf.sz <= _buf.size()) + if (buf.sz <= _buf.size()) { _sz = buf.sz; memcpy(_buf.data(), buf.base, _sz); @@ -104,7 +104,7 @@ namespace llarp void Randomize() { - if(_sz) + if (_sz) randombytes(_buf.data(), _sz); } @@ -112,12 +112,12 @@ namespace llarp BDecode(llarp_buffer_t* buf) { llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz > sizeof(_buf)) + if (strbuf.sz > sizeof(_buf)) return false; _sz = strbuf.sz; - if(_sz) + if (_sz) memcpy(_buf.data(), strbuf.base, _sz); UpdateBuffer(); return true; @@ -158,10 +158,10 @@ namespace llarp UpdateBuffer() { m_Buffer.base = _buf.data(); - m_Buffer.cur = _buf.data(); - m_Buffer.sz = _sz; + m_Buffer.cur = _buf.data(); + m_Buffer.sz = _sz; } - AlignedBuffer< bufsz > _buf; + AlignedBuffer _buf; size_t _sz; llarp_buffer_t m_Buffer; }; // namespace llarp diff --git a/llarp/crypto/encrypted_frame.cpp b/llarp/crypto/encrypted_frame.cpp index e980a889b..5e4369d5c 100644 --- a/llarp/crypto/encrypted_frame.cpp +++ b/llarp/crypto/encrypted_frame.cpp @@ -9,17 +9,17 @@ namespace llarp bool EncryptedFrame::DoEncrypt(const SharedSecret& shared, bool noDH) { - byte_t* hash = data(); + byte_t* hash = data(); byte_t* noncePtr = hash + SHORTHASHSIZE; - byte_t* pubkey = noncePtr + TUNNONCESIZE; - byte_t* body = pubkey + PUBKEYSIZE; + byte_t* pubkey = noncePtr + TUNNONCESIZE; + byte_t* body = pubkey + PUBKEYSIZE; auto crypto = CryptoManager::instance(); // if noDH flag, means key exchange has already taken place // in this case, set pubkey to random noise and choose a // random nonce here - if(noDH) + if (noDH) { crypto->randbytes(noncePtr, TUNNONCESIZE); crypto->randbytes(pubkey, PUBKEYSIZE); @@ -29,11 +29,11 @@ namespace llarp llarp_buffer_t buf; buf.base = body; - buf.cur = buf.base; - buf.sz = size() - EncryptedFrameOverheadSize; + buf.cur = buf.base; + buf.sz = size() - EncryptedFrameOverheadSize; // encrypt body - if(!crypto->xchacha20(buf, shared, nonce)) + if (!crypto->xchacha20(buf, shared, nonce)) { llarp::LogError("encrypt failed"); return false; @@ -41,10 +41,10 @@ namespace llarp // generate message auth buf.base = noncePtr; - buf.cur = buf.base; - buf.sz = size() - SHORTHASHSIZE; + buf.cur = buf.base; + buf.sz = size() - SHORTHASHSIZE; - if(!crypto->hmac(hash, buf, shared)) + if (!crypto->hmac(hash, buf, shared)) { llarp::LogError("Failed to generate message auth"); return false; @@ -54,8 +54,7 @@ namespace llarp } bool - EncryptedFrame::EncryptInPlace(const SecretKey& ourSecretKey, - const PubKey& otherPubkey) + EncryptedFrame::EncryptInPlace(const SecretKey& ourSecretKey, const PubKey& otherPubkey) { // format of frame is // <32 bytes keyed hash of following data> @@ -63,9 +62,9 @@ namespace llarp // <32 bytes pubkey> // // - byte_t* hash = data(); + byte_t* hash = data(); byte_t* noncePtr = hash + SHORTHASHSIZE; - byte_t* pubkey = noncePtr + TUNNONCESIZE; + byte_t* pubkey = noncePtr + TUNNONCESIZE; SharedSecret shared; @@ -78,7 +77,7 @@ namespace llarp TunnelNonce nonce(noncePtr); // derive shared key - if(!crypto->dh_client(shared, otherPubkey, ourSecretKey, nonce)) + if (!crypto->dh_client(shared, otherPubkey, ourSecretKey, nonce)) { llarp::LogError("DH failed"); return false; @@ -92,34 +91,34 @@ namespace llarp { ShortHash hash(data()); byte_t* noncePtr = data() + SHORTHASHSIZE; - byte_t* body = data() + EncryptedFrameOverheadSize; + byte_t* body = data() + EncryptedFrameOverheadSize; TunnelNonce nonce(noncePtr); auto crypto = CryptoManager::instance(); llarp_buffer_t buf; buf.base = noncePtr; - buf.cur = buf.base; - buf.sz = size() - SHORTHASHSIZE; + buf.cur = buf.base; + buf.sz = size() - SHORTHASHSIZE; ShortHash digest; - if(!crypto->hmac(digest.data(), buf, shared)) + if (!crypto->hmac(digest.data(), buf, shared)) { llarp::LogError("Digest failed"); return false; } - if(!std::equal(digest.begin(), digest.end(), hash.begin())) + if (!std::equal(digest.begin(), digest.end(), hash.begin())) { llarp::LogError("message authentication failed"); return false; } buf.base = body; - buf.cur = body; - buf.sz = size() - EncryptedFrameOverheadSize; + buf.cur = body; + buf.sz = size() - EncryptedFrameOverheadSize; - if(!crypto->xchacha20(buf, shared, nonce)) + if (!crypto->xchacha20(buf, shared, nonce)) { llarp::LogError("decrypt failed"); return false; @@ -146,7 +145,7 @@ namespace llarp auto crypto = CryptoManager::instance(); // use dh_server because we are not the creator of this message - if(!crypto->dh_server(shared, otherPubkey, ourSecretKey, nonce)) + if (!crypto->dh_server(shared, otherPubkey, ourSecretKey, nonce)) { llarp::LogError("DH failed"); return false; diff --git a/llarp/crypto/encrypted_frame.hpp b/llarp/crypto/encrypted_frame.hpp index 00a99f7bd..27fdcf8d0 100644 --- a/llarp/crypto/encrypted_frame.hpp +++ b/llarp/crypto/encrypted_frame.hpp @@ -10,28 +10,26 @@ namespace llarp { - static constexpr size_t EncryptedFrameOverheadSize = - PUBKEYSIZE + TUNNONCESIZE + SHORTHASHSIZE; + static constexpr size_t EncryptedFrameOverheadSize = PUBKEYSIZE + TUNNONCESIZE + SHORTHASHSIZE; static constexpr size_t EncryptedFrameBodySize = 128 * 6; - static constexpr size_t EncryptedFrameSize = - EncryptedFrameOverheadSize + EncryptedFrameBodySize; + static constexpr size_t EncryptedFrameSize = EncryptedFrameOverheadSize + EncryptedFrameBodySize; - struct EncryptedFrame : public Encrypted< EncryptedFrameSize > + struct EncryptedFrame : public Encrypted { EncryptedFrame() : EncryptedFrame(EncryptedFrameBodySize) { } EncryptedFrame(size_t sz) - : Encrypted< EncryptedFrameSize >(std::min(sz, EncryptedFrameBodySize) - + EncryptedFrameOverheadSize) + : Encrypted( + std::min(sz, EncryptedFrameBodySize) + EncryptedFrameOverheadSize) { } void Resize(size_t sz) { - if(sz <= EncryptedFrameSize) + if (sz <= EncryptedFrameSize) { _sz = sz; UpdateBuffer(); @@ -52,16 +50,16 @@ namespace llarp }; /// TODO: can only handle 1 frame at a time - template < typename User > + template struct AsyncFrameDecrypter { - using User_ptr = std::shared_ptr< User >; - using DecryptHandler = std::function< void(llarp_buffer_t*, User_ptr) >; + using User_ptr = std::shared_ptr; + using DecryptHandler = std::function; void Decrypt(User_ptr user) { - if(target.DecryptInPlace(seckey)) + if (target.DecryptInPlace(seckey)) { auto buf = target.Buffer(); buf->cur = buf->base + EncryptedFrameOverheadSize; @@ -81,12 +79,11 @@ namespace llarp EncryptedFrame target; void - AsyncDecrypt(const std::shared_ptr< thread::ThreadPool >& worker, - const EncryptedFrame& frame, User_ptr u) + AsyncDecrypt( + const std::shared_ptr& worker, const EncryptedFrame& frame, User_ptr u) { target = frame; - worker->addJob( - std::bind(&AsyncFrameDecrypter< User >::Decrypt, this, std::move(u))); + worker->addJob(std::bind(&AsyncFrameDecrypter::Decrypt, this, std::move(u))); } }; } // namespace llarp diff --git a/llarp/crypto/types.cpp b/llarp/crypto/types.cpp index a3f2a07f3..0f8a21336 100644 --- a/llarp/crypto/types.cpp +++ b/llarp/crypto/types.cpp @@ -30,7 +30,7 @@ namespace llarp SecretKey::LoadFromFile(const char* fname) { std::ifstream f(fname, std::ios::in | std::ios::binary); - if(!f.is_open()) + if (!f.is_open()) { return false; } @@ -39,19 +39,19 @@ namespace llarp const size_t sz = f.tellg(); f.seekg(0, std::ios::beg); - if(sz == size()) + if (sz == size()) { // is raw buffer - std::copy_n(std::istreambuf_iterator< char >(f), sz, begin()); + std::copy_n(std::istreambuf_iterator(f), sz, begin()); return true; } - std::array< byte_t, 128 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(sz > sizeof(tmp)) + if (sz > sizeof(tmp)) { return false; } - f.read(reinterpret_cast< char* >(tmp.data()), sz); + f.read(reinterpret_cast(tmp.data()), sz); return BDecode(&buf); } @@ -60,7 +60,7 @@ namespace llarp { PrivateKey key; PubKey pubkey; - if(!toPrivate(key) || !key.toPublic(pubkey)) + if (!toPrivate(key) || !key.toPublic(pubkey)) return false; std::memcpy(data() + 32, pubkey.data(), 32); return true; @@ -73,7 +73,7 @@ namespace llarp // is the private key; the second half is the hash that gets used in // signing. unsigned char h[crypto_hash_sha512_BYTES]; - if(crypto_hash_sha512(h, data(), 32) < 0) + if (crypto_hash_sha512(h, data(), 32) < 0) return false; h[0] &= 248; h[31] &= 63; @@ -91,19 +91,18 @@ namespace llarp bool SecretKey::SaveToFile(const char* fname) const { - std::array< byte_t, 128 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!BEncode(&buf)) + if (!BEncode(&buf)) { return false; } const fs::path fpath = std::string(fname); - auto optional_f = - llarp::util::OpenFileStream< std::ofstream >(fpath, std::ios::binary); - if(!optional_f) + auto optional_f = llarp::util::OpenFileStream(fpath, std::ios::binary); + if (!optional_f) return false; auto& f = optional_f.value(); - if(!f.is_open()) + if (!f.is_open()) return false; f.write((char*)buf.base, buf.cur - buf.base); return f.good(); @@ -113,20 +112,19 @@ namespace llarp IdentitySecret::LoadFromFile(const char* fname) { const fs::path fpath = std::string(fname); - auto optional = util::OpenFileStream< std::ifstream >( - fpath, std::ios::binary | std::ios::in); - if(!optional) + auto optional = util::OpenFileStream(fpath, std::ios::binary | std::ios::in); + if (!optional) return false; auto& f = optional.value(); f.seekg(0, std::ios::end); const size_t sz = f.tellg(); f.seekg(0, std::ios::beg); - if(sz != 32) + if (sz != 32) { llarp::LogError("service node seed size invalid: ", sz, " != 32"); return false; } - std::copy_n(std::istreambuf_iterator< char >(f), sz, begin()); + std::copy_n(std::istreambuf_iterator(f), sz, begin()); return true; } diff --git a/llarp/crypto/types.hpp b/llarp/crypto/types.hpp index 25f439524..acaa4669d 100644 --- a/llarp/crypto/types.hpp +++ b/llarp/crypto/types.hpp @@ -11,23 +11,22 @@ namespace llarp { - using SharedSecret = AlignedBuffer< SHAREDKEYSIZE >; - using KeyExchangeNonce = AlignedBuffer< 32 >; + using SharedSecret = AlignedBuffer; + using KeyExchangeNonce = AlignedBuffer<32>; - struct PubKey final : public AlignedBuffer< PUBKEYSIZE > + struct PubKey final : public AlignedBuffer { PubKey() = default; - explicit PubKey(const byte_t *ptr) : AlignedBuffer< SIZE >(ptr) + explicit PubKey(const byte_t* ptr) : AlignedBuffer(ptr) { } - explicit PubKey(const Data &data) : AlignedBuffer< SIZE >(data) + explicit PubKey(const Data& data) : AlignedBuffer(data) { } - explicit PubKey(const AlignedBuffer< SIZE > &other) - : AlignedBuffer< SIZE >(other) + explicit PubKey(const AlignedBuffer& other) : AlignedBuffer(other) { } @@ -35,41 +34,41 @@ namespace llarp ToString() const; bool - FromString(const std::string &str); + FromString(const std::string& str); operator RouterID() const { return RouterID(as_array()); } - PubKey & - operator=(const byte_t *ptr) + PubKey& + operator=(const byte_t* ptr) { std::copy(ptr, ptr + SIZE, begin()); return *this; } }; - inline std::ostream & - operator<<(std::ostream &out, const PubKey &k) + inline std::ostream& + operator<<(std::ostream& out, const PubKey& k) { return out << k.ToString(); } inline bool - operator==(const PubKey &lhs, const PubKey &rhs) + operator==(const PubKey& lhs, const PubKey& rhs) { return lhs.as_array() == rhs.as_array(); } inline bool - operator==(const PubKey &lhs, const RouterID &rhs) + operator==(const PubKey& lhs, const RouterID& rhs) { return lhs.as_array() == rhs.as_array(); } inline bool - operator==(const RouterID &lhs, const PubKey &rhs) + operator==(const RouterID& lhs, const PubKey& rhs) { return lhs.as_array() == rhs.as_array(); } @@ -79,22 +78,21 @@ namespace llarp /// Stores a sodium "secret key" value, which is actually the seed /// concatenated with the public key. Note that the seed is *not* the private /// key value itself, but rather the seed from which it can be calculated. - struct SecretKey final : public AlignedBuffer< SECKEYSIZE > + struct SecretKey final : public AlignedBuffer { SecretKey() = default; - explicit SecretKey(const byte_t *ptr) : AlignedBuffer< SECKEYSIZE >(ptr) + explicit SecretKey(const byte_t* ptr) : AlignedBuffer(ptr) { } // The full data - explicit SecretKey(const AlignedBuffer< SECKEYSIZE > &seed) - : AlignedBuffer< SECKEYSIZE >(seed) + explicit SecretKey(const AlignedBuffer& seed) : AlignedBuffer(seed) { } // Just the seed, we recalculate the pubkey - explicit SecretKey(const AlignedBuffer< 32 > &seed) + explicit SecretKey(const AlignedBuffer<32>& seed) { std::copy(seed.begin(), seed.end(), begin()); Recalculate(); @@ -104,8 +102,8 @@ namespace llarp bool Recalculate(); - std::ostream & - print(std::ostream &stream, int level, int spaces) const + std::ostream& + print(std::ostream& stream, int level, int spaces) const { Printer printer(stream, level, spaces); printer.printValue("secretkey"); @@ -121,17 +119,17 @@ namespace llarp /// Computes the private key from the secret key (which is actually the /// seed) bool - toPrivate(PrivateKey &key) const; + toPrivate(PrivateKey& key) const; bool - LoadFromFile(const char *fname); + LoadFromFile(const char* fname); bool - SaveToFile(const char *fname) const; + SaveToFile(const char* fname) const; }; - inline std::ostream & - operator<<(std::ostream &out, const SecretKey &) + inline std::ostream& + operator<<(std::ostream& out, const SecretKey&) { // return out << k.ToHex(); // make sure we never print out secret keys @@ -143,22 +141,21 @@ namespace llarp /// the private key and hash value are generated. This is primarily intended /// for use with derived keys, where we can derive the private key but not the /// seed. - struct PrivateKey final : public AlignedBuffer< 64 > + struct PrivateKey final : public AlignedBuffer<64> { PrivateKey() = default; - explicit PrivateKey(const byte_t *ptr) : AlignedBuffer< 64 >(ptr) + explicit PrivateKey(const byte_t* ptr) : AlignedBuffer<64>(ptr) { } - explicit PrivateKey(const AlignedBuffer< 64 > &key_and_hash) - : AlignedBuffer< 64 >(key_and_hash) + explicit PrivateKey(const AlignedBuffer<64>& key_and_hash) : AlignedBuffer<64>(key_and_hash) { } /// Returns a pointer to the beginning of the 32-byte hash which is used for /// pseudorandomness when signing with this private key. - const byte_t * + const byte_t* signingHash() const { return data() + 32; @@ -166,14 +163,14 @@ namespace llarp /// Returns a pointer to the beginning of the 32-byte hash which is used for /// pseudorandomness when signing with this private key. - byte_t * + byte_t* signingHash() { return data() + 32; } - std::ostream & - print(std::ostream &stream, int level, int spaces) const + std::ostream& + print(std::ostream& stream, int level, int spaces) const { Printer printer(stream, level, spaces); printer.printValue("privatekey"); @@ -182,11 +179,11 @@ namespace llarp /// Computes the public key bool - toPublic(PubKey &pubkey) const; + toPublic(PubKey& pubkey) const; }; - inline std::ostream & - operator<<(std::ostream &out, const PrivateKey &) + inline std::ostream& + operator<<(std::ostream& out, const PrivateKey&) { // return out << k.ToHex(); // make sure we never print out private keys @@ -194,66 +191,65 @@ namespace llarp } /// IdentitySecret is a secret key from a service node secret seed - struct IdentitySecret final : public AlignedBuffer< 32 > + struct IdentitySecret final : public AlignedBuffer<32> { - IdentitySecret() : AlignedBuffer< 32 >() + IdentitySecret() : AlignedBuffer<32>() { } /// no copy constructor - explicit IdentitySecret(const IdentitySecret &) = delete; + explicit IdentitySecret(const IdentitySecret&) = delete; // no byte data constructor - explicit IdentitySecret(const byte_t *) = delete; + explicit IdentitySecret(const byte_t*) = delete; /// load service node seed from file bool - LoadFromFile(const char *fname); + LoadFromFile(const char* fname); }; - inline std::ostream & - operator<<(std::ostream &out, const IdentitySecret &) + inline std::ostream& + operator<<(std::ostream& out, const IdentitySecret&) { // make sure we never print out secret keys return out << "[IdentitySecret]"; } - using ShortHash = AlignedBuffer< SHORTHASHSIZE >; - using LongHash = AlignedBuffer< HASHSIZE >; + using ShortHash = AlignedBuffer; + using LongHash = AlignedBuffer; - struct Signature final : public AlignedBuffer< SIGSIZE > + struct Signature final : public AlignedBuffer { - byte_t * + byte_t* Hi(); - const byte_t * + const byte_t* Hi() const; - byte_t * + byte_t* Lo(); - const byte_t * + const byte_t* Lo() const; }; - using TunnelNonce = AlignedBuffer< TUNNONCESIZE >; - using SymmNonce = AlignedBuffer< NONCESIZE >; - using SymmKey = AlignedBuffer< 32 >; + using TunnelNonce = AlignedBuffer; + using SymmNonce = AlignedBuffer; + using SymmKey = AlignedBuffer<32>; - using PQCipherBlock = AlignedBuffer< PQ_CIPHERTEXTSIZE + 1 >; - using PQPubKey = AlignedBuffer< PQ_PUBKEYSIZE >; - using PQKeyPair = AlignedBuffer< PQ_KEYPAIRSIZE >; + using PQCipherBlock = AlignedBuffer; + using PQPubKey = AlignedBuffer; + using PQKeyPair = AlignedBuffer; /// PKE(result, publickey, secretkey, nonce) - using path_dh_func = std::function< bool( - SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; + using path_dh_func = + std::function; /// TKE(result, publickey, secretkey, nonce) - using transport_dh_func = std::function< bool( - SharedSecret &, const PubKey &, const SecretKey &, const TunnelNonce &) >; + using transport_dh_func = + std::function; /// SH(result, body) - using shorthash_func = - std::function< bool(ShortHash &, const llarp_buffer_t &) >; + using shorthash_func = std::function; } // namespace llarp #endif diff --git a/llarp/dht/bucket.hpp b/llarp/dht/bucket.hpp index 0f623270c..47cb6d4b6 100644 --- a/llarp/dht/bucket.hpp +++ b/llarp/dht/bucket.hpp @@ -13,14 +13,13 @@ namespace llarp { namespace dht { - template < typename Val_t > + template struct Bucket { - using BucketStorage_t = std::map< Key_t, Val_t, XorMetric >; - using Random_t = std::function< uint64_t() >; + using BucketStorage_t = std::map; + using Random_t = std::function; - Bucket(const Key_t& us, Random_t r) - : nodes(XorMetric(us)), random(std::move(r)) + Bucket(const Key_t& us, Random_t r) : nodes(XorMetric(us)), random(std::move(r)) { } @@ -28,7 +27,7 @@ namespace llarp ExtractStatus() const { util::StatusObject obj{}; - for(const auto& item : nodes) + for (const auto& item : nodes) { obj[item.first.ToString()] = item.second.ExtractStatus(); } @@ -44,30 +43,31 @@ namespace llarp struct SetIntersector { bool - operator()(const typename BucketStorage_t::value_type& lhs, - const Key_t& rhs) + operator()(const typename BucketStorage_t::value_type& lhs, const Key_t& rhs) { return lhs.first < rhs; } bool - operator()(const Key_t& lhs, - const typename BucketStorage_t::value_type& rhs) + operator()(const Key_t& lhs, const typename BucketStorage_t::value_type& rhs) { return lhs < rhs.first; } }; bool - GetRandomNodeExcluding(Key_t& result, - const std::set< Key_t >& exclude) const + GetRandomNodeExcluding(Key_t& result, const std::set& exclude) const { - std::vector< typename BucketStorage_t::value_type > candidates; - std::set_difference(nodes.begin(), nodes.end(), exclude.begin(), - exclude.end(), std::back_inserter(candidates), - SetIntersector()); - - if(candidates.empty()) + std::vector candidates; + std::set_difference( + nodes.begin(), + nodes.end(), + exclude.begin(), + exclude.end(), + std::back_inserter(candidates), + SetIntersector()); + + if (candidates.empty()) { return false; } @@ -80,42 +80,42 @@ namespace llarp { Key_t mindist; mindist.Fill(0xff); - for(const auto& item : nodes) + for (const auto& item : nodes) { auto curDist = item.first ^ target; - if(curDist < mindist) + if (curDist < mindist) { mindist = curDist; - result = item.first; + result = item.first; } } return nodes.size() > 0; } bool - GetManyRandom(std::set< Key_t >& result, size_t N) const + GetManyRandom(std::set& result, size_t N) const { - if(nodes.size() < N || nodes.empty()) + if (nodes.size() < N || nodes.empty()) { - llarp::LogWarn("Not enough dht nodes, have ", nodes.size(), " want ", - N); + llarp::LogWarn("Not enough dht nodes, have ", nodes.size(), " want ", N); return false; } - if(nodes.size() == N) + 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; } size_t expecting = N; - size_t sz = nodes.size(); - while(N) + size_t sz = nodes.size(); + while (N) { auto itr = nodes.begin(); std::advance(itr, random() % sz); - if(result.insert(itr->first).second) + if (result.insert(itr->first).second) { --N; } @@ -124,40 +124,42 @@ namespace llarp } bool - FindCloseExcluding(const Key_t& target, Key_t& result, - const std::set< Key_t >& exclude) const + FindCloseExcluding(const Key_t& target, Key_t& result, const std::set& exclude) const { Key_t maxdist; maxdist.Fill(0xff); Key_t mindist; mindist.Fill(0xff); - for(const auto& item : nodes) + for (const auto& item : nodes) { - if(exclude.count(item.first)) + if (exclude.count(item.first)) { continue; } auto curDist = item.first ^ target; - if(curDist < mindist) + if (curDist < mindist) { mindist = curDist; - result = item.first; + result = item.first; } } return mindist < maxdist; } bool - GetManyNearExcluding(const Key_t& target, std::set< Key_t >& result, - size_t N, const std::set< Key_t >& exclude) const + GetManyNearExcluding( + const Key_t& target, + std::set& result, + size_t N, + const std::set& exclude) const { - std::set< Key_t > s(exclude.begin(), exclude.end()); + std::set s(exclude.begin(), exclude.end()); Key_t peer; - while(N--) + while (N--) { - if(!FindCloseExcluding(target, peer, s)) + if (!FindCloseExcluding(target, peer, s)) { return false; } @@ -171,7 +173,7 @@ namespace llarp PutNode(const Val_t& val) { auto itr = nodes.find(val.ID); - if(itr == nodes.end() || itr->second < val) + if (itr == nodes.end() || itr->second < val) { nodes[val.ID] = val; } @@ -181,7 +183,7 @@ namespace llarp DelNode(const Key_t& key) { auto itr = nodes.find(key); - if(itr != nodes.end()) + if (itr != nodes.end()) { nodes.erase(itr); } @@ -194,25 +196,25 @@ namespace llarp } // remove all nodes who's key matches a predicate - template < typename Predicate > + template void RemoveIf(Predicate pred) { auto itr = nodes.begin(); - while(itr != nodes.end()) + while (itr != nodes.end()) { - if(pred(itr->first)) + if (pred(itr->first)) itr = nodes.erase(itr); else ++itr; } } - template < typename Visit_t > + template void ForEachNode(Visit_t visit) { - for(const auto& item : nodes) + for (const auto& item : nodes) { visit(item.second); } diff --git a/llarp/dht/context.cpp b/llarp/dht/context.cpp index 24a07cf3e..c6cdb376e 100644 --- a/llarp/dht/context.cpp +++ b/llarp/dht/context.cpp @@ -47,28 +47,36 @@ namespace llarp void LookupIntroSetRelayed( - const Key_t& target, const Key_t& whoasked, uint64_t whoaskedTX, - const Key_t& askpeer, uint64_t relayOrder, + const Key_t& target, + const Key_t& whoasked, + uint64_t whoaskedTX, + const Key_t& askpeer, + uint64_t relayOrder, service::EncryptedIntroSetLookupHandler result = nullptr) override; void LookupIntroSetDirect( - const Key_t& target, const Key_t& whoasked, uint64_t whoaskedTX, + const Key_t& target, + const Key_t& whoasked, + uint64_t whoaskedTX, const Key_t& askpeer, service::EncryptedIntroSetLookupHandler result = nullptr) override; /// on behalf of whoasked request router with public key target from dht /// router with key askpeer void - LookupRouterRecursive(const RouterID& target, const Key_t& whoasked, - uint64_t whoaskedTX, const Key_t& askpeer, - RouterLookupHandler result = nullptr) override; + LookupRouterRecursive( + const RouterID& target, + const Key_t& whoasked, + uint64_t whoaskedTX, + const Key_t& askpeer, + RouterLookupHandler result = nullptr) override; bool LookupRouter(const RouterID& target, RouterLookupHandler result) override { Key_t askpeer; - if(!_nodes->FindClosest(Key_t(target), askpeer)) + if (!_nodes->FindClosest(Key_t(target), askpeer)) { return false; } @@ -84,58 +92,72 @@ namespace llarp /// issue dht lookup for router via askpeer and send reply to local path void - LookupRouterForPath(const RouterID& target, uint64_t txid, - const PathID_t& path, const Key_t& askpeer) override; + LookupRouterForPath( + const RouterID& target, + uint64_t txid, + const PathID_t& path, + const Key_t& askpeer) override; /// issue dht lookup for introset for addr via askpeer and send reply to /// local path void - LookupIntroSetForPath(const Key_t& addr, uint64_t txid, - const llarp::PathID_t& path, const Key_t& askpeer, - uint64_t relayOrder) override; + LookupIntroSetForPath( + const Key_t& addr, + uint64_t txid, + const llarp::PathID_t& path, + const Key_t& askpeer, + uint64_t relayOrder) override; /// send a dht message to peer, if keepalive is true then keep the session /// with that peer alive for 10 seconds void - DHTSendTo(const RouterID& peer, IMessage* msg, - bool keepalive = true) override; + DHTSendTo(const RouterID& peer, IMessage* msg, bool keepalive = true) override; /// get routers closest to target excluding requester bool HandleExploritoryRouterLookup( - const Key_t& requester, uint64_t txid, const RouterID& target, - std::vector< std::unique_ptr< IMessage > >& reply) override; + const Key_t& requester, + uint64_t txid, + const RouterID& target, + std::vector>& reply) override; /// handle rc lookup from requester for target void LookupRouterRelayed( - const Key_t& requester, uint64_t txid, const Key_t& target, + const Key_t& requester, + uint64_t txid, + const Key_t& target, bool recursive, - std::vector< std::unique_ptr< IMessage > >& replies) override; + std::vector>& replies) override; /// relay a dht message from a local path to the main network bool - RelayRequestForPath(const llarp::PathID_t& localPath, - const IMessage& msg) override; + RelayRequestForPath(const llarp::PathID_t& localPath, const IMessage& msg) override; /// send introset to peer as R/S void - PropagateLocalIntroSet(const PathID_t& from, uint64_t txid, - const service::EncryptedIntroSet& introset, - const Key_t& tellpeer, uint64_t relayOrder); + PropagateLocalIntroSet( + const PathID_t& from, + uint64_t txid, + const service::EncryptedIntroSet& introset, + const Key_t& tellpeer, + uint64_t relayOrder); /// send introset to peer from source with S counter and excluding peers void - PropagateIntroSetTo(const Key_t& from, uint64_t txid, - const service::EncryptedIntroSet& introset, - const Key_t& tellpeer, uint64_t relayOrder); + PropagateIntroSetTo( + const Key_t& from, + uint64_t txid, + const service::EncryptedIntroSet& introset, + const Key_t& tellpeer, + uint64_t relayOrder); /// initialize dht context and explore every exploreInterval milliseconds void Init(const Key_t& us, AbstractRouter* router) override; /// get localally stored introset by service address - nonstd::optional< llarp::service::EncryptedIntroSet > + nonstd::optional GetIntroSetByLocation(const Key_t& location) const override; void @@ -147,12 +169,12 @@ namespace llarp llarp::AbstractRouter* router{nullptr}; // for router contacts - std::unique_ptr< Bucket< RCNode > > _nodes; + std::unique_ptr> _nodes; // for introduction sets - std::unique_ptr< Bucket< ISNode > > _services; + std::unique_ptr> _services; - Bucket< ISNode >* + Bucket* services() override { return _services.get(); @@ -171,7 +193,7 @@ namespace llarp return allowTransit; } - Bucket< RCNode >* + Bucket* Nodes() const override { return _nodes.get(); @@ -180,14 +202,14 @@ namespace llarp void PutRCNodeAsync(const RCNode& val) override { - auto func = std::bind(&Bucket< RCNode >::PutNode, Nodes(), val); + auto func = std::bind(&Bucket::PutNode, Nodes(), val); LogicCall(router->logic(), func); } void DelRCNodeAsync(const Key_t& val) override { - auto func = std::bind(&Bucket< RCNode >::DelNode, Nodes(), val); + auto func = std::bind(&Bucket::DelNode, Nodes(), val); LogicCall(router->logic(), func); } @@ -283,16 +305,15 @@ namespace llarp { // ask N random peers for new routers llarp::LogDebug("Exploring network via ", N, " peers"); - std::set< Key_t > peers; + std::set peers; - if(_nodes->GetManyRandom(peers, N)) + if (_nodes->GetManyRandom(peers, N)) { - for(const auto& peer : peers) + for (const auto& peer : peers) ExploreNetworkVia(peer); } else - llarp::LogError("failed to select ", N, - " random nodes for exploration"); + llarp::LogError("failed to select ", N, " random nodes for exploration"); } void @@ -313,14 +334,14 @@ namespace llarp CleanupTX(); const llarp_time_t now = Now(); - if(_services) + if (_services) { // expire intro sets auto& nodes = _services->nodes; - auto itr = nodes.begin(); - while(itr != nodes.end()) + auto itr = nodes.begin(); + while (itr != nodes.end()) { - if(itr->second.introset.IsExpired(now)) + if (itr->second.introset.IsExpired(now)) { itr = nodes.erase(itr); } @@ -333,17 +354,19 @@ namespace llarp void Context::LookupRouterRelayed( - const Key_t& requester, uint64_t txid, const Key_t& target, - bool recursive, std::vector< std::unique_ptr< IMessage > >& replies) + const Key_t& requester, + uint64_t txid, + const Key_t& target, + bool recursive, + std::vector>& replies) { - if(target == ourKey) + if (target == ourKey) { // we are the target, give them our RC - replies.emplace_back( - new GotRouterMessage(requester, txid, {router->rc()}, false)); + replies.emplace_back(new GotRouterMessage(requester, txid, {router->rc()}, false)); return; } - if(not GetRouter()->ConnectionToRouterAllowed(target.as_array())) + if (not GetRouter()->ConnectionToRouterAllowed(target.as_array())) { // explicitly not allowed replies.emplace_back(new GotRouterMessage(requester, txid, {}, false)); @@ -352,10 +375,10 @@ namespace llarp const auto rc = GetRouter()->nodedb()->FindClosestTo(target); const Key_t next(rc.pubkey); { - if(next == target) + if (next == target) { // we know the target - if(rc.ExpiresSoon(llarp::time_now_ms())) + if (rc.ExpiresSoon(llarp::time_now_ms())) { // ask target for their rc to keep it updated LookupRouterRecursive(target.as_array(), requester, txid, next); @@ -363,14 +386,13 @@ namespace llarp else { // send reply with rc we know of - replies.emplace_back( - new GotRouterMessage(requester, txid, {rc}, false)); + replies.emplace_back(new GotRouterMessage(requester, txid, {rc}, false)); } } - else if(recursive) // are we doing a recursive lookup? + else if (recursive) // are we doing a recursive lookup? { // is the next peer we ask closer to the target than us? - if((next ^ target) < (ourKey ^ target)) + if ((next ^ target) < (ourKey ^ target)) { // yes it is closer, ask neighbour recursively LookupRouterRecursive(target.as_array(), requester, txid, next); @@ -379,24 +401,22 @@ namespace llarp { // no we are closer to the target so tell requester it's not there // so they switch to iterative lookup - replies.emplace_back( - new GotRouterMessage(requester, txid, {}, false)); + replies.emplace_back(new GotRouterMessage(requester, txid, {}, false)); } } else { // iterative lookup and we don't have it tell them who is closer - replies.emplace_back( - new GotRouterMessage(requester, next, txid, false)); + replies.emplace_back(new GotRouterMessage(requester, next, txid, false)); } } } - nonstd::optional< llarp::service::EncryptedIntroSet > + nonstd::optional Context::GetIntroSetByLocation(const Key_t& key) const { auto itr = _services->nodes.find(key); - if(itr == _services->nodes.end()) + if (itr == _services->nodes.end()) return {}; return itr->second.introset; } @@ -415,23 +435,22 @@ namespace llarp util::StatusObject Context::ExtractStatus() const { - util::StatusObject obj{ - {"pendingRouterLookups", pendingRouterLookups().ExtractStatus()}, - {"pendingIntrosetLookups", _pendingIntrosetLookups.ExtractStatus()}, - {"pendingExploreLookups", pendingExploreLookups().ExtractStatus()}, - {"nodes", _nodes->ExtractStatus()}, - {"services", _services->ExtractStatus()}, - {"ourKey", ourKey.ToHex()}}; + util::StatusObject obj{{"pendingRouterLookups", pendingRouterLookups().ExtractStatus()}, + {"pendingIntrosetLookups", _pendingIntrosetLookups.ExtractStatus()}, + {"pendingExploreLookups", pendingExploreLookups().ExtractStatus()}, + {"nodes", _nodes->ExtractStatus()}, + {"services", _services->ExtractStatus()}, + {"ourKey", ourKey.ToHex()}}; return obj; } void Context::Init(const Key_t& us, AbstractRouter* r) { - router = r; - ourKey = us; - _nodes = std::make_unique< Bucket< RCNode > >(ourKey, llarp::randint); - _services = std::make_unique< Bucket< ISNode > >(ourKey, llarp::randint); + router = r; + ourKey = us; + _nodes = std::make_unique>(ourKey, llarp::randint); + _services = std::make_unique>(ourKey, llarp::randint); llarp::LogDebug("initialize dht with key ", ourKey); // start cleanup timer ScheduleCleanupTimer(); @@ -441,8 +460,7 @@ namespace llarp Context::ScheduleCleanupTimer() { router->logic()->call_later( - 1s, - std::bind(&llarp::dht::Context::handle_cleaner_timer, this, 1000)); + 1s, std::bind(&llarp::dht::Context::handle_cleaner_timer, this, 1000)); } void @@ -451,7 +469,7 @@ namespace llarp llarp::DHTImmediateMessage m; m.msgs.emplace_back(msg); router->SendToOrQueue(peer, &m, [](SendStatus status) { - if(status != SendStatus::Success) + if (status != SendStatus::Success) LogInfo("DHTSendTo unsuccessful, status: ", (int)status); }); auto now = Now(); @@ -466,9 +484,9 @@ namespace llarp Context::RelayRequestForPath(const llarp::PathID_t& id, const IMessage& msg) { llarp::routing::DHTMessage reply; - if(!msg.HandleMessage(router->dht(), reply.M)) + if (!msg.HandleMessage(router->dht(), reply.M)) return false; - if(not reply.M.empty()) + if (not reply.M.empty()) { auto path = router->pathContext().GetByUpstream(router->pubkey(), id); return path && path->SendRoutingMessage(reply, router); @@ -477,106 +495,120 @@ namespace llarp } void - Context::LookupIntroSetForPath(const Key_t& addr, uint64_t txid, - const llarp::PathID_t& path, - const Key_t& askpeer, uint64_t relayOrder) + Context::LookupIntroSetForPath( + const Key_t& addr, + uint64_t txid, + const llarp::PathID_t& path, + const Key_t& askpeer, + uint64_t relayOrder) { const TXOwner asker(OurKey(), txid); const TXOwner peer(askpeer, ++ids); _pendingIntrosetLookups.NewTX( - peer, asker, asker, - new LocalServiceAddressLookup(path, txid, relayOrder, addr, this, - askpeer)); + peer, + asker, + asker, + new LocalServiceAddressLookup(path, txid, relayOrder, addr, this, askpeer)); } void - Context::PropagateIntroSetTo(const Key_t& from, uint64_t txid, - const service::EncryptedIntroSet& introset, - const Key_t& tellpeer, uint64_t relayOrder) + Context::PropagateIntroSetTo( + const Key_t& from, + uint64_t txid, + const service::EncryptedIntroSet& introset, + const Key_t& tellpeer, + uint64_t relayOrder) { const TXOwner asker(from, txid); const TXOwner peer(tellpeer, ++ids); _pendingIntrosetLookups.NewTX( - peer, asker, asker, - new PublishServiceJob(asker, introset, this, relayOrder)); + peer, asker, asker, new PublishServiceJob(asker, introset, this, relayOrder)); } void - Context::PropagateLocalIntroSet(const PathID_t& from, uint64_t txid, - const service::EncryptedIntroSet& introset, - const Key_t& tellpeer, uint64_t relayOrder) + Context::PropagateLocalIntroSet( + const PathID_t& from, + uint64_t txid, + const service::EncryptedIntroSet& introset, + const Key_t& tellpeer, + uint64_t relayOrder) { const TXOwner asker(OurKey(), txid); const TXOwner peer(tellpeer, ++ids); _pendingIntrosetLookups.NewTX( - peer, asker, peer, - new LocalPublishServiceJob(peer, from, txid, introset, this, - relayOrder)); + peer, + asker, + peer, + new LocalPublishServiceJob(peer, from, txid, introset, this, relayOrder)); } void Context::LookupIntroSetRelayed( - const Key_t& addr, const Key_t& whoasked, uint64_t txid, - const Key_t& askpeer, uint64_t relayOrder, + const Key_t& addr, + const Key_t& whoasked, + uint64_t txid, + const Key_t& askpeer, + uint64_t relayOrder, service::EncryptedIntroSetLookupHandler handler) { const TXOwner asker(whoasked, txid); const TXOwner peer(askpeer, ++ids); _pendingIntrosetLookups.NewTX( - peer, asker, asker, - new ServiceAddressLookup(asker, addr, this, relayOrder, handler)); + peer, asker, asker, new ServiceAddressLookup(asker, addr, this, relayOrder, handler)); } void Context::LookupIntroSetDirect( - const Key_t& addr, const Key_t& whoasked, uint64_t txid, - const Key_t& askpeer, service::EncryptedIntroSetLookupHandler handler) + const Key_t& addr, + const Key_t& whoasked, + uint64_t txid, + const Key_t& askpeer, + service::EncryptedIntroSetLookupHandler handler) { const TXOwner asker(whoasked, txid); const TXOwner peer(askpeer, ++ids); _pendingIntrosetLookups.NewTX( - peer, asker, asker, - new ServiceAddressLookup(asker, addr, this, 0, handler), 1s); + peer, asker, asker, new ServiceAddressLookup(asker, addr, this, 0, handler), 1s); } bool Context::HandleExploritoryRouterLookup( - const Key_t& requester, uint64_t txid, const RouterID& target, - std::vector< std::unique_ptr< IMessage > >& reply) + const Key_t& requester, + uint64_t txid, + const RouterID& target, + std::vector>& reply) { - std::vector< RouterID > closer; + std::vector closer; const Key_t t(target.as_array()); - std::set< Key_t > foundRouters; - if(!_nodes) + std::set foundRouters; + if (!_nodes) return false; const size_t nodeCount = _nodes->size(); - if(nodeCount == 0) + if (nodeCount == 0) { - llarp::LogError( - "cannot handle exploritory router lookup, no dht peers"); + llarp::LogError("cannot handle exploritory router lookup, no dht peers"); return false; } - llarp::LogDebug("We have ", _nodes->size(), - " connected nodes into the DHT"); + llarp::LogDebug("We have ", _nodes->size(), " connected nodes into the DHT"); // ourKey should never be in the connected list // requester is likely in the connected list // 4 or connection nodes (minus a potential requestor), whatever is less - if(!_nodes->GetManyNearExcluding(t, foundRouters, - std::min(nodeCount, size_t{4}), - std::set< Key_t >{ourKey, requester})) + if (!_nodes->GetManyNearExcluding( + t, foundRouters, std::min(nodeCount, size_t{4}), std::set{ourKey, requester})) { llarp::LogError( "not enough dht nodes to handle exploritory router lookup, " "have ", - nodeCount, " dht peers"); + nodeCount, + " dht peers"); return false; } - for(const auto& f : foundRouters) + for (const auto& f : foundRouters) { const RouterID id = f.as_array(); // discard shit routers - if(router->routerProfiling().IsBadForConnect(id)) + if (router->routerProfiling().IsBadForConnect(id)) continue; closer.emplace_back(id); } @@ -586,29 +618,28 @@ namespace llarp } void - Context::LookupRouterForPath(const RouterID& target, uint64_t txid, - const llarp::PathID_t& path, - const Key_t& askpeer) + Context::LookupRouterForPath( + const RouterID& target, uint64_t txid, const llarp::PathID_t& path, const Key_t& askpeer) { const TXOwner peer(askpeer, ++ids); const TXOwner whoasked(OurKey(), txid); _pendingRouterLookups.NewTX( - peer, whoasked, target, - new LocalRouterLookup(path, txid, target, this)); + peer, whoasked, target, new LocalRouterLookup(path, txid, target, this)); } void - Context::LookupRouterRecursive(const RouterID& target, - const Key_t& whoasked, uint64_t txid, - const Key_t& askpeer, - RouterLookupHandler handler) + Context::LookupRouterRecursive( + const RouterID& target, + const Key_t& whoasked, + uint64_t txid, + const Key_t& askpeer, + RouterLookupHandler handler) { const TXOwner asker(whoasked, txid); const TXOwner peer(askpeer, ++ids); _pendingRouterLookups.NewTX( - peer, asker, target, - new RecursiveRouterLookup(asker, target, this, handler)); + peer, asker, target, new RecursiveRouterLookup(asker, target, this, handler)); } llarp_time_t @@ -617,10 +648,10 @@ namespace llarp return router->Now(); } - std::unique_ptr< AbstractContext > + std::unique_ptr makeContext() { - return std::make_unique< Context >(); + return std::make_unique(); } } // namespace dht diff --git a/llarp/dht/context.hpp b/llarp/dht/context.hpp index fd23025af..3f0febb72 100644 --- a/llarp/dht/context.hpp +++ b/llarp/dht/context.hpp @@ -34,12 +34,9 @@ namespace llarp struct AbstractContext { - using PendingIntrosetLookups = - TXHolder< TXOwner, service::EncryptedIntroSet, TXOwner::Hash >; - using PendingRouterLookups = - TXHolder< RouterID, RouterContact, RouterID::Hash >; - using PendingExploreLookups = - TXHolder< RouterID, RouterID, RouterID::Hash >; + using PendingIntrosetLookups = TXHolder; + using PendingRouterLookups = TXHolder; + using PendingExploreLookups = TXHolder; virtual ~AbstractContext() = 0; @@ -47,37 +44,49 @@ namespace llarp LookupRouter(const RouterID& target, RouterLookupHandler result) = 0; virtual void - LookupRouterRecursive(const RouterID& target, const Key_t& whoasked, - uint64_t whoaskedTX, const Key_t& askpeer, - RouterLookupHandler result = nullptr) = 0; + LookupRouterRecursive( + const RouterID& target, + const Key_t& whoasked, + uint64_t whoaskedTX, + const Key_t& askpeer, + RouterLookupHandler result = nullptr) = 0; /// Ask a Service Node to perform an Introset lookup for us virtual void - LookupIntroSetRelayed(const Key_t& target, const Key_t& whoasked, - uint64_t whoaskedTX, const Key_t& askpeer, - uint64_t relayOrder, - service::EncryptedIntroSetLookupHandler result = - service::EncryptedIntroSetLookupHandler()) = 0; + LookupIntroSetRelayed( + const Key_t& target, + const Key_t& whoasked, + uint64_t whoaskedTX, + const Key_t& askpeer, + uint64_t relayOrder, + service::EncryptedIntroSetLookupHandler result = + service::EncryptedIntroSetLookupHandler()) = 0; /// Directly as a Service Node for an Introset virtual void - LookupIntroSetDirect(const Key_t& target, const Key_t& whoasked, - uint64_t whoaskedTX, const Key_t& askpeer, - service::EncryptedIntroSetLookupHandler result = - service::EncryptedIntroSetLookupHandler()) = 0; + LookupIntroSetDirect( + const Key_t& target, + const Key_t& whoasked, + uint64_t whoaskedTX, + const Key_t& askpeer, + service::EncryptedIntroSetLookupHandler result = + service::EncryptedIntroSetLookupHandler()) = 0; virtual bool HasRouterLookup(const RouterID& target) const = 0; /// issue dht lookup for router via askpeer and send reply to local path virtual void - LookupRouterForPath(const RouterID& target, uint64_t txid, - const PathID_t& path, const Key_t& askpeer) = 0; + LookupRouterForPath( + const RouterID& target, uint64_t txid, const PathID_t& path, const Key_t& askpeer) = 0; virtual void - LookupIntroSetForPath(const Key_t& addr, uint64_t txid, - const PathID_t& path, const Key_t& askpeer, - uint64_t relayOrder) = 0; + LookupIntroSetForPath( + const Key_t& addr, + uint64_t txid, + const PathID_t& path, + const Key_t& askpeer, + uint64_t relayOrder) = 0; virtual void DHTSendTo(const RouterID& peer, IMessage* msg, bool keepalive = true) = 0; @@ -85,35 +94,45 @@ namespace llarp /// get routers closest to target excluding requester virtual bool HandleExploritoryRouterLookup( - const Key_t& requester, uint64_t txid, const RouterID& target, - std::vector< std::unique_ptr< IMessage > >& reply) = 0; + const Key_t& requester, + uint64_t txid, + const RouterID& target, + std::vector>& reply) = 0; /// handle rc lookup from requester for target virtual void LookupRouterRelayed( - const Key_t& requester, uint64_t txid, const Key_t& target, + const Key_t& requester, + uint64_t txid, + const Key_t& target, bool recursive, - std::vector< std::unique_ptr< IMessage > >& replies) = 0; + std::vector>& replies) = 0; virtual bool RelayRequestForPath(const PathID_t& localPath, const IMessage& msg) = 0; /// send introset to peer from source with S counter and excluding peers virtual void - PropagateLocalIntroSet(const PathID_t& path, uint64_t sourceTX, - const service::EncryptedIntroSet& introset, - const Key_t& peer, uint64_t relayOrder) = 0; + PropagateLocalIntroSet( + const PathID_t& path, + uint64_t sourceTX, + const service::EncryptedIntroSet& introset, + const Key_t& peer, + uint64_t relayOrder) = 0; /// send introset to peer from source with S counter and excluding peers virtual void - PropagateIntroSetTo(const Key_t& source, uint64_t sourceTX, - const service::EncryptedIntroSet& introset, - const Key_t& peer, uint64_t relayOrder) = 0; + PropagateIntroSetTo( + const Key_t& source, + uint64_t sourceTX, + const service::EncryptedIntroSet& introset, + const Key_t& peer, + uint64_t relayOrder) = 0; virtual void Init(const Key_t& us, AbstractRouter* router) = 0; - virtual nonstd::optional< llarp::service::EncryptedIntroSet > + virtual nonstd::optional GetIntroSetByLocation(const Key_t& location) const = 0; virtual llarp_time_t @@ -149,7 +168,7 @@ namespace llarp virtual const PendingExploreLookups& pendingExploreLookups() const = 0; - virtual Bucket< ISNode >* + virtual Bucket* services() = 0; virtual bool& @@ -157,7 +176,7 @@ namespace llarp virtual const bool& AllowTransit() const = 0; - virtual Bucket< RCNode >* + virtual Bucket* Nodes() const = 0; virtual void @@ -173,14 +192,14 @@ namespace llarp StoreRC(const RouterContact rc) const = 0; }; - std::unique_ptr< AbstractContext > + std::unique_ptr makeContext(); } // namespace dht } // namespace llarp struct llarp_dht_context { - std::unique_ptr< llarp::dht::AbstractContext > impl; + std::unique_ptr impl; llarp::AbstractRouter* parent; llarp_dht_context(llarp::AbstractRouter* router); }; diff --git a/llarp/dht/dht.cpp b/llarp/dht/dht.cpp index cd4f29f57..74ed56a61 100644 --- a/llarp/dht/dht.cpp +++ b/llarp/dht/dht.cpp @@ -2,47 +2,46 @@ #include #include -llarp_dht_context::llarp_dht_context(llarp::AbstractRouter *router) +llarp_dht_context::llarp_dht_context(llarp::AbstractRouter* router) { parent = router; - impl = llarp::dht::makeContext(); + impl = llarp::dht::makeContext(); } -struct llarp_dht_context * -llarp_dht_context_new(llarp::AbstractRouter *router) +struct llarp_dht_context* +llarp_dht_context_new(llarp::AbstractRouter* router) { return new llarp_dht_context(router); } void -llarp_dht_context_free(struct llarp_dht_context *ctx) +llarp_dht_context_free(struct llarp_dht_context* ctx) { delete ctx; } void -__llarp_dht_remove_peer(struct llarp_dht_context *ctx, const byte_t *id) +__llarp_dht_remove_peer(struct llarp_dht_context* ctx, const byte_t* id) { ctx->impl->Nodes()->DelNode(llarp::dht::Key_t(id)); } void -llarp_dht_allow_transit(llarp_dht_context *ctx) +llarp_dht_allow_transit(llarp_dht_context* ctx) { ctx->impl->AllowTransit() = true; } void -llarp_dht_context_start(struct llarp_dht_context *ctx, const byte_t *key) +llarp_dht_context_start(struct llarp_dht_context* ctx, const byte_t* key) { ctx->impl->Init(llarp::dht::Key_t(key), ctx->parent); } void -llarp_dht_lookup_router(struct llarp_dht_context *ctx, - struct llarp_router_lookup_job *job) +llarp_dht_lookup_router(struct llarp_dht_context* ctx, struct llarp_router_lookup_job* job) { - job->dht = ctx; + job->dht = ctx; job->found = false; job->result.Clear(); // llarp_rc_clear(&job->result); diff --git a/llarp/dht/dht.h b/llarp/dht/dht.h index c7854085c..972a5ed54 100644 --- a/llarp/dht/dht.h +++ b/llarp/dht/dht.h @@ -59,7 +59,6 @@ void __llarp_dht_remove_peer(struct llarp_dht_context* ctx, const byte_t* id); void -llarp_dht_lookup_router(struct llarp_dht_context* ctx, - struct llarp_router_lookup_job* job); +llarp_dht_lookup_router(struct llarp_dht_context* ctx, struct llarp_router_lookup_job* job); #endif diff --git a/llarp/dht/explorenetworkjob.cpp b/llarp/dht/explorenetworkjob.cpp index 70912137b..3b80bbca4 100644 --- a/llarp/dht/explorenetworkjob.cpp +++ b/llarp/dht/explorenetworkjob.cpp @@ -13,14 +13,11 @@ namespace llarp namespace dht { void - ExploreNetworkJob::Start(const TXOwner &peer) + ExploreNetworkJob::Start(const TXOwner& peer) { - auto msg = new FindRouterMessage(peer.txid); auto router = parent->GetRouter(); - router->NotifyRouterEvent< tooling::FindRouterSentEvent >( - router->pubkey(), - msg); + router->NotifyRouterEvent(router->pubkey(), msg); parent->DHTSendTo(peer.node.as_array(), msg); } @@ -32,15 +29,13 @@ namespace llarp auto router = parent->GetRouter(); using std::placeholders::_1; - for(const auto &pk : valuesFound) + for (const auto& pk : valuesFound) { // lookup router - if(router and router->nodedb()->Has(pk)) + if (router and router->nodedb()->Has(pk)) continue; parent->LookupRouter( - pk, - std::bind(&AbstractRouter::HandleDHTLookupForExplore, router, pk, - _1)); + pk, std::bind(&AbstractRouter::HandleDHTLookupForExplore, router, pk, _1)); } } } // namespace dht diff --git a/llarp/dht/explorenetworkjob.hpp b/llarp/dht/explorenetworkjob.hpp index 598fc663a..6c6b22678 100644 --- a/llarp/dht/explorenetworkjob.hpp +++ b/llarp/dht/explorenetworkjob.hpp @@ -8,22 +8,22 @@ namespace llarp { namespace dht { - struct ExploreNetworkJob : public TX< RouterID, RouterID > + struct ExploreNetworkJob : public TX { - ExploreNetworkJob(const RouterID &peer, AbstractContext *ctx) - : TX< RouterID, RouterID >(TXOwner{}, peer, ctx) + ExploreNetworkJob(const RouterID& peer, AbstractContext* ctx) + : TX(TXOwner{}, peer, ctx) { } bool - Validate(const RouterID &) const override + Validate(const RouterID&) const override { // TODO: check with lokid return true; } void - Start(const TXOwner &peer) override; + Start(const TXOwner& peer) override; void SendReply() override; diff --git a/llarp/dht/key.hpp b/llarp/dht/key.hpp index 760cc2614..804e7f040 100644 --- a/llarp/dht/key.hpp +++ b/llarp/dht/key.hpp @@ -10,22 +10,21 @@ namespace llarp { namespace dht { - struct Key_t : public AlignedBuffer< 32 > + struct Key_t : public AlignedBuffer<32> { - explicit Key_t(const byte_t* buf) : AlignedBuffer< SIZE >(buf) + explicit Key_t(const byte_t* buf) : AlignedBuffer(buf) { } - explicit Key_t(const Data& data) : AlignedBuffer< SIZE >(data) + explicit Key_t(const Data& data) : AlignedBuffer(data) { } - explicit Key_t(const AlignedBuffer< SIZE >& data) - : AlignedBuffer< SIZE >(data) + explicit Key_t(const AlignedBuffer& data) : AlignedBuffer(data) { } - Key_t() : AlignedBuffer< SIZE >() + Key_t() : AlignedBuffer() { } @@ -50,8 +49,7 @@ namespace llarp operator^(const Key_t& other) const { Key_t dist; - std::transform(begin(), end(), other.begin(), dist.begin(), - std::bit_xor< byte_t >()); + std::transform(begin(), end(), other.begin(), dist.begin(), std::bit_xor()); return dist; } diff --git a/llarp/dht/localrouterlookup.cpp b/llarp/dht/localrouterlookup.cpp index 7e953f9e7..11766f17d 100644 --- a/llarp/dht/localrouterlookup.cpp +++ b/llarp/dht/localrouterlookup.cpp @@ -12,11 +12,9 @@ namespace llarp { namespace dht { - LocalRouterLookup::LocalRouterLookup(const PathID_t &path, uint64_t txid, - const RouterID &_target, - AbstractContext *ctx) - : RecursiveRouterLookup(TXOwner{ctx->OurKey(), txid}, _target, ctx, - nullptr) + LocalRouterLookup::LocalRouterLookup( + const PathID_t& path, uint64_t txid, const RouterID& _target, AbstractContext* ctx) + : RecursiveRouterLookup(TXOwner{ctx->OurKey(), txid}, _target, ctx, nullptr) , localPath(path) { } @@ -24,9 +22,9 @@ namespace llarp void LocalRouterLookup::SendReply() { - auto path = parent->GetRouter()->pathContext().GetByUpstream( - parent->OurKey().as_array(), localPath); - if(!path) + auto path = + parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + if (!path) { llarp::LogWarn( "did not send reply for relayed dht request, no such local path " @@ -34,16 +32,16 @@ namespace llarp localPath); return; } - if(valuesFound.size()) + if (valuesFound.size()) { RouterContact found; - for(const auto &rc : valuesFound) + for (const auto& rc : valuesFound) { - if(rc.OtherIsNewer(found)) + if (rc.OtherIsNewer(found)) found = rc; } valuesFound.clear(); - if(not found.pubkey.IsZero()) + if (not found.pubkey.IsZero()) { valuesFound.resize(1); valuesFound[0] = found; @@ -54,9 +52,8 @@ namespace llarp } } routing::DHTMessage msg; - msg.M.emplace_back(new GotRouterMessage(parent->OurKey(), whoasked.txid, - valuesFound, true)); - if(!path->SendRoutingMessage(msg, parent->GetRouter())) + msg.M.emplace_back(new GotRouterMessage(parent->OurKey(), whoasked.txid, valuesFound, true)); + if (!path->SendRoutingMessage(msg, parent->GetRouter())) { llarp::LogWarn( "failed to send routing message when informing result of dht " diff --git a/llarp/dht/localrouterlookup.hpp b/llarp/dht/localrouterlookup.hpp index 35834d0df..8c103c6bd 100644 --- a/llarp/dht/localrouterlookup.hpp +++ b/llarp/dht/localrouterlookup.hpp @@ -15,8 +15,8 @@ namespace llarp { PathID_t localPath; - LocalRouterLookup(const PathID_t &path, uint64_t txid, - const RouterID &target, AbstractContext *ctx); + LocalRouterLookup( + const PathID_t& path, uint64_t txid, const RouterID& target, AbstractContext* ctx); void SendReply() override; diff --git a/llarp/dht/localserviceaddresslookup.cpp b/llarp/dht/localserviceaddresslookup.cpp index 23c2c4912..081f20d42 100644 --- a/llarp/dht/localserviceaddresslookup.cpp +++ b/llarp/dht/localserviceaddresslookup.cpp @@ -12,11 +12,13 @@ namespace llarp namespace dht { LocalServiceAddressLookup::LocalServiceAddressLookup( - const PathID_t &pathid, uint64_t txid, uint64_t relayOrder, - const Key_t &addr, AbstractContext *ctx, - __attribute__((unused)) const Key_t &askpeer) - : ServiceAddressLookup(TXOwner{ctx->OurKey(), txid}, addr, ctx, - relayOrder, nullptr) + const PathID_t& pathid, + uint64_t txid, + uint64_t relayOrder, + const Key_t& addr, + AbstractContext* ctx, + __attribute__((unused)) const Key_t& askpeer) + : ServiceAddressLookup(TXOwner{ctx->OurKey(), txid}, addr, ctx, relayOrder, nullptr) , localPath(pathid) { } @@ -24,9 +26,9 @@ namespace llarp void LocalServiceAddressLookup::SendReply() { - auto path = parent->GetRouter()->pathContext().GetByUpstream( - parent->OurKey().as_array(), localPath); - if(!path) + auto path = + parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + if (!path) { llarp::LogWarn( "did not send reply for relayed dht request, no such local path " @@ -35,12 +37,12 @@ namespace llarp return; } // pick newest if we have more than 1 result - if(valuesFound.size()) + if (valuesFound.size()) { service::EncryptedIntroSet found; - for(const auto &introset : valuesFound) + for (const auto& introset : valuesFound) { - if(found.OtherIsNewer(introset)) + if (found.OtherIsNewer(introset)) found = introset; } valuesFound.clear(); @@ -48,7 +50,7 @@ namespace llarp } routing::DHTMessage msg; msg.M.emplace_back(new GotIntroMessage(valuesFound, whoasked.txid)); - if(!path->SendRoutingMessage(msg, parent->GetRouter())) + if (!path->SendRoutingMessage(msg, parent->GetRouter())) { llarp::LogWarn( "failed to send routing message when informing result of dht " diff --git a/llarp/dht/localserviceaddresslookup.hpp b/llarp/dht/localserviceaddresslookup.hpp index 04ba23530..5b228db70 100644 --- a/llarp/dht/localserviceaddresslookup.hpp +++ b/llarp/dht/localserviceaddresslookup.hpp @@ -13,10 +13,13 @@ namespace llarp { PathID_t localPath; - LocalServiceAddressLookup(const PathID_t &pathid, uint64_t txid, - uint64_t relayOrder, const Key_t &addr, - AbstractContext *ctx, - __attribute__((unused)) const Key_t &askpeer); + LocalServiceAddressLookup( + const PathID_t& pathid, + uint64_t txid, + uint64_t relayOrder, + const Key_t& addr, + AbstractContext* ctx, + __attribute__((unused)) const Key_t& askpeer); void SendReply() override; diff --git a/llarp/dht/localtaglookup.cpp b/llarp/dht/localtaglookup.cpp index ec223d24c..5806716c5 100644 --- a/llarp/dht/localtaglookup.cpp +++ b/llarp/dht/localtaglookup.cpp @@ -10,20 +10,18 @@ namespace llarp { namespace dht { - LocalTagLookup::LocalTagLookup(const PathID_t &path, uint64_t txid, - const service::Tag &_target, - AbstractContext *ctx) - : TagLookup(TXOwner{ctx->OurKey(), txid}, _target, ctx, 0) - , localPath(path) + LocalTagLookup::LocalTagLookup( + const PathID_t& path, uint64_t txid, const service::Tag& _target, AbstractContext* ctx) + : TagLookup(TXOwner{ctx->OurKey(), txid}, _target, ctx, 0), localPath(path) { } void LocalTagLookup::SendReply() { - auto path = parent->GetRouter()->pathContext().GetByUpstream( - parent->OurKey().as_array(), localPath); - if(!path) + auto path = + parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + if (!path) { llarp::LogWarn( "did not send reply for relayed dht request, no such local path " @@ -33,7 +31,7 @@ namespace llarp } routing::DHTMessage msg; msg.M.emplace_back(new GotIntroMessage(valuesFound, whoasked.txid)); - if(!path->SendRoutingMessage(msg, parent->GetRouter())) + if (!path->SendRoutingMessage(msg, parent->GetRouter())) { llarp::LogWarn( "failed to send routing message when informing result of dht " diff --git a/llarp/dht/localtaglookup.hpp b/llarp/dht/localtaglookup.hpp index 27aff4852..d51f72e3d 100644 --- a/llarp/dht/localtaglookup.hpp +++ b/llarp/dht/localtaglookup.hpp @@ -11,8 +11,8 @@ namespace llarp { PathID_t localPath; - LocalTagLookup(const PathID_t &path, uint64_t txid, - const service::Tag &target, AbstractContext *ctx); + LocalTagLookup( + const PathID_t& path, uint64_t txid, const service::Tag& target, AbstractContext* ctx); void SendReply() override; diff --git a/llarp/dht/message.cpp b/llarp/dht/message.cpp index ed8640099..35e29c9f9 100644 --- a/llarp/dht/message.cpp +++ b/llarp/dht/message.cpp @@ -14,62 +14,60 @@ namespace llarp { struct MessageDecoder { - const Key_t &From; + const Key_t& From; IMessage::Ptr_t msg; bool firstKey = true; - bool relayed = false; + bool relayed = false; - MessageDecoder(const Key_t &from, bool wasRelayed) - : From(from), relayed(wasRelayed) + MessageDecoder(const Key_t& from, bool wasRelayed) : From(from), relayed(wasRelayed) { } bool - operator()(llarp_buffer_t *buffer, llarp_buffer_t *key) + operator()(llarp_buffer_t* buffer, llarp_buffer_t* key) { llarp_buffer_t strbuf; // check for empty dict - if(!key) + if (!key) return !firstKey; // first key - if(firstKey) + if (firstKey) { - if(!(*key == "A")) + if (!(*key == "A")) return false; - if(!bencode_read_string(buffer, &strbuf)) + if (!bencode_read_string(buffer, &strbuf)) return false; // bad msg size? - if(strbuf.sz != 1) + if (strbuf.sz != 1) return false; - llarp::LogDebug("Handle DHT message ", *strbuf.base, - " relayed=", relayed); - switch(*strbuf.base) + llarp::LogDebug("Handle DHT message ", *strbuf.base, " relayed=", relayed); + switch (*strbuf.base) { case 'F': - msg = std::make_unique< FindIntroMessage >(From, relayed, 0); + msg = std::make_unique(From, relayed, 0); break; case 'R': - if(relayed) - msg = std::make_unique< RelayedFindRouterMessage >(From); + if (relayed) + msg = std::make_unique(From); else - msg = std::make_unique< FindRouterMessage >(From); + msg = std::make_unique(From); break; case 'S': - msg = std::make_unique< GotRouterMessage >(From, relayed); + msg = std::make_unique(From, relayed); break; case 'I': - msg = std::make_unique< PublishIntroMessage >(From, relayed); + msg = std::make_unique(From, relayed); break; case 'G': - if(relayed) + if (relayed) { - msg = std::make_unique< RelayedGotIntroMessage >(); + msg = std::make_unique(); break; } else { - msg = std::make_unique< GotIntroMessage >(From); + msg = std::make_unique(From); break; } default: @@ -86,10 +84,10 @@ namespace llarp }; IMessage::Ptr_t - DecodeMesssage(const Key_t &from, llarp_buffer_t *buf, bool relayed) + DecodeMesssage(const Key_t& from, llarp_buffer_t* buf, bool relayed) { MessageDecoder dec(from, relayed); - if(!bencode_read_dict(dec, buf)) + if (!bencode_read_dict(dec, buf)) return nullptr; return std::move(dec.msg); @@ -97,23 +95,22 @@ namespace llarp struct ListDecoder { - ListDecoder(bool hasRelayed, const Key_t &from, - std::vector< IMessage::Ptr_t > &list) + ListDecoder(bool hasRelayed, const Key_t& from, std::vector& list) : relayed(hasRelayed), From(from), l(list) { } bool relayed; - const Key_t &From; - std::vector< IMessage::Ptr_t > &l; + const Key_t& From; + std::vector& l; bool - operator()(llarp_buffer_t *buffer, bool has) + operator()(llarp_buffer_t* buffer, bool has) { - if(!has) + if (!has) return true; auto msg = DecodeMesssage(From, buffer, relayed); - if(msg) + if (msg) { l.emplace_back(std::move(msg)); return true; @@ -124,8 +121,8 @@ namespace llarp }; bool - DecodeMesssageList(Key_t from, llarp_buffer_t *buf, - std::vector< IMessage::Ptr_t > &list, bool relayed) + DecodeMesssageList( + Key_t from, llarp_buffer_t* buf, std::vector& list, bool relayed) { ListDecoder dec(relayed, from, list); return bencode_read_list(dec, buf); diff --git a/llarp/dht/message.hpp b/llarp/dht/message.hpp index cf5adf199..9f7d9af0d 100644 --- a/llarp/dht/message.hpp +++ b/llarp/dht/message.hpp @@ -23,11 +23,10 @@ namespace llarp { } - using Ptr_t = std::unique_ptr< IMessage >; + using Ptr_t = std::unique_ptr; virtual bool - HandleMessage(struct llarp_dht_context* dht, - std::vector< Ptr_t >& replies) const = 0; + HandleMessage(struct llarp_dht_context* dht, std::vector& replies) const = 0; virtual bool BEncode(llarp_buffer_t* buf) const = 0; @@ -44,9 +43,8 @@ namespace llarp DecodeMessage(const Key_t& from, llarp_buffer_t* buf, bool relayed = false); bool - DecodeMesssageList(Key_t from, llarp_buffer_t* buf, - std::vector< IMessage::Ptr_t >& dst, - bool relayed = false); + DecodeMesssageList( + Key_t from, llarp_buffer_t* buf, std::vector& dst, bool relayed = false); } // namespace dht } // namespace llarp diff --git a/llarp/dht/messages/consensus.hpp b/llarp/dht/messages/consensus.hpp index 59b39d3b9..3c17ba1af 100644 --- a/llarp/dht/messages/consensus.hpp +++ b/llarp/dht/messages/consensus.hpp @@ -12,7 +12,7 @@ namespace llarp /// H ShortHash m_Hash; /// K - std::vector< RouterID > m_Keys; + std::vector m_Keys; /// N uint64_t m_NumberOfEntries; /// O diff --git a/llarp/dht/messages/findintro.cpp b/llarp/dht/messages/findintro.cpp index fc905616d..9c26a11bf 100644 --- a/llarp/dht/messages/findintro.cpp +++ b/llarp/dht/messages/findintro.cpp @@ -16,20 +16,19 @@ namespace llarp { bool read = false; - if(!BEncodeMaybeReadDictEntry("N", tagName, read, k, val)) + if (!BEncodeMaybeReadDictEntry("N", tagName, read, k, val)) return false; - if(!BEncodeMaybeReadDictInt("O", relayOrder, read, k, val)) + if (!BEncodeMaybeReadDictInt("O", relayOrder, read, k, val)) return false; - if(!BEncodeMaybeReadDictEntry("S", location, read, k, val)) + if (!BEncodeMaybeReadDictEntry("S", location, read, k, val)) return false; - if(!BEncodeMaybeReadDictInt("T", txID, read, k, val)) + if (!BEncodeMaybeReadDictInt("T", txID, read, k, val)) return false; - if(!BEncodeMaybeVerifyVersion("V", version, LLARP_PROTO_VERSION, read, k, - val)) + if (!BEncodeMaybeVerifyVersion("V", version, LLARP_PROTO_VERSION, read, k, val)) return false; return read; @@ -38,36 +37,36 @@ namespace llarp bool FindIntroMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; // message id - if(!BEncodeWriteDictMsgType(buf, "A", "F")) + if (!BEncodeWriteDictMsgType(buf, "A", "F")) return false; - if(tagName.Empty()) + if (tagName.Empty()) { // relay order - if(!BEncodeWriteDictInt("O", relayOrder, buf)) + if (!BEncodeWriteDictInt("O", relayOrder, buf)) return false; // service address - if(!BEncodeWriteDictEntry("S", location, buf)) + if (!BEncodeWriteDictEntry("S", location, buf)) return false; } else { - if(!BEncodeWriteDictEntry("N", tagName, buf)) + if (!BEncodeWriteDictEntry("N", tagName, buf)) return false; // relay order - if(!BEncodeWriteDictInt("O", relayOrder, buf)) + if (!BEncodeWriteDictInt("O", relayOrder, buf)) return false; } // txid - if(!BEncodeWriteDictInt("T", txID, buf)) + if (!BEncodeWriteDictInt("T", txID, buf)) return false; // protocol version - if(!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) + if (!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) return false; return bencode_end(buf); @@ -75,20 +74,20 @@ namespace llarp bool FindIntroMessage::HandleMessage( - llarp_dht_context* ctx, std::vector< IMessage::Ptr_t >& replies) const + llarp_dht_context* ctx, std::vector& replies) const { auto& dht = *ctx->impl; - if(dht.pendingIntrosetLookups().HasPendingLookupFrom(TXOwner{From, txID})) + if (dht.pendingIntrosetLookups().HasPendingLookupFrom(TXOwner{From, txID})) { llarp::LogWarn("duplicate FIM from ", From, " txid=", txID); return false; } - if(not tagName.Empty()) + if (not tagName.Empty()) return false; // bad request (request for zero-key) - if(location.IsZero()) + if (location.IsZero()) { // we dont got it replies.emplace_back(new GotIntroMessage({}, txID)); @@ -96,35 +95,34 @@ namespace llarp } // we are relaying this message for e.g. a client - if(relayed) + if (relayed) { - if(relayOrder >= IntroSetStorageRedundancy) + if (relayOrder >= IntroSetStorageRedundancy) { llarp::LogWarn("Invalid relayOrder received: ", relayOrder); replies.emplace_back(new GotIntroMessage({}, txID)); return true; } - auto closestRCs = dht.GetRouter()->nodedb()->FindClosestTo( - location, IntroSetStorageRedundancy); + auto closestRCs = + dht.GetRouter()->nodedb()->FindClosestTo(location, IntroSetStorageRedundancy); - if(closestRCs.size() <= relayOrder) + if (closestRCs.size() <= relayOrder) { - llarp::LogWarn("Can't fulfill FindIntro for relayOrder: ", - relayOrder); + llarp::LogWarn("Can't fulfill FindIntro for relayOrder: ", relayOrder); replies.emplace_back(new GotIntroMessage({}, txID)); return true; } const auto& entry = closestRCs[relayOrder]; - Key_t peer = Key_t(entry.pubkey); + Key_t peer = Key_t(entry.pubkey); dht.LookupIntroSetForPath(location, txID, pathID, peer, 0); } else { // we should have this value if introset was propagated properly const auto maybe = dht.GetIntroSetByLocation(location); - if(maybe.has_value()) + if (maybe.has_value()) { replies.emplace_back(new GotIntroMessage({maybe.value()}, txID)); } diff --git a/llarp/dht/messages/findintro.hpp b/llarp/dht/messages/findintro.hpp index e40a9a903..71f662625 100644 --- a/llarp/dht/messages/findintro.hpp +++ b/llarp/dht/messages/findintro.hpp @@ -14,14 +14,13 @@ namespace llarp { Key_t location; llarp::service::Tag tagName; - uint64_t txID = 0; - bool relayed = false; + uint64_t txID = 0; + bool relayed = false; uint64_t relayOrder = 0; - FindIntroMessage(const Key_t& from, bool relay, uint64_t order) - : IMessage(from) + FindIntroMessage(const Key_t& from, bool relay, uint64_t order) : IMessage(from) { - relayed = relay; + relayed = relay; relayOrder = order; } @@ -30,8 +29,7 @@ namespace llarp { } - explicit FindIntroMessage(uint64_t txid, const Key_t& addr, - uint64_t order) + explicit FindIntroMessage(uint64_t txid, const Key_t& addr, uint64_t order) : IMessage({}), location(addr), txID(txid), relayOrder(order) { tagName.Zero(); @@ -46,8 +44,7 @@ namespace llarp DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) override; bool - HandleMessage(llarp_dht_context* ctx, - std::vector< IMessage::Ptr_t >& replies) const override; + HandleMessage(llarp_dht_context* ctx, std::vector& replies) const override; }; } // namespace dht } // namespace llarp diff --git a/llarp/dht/messages/findrouter.cpp b/llarp/dht/messages/findrouter.cpp index 00fd8517f..714ff0cdd 100644 --- a/llarp/dht/messages/findrouter.cpp +++ b/llarp/dht/messages/findrouter.cpp @@ -15,21 +15,18 @@ namespace llarp { bool RelayedFindRouterMessage::HandleMessage( - llarp_dht_context *ctx, - std::vector< std::unique_ptr< IMessage > > &replies) const + llarp_dht_context* ctx, std::vector>& replies) const { - auto &dht = *ctx->impl; + auto& dht = *ctx->impl; /// lookup for us, send an immeidate reply const Key_t us = dht.OurKey(); const Key_t k{targetKey}; - if(k == us) + if (k == us) { - auto path = - dht.GetRouter()->pathContext().GetByUpstream(targetKey, pathID); - if(path) + auto path = dht.GetRouter()->pathContext().GetByUpstream(targetKey, pathID); + if (path) { - replies.emplace_back( - new GotRouterMessage(k, txid, {dht.GetRouter()->rc()}, false)); + replies.emplace_back(new GotRouterMessage(k, txid, {dht.GetRouter()->rc()}, false)); return true; } return false; @@ -37,7 +34,7 @@ namespace llarp Key_t peer; // check if we know this in our nodedb first - if(not dht.GetRouter()->ConnectionToRouterAllowed(targetKey)) + if (not dht.GetRouter()->ConnectionToRouterAllowed(targetKey)) { // explicitly disallowed by network replies.emplace_back(new GotRouterMessage(k, txid, {}, false)); @@ -45,7 +42,7 @@ namespace llarp } // check netdb const auto rc = dht.GetRouter()->nodedb()->FindClosestTo(k); - if(rc.pubkey == targetKey) + if (rc.pubkey == targetKey) { replies.emplace_back(new GotRouterMessage(k, txid, {rc}, false)); return true; @@ -59,89 +56,89 @@ namespace llarp FindRouterMessage::~FindRouterMessage() = default; bool - FindRouterMessage::BEncode(llarp_buffer_t *buf) const + FindRouterMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; // message type - if(!bencode_write_bytestring(buf, "A", 1)) + if (!bencode_write_bytestring(buf, "A", 1)) return false; - if(!bencode_write_bytestring(buf, "R", 1)) + if (!bencode_write_bytestring(buf, "R", 1)) return false; // exploritory or not? - if(!bencode_write_bytestring(buf, "E", 1)) + if (!bencode_write_bytestring(buf, "E", 1)) return false; - if(!bencode_write_uint64(buf, exploritory ? 1 : 0)) + if (!bencode_write_uint64(buf, exploritory ? 1 : 0)) return false; // iterative or not? - if(!bencode_write_bytestring(buf, "I", 1)) + if (!bencode_write_bytestring(buf, "I", 1)) return false; - if(!bencode_write_uint64(buf, iterative ? 1 : 0)) + if (!bencode_write_uint64(buf, iterative ? 1 : 0)) return false; // key - if(!bencode_write_bytestring(buf, "K", 1)) + if (!bencode_write_bytestring(buf, "K", 1)) return false; - if(!bencode_write_bytestring(buf, targetKey.data(), targetKey.size())) + if (!bencode_write_bytestring(buf, targetKey.data(), targetKey.size())) return false; // txid - if(!bencode_write_bytestring(buf, "T", 1)) + if (!bencode_write_bytestring(buf, "T", 1)) return false; - if(!bencode_write_uint64(buf, txid)) + if (!bencode_write_uint64(buf, txid)) return false; // version - if(!bencode_write_bytestring(buf, "V", 1)) + if (!bencode_write_bytestring(buf, "V", 1)) return false; - if(!bencode_write_uint64(buf, version)) + if (!bencode_write_uint64(buf, version)) return false; return bencode_end(buf); } bool - FindRouterMessage::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *val) + FindRouterMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { llarp_buffer_t strbuf; - if(key == "E") + if (key == "E") { uint64_t result; - if(!bencode_read_integer(val, &result)) + if (!bencode_read_integer(val, &result)) return false; exploritory = result != 0; return true; } - if(key == "I") + if (key == "I") { uint64_t result; - if(!bencode_read_integer(val, &result)) + if (!bencode_read_integer(val, &result)) return false; iterative = result != 0; return true; } - if(key == "K") + if (key == "K") { - if(!bencode_read_string(val, &strbuf)) + if (!bencode_read_string(val, &strbuf)) return false; - if(strbuf.sz != targetKey.size()) + if (strbuf.sz != targetKey.size()) return false; std::copy(strbuf.base, strbuf.base + targetKey.SIZE, targetKey.begin()); return true; } - if(key == "T") + if (key == "T") { return bencode_read_integer(val, &txid); } - if(key == "V") + if (key == "V") { return bencode_read_integer(val, &version); } @@ -150,37 +147,32 @@ namespace llarp bool FindRouterMessage::HandleMessage( - llarp_dht_context *ctx, - std::vector< std::unique_ptr< IMessage > > &replies) const + llarp_dht_context* ctx, std::vector>& replies) const { - auto &dht = *ctx->impl; + auto& dht = *ctx->impl; auto router = dht.GetRouter(); - router->NotifyRouterEvent< tooling::FindRouterReceivedEvent >( - router->pubkey(), - this); + router->NotifyRouterEvent(router->pubkey(), this); - if(!dht.AllowTransit()) + if (!dht.AllowTransit()) { - llarp::LogWarn("Got DHT lookup from ", From, - " when we are not allowing dht transit"); + llarp::LogWarn("Got DHT lookup from ", From, " when we are not allowing dht transit"); return false; } - if(dht.pendingRouterLookups().HasPendingLookupFrom({From, txid})) + if (dht.pendingRouterLookups().HasPendingLookupFrom({From, txid})) { llarp::LogWarn("Duplicate FRM from ", From, " txid=", txid); return false; } RouterContact found; - if(targetKey.IsZero()) + if (targetKey.IsZero()) { llarp::LogError("invalid FRM from ", From, " key is zero"); return false; } const Key_t k(targetKey); - if(exploritory) - return dht.HandleExploritoryRouterLookup(From, txid, targetKey, - replies); + if (exploritory) + return dht.HandleExploritoryRouterLookup(From, txid, targetKey, replies); dht.LookupRouterRelayed(From, txid, k, !iterative, replies); return true; } diff --git a/llarp/dht/messages/findrouter.hpp b/llarp/dht/messages/findrouter.hpp index 40a79b282..a8a28e95d 100644 --- a/llarp/dht/messages/findrouter.hpp +++ b/llarp/dht/messages/findrouter.hpp @@ -35,13 +35,12 @@ namespace llarp bool HandleMessage( - llarp_dht_context* ctx, - std::vector< std::unique_ptr< IMessage > >& replies) const override; + llarp_dht_context* ctx, std::vector>& replies) const override; RouterID targetKey; - bool iterative = false; + bool iterative = false; bool exploritory = false; - uint64_t txid = 0; + uint64_t txid = 0; uint64_t version = 0; }; @@ -56,8 +55,7 @@ namespace llarp /// the path of the result /// TODO: smart path expiration logic needs to be implemented bool - HandleMessage(llarp_dht_context* ctx, - std::vector< IMessage::Ptr_t >& replies) const override; + HandleMessage(llarp_dht_context* ctx, std::vector& replies) const override; }; } // namespace dht } // namespace llarp diff --git a/llarp/dht/messages/gotintro.cpp b/llarp/dht/messages/gotintro.cpp index d70549d6d..291a4b07d 100644 --- a/llarp/dht/messages/gotintro.cpp +++ b/llarp/dht/messages/gotintro.cpp @@ -13,28 +13,27 @@ namespace llarp { namespace dht { - GotIntroMessage::GotIntroMessage( - std::vector< service::EncryptedIntroSet > results, uint64_t tx) + GotIntroMessage::GotIntroMessage(std::vector results, uint64_t tx) : IMessage({}), found(std::move(results)), txid(tx) { } bool GotIntroMessage::HandleMessage( - llarp_dht_context *ctx, - std::vector< std::unique_ptr< IMessage > > & /*replies*/) const + llarp_dht_context* ctx, std::vector>& /*replies*/) const { - auto &dht = *ctx->impl; - auto *router = dht.GetRouter(); + auto& dht = *ctx->impl; + auto* router = dht.GetRouter(); - router->NotifyRouterEvent< tooling::GotIntroReceivedEvent >( - router->pubkey(), Key_t(From.data()), + router->NotifyRouterEvent( + router->pubkey(), + Key_t(From.data()), (found.size() > 0 ? found[0] : llarp::service::EncryptedIntroSet{}), txid); - for(const auto &introset : found) + for (const auto& introset : found) { - if(!introset.Verify(dht.Now())) + if (!introset.Verify(dht.Now())) { LogWarn( "Invalid introset while handling direct GotIntro " @@ -45,14 +44,12 @@ namespace llarp } TXOwner owner(From, txid); - auto serviceLookup = - dht.pendingIntrosetLookups().GetPendingLookupFrom(owner); - if(serviceLookup) + auto serviceLookup = dht.pendingIntrosetLookups().GetPendingLookupFrom(owner); + if (serviceLookup) { - if(not found.empty()) + if (not found.empty()) { - dht.pendingIntrosetLookups().Found(owner, serviceLookup->target, - found); + dht.pendingIntrosetLookups().Found(owner, serviceLookup->target, found); } else { @@ -66,16 +63,14 @@ namespace llarp bool RelayedGotIntroMessage::HandleMessage( - llarp_dht_context *ctx, - __attribute__((unused)) - std::vector< std::unique_ptr< IMessage > > &replies) const + llarp_dht_context* ctx, + __attribute__((unused)) std::vector>& replies) const { // TODO: implement me better? - auto pathset = - ctx->impl->GetRouter()->pathContext().GetLocalPathSet(pathID); - if(pathset) + auto pathset = ctx->impl->GetRouter()->pathContext().GetLocalPathSet(pathID); + if (pathset) { - auto copy = std::make_shared< const RelayedGotIntroMessage >(*this); + auto copy = std::make_shared(*this); return pathset->HandleGotIntroMessage(copy); } LogWarn("No path for got intro message pathid=", pathID); @@ -83,47 +78,47 @@ namespace llarp } bool - GotIntroMessage::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf) + GotIntroMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { - if(key == "I") + if (key == "I") { return BEncodeReadList(found, buf); } - if(key == "K") + if (key == "K") { - if(closer.has_value()) // duplicate key? + if (closer.has_value()) // duplicate key? return false; dht::Key_t K; - if(not K.BDecode(buf)) + if (not K.BDecode(buf)) return false; closer = K; return true; } bool read = false; - if(!BEncodeMaybeReadDictInt("T", txid, read, key, buf)) + if (!BEncodeMaybeReadDictInt("T", txid, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, key, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, key, buf)) return false; return read; } bool - GotIntroMessage::BEncode(llarp_buffer_t *buf) const + GotIntroMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "G")) + if (!BEncodeWriteDictMsgType(buf, "A", "G")) return false; - if(!BEncodeWriteDictList("I", found, buf)) + if (!BEncodeWriteDictList("I", found, buf)) return false; - if(closer.has_value()) + if (closer.has_value()) { - if(!BEncodeWriteDictEntry("K", closer.value(), buf)) + if (!BEncodeWriteDictEntry("K", closer.value(), buf)) return false; } - if(!BEncodeWriteDictInt("T", txid, buf)) + if (!BEncodeWriteDictInt("T", txid, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; return bencode_end(buf); } diff --git a/llarp/dht/messages/gotintro.hpp b/llarp/dht/messages/gotintro.hpp index bf9fbb2a3..8001e15dc 100644 --- a/llarp/dht/messages/gotintro.hpp +++ b/llarp/dht/messages/gotintro.hpp @@ -16,21 +16,18 @@ namespace llarp struct GotIntroMessage : public IMessage { /// the found introsets - std::vector< service::EncryptedIntroSet > found; + std::vector found; /// txid uint64_t txid = 0; /// the key of a router closer in keyspace if iterative lookup - nonstd::optional< Key_t > closer; + nonstd::optional closer; GotIntroMessage(const Key_t& from) : IMessage(from) { } GotIntroMessage(const GotIntroMessage& other) - : IMessage(other.From) - , found(other.found) - , txid(other.txid) - , closer(other.closer) + : IMessage(other.From), found(other.found), txid(other.txid), closer(other.closer) { version = other.version; } @@ -42,8 +39,7 @@ namespace llarp } /// for recursive reply - GotIntroMessage(std::vector< service::EncryptedIntroSet > results, - uint64_t txid); + GotIntroMessage(std::vector results, uint64_t txid); ~GotIntroMessage() override = default; @@ -54,8 +50,7 @@ namespace llarp DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) override; bool - HandleMessage(llarp_dht_context* ctx, - std::vector< IMessage::Ptr_t >& replies) const override; + HandleMessage(llarp_dht_context* ctx, std::vector& replies) const override; }; struct RelayedGotIntroMessage final : public GotIntroMessage @@ -65,11 +60,10 @@ namespace llarp } bool - HandleMessage(llarp_dht_context* ctx, - std::vector< IMessage::Ptr_t >& replies) const override; + HandleMessage(llarp_dht_context* ctx, std::vector& replies) const override; }; - using GotIntroMessage_constptr = std::shared_ptr< const GotIntroMessage >; + using GotIntroMessage_constptr = std::shared_ptr; } // namespace dht } // namespace llarp #endif diff --git a/llarp/dht/messages/gotrouter.cpp b/llarp/dht/messages/gotrouter.cpp index c893dac59..864d53db9 100644 --- a/llarp/dht/messages/gotrouter.cpp +++ b/llarp/dht/messages/gotrouter.cpp @@ -14,67 +14,66 @@ namespace llarp GotRouterMessage::~GotRouterMessage() = default; bool - GotRouterMessage::BEncode(llarp_buffer_t *buf) const + GotRouterMessage::BEncode(llarp_buffer_t* buf) const { - if(not bencode_start_dict(buf)) + if (not bencode_start_dict(buf)) return false; // message type - if(not BEncodeWriteDictMsgType(buf, "A", "S")) + if (not BEncodeWriteDictMsgType(buf, "A", "S")) return false; - if(closerTarget) + if (closerTarget) { - if(not BEncodeWriteDictEntry("K", *closerTarget, buf)) + if (not BEncodeWriteDictEntry("K", *closerTarget, buf)) return false; } // near - if(not nearKeys.empty()) + if (not nearKeys.empty()) { - if(not BEncodeWriteDictList("N", nearKeys, buf)) + if (not BEncodeWriteDictList("N", nearKeys, buf)) return false; } - if(not BEncodeWriteDictList("R", foundRCs, buf)) + if (not BEncodeWriteDictList("R", foundRCs, buf)) return false; // txid - if(not BEncodeWriteDictInt("T", txid, buf)) + if (not BEncodeWriteDictInt("T", txid, buf)) return false; // version - if(not BEncodeWriteDictInt("V", version, buf)) + if (not BEncodeWriteDictInt("V", version, buf)) return false; return bencode_end(buf); } bool - GotRouterMessage::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *val) + GotRouterMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { - if(key == "K") + if (key == "K") { - if(closerTarget) // duplicate key? + if (closerTarget) // duplicate key? return false; - closerTarget = std::make_unique< dht::Key_t >(); + closerTarget = std::make_unique(); return closerTarget->BDecode(val); } - if(key == "N") + if (key == "N") { return BEncodeReadList(nearKeys, val); } - if(key == "R") + if (key == "R") { return BEncodeReadList(foundRCs, val); } - if(key == "T") + if (key == "T") { return bencode_read_integer(val, &txid); } bool read = false; - if(!BEncodeMaybeVerifyVersion("V", version, LLARP_PROTO_VERSION, read, - key, val)) + if (!BEncodeMaybeVerifyVersion("V", version, LLARP_PROTO_VERSION, read, key, val)) return false; return read; @@ -82,25 +81,23 @@ namespace llarp bool GotRouterMessage::HandleMessage( - llarp_dht_context *ctx, - __attribute__((unused)) - std::vector< std::unique_ptr< IMessage > > &replies) const + llarp_dht_context* ctx, + __attribute__((unused)) std::vector>& replies) const { - auto &dht = *ctx->impl; - if(relayed) + auto& dht = *ctx->impl; + if (relayed) { - auto pathset = - ctx->impl->GetRouter()->pathContext().GetLocalPathSet(pathID); - auto copy = std::make_shared< const GotRouterMessage >(*this); + auto pathset = ctx->impl->GetRouter()->pathContext().GetLocalPathSet(pathID); + auto copy = std::make_shared(*this); return pathset && pathset->HandleGotRouterMessage(copy); } // not relayed const TXOwner owner(From, txid); - if(dht.pendingExploreLookups().HasPendingLookupFrom(owner)) + if (dht.pendingExploreLookups().HasPendingLookupFrom(owner)) { LogDebug("got ", nearKeys.size(), " results in GRM for explore"); - if(nearKeys.empty()) + if (nearKeys.empty()) dht.pendingExploreLookups().NotFound(owner, closerTarget); else { @@ -109,28 +106,27 @@ namespace llarp return true; } // not explore lookup - if(dht.pendingRouterLookups().HasPendingLookupFrom(owner)) + if (dht.pendingRouterLookups().HasPendingLookupFrom(owner)) { LogDebug("got ", foundRCs.size(), " results in GRM for lookup"); - if(foundRCs.empty()) + if (foundRCs.empty()) dht.pendingRouterLookups().NotFound(owner, closerTarget); - else if(foundRCs[0].pubkey.IsZero()) + else if (foundRCs[0].pubkey.IsZero()) return false; else dht.pendingRouterLookups().Found(owner, foundRCs[0].pubkey, foundRCs); return true; } // store if valid - for(const auto &rc : foundRCs) + for (const auto& rc : foundRCs) { - if(not dht.GetRouter()->rcLookupHandler().CheckRC(rc)) + if (not dht.GetRouter()->rcLookupHandler().CheckRC(rc)) return false; - if(txid == 0) // txid == 0 on gossip + if (txid == 0) // txid == 0 on gossip { LogWarn("Received Gossiped RC, generating RCGossipReceivedEvent"); - auto *router = dht.GetRouter(); - router->NotifyRouterEvent< tooling::RCGossipReceivedEvent >( - router->pubkey(), rc); + auto* router = dht.GetRouter(); + router->NotifyRouterEvent(router->pubkey(), rc); router->GossipRCIfNeeded(rc); } } diff --git a/llarp/dht/messages/gotrouter.hpp b/llarp/dht/messages/gotrouter.hpp index 29eb9a2e6..6751bc649 100644 --- a/llarp/dht/messages/gotrouter.hpp +++ b/llarp/dht/messages/gotrouter.hpp @@ -13,38 +13,27 @@ namespace llarp { struct GotRouterMessage final : public IMessage { - GotRouterMessage(const Key_t& from, bool tunneled) - : IMessage(from), relayed(tunneled) + GotRouterMessage(const Key_t& from, bool tunneled) : IMessage(from), relayed(tunneled) { } - GotRouterMessage(const Key_t& from, uint64_t id, - const std::vector< RouterContact >& results, - bool tunneled) + GotRouterMessage( + const Key_t& from, uint64_t id, const std::vector& results, bool tunneled) : IMessage(from), foundRCs(results), txid(id), relayed(tunneled) { } - GotRouterMessage(const Key_t& from, const Key_t& closer, uint64_t id, - bool tunneled) - : IMessage(from) - , closerTarget(new Key_t(closer)) - , txid(id) - , relayed(tunneled) + GotRouterMessage(const Key_t& from, const Key_t& closer, uint64_t id, bool tunneled) + : IMessage(from), closerTarget(new Key_t(closer)), txid(id), relayed(tunneled) { } - GotRouterMessage(uint64_t id, std::vector< RouterID > _near, - bool tunneled) - : IMessage({}) - , nearKeys(std::move(_near)) - , txid(id) - , relayed(tunneled) + GotRouterMessage(uint64_t id, std::vector _near, bool tunneled) + : IMessage({}), nearKeys(std::move(_near)), txid(id), relayed(tunneled) { } /// gossip message - GotRouterMessage(const RouterContact rc) - : IMessage({}), foundRCs({rc}), txid(0) + GotRouterMessage(const RouterContact rc) : IMessage({}), foundRCs({rc}), txid(0) { version = LLARP_PROTO_VERSION; } @@ -70,17 +59,16 @@ namespace llarp bool HandleMessage( - llarp_dht_context* ctx, - std::vector< std::unique_ptr< IMessage > >& replies) const override; + llarp_dht_context* ctx, std::vector>& replies) const override; - std::vector< RouterContact > foundRCs; - std::vector< RouterID > nearKeys; - std::unique_ptr< Key_t > closerTarget; + std::vector foundRCs; + std::vector nearKeys; + std::unique_ptr closerTarget; uint64_t txid = 0; - bool relayed = false; + bool relayed = false; }; - using GotRouterMessage_constptr = std::shared_ptr< const GotRouterMessage >; + using GotRouterMessage_constptr = std::shared_ptr; } // namespace dht } // namespace llarp #endif diff --git a/llarp/dht/messages/pubintro.cpp b/llarp/dht/messages/pubintro.cpp index ae3fa16d0..878f9bbf4 100644 --- a/llarp/dht/messages/pubintro.cpp +++ b/llarp/dht/messages/pubintro.cpp @@ -14,40 +14,39 @@ namespace llarp namespace dht { const uint64_t PublishIntroMessage::MaxPropagationDepth = 5; - PublishIntroMessage::~PublishIntroMessage() = default; + PublishIntroMessage::~PublishIntroMessage() = default; bool - PublishIntroMessage::DecodeKey(const llarp_buffer_t &key, - llarp_buffer_t *val) + PublishIntroMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { bool read = false; - if(!BEncodeMaybeReadDictEntry("I", introset, read, key, val)) + if (!BEncodeMaybeReadDictEntry("I", introset, read, key, val)) return false; - if(read) + if (read) return true; - if(!BEncodeMaybeReadDictInt("O", relayOrder, read, key, val)) + if (!BEncodeMaybeReadDictInt("O", relayOrder, read, key, val)) return false; - if(read) + if (read) return true; uint64_t relayedInt = (relayed ? 1 : 0); - if(!BEncodeMaybeReadDictInt("R", relayedInt, read, key, val)) + if (!BEncodeMaybeReadDictInt("R", relayedInt, read, key, val)) return false; - if(read) + if (read) { relayed = relayedInt; return true; } - if(!BEncodeMaybeReadDictInt("T", txID, read, key, val)) + if (!BEncodeMaybeReadDictInt("T", txID, read, key, val)) return false; - if(read) + if (read) return true; - if(!BEncodeMaybeReadDictInt("V", version, read, key, val)) + if (!BEncodeMaybeReadDictInt("V", version, read, key, val)) return false; - if(read) + if (read) return true; return false; @@ -55,61 +54,58 @@ namespace llarp bool PublishIntroMessage::HandleMessage( - llarp_dht_context *ctx, - std::vector< std::unique_ptr< IMessage > > &replies) const + llarp_dht_context* ctx, std::vector>& replies) const { const auto now = ctx->impl->Now(); const llarp::dht::Key_t addr(introset.derivedSigningKey); const auto keyStr = addr.ToHex(); auto router = ctx->impl->GetRouter(); - router->NotifyRouterEvent< tooling::PubIntroReceivedEvent >( - router->pubkey(), Key_t(relayed ? router->pubkey() : From.data()), - addr, txID, relayOrder); - - auto &dht = *ctx->impl; - if(!introset.Verify(now)) + router->NotifyRouterEvent( + router->pubkey(), + Key_t(relayed ? router->pubkey() : From.data()), + addr, + txID, + relayOrder); + + auto& dht = *ctx->impl; + if (!introset.Verify(now)) { - llarp::LogWarn("Received PublishIntroMessage with invalid introset: ", - introset); + llarp::LogWarn("Received PublishIntroMessage with invalid introset: ", introset); // don't propogate or store replies.emplace_back(new GotIntroMessage({}, txID)); return true; } - if(introset.IsExpired(now + llarp::service::MAX_INTROSET_TIME_DELTA)) + if (introset.IsExpired(now + llarp::service::MAX_INTROSET_TIME_DELTA)) { // don't propogate or store - llarp::LogWarn("Received PublishIntroMessage with expired Introset: ", - introset); + llarp::LogWarn("Received PublishIntroMessage with expired Introset: ", introset); replies.emplace_back(new GotIntroMessage({}, txID)); return true; } // identify closest 4 routers - auto closestRCs = dht.GetRouter()->nodedb()->FindClosestTo( - addr, IntroSetStorageRedundancy); - if(closestRCs.size() != IntroSetStorageRedundancy) + auto closestRCs = dht.GetRouter()->nodedb()->FindClosestTo(addr, IntroSetStorageRedundancy); + if (closestRCs.size() != IntroSetStorageRedundancy) { - llarp::LogWarn("Received PublishIntroMessage but only know ", - closestRCs.size(), " nodes"); + llarp::LogWarn("Received PublishIntroMessage but only know ", closestRCs.size(), " nodes"); replies.emplace_back(new GotIntroMessage({}, txID)); return true; } - const auto &us = dht.OurKey(); + const auto& us = dht.OurKey(); // function to identify the closest 4 routers we know of for this introset auto propagateIfNotUs = [&](size_t index) { assert(index < IntroSetStorageRedundancy); - const auto &rc = closestRCs[index]; + const auto& rc = closestRCs[index]; const Key_t peer{rc.pubkey}; - if(peer == us) + if (peer == us) { - llarp::LogInfo("we are peer ", index, - " so storing instead of propagating"); + llarp::LogInfo("we are peer ", index, " so storing instead of propagating"); dht.services()->PutNode(introset); replies.emplace_back(new GotIntroMessage({introset}, txID)); @@ -117,7 +113,7 @@ namespace llarp else { llarp::LogInfo("propagating to peer ", index); - if(relayed) + if (relayed) { dht.PropagateLocalIntroSet(pathID, txID, introset, peer, 0); } @@ -128,29 +124,26 @@ namespace llarp } }; - if(relayed) + if (relayed) { - if(relayOrder >= IntroSetStorageRedundancy) + if (relayOrder >= IntroSetStorageRedundancy) { - llarp::LogWarn( - "Received PublishIntroMessage with invalid relayOrder: ", - relayOrder); + llarp::LogWarn("Received PublishIntroMessage with invalid relayOrder: ", relayOrder); replies.emplace_back(new GotIntroMessage({}, txID)); return true; } - llarp::LogInfo("Relaying PublishIntroMessage for ", keyStr, - ", txid=", txID); + llarp::LogInfo("Relaying PublishIntroMessage for ", keyStr, ", txid=", txID); propagateIfNotUs(relayOrder); } else { int candidateNumber = -1; - int index = 0; - for(const auto &rc : closestRCs) + int index = 0; + for (const auto& rc : closestRCs) { - if(rc.pubkey == dht.OurKey()) + if (rc.pubkey == dht.OurKey()) { candidateNumber = index; break; @@ -158,10 +151,15 @@ namespace llarp ++index; } - if(candidateNumber >= 0) + if (candidateNumber >= 0) { - LogInfo("Received PubIntro for ", keyStr, ", txid=", txID, - " and we are candidate ", candidateNumber); + LogInfo( + "Received PubIntro for ", + keyStr, + ", txid=", + txID, + " and we are candidate ", + candidateNumber); dht.services()->PutNode(introset); replies.emplace_back(new GotIntroMessage({introset}, txID)); } @@ -170,7 +168,11 @@ namespace llarp LogWarn( "!!! Received PubIntro with relayed==false but we aren't" " candidate, intro derived key: ", - keyStr, ", txid=", txID, ", message from: ", From); + keyStr, + ", txid=", + txID, + ", message from: ", + From); } } @@ -178,21 +180,21 @@ namespace llarp } bool - PublishIntroMessage::BEncode(llarp_buffer_t *buf) const + PublishIntroMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "I")) + if (!BEncodeWriteDictMsgType(buf, "A", "I")) return false; - if(!BEncodeWriteDictEntry("I", introset, buf)) + if (!BEncodeWriteDictEntry("I", introset, buf)) return false; - if(!BEncodeWriteDictInt("O", relayOrder, buf)) + if (!BEncodeWriteDictInt("O", relayOrder, buf)) return false; - if(!BEncodeWriteDictInt("R", relayed, buf)) + if (!BEncodeWriteDictInt("R", relayed, buf)) return false; - if(!BEncodeWriteDictInt("T", txID, buf)) + if (!BEncodeWriteDictInt("T", txID, buf)) return false; - if(!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) + if (!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) return false; return bencode_end(buf); } diff --git a/llarp/dht/messages/pubintro.hpp b/llarp/dht/messages/pubintro.hpp index 2f185ce89..26aa95b6b 100644 --- a/llarp/dht/messages/pubintro.hpp +++ b/llarp/dht/messages/pubintro.hpp @@ -14,21 +14,19 @@ namespace llarp { static const uint64_t MaxPropagationDepth; llarp::service::EncryptedIntroSet introset; - bool relayed = false; + bool relayed = false; uint64_t relayOrder = 0; - uint64_t txID = 0; - PublishIntroMessage(const Key_t& from, bool relayed_) - : IMessage(from), relayed(relayed_) + uint64_t txID = 0; + PublishIntroMessage(const Key_t& from, bool relayed_) : IMessage(from), relayed(relayed_) { } - PublishIntroMessage(const llarp::service::EncryptedIntroSet& introset_, - uint64_t tx, bool relayed_, uint64_t relayOrder_) - : IMessage({}) - , introset(introset_) - , relayed(relayed_) - , relayOrder(relayOrder_) - , txID(tx) + PublishIntroMessage( + const llarp::service::EncryptedIntroSet& introset_, + uint64_t tx, + bool relayed_, + uint64_t relayOrder_) + : IMessage({}), introset(introset_), relayed(relayed_), relayOrder(relayOrder_), txID(tx) { } @@ -42,8 +40,7 @@ namespace llarp bool HandleMessage( - llarp_dht_context* ctx, - std::vector< std::unique_ptr< IMessage > >& replies) const override; + llarp_dht_context* ctx, std::vector>& replies) const override; }; } // namespace dht } // namespace llarp diff --git a/llarp/dht/publishservicejob.cpp b/llarp/dht/publishservicejob.cpp index 6a1d7d3bc..90bd7ab88 100644 --- a/llarp/dht/publishservicejob.cpp +++ b/llarp/dht/publishservicejob.cpp @@ -13,21 +13,22 @@ namespace llarp namespace dht { PublishServiceJob::PublishServiceJob( - const TXOwner &asker, const service::EncryptedIntroSet &introset_, - AbstractContext *ctx, uint64_t relayOrder_) - : TX< TXOwner, service::EncryptedIntroSet >(asker, asker, ctx) + const TXOwner& asker, + const service::EncryptedIntroSet& introset_, + AbstractContext* ctx, + uint64_t relayOrder_) + : TX(asker, asker, ctx) , relayOrder(relayOrder_) , introset(introset_) { } bool - PublishServiceJob::Validate(const service::EncryptedIntroSet &value) const + PublishServiceJob::Validate(const service::EncryptedIntroSet& value) const { - if(value.derivedSigningKey != introset.derivedSigningKey) + if (value.derivedSigningKey != introset.derivedSigningKey) { - llarp::LogWarn( - "publish introset acknowledgement acked a different service"); + llarp::LogWarn("publish introset acknowledgement acked a different service"); return false; } const llarp_time_t now = llarp::time_now_ms(); @@ -35,36 +36,35 @@ namespace llarp } void - PublishServiceJob::Start(const TXOwner &peer) + PublishServiceJob::Start(const TXOwner& peer) { parent->DHTSendTo( - peer.node.as_array(), - new PublishIntroMessage(introset, peer.txid, false, relayOrder)); + peer.node.as_array(), new PublishIntroMessage(introset, peer.txid, false, relayOrder)); } void PublishServiceJob::SendReply() { - parent->DHTSendTo(whoasked.node.as_array(), - new GotIntroMessage({introset}, whoasked.txid)); + parent->DHTSendTo(whoasked.node.as_array(), new GotIntroMessage({introset}, whoasked.txid)); } LocalPublishServiceJob::LocalPublishServiceJob( - const TXOwner &peer, const PathID_t &fromID, uint64_t _txid, - const service::EncryptedIntroSet &introset, AbstractContext *ctx, + const TXOwner& peer, + const PathID_t& fromID, + uint64_t _txid, + const service::EncryptedIntroSet& introset, + AbstractContext* ctx, uint64_t relayOrder) - : PublishServiceJob(peer, introset, ctx, relayOrder) - , localPath(fromID) - , txid(_txid) + : PublishServiceJob(peer, introset, ctx, relayOrder), localPath(fromID), txid(_txid) { } void LocalPublishServiceJob::SendReply() { - auto path = parent->GetRouter()->pathContext().GetByUpstream( - parent->OurKey().as_array(), localPath); - if(!path) + auto path = + parent->GetRouter()->pathContext().GetByUpstream(parent->OurKey().as_array(), localPath); + if (!path) { llarp::LogWarn( "did not send reply for relayed dht request, no such local path " @@ -74,7 +74,7 @@ namespace llarp } routing::DHTMessage msg; msg.M.emplace_back(new GotIntroMessage({introset}, txid)); - if(!path->SendRoutingMessage(msg, parent->GetRouter())) + if (!path->SendRoutingMessage(msg, parent->GetRouter())) { llarp::LogWarn( "failed to send routing message when informing result of dht " diff --git a/llarp/dht/publishservicejob.hpp b/llarp/dht/publishservicejob.hpp index 3e95e4b90..d23690f9b 100644 --- a/llarp/dht/publishservicejob.hpp +++ b/llarp/dht/publishservicejob.hpp @@ -12,20 +12,22 @@ namespace llarp { namespace dht { - struct PublishServiceJob : public TX< TXOwner, service::EncryptedIntroSet > + struct PublishServiceJob : public TX { uint64_t relayOrder; service::EncryptedIntroSet introset; - PublishServiceJob(const TXOwner &asker, - const service::EncryptedIntroSet &introset, - AbstractContext *ctx, uint64_t relayOrder); + PublishServiceJob( + const TXOwner& asker, + const service::EncryptedIntroSet& introset, + AbstractContext* ctx, + uint64_t relayOrder); bool - Validate(const service::EncryptedIntroSet &introset) const override; + Validate(const service::EncryptedIntroSet& introset) const override; void - Start(const TXOwner &peer) override; + Start(const TXOwner& peer) override; virtual void SendReply() override; @@ -35,10 +37,13 @@ namespace llarp { PathID_t localPath; uint64_t txid; - LocalPublishServiceJob(const TXOwner &peer, const PathID_t &fromID, - uint64_t txid, - const service::EncryptedIntroSet &introset, - AbstractContext *ctx, uint64_t relayOrder); + LocalPublishServiceJob( + const TXOwner& peer, + const PathID_t& fromID, + uint64_t txid, + const service::EncryptedIntroSet& introset, + AbstractContext* ctx, + uint64_t relayOrder); void SendReply() override; diff --git a/llarp/dht/recursiverouterlookup.cpp b/llarp/dht/recursiverouterlookup.cpp index b92c6ef17..537026382 100644 --- a/llarp/dht/recursiverouterlookup.cpp +++ b/llarp/dht/recursiverouterlookup.cpp @@ -13,21 +13,21 @@ namespace llarp { namespace dht { - RecursiveRouterLookup::RecursiveRouterLookup(const TXOwner &_whoasked, - const RouterID &_target, - AbstractContext *ctx, - RouterLookupHandler result) - : TX< RouterID, RouterContact >(_whoasked, _target, ctx) - , resultHandler(std::move(result)) + RecursiveRouterLookup::RecursiveRouterLookup( + const TXOwner& _whoasked, + const RouterID& _target, + AbstractContext* ctx, + RouterLookupHandler result) + : TX(_whoasked, _target, ctx), resultHandler(std::move(result)) { peersAsked.insert(ctx->OurKey()); } bool - RecursiveRouterLookup::Validate(const RouterContact &rc) const + RecursiveRouterLookup::Validate(const RouterContact& rc) const { - if(!rc.Verify(parent->Now())) + if (!rc.Verify(parent->Now())) { llarp::LogWarn("rc from lookup result is invalid"); return false; @@ -36,36 +36,35 @@ namespace llarp } void - RecursiveRouterLookup::Start(const TXOwner &peer) + RecursiveRouterLookup::Start(const TXOwner& peer) { - parent->DHTSendTo(peer.node.as_array(), - new FindRouterMessage(peer.txid, target)); + parent->DHTSendTo(peer.node.as_array(), new FindRouterMessage(peer.txid, target)); } void RecursiveRouterLookup::SendReply() { - if(valuesFound.size()) + if (valuesFound.size()) { RouterContact found; - for(const auto &rc : valuesFound) + for (const auto& rc : valuesFound) { - if(found.OtherIsNewer(rc) - && parent->GetRouter()->rcLookupHandler().CheckRC(rc)) + if (found.OtherIsNewer(rc) && parent->GetRouter()->rcLookupHandler().CheckRC(rc)) found = rc; } valuesFound.clear(); valuesFound.emplace_back(found); } - if(resultHandler) + if (resultHandler) { resultHandler(valuesFound); } - if(whoasked.node != parent->OurKey()) + if (whoasked.node != parent->OurKey()) { parent->DHTSendTo( whoasked.node.as_array(), - new GotRouterMessage({}, whoasked.txid, valuesFound, false), false); + new GotRouterMessage({}, whoasked.txid, valuesFound, false), + false); } } } // namespace dht diff --git a/llarp/dht/recursiverouterlookup.hpp b/llarp/dht/recursiverouterlookup.hpp index 37c3162d4..78c7211e4 100644 --- a/llarp/dht/recursiverouterlookup.hpp +++ b/llarp/dht/recursiverouterlookup.hpp @@ -10,17 +10,20 @@ namespace llarp { namespace dht { - struct RecursiveRouterLookup : public TX< RouterID, RouterContact > + struct RecursiveRouterLookup : public TX { RouterLookupHandler resultHandler; - RecursiveRouterLookup(const TXOwner &whoasked, const RouterID &target, - AbstractContext *ctx, RouterLookupHandler result); + RecursiveRouterLookup( + const TXOwner& whoasked, + const RouterID& target, + AbstractContext* ctx, + RouterLookupHandler result); bool - Validate(const RouterContact &rc) const override; + Validate(const RouterContact& rc) const override; void - Start(const TXOwner &peer) override; + Start(const TXOwner& peer) override; void SendReply() override; diff --git a/llarp/dht/serviceaddresslookup.cpp b/llarp/dht/serviceaddresslookup.cpp index 972e90007..15b54d3f2 100644 --- a/llarp/dht/serviceaddresslookup.cpp +++ b/llarp/dht/serviceaddresslookup.cpp @@ -10,9 +10,12 @@ namespace llarp namespace dht { ServiceAddressLookup::ServiceAddressLookup( - const TXOwner &asker, const Key_t &addr, AbstractContext *ctx, - uint32_t order, service::EncryptedIntroSetLookupHandler handler) - : TX< TXOwner, service::EncryptedIntroSet >(asker, asker, ctx) + const TXOwner& asker, + const Key_t& addr, + AbstractContext* ctx, + uint32_t order, + service::EncryptedIntroSetLookupHandler handler) + : TX(asker, asker, ctx) , location(addr) , handleResult(std::move(handler)) , relayOrder(order) @@ -21,15 +24,14 @@ namespace llarp } bool - ServiceAddressLookup::Validate( - const service::EncryptedIntroSet &value) const + ServiceAddressLookup::Validate(const service::EncryptedIntroSet& value) const { - if(!value.Verify(parent->Now())) + if (!value.Verify(parent->Now())) { llarp::LogWarn("Got invalid introset from service lookup"); return false; } - if(value.derivedSigningKey != location) + if (value.derivedSigningKey != location) { llarp::LogWarn("got introset with wrong target from service lookup"); return false; @@ -38,33 +40,32 @@ namespace llarp } void - ServiceAddressLookup::Start(const TXOwner &peer) + ServiceAddressLookup::Start(const TXOwner& peer) { - parent->DHTSendTo(peer.node.as_array(), - new FindIntroMessage(peer.txid, location, relayOrder)); + parent->DHTSendTo( + peer.node.as_array(), new FindIntroMessage(peer.txid, location, relayOrder)); } void ServiceAddressLookup::SendReply() { // get newest introset - if(valuesFound.size()) + if (valuesFound.size()) { llarp::service::EncryptedIntroSet found; - for(const auto &introset : valuesFound) + for (const auto& introset : valuesFound) { - if(found.OtherIsNewer(introset)) + if (found.OtherIsNewer(introset)) found = introset; } valuesFound.clear(); valuesFound.emplace_back(found); } - if(handleResult) + if (handleResult) { handleResult(valuesFound); } - parent->DHTSendTo(whoasked.node.as_array(), - new GotIntroMessage(valuesFound, whoasked.txid)); + parent->DHTSendTo(whoasked.node.as_array(), new GotIntroMessage(valuesFound, whoasked.txid)); } } // namespace dht } // namespace llarp diff --git a/llarp/dht/serviceaddresslookup.hpp b/llarp/dht/serviceaddresslookup.hpp index 7d2e348dd..3ac858b21 100644 --- a/llarp/dht/serviceaddresslookup.hpp +++ b/llarp/dht/serviceaddresslookup.hpp @@ -12,22 +12,24 @@ namespace llarp { struct TXOwner; - struct ServiceAddressLookup - : public TX< TXOwner, service::EncryptedIntroSet > + struct ServiceAddressLookup : public TX { Key_t location; service::EncryptedIntroSetLookupHandler handleResult; uint32_t relayOrder; - ServiceAddressLookup(const TXOwner &asker, const Key_t &addr, - AbstractContext *ctx, uint32_t relayOrder, - service::EncryptedIntroSetLookupHandler handler); + ServiceAddressLookup( + const TXOwner& asker, + const Key_t& addr, + AbstractContext* ctx, + uint32_t relayOrder, + service::EncryptedIntroSetLookupHandler handler); bool - Validate(const service::EncryptedIntroSet &value) const override; + Validate(const service::EncryptedIntroSet& value) const override; void - Start(const TXOwner &peer) override; + Start(const TXOwner& peer) override; void SendReply() override; diff --git a/llarp/dht/taglookup.cpp b/llarp/dht/taglookup.cpp index e2e7cbfa2..8dd5ae545 100644 --- a/llarp/dht/taglookup.cpp +++ b/llarp/dht/taglookup.cpp @@ -8,16 +8,16 @@ namespace llarp namespace dht { bool - TagLookup::Validate(const service::EncryptedIntroSet &introset) const + TagLookup::Validate(const service::EncryptedIntroSet& introset) const { - if(!introset.Verify(parent->Now())) + if (!introset.Verify(parent->Now())) { llarp::LogWarn("got invalid introset from tag lookup"); return false; } - if(not introset.topic.has_value()) + if (not introset.topic.has_value()) return false; - if(introset.topic.value() != target) + if (introset.topic.value() != target) { llarp::LogWarn("got introset with missmatched topic in tag lookup"); return false; @@ -26,17 +26,15 @@ namespace llarp } void - TagLookup::Start(const TXOwner &peer) + TagLookup::Start(const TXOwner& peer) { - parent->DHTSendTo(peer.node.as_array(), - new FindIntroMessage(target, peer.txid)); + parent->DHTSendTo(peer.node.as_array(), new FindIntroMessage(target, peer.txid)); } void TagLookup::SendReply() { - parent->DHTSendTo(whoasked.node.as_array(), - new GotIntroMessage({}, whoasked.txid)); + parent->DHTSendTo(whoasked.node.as_array(), new GotIntroMessage({}, whoasked.txid)); } } // namespace dht } // namespace llarp diff --git a/llarp/dht/taglookup.hpp b/llarp/dht/taglookup.hpp index 954c0ec60..cc3ab398b 100644 --- a/llarp/dht/taglookup.hpp +++ b/llarp/dht/taglookup.hpp @@ -9,21 +9,20 @@ namespace llarp { namespace dht { - struct TagLookup : public TX< service::Tag, service::EncryptedIntroSet > + struct TagLookup : public TX { uint64_t recursionDepth; - TagLookup(const TXOwner &asker, const service::Tag &tag, - AbstractContext *ctx, uint64_t recursion) - : TX< service::Tag, service::EncryptedIntroSet >(asker, tag, ctx) - , recursionDepth(recursion) + TagLookup( + const TXOwner& asker, const service::Tag& tag, AbstractContext* ctx, uint64_t recursion) + : TX(asker, tag, ctx), recursionDepth(recursion) { } bool - Validate(const service::EncryptedIntroSet &introset) const override; + Validate(const service::EncryptedIntroSet& introset) const override; void - Start(const TXOwner &peer) override; + Start(const TXOwner& peer) override; void SendReply() override; diff --git a/llarp/dht/tx.hpp b/llarp/dht/tx.hpp index 0c4d71859..b9550bba2 100644 --- a/llarp/dht/tx.hpp +++ b/llarp/dht/tx.hpp @@ -15,13 +15,13 @@ namespace llarp { struct AbstractContext; - template < typename K, typename V > + template struct TX { K target; AbstractContext* parent; - std::set< Key_t > peersAsked; - std::vector< V > valuesFound; + std::set peersAsked; + std::vector valuesFound; TXOwner whoasked; TX(const TXOwner& asker, const K& k, AbstractContext* p) @@ -39,17 +39,19 @@ namespace llarp { util::StatusObject obj{{"whoasked", whoasked.ExtractStatus()}, {"target", target.ExtractStatus()}}; - std::vector< util::StatusObject > foundObjs; - std::transform(valuesFound.begin(), valuesFound.end(), - std::back_inserter(foundObjs), - [](const auto& item) -> util::StatusObject { - return item.ExtractStatus(); - }); + std::vector foundObjs; + std::transform( + valuesFound.begin(), + valuesFound.end(), + std::back_inserter(foundObjs), + [](const auto& item) -> util::StatusObject { return item.ExtractStatus(); }); obj["found"] = foundObjs; - std::vector< std::string > asked; + std::vector asked; std::transform( - peersAsked.begin(), peersAsked.end(), std::back_inserter(asked), + peersAsked.begin(), + peersAsked.end(), + std::back_inserter(asked), [](const auto& item) -> std::string { return item.ToString(); }); obj["asked"] = asked; return obj; @@ -65,12 +67,12 @@ namespace llarp SendReply() = 0; }; - template < typename K, typename V > + template inline void - TX< K, V >::OnFound(const Key_t& askedPeer, const V& value) + TX::OnFound(const Key_t& askedPeer, const V& value) { peersAsked.insert(askedPeer); - if(Validate(value)) + if (Validate(value)) { valuesFound.push_back(value); } diff --git a/llarp/dht/txholder.hpp b/llarp/dht/txholder.hpp index 8145e3b61..4fa8a7f96 100644 --- a/llarp/dht/txholder.hpp +++ b/llarp/dht/txholder.hpp @@ -13,46 +13,51 @@ namespace llarp { namespace dht { - template < typename K, typename V, typename K_Hash > + template struct TXHolder { - using TXPtr = std::unique_ptr< TX< K, V > >; + using TXPtr = std::unique_ptr>; // tx who are waiting for a reply for each key - std::unordered_multimap< K, TXOwner, K_Hash > waiting; + std::unordered_multimap waiting; // tx timesouts by key - std::unordered_map< K, llarp_time_t, K_Hash > timeouts; + std::unordered_map timeouts; // maps remote peer with tx to handle reply from them - std::unordered_map< TXOwner, TXPtr, TXOwner::Hash > tx; + std::unordered_map tx; - const TX< K, V >* + const TX* GetPendingLookupFrom(const TXOwner& owner) const; util::StatusObject ExtractStatus() const { util::StatusObject obj{}; - std::vector< util::StatusObject > txObjs, timeoutsObjs, waitingObjs; - std::transform(tx.begin(), tx.end(), std::back_inserter(txObjs), - [](const auto& item) -> util::StatusObject { - return util::StatusObject{ - {"owner", item.first.ExtractStatus()}, - {"tx", item.second->ExtractStatus()}}; - }); + std::vector txObjs, timeoutsObjs, waitingObjs; + std::transform( + tx.begin(), + tx.end(), + std::back_inserter(txObjs), + [](const auto& item) -> util::StatusObject { + return util::StatusObject{{"owner", item.first.ExtractStatus()}, + {"tx", item.second->ExtractStatus()}}; + }); obj["tx"] = txObjs; std::transform( - timeouts.begin(), timeouts.end(), std::back_inserter(timeoutsObjs), + timeouts.begin(), + timeouts.end(), + std::back_inserter(timeoutsObjs), [](const auto& item) -> util::StatusObject { return util::StatusObject{{"time", to_json(item.second)}, {"target", item.first.ExtractStatus()}}; }); obj["timeouts"] = timeoutsObjs; - std::transform(waiting.begin(), waiting.end(), - std::back_inserter(waitingObjs), - [](const auto& item) -> util::StatusObject { - return util::StatusObject{ - {"target", item.first.ExtractStatus()}, - {"whoasked", item.second.ExtractStatus()}}; - }); + std::transform( + waiting.begin(), + waiting.end(), + std::back_inserter(waitingObjs), + [](const auto& item) -> util::StatusObject { + return util::StatusObject{{"target", item.first.ExtractStatus()}, + {"whoasked", item.second.ExtractStatus()}}; + }); obj["waiting"] = waitingObjs; return obj; } @@ -70,34 +75,42 @@ namespace llarp } void - NewTX(const TXOwner& askpeer, const TXOwner& whoasked, const K& k, - TX< K, V >* t, llarp_time_t requestTimeoutMS = 15s); + NewTX( + const TXOwner& askpeer, + const TXOwner& whoasked, + const K& k, + TX* t, + llarp_time_t requestTimeoutMS = 15s); /// mark tx as not fond void - NotFound(const TXOwner& from, const std::unique_ptr< Key_t >& next); + NotFound(const TXOwner& from, const std::unique_ptr& next); void - Found(const TXOwner& from, const K& k, const std::vector< V >& values) + Found(const TXOwner& from, const K& k, const std::vector& values) { Inform(from, k, values, true); } /// inform all watches for key of values found void - Inform(TXOwner from, K key, std::vector< V > values, - bool sendreply = false, bool removeTimeouts = true); + Inform( + TXOwner from, + K key, + std::vector values, + bool sendreply = false, + bool removeTimeouts = true); void Expire(llarp_time_t now); }; - template < typename K, typename V, typename K_Hash > - const TX< K, V >* - TXHolder< K, V, K_Hash >::GetPendingLookupFrom(const TXOwner& owner) const + template + const TX* + TXHolder::GetPendingLookupFrom(const TXOwner& owner) const { auto itr = tx.find(owner); - if(itr == tx.end()) + if (itr == tx.end()) { return nullptr; } @@ -105,60 +118,60 @@ namespace llarp return itr->second.get(); } - template < typename K, typename V, typename K_Hash > + template void - TXHolder< K, V, K_Hash >::NewTX(const TXOwner& askpeer, - const TXOwner& whoasked, const K& k, - TX< K, V >* t, - llarp_time_t requestTimeoutMS) + TXHolder::NewTX( + const TXOwner& askpeer, + const TXOwner& whoasked, + const K& k, + TX* t, + llarp_time_t requestTimeoutMS) { (void)whoasked; - tx.emplace(askpeer, std::unique_ptr< TX< K, V > >(t)); + tx.emplace(askpeer, std::unique_ptr>(t)); auto count = waiting.count(k); waiting.emplace(k, askpeer); auto itr = timeouts.find(k); - if(itr == timeouts.end()) + if (itr == timeouts.end()) { timeouts.emplace(k, time_now_ms() + requestTimeoutMS); } - if(count == 0) + if (count == 0) { t->Start(askpeer); } } - template < typename K, typename V, typename K_Hash > + template void - TXHolder< K, V, K_Hash >::NotFound(const TXOwner& from, - const std::unique_ptr< Key_t >&) + TXHolder::NotFound(const TXOwner& from, const std::unique_ptr&) { auto txitr = tx.find(from); - if(txitr == tx.end()) + if (txitr == tx.end()) { return; } Inform(from, txitr->second->target, {}, true, true); } - template < typename K, typename V, typename K_Hash > + template void - TXHolder< K, V, K_Hash >::Inform(TXOwner from, K key, - std::vector< V > values, bool sendreply, - bool removeTimeouts) + TXHolder::Inform( + TXOwner from, K key, std::vector values, bool sendreply, bool removeTimeouts) { auto range = waiting.equal_range(key); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { auto txitr = tx.find(itr->second); - if(txitr != tx.end()) + if (txitr != tx.end()) { - for(const auto& value : values) + for (const auto& value : values) { txitr->second->OnFound(from.node, value); } - if(sendreply) + if (sendreply) { txitr->second->SendReply(); tx.erase(txitr); @@ -167,25 +180,25 @@ namespace llarp ++itr; } - if(sendreply) + if (sendreply) { waiting.erase(key); } - if(removeTimeouts) + if (removeTimeouts) { timeouts.erase(key); } } - template < typename K, typename V, typename K_Hash > + template void - TXHolder< K, V, K_Hash >::Expire(llarp_time_t now) + TXHolder::Expire(llarp_time_t now) { auto itr = timeouts.begin(); - while(itr != timeouts.end()) + while (itr != timeouts.end()) { - if(now >= itr->second) + if (now >= itr->second) { Inform(TXOwner{}, itr->first, {}, true, false); itr = timeouts.erase(itr); diff --git a/llarp/dht/txowner.hpp b/llarp/dht/txowner.hpp index 5c819d83b..23e337211 100644 --- a/llarp/dht/txowner.hpp +++ b/llarp/dht/txowner.hpp @@ -14,9 +14,9 @@ namespace llarp Key_t node; uint64_t txid = 0; - TXOwner() = default; + TXOwner() = default; TXOwner(const TXOwner&) = default; - TXOwner(TXOwner&&) = default; + TXOwner(TXOwner&&) = default; TXOwner& operator=(const TXOwner&) = default; diff --git a/llarp/dns/dns.hpp b/llarp/dns/dns.hpp index cfcd5ee9c..66d101cdd 100644 --- a/llarp/dns/dns.hpp +++ b/llarp/dns/dns.hpp @@ -7,24 +7,24 @@ namespace llarp { namespace dns { - constexpr uint16_t qTypeAAAA = 28; - constexpr uint16_t qTypeTXT = 16; - constexpr uint16_t qTypeMX = 15; - constexpr uint16_t qTypePTR = 12; + constexpr uint16_t qTypeAAAA = 28; + constexpr uint16_t qTypeTXT = 16; + constexpr uint16_t qTypeMX = 15; + constexpr uint16_t qTypePTR = 12; constexpr uint16_t qTypeCNAME = 5; - constexpr uint16_t qTypeNS = 2; - constexpr uint16_t qTypeA = 1; + constexpr uint16_t qTypeNS = 2; + constexpr uint16_t qTypeA = 1; constexpr uint16_t qClassIN = 1; - constexpr uint16_t flags_QR = (1 << 15); - constexpr uint16_t flags_AA = (1 << 10); - constexpr uint16_t flags_TC = (1 << 9); - constexpr uint16_t flags_RD = (1 << 8); - constexpr uint16_t flags_RA = (1 << 7); + constexpr uint16_t flags_QR = (1 << 15); + constexpr uint16_t flags_AA = (1 << 10); + constexpr uint16_t flags_TC = (1 << 9); + constexpr uint16_t flags_RD = (1 << 8); + constexpr uint16_t flags_RA = (1 << 7); constexpr uint16_t flags_RCODENameError = (3); - constexpr uint16_t flags_RCODEServFail = (2); - constexpr uint16_t flags_RCODENoError = (0); + constexpr uint16_t flags_RCODEServFail = (2); + constexpr uint16_t flags_RCODENoError = (0); } // namespace dns } // namespace llarp diff --git a/llarp/dns/message.cpp b/llarp/dns/message.cpp index 602b0cba3..fd98db744 100644 --- a/llarp/dns/message.cpp +++ b/llarp/dns/message.cpp @@ -16,15 +16,15 @@ namespace llarp bool MessageHeader::Encode(llarp_buffer_t* buf) const { - if(!buf->put_uint16(id)) + if (!buf->put_uint16(id)) return false; - if(!buf->put_uint16(fields)) + if (!buf->put_uint16(fields)) return false; - if(!buf->put_uint16(qd_count)) + if (!buf->put_uint16(qd_count)) return false; - if(!buf->put_uint16(an_count)) + if (!buf->put_uint16(an_count)) return false; - if(!buf->put_uint16(ns_count)) + if (!buf->put_uint16(ns_count)) return false; return buf->put_uint16(ar_count); } @@ -32,17 +32,17 @@ namespace llarp bool MessageHeader::Decode(llarp_buffer_t* buf) { - if(!buf->read_uint16(id)) + if (!buf->read_uint16(id)) return false; - if(!buf->read_uint16(fields)) + if (!buf->read_uint16(fields)) return false; - if(!buf->read_uint16(qd_count)) + if (!buf->read_uint16(qd_count)) return false; - if(!buf->read_uint16(an_count)) + if (!buf->read_uint16(an_count)) return false; - if(!buf->read_uint16(ns_count)) + if (!buf->read_uint16(ns_count)) return false; - if(!buf->read_uint16(ar_count)) + if (!buf->read_uint16(ar_count)) return false; return true; } @@ -67,8 +67,7 @@ namespace llarp { } - Message::Message(const MessageHeader& hdr) - : hdr_id(hdr.id), hdr_fields(hdr.fields) + Message::Message(const MessageHeader& hdr) : hdr_id(hdr.id), hdr_fields(hdr.fields) { questions.resize(size_t(hdr.qd_count)); answers.resize(size_t(hdr.an_count)); @@ -80,22 +79,22 @@ namespace llarp Message::Encode(llarp_buffer_t* buf) const { MessageHeader hdr; - hdr.id = hdr_id; - hdr.fields = hdr_fields; + hdr.id = hdr_id; + hdr.fields = hdr_fields; hdr.qd_count = questions.size(); hdr.an_count = answers.size(); hdr.ns_count = 0; hdr.ar_count = 0; - if(!hdr.Encode(buf)) + if (!hdr.Encode(buf)) return false; - for(const auto& question : questions) - if(!question.Encode(buf)) + for (const auto& question : questions) + if (!question.Encode(buf)) return false; - for(const auto& answer : answers) - if(!answer.Encode(buf)) + for (const auto& answer : answers) + if (!answer.Encode(buf)) return false; return true; @@ -104,18 +103,18 @@ namespace llarp bool Message::Decode(llarp_buffer_t* buf) { - for(auto& qd : questions) + for (auto& qd : questions) { - if(!qd.Decode(buf)) + if (!qd.Decode(buf)) { llarp::LogError("failed to decode question"); return false; } llarp::LogDebug(qd); } - for(auto& an : answers) + for (auto& an : answers) { - if(not an.Decode(buf)) + if (not an.Decode(buf)) { llarp::LogDebug("failed to decode answer"); return false; @@ -126,7 +125,7 @@ namespace llarp void Message::AddServFail(RR_TTL_t) { - if(questions.size()) + if (questions.size()) { hdr_fields |= flags_RCODEServFail; // authorative response with recursion available @@ -145,14 +144,14 @@ namespace llarp void Message::AddINReply(llarp::huint128_t ip, bool isV6, RR_TTL_t ttl) { - if(questions.size()) + if (questions.size()) { hdr_fields = reply_flags(hdr_fields); ResourceRecord rec; - rec.rr_name = questions[0].qname; + rec.rr_name = questions[0].qname; rec.rr_class = qClassIN; - rec.ttl = ttl; - if(isV6) + rec.ttl = ttl; + if (isV6) { rec.rr_type = qTypeAAAA; ip.ToV6(rec.rData); @@ -160,7 +159,7 @@ namespace llarp else { const auto addr = net::IPPacket::TruncateV6(ip); - rec.rr_type = qTypeA; + rec.rr_type = qTypeA; rec.rData.resize(4); htobe32buf(rec.rData.data(), addr.h); } @@ -171,20 +170,20 @@ namespace llarp void Message::AddAReply(std::string name, RR_TTL_t ttl) { - if(questions.size()) + if (questions.size()) { hdr_fields = reply_flags(hdr_fields); const auto& question = questions[0]; answers.emplace_back(); - auto& rec = answers.back(); - rec.rr_name = question.qname; - rec.rr_type = question.qtype; - rec.rr_class = qClassIN; - rec.ttl = ttl; - std::array< byte_t, 512 > tmp = {{0}}; + auto& rec = answers.back(); + rec.rr_name = question.qname; + rec.rr_type = question.qtype; + rec.rr_class = qClassIN; + rec.ttl = ttl; + std::array tmp = {{0}}; llarp_buffer_t buf(tmp); - if(EncodeName(&buf, name)) + if (EncodeName(&buf, name)) { buf.sz = buf.cur - buf.base; rec.rData.resize(buf.sz); @@ -196,20 +195,20 @@ namespace llarp void Message::AddNSReply(std::string name, RR_TTL_t ttl) { - if(not questions.empty()) + if (not questions.empty()) { hdr_fields = reply_flags(hdr_fields); const auto& question = questions[0]; answers.emplace_back(); - auto& rec = answers.back(); - rec.rr_name = question.qname; - rec.rr_type = qTypeNS; - rec.rr_class = qClassIN; - rec.ttl = ttl; - std::array< byte_t, 512 > tmp = {{0}}; + auto& rec = answers.back(); + rec.rr_name = question.qname; + rec.rr_type = qTypeNS; + rec.rr_class = qClassIN; + rec.ttl = ttl; + std::array tmp = {{0}}; llarp_buffer_t buf(tmp); - if(EncodeName(&buf, name)) + if (EncodeName(&buf, name)) { buf.sz = buf.cur - buf.base; rec.rData.resize(buf.sz); @@ -221,20 +220,20 @@ namespace llarp void Message::AddCNAMEReply(std::string name, RR_TTL_t ttl) { - if(questions.size()) + if (questions.size()) { hdr_fields = reply_flags(hdr_fields); const auto& question = questions[0]; answers.emplace_back(); - auto& rec = answers.back(); - rec.rr_name = question.qname; - rec.rr_type = qTypeCNAME; - rec.rr_class = qClassIN; - rec.ttl = ttl; - std::array< byte_t, 512 > tmp = {{0}}; + auto& rec = answers.back(); + rec.rr_name = question.qname; + rec.rr_type = qTypeCNAME; + rec.rr_class = qClassIN; + rec.ttl = ttl; + std::array tmp = {{0}}; llarp_buffer_t buf(tmp); - if(EncodeName(&buf, name)) + if (EncodeName(&buf, name)) { buf.sz = buf.cur - buf.base; rec.rData.resize(buf.sz); @@ -246,21 +245,21 @@ namespace llarp void Message::AddMXReply(std::string name, uint16_t priority, RR_TTL_t ttl) { - if(questions.size()) + if (questions.size()) { hdr_fields = reply_flags(hdr_fields); const auto& question = questions[0]; answers.emplace_back(); - auto& rec = answers.back(); - rec.rr_name = question.qname; - rec.rr_type = qTypeMX; - rec.rr_class = qClassIN; - rec.ttl = ttl; - std::array< byte_t, 512 > tmp = {{0}}; + auto& rec = answers.back(); + rec.rr_name = question.qname; + rec.rr_type = qTypeMX; + rec.rr_class = qClassIN; + rec.ttl = ttl; + std::array tmp = {{0}}; llarp_buffer_t buf(tmp); buf.put_uint16(priority); - if(EncodeName(&buf, name)) + if (EncodeName(&buf, name)) { buf.sz = buf.cur - buf.base; rec.rData.resize(buf.sz); @@ -271,7 +270,7 @@ namespace llarp void Message::AddNXReply(RR_TTL_t) { - if(questions.size()) + if (questions.size()) { // authorative response with recursion available hdr_fields = reply_flags(hdr_fields); diff --git a/llarp/dns/message.hpp b/llarp/dns/message.hpp index 3d1987ece..b4b0379fb 100644 --- a/llarp/dns/message.hpp +++ b/llarp/dns/message.hpp @@ -9,9 +9,9 @@ namespace llarp { namespace dns { - using MsgID_t = uint16_t; + using MsgID_t = uint16_t; using Fields_t = uint16_t; - using Count_t = uint16_t; + using Count_t = uint16_t; struct MessageHeader : public Serialize { @@ -35,9 +35,9 @@ 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; + 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; } }; @@ -83,10 +83,10 @@ namespace llarp MsgID_t hdr_id; Fields_t hdr_fields; - std::vector< Question > questions; - std::vector< ResourceRecord > answers; - std::vector< ResourceRecord > authorities; - std::vector< ResourceRecord > additional; + std::vector questions; + std::vector answers; + std::vector authorities; + std::vector additional; }; inline std::ostream& diff --git a/llarp/dns/name.cpp b/llarp/dns/name.cpp index 3ae7ed8e3..d67ee99ee 100644 --- a/llarp/dns/name.cpp +++ b/llarp/dns/name.cpp @@ -13,7 +13,7 @@ namespace llarp bool DecodeName(llarp_buffer_t* buf, Name_t& name, bool trimTrailingDot) { - if(buf->size_left() < 1) + if (buf->size_left() < 1) return false; std::stringstream ss; size_t l; @@ -21,19 +21,19 @@ namespace llarp { l = *buf->cur; buf->cur++; - if(l) + if (l) { - if(buf->size_left() < l) + if (buf->size_left() < l) return false; ss << Name_t((const char*)buf->cur, l); ss << "."; } buf->cur = buf->cur + l; - } while(l); + } while (l); name = ss.str(); /// trim off last dot - if(trimTrailingDot) + if (trimTrailingDot) name = name.substr(0, name.find_last_of('.')); return true; } @@ -42,22 +42,22 @@ namespace llarp EncodeName(llarp_buffer_t* buf, const Name_t& name) { std::stringstream ss; - if(name.size() && name[name.size() - 1] == '.') + if (name.size() && name[name.size() - 1] == '.') ss << name.substr(0, name.size() - 1); else ss << name; std::string part; - while(std::getline(ss, part, '.')) + while (std::getline(ss, part, '.')) { size_t l = part.length(); - if(l > 63) + if (l > 63) return false; *(buf->cur) = l; buf->cur++; - if(buf->size_left() < l) + if (buf->size_left() < l) return false; - if(l) + if (l) { memcpy(buf->cur, part.data(), l); buf->cur += l; @@ -74,46 +74,46 @@ namespace llarp DecodePTR(const Name_t& name, huint128_t& ip) { bool isV6 = false; - auto pos = name.find(".in-addr.arpa"); - if(pos == std::string::npos) + auto pos = name.find(".in-addr.arpa"); + if (pos == std::string::npos) { - pos = name.find(".ip6.arpa"); + pos = name.find(".ip6.arpa"); isV6 = true; } - if(pos == std::string::npos) + if (pos == std::string::npos) return false; - std::string sub = name.substr(0, pos + 1); + std::string sub = name.substr(0, pos + 1); const auto numdots = std::count(sub.begin(), sub.end(), '.'); - if(numdots == 4 && !isV6) + if (numdots == 4 && !isV6) { uint8_t a, b, c, d; pos = sub.find('.'); - d = atoi(sub.substr(0, pos).c_str()); + d = atoi(sub.substr(0, pos).c_str()); sub = sub.substr(pos + 1); pos = sub.find('.'); - c = atoi(sub.substr(0, pos).c_str()); + c = atoi(sub.substr(0, pos).c_str()); sub = sub.substr(pos + 1); pos = sub.find('.'); - b = atoi(sub.substr(0, pos).c_str()); + b = atoi(sub.substr(0, pos).c_str()); sub = sub.substr(pos + 1); pos = sub.find('.'); - a = atoi(sub.substr(0, pos).c_str()); - ip = net::IPPacket::ExpandV4(llarp::ipaddr_ipv4_bits(a, b, c, d)); + a = atoi(sub.substr(0, pos).c_str()); + ip = net::IPPacket::ExpandV4(llarp::ipaddr_ipv4_bits(a, b, c, d)); return true; } - if(numdots == 32 && isV6) + if (numdots == 32 && isV6) { size_t idx = 0; uint8_t lo, hi; auto* ptr = (uint8_t*)&ip.h; - while(idx < 16) + while (idx < 16) { - pos = sub.find('.'); - lo = (*sub.substr(0, pos).c_str()) - 'a'; - sub = sub.substr(pos + 1); - pos = sub.find('.'); - hi = (*sub.substr(0, pos).c_str()) - 'a'; - sub = sub.substr(pos + 1); + pos = sub.find('.'); + lo = (*sub.substr(0, pos).c_str()) - 'a'; + sub = sub.substr(pos + 1); + pos = sub.find('.'); + hi = (*sub.substr(0, pos).c_str()) - 'a'; + sub = sub.substr(pos + 1); ptr[idx] = lo | (hi << 4); ++idx; } diff --git a/llarp/dns/question.cpp b/llarp/dns/question.cpp index 3378531a7..83ff57262 100644 --- a/llarp/dns/question.cpp +++ b/llarp/dns/question.cpp @@ -21,9 +21,9 @@ namespace llarp bool Question::Encode(llarp_buffer_t* buf) const { - if(!EncodeName(buf, qname)) + if (!EncodeName(buf, qname)) return false; - if(!buf->put_uint16(qtype)) + if (!buf->put_uint16(qtype)) return false; return buf->put_uint16(qclass); } @@ -31,17 +31,17 @@ namespace llarp bool Question::Decode(llarp_buffer_t* buf) { - if(!DecodeName(buf, qname)) + if (!DecodeName(buf, qname)) { llarp::LogError("failed to decode name"); return false; } - if(!buf->read_uint16(qtype)) + if (!buf->read_uint16(qtype)) { llarp::LogError("failed to decode type"); return false; } - if(!buf->read_uint16(qclass)) + if (!buf->read_uint16(qclass)) { llarp::LogError("failed to decode class"); return false; @@ -53,7 +53,7 @@ namespace llarp Question::IsName(const std::string& other) const { // does other have a . at the end? - if(other.find_last_of('.') == (other.size() - 1)) + if (other.find_last_of('.') == (other.size() - 1)) return other == qname; // no, add it and retry return IsName(other + "."); diff --git a/llarp/dns/question.hpp b/llarp/dns/question.hpp index 43490df91..2f4f19fa5 100644 --- a/llarp/dns/question.hpp +++ b/llarp/dns/question.hpp @@ -9,7 +9,7 @@ namespace llarp { namespace dns { - using QType_t = uint16_t; + using QType_t = uint16_t; using QClass_t = uint16_t; struct Question : public Serialize @@ -29,8 +29,7 @@ namespace llarp bool operator==(const Question& other) const { - return qname == other.qname && qtype == other.qtype - && qclass == other.qclass; + return qname == other.qname && qtype == other.qtype && qclass == other.qclass; } Name_t qname; diff --git a/llarp/dns/rr.cpp b/llarp/dns/rr.cpp index c29a4dce0..d5c457b0f 100644 --- a/llarp/dns/rr.cpp +++ b/llarp/dns/rr.cpp @@ -29,21 +29,21 @@ namespace llarp bool ResourceRecord::Encode(llarp_buffer_t* buf) const { - if(not EncodeName(buf, rr_name)) + if (not EncodeName(buf, rr_name)) return false; - if(!buf->put_uint16(rr_type)) + if (!buf->put_uint16(rr_type)) { return false; } - if(!buf->put_uint16(rr_class)) + if (!buf->put_uint16(rr_class)) { return false; } - if(!buf->put_uint32(ttl)) + if (!buf->put_uint32(ttl)) { return false; } - if(!EncodeRData(buf, rData)) + if (!EncodeRData(buf, rData)) { return false; } @@ -54,24 +54,24 @@ namespace llarp ResourceRecord::Decode(llarp_buffer_t* buf) { uint16_t discard; - if(!buf->read_uint16(discard)) + if (!buf->read_uint16(discard)) return false; - if(!buf->read_uint16(rr_type)) + if (!buf->read_uint16(rr_type)) { llarp::LogDebug("failed to decode rr type"); return false; } - if(!buf->read_uint16(rr_class)) + if (!buf->read_uint16(rr_class)) { llarp::LogDebug("failed to decode rr class"); return false; } - if(!buf->read_uint32(ttl)) + if (!buf->read_uint32(ttl)) { llarp::LogDebug("failed to decode ttl"); return false; } - if(!DecodeRData(buf, rData)) + if (!DecodeRData(buf, rData)) { llarp::LogDebug("failed to decode rr rdata ", *this); return false; @@ -95,11 +95,11 @@ namespace llarp bool ResourceRecord::HasCNameForTLD(const std::string& tld) const { - if(rr_type != qTypeCNAME) + if (rr_type != qTypeCNAME) return false; Name_t name; llarp_buffer_t buf(rData); - if(not DecodeName(&buf, name)) + if (not DecodeName(&buf, name)) return false; return name.find(tld) != std::string::npos && name.rfind(tld) == (name.size() - tld.size()) - 1; diff --git a/llarp/dns/rr.hpp b/llarp/dns/rr.hpp index 71a32ece4..d4cbb3005 100644 --- a/llarp/dns/rr.hpp +++ b/llarp/dns/rr.hpp @@ -12,10 +12,10 @@ namespace llarp { namespace dns { - using RRClass_t = uint16_t; - using RRType_t = uint16_t; - using RR_RData_t = std::vector< byte_t >; - using RR_TTL_t = uint32_t; + using RRClass_t = uint16_t; + using RRType_t = uint16_t; + using RR_RData_t = std::vector; + using RR_TTL_t = uint32_t; struct ResourceRecord : public Serialize { diff --git a/llarp/dns/serialize.cpp b/llarp/dns/serialize.cpp index 70a29c356..f848da23c 100644 --- a/llarp/dns/serialize.cpp +++ b/llarp/dns/serialize.cpp @@ -8,14 +8,14 @@ namespace llarp Serialize::~Serialize() = default; bool - EncodeRData(llarp_buffer_t* buf, const std::vector< byte_t >& v) + EncodeRData(llarp_buffer_t* buf, const std::vector& v) { - if(v.size() > 65536) + if (v.size() > 65536) return false; uint16_t len = v.size(); - if(!buf->put_uint16(len)) + if (!buf->put_uint16(len)) return false; - if(buf->size_left() < len) + if (buf->size_left() < len) return false; memcpy(buf->cur, v.data(), len); buf->cur += len; @@ -23,16 +23,16 @@ namespace llarp } bool - DecodeRData(llarp_buffer_t* buf, std::vector< byte_t >& v) + DecodeRData(llarp_buffer_t* buf, std::vector& v) { uint16_t len; - if(!buf->read_uint16(len)) + if (!buf->read_uint16(len)) return false; size_t left = buf->size_left(); - if(left < len) + if (left < len) return false; v.resize(size_t(len)); - if(len) + if (len) { memcpy(v.data(), buf->cur, len); buf->cur += len; diff --git a/llarp/dns/serialize.hpp b/llarp/dns/serialize.hpp index 564ca049c..1aa875ef4 100644 --- a/llarp/dns/serialize.hpp +++ b/llarp/dns/serialize.hpp @@ -24,10 +24,10 @@ namespace llarp }; bool - EncodeRData(llarp_buffer_t* buf, const std::vector< byte_t >& rdata); + EncodeRData(llarp_buffer_t* buf, const std::vector& rdata); bool - DecodeRData(llarp_buffer_t* buf, std::vector< byte_t >& rdata); + DecodeRData(llarp_buffer_t* buf, std::vector& rdata); } // namespace dns } // namespace llarp diff --git a/llarp/dns/server.cpp b/llarp/dns/server.cpp index f37768554..50b22b073 100644 --- a/llarp/dns/server.cpp +++ b/llarp/dns/server.cpp @@ -9,19 +9,22 @@ namespace llarp { namespace dns { - Proxy::Proxy(llarp_ev_loop_ptr serverLoop, Logic_ptr serverLogic, - llarp_ev_loop_ptr clientLoop, Logic_ptr clientLogic, - IQueryHandler* h) + Proxy::Proxy( + llarp_ev_loop_ptr serverLoop, + Logic_ptr serverLogic, + llarp_ev_loop_ptr clientLoop, + Logic_ptr clientLogic, + IQueryHandler* h) : m_ServerLoop(std::move(serverLoop)) , m_ClientLoop(std::move(clientLoop)) , m_ServerLogic(std::move(serverLogic)) , m_ClientLogic(std::move(clientLogic)) , m_QueryHandler(h) { - m_Client.user = this; - m_Server.user = this; - m_Client.tick = nullptr; - m_Server.tick = nullptr; + m_Client.user = this; + m_Server.user = this; + m_Client.tick = nullptr; + m_Server.tick = nullptr; m_Client.recvfrom = &HandleUDPRecv_client; m_Server.recvfrom = &HandleUDPRecv_server; } @@ -32,8 +35,7 @@ namespace llarp } bool - Proxy::Start(const llarp::Addr addr, - const std::vector< llarp::Addr >& resolvers) + Proxy::Start(const llarp::Addr addr, const std::vector& resolvers) { m_Resolvers.clear(); m_Resolvers = resolvers; @@ -51,42 +53,38 @@ namespace llarp static Proxy::Buffer_t CopyBuffer(const llarp_buffer_t& buf) { - std::vector< byte_t > msgbuf(buf.sz); + std::vector msgbuf(buf.sz); std::copy_n(buf.base, buf.sz, msgbuf.data()); return msgbuf; } void - Proxy::HandleUDPRecv_server(llarp_udp_io* u, const sockaddr* from, - ManagedBuffer buf) + Proxy::HandleUDPRecv_server(llarp_udp_io* u, const sockaddr* from, ManagedBuffer buf) { const llarp::Addr addr(*from); Buffer_t msgbuf = CopyBuffer(buf.underlying); - auto self = static_cast< Proxy* >(u->user)->shared_from_this(); + auto self = static_cast(u->user)->shared_from_this(); // yes we use the server loop here because if the server loop is not the // client loop we'll crash again - LogicCall(self->m_ServerLogic, [self, addr, msgbuf]() { - self->HandlePktServer(addr, msgbuf); - }); + LogicCall( + self->m_ServerLogic, [self, addr, msgbuf]() { self->HandlePktServer(addr, msgbuf); }); } void - Proxy::HandleUDPRecv_client(llarp_udp_io* u, const sockaddr* from, - ManagedBuffer buf) + Proxy::HandleUDPRecv_client(llarp_udp_io* u, const sockaddr* from, ManagedBuffer buf) { const llarp::Addr addr(*from); Buffer_t msgbuf = CopyBuffer(buf.underlying); - auto self = static_cast< Proxy* >(u->user)->shared_from_this(); - LogicCall(self->m_ServerLogic, [self, addr, msgbuf]() { - self->HandlePktClient(addr, msgbuf); - }); + auto self = static_cast(u->user)->shared_from_this(); + LogicCall( + self->m_ServerLogic, [self, addr, msgbuf]() { self->HandlePktClient(addr, msgbuf); }); } llarp::Addr Proxy::PickRandomResolver() const { const size_t sz = m_Resolvers.size(); - if(sz <= 1) + if (sz <= 1) return m_Resolvers[0]; auto itr = m_Resolvers.begin(); std::advance(itr, llarp::randint() % sz); @@ -103,11 +101,11 @@ namespace llarp { auto self = shared_from_this(); LogicCall(m_ServerLogic, [to, msg, self]() { - std::array< byte_t, 1500 > tmp = {{0}}; + std::array tmp = {{0}}; llarp_buffer_t buf(tmp); - if(msg.Encode(&buf)) + if (msg.Encode(&buf)) { - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; llarp_ev_udp_sendto(&self->m_Server, to, buf); } @@ -121,11 +119,11 @@ namespace llarp { auto self = shared_from_this(); LogicCall(m_ClientLogic, [to, msg, self]() { - std::array< byte_t, 1500 > tmp = {{0}}; + std::array tmp = {{0}}; llarp_buffer_t buf(tmp); - if(msg.Encode(&buf)) + if (msg.Encode(&buf)) { - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; llarp_ev_udp_sendto(&self->m_Client, to, buf); } @@ -139,27 +137,26 @@ namespace llarp { llarp_buffer_t pkt(buf); MessageHeader hdr; - if(!hdr.Decode(&pkt)) + if (!hdr.Decode(&pkt)) { llarp::LogWarn("failed to parse dns header from ", from); return; } - TX tx = {hdr.id, from}; + TX tx = {hdr.id, from}; auto itr = m_Forwarded.find(tx); - if(itr == m_Forwarded.end()) + if (itr == m_Forwarded.end()) return; const Addr requester = itr->second; - auto self = shared_from_this(); + auto self = shared_from_this(); Message msg(hdr); - if(msg.Decode(&pkt)) + if (msg.Decode(&pkt)) { - if(m_QueryHandler && m_QueryHandler->ShouldHookDNSMessage(msg)) + if (m_QueryHandler && m_QueryHandler->ShouldHookDNSMessage(msg)) { msg.hdr_id = itr->first.txid; - if(!m_QueryHandler->HandleHookedDNSMessage( - std::move(msg), - std::bind(&Proxy::SendServerMessageTo, self, requester, - std::placeholders::_1))) + if (!m_QueryHandler->HandleHookedDNSMessage( + std::move(msg), + std::bind(&Proxy::SendServerMessageTo, self, requester, std::placeholders::_1))) { llarp::LogWarn("failed to handle hooked dns"); } @@ -180,16 +177,16 @@ namespace llarp { MessageHeader hdr; llarp_buffer_t pkt(buf); - if(!hdr.Decode(&pkt)) + if (!hdr.Decode(&pkt)) { llarp::LogWarn("failed to parse dns header from ", from); return; } - TX tx = {hdr.id, from}; + TX tx = {hdr.id, from}; auto itr = m_Forwarded.find(tx); Message msg(hdr); - if(!msg.Decode(&pkt)) + if (!msg.Decode(&pkt)) { llarp::LogWarn("failed to parse dns message from ", from); return; @@ -200,10 +197,10 @@ namespace llarp // thankfully mozilla added a backdoor that allows ISPs to turn it off // so we disable DoH for firefox using mozilla's ISP backdoor // see: https://github.com/loki-project/loki-network/issues/832 - for(const auto& q : msg.questions) + for (const auto& q : msg.questions) { // is this firefox looking for their backdoor record? - if(q.IsName("use-application-dns.net")) + if (q.IsName("use-application-dns.net")) { // yea it is, let's turn off DoH because god is dead. msg.AddNXReply(); @@ -214,17 +211,16 @@ namespace llarp } auto self = shared_from_this(); - if(m_QueryHandler && m_QueryHandler->ShouldHookDNSMessage(msg)) + if (m_QueryHandler && m_QueryHandler->ShouldHookDNSMessage(msg)) { - if(!m_QueryHandler->HandleHookedDNSMessage( - std::move(msg), - std::bind(&Proxy::SendServerMessageTo, self, from, - std::placeholders::_1))) + if (!m_QueryHandler->HandleHookedDNSMessage( + std::move(msg), + std::bind(&Proxy::SendServerMessageTo, self, from, std::placeholders::_1))) { llarp::LogWarn("failed to handle hooked dns"); } } - else if(m_Resolvers.size() == 0) + else if (m_Resolvers.size() == 0) { // no upstream resolvers // let's serv fail it @@ -232,10 +228,10 @@ namespace llarp SendServerMessageTo(from, std::move(msg)); } - else if(itr == m_Forwarded.end()) + else if (itr == m_Forwarded.end()) { // new forwarded query - tx.from = PickRandomResolver(); + tx.from = PickRandomResolver(); m_Forwarded[tx] = from; LogicCall(m_ClientLogic, [=] { // do query diff --git a/llarp/dns/server.hpp b/llarp/dns/server.hpp index 509e1d831..2c706cb31 100644 --- a/llarp/dns/server.hpp +++ b/llarp/dns/server.hpp @@ -24,34 +24,33 @@ namespace llarp /// handle a hooked message virtual bool - HandleHookedDNSMessage(Message query, - std::function< void(Message) > sendReply) = 0; + HandleHookedDNSMessage(Message query, std::function sendReply) = 0; }; - struct Proxy : public std::enable_shared_from_this< Proxy > + struct Proxy : public std::enable_shared_from_this { - using Logic_ptr = std::shared_ptr< Logic >; - Proxy(llarp_ev_loop_ptr serverLoop, Logic_ptr serverLogic, - llarp_ev_loop_ptr clientLoop, Logic_ptr clientLogic, - IQueryHandler* handler); + using Logic_ptr = std::shared_ptr; + Proxy( + llarp_ev_loop_ptr serverLoop, + Logic_ptr serverLogic, + llarp_ev_loop_ptr clientLoop, + Logic_ptr clientLogic, + IQueryHandler* handler); bool - Start(const llarp::Addr addr, - const std::vector< llarp::Addr >& resolvers); + Start(const llarp::Addr addr, const std::vector& resolvers); void Stop(); - using Buffer_t = std::vector< uint8_t >; + using Buffer_t = std::vector; private: /// low level packet handler static void - HandleUDPRecv_client(llarp_udp_io*, const struct sockaddr*, - ManagedBuffer); + HandleUDPRecv_client(llarp_udp_io*, const struct sockaddr*, ManagedBuffer); static void - HandleUDPRecv_server(llarp_udp_io*, const struct sockaddr*, - ManagedBuffer); + HandleUDPRecv_server(llarp_udp_io*, const struct sockaddr*, ManagedBuffer); /// low level ticker static void @@ -83,7 +82,7 @@ namespace llarp Logic_ptr m_ServerLogic; Logic_ptr m_ClientLogic; IQueryHandler* m_QueryHandler; - std::vector< llarp::Addr > m_Resolvers; + std::vector m_Resolvers; struct TX { @@ -107,7 +106,7 @@ namespace llarp }; // maps tx to who to send reply to - std::unordered_map< TX, llarp::Addr, TX::Hash > m_Forwarded; + std::unordered_map m_Forwarded; }; } // namespace dns } // namespace llarp diff --git a/llarp/ev/ev.cpp b/llarp/ev/ev.cpp index 1d952c1bc..944668617 100644 --- a/llarp/ev/ev.cpp +++ b/llarp/ev/ev.cpp @@ -17,17 +17,16 @@ llarp_ev_loop_ptr llarp_make_ev_loop() { - llarp_ev_loop_ptr r = std::make_shared< libuv::Loop >(); + llarp_ev_loop_ptr r = std::make_shared(); r->init(); r->update_time(); return r; } void -llarp_ev_loop_run_single_process(llarp_ev_loop_ptr ev, - std::shared_ptr< llarp::Logic > logic) +llarp_ev_loop_run_single_process(llarp_ev_loop_ptr ev, std::shared_ptr logic) { - while(ev->running()) + while (ev->running()) { ev->update_time(); ev->tick(EV_TICK_INTERVAL); @@ -38,53 +37,51 @@ llarp_ev_loop_run_single_process(llarp_ev_loop_ptr ev, } int -llarp_ev_add_udp(struct llarp_ev_loop *ev, struct llarp_udp_io *udp, - const struct sockaddr *src) +llarp_ev_add_udp(struct llarp_ev_loop* ev, struct llarp_udp_io* udp, const struct sockaddr* src) { udp->parent = ev; - if(ev->udp_listen(udp, src)) + if (ev->udp_listen(udp, src)) return 0; return -1; } int -llarp_ev_close_udp(struct llarp_udp_io *udp) +llarp_ev_close_udp(struct llarp_udp_io* udp) { - if(udp->parent->udp_close(udp)) + if (udp->parent->udp_close(udp)) return 0; return -1; } llarp_time_t -llarp_ev_loop_time_now_ms(const llarp_ev_loop_ptr &loop) +llarp_ev_loop_time_now_ms(const llarp_ev_loop_ptr& loop) { - if(loop) + if (loop) return loop->time_now(); return llarp::time_now_ms(); } void -llarp_ev_loop_stop(const llarp_ev_loop_ptr &loop) +llarp_ev_loop_stop(const llarp_ev_loop_ptr& loop) { loop->stop(); } int -llarp_ev_udp_sendto(struct llarp_udp_io *udp, const sockaddr *to, - const llarp_buffer_t &buf) +llarp_ev_udp_sendto(struct llarp_udp_io* udp, const sockaddr* to, const llarp_buffer_t& buf) { return udp->sendto(udp, to, buf.base, buf.sz); } bool -llarp_ev_add_tun(struct llarp_ev_loop *loop, struct llarp_tun_io *tun) +llarp_ev_add_tun(struct llarp_ev_loop* loop, struct llarp_tun_io* tun) { - if(tun->ifaddr[0] == 0 || strcmp(tun->ifaddr, "auto") == 0) + if (tun->ifaddr[0] == 0 || strcmp(tun->ifaddr, "auto") == 0) { LogError("invalid ifaddr on tun: ", tun->ifaddr); return false; } - if(tun->ifname[0] == 0 || strcmp(tun->ifname, "auto") == 0) + if (tun->ifname[0] == 0 || strcmp(tun->ifname, "auto") == 0) { LogError("invalid ifname on tun: ", tun->ifname); return false; @@ -93,10 +90,10 @@ llarp_ev_add_tun(struct llarp_ev_loop *loop, struct llarp_tun_io *tun) return loop->tun_listen(tun); #else UNREFERENCED_PARAMETER(loop); - auto dev = new win32_tun_io(tun); + auto dev = new win32_tun_io(tun); tun->impl = dev; // We're not even going to add this to the socket event loop - if(dev) + if (dev) { dev->setup(); return dev->add_ev(loop); // start up tun and add to event queue @@ -107,9 +104,9 @@ llarp_ev_add_tun(struct llarp_ev_loop *loop, struct llarp_tun_io *tun) } bool -llarp_ev_tun_async_write(struct llarp_tun_io *tun, const llarp_buffer_t &buf) +llarp_ev_tun_async_write(struct llarp_tun_io* tun, const llarp_buffer_t& buf) { - if(buf.sz > EV_WRITE_BUF_SZ) + if (buf.sz > EV_WRITE_BUF_SZ) { llarp::LogWarn("packet too big, ", buf.sz, " > ", EV_WRITE_BUF_SZ); return false; @@ -117,22 +114,21 @@ llarp_ev_tun_async_write(struct llarp_tun_io *tun, const llarp_buffer_t &buf) #ifndef _WIN32 return tun->writepkt(tun, buf.base, buf.sz); #else - return static_cast< win32_tun_io * >(tun->impl)->queue_write(buf.base, - buf.sz); + return static_cast(tun->impl)->queue_write(buf.base, buf.sz); #endif } bool -llarp_tcp_conn_async_write(struct llarp_tcp_conn *conn, const llarp_buffer_t &b) +llarp_tcp_conn_async_write(struct llarp_tcp_conn* conn, const llarp_buffer_t& b) { ManagedBuffer buf{b}; - size_t sz = buf.underlying.sz; + size_t sz = buf.underlying.sz; buf.underlying.cur = buf.underlying.base; - while(sz > EV_WRITE_BUF_SZ) + while (sz > EV_WRITE_BUF_SZ) { ssize_t amount = conn->write(conn, buf.underlying.cur, EV_WRITE_BUF_SZ); - if(amount <= 0) + if (amount <= 0) { llarp::LogError("write underrun"); llarp_tcp_conn_close(conn); @@ -145,25 +141,24 @@ llarp_tcp_conn_async_write(struct llarp_tcp_conn *conn, const llarp_buffer_t &b) } void -llarp_tcp_async_try_connect(struct llarp_ev_loop *loop, - struct llarp_tcp_connecter *tcp) +llarp_tcp_async_try_connect(struct llarp_ev_loop* loop, struct llarp_tcp_connecter* tcp) { tcp->loop = loop; llarp::string_view addr_str, port_str; // try parsing address - const char *begin = tcp->remote; - const char *ptr = strstr(tcp->remote, ":"); + const char* begin = tcp->remote; + const char* ptr = strstr(tcp->remote, ":"); // get end of address - if(ptr == nullptr) + if (ptr == nullptr) { llarp::LogError("bad address: ", tcp->remote); - if(tcp->error) + if (tcp->error) tcp->error(tcp); return; } - const char *end = ptr; - while(*end && ((end - begin) < static_cast< ptrdiff_t >(sizeof tcp->remote))) + const char* end = ptr; + while (*end && ((end - begin) < static_cast(sizeof tcp->remote))) { ++end; } @@ -173,30 +168,30 @@ llarp_tcp_async_try_connect(struct llarp_ev_loop *loop, // actually parse address llarp::Addr addr(addr_str, port_str); - if(!loop->tcp_connect(tcp, addr)) + if (!loop->tcp_connect(tcp, addr)) { llarp::LogError("async connect failed"); - if(tcp->error) + if (tcp->error) tcp->error(tcp); } } bool -llarp_tcp_serve(struct llarp_ev_loop *loop, struct llarp_tcp_acceptor *tcp, - const struct sockaddr *bindaddr) +llarp_tcp_serve( + struct llarp_ev_loop* loop, struct llarp_tcp_acceptor* tcp, const struct sockaddr* bindaddr) { tcp->loop = loop; return loop->tcp_listen(tcp, bindaddr); } void -llarp_tcp_acceptor_close(struct llarp_tcp_acceptor *tcp) +llarp_tcp_acceptor_close(struct llarp_tcp_acceptor* tcp) { tcp->close(tcp); } void -llarp_tcp_conn_close(struct llarp_tcp_conn *conn) +llarp_tcp_conn_close(struct llarp_tcp_conn* conn) { conn->close(conn); } @@ -206,14 +201,14 @@ namespace llarp bool tcp_conn::tick() { - if(_shouldClose) + if (_shouldClose) { - if(tcp.closed) + if (tcp.closed) tcp.closed(&tcp); ::shutdown(fd, SHUT_RDWR); return false; } - if(tcp.tick) + if (tcp.tick) tcp.tick(&tcp); return true; } diff --git a/llarp/ev/ev.h b/llarp/ev/ev.h index 3cf609eb1..5a1085478 100644 --- a/llarp/ev/ev.h +++ b/llarp/ev/ev.h @@ -42,7 +42,7 @@ namespace llarp class Logic; } -using llarp_ev_loop_ptr = std::shared_ptr< llarp_ev_loop >; +using llarp_ev_loop_ptr = std::shared_ptr; /// make an event loop using our baked in event loop on Windows /// make an event loop using libuv otherwise. @@ -51,16 +51,15 @@ llarp_make_ev_loop(); // run mainloop void -llarp_ev_loop_run_single_process(llarp_ev_loop_ptr ev, - std::shared_ptr< llarp::Logic > logic); +llarp_ev_loop_run_single_process(llarp_ev_loop_ptr ev, std::shared_ptr logic); /// get the current time on the event loop llarp_time_t -llarp_ev_loop_time_now_ms(const llarp_ev_loop_ptr &ev); +llarp_ev_loop_time_now_ms(const llarp_ev_loop_ptr& ev); /// stop event loop and wait for it to complete all jobs void -llarp_ev_loop_stop(const llarp_ev_loop_ptr &ev); +llarp_ev_loop_stop(const llarp_ev_loop_ptr& ev); /// list of packets we recv'd /// forward declared @@ -71,38 +70,34 @@ struct llarp_udp_io { /// set after added int fd; - void *user; - void *impl; - struct llarp_ev_loop *parent; + void* user; + void* impl; + struct llarp_ev_loop* parent; /// called every event loop tick after reads - void (*tick)(struct llarp_udp_io *); + void (*tick)(struct llarp_udp_io*); /// sockaddr * is the source address - void (*recvfrom)(struct llarp_udp_io *, const struct sockaddr *, - ManagedBuffer); + void (*recvfrom)(struct llarp_udp_io*, const struct sockaddr*, ManagedBuffer); /// set by parent - int (*sendto)(struct llarp_udp_io *, const struct sockaddr *, const byte_t *, - size_t); + int (*sendto)(struct llarp_udp_io*, const struct sockaddr*, const byte_t*, size_t); }; /// get all packets recvieved last tick /// return true if we got packets return false if we didn't bool -llarp_ev_udp_recvmany(struct llarp_udp_io *udp, struct llarp_pkt_list *pkts); +llarp_ev_udp_recvmany(struct llarp_udp_io* udp, struct llarp_pkt_list* pkts); /// add UDP handler int -llarp_ev_add_udp(struct llarp_ev_loop *ev, struct llarp_udp_io *udp, - const struct sockaddr *src); +llarp_ev_add_udp(struct llarp_ev_loop* ev, struct llarp_udp_io* udp, const struct sockaddr* src); /// send a UDP packet int -llarp_ev_udp_sendto(struct llarp_udp_io *udp, const struct sockaddr *to, - const llarp_buffer_t &pkt); +llarp_ev_udp_sendto(struct llarp_udp_io* udp, const struct sockaddr* to, const llarp_buffer_t& pkt); /// close UDP handler int -llarp_ev_close_udp(struct llarp_udp_io *udp); +llarp_ev_close_udp(struct llarp_udp_io* udp); // forward declare struct llarp_tcp_acceptor; @@ -111,33 +106,33 @@ struct llarp_tcp_acceptor; struct llarp_tcp_conn { /// user data - void *user; + void* user; /// private implementation - void *impl; + void* impl; /// parent loop (dont set me) - struct llarp_ev_loop *loop; + struct llarp_ev_loop* loop; /// handle read event - void (*read)(struct llarp_tcp_conn *, const llarp_buffer_t &); + void (*read)(struct llarp_tcp_conn*, const llarp_buffer_t&); //// set by parent - ssize_t (*write)(struct llarp_tcp_conn *, const byte_t *, size_t sz); + ssize_t (*write)(struct llarp_tcp_conn*, const byte_t*, size_t sz); /// set by parent - bool (*is_open)(struct llarp_tcp_conn *); + bool (*is_open)(struct llarp_tcp_conn*); /// handle close event (free-ing is handled by event loop) - void (*closed)(struct llarp_tcp_conn *); + void (*closed)(struct llarp_tcp_conn*); /// explict close by user (set by parent) - void (*close)(struct llarp_tcp_conn *); + void (*close)(struct llarp_tcp_conn*); /// handle event loop tick - void (*tick)(struct llarp_tcp_conn *); + void (*tick)(struct llarp_tcp_conn*); }; /// queue async write a buffer in full /// return if we queued it or not bool -llarp_tcp_conn_async_write(struct llarp_tcp_conn *, const llarp_buffer_t &); +llarp_tcp_conn_async_write(struct llarp_tcp_conn*, const llarp_buffer_t&); /// close a tcp connection void -llarp_tcp_conn_close(struct llarp_tcp_conn *); +llarp_tcp_conn_close(struct llarp_tcp_conn*); /// handles outbound connections to 1 endpoint struct llarp_tcp_connecter @@ -147,51 +142,49 @@ struct llarp_tcp_connecter /// remote address string char remote[512]; /// userdata pointer - void *user; + void* user; /// private implementation (dont set me) - void *impl; + void* impl; /// parent event loop (dont set me) - struct llarp_ev_loop *loop; + struct llarp_ev_loop* loop; /// handle outbound connection made - void (*connected)(struct llarp_tcp_connecter *, struct llarp_tcp_conn *); + void (*connected)(struct llarp_tcp_connecter*, struct llarp_tcp_conn*); /// handle outbound connection error - void (*error)(struct llarp_tcp_connecter *); + void (*error)(struct llarp_tcp_connecter*); }; /// async try connecting to a remote connection 1 time void -llarp_tcp_async_try_connect(struct llarp_ev_loop *l, - struct llarp_tcp_connecter *tcp); +llarp_tcp_async_try_connect(struct llarp_ev_loop* l, struct llarp_tcp_connecter* tcp); /// handles inbound connections struct llarp_tcp_acceptor { /// userdata pointer - void *user; + void* user; /// internal implementation - void *impl; + void* impl; /// parent event loop (dont set me) - struct llarp_ev_loop *loop; + struct llarp_ev_loop* loop; /// handle event loop tick - void (*tick)(struct llarp_tcp_acceptor *); + void (*tick)(struct llarp_tcp_acceptor*); /// handle inbound connection - void (*accepted)(struct llarp_tcp_acceptor *, struct llarp_tcp_conn *); + void (*accepted)(struct llarp_tcp_acceptor*, struct llarp_tcp_conn*); /// handle after server socket closed (free-ing is handled by event loop) - void (*closed)(struct llarp_tcp_acceptor *); + void (*closed)(struct llarp_tcp_acceptor*); /// set by impl - void (*close)(struct llarp_tcp_acceptor *); + void (*close)(struct llarp_tcp_acceptor*); }; /// bind to an address and start serving async /// return false if failed to bind /// return true on success bool -llarp_tcp_serve(struct llarp_ev_loop *loop, struct llarp_tcp_acceptor *t, - const sockaddr *bindaddr); +llarp_tcp_serve(struct llarp_ev_loop* loop, struct llarp_tcp_acceptor* t, const sockaddr* bindaddr); /// close and stop accepting connections void -llarp_tcp_acceptor_close(struct llarp_tcp_acceptor *); +llarp_tcp_acceptor_close(struct llarp_tcp_acceptor*); #ifdef _WIN32 #define IFNAMSIZ (16) @@ -201,7 +194,7 @@ struct llarp_fd_promise; /// wait until the fd promise is set int -llarp_fd_promise_wait_for_value(struct llarp_fd_promise *promise); +llarp_fd_promise_wait_for_value(struct llarp_fd_promise* promise); struct llarp_tun_io { @@ -212,32 +205,32 @@ struct llarp_tun_io int netmask; char ifname[IFNAMSIZ + 1]; - void *user; - void *impl; + void* user; + void* impl; /// functor for getting a promise that returns the vpn fd /// dont set me if you don't know how to use this - struct llarp_fd_promise *(*get_fd_promise)(struct llarp_tun_io *); + struct llarp_fd_promise* (*get_fd_promise)(struct llarp_tun_io*); - struct llarp_ev_loop *parent; + struct llarp_ev_loop* parent; /// called when we are able to write right before we write /// this happens after reading packets - void (*before_write)(struct llarp_tun_io *); + void (*before_write)(struct llarp_tun_io*); /// called every event loop tick after reads - void (*tick)(struct llarp_tun_io *); - void (*recvpkt)(struct llarp_tun_io *, const llarp_buffer_t &); + void (*tick)(struct llarp_tun_io*); + void (*recvpkt)(struct llarp_tun_io*, const llarp_buffer_t&); /// set by parent - bool (*writepkt)(struct llarp_tun_io *, const byte_t *, size_t); + bool (*writepkt)(struct llarp_tun_io*, const byte_t*, size_t); }; /// create tun interface with network interface name ifname /// returns true on success otherwise returns false bool -llarp_ev_add_tun(struct llarp_ev_loop *ev, struct llarp_tun_io *tun); +llarp_ev_add_tun(struct llarp_ev_loop* ev, struct llarp_tun_io* tun); /// async write a packet on tun interface /// returns true if queued, returns false on drop bool -llarp_ev_tun_async_write(struct llarp_tun_io *tun, const llarp_buffer_t &); +llarp_ev_tun_async_write(struct llarp_tun_io* tun, const llarp_buffer_t&); #endif diff --git a/llarp/ev/ev.hpp b/llarp/ev/ev.hpp index ad8874896..8e90bbee0 100644 --- a/llarp/ev/ev.hpp +++ b/llarp/ev/ev.hpp @@ -31,8 +31,7 @@ typedef struct sockaddr_un } SOCKADDR_UN, *PSOCKADDR_UN; #else -#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \ - || (__APPLE__ && __MACH__) +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || (__APPLE__ && __MACH__) #include #endif @@ -54,7 +53,7 @@ struct llarp_ev_pkt_pipe; /// do io and reset errno after static ssize_t -IO(std::function< ssize_t(void) > iofunc) +IO(std::function iofunc) { ssize_t ret = iofunc(); #ifndef _WIN32 @@ -80,7 +79,7 @@ namespace llarp WriteBuffer(const byte_t* ptr, size_t sz) { - if(sz <= sizeof(buf)) + if (sz <= sizeof(buf)) { bufsz = sz; memcpy(buf, ptr, bufsz); @@ -135,17 +134,15 @@ namespace llarp }; }; - using LosslessWriteQueue_t = std::deque< WriteBuffer >; + using LosslessWriteQueue_t = std::deque; - intptr_t - fd; // Sockets only, fuck UNIX-style reactive IO with a rusty knife + intptr_t fd; // Sockets only, fuck UNIX-style reactive IO with a rusty knife int flags = 0; win32_ev_io(intptr_t f) : fd(f){}; /// for tcp - win32_ev_io(intptr_t f, LosslessWriteQueue_t* q) - : fd(f), m_BlockingWriteQueue(q) + win32_ev_io(intptr_t f, LosslessWriteQueue_t* q) : fd(f), m_BlockingWriteQueue(q) { } @@ -154,8 +151,7 @@ namespace llarp { char ebuf[1024]; int err = WSAGetLastError(); - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL, - ebuf, 1024, nullptr); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL, ebuf, 1024, nullptr); llarp::LogError(ebuf); } @@ -188,7 +184,7 @@ namespace llarp bool queue_write(const byte_t* buf, size_t sz) { - if(m_BlockingWriteQueue) + if (m_BlockingWriteQueue) { m_BlockingWriteQueue->emplace_back(buf, sz); return true; @@ -209,18 +205,18 @@ namespace llarp virtual void flush_write_buffers(size_t amount) { - if(m_BlockingWriteQueue) + if (m_BlockingWriteQueue) { - if(amount) + if (amount) { - while(amount && m_BlockingWriteQueue->size()) + while (amount && m_BlockingWriteQueue->size()) { - auto& itr = m_BlockingWriteQueue->front(); + auto& itr = m_BlockingWriteQueue->front(); ssize_t result = do_write(itr.buf, std::min(amount, itr.bufsz)); - if(result == -1) + if (result == -1) return; ssize_t dlt = itr.bufsz - result; - if(dlt > 0) + if (dlt > 0) { // queue remaining to front of queue WriteBuffer buff(itr.buf + dlt, itr.bufsz - dlt); @@ -236,14 +232,14 @@ namespace llarp else { // write buffers - while(m_BlockingWriteQueue->size()) + while (m_BlockingWriteQueue->size()) { - auto& itr = m_BlockingWriteQueue->front(); + auto& itr = m_BlockingWriteQueue->front(); ssize_t result = do_write(itr.buf, itr.bufsz); - if(result == -1) + if (result == -1) return; ssize_t dlt = itr.bufsz - result; - if(dlt > 0) + if (dlt > 0) { // queue remaining to front of queue WriteBuffer buff(itr.buf + dlt, itr.bufsz - dlt); @@ -254,7 +250,7 @@ namespace llarp } m_BlockingWriteQueue->pop_front(); int wsaerr = WSAGetLastError(); - if(wsaerr == WSA_IO_PENDING || wsaerr == WSAEWOULDBLOCK) + if (wsaerr == WSA_IO_PENDING || wsaerr == WSAEWOULDBLOCK) { WSASetLastError(0); return; @@ -266,7 +262,7 @@ namespace llarp WSASetLastError(0); } - std::unique_ptr< LosslessWriteQueue_t > m_BlockingWriteQueue; + std::unique_ptr m_BlockingWriteQueue; virtual ~win32_ev_io() { @@ -286,7 +282,7 @@ namespace llarp WriteBuffer(const byte_t* ptr, size_t sz) { - if(sz <= sizeof(buf)) + if (sz <= sizeof(buf)) { bufsz = sz; memcpy(buf, ptr, bufsz); @@ -341,18 +337,20 @@ namespace llarp }; }; - using LossyWriteQueue_t = - llarp::util::CoDelQueue< WriteBuffer, WriteBuffer::GetTime, - WriteBuffer::PutTime, WriteBuffer::Compare, - WriteBuffer::GetNow, llarp::util::NullMutex, - llarp::util::NullLock >; + using LossyWriteQueue_t = llarp::util::CoDelQueue< + WriteBuffer, + WriteBuffer::GetTime, + WriteBuffer::PutTime, + WriteBuffer::Compare, + WriteBuffer::GetNow, + llarp::util::NullMutex, + llarp::util::NullLock>; - using LosslessWriteQueue_t = std::deque< WriteBuffer >; + using LosslessWriteQueue_t = std::deque; int fd; int flags = 0; -#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \ - || (__APPLE__ && __MACH__) +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || (__APPLE__ && __MACH__) struct kevent change; #endif @@ -380,9 +378,10 @@ namespace llarp read(byte_t* buf, size_t sz) = 0; virtual int - sendto(__attribute__((unused)) const sockaddr* dst, - __attribute__((unused)) const void* data, - __attribute__((unused)) size_t sz) + sendto( + __attribute__((unused)) const sockaddr* dst, + __attribute__((unused)) const void* data, + __attribute__((unused)) size_t sz) { return -1; } @@ -404,12 +403,12 @@ namespace llarp bool queue_write(const byte_t* buf, size_t sz) { - if(m_LossyWriteQueue) + if (m_LossyWriteQueue) { m_LossyWriteQueue->Emplace(buf, sz); return true; } - if(m_BlockingWriteQueue) + if (m_BlockingWriteQueue) { m_BlockingWriteQueue->emplace_back(buf, sz); return true; @@ -436,7 +435,7 @@ namespace llarp flush_write_buffers(size_t amount) { before_flush_write(); - if(m_LossyWriteQueue) + if (m_LossyWriteQueue) { m_LossyWriteQueue->Process([&](WriteBuffer& buffer) { do_write(buffer.buf, buffer.bufsz); @@ -444,18 +443,18 @@ namespace llarp // discard entry }); } - else if(m_BlockingWriteQueue) + else if (m_BlockingWriteQueue) { - if(amount) + if (amount) { - while(amount && m_BlockingWriteQueue->size()) + while (amount && m_BlockingWriteQueue->size()) { - auto& itr = m_BlockingWriteQueue->front(); + auto& itr = m_BlockingWriteQueue->front(); ssize_t result = do_write(itr.buf, std::min(amount, itr.bufsz)); - if(result <= 0) + if (result <= 0) return; ssize_t dlt = itr.bufsz - result; - if(dlt > 0) + if (dlt > 0) { // queue remaining to front of queue WriteBuffer buff(itr.buf + dlt, itr.bufsz - dlt); @@ -471,17 +470,17 @@ namespace llarp else { // write buffers - while(m_BlockingWriteQueue->size()) + while (m_BlockingWriteQueue->size()) { - auto& itr = m_BlockingWriteQueue->front(); + auto& itr = m_BlockingWriteQueue->front(); ssize_t result = do_write(itr.buf, itr.bufsz); - if(result <= 0) + if (result <= 0) { errno = 0; return; } ssize_t dlt = itr.bufsz - result; - if(dlt > 0) + if (dlt > 0) { // queue remaining to front of queue WriteBuffer buff(itr.buf + dlt, itr.bufsz - dlt); @@ -491,7 +490,7 @@ namespace llarp return; } m_BlockingWriteQueue->pop_front(); - if(errno == EAGAIN || errno == EWOULDBLOCK) + if (errno == EAGAIN || errno == EWOULDBLOCK) { errno = 0; return; @@ -503,8 +502,8 @@ namespace llarp errno = 0; } - std::unique_ptr< LossyWriteQueue_t > m_LossyWriteQueue; - std::unique_ptr< LosslessWriteQueue_t > m_BlockingWriteQueue; + std::unique_ptr m_LossyWriteQueue; + std::unique_ptr m_BlockingWriteQueue; virtual ~posix_ev_io() { @@ -527,7 +526,7 @@ namespace llarp struct tcp_conn : public ev_io { sockaddr_storage _addr; - bool _shouldClose = false; + bool _shouldClose = false; bool _calledConnected = false; llarp_tcp_conn tcp; // null if inbound otherwise outbound @@ -536,40 +535,38 @@ namespace llarp static void DoClose(llarp_tcp_conn* conn) { - static_cast< tcp_conn* >(conn->impl)->_shouldClose = true; + static_cast(conn->impl)->_shouldClose = true; } /// inbound - tcp_conn(llarp_ev_loop* loop, int _fd) - : ev_io(_fd, new LosslessWriteQueue_t{}), _conn(nullptr) + tcp_conn(llarp_ev_loop* loop, int _fd) : ev_io(_fd, new LosslessWriteQueue_t{}), _conn(nullptr) { - tcp.impl = this; - tcp.loop = loop; + tcp.impl = this; + tcp.loop = loop; tcp.closed = nullptr; - tcp.user = nullptr; - tcp.read = nullptr; - tcp.tick = nullptr; - tcp.close = &DoClose; + tcp.user = nullptr; + tcp.read = nullptr; + tcp.tick = nullptr; + tcp.close = &DoClose; } /// outbound - tcp_conn(llarp_ev_loop* loop, int _fd, const sockaddr* addr, - llarp_tcp_connecter* conn) + tcp_conn(llarp_ev_loop* loop, int _fd, const sockaddr* addr, llarp_tcp_connecter* conn) : ev_io(_fd, new LosslessWriteQueue_t{}), _conn(conn) { socklen_t slen = sizeof(sockaddr_in); - if(addr->sa_family == AF_INET6) + if (addr->sa_family == AF_INET6) slen = sizeof(sockaddr_in6); - else if(addr->sa_family == AF_UNIX) + else if (addr->sa_family == AF_UNIX) slen = sizeof(sockaddr_un); memcpy(&_addr, addr, slen); - tcp.impl = this; - tcp.loop = loop; + tcp.impl = this; + tcp.loop = loop; tcp.closed = nullptr; - tcp.user = nullptr; - tcp.read = nullptr; - tcp.tick = nullptr; - tcp.close = &DoClose; + tcp.user = nullptr; + tcp.read = nullptr; + tcp.tick = nullptr; + tcp.close = &DoClose; } ~tcp_conn() override = default; @@ -584,12 +581,12 @@ namespace llarp { sockaddr_storage st; socklen_t sl; - if(getpeername(fd, (sockaddr*)&st, &sl) == 0) + if (getpeername(fd, (sockaddr*)&st, &sl) == 0) { // we are connected yeh boi - if(_conn) + if (_conn) { - if(_conn->connected && !_calledConnected) + if (_conn->connected && !_calledConnected) _conn->connected(_conn, &tcp); } _calledConnected = true; @@ -614,18 +611,17 @@ namespace llarp error() override { _shouldClose = true; - if(_conn) + if (_conn) { #ifndef _WIN32 llarp::LogError("tcp_conn error: ", strerror(errno)); #else char ebuf[1024]; int err = WSAGetLastError(); - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL, - ebuf, 1024, nullptr); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL, ebuf, 1024, nullptr); llarp::LogError("tcp_conn error: ", ebuf); #endif - if(_conn->error) + if (_conn->error) _conn->error(_conn); } errno = 0; @@ -645,8 +641,7 @@ namespace llarp { llarp_ev_loop* loop; llarp_tcp_acceptor* tcp; - tcp_serv(llarp_ev_loop* l, int _fd, llarp_tcp_acceptor* t) - : ev_io(_fd), loop(l), tcp(t) + tcp_serv(llarp_ev_loop* l, int _fd, llarp_tcp_acceptor* t) : ev_io(_fd), loop(l), tcp(t) { tcp->impl = this; } @@ -654,7 +649,7 @@ namespace llarp bool tick() override { - if(tcp->tick) + if (tcp->tick) tcp->tick(tcp); return true; } @@ -669,8 +664,7 @@ namespace llarp #ifdef _WIN32 struct llarp_fd_promise { - void - Set(std::pair< int, int >) + void Set(std::pair) { } @@ -683,11 +677,11 @@ struct llarp_fd_promise #else struct llarp_fd_promise { - using promise_val_t = std::pair< int, int >; - llarp_fd_promise(std::promise< promise_val_t >* p) : _impl(p) + using promise_val_t = std::pair; + llarp_fd_promise(std::promise* p) : _impl(p) { } - std::promise< promise_val_t >* _impl; + std::promise* _impl; void Set(promise_val_t fds) @@ -742,14 +736,13 @@ struct llarp_ev_loop tick(int ms) = 0; virtual uint32_t - call_after_delay(llarp_time_t delay_ms, - std::function< void(void) > callback) = 0; + call_after_delay(llarp_time_t delay_ms, std::function callback) = 0; virtual void cancel_delayed_call(uint32_t call_id) = 0; virtual bool - add_ticker(std::function< void(void) > ticker) = 0; + add_ticker(std::function ticker) = 0; virtual void stop() = 0; @@ -766,9 +759,9 @@ struct llarp_ev_loop virtual bool tun_listen(llarp_tun_io* tun) { - auto dev = create_tun(tun); + auto dev = create_tun(tun); tun->impl = dev; - if(dev) + if (dev) { return add_ev(dev, false); } @@ -788,7 +781,7 @@ struct llarp_ev_loop } /// give this event loop a logic thread for calling - virtual void set_logic(std::shared_ptr< llarp::Logic >) = 0; + virtual void set_logic(std::shared_ptr) = 0; /// register event listener virtual bool @@ -803,15 +796,15 @@ struct llarp_ev_loop virtual ~llarp_ev_loop() = default; - std::list< std::unique_ptr< llarp::ev_io > > handlers; + std::list> handlers; virtual void tick_listeners() { auto itr = handlers.begin(); - while(itr != handlers.end()) + while (itr != handlers.end()) { - if((*itr)->tick()) + if ((*itr)->tick()) ++itr; else { @@ -822,17 +815,17 @@ struct llarp_ev_loop } virtual void - call_soon(std::function< void(void) > f) = 0; + call_soon(std::function f) = 0; }; struct PacketBuffer { PacketBuffer(PacketBuffer&& other) { - _ptr = other._ptr; - _sz = other._sz; + _ptr = other._ptr; + _sz = other._sz; other._ptr = nullptr; - other._sz = 0; + other._sz = 0; } PacketBuffer(const PacketBuffer&) = delete; @@ -848,11 +841,11 @@ struct PacketBuffer PacketBuffer(char* buf, size_t sz) { _ptr = buf; - _sz = sz; + _sz = sz; } ~PacketBuffer() { - if(_ptr) + if (_ptr) delete[] _ptr; } byte_t* @@ -872,10 +865,10 @@ struct PacketBuffer void reserve(size_t sz) { - if(_ptr) + if (_ptr) delete[] _ptr; _ptr = new char[sz]; - _sz = sz; + _sz = sz; } private: @@ -889,7 +882,7 @@ struct PacketEvent PacketBuffer pkt; }; -struct llarp_pkt_list : public std::vector< PacketEvent > +struct llarp_pkt_list : public std::vector { }; diff --git a/llarp/ev/ev_libuv.cpp b/llarp/ev/ev_libuv.cpp index aaa13dc69..990437605 100644 --- a/llarp/ev/ev_libuv.cpp +++ b/llarp/ev/ev_libuv.cpp @@ -7,8 +7,7 @@ namespace libuv { -#define LoopCall(h, ...) \ - LogicCall(static_cast< Loop* >((h)->loop->data)->m_Logic, __VA_ARGS__) +#define LoopCall(h, ...) LogicCall(static_cast((h)->loop->data)->m_Logic, __VA_ARGS__) struct glue { @@ -20,7 +19,7 @@ namespace libuv /// tcp connection glue between llarp and libuv struct conn_glue : public glue { - using WriteBuffer_t = std::vector< char >; + using WriteBuffer_t = std::vector; struct WriteEvent { @@ -61,8 +60,8 @@ namespace libuv : m_TCP(tcp), m_Accept(nullptr), m_Addr(*addr) { m_Connect.data = this; - m_Handle.data = this; - m_TCP->impl = this; + m_Handle.data = this; + m_TCP->impl = this; uv_tcp_init(loop, &m_Handle); m_Ticker.data = this; uv_check_init(loop, &m_Ticker); @@ -74,22 +73,22 @@ namespace libuv : m_TCP(nullptr), m_Accept(tcp), m_Addr(*addr) { m_Connect.data = nullptr; - m_Handle.data = this; + m_Handle.data = this; uv_tcp_init(loop, &m_Handle); m_Ticker.data = this; uv_check_init(loop, &m_Ticker); m_Accept->close = &ExplicitCloseAccept; - m_Conn.write = nullptr; - m_Conn.closed = nullptr; - m_Conn.tick = nullptr; + m_Conn.write = nullptr; + m_Conn.closed = nullptr; + m_Conn.tick = nullptr; } conn_glue(conn_glue* parent) : m_TCP(nullptr), m_Accept(nullptr) { m_Connect.data = nullptr; - m_Conn.close = &ExplicitClose; - m_Conn.write = &ExplicitWrite; - m_Handle.data = this; + m_Conn.close = &ExplicitClose; + m_Conn.write = &ExplicitWrite; + m_Handle.data = this; uv_tcp_init(parent->m_Handle.loop, &m_Handle); m_Ticker.data = this; uv_check_init(parent->m_Handle.loop, &m_Ticker); @@ -98,7 +97,7 @@ namespace libuv static void OnOutboundConnect(uv_connect_t* c, int status) { - conn_glue* self = static_cast< conn_glue* >(c->data); + conn_glue* self = static_cast(c->data); self->HandleConnectResult(status); c->data = nullptr; } @@ -106,38 +105,37 @@ namespace libuv bool ConnectAsync() { - return uv_tcp_connect(&m_Connect, &m_Handle, m_Addr, &OnOutboundConnect) - != -1; + return uv_tcp_connect(&m_Connect, &m_Handle, m_Addr, &OnOutboundConnect) != -1; } static void ExplicitClose(llarp_tcp_conn* conn) { - static_cast< conn_glue* >(conn->impl)->Close(); + static_cast(conn->impl)->Close(); } static void ExplicitCloseAccept(llarp_tcp_acceptor* tcp) { - static_cast< conn_glue* >(tcp->impl)->Close(); + static_cast(tcp->impl)->Close(); } static ssize_t ExplicitWrite(llarp_tcp_conn* conn, const byte_t* ptr, size_t sz) { - return static_cast< conn_glue* >(conn->impl)->WriteAsync((char*)ptr, sz); + return static_cast(conn->impl)->WriteAsync((char*)ptr, sz); } static void OnRead(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { - if(nread >= 0) + if (nread >= 0) { - auto* conn = static_cast< conn_glue* >(stream->data); + auto* conn = static_cast(stream->data); conn->Read(buf->base, nread); } - else if(nread < 0) + else if (nread < 0) { - static_cast< conn_glue* >(stream->data)->Close(); + static_cast(stream->data)->Close(); } delete[] buf->base; } @@ -146,13 +144,13 @@ namespace libuv Alloc(uv_handle_t*, size_t suggested_size, uv_buf_t* buf) { buf->base = new char[suggested_size]; - buf->len = suggested_size; + buf->len = suggested_size; } void Read(const char* ptr, ssize_t sz) { - if(m_Conn.read) + if (m_Conn.read) { llarp::LogDebug("tcp read ", sz, " bytes"); const llarp_buffer_t buf(ptr, sz); @@ -163,18 +161,18 @@ namespace libuv void HandleConnectResult(int status) { - if(m_TCP && m_TCP->connected) + if (m_TCP && m_TCP->connected) { - if(status == 0) + if (status == 0) { - m_Conn.impl = this; - m_Conn.loop = m_TCP->loop; + m_Conn.impl = this; + m_Conn.loop = m_TCP->loop; m_Conn.close = &ExplicitClose; m_Conn.write = &ExplicitWrite; m_TCP->connected(m_TCP, &m_Conn); Start(); } - else if(m_TCP->error) + else if (m_TCP->error) { llarp::LogError("failed to connect tcp ", uv_strerror(status)); m_TCP->error(m_TCP); @@ -185,7 +183,7 @@ namespace libuv void WriteFail() { - if(m_Conn.close) + if (m_Conn.close) m_Conn.close(&m_Conn); } @@ -198,8 +196,8 @@ namespace libuv static void OnWritten(uv_write_t* req, int status) { - WriteEvent* ev = static_cast< WriteEvent* >(req->data); - if(status == 0) + WriteEvent* ev = static_cast(req->data); + if (status == 0) { llarp::LogDebug("wrote ", ev->data.size()); } @@ -213,11 +211,11 @@ namespace libuv int WriteAsync(char* data, size_t sz) { - if(uv_is_closing((const uv_handle_t*)&m_Handle)) + if (uv_is_closing((const uv_handle_t*)&m_Handle)) return -1; WriteEvent* ev = new WriteEvent(sz, data); - auto buf = ev->Buffer(); - if(uv_write(ev->Request(), Stream(), &buf, 1, &OnWritten) == 0) + auto buf = ev->Buffer(); + if (uv_write(ev->Request(), Stream(), &buf, 1, &OnWritten) == 0) return sz; delete ev; return -1; @@ -226,15 +224,15 @@ namespace libuv static void OnClosed(uv_handle_t* h) { - conn_glue* conn = static_cast< conn_glue* >(h->data); + conn_glue* conn = static_cast(h->data); conn->HandleClosed(); } static void FullClose(uv_handle_t* h) { - auto* self = static_cast< conn_glue* >(h->data); - h->data = nullptr; + auto* self = static_cast(h->data); + h->data = nullptr; delete self; llarp::LogDebug("deleted"); } @@ -243,13 +241,13 @@ namespace libuv HandleClosed() { m_Handle.data = nullptr; - if(m_Accept) + if (m_Accept) { - if(m_Accept->closed) + if (m_Accept->closed) m_Accept->closed(m_Accept); m_Accept->impl = nullptr; } - if(m_Conn.closed) + if (m_Conn.closed) { m_Conn.closed(&m_Conn); } @@ -262,7 +260,7 @@ namespace libuv OnShutdown(uv_shutdown_t* shut, int code) { llarp::LogDebug("shut down ", code); - auto* self = static_cast< conn_glue* >(shut->data); + auto* self = static_cast(shut->data); uv_close((uv_handle_t*)&self->m_Handle, &OnClosed); delete shut; } @@ -270,7 +268,7 @@ namespace libuv void Close() override { - if(uv_is_closing((uv_handle_t*)Stream())) + if (uv_is_closing((uv_handle_t*)Stream())) return; llarp::LogDebug("close tcp connection"); uv_check_stop(&m_Ticker); @@ -283,9 +281,9 @@ namespace libuv static void OnAccept(uv_stream_t* stream, int status) { - if(status == 0) + if (status == 0) { - conn_glue* conn = static_cast< conn_glue* >(stream->data); + conn_glue* conn = static_cast(stream->data); conn->Accept(); } else @@ -297,18 +295,18 @@ namespace libuv static void OnTick(uv_check_t* t) { - conn_glue* conn = static_cast< conn_glue* >(t->data); + conn_glue* conn = static_cast(t->data); conn->Tick(); } void Tick() { - if(m_Accept && m_Accept->tick) + if (m_Accept && m_Accept->tick) { m_Accept->tick(m_Accept); } - if(m_Conn.tick) + if (m_Conn.tick) { m_Conn.tick(&m_Conn); } @@ -318,26 +316,26 @@ namespace libuv Start() { auto result = uv_check_start(&m_Ticker, &OnTick); - if(result) + if (result) llarp::LogError("failed to start timer ", uv_strerror(result)); result = uv_read_start(Stream(), &Alloc, &OnRead); - if(result) + if (result) llarp::LogError("failed to start reader ", uv_strerror(result)); } void Accept() { - if(m_Accept && m_Accept->accepted) + if (m_Accept && m_Accept->accepted) { auto* child = new conn_glue(this); llarp::LogDebug("accepted new connection"); - child->m_Conn.impl = child; - child->m_Conn.loop = m_Accept->loop; + child->m_Conn.impl = child; + child->m_Conn.loop = m_Accept->loop; child->m_Conn.close = &ExplicitClose; child->m_Conn.write = &ExplicitWrite; - auto res = uv_accept(Stream(), child->Stream()); - if(res) + auto res = uv_accept(Stream(), child->Stream()); + if (res) { llarp::LogError("failed to accept tcp connection ", uv_strerror(res)); child->Close(); @@ -353,16 +351,15 @@ namespace libuv { uv_check_start(&m_Ticker, &OnTick); m_Accept->close = &ExplicitCloseAccept; - return uv_tcp_bind(&m_Handle, m_Addr, 0) == 0 - && uv_listen(Stream(), 5, &OnAccept) == 0; + return uv_tcp_bind(&m_Handle, m_Addr, 0) == 0 && uv_listen(Stream(), 5, &OnAccept) == 0; } }; struct ticker_glue : public glue { - std::function< void(void) > func; + std::function func; - ticker_glue(uv_loop_t* loop, std::function< void(void) > tick) : func(tick) + ticker_glue(uv_loop_t* loop, std::function tick) : func(tick) { m_Ticker.data = this; uv_check_init(loop, &m_Ticker); @@ -371,7 +368,7 @@ namespace libuv static void OnTick(uv_check_t* t) { - ticker_glue* ticker = static_cast< ticker_glue* >(t->data); + ticker_glue* ticker = static_cast(t->data); LoopCall(t, ticker->func); } @@ -387,7 +384,7 @@ namespace libuv uv_check_stop(&m_Ticker); uv_close((uv_handle_t*)&m_Ticker, [](auto h) { ticker_glue* self = (ticker_glue*)h->data; - h->data = nullptr; + h->data = nullptr; delete self; }); } @@ -402,10 +399,9 @@ namespace libuv llarp_udp_io* const m_UDP; llarp::Addr m_Addr; llarp_pkt_list m_LastPackets; - std::array< char, 1500 > m_Buffer; + std::array m_Buffer; - udp_glue(uv_loop_t* loop, llarp_udp_io* udp, const sockaddr* src) - : m_UDP(udp), m_Addr(*src) + udp_glue(uv_loop_t* loop, llarp_udp_io* udp, const sockaddr* src) : m_UDP(udp), m_Addr(*src) { m_Handle.data = this; m_Ticker.data = this; @@ -417,26 +413,25 @@ namespace libuv Alloc(uv_handle_t*, size_t suggested_size, uv_buf_t* buf) { const size_t sz = std::min(suggested_size, size_t{1500}); - buf->base = new char[sz]; - buf->len = sz; + buf->base = new char[sz]; + buf->len = sz; } static void - OnRecv(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, - const struct sockaddr* addr, unsigned) + OnRecv( + uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned) { - udp_glue* glue = static_cast< udp_glue* >(handle->data); - if(addr) + udp_glue* glue = static_cast(handle->data); + if (addr) glue->RecvFrom(nread, buf, addr); - if(nread <= 0 || glue->m_UDP == nullptr - || glue->m_UDP->recvfrom != nullptr) + if (nread <= 0 || glue->m_UDP == nullptr || glue->m_UDP->recvfrom != nullptr) delete[] buf->base; } bool RecvMany(llarp_pkt_list* pkts) { - *pkts = std::move(m_LastPackets); + *pkts = std::move(m_LastPackets); m_LastPackets = llarp_pkt_list(); return pkts->size() > 0; } @@ -444,10 +439,10 @@ namespace libuv void RecvFrom(ssize_t sz, const uv_buf_t* buf, const struct sockaddr* fromaddr) { - if(sz > 0 && m_UDP) + if (sz > 0 && m_UDP) { const size_t pktsz = sz; - if(m_UDP->recvfrom) + if (m_UDP->recvfrom) { const llarp_buffer_t pkt((const byte_t*)buf->base, pktsz); m_UDP->recvfrom(m_UDP, fromaddr, ManagedBuffer{pkt}); @@ -463,22 +458,22 @@ namespace libuv static void OnTick(uv_check_t* t) { - udp_glue* udp = static_cast< udp_glue* >(t->data); + udp_glue* udp = static_cast(t->data); udp->Tick(); } void Tick() { - if(m_UDP && m_UDP->tick) + if (m_UDP && m_UDP->tick) m_UDP->tick(m_UDP); } static int SendTo(llarp_udp_io* udp, const sockaddr* to, const byte_t* ptr, size_t sz) { - auto* self = static_cast< udp_glue* >(udp->impl); - if(self == nullptr) + auto* self = static_cast(udp->impl); + if (self == nullptr) return -1; uv_buf_t buf = uv_buf_init((char*)ptr, sz); return uv_udp_try_send(&self->m_Handle, &buf, 1, to); @@ -488,36 +483,36 @@ namespace libuv Bind() { auto ret = uv_udp_bind(&m_Handle, m_Addr, 0); - if(ret) + if (ret) { llarp::LogError("failed to bind to ", m_Addr, " ", uv_strerror(ret)); return false; } - if(uv_udp_recv_start(&m_Handle, &Alloc, &OnRecv)) + if (uv_udp_recv_start(&m_Handle, &Alloc, &OnRecv)) { llarp::LogError("failed to start recving packets via ", m_Addr); return false; } - if(uv_check_start(&m_Ticker, &OnTick)) + if (uv_check_start(&m_Ticker, &OnTick)) { llarp::LogError("failed to start ticker"); return false; } #if defined(_WIN32) || defined(_WIN64) #else - if(uv_fileno((const uv_handle_t*)&m_Handle, &m_UDP->fd)) + if (uv_fileno((const uv_handle_t*)&m_Handle, &m_UDP->fd)) return false; #endif m_UDP->sendto = &SendTo; - m_UDP->impl = this; + m_UDP->impl = this; return true; } static void OnClosed(uv_handle_t* h) { - auto* glue = static_cast< udp_glue* >(h->data); - if(glue) + auto* glue = static_cast(h->data); + if (glue) { h->data = nullptr; delete glue; @@ -554,23 +549,23 @@ namespace libuv static void OnRead(uv_poll_t* handle, int status, int) { - if(status) + if (status) { return; } - pipe_glue* glue = static_cast< pipe_glue* >(handle->data); + pipe_glue* glue = static_cast(handle->data); int r = glue->m_Pipe->read(glue->m_Buffer, sizeof(glue->m_Buffer)); - if(r <= 0) + if (r <= 0) return; - const llarp_buffer_t buf{glue->m_Buffer, static_cast< size_t >(r)}; + const llarp_buffer_t buf{glue->m_Buffer, static_cast(r)}; glue->m_Pipe->OnRead(buf); } static void OnClosed(uv_handle_t* h) { - auto* self = static_cast< pipe_glue* >(h->data); - if(self) + auto* self = static_cast(h->data); + if (self) { h->data = nullptr; delete self; @@ -587,16 +582,16 @@ namespace libuv static void OnTick(uv_check_t* h) { - pipe_glue* pipe = static_cast< pipe_glue* >(h->data); + pipe_glue* pipe = static_cast(h->data); LoopCall(h, std::bind(&pipe_glue::Tick, pipe)); } bool Start() { - if(uv_poll_start(&m_Handle, UV_READABLE, &OnRead)) + if (uv_poll_start(&m_Handle, UV_READABLE, &OnRead)) return false; - if(uv_check_start(&m_Ticker, &OnTick)) + if (uv_check_start(&m_Ticker, &OnTick)) return false; return true; } @@ -630,16 +625,16 @@ namespace libuv static void OnTick(uv_check_t* timer) { - tun_glue* tun = static_cast< tun_glue* >(timer->data); + tun_glue* tun = static_cast(timer->data); tun->Tick(); } static void OnPoll(uv_poll_t* h, int, int events) { - if(events & UV_READABLE) + if (events & UV_READABLE) { - static_cast< tun_glue* >(h->data)->Read(); + static_cast(h->data)->Read(); } } @@ -647,11 +642,11 @@ namespace libuv Read() { auto sz = tuntap_read(m_Device, m_Buffer, sizeof(m_Buffer)); - if(sz > 0) + if (sz > 0) { llarp::LogDebug("tun read ", sz); const llarp_buffer_t pkt(m_Buffer, sz); - if(m_Tun && m_Tun->recvpkt) + if (m_Tun && m_Tun->recvpkt) m_Tun->recvpkt(m_Tun, pkt); } } @@ -659,17 +654,17 @@ namespace libuv void Tick() { - if(m_Tun->before_write) + if (m_Tun->before_write) m_Tun->before_write(m_Tun); - if(m_Tun->tick) + if (m_Tun->tick) m_Tun->tick(m_Tun); } static void OnClosed(uv_handle_t* h) { - auto* self = static_cast< tun_glue* >(h->data); - if(self) + auto* self = static_cast(h->data); + if (self) { h->data = nullptr; delete self; @@ -679,12 +674,12 @@ namespace libuv void Close() override { - if(m_Tun->impl == nullptr) + if (m_Tun->impl == nullptr) return; m_Tun->impl = nullptr; uv_check_stop(&m_Ticker); uv_close((uv_handle_t*)&m_Ticker, [](uv_handle_t* h) { - tun_glue* glue = static_cast< tun_glue* >(h->data); + tun_glue* glue = static_cast(h->data); uv_close((uv_handle_t*)&glue->m_Handle, &OnClosed); }); } @@ -698,7 +693,7 @@ namespace libuv static bool WritePkt(llarp_tun_io* tun, const byte_t* pkt, size_t sz) { - tun_glue* glue = static_cast< tun_glue* >(tun->impl); + tun_glue* glue = static_cast(tun->impl); return glue && glue->Write(pkt, sz); } @@ -706,46 +701,42 @@ namespace libuv Init(uv_loop_t* loop) { memcpy(m_Device->if_name, m_Tun->ifname, sizeof(m_Device->if_name)); - if(tuntap_start(m_Device, TUNTAP_MODE_TUNNEL, 0) == -1) + if (tuntap_start(m_Device, TUNTAP_MODE_TUNNEL, 0) == -1) { llarp::LogError("failed to start up ", m_Tun->ifname); return false; } - if(tuntap_set_ip(m_Device, m_Tun->ifaddr, m_Tun->ifaddr, m_Tun->netmask) - == -1) + if (tuntap_set_ip(m_Device, m_Tun->ifaddr, m_Tun->ifaddr, m_Tun->netmask) == -1) { llarp::LogError("failed to set address on ", m_Tun->ifname); return false; } - if(tuntap_up(m_Device) == -1) + if (tuntap_up(m_Device) == -1) { llarp::LogError("failed to put up ", m_Tun->ifname); return false; } - if(m_Device->tun_fd == -1) + if (m_Device->tun_fd == -1) { - llarp::LogError("tun interface ", m_Tun->ifname, - " has invalid fd: ", m_Device->tun_fd); + llarp::LogError("tun interface ", m_Tun->ifname, " has invalid fd: ", m_Device->tun_fd); return false; } tuntap_set_nonblocking(m_Device, 1); - if(uv_poll_init(loop, &m_Handle, m_Device->tun_fd) == -1) + if (uv_poll_init(loop, &m_Handle, m_Device->tun_fd) == -1) { llarp::LogError("failed to start polling on ", m_Tun->ifname); return false; } - if(uv_poll_start(&m_Handle, UV_READABLE, &OnPoll)) + if (uv_poll_start(&m_Handle, UV_READABLE, &OnPoll)) { llarp::LogError("failed to start polling on ", m_Tun->ifname); return false; } - if(uv_check_init(loop, &m_Ticker) != 0 - || uv_check_start(&m_Ticker, &OnTick) != 0) + if (uv_check_init(loop, &m_Ticker) != 0 || uv_check_start(&m_Ticker, &OnTick) != 0) { - llarp::LogError("failed to set up tun interface timer for ", - m_Tun->ifname); + llarp::LogError("failed to set up tun interface timer for ", m_Tun->ifname); return false; } m_Tun->writepkt = &WritePkt; @@ -758,27 +749,23 @@ namespace libuv static void OnAsyncWake(uv_async_t* async_handle) { - Loop* loop = static_cast< Loop* >(async_handle->data); + Loop* loop = static_cast(async_handle->data); loop->process_timer_queue(); loop->process_cancel_queue(); } - Loop::Loop() - : llarp_ev_loop() - , m_LogicCalls(1024) - , m_timerQueue(20) - , m_timerCancelQueue(20) + Loop::Loop() : llarp_ev_loop(), m_LogicCalls(1024), m_timerQueue(20), m_timerCancelQueue(20) { } bool Loop::init() { - if(uv_loop_init(&m_Impl) == -1) + if (uv_loop_init(&m_Impl) == -1) return false; #ifdef LOKINET_DEBUG - last_time = 0; + last_time = 0; loop_run_count = 0; #endif @@ -789,22 +776,24 @@ namespace libuv #endif m_LogicCaller.data = this; int err; - if((err = uv_async_init(&m_Impl, &m_LogicCaller, - [](uv_async_t* h) { - Loop* l = static_cast< Loop* >(h->data); - while(not l->m_LogicCalls.empty()) - { - auto f = l->m_LogicCalls.popFront(); - f(); - } - })) - != 0) + if ((err = uv_async_init( + &m_Impl, + &m_LogicCaller, + [](uv_async_t* h) { + Loop* l = static_cast(h->data); + while (not l->m_LogicCalls.empty()) + { + auto f = l->m_LogicCalls.popFront(); + f(); + } + })) + != 0) { llarp::LogError("Libuv uv_async_init returned error: ", uv_strerror(err)); return false; } - m_TickTimer = new uv_timer_t; + m_TickTimer = new uv_timer_t; m_TickTimer->data = this; m_Run.store(true); m_nextID.store(0); @@ -831,8 +820,8 @@ namespace libuv Loop::tcp_connect(llarp_tcp_connecter* tcp, const sockaddr* addr) { auto* impl = new conn_glue(&m_Impl, tcp, addr); - tcp->impl = impl; - if(impl->ConnectAsync()) + tcp->impl = impl; + if (impl->ConnectAsync()) return true; delete impl; tcp->impl = nullptr; @@ -848,7 +837,7 @@ namespace libuv int Loop::tick(int ms) { - if(m_Run) + if (m_Run) { #ifdef TESTNET_SPEED ms *= TESTNET_SPEED; @@ -870,15 +859,14 @@ namespace libuv { // have to delete timer handle this way because libuv. uv_timer_stop(timer); - uv_close((uv_handle_t*)timer, - [](uv_handle_t* handle) { delete(uv_timer_t*)handle; }); + uv_close((uv_handle_t*)timer, [](uv_handle_t* handle) { delete (uv_timer_t*)handle; }); } static void OnUVTimer(uv_timer_t* timer) { - TimerData* timer_data = static_cast< TimerData* >(timer->data); - Loop* loop = timer_data->loop; + TimerData* timer_data = static_cast(timer->data); + Loop* loop = timer_data->loop; loop->do_timer_job(timer_data->job_id); delete timer_data; @@ -886,16 +874,15 @@ namespace libuv } uint32_t - Loop::call_after_delay(llarp_time_t delay_ms, - std::function< void(void) > callback) + Loop::call_after_delay(llarp_time_t delay_ms, std::function callback) { #ifdef TESTNET_SPEED delay_ms *= TESTNET_SPEED; #endif PendingTimer timer; - timer.delay_ms = delay_ms; - timer.callback = callback; - timer.job_id = m_nextID++; + timer.delay_ms = delay_ms; + timer.callback = callback; + timer.job_id = m_nextID++; uint64_t job_id = timer.job_id; m_timerQueue.pushBack(std::move(timer)); @@ -914,18 +901,18 @@ namespace libuv void Loop::process_timer_queue() { - while(not m_timerQueue.empty()) + while (not m_timerQueue.empty()) { PendingTimer job = m_timerQueue.popFront(); - uint64_t job_id = job.job_id; + uint64_t job_id = job.job_id; m_pendingCalls.emplace(job_id, std::move(job.callback)); TimerData* timer_data = new TimerData; - timer_data->loop = this; - timer_data->job_id = job_id; + timer_data->loop = this; + timer_data->job_id = job_id; uv_timer_t* newTimer = new uv_timer_t; - newTimer->data = (void*)timer_data; + newTimer->data = (void*)timer_data; uv_timer_init(&m_Impl, newTimer); uv_timer_start(newTimer, &OnUVTimer, job.delay_ms.count(), 0); @@ -935,11 +922,11 @@ namespace libuv void Loop::process_cancel_queue() { - while(not m_timerCancelQueue.empty()) + while (not m_timerCancelQueue.empty()) { uint64_t job_id = m_timerCancelQueue.popFront(); - auto itr = m_pendingCalls.find(job_id); - if(itr != m_pendingCalls.end()) + auto itr = m_pendingCalls.find(job_id); + if (itr != m_pendingCalls.end()) { m_pendingCalls.erase(itr); } @@ -950,7 +937,7 @@ namespace libuv Loop::do_timer_job(uint64_t job_id) { auto itr = m_pendingCalls.find(job_id); - if(itr != m_pendingCalls.end()) + if (itr != m_pendingCalls.end()) { LogicCall(m_Logic, itr->second); m_pendingCalls.erase(itr); @@ -960,7 +947,7 @@ namespace libuv void Loop::stop() { - if(m_Run) + if (m_Run) { llarp::LogInfo("stopping event loop"); CloseAll(); @@ -976,11 +963,11 @@ namespace libuv uv_walk( &m_Impl, [](uv_handle_t* h, void*) { - if(uv_is_closing(h)) + if (uv_is_closing(h)) return; - if(h->data && uv_is_active(h) && h->type != UV_TIMER) + if (h->data && uv_is_active(h) && h->type != UV_TIMER) { - static_cast< glue* >(h->data)->Close(); + static_cast(h->data)->Close(); } }, nullptr); @@ -997,8 +984,8 @@ namespace libuv Loop::udp_listen(llarp_udp_io* udp, const sockaddr* src) { auto* impl = new udp_glue(&m_Impl, udp, src); - udp->impl = impl; - if(impl->Bind()) + udp->impl = impl; + if (impl->Bind()) { return true; } @@ -1007,10 +994,10 @@ namespace libuv } bool - Loop::add_ticker(std::function< void(void) > func) + Loop::add_ticker(std::function func) { auto* ticker = new ticker_glue(&m_Impl, func); - if(ticker->Start()) + if (ticker->Start()) { return true; } @@ -1021,10 +1008,10 @@ namespace libuv bool Loop::udp_close(llarp_udp_io* udp) { - if(udp == nullptr) + if (udp == nullptr) return false; - auto* glue = static_cast< udp_glue* >(udp->impl); - if(glue == nullptr) + auto* glue = static_cast(udp->impl); + if (glue == nullptr) return false; glue->Close(); return true; @@ -1039,7 +1026,7 @@ namespace libuv #else auto* glue = new tun_glue(tun); tun->impl = glue; - if(glue->Init(&m_Impl)) + if (glue->Init(&m_Impl)) { return true; } @@ -1052,8 +1039,8 @@ namespace libuv Loop::tcp_listen(llarp_tcp_acceptor* tcp, const sockaddr* addr) { auto* glue = new conn_glue(&m_Impl, tcp, addr); - tcp->impl = glue; - if(glue->Server()) + tcp->impl = glue; + if (glue->Server()) return true; tcp->impl = nullptr; delete glue; @@ -1064,14 +1051,14 @@ namespace libuv Loop::add_pipe(llarp_ev_pkt_pipe* p) { auto* glue = new pipe_glue(&m_Impl, p); - if(glue->Start()) + if (glue->Start()) return true; delete glue; return false; } void - Loop::call_soon(std::function< void(void) > f) + Loop::call_soon(std::function f) { m_LogicCalls.tryPushBack(f); uv_async_send(&m_LogicCaller); @@ -1082,5 +1069,5 @@ namespace libuv bool llarp_ev_udp_recvmany(struct llarp_udp_io* u, struct llarp_pkt_list* pkts) { - return static_cast< libuv::udp_glue* >(u->impl)->RecvMany(pkts); + return static_cast(u->impl)->RecvMany(pkts); } diff --git a/llarp/ev/ev_libuv.hpp b/llarp/ev/ev_libuv.hpp index db8b1520f..110f80339 100644 --- a/llarp/ev/ev_libuv.hpp +++ b/llarp/ev/ev_libuv.hpp @@ -15,7 +15,7 @@ namespace libuv { struct Loop final : public llarp_ev_loop { - typedef std::function< void(void) > Callback; + typedef std::function Callback; struct PendingTimer { @@ -49,8 +49,7 @@ namespace libuv tick(int ms) override; uint32_t - call_after_delay(llarp_time_t delay_ms, - std::function< void(void) > callback) override; + call_after_delay(llarp_time_t delay_ms, std::function callback) override; void cancel_delayed_call(uint32_t job_id) override; @@ -108,7 +107,7 @@ namespace libuv } bool - add_ticker(std::function< void(void) > ticker) override; + add_ticker(std::function ticker) override; /// register event listener bool @@ -118,36 +117,36 @@ namespace libuv } void - set_logic(std::shared_ptr< llarp::Logic > l) override + set_logic(std::shared_ptr l) override { m_Logic = l; m_Logic->SetQueuer(llarp::util::memFn(&Loop::call_soon, this)); } - std::shared_ptr< llarp::Logic > m_Logic; + std::shared_ptr m_Logic; void - call_soon(std::function< void(void) > f) override; + call_soon(std::function f) override; private: uv_loop_t m_Impl; uv_timer_t* m_TickTimer; uv_async_t m_WakeUp; - std::atomic< bool > m_Run; + std::atomic m_Run; uv_async_t m_LogicCaller; - using AtomicQueue_t = llarp::thread::Queue< std::function< void(void) > >; + using AtomicQueue_t = llarp::thread::Queue>; AtomicQueue_t m_LogicCalls; #ifdef LOKINET_DEBUG uint64_t last_time; uint64_t loop_run_count; #endif - std::atomic< uint32_t > m_nextID; + std::atomic m_nextID; - std::map< uint32_t, Callback > m_pendingCalls; + std::map m_pendingCalls; - llarp::thread::Queue< PendingTimer > m_timerQueue; - llarp::thread::Queue< uint32_t > m_timerCancelQueue; + llarp::thread::Queue m_timerQueue; + llarp::thread::Queue m_timerCancelQueue; }; } // namespace libuv diff --git a/llarp/ev/ev_win32.cpp b/llarp/ev/ev_win32.cpp index dd97a118a..7e0418ce7 100644 --- a/llarp/ev/ev_win32.cpp +++ b/llarp/ev/ev_win32.cpp @@ -13,13 +13,13 @@ static int poolSize; static CRITICAL_SECTION HandlerMtx; // list of TUN listeners (useful for exits or other nodes with multiple TUNs) -std::list< win32_tun_io* > tun_listeners; +std::list tun_listeners; void begin_tun_loop(int nThreads, llarp_ev_loop* loop) { kThreadPool = new HANDLE[nThreads]; - for(int i = 0; i < nThreads; ++i) + for (int i = 0; i < nThreads; ++i) { kThreadPool[i] = CreateThread(nullptr, 0, &tun_ev_loop, loop, 0, nullptr); } @@ -44,29 +44,28 @@ win32_tun_io::setup() // time InitializeCriticalSection(&HandlerMtx); - if(tuntap_start(tunif, TUNTAP_MODE_TUNNEL, 0) == -1) + if (tuntap_start(tunif, TUNTAP_MODE_TUNNEL, 0) == -1) { llarp::LogWarn("failed to start interface"); return false; } - if(tuntap_up(tunif) == -1) + if (tuntap_up(tunif) == -1) { char ebuf[1024]; int err = GetLastError(); - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL, ebuf, - 1024, nullptr); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, err, LANG_NEUTRAL, ebuf, 1024, nullptr); llarp::LogWarn("failed to put interface up: ", ebuf); return false; } tunif->bindaddr = t->dnsaddr; - if(tuntap_set_ip(tunif, t->ifaddr, t->ifaddr, t->netmask) == -1) + if (tuntap_set_ip(tunif, t->ifaddr, t->ifaddr, t->netmask) == -1) { llarp::LogWarn("failed to set ip"); return false; } - if(tunif->tun_fd == INVALID_HANDLE_VALUE) + if (tunif->tun_fd == INVALID_HANDLE_VALUE) return false; return true; @@ -76,15 +75,14 @@ win32_tun_io::setup() bool win32_tun_io::add_ev(llarp_ev_loop* loop) { - if(tun_event_queue == INVALID_HANDLE_VALUE) + if (tun_event_queue == INVALID_HANDLE_VALUE) { SYSTEM_INFO sys_info; GetSystemInfo(&sys_info); unsigned long numCPU = sys_info.dwNumberOfProcessors; // let the system handle 2x the number of CPUs or hardware // threads - tun_event_queue = CreateIoCompletionPort(tunif->tun_fd, nullptr, - (ULONG_PTR)this, numCPU * 2); + tun_event_queue = CreateIoCompletionPort(tunif->tun_fd, nullptr, (ULONG_PTR)this, numCPU * 2); begin_tun_loop(numCPU * 2, loop); } else @@ -102,9 +100,9 @@ void win32_tun_io::do_write(void* data, size_t sz) { asio_evt_pkt* pkt = new asio_evt_pkt; - pkt->buf = data; - pkt->sz = sz; - pkt->write = true; + pkt->buf = data; + pkt->sz = sz; + pkt->write = true; memset(&pkt->pkt, '\0', sizeof(pkt->pkt)); WriteFile(tunif->tun_fd, data, sz, nullptr, &pkt->pkt); } @@ -114,7 +112,7 @@ win32_tun_io::do_write(void* data, size_t sz) void win32_tun_io::flush_write() { - if(t->before_write) + if (t->before_write) t->before_write(t); } @@ -122,9 +120,9 @@ void win32_tun_io::read(byte_t* buf, size_t sz) { asio_evt_pkt* pkt = new asio_evt_pkt; - pkt->buf = buf; + pkt->buf = buf; memset(&pkt->pkt, '\0', sizeof(OVERLAPPED)); - pkt->sz = sz; + pkt->sz = sz; pkt->write = false; ReadFile(tunif->tun_fd, buf, sz, nullptr, &pkt->pkt); } @@ -133,53 +131,52 @@ win32_tun_io::read(byte_t* buf, size_t sz) extern "C" DWORD FAR PASCAL tun_ev_loop(void* u) { - llarp_ev_loop* logic = static_cast< llarp_ev_loop* >(u); + llarp_ev_loop* logic = static_cast(u); - DWORD size = 0; - OVERLAPPED* ovl = nullptr; + DWORD size = 0; + OVERLAPPED* ovl = nullptr; ULONG_PTR listener = 0; - asio_evt_pkt* pkt = nullptr; + asio_evt_pkt* pkt = nullptr; BOOL alert; - while(true) + while (true) { - alert = GetQueuedCompletionStatus(tun_event_queue, &size, &listener, &ovl, - EV_TICK_INTERVAL); + alert = GetQueuedCompletionStatus(tun_event_queue, &size, &listener, &ovl, EV_TICK_INTERVAL); - if(!alert) + if (!alert) { // tick listeners on io timeout, this is required to be done every tick // cycle regardless of any io being done, this manages the internal state // of the tun logic - for(const auto& tun : tun_listeners) + for (const auto& tun : tun_listeners) { logic->call_soon([tun]() { - if(tun->t->tick) + if (tun->t->tick) tun->t->tick(tun->t); tun->flush_write(); }); } continue; // let's go at it once more } - if(listener == (ULONG_PTR)~0) + if (listener == (ULONG_PTR)~0) break; // if we're here, then we got something interesting :> - pkt = (asio_evt_pkt*)ovl; - win32_tun_io* ev = reinterpret_cast< win32_tun_io* >(listener); - if(!pkt->write) + pkt = (asio_evt_pkt*)ovl; + win32_tun_io* ev = reinterpret_cast(listener); + if (!pkt->write) { // llarp::LogInfo("read tun ", size, " bytes, pass to handler"); // skip if our buffer remains empty // (if our buffer is empty, we don't even have a valid IP frame. // just throw it out) - if(*(byte_t*)pkt->buf == '\0') + if (*(byte_t*)pkt->buf == '\0') { delete pkt; continue; } // EnterCriticalSection(&HandlerMtx); logic->call_soon([pkt, size, ev]() { - if(ev->t->recvpkt) + if (ev->t->recvpkt) ev->t->recvpkt(ev->t, llarp_buffer_t(pkt->buf, size)); delete pkt; }); @@ -194,7 +191,7 @@ tun_ev_loop(void* u) // LeaveCriticalSection(&HandlerMtx); } logic->call_soon([ev]() { - if(ev->t->tick) + if (ev->t->tick) ev->t->tick(ev->t); ev->flush_write(); }); @@ -206,17 +203,17 @@ tun_ev_loop(void* u) void exit_tun_loop() { - if(kThreadPool) + if (kThreadPool) { // kill the kernel's thread pool // int i = (&kThreadPool)[1] - kThreadPool; // get the size of our thread // pool llarp::LogInfo("closing ", poolSize, " threads"); // if we get all-ones in the queue, thread exits, and we clean up - for(int j = 0; j < poolSize; ++j) + for (int j = 0; j < poolSize; ++j) PostQueuedCompletionStatus(tun_event_queue, 0, ~0, nullptr); WaitForMultipleObjects(poolSize, kThreadPool, TRUE, INFINITE); - for(int j = 0; j < poolSize; ++j) + for (int j = 0; j < poolSize; ++j) CloseHandle(kThreadPool[j]); delete[] kThreadPool; kThreadPool = nullptr; @@ -226,9 +223,9 @@ exit_tun_loop() // the fds are closed in their destructors // once we get to zero, we can safely close the event port auto itr = tun_listeners.begin(); - while(itr != tun_listeners.end()) + while (itr != tun_listeners.end()) { - delete(*itr); + delete (*itr); itr = tun_listeners.erase(itr); } CloseHandle(tun_event_queue); diff --git a/llarp/ev/ev_win32.hpp b/llarp/ev/ev_win32.hpp index 000d8d12c..c09349ded 100644 --- a/llarp/ev/ev_win32.hpp +++ b/llarp/ev/ev_win32.hpp @@ -15,10 +15,9 @@ // io packet for TUN read/write struct asio_evt_pkt { - OVERLAPPED pkt = { - 0, 0, 0, 0, nullptr}; // must be first, since this is part of the IO call - bool write = false; // true, or false if read pkt - size_t sz; // should match the queued data size, if not try again? + OVERLAPPED pkt = {0, 0, 0, 0, nullptr}; // must be first, since this is part of the IO call + bool write = false; // true, or false if read pkt + size_t sz; // should match the queued data size, if not try again? void* buf; // must remain valid until we get notification; this is _supposed_ // to be zero-copy }; @@ -95,7 +94,7 @@ struct win32_tun_io ~win32_tun_io() { CancelIo(tunif->tun_fd); - if(tunif->tun_fd) + if (tunif->tun_fd) tuntap_destroy(tunif); } }; diff --git a/llarp/ev/pipe.cpp b/llarp/ev/pipe.cpp index 049e702ee..27e70fdc8 100644 --- a/llarp/ev/pipe.cpp +++ b/llarp/ev/pipe.cpp @@ -19,12 +19,11 @@ llarp_ev_pkt_pipe::StartPipe() return false; #else int _fds[2]; - if(pipe(_fds) == -1 - && fcntl(_fds[0], F_SETFL, fcntl(_fds[0], F_GETFL) | O_NONBLOCK)) + if (pipe(_fds) == -1 && fcntl(_fds[0], F_SETFL, fcntl(_fds[0], F_GETFL) | O_NONBLOCK)) { return false; } - fd = _fds[0]; + fd = _fds[0]; writefd = _fds[1]; return m_Loop->add_pipe(this); #endif @@ -34,7 +33,7 @@ int llarp_ev_pkt_pipe::read(byte_t* pkt, size_t sz) { auto res = ::read(fd, pkt, sz); - if(res <= 0) + if (res <= 0) return res; llarp::LogDebug("read ", res, " on pipe"); llarp_buffer_t buf(pkt, res); @@ -52,7 +51,7 @@ bool llarp_ev_pkt_pipe::Write(const llarp_buffer_t& pkt) { const ssize_t sz = pkt.sz; - if(do_write(pkt.base, pkt.sz) != sz) + if (do_write(pkt.base, pkt.sz) != sz) { llarp::LogDebug("queue write ", pkt.sz); return queue_write(pkt.base, pkt.sz); diff --git a/llarp/ev/vpnio.cpp b/llarp/ev/vpnio.cpp index c8dac8ab9..ab56d7547 100644 --- a/llarp/ev/vpnio.cpp +++ b/llarp/ev/vpnio.cpp @@ -12,12 +12,12 @@ llarp_vpn_io_impl::AsyncClose() } void -llarp_vpn_io_impl::CallSafe(std::function< void(void) > f) +llarp_vpn_io_impl::CallSafe(std::function f) { auto ctx = llarp::Context::Get(ptr); - if(ctx && ctx->CallSafe(f)) + if (ctx && ctx->CallSafe(f)) return; - else if(ctx == nullptr || ctx->logic == nullptr) + else if (ctx == nullptr || ctx->logic == nullptr) f(); } @@ -25,7 +25,7 @@ void llarp_vpn_io_impl::Expunge() { parent->impl = nullptr; - if(parent->closed) + if (parent->closed) parent->closed(parent); delete this; } \ No newline at end of file diff --git a/llarp/ev/vpnio.hpp b/llarp/ev/vpnio.hpp index d522ddb29..4c4e1e838 100644 --- a/llarp/ev/vpnio.hpp +++ b/llarp/ev/vpnio.hpp @@ -10,7 +10,7 @@ struct llarp_vpn_io; struct llarp_vpn_pkt_queue { using Packet_t = llarp::net::IPPacket; - llarp::thread::Queue< Packet_t > queue; + llarp::thread::Queue queue; llarp_vpn_pkt_queue() : queue(1024){}; ~llarp_vpn_pkt_queue() = default; @@ -42,7 +42,7 @@ struct llarp_vpn_io_impl private: void - CallSafe(std::function< void(void) > f); + CallSafe(std::function f); void Expunge(); diff --git a/llarp/exit/context.cpp b/llarp/exit/context.cpp index fceafb040..07df13d92 100644 --- a/llarp/exit/context.cpp +++ b/llarp/exit/context.cpp @@ -15,7 +15,7 @@ namespace llarp { { auto itr = m_Exits.begin(); - while(itr != m_Exits.end()) + while (itr != m_Exits.end()) { itr->second->Tick(now); ++itr; @@ -23,9 +23,9 @@ namespace llarp } { auto itr = m_Closed.begin(); - while(itr != m_Closed.end()) + while (itr != m_Closed.end()) { - if((*itr)->ShouldRemove()) + if ((*itr)->ShouldRemove()) itr = m_Closed.erase(itr); else ++itr; @@ -37,7 +37,7 @@ namespace llarp Context::Stop() { auto itr = m_Exits.begin(); - while(itr != m_Exits.end()) + while (itr != m_Exits.end()) { itr->second->Stop(); m_Closed.emplace_back(std::move(itr->second)); @@ -50,7 +50,7 @@ namespace llarp { util::StatusObject obj{}; auto itr = m_Exits.begin(); - while(itr != m_Exits.end()) + while (itr != m_Exits.end()) { obj[itr->first] = itr->second->ExtractStatus(); ++itr; @@ -62,7 +62,7 @@ namespace llarp Context::CalculateExitTraffic(TrafficStats& stats) { auto itr = m_Exits.begin(); - while(itr != m_Exits.end()) + while (itr != m_Exits.end()) { itr->second->CalculateTrafficStats(stats); ++itr; @@ -73,10 +73,10 @@ namespace llarp Context::FindEndpointForPath(const PathID_t& path) const { auto itr = m_Exits.begin(); - while(itr != m_Exits.end()) + while (itr != m_Exits.end()) { auto ep = itr->second->FindEndpointByPath(path); - if(ep) + if (ep) return ep; ++itr; } @@ -84,13 +84,12 @@ namespace llarp } bool - Context::ObtainNewExit(const PubKey& pk, const PathID_t& path, - bool permitInternet) + Context::ObtainNewExit(const PubKey& pk, const PathID_t& path, bool permitInternet) { auto itr = m_Exits.begin(); - while(itr != m_Exits.end()) + while (itr != m_Exits.end()) { - if(itr->second->AllocateNewExit(pk, path, permitInternet)) + if (itr->second->AllocateNewExit(pk, path, permitInternet)) return true; ++itr; } @@ -103,21 +102,21 @@ namespace llarp // check for duplicate exit by name { auto itr = m_Exits.find(name); - if(itr != m_Exits.end()) + if (itr != m_Exits.end()) { LogError("duplicate exit with name ", name); return false; } } - std::unique_ptr< handlers::ExitEndpoint > endpoint; + std::unique_ptr endpoint; // make new endpoint - endpoint = std::make_unique< handlers::ExitEndpoint >(name, m_Router); + endpoint = std::make_unique(name, m_Router); // configure { auto itr = conf.begin(); - while(itr != conf.end()) + while (itr != conf.end()) { - if(!endpoint->SetOption(itr->first, itr->second)) + if (!endpoint->SetOption(itr->first, itr->second)) { LogWarn("Couldn't set option ", itr->first, " to ", itr->second); return false; @@ -126,7 +125,7 @@ namespace llarp } } // add endpoint - if(!endpoint->Start()) + if (!endpoint->Start()) { LogWarn("Couldn't start exit endpoint"); return false; diff --git a/llarp/exit/context.hpp b/llarp/exit/context.hpp index 4dc10cb7d..dbd58bf4b 100644 --- a/llarp/exit/context.hpp +++ b/llarp/exit/context.hpp @@ -13,9 +13,9 @@ namespace llarp /// owner of all the exit endpoints struct Context { - using Config_t = std::unordered_multimap< std::string, std::string >; + using Config_t = std::unordered_multimap; - Context(AbstractRouter *r); + Context(AbstractRouter* r); ~Context(); void @@ -32,29 +32,24 @@ namespace llarp Stop(); bool - AddExitEndpoint(const std::string &name, const Config_t &config); + AddExitEndpoint(const std::string& name, const Config_t& config); bool - ObtainNewExit(const PubKey &remote, const PathID_t &path, - bool permitInternet); + ObtainNewExit(const PubKey& remote, const PathID_t& path, bool permitInternet); - exit::Endpoint * - FindEndpointForPath(const PathID_t &path) const; + exit::Endpoint* + FindEndpointForPath(const PathID_t& path) const; /// calculate (pk, tx, rx) for all exit traffic - using TrafficStats = - std::unordered_map< PubKey, std::pair< uint64_t, uint64_t >, - PubKey::Hash >; + using TrafficStats = std::unordered_map, PubKey::Hash>; void - CalculateExitTraffic(TrafficStats &stats); + CalculateExitTraffic(TrafficStats& stats); private: - AbstractRouter *m_Router; - std::unordered_map< std::string, - std::shared_ptr< handlers::ExitEndpoint > > - m_Exits; - std::list< std::shared_ptr< handlers::ExitEndpoint > > m_Closed; + AbstractRouter* m_Router; + std::unordered_map> m_Exits; + std::list> m_Closed; }; } // namespace exit } // namespace llarp diff --git a/llarp/exit/endpoint.cpp b/llarp/exit/endpoint.cpp index 4a2285603..752985d24 100644 --- a/llarp/exit/endpoint.cpp +++ b/llarp/exit/endpoint.cpp @@ -8,9 +8,12 @@ namespace llarp { namespace exit { - Endpoint::Endpoint(const llarp::PubKey& remoteIdent, - const llarp::PathID_t& beginPath, bool rewriteIP, - huint128_t ip, llarp::handlers::ExitEndpoint* parent) + Endpoint::Endpoint( + const llarp::PubKey& remoteIdent, + const llarp::PathID_t& beginPath, + bool rewriteIP, + huint128_t ip, + llarp::handlers::ExitEndpoint* parent) : createdAt(parent->Now()) , m_Parent(parent) , m_remoteSignKey(remoteIdent) @@ -52,7 +55,7 @@ namespace llarp bool Endpoint::UpdateLocalPath(const llarp::PathID_t& nextPath) { - if(!m_Parent->UpdateEndpointPath(m_remoteSignKey, nextPath)) + if (!m_Parent->UpdateEndpointPath(m_remoteSignKey, nextPath)) return false; m_CurrentPath = nextPath; return true; @@ -70,7 +73,7 @@ namespace llarp Endpoint::IsExpired(llarp_time_t now) const { auto path = GetCurrentPath(); - if(path) + if (path) { return path->Expired(now); } @@ -82,7 +85,7 @@ namespace llarp Endpoint::ExpiresSoon(llarp_time_t now, llarp_time_t dlt) const { auto path = GetCurrentPath(); - if(path) + if (path) return path->ExpiresSoon(now, dlt); return true; } @@ -90,15 +93,15 @@ namespace llarp bool Endpoint::LooksDead(llarp_time_t now, llarp_time_t timeout) const { - if(ExpiresSoon(now, timeout)) + if (ExpiresSoon(now, timeout)) return true; auto path = GetCurrentPath(); - if(!path) + if (!path) return true; auto lastPing = path->LastRemoteActivityAt(); - if(lastPing == 0s || (now > lastPing && now - lastPing > timeout)) + if (lastPing == 0s || (now > lastPing && now - lastPing > timeout)) return now > m_LastActive && now - m_LastActive > timeout; - else if(lastPing > 0s) // NOLINT + else if (lastPing > 0s) // NOLINT return now > lastPing && now - lastPing > timeout; return lastPing > 0s; } @@ -107,30 +110,29 @@ namespace llarp Endpoint::QueueOutboundTraffic(ManagedBuffer buf, uint64_t counter) { // queue overflow - if(m_UpstreamQueue.size() > MaxUpstreamQueueSize) + if (m_UpstreamQueue.size() > MaxUpstreamQueueSize) return false; llarp::net::IPPacket pkt; - if(!pkt.Load(buf.underlying)) + if (!pkt.Load(buf.underlying)) return false; - if(pkt.IsV6() && m_Parent->SupportsV6()) + if (pkt.IsV6() && m_Parent->SupportsV6()) { huint128_t dst; - if(m_RewriteSource) + if (m_RewriteSource) dst = m_Parent->GetIfAddr(); else dst = pkt.dstv6(); pkt.UpdateIPv6Address(m_IP, dst); } - else if(pkt.IsV4() && !m_Parent->SupportsV6()) + else if (pkt.IsV4() && !m_Parent->SupportsV6()) { huint32_t dst; - if(m_RewriteSource) + if (m_RewriteSource) dst = net::IPPacket::TruncateV6(m_Parent->GetIfAddr()); else dst = pkt.dstv4(); - pkt.UpdateIPv4Address(xhtonl(net::IPPacket::TruncateV6(m_IP)), - xhtonl(dst)); + pkt.UpdateIPv4Address(xhtonl(net::IPPacket::TruncateV6(m_IP)), xhtonl(dst)); } else { @@ -146,33 +148,33 @@ namespace llarp Endpoint::QueueInboundTraffic(ManagedBuffer buf) { llarp::net::IPPacket pkt; - if(!pkt.Load(buf.underlying)) + if (!pkt.Load(buf.underlying)) return false; huint128_t src; - if(m_RewriteSource) + if (m_RewriteSource) src = m_Parent->GetIfAddr(); else src = pkt.srcv6(); - if(pkt.IsV6()) + if (pkt.IsV6()) pkt.UpdateIPv6Address(src, m_IP); else - pkt.UpdateIPv4Address(xhtonl(net::IPPacket::TruncateV6(src)), - xhtonl(net::IPPacket::TruncateV6(m_IP))); + pkt.UpdateIPv4Address( + xhtonl(net::IPPacket::TruncateV6(src)), xhtonl(net::IPPacket::TruncateV6(m_IP))); - const auto _pktbuf = pkt.Buffer(); + const auto _pktbuf = pkt.Buffer(); const llarp_buffer_t& pktbuf = _pktbuf.underlying; - const uint8_t queue_idx = pktbuf.sz / llarp::routing::ExitPadSize; - if(m_DownstreamQueues.find(queue_idx) == m_DownstreamQueues.end()) + const uint8_t queue_idx = pktbuf.sz / llarp::routing::ExitPadSize; + if (m_DownstreamQueues.find(queue_idx) == m_DownstreamQueues.end()) m_DownstreamQueues.emplace(queue_idx, InboundTrafficQueue_t{}); auto& queue = m_DownstreamQueues.at(queue_idx); - if(queue.size() == 0) + if (queue.size() == 0) { queue.emplace_back(); return queue.back().PutBuffer(pktbuf, m_Counter++); } auto& msg = queue.back(); - if(msg.Size() + pktbuf.sz > llarp::routing::ExitPadSize) + if (msg.Size() + pktbuf.sz > llarp::routing::ExitPadSize) { queue.emplace_back(); return queue.back().PutBuffer(pktbuf, m_Counter++); @@ -185,7 +187,7 @@ namespace llarp Endpoint::Flush() { // flush upstream queue - while(m_UpstreamQueue.size()) + while (m_UpstreamQueue.size()) { m_Parent->QueueOutboundTraffic(m_UpstreamQueue.top().pkt.ConstBuffer()); m_UpstreamQueue.pop(); @@ -193,16 +195,16 @@ namespace llarp // flush downstream queue auto path = GetCurrentPath(); bool sent = path != nullptr; - if(path) + if (path) { - for(auto& item : m_DownstreamQueues) + for (auto& item : m_DownstreamQueues) { auto& queue = item.second; - while(queue.size()) + while (queue.size()) { auto& msg = queue.front(); - msg.S = path->NextSeqNo(); - if(path->SendRoutingMessage(msg, m_Parent->GetRouter())) + msg.S = path->NextSeqNo(); + if (path->SendRoutingMessage(msg, m_Parent->GetRouter())) { m_RxRate += msg.Size(); sent = true; @@ -211,7 +213,7 @@ namespace llarp } } } - for(auto& item : m_DownstreamQueues) + for (auto& item : m_DownstreamQueues) item.second.clear(); return sent; } @@ -220,8 +222,7 @@ namespace llarp Endpoint::GetCurrentPath() const { auto router = m_Parent->GetRouter(); - return router->pathContext().GetByUpstream(router->pubkey(), - m_CurrentPath); + return router->pathContext().GetByUpstream(router->pubkey(), m_CurrentPath); } } // namespace exit } // namespace llarp diff --git a/llarp/exit/endpoint.hpp b/llarp/exit/endpoint.hpp index 8a19a6381..e55298b62 100644 --- a/llarp/exit/endpoint.hpp +++ b/llarp/exit/endpoint.hpp @@ -23,9 +23,12 @@ namespace llarp { static constexpr size_t MaxUpstreamQueueSize = 256; - Endpoint(const llarp::PubKey& remoteIdent, - const llarp::PathID_t& beginPath, bool rewriteIP, huint128_t ip, - llarp::handlers::ExitEndpoint* parent); + Endpoint( + const llarp::PubKey& remoteIdent, + const llarp::PathID_t& beginPath, + bool rewriteIP, + huint128_t ip, + llarp::handlers::ExitEndpoint* parent); ~Endpoint(); @@ -113,16 +116,14 @@ namespace llarp uint64_t m_TxRate, m_RxRate; llarp_time_t m_LastActive; bool m_RewriteSource; - using InboundTrafficQueue_t = - std::deque< llarp::routing::TransferTrafficMessage >; - using TieredQueue = std::map< uint8_t, InboundTrafficQueue_t >; + using InboundTrafficQueue_t = std::deque; + using TieredQueue = std::map; // maps number of fragments the message will fit in to the queue for it TieredQueue m_DownstreamQueues; struct UpstreamBuffer { - UpstreamBuffer(const llarp::net::IPPacket& p, uint64_t c) - : pkt(p), counter(c) + UpstreamBuffer(const llarp::net::IPPacket& p, uint64_t c) : pkt(p), counter(c) { } @@ -136,7 +137,7 @@ namespace llarp } }; - using UpstreamQueue_t = std::priority_queue< UpstreamBuffer >; + using UpstreamQueue_t = std::priority_queue; UpstreamQueue_t m_UpstreamQueue; uint64_t m_Counter; }; diff --git a/llarp/exit/exit_messages.cpp b/llarp/exit/exit_messages.cpp index 0693b036b..75adb2634 100644 --- a/llarp/exit/exit_messages.cpp +++ b/llarp/exit/exit_messages.cpp @@ -10,11 +10,11 @@ namespace llarp bool ObtainExitMessage::Sign(const llarp::SecretKey& sk) { - std::array< byte_t, 1024 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); I = seckey_topublic(sk); Z.Zero(); - if(!BEncode(&buf)) + if (!BEncode(&buf)) { return false; } @@ -25,12 +25,12 @@ namespace llarp bool ObtainExitMessage::Verify() const { - std::array< byte_t, 1024 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); ObtainExitMessage copy; copy = *this; copy.Z.Zero(); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) { return false; } @@ -42,27 +42,27 @@ namespace llarp bool ObtainExitMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "O")) + if (!BEncodeWriteDictMsgType(buf, "A", "O")) return false; - if(!BEncodeWriteDictArray("B", B, buf)) + if (!BEncodeWriteDictArray("B", B, buf)) return false; - if(!BEncodeWriteDictInt("E", E, buf)) + if (!BEncodeWriteDictInt("E", E, buf)) return false; - if(!BEncodeWriteDictEntry("I", I, buf)) + if (!BEncodeWriteDictEntry("I", I, buf)) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("T", T, buf)) + if (!BEncodeWriteDictInt("T", T, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; - if(!BEncodeWriteDictArray("W", W, buf)) + if (!BEncodeWriteDictArray("W", W, buf)) return false; - if(!BEncodeWriteDictInt("X", X, buf)) + if (!BEncodeWriteDictInt("X", X, buf)) return false; - if(!BEncodeWriteDictEntry("Z", Z, buf)) + if (!BEncodeWriteDictEntry("Z", Z, buf)) return false; return bencode_end(buf); } @@ -71,30 +71,29 @@ namespace llarp ObtainExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictList("B", B, read, k, buf)) + if (!BEncodeMaybeReadDictList("B", B, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("E", E, read, k, buf)) + if (!BEncodeMaybeReadDictInt("E", E, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("I", I, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("I", I, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("S", S, read, k, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("T", T, read, k, buf)) + if (!BEncodeMaybeReadDictInt("T", T, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, k, buf)) return false; - if(!BEncodeMaybeReadDictList("W", W, read, k, buf)) + if (!BEncodeMaybeReadDictList("W", W, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("X", X, read, k, buf)) + if (!BEncodeMaybeReadDictInt("X", X, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) return false; return read; } bool - ObtainExitMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + ObtainExitMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h->HandleObtainExitMessage(*this, r); } @@ -102,19 +101,19 @@ namespace llarp bool GrantExitMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "G")) + if (!BEncodeWriteDictMsgType(buf, "A", "G")) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("T", T, buf)) + if (!BEncodeWriteDictInt("T", T, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; - if(!BEncodeWriteDictEntry("Y", Y, buf)) + if (!BEncodeWriteDictEntry("Y", Y, buf)) return false; - if(!BEncodeWriteDictEntry("Z", Z, buf)) + if (!BEncodeWriteDictEntry("Z", Z, buf)) return false; return bencode_end(buf); } @@ -123,15 +122,15 @@ namespace llarp GrantExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("S", S, read, k, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("T", T, read, k, buf)) + if (!BEncodeMaybeReadDictInt("T", T, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Y", Y, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Y", Y, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) return false; return read; } @@ -139,12 +138,12 @@ namespace llarp bool GrantExitMessage::Verify(const llarp::PubKey& pk) const { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); GrantExitMessage copy; copy = *this; copy.Z.Zero(); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->verify(pk, buf, Z); @@ -153,11 +152,11 @@ namespace llarp bool GrantExitMessage::Sign(const llarp::SecretKey& sk) { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); Z.Zero(); Y.Randomize(); - if(!BEncode(&buf)) + if (!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->sign(Z, sk, buf); @@ -172,23 +171,23 @@ namespace llarp bool RejectExitMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "J")) + if (!BEncodeWriteDictMsgType(buf, "A", "J")) return false; - if(!BEncodeWriteDictInt("B", B, buf)) + if (!BEncodeWriteDictInt("B", B, buf)) return false; - if(!BEncodeWriteDictList("R", R, buf)) + if (!BEncodeWriteDictList("R", R, buf)) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("T", T, buf)) + if (!BEncodeWriteDictInt("T", T, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; - if(!BEncodeWriteDictEntry("Y", Y, buf)) + if (!BEncodeWriteDictEntry("Y", Y, buf)) return false; - if(!BEncodeWriteDictEntry("Z", Z, buf)) + if (!BEncodeWriteDictEntry("Z", Z, buf)) return false; return bencode_end(buf); } @@ -197,19 +196,19 @@ namespace llarp RejectExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("B", B, read, k, buf)) + if (!BEncodeMaybeReadDictInt("B", B, read, k, buf)) return false; - if(!BEncodeMaybeReadDictList("R", R, read, k, buf)) + if (!BEncodeMaybeReadDictList("R", R, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("S", S, read, k, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("T", T, read, k, buf)) + if (!BEncodeMaybeReadDictInt("T", T, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Y", Y, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Y", Y, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) return false; return read; } @@ -217,11 +216,11 @@ namespace llarp bool RejectExitMessage::Sign(const llarp::SecretKey& sk) { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); Z.Zero(); Y.Randomize(); - if(!BEncode(&buf)) + if (!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->sign(Z, sk, buf); @@ -230,20 +229,19 @@ namespace llarp bool RejectExitMessage::Verify(const llarp::PubKey& pk) const { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); RejectExitMessage copy; copy = *this; copy.Z.Zero(); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->verify(pk, buf, Z); } bool - RejectExitMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + RejectExitMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h->HandleRejectExitMessage(*this, r); } @@ -251,19 +249,19 @@ namespace llarp bool UpdateExitMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "V")) + if (!BEncodeWriteDictMsgType(buf, "A", "V")) return false; - if(!BEncodeWriteDictEntry("P", P, buf)) + if (!BEncodeWriteDictEntry("P", P, buf)) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("T", T, buf)) + if (!BEncodeWriteDictInt("T", T, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; - if(!BEncodeWriteDictEntry("Z", Z, buf)) + if (!BEncodeWriteDictEntry("Z", Z, buf)) return false; return bencode_end(buf); } @@ -272,15 +270,15 @@ namespace llarp UpdateExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("S", S, read, k, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("T", T, read, k, buf)) + if (!BEncodeMaybeReadDictInt("T", T, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("P", P, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("P", P, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) return false; return read; } @@ -289,12 +287,12 @@ namespace llarp UpdateExitMessage::Verify(const llarp::PubKey& pk) const { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); UpdateExitMessage copy; copy = *this; copy.Z.Zero(); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->verify(pk, buf, Z); @@ -303,18 +301,17 @@ namespace llarp bool UpdateExitMessage::Sign(const llarp::SecretKey& sk) { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); Y.Randomize(); - if(!BEncode(&buf)) + if (!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->sign(Z, sk, buf); } bool - UpdateExitMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + UpdateExitMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h->HandleUpdateExitMessage(*this, r); } @@ -322,36 +319,34 @@ namespace llarp bool UpdateExitVerifyMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "V")) + if (!BEncodeWriteDictMsgType(buf, "A", "V")) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("T", T, buf)) + if (!BEncodeWriteDictInt("T", T, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; return bencode_end(buf); } bool - UpdateExitVerifyMessage::DecodeKey(const llarp_buffer_t& k, - llarp_buffer_t* buf) + UpdateExitVerifyMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("S", S, read, k, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("T", T, read, k, buf)) + if (!BEncodeMaybeReadDictInt("T", T, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, k, buf)) return false; return read; } bool - UpdateExitVerifyMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + UpdateExitVerifyMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h->HandleUpdateExitVerifyMessage(*this, r); } @@ -359,17 +354,17 @@ namespace llarp bool CloseExitMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "C")) + if (!BEncodeWriteDictMsgType(buf, "A", "C")) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; - if(!BEncodeWriteDictEntry("Y", Y, buf)) + if (!BEncodeWriteDictEntry("Y", Y, buf)) return false; - if(!BEncodeWriteDictEntry("Z", Z, buf)) + if (!BEncodeWriteDictEntry("Z", Z, buf)) return false; return bencode_end(buf); } @@ -378,13 +373,13 @@ namespace llarp CloseExitMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("S", S, read, k, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Y", Y, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Y", Y, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("Z", Z, read, k, buf)) return false; return read; } @@ -392,12 +387,12 @@ namespace llarp bool CloseExitMessage::Verify(const llarp::PubKey& pk) const { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); CloseExitMessage copy; copy = *this; copy.Z.Zero(); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->verify(pk, buf, Z); @@ -406,11 +401,11 @@ namespace llarp bool CloseExitMessage::Sign(const llarp::SecretKey& sk) { - std::array< byte_t, 512 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); Z.Zero(); Y.Randomize(); - if(!BEncode(&buf)) + if (!BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; return CryptoManager::instance()->sign(Z, sk, buf); diff --git a/llarp/exit/exit_messages.hpp b/llarp/exit/exit_messages.hpp index 8f32b51d8..a3bb54b15 100644 --- a/llarp/exit/exit_messages.hpp +++ b/llarp/exit/exit_messages.hpp @@ -13,11 +13,11 @@ namespace llarp { struct ObtainExitMessage final : public IMessage { - std::vector< llarp::exit::Policy > B; + std::vector B; uint64_t E{0}; llarp::PubKey I; uint64_t T{0}; - std::vector< llarp::exit::Policy > W; + std::vector W; uint64_t X{0}; llarp::Signature Z; @@ -58,7 +58,7 @@ namespace llarp struct GrantExitMessage final : public IMessage { - using Nonce_t = llarp::AlignedBuffer< 16 >; + using Nonce_t = llarp::AlignedBuffer<16>; uint64_t T; Nonce_t Y; @@ -90,9 +90,9 @@ namespace llarp struct RejectExitMessage final : public IMessage { - using Nonce_t = llarp::AlignedBuffer< 16 >; + using Nonce_t = llarp::AlignedBuffer<16>; uint64_t B; - std::vector< llarp::exit::Policy > R; + std::vector R; uint64_t T; Nonce_t Y; llarp::Signature Z; @@ -125,7 +125,7 @@ namespace llarp struct UpdateExitVerifyMessage final : public IMessage { - using Nonce_t = llarp::AlignedBuffer< 16 >; + using Nonce_t = llarp::AlignedBuffer<16>; uint64_t T; Nonce_t Y; llarp::Signature Z; @@ -152,7 +152,7 @@ namespace llarp struct UpdateExitMessage final : public IMessage { - using Nonce_t = llarp::AlignedBuffer< 16 >; + using Nonce_t = llarp::AlignedBuffer<16>; llarp::PathID_t P; uint64_t T; Nonce_t Y; @@ -185,7 +185,7 @@ namespace llarp struct CloseExitMessage final : public IMessage { - using Nonce_t = llarp::AlignedBuffer< 16 >; + using Nonce_t = llarp::AlignedBuffer<16>; Nonce_t Y; llarp::Signature Z; diff --git a/llarp/exit/policy.cpp b/llarp/exit/policy.cpp index 7ff7b9e88..558ef8083 100644 --- a/llarp/exit/policy.cpp +++ b/llarp/exit/policy.cpp @@ -5,32 +5,32 @@ namespace llarp namespace exit { bool - Policy::BEncode(llarp_buffer_t *buf) const + Policy::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictInt("a", proto, buf)) + if (!BEncodeWriteDictInt("a", proto, buf)) return false; - if(!BEncodeWriteDictInt("b", port, buf)) + if (!BEncodeWriteDictInt("b", port, buf)) return false; - if(!BEncodeWriteDictInt("d", drop, buf)) + if (!BEncodeWriteDictInt("d", drop, buf)) return false; - if(!BEncodeWriteDictInt("v", version, buf)) + if (!BEncodeWriteDictInt("v", version, buf)) return false; return bencode_end(buf); } bool - Policy::DecodeKey(const llarp_buffer_t &k, llarp_buffer_t *buf) + Policy::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("a", proto, read, k, buf)) + if (!BEncodeMaybeReadDictInt("a", proto, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("b", port, read, k, buf)) + if (!BEncodeMaybeReadDictInt("b", port, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("d", drop, read, k, buf)) + if (!BEncodeMaybeReadDictInt("d", drop, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, k, buf)) return false; return read; } diff --git a/llarp/exit/policy.hpp b/llarp/exit/policy.hpp index 4a0fd9373..55ba2cefa 100644 --- a/llarp/exit/policy.hpp +++ b/llarp/exit/policy.hpp @@ -9,9 +9,9 @@ namespace llarp { struct Policy { - uint64_t proto = 0; - uint64_t port = 0; - uint64_t drop = 0; + uint64_t proto = 0; + uint64_t port = 0; + uint64_t drop = 0; uint64_t version = LLARP_PROTO_VERSION; bool diff --git a/llarp/exit/session.cpp b/llarp/exit/session.cpp index ea3ad169b..bc565f753 100644 --- a/llarp/exit/session.cpp +++ b/llarp/exit/session.cpp @@ -14,8 +14,11 @@ namespace llarp { BaseSession::BaseSession( const llarp::RouterID& routerId, - std::function< bool(const llarp_buffer_t&) > writepkt, - AbstractRouter* r, size_t numpaths, size_t hoplen, bool bundleRC) + std::function writepkt, + AbstractRouter* r, + size_t numpaths, + size_t hoplen, + bool bundleRC) : llarp::path::Builder(r, numpaths, hoplen) , m_ExitRouter(routerId) , m_WritePacket(std::move(writepkt)) @@ -37,9 +40,9 @@ namespace llarp util::StatusObject BaseSession::ExtractStatus() const { - auto obj = path::Builder::ExtractStatus(); - obj["lastExitUse"] = to_json(m_LastUse); - auto pub = m_ExitIdentity.toPublic(); + auto obj = path::Builder::ExtractStatus(); + obj["lastExitUse"] = to_json(m_LastUse); + auto pub = m_ExitIdentity.toPublic(); obj["exitIdentity"] = pub.ToString(); return obj; } @@ -53,7 +56,7 @@ namespace llarp bool BaseSession::ShouldBuildMore(llarp_time_t now) const { - if(BuildCooldownHit(now)) + if (BuildCooldownHit(now)) return false; const size_t expect = (1 + (numPaths / 2)); // check 30 seconds into the future and see if we need more paths @@ -68,20 +71,23 @@ namespace llarp } bool - BaseSession::SelectHop(llarp_nodedb* db, const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, - llarp::path::PathRole roles) + BaseSession::SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + llarp::path::PathRole roles) { - std::set< RouterID > exclude = prev; - for(const auto& snode : m_SnodeBlacklist) + std::set exclude = prev; + for (const auto& snode : m_SnodeBlacklist) { - if(snode != m_ExitRouter) + if (snode != m_ExitRouter) exclude.insert(snode); } exclude.insert(m_ExitRouter); - if(hop == numHops - 1) + if (hop == numHops - 1) { - if(db->Get(m_ExitRouter, cur)) + if (db->Get(m_ExitRouter, cur)) return true; m_router->LookupRouter(m_ExitRouter, nullptr); return false; @@ -109,12 +115,12 @@ namespace llarp obtain.S = p->NextSeqNo(); obtain.T = llarp::randint(); PopulateRequest(obtain); - if(!obtain.Sign(m_ExitIdentity)) + if (!obtain.Sign(m_ExitIdentity)) { llarp::LogError("Failed to sign exit request"); return; } - if(p->SendExitRequest(obtain, m_router)) + if (p->SendExitRequest(obtain, m_router)) llarp::LogInfo("asking ", m_ExitRouter, " for exit"); else llarp::LogError("failed to send exit request"); @@ -129,7 +135,7 @@ namespace llarp bool BaseSession::HandleGotExit(llarp::path::Path_ptr p, llarp_time_t b) { - if(b == 0s) + if (b == 0s) { llarp::LogInfo("obtained an exit via ", p->Endpoint()); CallPendingCallbacks(true); @@ -140,15 +146,15 @@ namespace llarp void BaseSession::CallPendingCallbacks(bool success) { - if(success) + if (success) { auto self = shared_from_this(); - for(auto& f : m_PendingCallbacks) + for (auto& f : m_PendingCallbacks) f(self); } else { - for(auto& f : m_PendingCallbacks) + for (auto& f : m_PendingCallbacks) f(nullptr); } m_PendingCallbacks.clear(); @@ -158,13 +164,12 @@ namespace llarp BaseSession::ResetInternalState() { auto sendExitClose = [&](const llarp::path::Path_ptr p) { - const static auto roles = - llarp::path::ePathRoleExit | llarp::path::ePathRoleSVC; - if(p->SupportsAnyRoles(roles)) + const static auto roles = llarp::path::ePathRoleExit | llarp::path::ePathRoleSVC; + if (p->SupportsAnyRoles(roles)) { llarp::LogInfo(p->Name(), " closing exit path"); routing::CloseExitMessage msg; - if(msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, m_router)) + if (msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, m_router)) { p->ClearRoles(roles); } @@ -181,11 +186,11 @@ namespace llarp { CallPendingCallbacks(false); auto sendExitClose = [&](const path::Path_ptr p) { - if(p->SupportsAnyRoles(path::ePathRoleExit)) + if (p->SupportsAnyRoles(path::ePathRoleExit)) { LogInfo(p->Name(), " closing exit path"); routing::CloseExitMessage msg; - if(!(msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, m_router))) + if (!(msg.Sign(m_ExitIdentity) && p->SendExitClose(msg, m_router))) LogWarn(p->Name(), " failed to send exit close message"); } }; @@ -195,13 +200,12 @@ namespace llarp } bool - BaseSession::HandleTraffic(llarp::path::Path_ptr, const llarp_buffer_t& buf, - uint64_t counter) + BaseSession::HandleTraffic(llarp::path::Path_ptr, const llarp_buffer_t& buf, uint64_t counter) { - if(m_WritePacket) + if (m_WritePacket) { llarp::net::IPPacket pkt; - if(!pkt.Load(buf)) + if (!pkt.Load(buf)) return false; m_LastUse = m_router->Now(); m_Downstream.emplace(counter, pkt); @@ -211,11 +215,9 @@ namespace llarp } bool - BaseSession::HandleTrafficDrop(llarp::path::Path_ptr p, - const PathID_t& path, uint64_t s) + BaseSession::HandleTrafficDrop(llarp::path::Path_ptr p, const PathID_t& path, uint64_t s) { - llarp::LogError("dropped traffic on exit ", m_ExitRouter, " S=", s, - " P=", path); + llarp::LogError("dropped traffic on exit ", m_ExitRouter, " S=", s, " P=", path); p->EnterState(path::ePathIgnore, m_router->Now()); return true; } @@ -223,20 +225,20 @@ namespace llarp bool BaseSession::QueueUpstreamTraffic(llarp::net::IPPacket pkt, const size_t N) { - const auto pktbuf = pkt.ConstBuffer(); + const auto pktbuf = pkt.ConstBuffer(); const llarp_buffer_t& buf = pktbuf; - auto& queue = m_Upstream[buf.sz / N]; + auto& queue = m_Upstream[buf.sz / N]; // queue overflow - if(queue.size() >= MaxUpstreamQueueLength) + if (queue.size() >= MaxUpstreamQueueLength) return false; - if(queue.size() == 0) + if (queue.size() == 0) { queue.emplace_back(); return queue.back().PutBuffer(buf, m_Counter++); } auto& back = queue.back(); // pack to nearest N - if(back.Size() + buf.sz > N) + if (back.Size() + buf.sz > N) { queue.emplace_back(); return queue.back().PutBuffer(buf, m_Counter++); @@ -261,9 +263,9 @@ namespace llarp bool BaseSession::UrgentBuild(llarp_time_t now) const { - if(BuildCooldownHit(now)) + if (BuildCooldownHit(now)) return false; - if(!IsReady()) + if (!IsReady()) return NumInStatus(path::ePathBuilding) < numPaths; return path::Builder::UrgentBuild(now); } @@ -271,17 +273,17 @@ namespace llarp bool BaseSession::FlushUpstream() { - auto now = m_router->Now(); + auto now = m_router->Now(); auto path = PickRandomEstablishedPath(llarp::path::ePathRoleExit); - if(path) + if (path) { - for(auto& item : m_Upstream) + for (auto& item : m_Upstream) { auto& queue = item.second; // XXX: uninitialised memory here! - while(queue.size()) + while (queue.size()) { auto& msg = queue.front(); - if(path) + if (path) { msg.S = path->NextSeqNo(); path->SendRoutingMessage(msg, m_router); @@ -295,26 +297,25 @@ namespace llarp } else { - if(m_Upstream.size()) + if (m_Upstream.size()) llarp::LogWarn("no path for exit session"); // discard upstream - for(auto& item : m_Upstream) + for (auto& item : m_Upstream) item.second.clear(); m_Upstream.clear(); - if(numHops == 1) + if (numHops == 1) { auto r = m_router; RouterContact rc; - if(r->nodedb()->Get(m_ExitRouter, rc)) + if (r->nodedb()->Get(m_ExitRouter, rc)) r->TryConnectAsync(rc, 5); else - r->LookupRouter(m_ExitRouter, - [r](const std::vector< RouterContact >& results) { - if(results.size()) - r->TryConnectAsync(results[0], 5); - }); + r->LookupRouter(m_ExitRouter, [r](const std::vector& results) { + if (results.size()) + r->TryConnectAsync(results[0], 5); + }); } - else if(UrgentBuild(now)) + else if (UrgentBuild(now)) BuildOneAlignedTo(m_ExitRouter); } return true; @@ -323,9 +324,9 @@ namespace llarp void BaseSession::FlushDownstream() { - while(m_Downstream.size()) + while (m_Downstream.size()) { - if(m_WritePacket) + if (m_WritePacket) m_WritePacket(m_Downstream.top().second.ConstBuffer()); m_Downstream.pop(); } @@ -333,12 +334,15 @@ namespace llarp SNodeSession::SNodeSession( const llarp::RouterID& snodeRouter, - std::function< bool(const llarp_buffer_t&) > writepkt, - AbstractRouter* r, size_t numpaths, size_t hoplen, - bool useRouterSNodeKey, bool bundleRC) + std::function writepkt, + AbstractRouter* r, + size_t numpaths, + size_t hoplen, + bool useRouterSNodeKey, + bool bundleRC) : BaseSession(snodeRouter, writepkt, r, numpaths, hoplen, bundleRC) { - if(useRouterSNodeKey) + if (useRouterSNodeKey) { m_ExitIdentity = r->identity(); } diff --git a/llarp/exit/session.hpp b/llarp/exit/session.hpp index 29ffa7496..38581312b 100644 --- a/llarp/exit/session.hpp +++ b/llarp/exit/session.hpp @@ -15,26 +15,29 @@ namespace llarp { struct BaseSession; - using BaseSession_ptr = std::shared_ptr< BaseSession >; + using BaseSession_ptr = std::shared_ptr; - using SessionReadyFunc = std::function< void(BaseSession_ptr) >; + using SessionReadyFunc = std::function; static constexpr auto LifeSpan = path::default_lifetime; /// a persisting exit session with an exit router struct BaseSession : public llarp::path::Builder, - public std::enable_shared_from_this< BaseSession > + public std::enable_shared_from_this { static constexpr size_t MaxUpstreamQueueLength = 256; - BaseSession(const llarp::RouterID& exitRouter, - std::function< bool(const llarp_buffer_t&) > writepkt, - AbstractRouter* r, size_t numpaths, size_t hoplen, - bool bundleRC); + BaseSession( + const llarp::RouterID& exitRouter, + std::function writepkt, + AbstractRouter* r, + size_t numpaths, + size_t hoplen, + bool bundleRC); ~BaseSession() override; - std::shared_ptr< path::PathSet > + std::shared_ptr GetSelf() override { return shared_from_this(); @@ -64,9 +67,12 @@ namespace llarp CheckPathDead(path::Path_ptr p, llarp_time_t dlt); bool - SelectHop(llarp_nodedb* db, const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, - llarp::path::PathRole roles) override; + SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + llarp::path::PathRole roles) override; bool ShouldBuildMore(llarp_time_t now) const override; @@ -116,31 +122,28 @@ namespace llarp protected: llarp::RouterID m_ExitRouter; llarp::SecretKey m_ExitIdentity; - std::function< bool(const llarp_buffer_t&) > m_WritePacket; + std::function m_WritePacket; virtual void PopulateRequest(llarp::routing::ObtainExitMessage& msg) const = 0; bool - HandleTrafficDrop(llarp::path::Path_ptr p, const llarp::PathID_t& path, - uint64_t s); + HandleTrafficDrop(llarp::path::Path_ptr p, const llarp::PathID_t& path, uint64_t s); bool HandleGotExit(llarp::path::Path_ptr p, llarp_time_t b); bool - HandleTraffic(llarp::path::Path_ptr p, const llarp_buffer_t& buf, - uint64_t seqno); + HandleTraffic(llarp::path::Path_ptr p, const llarp_buffer_t& buf, uint64_t seqno); private: - std::set< RouterID > m_SnodeBlacklist; + std::set m_SnodeBlacklist; - using UpstreamTrafficQueue_t = - std::deque< llarp::routing::TransferTrafficMessage >; - using TieredQueue_t = std::map< uint8_t, UpstreamTrafficQueue_t >; + using UpstreamTrafficQueue_t = std::deque; + using TieredQueue_t = std::map; TieredQueue_t m_Upstream; - using DownstreamPkt = std::pair< uint64_t, llarp::net::IPPacket >; + using DownstreamPkt = std::pair; struct DownstreamPktSorter { @@ -152,14 +155,13 @@ namespace llarp }; using DownstreamTrafficQueue_t = - std::priority_queue< DownstreamPkt, std::vector< DownstreamPkt >, - DownstreamPktSorter >; + std::priority_queue, DownstreamPktSorter>; DownstreamTrafficQueue_t m_Downstream; uint64_t m_Counter; llarp_time_t m_LastUse; - std::vector< SessionReadyFunc > m_PendingCallbacks; + std::vector m_PendingCallbacks; const bool m_BundleRC; void @@ -168,10 +170,13 @@ namespace llarp struct ExitSession final : public BaseSession { - ExitSession(const llarp::RouterID& snodeRouter, - std::function< bool(const llarp_buffer_t&) > writepkt, - AbstractRouter* r, size_t numpaths, size_t hoplen, - bool bundleRC) + ExitSession( + const llarp::RouterID& snodeRouter, + std::function writepkt, + AbstractRouter* r, + size_t numpaths, + size_t hoplen, + bool bundleRC) : BaseSession(snodeRouter, writepkt, r, numpaths, hoplen, bundleRC) { } @@ -193,10 +198,14 @@ namespace llarp struct SNodeSession final : public BaseSession { - SNodeSession(const llarp::RouterID& snodeRouter, - std::function< bool(const llarp_buffer_t&) > writepkt, - AbstractRouter* r, size_t numpaths, size_t hoplen, - bool useRouterSNodeKey, bool bundleRC); + SNodeSession( + const llarp::RouterID& snodeRouter, + std::function writepkt, + AbstractRouter* r, + size_t numpaths, + size_t hoplen, + bool useRouterSNodeKey, + bool bundleRC); ~SNodeSession() override = default; diff --git a/llarp/handlers/exit.cpp b/llarp/handlers/exit.cpp index 4e21214f1..4837374f3 100644 --- a/llarp/handlers/exit.cpp +++ b/llarp/handlers/exit.cpp @@ -14,38 +14,48 @@ namespace llarp namespace handlers { static void - ExitHandlerRecvPkt(llarp_tun_io *tun, const llarp_buffer_t &buf) + ExitHandlerRecvPkt(llarp_tun_io* tun, const llarp_buffer_t& buf) { - std::vector< byte_t > pkt; + std::vector pkt; pkt.resize(buf.sz); std::copy_n(buf.base, buf.sz, pkt.data()); - auto self = static_cast< ExitEndpoint * >(tun->user); + auto self = static_cast(tun->user); LogicCall(self->GetRouter()->logic(), [self, pktbuf = std::move(pkt)]() { self->OnInetPacket(std::move(pktbuf)); }); } static void - ExitHandlerFlush(llarp_tun_io *tun) + ExitHandlerFlush(llarp_tun_io* tun) { - auto *ep = static_cast< ExitEndpoint * >(tun->user); + auto* ep = static_cast(tun->user); LogicCall(ep->GetRouter()->logic(), std::bind(&ExitEndpoint::Flush, ep)); } - ExitEndpoint::ExitEndpoint(const std::string &name, AbstractRouter *r) + ExitEndpoint::ExitEndpoint(const std::string& name, AbstractRouter* r) : m_Router(r) - , m_Resolver(std::make_shared< dns::Proxy >( + , m_Resolver(std::make_shared( r->netloop(), r->logic(), r->netloop(), r->logic(), this)) , m_Name(name) - , m_Tun{{0}, 0, 0, {0}, nullptr, nullptr, - nullptr, nullptr, nullptr, nullptr, nullptr, nullptr} + , m_Tun{{0}, + 0, + 0, + {0}, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr} , m_LocalResolverAddr("127.0.0.1", 53) , m_InetToNetwork(name + "_exit_rx", r->netloop(), r->netloop()) { - m_Tun.user = this; - m_Tun.recvpkt = &ExitHandlerRecvPkt; - m_Tun.tick = &ExitHandlerFlush; + m_Tun.user = this; + m_Tun.recvpkt = &ExitHandlerRecvPkt; + m_Tun.tick = &ExitHandlerFlush; m_ShouldInitTun = true; } @@ -54,10 +64,9 @@ namespace llarp util::StatusObject ExitEndpoint::ExtractStatus() const { - util::StatusObject obj{{"permitExit", m_PermitExit}, - {"ip", m_IfAddr.ToString()}}; + util::StatusObject obj{{"permitExit", m_PermitExit}, {"ip", m_IfAddr.ToString()}}; util::StatusObject exitsObj{}; - for(const auto &item : m_ActiveExits) + for (const auto& item : m_ActiveExits) { exitsObj[item.first.ToString()] = item.second->ExtractStatus(); } @@ -72,40 +81,38 @@ namespace llarp } bool - ExitEndpoint::ShouldHookDNSMessage(const dns::Message &msg) const + ExitEndpoint::ShouldHookDNSMessage(const dns::Message& msg) const { - if(msg.questions.size() == 0) + if (msg.questions.size() == 0) return false; // always hook ptr for ranges we own - if(msg.questions[0].qtype == dns::qTypePTR) + if (msg.questions[0].qtype == dns::qTypePTR) { huint128_t ip; - if(!dns::DecodePTR(msg.questions[0].qname, ip)) + if (!dns::DecodePTR(msg.questions[0].qname, ip)) return false; return m_OurRange.Contains(ip); } - if(msg.questions[0].qtype == dns::qTypeA - || msg.questions[0].qtype == dns::qTypeCNAME - || msg.questions[0].qtype == dns::qTypeAAAA) + if (msg.questions[0].qtype == dns::qTypeA || msg.questions[0].qtype == dns::qTypeCNAME + || msg.questions[0].qtype == dns::qTypeAAAA) { - if(msg.questions[0].IsName("localhost.loki")) + if (msg.questions[0].IsName("localhost.loki")) return true; - if(msg.questions[0].HasTLD(".snode")) + if (msg.questions[0].HasTLD(".snode")) return true; } return false; } bool - ExitEndpoint::HandleHookedDNSMessage( - dns::Message msg, std::function< void(dns::Message) > reply) + ExitEndpoint::HandleHookedDNSMessage(dns::Message msg, std::function reply) { - if(msg.questions[0].qtype == dns::qTypePTR) + if (msg.questions[0].qtype == dns::qTypePTR) { huint128_t ip; - if(!dns::DecodePTR(msg.questions[0].qname, ip)) + if (!dns::DecodePTR(msg.questions[0].qname, ip)) return false; - if(ip == m_IfAddr) + if (ip == m_IfAddr) { RouterID us = GetRouter()->pubkey(); msg.AddAReply(us.ToString(), 300); @@ -113,8 +120,7 @@ namespace llarp else { auto itr = m_IPToKey.find(ip); - if(itr != m_IPToKey.end() - && m_SNodeKeys.find(itr->second) != m_SNodeKeys.end()) + if (itr != m_IPToKey.end() && m_SNodeKeys.find(itr->second) != m_SNodeKeys.end()) { RouterID them = itr->second; msg.AddAReply(them.ToString()); @@ -123,17 +129,17 @@ namespace llarp msg.AddNXReply(); } } - else if(msg.questions[0].qtype == dns::qTypeCNAME) + else if (msg.questions[0].qtype == dns::qTypeCNAME) { - if(msg.questions[0].IsName("random.snode")) + if (msg.questions[0].IsName("random.snode")) { RouterID random; - if(GetRouter()->GetRandomGoodRouter(random)) + if (GetRouter()->GetRandomGoodRouter(random)) msg.AddCNAMEReply(random.ToString(), 1); else msg.AddNXReply(); } - else if(msg.questions[0].IsName("localhost.loki")) + else if (msg.questions[0].IsName("localhost.loki")) { RouterID us = m_Router->pubkey(); msg.AddAReply(us.ToString(), 1); @@ -141,15 +147,14 @@ namespace llarp else msg.AddNXReply(); } - else if(msg.questions[0].qtype == dns::qTypeA - || msg.questions[0].qtype == dns::qTypeAAAA) + else if (msg.questions[0].qtype == dns::qTypeA || msg.questions[0].qtype == dns::qTypeAAAA) { const bool isV6 = msg.questions[0].qtype == dns::qTypeAAAA; const bool isV4 = msg.questions[0].qtype == dns::qTypeA; - if(msg.questions[0].IsName("random.snode")) + if (msg.questions[0].IsName("random.snode")) { RouterID random; - if(GetRouter()->GetRandomGoodRouter(random)) + if (GetRouter()->GetRandomGoodRouter(random)) { msg.AddCNAMEReply(random.ToString(), 1); auto ip = ObtainServiceNodeIP(random); @@ -160,7 +165,7 @@ namespace llarp reply(msg); return true; } - if(msg.questions[0].IsName("localhost.loki")) + if (msg.questions[0].IsName("localhost.loki")) { msg.AddINReply(GetIfAddr(), isV6); reply(msg); @@ -168,36 +173,35 @@ namespace llarp } // forward dns for snode RouterID r; - if(r.FromString(msg.questions[0].Name())) + if (r.FromString(msg.questions[0].Name())) { huint128_t ip; PubKey pubKey(r); - if(isV4 && SupportsV6()) + if (isV4 && SupportsV6()) { msg.hdr_fields |= dns::flags_QR | dns::flags_AA | dns::flags_RA; } - else if(m_SNodeKeys.find(pubKey) == m_SNodeKeys.end()) + else if (m_SNodeKeys.find(pubKey) == m_SNodeKeys.end()) { // we do not have it mapped, async obtain it - ObtainSNodeSession( - r, [&](std::shared_ptr< exit::BaseSession > session) { - if(session && session->IsReady()) - { - msg.AddINReply(m_KeyToIP[pubKey], isV6); - } - else - { - msg.AddNXReply(); - } - reply(msg); - }); + ObtainSNodeSession(r, [&](std::shared_ptr session) { + if (session && session->IsReady()) + { + msg.AddINReply(m_KeyToIP[pubKey], isV6); + } + else + { + msg.AddNXReply(); + } + reply(msg); + }); return true; } else { // we have it mapped already as a service node auto itr = m_KeyToIP.find(pubKey); - if(itr != m_KeyToIP.end()) + if (itr != m_KeyToIP.end()) { ip = itr->second; msg.AddINReply(ip, isV6); @@ -214,8 +218,7 @@ namespace llarp } void - ExitEndpoint::ObtainSNodeSession(const RouterID &router, - exit::SessionReadyFunc obtainCb) + ExitEndpoint::ObtainSNodeSession(const RouterID& router, exit::SessionReadyFunc obtainCb) { ObtainServiceNodeIP(router); m_SNodeSessions[router]->AddReadyHook(obtainCb); @@ -229,13 +232,13 @@ namespace llarp bool ExitEndpoint::VisitEndpointsFor( - const PubKey &pk, std::function< bool(exit::Endpoint *const) > visit) + const PubKey& pk, std::function visit) { auto range = m_ActiveExits.equal_range(pk); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { - if(visit(itr->second.get())) + if (visit(itr->second.get())) ++itr; else return true; @@ -246,55 +249,60 @@ namespace llarp void ExitEndpoint::Flush() { - m_InetToNetwork.Process([&](Pkt_t &pkt) { + m_InetToNetwork.Process([&](Pkt_t& pkt) { PubKey pk; { auto itr = m_IPToKey.find(pkt.dstv6()); - if(itr == m_IPToKey.end()) + if (itr == m_IPToKey.end()) { // drop - LogWarn(Name(), " dropping packet, has no session at ", - pkt.dstv6()); + LogWarn(Name(), " dropping packet, has no session at ", pkt.dstv6()); return; } pk = itr->second; } // check if this key is a service node - if(m_SNodeKeys.find(pk) != m_SNodeKeys.end()) + if (m_SNodeKeys.find(pk) != m_SNodeKeys.end()) { // check if it's a service node session we made and queue it via our // snode session that we made otherwise use an inbound session that // was made by the other service node auto itr = m_SNodeSessions.find(pk); - if(itr != m_SNodeSessions.end()) + if (itr != m_SNodeSessions.end()) { - if(itr->second->QueueUpstreamTraffic(pkt, routing::ExitPadSize)) + if (itr->second->QueueUpstreamTraffic(pkt, routing::ExitPadSize)) return; } } - auto tryFlushingTraffic = [&](exit::Endpoint *const ep) -> bool { - if(!ep->QueueInboundTraffic(ManagedBuffer{pkt.Buffer()})) + auto tryFlushingTraffic = [&](exit::Endpoint* const ep) -> bool { + if (!ep->QueueInboundTraffic(ManagedBuffer{pkt.Buffer()})) { - 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; } // break iteration return false; }; - if(!VisitEndpointsFor(pk, tryFlushingTraffic)) + 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"); } }); { auto itr = m_ActiveExits.begin(); - while(itr != m_ActiveExits.end()) + while (itr != m_ActiveExits.end()) { - if(!itr->second->Flush()) + if (!itr->second->Flush()) { LogWarn("exit session with ", itr->first, " dropped packets"); } @@ -303,13 +311,12 @@ namespace llarp } { auto itr = m_SNodeSessions.begin(); - while(itr != m_SNodeSessions.end()) + while (itr != m_SNodeSessions.end()) { // TODO: move flush upstream to router event loop - if(!itr->second->FlushUpstream()) + if (!itr->second->FlushUpstream()) { - LogWarn("failed to flush snode traffic to ", itr->first, - " via outbound session"); + LogWarn("failed to flush snode traffic to ", itr->first, " via outbound session"); } itr->second->FlushDownstream(); ++itr; @@ -324,26 +331,25 @@ namespace llarp // map our address const PubKey us(m_Router->pubkey()); const huint128_t ip = GetIfAddr(); - m_KeyToIP[us] = ip; - m_IPToKey[ip] = us; - m_IPActivity[ip] = std::numeric_limits< llarp_time_t >::max(); + m_KeyToIP[us] = ip; + m_IPToKey[ip] = us; + m_IPActivity[ip] = std::numeric_limits::max(); m_SNodeKeys.insert(us); - if(m_ShouldInitTun) + if (m_ShouldInitTun) { auto loop = GetRouter()->netloop(); - if(!llarp_ev_add_tun(loop.get(), &m_Tun)) + if (!llarp_ev_add_tun(loop.get(), &m_Tun)) { llarp::LogWarn("Could not create tunnel for exit endpoint"); return false; } - llarp::LogInfo("Trying to start resolver ", - m_LocalResolverAddr.ToString()); + llarp::LogInfo("Trying to start resolver ", m_LocalResolverAddr.ToString()); return m_Resolver->Start(m_LocalResolverAddr, m_UpstreamResolvers); } return true; } - AbstractRouter * + AbstractRouter* ExitEndpoint::GetRouter() { return m_Router; @@ -358,7 +364,7 @@ namespace llarp bool ExitEndpoint::Stop() { - for(auto &item : m_SNodeSessions) + for (auto& item : m_SNodeSessions) item.second->Stop(); return true; } @@ -366,14 +372,14 @@ namespace llarp bool ExitEndpoint::ShouldRemove() const { - for(auto &item : m_SNodeSessions) - if(!item.second->ShouldRemove()) + for (auto& item : m_SNodeSessions) + if (!item.second->ShouldRemove()) return false; return true; } bool - ExitEndpoint::HasLocalMappedAddrFor(const PubKey &pk) const + ExitEndpoint::HasLocalMappedAddrFor(const PubKey& pk) const { return m_KeyToIP.find(pk) != m_KeyToIP.end(); } @@ -382,21 +388,21 @@ namespace llarp ExitEndpoint::GetIPForIdent(const PubKey pk) { huint128_t found = {0}; - if(!HasLocalMappedAddrFor(pk)) + if (!HasLocalMappedAddrFor(pk)) { // allocate and map found.h = AllocateNewAddress().h; - if(!m_KeyToIP.emplace(pk, found).second) + if (!m_KeyToIP.emplace(pk, found).second) { LogError(Name(), "failed to map ", pk, " to ", found); return found; } - if(!m_IPToKey.emplace(found, pk).second) + if (!m_IPToKey.emplace(found, pk).second) { LogError(Name(), "failed to map ", found, " to ", pk); return found; } - if(HasLocalMappedAddrFor(pk)) + if (HasLocalMappedAddrFor(pk)) LogInfo(Name(), " mapping ", pk, " to ", found); else LogError(Name(), "failed to map ", pk, " to ", found); @@ -413,19 +419,19 @@ namespace llarp huint128_t ExitEndpoint::AllocateNewAddress() { - if(m_NextAddr < m_HigestAddr) + if (m_NextAddr < m_HigestAddr) return ++m_NextAddr; // find oldest activity ip address huint128_t found = {0}; - llarp_time_t min = std::numeric_limits< llarp_time_t >::max(); - auto itr = m_IPActivity.begin(); - while(itr != m_IPActivity.end()) + llarp_time_t min = std::numeric_limits::max(); + auto itr = m_IPActivity.begin(); + while (itr != m_IPActivity.end()) { - if(itr->second < min) + if (itr->second < min) { found.h = itr->first.h; - min = itr->second; + min = itr->second; } ++itr; } @@ -438,21 +444,21 @@ namespace llarp } bool - ExitEndpoint::QueueOutboundTraffic(const llarp_buffer_t &buf) + ExitEndpoint::QueueOutboundTraffic(const llarp_buffer_t& buf) { return llarp_ev_tun_async_write(&m_Tun, buf); } void - ExitEndpoint::KickIdentOffExit(const PubKey &pk) + ExitEndpoint::KickIdentOffExit(const PubKey& pk) { LogInfo(Name(), " kicking ", pk, " off exit"); huint128_t ip = m_KeyToIP[pk]; m_KeyToIP.erase(pk); m_IPToKey.erase(ip); - auto range = m_ActiveExits.equal_range(pk); + auto range = m_ActiveExits.equal_range(pk); auto exit_itr = range.first; - while(exit_itr != range.second) + while (exit_itr != range.second) exit_itr = m_ActiveExits.erase(exit_itr); } @@ -463,46 +469,44 @@ namespace llarp } void - ExitEndpoint::OnInetPacket(std::vector< byte_t > buf) + ExitEndpoint::OnInetPacket(std::vector buf) { const llarp_buffer_t buffer(buf); m_InetToNetwork.EmplaceIf( - [b = ManagedBuffer(buffer)](Pkt_t &pkt) -> bool { - return pkt.Load(b); - }); + [b = ManagedBuffer(buffer)](Pkt_t& pkt) -> bool { return pkt.Load(b); }); } bool - ExitEndpoint::QueueSNodePacket(const llarp_buffer_t &buf, huint128_t from) + ExitEndpoint::QueueSNodePacket(const llarp_buffer_t& buf, huint128_t from) { net::IPPacket pkt; - if(!pkt.Load(buf)) + if (!pkt.Load(buf)) return false; // rewrite ip - if(m_UseV6) + if (m_UseV6) pkt.UpdateIPv6Address(from, m_IfAddr); else - pkt.UpdateIPv4Address(xhtonl(net::IPPacket::TruncateV6(from)), - xhtonl(net::IPPacket::TruncateV6(m_IfAddr))); + pkt.UpdateIPv4Address( + xhtonl(net::IPPacket::TruncateV6(from)), xhtonl(net::IPPacket::TruncateV6(m_IfAddr))); return llarp_ev_tun_async_write(&m_Tun, pkt.Buffer()); } - exit::Endpoint * - ExitEndpoint::FindEndpointByPath(const PathID_t &path) + exit::Endpoint* + ExitEndpoint::FindEndpointByPath(const PathID_t& path) { - exit::Endpoint *endpoint = nullptr; + exit::Endpoint* endpoint = nullptr; PubKey pk; { auto itr = m_Paths.find(path); - if(itr == m_Paths.end()) + if (itr == m_Paths.end()) return nullptr; pk = itr->second; } { auto itr = m_ActiveExits.find(pk); - if(itr != m_ActiveExits.end()) + if (itr != m_ActiveExits.end()) { - if(itr->second->PubKey() == pk) + if (itr->second->PubKey() == pk) endpoint = itr->second.get(); } } @@ -510,84 +514,91 @@ namespace llarp } bool - ExitEndpoint::UpdateEndpointPath(const PubKey &remote, const PathID_t &next) + ExitEndpoint::UpdateEndpointPath(const PubKey& remote, const PathID_t& next) { // check if already mapped auto itr = m_Paths.find(next); - if(itr != m_Paths.end()) + if (itr != m_Paths.end()) return false; m_Paths.emplace(next, remote); return true; } bool - ExitEndpoint::SetOption(const std::string &k, const std::string &v) + ExitEndpoint::SetOption(const std::string& k, const std::string& v) { - if(k == "type" && v == "null") + if (k == "type" && v == "null") { m_ShouldInitTun = false; return true; } - if(k == "exit") + if (k == "exit") { m_PermitExit = IsTrueValue(v.c_str()); return true; } - if(k == "local-dns") + if (k == "local-dns") { std::string resolverAddr = v; - uint16_t dnsport = 53; - auto pos = v.find(":"); - if(pos != std::string::npos) + uint16_t dnsport = 53; + auto pos = v.find(":"); + if (pos != std::string::npos) { resolverAddr = v.substr(0, pos); - dnsport = std::atoi(v.substr(pos + 1).c_str()); + dnsport = std::atoi(v.substr(pos + 1).c_str()); } m_LocalResolverAddr = Addr(resolverAddr, dnsport); LogInfo(Name(), " local dns set to ", m_LocalResolverAddr); } - if(k == "upstream-dns") + if (k == "upstream-dns") { std::string resolverAddr = v; - uint16_t dnsport = 53; - auto pos = v.find(":"); - if(pos != std::string::npos) + uint16_t dnsport = 53; + auto pos = v.find(":"); + if (pos != std::string::npos) { resolverAddr = v.substr(0, pos); - dnsport = std::atoi(v.substr(pos + 1).c_str()); + dnsport = std::atoi(v.substr(pos + 1).c_str()); } m_UpstreamResolvers.emplace_back(resolverAddr, dnsport); - LogInfo(Name(), " adding upstream dns set to ", resolverAddr, ":", - dnsport); + LogInfo(Name(), " adding upstream dns set to ", resolverAddr, ":", dnsport); } - if(k == "ifaddr") + if (k == "ifaddr") { - if(!m_OurRange.FromString(v)) + if (!m_OurRange.FromString(v)) { LogError(Name(), " has invalid address range: ", v); return false; } auto pos = v.find("/"); - if(pos == std::string::npos) + if (pos == std::string::npos) { LogError(Name(), " ifaddr is not a cidr: ", v); return false; } std::string nmask_str = v.substr(1 + pos); - std::string host_str = v.substr(0, pos); + std::string host_str = v.substr(0, pos); // string, or just a plain char array? strncpy(m_Tun.ifaddr, host_str.c_str(), sizeof(m_Tun.ifaddr) - 1); m_Tun.netmask = std::atoi(nmask_str.c_str()); - m_IfAddr = m_OurRange.addr; - m_NextAddr = m_IfAddr; - m_HigestAddr = m_OurRange.HighestAddr(); - LogInfo(Name(), " set ifaddr range to ", m_Tun.ifaddr, "/", - m_Tun.netmask, " lo=", m_IfAddr, " hi=", m_HigestAddr); + m_IfAddr = m_OurRange.addr; + m_NextAddr = m_IfAddr; + m_HigestAddr = m_OurRange.HighestAddr(); + LogInfo( + Name(), + " set ifaddr range to ", + m_Tun.ifaddr, + "/", + m_Tun.netmask, + " lo=", + m_IfAddr, + " hi=", + m_HigestAddr); m_UseV6 = false; } - if(k == "ifname") + if (k == "ifname") { - if(v.length() >= sizeof(m_Tun.ifname)) + if (v.length() >= sizeof(m_Tun.ifname)) { LogError(Name() + " ifname '", v, "' is too long"); return false; @@ -595,13 +606,13 @@ namespace llarp strncpy(m_Tun.ifname, v.c_str(), sizeof(m_Tun.ifname) - 1); LogInfo(Name(), " set ifname to ", m_Tun.ifname); } - if(k == "exit-whitelist") + if (k == "exit-whitelist") { // add exit policy whitelist rule // TODO: implement me return true; } - if(k == "exit-blacklist") + if (k == "exit-blacklist") { // add exit policy blacklist rule // TODO: implement me @@ -612,22 +623,25 @@ namespace llarp } huint128_t - ExitEndpoint::ObtainServiceNodeIP(const RouterID &other) + ExitEndpoint::ObtainServiceNodeIP(const RouterID& other) { const PubKey pubKey(other); const PubKey us(m_Router->pubkey()); // just in case - if(pubKey == us) + if (pubKey == us) return m_IfAddr; huint128_t ip = GetIPForIdent(pubKey); - if(m_SNodeKeys.emplace(pubKey).second) + if (m_SNodeKeys.emplace(pubKey).second) { - auto session = std::make_shared< exit::SNodeSession >( + auto session = std::make_shared( other, - std::bind(&ExitEndpoint::QueueSNodePacket, this, - std::placeholders::_1, ip), - GetRouter(), 2, 1, true, false); + std::bind(&ExitEndpoint::QueueSNodePacket, this, std::placeholders::_1, ip), + GetRouter(), + 2, + 1, + true, + false); // this is a new service node make an outbound session to them m_SNodeSessions.emplace(other, session); } @@ -635,22 +649,19 @@ namespace llarp } bool - ExitEndpoint::AllocateNewExit(const PubKey pk, const PathID_t &path, - bool wantInternet) + ExitEndpoint::AllocateNewExit(const PubKey pk, const PathID_t& path, bool wantInternet) { - if(wantInternet && !m_PermitExit) + if (wantInternet && !m_PermitExit) return false; auto ip = GetIPForIdent(pk); - if(GetRouter()->pathContext().TransitHopPreviousIsRouter(path, - pk.as_array())) + if (GetRouter()->pathContext().TransitHopPreviousIsRouter(path, pk.as_array())) { // we think this path belongs to a service node // mark it as such so we don't make an outbound session to them m_SNodeKeys.emplace(pk.as_array()); } - m_ActiveExits.emplace(pk, - std::make_unique< exit::Endpoint >( - pk, path, !wantInternet, ip, this)); + m_ActiveExits.emplace( + pk, std::make_unique(pk, path, !wantInternet, ip, this)); m_Paths[path] = pk; @@ -664,19 +675,19 @@ namespace llarp } void - ExitEndpoint::DelEndpointInfo(const PathID_t &path) + ExitEndpoint::DelEndpointInfo(const PathID_t& path) { m_Paths.erase(path); } void - ExitEndpoint::RemoveExit(const exit::Endpoint *ep) + ExitEndpoint::RemoveExit(const exit::Endpoint* ep) { auto range = m_ActiveExits.equal_range(ep->PubKey()); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { - if(itr->second->LocalPath() == ep->LocalPath()) + if (itr->second->LocalPath() == ep->LocalPath()) { itr = m_ActiveExits.erase(itr); // now ep is gone af @@ -691,9 +702,9 @@ namespace llarp { { auto itr = m_SNodeSessions.begin(); - while(itr != m_SNodeSessions.end()) + while (itr != m_SNodeSessions.end()) { - if(itr->second->IsExpired(now)) + if (itr->second->IsExpired(now)) itr = m_SNodeSessions.erase(itr); else { @@ -705,9 +716,9 @@ namespace llarp { // expire auto itr = m_ActiveExits.begin(); - while(itr != m_ActiveExits.end()) + while (itr != m_ActiveExits.end()) { - if(itr->second->IsExpired(now)) + if (itr->second->IsExpired(now)) itr = m_ActiveExits.erase(itr); else ++itr; @@ -715,23 +726,22 @@ namespace llarp // pick chosen exits and tick m_ChosenExits.clear(); itr = m_ActiveExits.begin(); - while(itr != m_ActiveExits.end()) + while (itr != m_ActiveExits.end()) { // do we have an exit set for this key? - if(m_ChosenExits.find(itr->first) != m_ChosenExits.end()) + if (m_ChosenExits.find(itr->first) != m_ChosenExits.end()) { // yes - if(m_ChosenExits[itr->first]->createdAt < itr->second->createdAt) + if (m_ChosenExits[itr->first]->createdAt < itr->second->createdAt) { // if the iterators's exit is newer use it for the chosen exit for // key - if(!itr->second->LooksDead(now)) + if (!itr->second->LooksDead(now)) m_ChosenExits[itr->first] = itr->second.get(); } } - else if(!itr->second->LooksDead( - now)) // set chosen exit if not dead for key that doesn't - // have one yet + else if (!itr->second->LooksDead(now)) // set chosen exit if not dead for key that + // doesn't have one yet m_ChosenExits[itr->first] = itr->second.get(); // tick which clears the tx rx counters itr->second->Tick(now); diff --git a/llarp/handlers/exit.hpp b/llarp/handlers/exit.hpp index 8867b0380..43d5b2f1e 100644 --- a/llarp/handlers/exit.hpp +++ b/llarp/handlers/exit.hpp @@ -26,8 +26,7 @@ namespace llarp Name() const; bool - VisitEndpointsFor(const PubKey& pk, - std::function< bool(exit::Endpoint* const) > visit); + VisitEndpointsFor(const PubKey& pk, std::function visit); util::StatusObject ExtractStatus() const; @@ -39,12 +38,10 @@ namespace llarp ShouldHookDNSMessage(const dns::Message& msg) const override; bool - HandleHookedDNSMessage(dns::Message msg, - std::function< void(dns::Message) >) override; + HandleHookedDNSMessage(dns::Message msg, std::function) override; bool - AllocateNewExit(const PubKey pk, const PathID_t& path, - bool permitInternet); + AllocateNewExit(const PubKey pk, const PathID_t& path, bool permitInternet); exit::Endpoint* FindEndpointByPath(const PathID_t& path); @@ -57,7 +54,7 @@ namespace llarp /// handle ip packet from outside void - OnInetPacket(std::vector< byte_t > buf); + OnInetPacket(std::vector buf); AbstractRouter* GetRouter(); @@ -65,12 +62,12 @@ namespace llarp llarp_time_t Now() const; - template < typename Stats > + template void CalculateTrafficStats(Stats& stats) { auto itr = m_ActiveExits.begin(); - while(itr != m_ActiveExits.end()) + while (itr != m_ActiveExits.end()) { stats[itr->first].first += itr->second->TxRate(); stats[itr->first].second += itr->second->RxRate(); @@ -122,8 +119,7 @@ namespace llarp /// async obtain snode session and call callback when it's ready to send void - ObtainSNodeSession(const RouterID& router, - exit::SessionReadyFunc obtainCb); + ObtainSNodeSession(const RouterID& router, exit::SessionReadyFunc obtainCb); bool QueueSNodePacket(const llarp_buffer_t& buf, huint128_t from); @@ -135,33 +131,30 @@ namespace llarp KickIdentOffExit(const PubKey& pk); AbstractRouter* m_Router; - std::shared_ptr< dns::Proxy > m_Resolver; + std::shared_ptr m_Resolver; bool m_ShouldInitTun; std::string m_Name; bool m_PermitExit; - std::unordered_map< PathID_t, PubKey, PathID_t::Hash > m_Paths; + std::unordered_map m_Paths; - std::unordered_map< PubKey, exit::Endpoint*, PubKey::Hash > m_ChosenExits; + std::unordered_map m_ChosenExits; - std::unordered_multimap< PubKey, std::unique_ptr< exit::Endpoint >, - PubKey::Hash > - m_ActiveExits; + std::unordered_multimap, PubKey::Hash> m_ActiveExits; - using KeyMap_t = std::unordered_map< PubKey, huint128_t, PubKey::Hash >; + using KeyMap_t = std::unordered_map; KeyMap_t m_KeyToIP; - using SNodes_t = std::set< PubKey >; + using SNodes_t = std::set; /// set of pubkeys we treat as snodes SNodes_t m_SNodeKeys; using SNodeSessions_t = - std::unordered_map< RouterID, std::shared_ptr< exit::SNodeSession >, - RouterID::Hash >; + std::unordered_map, RouterID::Hash>; /// snode sessions we are talking to directly SNodeSessions_t m_SNodeSessions; - std::unordered_map< huint128_t, PubKey > m_IPToKey; + std::unordered_map m_IPToKey; huint128_t m_IfAddr; huint128_t m_HigestAddr; @@ -169,18 +162,22 @@ namespace llarp huint128_t m_NextAddr; IPRange m_OurRange; - std::unordered_map< huint128_t, llarp_time_t > m_IPActivity; + std::unordered_map m_IPActivity; llarp_tun_io m_Tun; Addr m_LocalResolverAddr; - std::vector< Addr > m_UpstreamResolvers; + std::vector m_UpstreamResolvers; using Pkt_t = net::IPPacket; - using PacketQueue_t = - util::CoDelQueue< Pkt_t, Pkt_t::GetTime, Pkt_t::PutTime, - Pkt_t::CompareOrder, Pkt_t::GetNow, util::NullMutex, - util::NullLock >; + using PacketQueue_t = util::CoDelQueue< + Pkt_t, + Pkt_t::GetTime, + Pkt_t::PutTime, + Pkt_t::CompareOrder, + Pkt_t::GetNow, + util::NullMutex, + util::NullLock>; /// internet to llarp packet queue PacketQueue_t m_InetToNetwork; diff --git a/llarp/handlers/null.hpp b/llarp/handlers/null.hpp index 5f25c8545..4d8518290 100644 --- a/llarp/handlers/null.hpp +++ b/llarp/handlers/null.hpp @@ -7,19 +7,17 @@ namespace llarp { namespace 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(const std::string &name, AbstractRouter *r, - llarp::service::Context *parent) + NullEndpoint(const std::string& name, AbstractRouter* r, llarp::service::Context* parent) : llarp::service::Endpoint(name, r, parent) { } virtual bool - HandleInboundPacket(const service::ConvoTag, const llarp_buffer_t &, - service::ProtocolType) override + HandleInboundPacket( + const service::ConvoTag, const llarp_buffer_t&, service::ProtocolType) override { return true; } diff --git a/llarp/handlers/tun.cpp b/llarp/handlers/tun.cpp index 801c6bc17..fe2f1f871 100644 --- a/llarp/handlers/tun.cpp +++ b/llarp/handlers/tun.cpp @@ -23,9 +23,9 @@ namespace llarp namespace handlers { void - TunEndpoint::FlushToUser(std::function< bool(net::IPPacket &) > send) + TunEndpoint::FlushToUser(std::function send) { - m_ExitMap.ForEachValue([](const auto &exit) { exit->FlushDownstream(); }); + m_ExitMap.ForEachValue([](const auto& exit) { exit->FlushDownstream(); }); // flush network to user m_NetworkToUserPktQueue.Process(send); } @@ -38,101 +38,98 @@ namespace llarp } void - TunEndpoint::tunifTick(llarp_tun_io *tun) + TunEndpoint::tunifTick(llarp_tun_io* tun) { - auto *self = static_cast< TunEndpoint * >(tun->user); + auto* self = static_cast(tun->user); const auto now = self->Now(); - if(self->ShouldFlushNow(now)) + if (self->ShouldFlushNow(now)) { self->m_LastFlushAt = now; LogicCall(self->m_router->logic(), [self]() { self->Flush(); }); } } - TunEndpoint::TunEndpoint(const std::string &nickname, AbstractRouter *r, - service::Context *parent, bool lazyVPN) + TunEndpoint::TunEndpoint( + const std::string& nickname, AbstractRouter* r, service::Context* parent, bool lazyVPN) : service::Endpoint(nickname, r, parent) - , m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop(), - r->netloop()) - , m_NetworkToUserPktQueue(nickname + "_recvq", r->netloop(), - r->netloop()) - , m_Resolver(std::make_shared< dns::Proxy >( + , m_UserToNetworkPktQueue(nickname + "_sendq", r->netloop(), r->netloop()) + , m_NetworkToUserPktQueue(nickname + "_recvq", r->netloop(), r->netloop()) + , m_Resolver(std::make_shared( r->netloop(), r->logic(), r->netloop(), r->logic(), this)) { - if(not lazyVPN) + if (not lazyVPN) { tunif.reset(new llarp_tun_io()); std::fill(tunif->ifaddr, tunif->ifaddr + sizeof(tunif->ifaddr), 0); std::fill(tunif->ifname, tunif->ifname + sizeof(tunif->ifname), 0); - tunif->netmask = 0; + tunif->netmask = 0; tunif->get_fd_promise = nullptr; - tunif->user = this; + tunif->user = this; // eh this shouldn't do anything on windows anyway - tunif->tick = &tunifTick; + tunif->tick = &tunifTick; tunif->before_write = &tunifBeforeWrite; - tunif->recvpkt = &tunifRecvPkt; + tunif->recvpkt = &tunifRecvPkt; } } util::StatusObject TunEndpoint::ExtractStatus() const { - auto obj = service::Endpoint::ExtractStatus(); + auto obj = service::Endpoint::ExtractStatus(); obj["ifaddr"] = m_OurRange.ToString(); - std::vector< std::string > resolvers; - for(const auto &addr : m_UpstreamResolvers) + std::vector resolvers; + for (const auto& addr : m_UpstreamResolvers) resolvers.emplace_back(addr.ToString()); obj["ustreamResolvers"] = resolvers; - obj["localResolver"] = m_LocalResolverAddr.ToString(); + obj["localResolver"] = m_LocalResolverAddr.ToString(); util::StatusObject ips{}; - for(const auto &item : m_IPActivity) + for (const auto& item : m_IPActivity) { util::StatusObject ipObj{{"lastActive", to_json(item.second)}}; std::string remoteStr; - AlignedBuffer< 32 > addr = m_IPToAddr.at(item.first); - if(m_SNodes.at(addr)) + AlignedBuffer<32> addr = m_IPToAddr.at(item.first); + if (m_SNodes.at(addr)) remoteStr = RouterID(addr.as_array()).ToString(); else remoteStr = service::Address(addr.as_array()).ToString(); - ipObj["remote"] = remoteStr; + ipObj["remote"] = remoteStr; std::string ipaddr = item.first.ToString(); - ips[ipaddr] = ipObj; + ips[ipaddr] = ipObj; } - obj["addrs"] = ips; - obj["ourIP"] = m_OurIP.ToString(); + obj["addrs"] = ips; + obj["ourIP"] = m_OurIP.ToString(); obj["nextIP"] = m_NextIP.ToString(); - obj["maxIP"] = m_MaxIP.ToString(); + obj["maxIP"] = m_MaxIP.ToString(); return obj; } bool - TunEndpoint::SetOption(const std::string &k, const std::string &v) + TunEndpoint::SetOption(const std::string& k, const std::string& v) { - if(k == "reachable") + if (k == "reachable") { - if(IsFalseValue(v)) + if (IsFalseValue(v)) { m_PublishIntroSet = false; LogInfo(Name(), " setting to be not reachable by default"); } - else if(IsTrueValue(v)) + else if (IsTrueValue(v)) { m_PublishIntroSet = true; LogInfo(Name(), " setting to be reachable by default"); } else { - LogError(Name(), " config option reachable = '", v, - "' does not make sense"); + LogError(Name(), " config option reachable = '", v, "' does not make sense"); return false; } } - if(k == "isolate-network" && IsTrueValue(v.c_str())) + if (k == "isolate-network" && IsTrueValue(v.c_str())) { #if defined(__linux__) LogInfo(Name(), " isolating network..."); - if(!SpawnIsolatedNetwork()) + if (!SpawnIsolatedNetwork()) { LogError(Name(), " failed to spawn isolated network"); return false; @@ -140,47 +137,45 @@ namespace llarp LogInfo(Name(), " booyeah network isolation succeeded"); return true; #else - LogError(Name(), - " network isolation is not supported on your platform"); + LogError(Name(), " network isolation is not supported on your platform"); return false; #endif } - if(k == "strict-connect") + if (k == "strict-connect") { RouterID connect; - if(!connect.FromString(v)) + if (!connect.FromString(v)) { LogError(Name(), " invalid snode for strict-connect: ", v); return false; } RouterContact rc; - if(!m_router->nodedb()->Get(connect, rc)) + if (!m_router->nodedb()->Get(connect, rc)) { - LogError(Name(), " we don't have the RC for ", v, - " so we can't use it in strict-connect"); + LogError( + Name(), " we don't have the RC for ", v, " so we can't use it in strict-connect"); return false; } - for(const auto &ai : rc.addrs) + for (const auto& ai : rc.addrs) { m_StrictConnectAddrs.emplace_back(ai); - LogInfo(Name(), " added ", m_StrictConnectAddrs.back(), - " to strict connect"); + LogInfo(Name(), " added ", m_StrictConnectAddrs.back(), " to strict connect"); } return true; } // Name won't be set because we need to read the config before we can read // the keyfile - if(k == "exit-node") + if (k == "exit-node") { IPRange exitRange; llarp::RouterID exitRouter; std::string routerStr; const auto pos = v.find(","); - if(pos != std::string::npos) + if (pos != std::string::npos) { auto range_str = v.substr(1 + pos); - if(!exitRange.FromString(range_str)) + if (!exitRange.FromString(range_str)) { LogError("bad exit range: '", range_str, "'"); return false; @@ -192,63 +187,65 @@ namespace llarp routerStr = v; } routerStr = str(TrimWhitespace(routerStr)); - if(!(exitRouter.FromString(routerStr) - || HexDecode(routerStr.c_str(), exitRouter.begin(), - exitRouter.size()))) + if (!(exitRouter.FromString(routerStr) + || HexDecode(routerStr.c_str(), exitRouter.begin(), exitRouter.size()))) { llarp::LogError(Name(), " bad exit router key: ", routerStr); return false; } - auto exit = std::make_shared< llarp::exit::ExitSession >( + auto exit = std::make_shared( exitRouter, util::memFn(&TunEndpoint::QueueInboundPacketForExit, this), - m_router, numPaths, numHops, ShouldBundleRC()); + m_router, + numPaths, + numHops, + ShouldBundleRC()); m_ExitMap.Insert(exitRange, exit); - llarp::LogInfo(Name(), " using exit at ", exitRouter, " for ", - exitRange); + llarp::LogInfo(Name(), " using exit at ", exitRouter, " for ", exitRange); } - if(k == "local-dns") + if (k == "local-dns") { std::string resolverAddr = v; - uint16_t dnsport = 53; - auto pos = v.find(":"); - if(pos != std::string::npos) + uint16_t dnsport = 53; + auto pos = v.find(":"); + if (pos != std::string::npos) { resolverAddr = v.substr(0, pos); - dnsport = std::atoi(v.substr(pos + 1).c_str()); + dnsport = std::atoi(v.substr(pos + 1).c_str()); } m_LocalResolverAddr = llarp::Addr(resolverAddr, dnsport); // this field is ignored on all other platforms tunif->dnsaddr = m_LocalResolverAddr.ton(); llarp::LogInfo(Name(), " binding DNS server to ", m_LocalResolverAddr); } - if(k == "upstream-dns") + if (k == "upstream-dns") { std::string resolverAddr = v; - uint16_t dnsport = 53; - auto pos = v.find(":"); - if(pos != std::string::npos) + uint16_t dnsport = 53; + auto pos = v.find(":"); + if (pos != std::string::npos) { resolverAddr = v.substr(0, pos); - dnsport = std::atoi(v.substr(pos + 1).c_str()); + dnsport = std::atoi(v.substr(pos + 1).c_str()); } m_UpstreamResolvers.emplace_back(resolverAddr, dnsport); - llarp::LogInfo(Name(), " adding upstream DNS server ", resolverAddr, - ":", dnsport); + llarp::LogInfo(Name(), " adding upstream DNS server ", resolverAddr, ":", dnsport); } - if(k == "mapaddr") + if (k == "mapaddr") { auto pos = v.find(":"); - if(pos == std::string::npos) + if (pos == std::string::npos) { - llarp::LogError("Cannot map address ", v, - " invalid format, missing colon (:), expects " - "address.loki:ip.address.goes.here"); + llarp::LogError( + "Cannot map address ", + v, + " invalid format, missing colon (:), expects " + "address.loki:ip.address.goes.here"); return false; } service::Address addr; auto addr_str = v.substr(0, pos); - if(!addr.FromString(addr_str)) + if (!addr.FromString(addr_str)) { llarp::LogError(Name() + " cannot map invalid address ", addr_str); return false; @@ -256,24 +253,23 @@ namespace llarp auto ip_str = v.substr(pos + 1); huint32_t ip; huint128_t ipv6; - if(ip.FromString(ip_str)) + if (ip.FromString(ip_str)) { ipv6 = net::IPPacket::ExpandV4(ip); } - else if(ipv6.FromString(ip_str)) + else if (ipv6.FromString(ip_str)) { } else { - llarp::LogError(Name(), "failed to map ", ip_str, - " failed to parse IP"); + llarp::LogError(Name(), "failed to map ", ip_str, " failed to parse IP"); return false; } return MapAddress(addr, ipv6, false); } - if(k == "ifname" && tunif) + if (k == "ifname" && tunif) { - if(v.length() >= sizeof(tunif->ifname)) + if (v.length() >= sizeof(tunif->ifname)) { llarp::LogError(Name() + " ifname '", v, "' is too long"); return false; @@ -282,12 +278,12 @@ namespace llarp llarp::LogInfo(Name() + " setting ifname to ", tunif->ifname); return true; } - if(k == "ifaddr" && tunif) + if (k == "ifaddr" && tunif) { std::string addr; - m_UseV6 = addr.find(":") != std::string::npos; + m_UseV6 = addr.find(":") != std::string::npos; auto pos = v.find("/"); - if(pos != std::string::npos) + if (pos != std::string::npos) { int num; std::string part = v.substr(pos + 1); @@ -296,10 +292,10 @@ namespace llarp #else num = std::stoi(part); #endif - if(num > 0) + if (num > 0) { tunif->netmask = num; - addr = v.substr(0, pos); + addr = v.substr(0, pos); } else { @@ -309,14 +305,13 @@ namespace llarp } else { - if(m_UseV6) + if (m_UseV6) tunif->netmask = 128; else tunif->netmask = 32; addr = v; } - llarp::LogInfo(Name() + " set ifaddr to ", addr, " with netmask ", - tunif->netmask); + llarp::LogInfo(Name() + " set ifaddr to ", addr, " with netmask ", tunif->netmask); strncpy(tunif->ifaddr, addr.c_str(), sizeof(tunif->ifaddr) - 1); return true; } @@ -324,16 +319,16 @@ namespace llarp } bool - TunEndpoint::HasLocalIP(const huint128_t &ip) const + TunEndpoint::HasLocalIP(const huint128_t& ip) const { return m_IPToAddr.find(ip) != m_IPToAddr.end(); } bool - TunEndpoint::QueueOutboundTraffic(llarp::net::IPPacket &&pkt) + TunEndpoint::QueueOutboundTraffic(llarp::net::IPPacket&& pkt) { return m_NetworkToUserPktQueue.EmplaceIf( - [](llarp::net::IPPacket &) -> bool { return true; }, std::move(pkt)); + [](llarp::net::IPPacket&) -> bool { return true; }, std::move(pkt)); } void @@ -341,11 +336,10 @@ namespace llarp { static const auto func = [](auto self) { self->FlushSend(); - self->m_ExitMap.ForEachValue( - [](const auto &exit) { exit->FlushUpstream(); }); + self->m_ExitMap.ForEachValue([](const auto& exit) { exit->FlushUpstream(); }); self->Pump(self->Now()); }; - if(NetworkIsIsolated()) + if (NetworkIsIsolated()) { LogicCall(RouterLogic(), std::bind(func, shared_from_this())); } @@ -356,23 +350,23 @@ namespace llarp } static bool - is_random_snode(const dns::Message &msg) + is_random_snode(const dns::Message& msg) { return msg.questions[0].IsName("random.snode"); } static bool - is_localhost_loki(const dns::Message &msg) + is_localhost_loki(const dns::Message& msg) { return msg.questions[0].IsName("localhost.loki"); } template <> bool - TunEndpoint::FindAddrForIP(service::Address &addr, huint128_t ip) + TunEndpoint::FindAddrForIP(service::Address& addr, huint128_t ip) { auto itr = m_IPToAddr.find(ip); - if(itr != m_IPToAddr.end() and not m_SNodes[itr->second]) + if (itr != m_IPToAddr.end() and not m_SNodes[itr->second]) { addr = service::Address(itr->second.as_array()); return true; @@ -382,10 +376,10 @@ namespace llarp template <> bool - TunEndpoint::FindAddrForIP(RouterID &addr, huint128_t ip) + TunEndpoint::FindAddrForIP(RouterID& addr, huint128_t ip) { auto itr = m_IPToAddr.find(ip); - if(itr != m_IPToAddr.end() and m_SNodes[itr->second]) + if (itr != m_IPToAddr.end() and m_SNodes[itr->second]) { addr = RouterID(itr->second.as_array()); return true; @@ -393,8 +387,8 @@ namespace llarp return false; } - static dns::Message & - clear_dns_message(dns::Message &msg) + static dns::Message& + clear_dns_message(dns::Message& msg) { msg.authorities.resize(0); msg.additional.resize(0); @@ -404,23 +398,19 @@ namespace llarp } bool - TunEndpoint::HandleHookedDNSMessage( - dns::Message msg, std::function< void(dns::Message) > reply) + TunEndpoint::HandleHookedDNSMessage(dns::Message msg, std::function reply) { auto ReplyToSNodeDNSWhenReady = [self = this, reply = reply]( - RouterID snode, auto msg, - bool isV6) -> bool { - return self->EnsurePathToSNode( - snode, [=](const RouterID &, exit::BaseSession_ptr s) { - self->SendDNSReply(snode, s, msg, reply, true, isV6); - }); + RouterID snode, auto msg, bool isV6) -> bool { + return self->EnsurePathToSNode(snode, [=](const RouterID&, exit::BaseSession_ptr s) { + self->SendDNSReply(snode, s, msg, reply, true, isV6); + }); }; auto ReplyToLokiDNSWhenReady = [self = this, reply = reply]( - service::Address addr, auto msg, - bool isV6) -> bool { + service::Address addr, auto msg, bool isV6) -> bool { using service::Address; using service::OutboundContext; - if(self->HasAddress(addr)) + if (self->HasAddress(addr)) { const auto ip = self->ObtainIPForAddr(addr, false); msg->AddINReply(ip, isV6); @@ -429,154 +419,147 @@ namespace llarp } return self->EnsurePathToService( addr, - [=](const Address &, OutboundContext *ctx) { + [=](const Address&, OutboundContext* ctx) { self->SendDNSReply(addr, ctx, msg, reply, false, isV6); }, 2s); }; std::string qname; - if(msg.answers.size() > 0) + if (msg.answers.size() > 0) { - const auto &answer = msg.answers[0]; - if(answer.HasCNameForTLD(".snode")) + const auto& answer = msg.answers[0]; + if (answer.HasCNameForTLD(".snode")) { dns::Name_t qname; llarp_buffer_t buf(answer.rData); - if(not dns::DecodeName(&buf, qname, true)) + if (not dns::DecodeName(&buf, qname, true)) return false; RouterID addr; - if(not addr.FromString(qname)) + if (not addr.FromString(qname)) return false; - auto replyMsg = - std::make_shared< dns::Message >(clear_dns_message(msg)); + auto replyMsg = std::make_shared(clear_dns_message(msg)); return ReplyToSNodeDNSWhenReady(addr, std::move(replyMsg), false); } - else if(answer.HasCNameForTLD(".loki")) + else if (answer.HasCNameForTLD(".loki")) { dns::Name_t qname; llarp_buffer_t buf(answer.rData); - if(not dns::DecodeName(&buf, qname, true)) + if (not dns::DecodeName(&buf, qname, true)) return false; service::Address addr; - if(not addr.FromString(qname)) + if (not addr.FromString(qname)) return false; - auto replyMsg = - std::make_shared< dns::Message >(clear_dns_message(msg)); + auto replyMsg = std::make_shared(clear_dns_message(msg)); return ReplyToLokiDNSWhenReady(addr, replyMsg, false); } } - if(msg.questions.size() != 1) + if (msg.questions.size() != 1) { llarp::LogWarn("bad number of dns questions: ", msg.questions.size()); return false; } qname = msg.questions[0].Name(); - if(msg.questions[0].qtype == dns::qTypeMX) + if (msg.questions[0].qtype == dns::qTypeMX) { // 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 msg.AddNXReply(); reply(msg); } - else if(msg.questions[0].qtype == dns::qTypeCNAME) + else if (msg.questions[0].qtype == dns::qTypeCNAME) { - if(is_random_snode(msg)) + if (is_random_snode(msg)) { RouterID random; - if(Router()->GetRandomGoodRouter(random)) + if (Router()->GetRandomGoodRouter(random)) { msg.AddCNAMEReply(random.ToString(), 1); } else msg.AddNXReply(); } - else if(is_localhost_loki(msg)) + else if (is_localhost_loki(msg)) { 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) -> bool { const service::Address addr = service->GetIdentity().pub.Addr(); msg.AddCNAMEReply(addr.ToString(), 1); ++counter; return true; }); - if(counter == 0) + if (counter == 0) msg.AddNXReply(); } else msg.AddNXReply(); reply(msg); } - else if(msg.questions[0].qtype == dns::qTypeA - || msg.questions[0].qtype == dns::qTypeAAAA) + else if (msg.questions[0].qtype == dns::qTypeA || msg.questions[0].qtype == dns::qTypeAAAA) { const bool isV6 = msg.questions[0].qtype == dns::qTypeAAAA; const bool isV4 = msg.questions[0].qtype == dns::qTypeA; llarp::service::Address addr; - if(isV6 && !SupportsV6()) + if (isV6 && !SupportsV6()) { // empty reply but not a NXDOMAIN so that client can retry IPv4 msg.AddNSReply("localhost.loki."); } // on MacOS this is a typeA query - else if(is_random_snode(msg)) + else if (is_random_snode(msg)) { RouterID random; - if(Router()->GetRandomGoodRouter(random)) + if (Router()->GetRandomGoodRouter(random)) { msg.AddCNAMEReply(random.ToString(), 1); - return ReplyToSNodeDNSWhenReady( - random, std::make_shared< dns::Message >(msg), isV6); + return ReplyToSNodeDNSWhenReady(random, std::make_shared(msg), isV6); } else msg.AddNXReply(); } - else if(is_localhost_loki(msg)) + else if (is_localhost_loki(msg)) { size_t counter = 0; context->ForEachService( - [&](const std::string &, - const std::shared_ptr< service::Endpoint > &service) -> bool { - if(!service->HasIfAddr()) + [&](const std::string&, const std::shared_ptr& service) -> bool { + if (!service->HasIfAddr()) return true; huint128_t ip = service->GetIfAddr(); - if(ip.h) + if (ip.h) { msg.AddINReply(ip, isV6); ++counter; } return true; }); - if(counter == 0) + if (counter == 0) msg.AddNXReply(); } - else if(addr.FromString(qname, ".loki")) + else if (addr.FromString(qname, ".loki")) { - if(isV4 && SupportsV6()) + if (isV4 && SupportsV6()) { msg.hdr_fields |= dns::flags_QR | dns::flags_AA | dns::flags_RA; } else { - return ReplyToLokiDNSWhenReady( - addr, std::make_shared< dns::Message >(msg), isV6); + return ReplyToLokiDNSWhenReady(addr, std::make_shared(msg), isV6); } } - else if(addr.FromString(qname, ".snode")) + else if (addr.FromString(qname, ".snode")) { - if(isV4 && SupportsV6()) + if (isV4 && SupportsV6()) { msg.hdr_fields |= dns::flags_QR | dns::flags_AA | dns::flags_RA; } else { return ReplyToSNodeDNSWhenReady( - addr.as_array(), std::make_shared< dns::Message >(msg), isV6); + addr.as_array(), std::make_shared(msg), isV6); } } else @@ -584,25 +567,25 @@ namespace llarp reply(msg); } - else if(msg.questions[0].qtype == dns::qTypePTR) + else if (msg.questions[0].qtype == dns::qTypePTR) { // reverse dns huint128_t ip = {0}; - if(!dns::DecodePTR(msg.questions[0].qname, ip)) + if (!dns::DecodePTR(msg.questions[0].qname, ip)) { msg.AddNXReply(); reply(msg); return true; } RouterID snodeAddr; - if(FindAddrForIP(snodeAddr, ip)) + if (FindAddrForIP(snodeAddr, ip)) { msg.AddAReply(snodeAddr.ToString()); reply(msg); return true; } service::Address lokiAddr; - if(FindAddrForIP(lokiAddr, ip)) + if (FindAddrForIP(lokiAddr, ip)) { msg.AddAReply(lokiAddr.ToString()); reply(msg); @@ -624,8 +607,7 @@ namespace llarp TunEndpoint::ResetInternalState() { service::Endpoint::ResetInternalState(); - m_ExitMap.ForEachValue( - [](const auto &exit) { exit->ResetInternalState(); }); + m_ExitMap.ForEachValue([](const auto& exit) { exit->ResetInternalState(); }); } bool @@ -636,52 +618,51 @@ namespace llarp // FIXME: pass in which question it should be addressing bool - TunEndpoint::ShouldHookDNSMessage(const dns::Message &msg) const + TunEndpoint::ShouldHookDNSMessage(const dns::Message& msg) const { llarp::service::Address addr; - if(msg.questions.size() == 1) + if (msg.questions.size() == 1) { /// hook every .loki - if(msg.questions[0].HasTLD(".loki")) + if (msg.questions[0].HasTLD(".loki")) return true; /// hook every .snode - if(msg.questions[0].HasTLD(".snode")) + if (msg.questions[0].HasTLD(".snode")) return true; // hook any ranges we own - if(msg.questions[0].qtype == llarp::dns::qTypePTR) + if (msg.questions[0].qtype == llarp::dns::qTypePTR) { huint128_t ip = {0}; - if(!dns::DecodePTR(msg.questions[0].qname, ip)) + if (!dns::DecodePTR(msg.questions[0].qname, ip)) return false; return m_OurRange.Contains(ip); } } - for(const auto &answer : msg.answers) + for (const auto& answer : msg.answers) { - if(answer.HasCNameForTLD(".loki")) + if (answer.HasCNameForTLD(".loki")) return true; - if(answer.HasCNameForTLD(".snode")) + if (answer.HasCNameForTLD(".snode")) return true; } return false; } bool - TunEndpoint::MapAddress(const service::Address &addr, huint128_t ip, - bool SNode) + TunEndpoint::MapAddress(const service::Address& addr, huint128_t ip, bool SNode) { auto itr = m_IPToAddr.find(ip); - if(itr != m_IPToAddr.end()) + 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); - m_IPToAddr[ip] = addr; + m_IPToAddr[ip] = addr; m_AddrToIP[addr] = ip; - m_SNodes[addr] = SNode; + m_SNodes[addr] = SNode; MarkIPActiveForever(ip); return true; } @@ -689,14 +670,14 @@ namespace llarp bool TunEndpoint::Start() { - if(!Endpoint::Start()) + if (!Endpoint::Start()) { llarp::LogWarn("Couldn't start endpoint"); return false; } const auto blacklist = SnodeBlacklist(); - m_ExitMap.ForEachValue([blacklist](const auto &exit) { - for(const auto &snode : blacklist) + m_ExitMap.ForEachValue([blacklist](const auto& exit) { + for (const auto& snode : blacklist) exit->BlacklistSnode(snode); }); return SetupNetworking(); @@ -715,12 +696,12 @@ namespace llarp lazy_vpn vpn; huint32_t ip; auto loop = EndpointNetLoop(); - if(tunif == nullptr) + if (tunif == nullptr) { llarp::LogInfo(Name(), " waiting for vpn to start"); - vpn = m_LazyVPNPromise.get_future().get(); + vpn = m_LazyVPNPromise.get_future().get(); vpnif = vpn.io; - if(vpnif == nullptr) + if (vpnif == nullptr) { llarp::LogError(Name(), " failed to recieve vpn interface"); return false; @@ -728,17 +709,17 @@ namespace llarp llarp::LogInfo(Name(), " got vpn interface"); auto self = shared_from_this(); // function to queue a packet to send to vpn interface - auto sendpkt = [self](net::IPPacket &pkt) -> bool { + auto sendpkt = [self](net::IPPacket& pkt) -> bool { // drop if no endpoint auto impl = self->GetVPNImpl(); // drop if no vpn interface - if(impl == nullptr) + if (impl == nullptr) return true; // drop if queue to vpn not enabled - if(not impl->reader.queue.enabled()) + if (not impl->reader.queue.enabled()) return true; // drop if queue to vpn full - if(impl->reader.queue.full()) + if (impl->reader.queue.full()) return true; // queue to reader impl->reader.queue.pushBack(pkt); @@ -746,101 +727,99 @@ namespace llarp }; // event loop ticker auto ticker = [self, sendpkt]() { - TunEndpoint *ep = self.get(); + TunEndpoint* ep = self.get(); const bool running = not ep->IsStopped(); - auto impl = ep->GetVPNImpl(); - if(impl) + auto impl = ep->GetVPNImpl(); + if (impl) { /// get packets from vpn - while(not impl->writer.queue.empty()) + while (not impl->writer.queue.empty()) { // queue it to be sent over lokinet auto pkt = impl->writer.queue.popFront(); - if(running) + if (running) ep->m_UserToNetworkPktQueue.Emplace(pkt); } } // process packets queued from vpn - if(running) + if (running) { ep->Flush(); ep->FlushToUser(sendpkt); } // if impl has a tick function call it - if(impl && impl->parent && impl->parent->tick) + if (impl && impl->parent && impl->parent->tick) impl->parent->tick(impl->parent); }; - if(not loop->add_ticker(ticker)) + if (not loop->add_ticker(ticker)) { llarp::LogError(Name(), " failed to add vpn to event loop"); - if(vpnif->injected) + if (vpnif->injected) vpnif->injected(vpnif, false); return false; } } else { - if(!llarp_ev_add_tun(loop.get(), tunif.get())) + if (!llarp_ev_add_tun(loop.get(), tunif.get())) { - llarp::LogError(Name(), - " failed to set up tun interface: ", tunif->ifaddr, - " on ", tunif->ifname); + llarp::LogError( + Name(), " failed to set up tun interface: ", tunif->ifaddr, " on ", tunif->ifname); return false; } } - const char *ifname; - const char *ifaddr; + const char* ifname; + const char* ifaddr; unsigned char netmask; - if(tunif) + if (tunif) { - ifname = tunif->ifname; - ifaddr = tunif->ifaddr; + ifname = tunif->ifname; + ifaddr = tunif->ifaddr; netmask = tunif->netmask; } else { - ifname = vpn.info.ifname; - ifaddr = vpn.info.ifaddr; + ifname = vpn.info.ifname; + ifaddr = vpn.info.ifaddr; netmask = vpn.info.netmask; } - if(ip.FromString(ifaddr)) + if (ip.FromString(ifaddr)) { - m_OurIP = net::IPPacket::ExpandV4(ip); + m_OurIP = net::IPPacket::ExpandV4(ip); m_OurRange.netmask_bits = netmask_ipv6_bits(netmask + 96); } - else if(m_OurIP.FromString(ifaddr)) + else if (m_OurIP.FromString(ifaddr)) { m_OurRange.netmask_bits = netmask_ipv6_bits(netmask); - m_UseV6 = true; + m_UseV6 = true; } else { LogError(Name(), " invalid interface address given, ifaddr=", ifaddr); - if(vpnif && vpnif->injected) + if (vpnif && vpnif->injected) vpnif->injected(vpnif, false); return false; } - m_NextIP = m_OurIP; + m_NextIP = m_OurIP; m_OurRange.addr = m_OurIP; - m_MaxIP = m_OurRange.HighestAddr(); + m_MaxIP = m_OurRange.HighestAddr(); llarp::LogInfo(Name(), " set ", ifname, " to have address ", m_OurIP); - llarp::LogInfo(Name(), " allocated up to ", m_MaxIP, " on range ", - m_OurRange); + llarp::LogInfo(Name(), " allocated up to ", m_MaxIP, " on range ", m_OurRange); const service::Address ourAddr = m_Identity.pub.Addr(); - if(not MapAddress(ourAddr, GetIfAddr(), false)) + if (not MapAddress(ourAddr, GetIfAddr(), false)) { return false; } - if(m_OnUp) + if (m_OnUp) { m_OnUp->NotifyAsync(NotifyParams()); } - if(vpnif && vpnif->injected) + if (vpnif && vpnif->injected) { vpnif->injected(vpnif, true); } @@ -848,16 +827,16 @@ namespace llarp return HasAddress(ourAddr); } - std::unordered_map< std::string, std::string > + std::unordered_map TunEndpoint::NotifyParams() const { auto env = Endpoint::NotifyParams(); env.emplace("IP_ADDR", m_OurIP.ToString()); env.emplace("IF_ADDR", m_OurRange.ToString()); - if(tunif) + if (tunif) env.emplace("IF_NAME", tunif->ifname); std::string strictConnect; - for(const auto &addr : m_StrictConnectAddrs) + for (const auto& addr : m_StrictConnectAddrs) strictConnect += addr.ToString() + " "; env.emplace("STRICT_CONNECT_ADDRS", strictConnect); return env; @@ -867,12 +846,12 @@ namespace llarp TunEndpoint::SetupNetworking() { llarp::LogInfo("Set Up networking for ", Name()); - if(!SetupTun()) + if (!SetupTun()) { llarp::LogError(Name(), " failed to set up network interface"); return false; } - if(!m_Resolver->Start(m_LocalResolverAddr, m_UpstreamResolvers)) + if (!m_Resolver->Start(m_LocalResolverAddr, m_UpstreamResolvers)) { // downgrade DNS server failure to a warning llarp::LogWarn(Name(), " failed to start dns server"); @@ -884,7 +863,7 @@ namespace llarp void TunEndpoint::Tick(llarp_time_t now) { - m_ExitMap.ForEachValue([&](const auto &exit) { + m_ExitMap.ForEachValue([&](const auto& exit) { this->EnsureRouterIsKnown(exit->Endpoint()); exit->Tick(now); }); @@ -894,62 +873,66 @@ namespace llarp bool TunEndpoint::Stop() { - m_ExitMap.ForEachValue([](const auto &exit) { exit->Stop(); }); + m_ExitMap.ForEachValue([](const auto& exit) { exit->Stop(); }); return llarp::service::Endpoint::Stop(); } void TunEndpoint::FlushSend() { - m_UserToNetworkPktQueue.Process([&](net::IPPacket &pkt) { - std::function< bool(const llarp_buffer_t &) > sendFunc; + m_UserToNetworkPktQueue.Process([&](net::IPPacket& pkt) { + std::function sendFunc; huint128_t dst; - if(pkt.IsV4()) + if (pkt.IsV4()) dst = net::IPPacket::ExpandV4(pkt.dstv4()); else dst = pkt.dstv6(); auto itr = m_IPToAddr.find(dst); - if(itr == m_IPToAddr.end()) + if (itr == m_IPToAddr.end()) { const auto exits = m_ExitMap.FindAll(dst); - for(const auto &exit : exits) + for (const auto& exit : exits) { - if(pkt.IsV4() && !llarp::IsIPv4Bogon(pkt.dstv4())) + if (pkt.IsV4() && !llarp::IsIPv4Bogon(pkt.dstv4())) { pkt.UpdateIPv4Address({0}, xhtonl(pkt.dstv4())); - exit->QueueUpstreamTraffic(std::move(pkt), - llarp::routing::ExitPadSize); + exit->QueueUpstreamTraffic(std::move(pkt), llarp::routing::ExitPadSize); } - else if(pkt.IsV6()) + else if (pkt.IsV6()) { pkt.UpdateIPv6Address({0}, pkt.dstv6()); - exit->QueueUpstreamTraffic(std::move(pkt), - llarp::routing::ExitPadSize); + exit->QueueUpstreamTraffic(std::move(pkt), llarp::routing::ExitPadSize); } } return; } - if(m_SNodes.at(itr->second)) + if (m_SNodes.at(itr->second)) { - sendFunc = std::bind(&TunEndpoint::SendToSNodeOrQueue, this, - itr->second.as_array(), std::placeholders::_1); + sendFunc = std::bind( + &TunEndpoint::SendToSNodeOrQueue, + this, + itr->second.as_array(), + std::placeholders::_1); } else { - sendFunc = std::bind(&TunEndpoint::SendToServiceOrQueue, this, - service::Address(itr->second.as_array()), - std::placeholders::_1, pkt.ServiceProtocol()); + sendFunc = std::bind( + &TunEndpoint::SendToServiceOrQueue, + this, + service::Address(itr->second.as_array()), + std::placeholders::_1, + pkt.ServiceProtocol()); } // prepare packet for insertion into network // this includes clearing IP addresses, recalculating checksums, etc - if(pkt.IsV4()) + if (pkt.IsV4()) pkt.UpdateIPv4Address({0}, {0}); else pkt.UpdateIPv6Address({0}, {0}); - if(sendFunc && sendFunc(pkt.Buffer())) + if (sendFunc && sendFunc(pkt.Buffer())) { MarkIPActive(dst); return; @@ -960,43 +943,41 @@ namespace llarp bool TunEndpoint::HandleWriteIPPacket( - const llarp_buffer_t &b, std::function< huint128_t(void) > getFromIP) + const llarp_buffer_t& b, std::function getFromIP) { // llarp::LogInfo("got packet from ", msg->sender.Addr()); auto themIP = getFromIP(); // llarp::LogInfo("themIP ", themIP); auto usIP = m_OurIP; ManagedBuffer buf(b); - return m_NetworkToUserPktQueue.EmplaceIf( - [buf, themIP, usIP](net::IPPacket &pkt) -> bool { - // load - if(!pkt.Load(buf)) - return false; - // filter out: - // - packets smaller than minimal IPv4 header - // - non-IPv4 packets - // - packets with weird src/dst addresses - // (0.0.0.0/8 but not 0.0.0.0) - // - packets with 0 src but non-0 dst and oposite - if(pkt.IsV4()) - { - auto hdr = pkt.Header(); - if(pkt.sz < sizeof(*hdr) - || (hdr->saddr != 0 && *(byte_t *)&(hdr->saddr) == 0) - || (hdr->daddr != 0 && *(byte_t *)&(hdr->daddr) == 0) - || ((hdr->saddr == 0) != (hdr->daddr == 0))) - { - return false; - } - pkt.UpdateIPv4Address(xhtonl(net::IPPacket::TruncateV6(themIP)), - xhtonl(net::IPPacket::TruncateV6(usIP))); - } - else if(pkt.IsV6()) - { - pkt.UpdateIPv6Address(themIP, usIP); - } - return true; - }); + return m_NetworkToUserPktQueue.EmplaceIf([buf, themIP, usIP](net::IPPacket& pkt) -> bool { + // load + if (!pkt.Load(buf)) + return false; + // filter out: + // - packets smaller than minimal IPv4 header + // - non-IPv4 packets + // - packets with weird src/dst addresses + // (0.0.0.0/8 but not 0.0.0.0) + // - packets with 0 src but non-0 dst and oposite + if (pkt.IsV4()) + { + auto hdr = pkt.Header(); + if (pkt.sz < sizeof(*hdr) || (hdr->saddr != 0 && *(byte_t*)&(hdr->saddr) == 0) + || (hdr->daddr != 0 && *(byte_t*)&(hdr->daddr) == 0) + || ((hdr->saddr == 0) != (hdr->daddr == 0))) + { + return false; + } + pkt.UpdateIPv4Address( + xhtonl(net::IPPacket::TruncateV6(themIP)), xhtonl(net::IPPacket::TruncateV6(usIP))); + } + else if (pkt.IsV6()) + { + pkt.UpdateIPv6Address(themIP, usIP); + } + return true; + }); } huint128_t @@ -1006,14 +987,14 @@ namespace llarp } huint128_t - TunEndpoint::ObtainIPForAddr(const AlignedBuffer< 32 > &ident, bool snode) + TunEndpoint::ObtainIPForAddr(const AlignedBuffer<32>& ident, bool snode) { - llarp_time_t now = Now(); + llarp_time_t now = Now(); huint128_t nextIP = {0}; { // previously allocated address auto itr = m_AddrToIP.find(ident); - if(itr != m_AddrToIP.end()) + if (itr != m_AddrToIP.end()) { // mark ip active MarkIPActive(itr->second); @@ -1021,18 +1002,17 @@ namespace llarp } } // allocate new address - if(m_NextIP < m_MaxIP) + if (m_NextIP < m_MaxIP) { do { nextIP = ++m_NextIP; - } while(m_IPToAddr.find(nextIP) != m_IPToAddr.end() - && m_NextIP < m_MaxIP); - if(nextIP < m_MaxIP) + } while (m_IPToAddr.find(nextIP) != m_IPToAddr.end() && m_NextIP < m_MaxIP); + if (nextIP < m_MaxIP) { - m_AddrToIP[ident] = nextIP; + m_AddrToIP[ident] = nextIP; m_IPToAddr[nextIP] = ident; - m_SNodes[ident] = snode; + m_SNodes[ident] = snode; llarp::LogInfo(Name(), " mapped ", ident, " to ", nextIP); MarkIPActive(nextIP); return nextIP; @@ -1042,17 +1022,17 @@ namespace llarp // we are full // expire least active ip // TODO: prevent DoS - std::pair< huint128_t, llarp_time_t > oldest = {huint128_t{0}, 0s}; + std::pair oldest = {huint128_t{0}, 0s}; // find oldest entry auto itr = m_IPActivity.begin(); - while(itr != m_IPActivity.end()) + while (itr != m_IPActivity.end()) { - if(itr->second <= now) + if (itr->second <= now) { - if((now - itr->second) > oldest.second) + if ((now - itr->second) > oldest.second) { - oldest.first = itr->first; + oldest.first = itr->first; oldest.second = itr->second; } } @@ -1060,9 +1040,9 @@ namespace llarp } // remap address m_IPToAddr[oldest.first] = ident; - m_AddrToIP[ident] = oldest.first; - m_SNodes[ident] = snode; - nextIP = oldest.first; + m_AddrToIP[ident] = oldest.first; + m_SNodes[ident] = snode; + nextIP = oldest.first; // mark ip active m_IPActivity[nextIP] = std::max(m_IPActivity[nextIP], now); @@ -1086,7 +1066,7 @@ namespace llarp void TunEndpoint::MarkIPActiveForever(huint128_t ip) { - m_IPActivity[ip] = std::numeric_limits< llarp_time_t >::max(); + m_IPActivity[ip] = std::numeric_limits::max(); } void @@ -1096,20 +1076,20 @@ namespace llarp } void - TunEndpoint::tunifBeforeWrite(llarp_tun_io *tun) + TunEndpoint::tunifBeforeWrite(llarp_tun_io* tun) { // called in the isolated network thread - auto *self = static_cast< TunEndpoint * >(tun->user); - auto _pkts = std::move(self->m_TunPkts); - self->m_TunPkts = std::vector< net::IPPacket >(); + auto* self = static_cast(tun->user); + auto _pkts = std::move(self->m_TunPkts); + self->m_TunPkts = std::vector(); LogicCall(self->EndpointLogic(), [tun, self, pkts = std::move(_pkts)]() { - for(auto &pkt : pkts) + for (auto& pkt : pkts) { self->m_UserToNetworkPktQueue.Emplace(pkt); } - self->FlushToUser([self, tun](net::IPPacket &pkt) -> bool { - if(!llarp_ev_tun_async_write(tun, pkt.Buffer())) + self->FlushToUser([self, tun](net::IPPacket& pkt) -> bool { + if (!llarp_ev_tun_async_write(tun, pkt.Buffer())) { llarp::LogWarn(self->Name(), " packet dropped"); return true; @@ -1120,12 +1100,12 @@ namespace llarp } void - TunEndpoint::tunifRecvPkt(llarp_tun_io *tun, const llarp_buffer_t &b) + TunEndpoint::tunifRecvPkt(llarp_tun_io* tun, const llarp_buffer_t& b) { // called for every packet read from user in isolated network thread - auto *self = static_cast< TunEndpoint * >(tun->user); + auto* self = static_cast(tun->user); net::IPPacket pkt; - if(not pkt.Load(b)) + if (not pkt.Load(b)) return; self->m_TunPkts.emplace_back(pkt); } diff --git a/llarp/handlers/tun.hpp b/llarp/handlers/tun.hpp index 4b564677f..2754e881a 100644 --- a/llarp/handlers/tun.hpp +++ b/llarp/handlers/tun.hpp @@ -18,10 +18,13 @@ namespace llarp { struct TunEndpoint : public service::Endpoint, public dns::IQueryHandler, - public std::enable_shared_from_this< TunEndpoint > + public std::enable_shared_from_this { - TunEndpoint(const std::string& nickname, AbstractRouter* r, - llarp::service::Context* parent, bool lazyVPN = false); + TunEndpoint( + const std::string& nickname, + AbstractRouter* r, + llarp::service::Context* parent, + bool lazyVPN = false); ~TunEndpoint() override; path::PathSet_ptr @@ -39,7 +42,7 @@ namespace llarp util::StatusObject ExtractStatus() const; - std::unordered_map< std::string, std::string > + std::unordered_map NotifyParams() const override; bool @@ -50,8 +53,7 @@ namespace llarp bool HandleHookedDNSMessage( - dns::Message query, - std::function< void(dns::Message) > sendreply) override; + dns::Message query, std::function sendreply) override; void TickTun(llarp_time_t now); @@ -81,15 +83,14 @@ namespace llarp /// overrides Endpoint bool - HandleInboundPacket(const service::ConvoTag tag, - const llarp_buffer_t& pkt, - service::ProtocolType t) override + HandleInboundPacket( + const service::ConvoTag tag, const llarp_buffer_t& pkt, service::ProtocolType t) override { - if(t != service::eProtocolTrafficV4 && t != service::eProtocolTrafficV6) + if (t != service::eProtocolTrafficV4 && t != service::eProtocolTrafficV6) return false; - AlignedBuffer< 32 > addr; + AlignedBuffer<32> addr; bool snode = false; - if(!GetEndpointWithConvoTag(tag, addr, snode)) + if (!GetEndpointWithConvoTag(tag, addr, snode)) return false; return HandleWriteIPPacket( pkt, [=]() -> huint128_t { return ObtainIPForAddr(addr, snode); }); @@ -97,8 +98,7 @@ namespace llarp /// handle inbound traffic bool - HandleWriteIPPacket(const llarp_buffer_t& buf, - std::function< huint128_t(void) > getFromIP); + HandleWriteIPPacket(const llarp_buffer_t& buf, std::function getFromIP); /// queue outbound packet to the world bool @@ -118,13 +118,13 @@ namespace llarp bool HasLocalIP(const huint128_t& ip) const; - std::unique_ptr< llarp_tun_io > tunif; + std::unique_ptr tunif; llarp_vpn_io* vpnif = nullptr; bool InjectVPN(llarp_vpn_io* io, llarp_vpn_ifaddr_info info) override { - if(tunif) + if (tunif) return false; m_LazyVPNPromise.set_value(lazy_vpn{info, io}); return true; @@ -148,13 +148,13 @@ namespace llarp handleTickTun(void* u); /// get a key for ip address - template < typename Addr_t > + template Addr_t ObtainAddrForIP(huint128_t ip, bool isSNode) { Addr_t addr; auto itr = m_IPToAddr.find(ip); - if(itr != m_IPToAddr.end() and m_SNodes[itr->second] == isSNode) + if (itr != m_IPToAddr.end() and m_SNodes[itr->second] == isSNode) { addr = Addr_t(itr->second); } @@ -162,19 +162,19 @@ namespace llarp return addr; } - template < typename Addr_t > + template bool FindAddrForIP(Addr_t& addr, huint128_t ip); bool - HasAddress(const AlignedBuffer< 32 >& addr) const + HasAddress(const AlignedBuffer<32>& addr) const { return m_AddrToIP.find(addr) != m_AddrToIP.end(); } /// get ip address for key unconditionally huint128_t - ObtainIPForAddr(const AlignedBuffer< 32 >& addr, bool serviceNode); + ObtainIPForAddr(const AlignedBuffer<32>& addr, bool serviceNode); /// flush network traffic void @@ -188,12 +188,15 @@ namespace llarp ShouldFlushNow(llarp_time_t now) const; llarp_time_t m_LastFlushAt = 0s; - using PacketQueue_t = llarp::util::CoDelQueue< - net::IPPacket, net::IPPacket::GetTime, net::IPPacket::PutTime, - net::IPPacket::CompareOrder, net::IPPacket::GetNow >; + using PacketQueue_t = llarp::util::CoDelQueue< + net::IPPacket, + net::IPPacket::GetTime, + net::IPPacket::PutTime, + net::IPPacket::CompareOrder, + net::IPPacket::GetNow>; /// queue packet for send on net thread from user - std::vector< net::IPPacket > m_TunPkts; + std::vector m_TunPkts; /// queue for sending packets over the network from us PacketQueue_t m_UserToNetworkPktQueue; /// queue for sending packets to user from network @@ -215,23 +218,20 @@ namespace llarp FlushSend(); /// maps ip to key (host byte order) - std::unordered_map< huint128_t, AlignedBuffer< 32 > > m_IPToAddr; + std::unordered_map> m_IPToAddr; /// maps key to ip (host byte order) - std::unordered_map< AlignedBuffer< 32 >, huint128_t, - AlignedBuffer< 32 >::Hash > - m_AddrToIP; + std::unordered_map, huint128_t, AlignedBuffer<32>::Hash> m_AddrToIP; /// maps key to true if key is a service node, maps key to false if key is /// a hidden service - std::unordered_map< AlignedBuffer< 32 >, bool, AlignedBuffer< 32 >::Hash > - m_SNodes; + std::unordered_map, bool, AlignedBuffer<32>::Hash> m_SNodes; private: llarp_vpn_io_impl* GetVPNImpl() { - if(vpnif && vpnif->impl) - return static_cast< llarp_vpn_io_impl* >(vpnif->impl); + if (vpnif && vpnif->impl) + return static_cast(vpnif->impl); return nullptr; } @@ -239,43 +239,43 @@ namespace llarp QueueInboundPacketForExit(const llarp_buffer_t& buf) { ManagedBuffer copy{buf}; - return m_NetworkToUserPktQueue.EmplaceIf( - [&](llarp::net::IPPacket& pkt) -> bool { - if(!pkt.Load(copy.underlying)) - return false; - if(SupportsV6()) - { - if(pkt.IsV4()) - { - pkt.UpdateIPv6Address(net::IPPacket::ExpandV4(pkt.srcv4()), - m_OurIP); - } - else - { - pkt.UpdateIPv6Address(pkt.srcv6(), m_OurIP); - } - } - else - { - if(pkt.IsV4()) - pkt.UpdateIPv4Address( - xhtonl(pkt.srcv4()), - xhtonl(net::IPPacket::TruncateV6(m_OurIP))); - else - return false; - } - return true; - }); + return m_NetworkToUserPktQueue.EmplaceIf([&](llarp::net::IPPacket& pkt) -> bool { + if (!pkt.Load(copy.underlying)) + return false; + if (SupportsV6()) + { + if (pkt.IsV4()) + { + pkt.UpdateIPv6Address(net::IPPacket::ExpandV4(pkt.srcv4()), m_OurIP); + } + else + { + pkt.UpdateIPv6Address(pkt.srcv6(), m_OurIP); + } + } + else + { + if (pkt.IsV4()) + pkt.UpdateIPv4Address( + xhtonl(pkt.srcv4()), xhtonl(net::IPPacket::TruncateV6(m_OurIP))); + else + return false; + } + return true; + }); } - template < typename Addr_t, typename Endpoint_t > + template void - SendDNSReply(Addr_t addr, Endpoint_t ctx, - std::shared_ptr< dns::Message > query, - std::function< void(dns::Message) > reply, bool snode, - bool sendIPv6) + SendDNSReply( + Addr_t addr, + Endpoint_t ctx, + std::shared_ptr query, + std::function reply, + bool snode, + bool sendIPv6) { - if(ctx) + if (ctx) { huint128_t ip = ObtainIPForAddr(addr, snode); query->answers.clear(); @@ -286,10 +286,10 @@ namespace llarp reply(*query); } /// our dns resolver - std::shared_ptr< dns::Proxy > m_Resolver; + std::shared_ptr m_Resolver; /// maps ip address to timestamp last active - std::unordered_map< huint128_t, llarp_time_t > m_IPActivity; + std::unordered_map m_IPActivity; /// our ip address (host byte order) huint128_t m_OurIP; /// next ip address to allocate (host byte order) @@ -299,11 +299,11 @@ namespace llarp /// our ip range we are using llarp::IPRange m_OurRange; /// upstream dns resolver list - std::vector< llarp::Addr > m_UpstreamResolvers; + std::vector m_UpstreamResolvers; /// local dns llarp::Addr m_LocalResolverAddr; /// list of strict connect addresses for hooks - std::vector< llarp::Addr > m_StrictConnectAddrs; + std::vector m_StrictConnectAddrs; /// use v6? bool m_UseV6; struct lazy_vpn @@ -311,13 +311,13 @@ namespace llarp llarp_vpn_ifaddr_info info; llarp_vpn_io* io; }; - std::promise< lazy_vpn > m_LazyVPNPromise; + std::promise m_LazyVPNPromise; /// send packets on endpoint to user using send function /// send function returns true to indicate stop iteration and do codel /// drop void - FlushToUser(std::function< bool(net::IPPacket&) > sendfunc); + FlushToUser(std::function sendfunc); }; } // namespace handlers diff --git a/llarp/hook/ihook.hpp b/llarp/hook/ihook.hpp index 553de68e0..4fc211b99 100644 --- a/llarp/hook/ihook.hpp +++ b/llarp/hook/ihook.hpp @@ -13,7 +13,7 @@ namespace llarp { virtual ~IBackend() = 0; virtual void - NotifyAsync(std::unordered_map< std::string, std::string > params) = 0; + NotifyAsync(std::unordered_map params) = 0; /// start backend virtual bool @@ -24,7 +24,7 @@ namespace llarp Stop() = 0; }; - using Backend_ptr = std::shared_ptr< IBackend >; + using Backend_ptr = std::shared_ptr; inline IBackend::~IBackend() = default; } // namespace hooks diff --git a/llarp/hook/shell.cpp b/llarp/hook/shell.cpp index 127120699..17d9e5736 100644 --- a/llarp/hook/shell.cpp +++ b/llarp/hook/shell.cpp @@ -7,7 +7,7 @@ #include #if !defined(__linux__) || !defined(_GNU_SOURCE) // Not all systems declare this variable -extern char **environ; +extern char** environ; #endif #if defined(Darwin) #include @@ -19,30 +19,28 @@ namespace llarp namespace hooks { #if defined(ENABLE_SHELLHOOKS) - struct ExecShellHookBackend - : public IBackend, - public std::enable_shared_from_this< ExecShellHookBackend > + struct ExecShellHookBackend : public IBackend, + public std::enable_shared_from_this { thread::ThreadPool m_ThreadPool; - std::vector< std::string > _args; - std::vector< char * > args; + std::vector _args; + std::vector args; - ExecShellHookBackend(std::string script) - : m_ThreadPool(1, 1000, "exechook") + ExecShellHookBackend(std::string script) : m_ThreadPool(1, 1000, "exechook") { do { const auto idx = script.find_first_of(' '); std::string sub; - if(idx == std::string::npos) + if (idx == std::string::npos) sub = script; else sub = script.substr(0, idx); _args.emplace_back(std::move(sub)); - args.push_back((char *)_args.back().c_str()); + args.push_back((char*)_args.back().c_str()); script = script.substr(idx + 1); - } while(script.find_first_of(' ') != std::string::npos); + } while (script.find_first_of(' ') != std::string::npos); args.push_back(nullptr); LogInfo("make hook ", args.size()); } @@ -66,51 +64,51 @@ namespace llarp return true; } - char * + char* Exe() const { return args[0]; } - char *const * + char* const* Args() const { return args.data(); } void - NotifyAsync( - std::unordered_map< std::string, std::string > params) override; + NotifyAsync(std::unordered_map params) override; }; struct ExecShellHookJob { - std::vector< std::string > m_env; - std::vector< char * > _m_env; - std::shared_ptr< ExecShellHookBackend > m_Parent; + std::vector m_env; + std::vector _m_env; + std::shared_ptr m_Parent; - ExecShellHookJob(std::shared_ptr< ExecShellHookBackend > b, - const std::unordered_map< std::string, std::string > env) + ExecShellHookJob( + std::shared_ptr b, + const std::unordered_map env) : m_Parent(b) { #if defined(Darwin) - char **ptr = *_NSGetEnviron(); + char** ptr = *_NSGetEnviron(); #else - char **ptr = environ; + char** ptr = environ; #endif do { m_env.emplace_back(*ptr); ++ptr; - } while(ptr && *ptr); - for(const auto &item : env) + } while (ptr && *ptr); + for (const auto& item : env) m_env.emplace_back(item.first + "=" + item.second); - for(const auto &item : m_env) - _m_env.push_back((char *)item.c_str()); + for (const auto& item : m_env) + _m_env.push_back((char*)item.c_str()); _m_env.push_back(nullptr); } - char *const * + char* const* Env() { return _m_env.data(); @@ -120,11 +118,11 @@ namespace llarp Exec() { std::thread t([&]() { - int result = 0; + int result = 0; const pid_t child = ::fork(); - if(child == -1) + if (child == -1) return; - if(child) + if (child) ::waitpid(child, &result, 0); else ::execve(m_Parent->Exe(), m_Parent->Args(), Env()); @@ -134,11 +132,9 @@ namespace llarp }; void - ExecShellHookBackend::NotifyAsync( - std::unordered_map< std::string, std::string > params) + ExecShellHookBackend::NotifyAsync(std::unordered_map params) { - auto job = std::make_shared< ExecShellHookJob >(shared_from_this(), - std::move(params)); + auto job = std::make_shared(shared_from_this(), std::move(params)); m_ThreadPool.addJob(std::bind(&ExecShellHookJob::Exec, job)); } @@ -146,8 +142,8 @@ namespace llarp Backend_ptr ExecShellBackend(std::string execFilePath) { - Backend_ptr ptr = std::make_shared< ExecShellHookBackend >(execFilePath); - if(!ptr->Start()) + Backend_ptr ptr = std::make_shared(execFilePath); + if (!ptr->Start()) return nullptr; return ptr; } diff --git a/llarp/iwp/iwp.cpp b/llarp/iwp/iwp.cpp index 8a9464332..115f0e1ae 100644 --- a/llarp/iwp/iwp.cpp +++ b/llarp/iwp/iwp.cpp @@ -8,27 +8,35 @@ namespace llarp namespace iwp { LinkLayer_ptr - NewInboundLink(std::shared_ptr< KeyManager > keyManager, GetRCFunc getrc, - LinkMessageHandler h, SignBufferFunc sign, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, TimeoutHandler timeout, - SessionClosedHandler closed, PumpDoneHandler pumpDone) + NewInboundLink( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler h, + SignBufferFunc sign, + SessionEstablishedHandler est, + SessionRenegotiateHandler reneg, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone) { - return std::make_shared< LinkLayer >(keyManager, getrc, h, sign, est, - reneg, timeout, closed, pumpDone, - true); + return std::make_shared( + keyManager, getrc, h, sign, est, reneg, timeout, closed, pumpDone, true); } LinkLayer_ptr - NewOutboundLink(std::shared_ptr< KeyManager > keyManager, GetRCFunc getrc, - LinkMessageHandler h, SignBufferFunc sign, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, TimeoutHandler timeout, - SessionClosedHandler closed, PumpDoneHandler pumpDone) + NewOutboundLink( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler h, + SignBufferFunc sign, + SessionEstablishedHandler est, + SessionRenegotiateHandler reneg, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone) { - return std::make_shared< LinkLayer >(keyManager, getrc, h, sign, est, - reneg, timeout, closed, pumpDone, - false); + return std::make_shared( + keyManager, getrc, h, sign, est, reneg, timeout, closed, pumpDone, false); } } // namespace iwp } // namespace llarp diff --git a/llarp/iwp/iwp.hpp b/llarp/iwp/iwp.hpp index bec91fe3f..f33917870 100644 --- a/llarp/iwp/iwp.hpp +++ b/llarp/iwp/iwp.hpp @@ -11,17 +11,27 @@ namespace llarp namespace iwp { LinkLayer_ptr - NewInboundLink(std::shared_ptr< KeyManager > keyManager, GetRCFunc getrc, - LinkMessageHandler h, SignBufferFunc sign, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, TimeoutHandler timeout, - SessionClosedHandler closed, PumpDoneHandler pumpDone); + NewInboundLink( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler h, + SignBufferFunc sign, + SessionEstablishedHandler est, + SessionRenegotiateHandler reneg, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone); LinkLayer_ptr - NewOutboundLink(std::shared_ptr< KeyManager > keyManager, GetRCFunc getrc, - LinkMessageHandler h, SignBufferFunc sign, - SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, TimeoutHandler timeout, - SessionClosedHandler closed, PumpDoneHandler pumpDone); + NewOutboundLink( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler h, + SignBufferFunc sign, + SessionEstablishedHandler est, + SessionRenegotiateHandler reneg, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone); } // namespace iwp } // namespace llarp diff --git a/llarp/iwp/linklayer.cpp b/llarp/iwp/linklayer.cpp index 77e61c485..b0a30e36e 100644 --- a/llarp/iwp/linklayer.cpp +++ b/llarp/iwp/linklayer.cpp @@ -8,14 +8,18 @@ namespace llarp { namespace iwp { - LinkLayer::LinkLayer(std::shared_ptr< KeyManager > keyManager, - GetRCFunc getrc, LinkMessageHandler h, - SignBufferFunc sign, SessionEstablishedHandler est, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, SessionClosedHandler closed, - PumpDoneHandler pumpDone, bool allowInbound) - : ILinkLayer(keyManager, getrc, h, sign, est, reneg, timeout, closed, - pumpDone) + LinkLayer::LinkLayer( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler h, + SignBufferFunc sign, + SessionEstablishedHandler est, + SessionRenegotiateHandler reneg, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone, + bool allowInbound) + : ILinkLayer(keyManager, getrc, h, sign, est, reneg, timeout, closed, pumpDone) , permitInbound{allowInbound} { } @@ -35,7 +39,7 @@ namespace llarp } void - LinkLayer::QueueWork(std::function< void(void) > func) + LinkLayer::QueueWork(std::function func) { m_Worker->addJob(func); } @@ -43,18 +47,18 @@ namespace llarp void LinkLayer::RecvFrom(const Addr& from, ILinkSession::Packet_t pkt) { - std::shared_ptr< ILinkSession > session; - auto itr = m_AuthedAddrs.find(from); + std::shared_ptr session; + auto itr = m_AuthedAddrs.find(from); bool isNewSession = false; - if(itr == m_AuthedAddrs.end()) + if (itr == m_AuthedAddrs.end()) { Lock_t lock(m_PendingMutex); - if(m_Pending.count(from) == 0) + if (m_Pending.count(from) == 0) { - if(not permitInbound) + if (not permitInbound) return; isNewSession = true; - m_Pending.insert({from, std::make_shared< Session >(this, from)}); + m_Pending.insert({from, std::make_shared(this, from)}); } session = m_Pending.find(from)->second; } @@ -62,15 +66,14 @@ namespace llarp { Lock_t lock(m_AuthedLinksMutex); auto range = m_AuthedLinks.equal_range(itr->second); - session = range.first->second; + session = range.first->second; } - if(session) + if (session) { bool success = session->Recv_LL(std::move(pkt)); - if(!success and isNewSession) + if (!success and isNewSession) { - LogWarn( - "Brand new session failed; removing from pending sessions list"); + LogWarn("Brand new session failed; removing from pending sessions list"); m_Pending.erase(m_Pending.find(from)); } } @@ -79,7 +82,7 @@ namespace llarp bool LinkLayer::MapAddr(const RouterID& r, ILinkSession* s) { - if(!ILinkLayer::MapAddr(r, s)) + if (!ILinkLayer::MapAddr(r, s)) return false; m_AuthedAddrs.emplace(s->GetRemoteEndpoint(), r); return true; @@ -91,11 +94,10 @@ namespace llarp m_AuthedAddrs.erase(a); } - std::shared_ptr< ILinkSession > - LinkLayer::NewOutboundSession(const RouterContact& rc, - const AddressInfo& ai) + std::shared_ptr + LinkLayer::NewOutboundSession(const RouterContact& rc, const AddressInfo& ai) { - return std::make_shared< Session >(this, rc, ai); + return std::make_shared(this, rc, ai); } } // namespace iwp } // namespace llarp diff --git a/llarp/iwp/linklayer.hpp b/llarp/iwp/linklayer.hpp index 075f5e9f1..3c1422a59 100644 --- a/llarp/iwp/linklayer.hpp +++ b/llarp/iwp/linklayer.hpp @@ -17,42 +17,47 @@ namespace llarp { struct LinkLayer final : public ILinkLayer { - LinkLayer(std::shared_ptr< KeyManager > keyManager, GetRCFunc getrc, - LinkMessageHandler h, SignBufferFunc sign, - SessionEstablishedHandler est, SessionRenegotiateHandler reneg, - TimeoutHandler timeout, SessionClosedHandler closed, - PumpDoneHandler pumpDone, bool permitInbound); + LinkLayer( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler h, + SignBufferFunc sign, + SessionEstablishedHandler est, + SessionRenegotiateHandler reneg, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone, + bool permitInbound); ~LinkLayer() override; - std::shared_ptr< ILinkSession > - NewOutboundSession(const RouterContact &rc, - const AddressInfo &ai) override; + std::shared_ptr + NewOutboundSession(const RouterContact& rc, const AddressInfo& ai) override; - const char * + const char* Name() const override; uint16_t Rank() const override; void - RecvFrom(const Addr &from, ILinkSession::Packet_t pkt) override; + RecvFrom(const Addr& from, ILinkSession::Packet_t pkt) override; bool - MapAddr(const RouterID &pk, ILinkSession *s) override; + MapAddr(const RouterID& pk, ILinkSession* s) override; void - UnmapAddr(const Addr &addr); + UnmapAddr(const Addr& addr); void - QueueWork(std::function< void(void) > work); + QueueWork(std::function work); private: - std::unordered_map< Addr, RouterID, Addr::Hash > m_AuthedAddrs; + std::unordered_map m_AuthedAddrs; const bool permitInbound; }; - using LinkLayer_ptr = std::shared_ptr< LinkLayer >; + using LinkLayer_ptr = std::shared_ptr; } // namespace iwp } // namespace llarp diff --git a/llarp/iwp/message_buffer.cpp b/llarp/iwp/message_buffer.cpp index 25f3b1f4d..67d137c83 100644 --- a/llarp/iwp/message_buffer.cpp +++ b/llarp/iwp/message_buffer.cpp @@ -6,10 +6,11 @@ namespace llarp { namespace iwp { - OutboundMessage::OutboundMessage(uint64_t msgid, - ILinkSession::Message_t msg, - llarp_time_t now, - ILinkSession::CompletionHandler handler) + OutboundMessage::OutboundMessage( + uint64_t msgid, + ILinkSession::Message_t msg, + llarp_time_t now, + ILinkSession::CompletionHandler handler) : m_Data{std::move(msg)} , m_MsgID{msgid} , m_Completed{handler} @@ -24,20 +25,19 @@ namespace llarp OutboundMessage::XMIT() const { size_t extra = std::min(m_Data.size(), FragmentSize); - auto xmit = CreatePacket(Command::eXMIT, 10 + 32 + extra, 0, 0); + auto xmit = CreatePacket(Command::eXMIT, 10 + 32 + extra, 0, 0); htobe16buf(xmit.data() + CommandOverhead + PacketOverhead, m_Data.size()); htobe64buf(xmit.data() + 2 + CommandOverhead + PacketOverhead, m_MsgID); - std::copy_n(m_Digest.begin(), m_Digest.size(), - xmit.data() + 10 + CommandOverhead + PacketOverhead); - std::copy_n(m_Data.data(), extra, - xmit.data() + 10 + CommandOverhead + PacketOverhead + 32); + std::copy_n( + m_Digest.begin(), m_Digest.size(), xmit.data() + 10 + CommandOverhead + PacketOverhead); + std::copy_n(m_Data.data(), extra, xmit.data() + 10 + CommandOverhead + PacketOverhead + 32); return xmit; } void OutboundMessage::Completed() { - if(m_Completed) + if (m_Completed) { m_Completed(ILinkSession::DeliveryStatus::eDeliverySuccess); } @@ -53,28 +53,29 @@ namespace llarp void OutboundMessage::Ack(byte_t bitmask) { - m_Acks = std::bitset< 8 >(bitmask); + m_Acks = std::bitset<8>(bitmask); } void OutboundMessage::FlushUnAcked( - std::function< void(ILinkSession::Packet_t) > sendpkt, llarp_time_t now) + std::function sendpkt, llarp_time_t now) { /// overhead for a data packet in plaintext static constexpr size_t Overhead = 10; - uint16_t idx = 0; - const auto datasz = m_Data.size(); - while(idx < datasz) + uint16_t idx = 0; + const auto datasz = m_Data.size(); + while (idx < datasz) { - if(not m_Acks[idx / FragmentSize]) + if (not m_Acks[idx / FragmentSize]) { - const size_t fragsz = - idx + FragmentSize < datasz ? FragmentSize : datasz - idx; + const size_t fragsz = idx + FragmentSize < datasz ? FragmentSize : datasz - idx; auto frag = CreatePacket(Command::eDATA, fragsz + Overhead, 0, 0); htobe16buf(frag.data() + 2 + PacketOverhead, idx); htobe64buf(frag.data() + 4 + PacketOverhead, m_MsgID); - std::copy(m_Data.begin() + idx, m_Data.begin() + idx + fragsz, - frag.data() + PacketOverhead + Overhead + 2); + std::copy( + m_Data.begin() + idx, + m_Data.begin() + idx + fragsz, + frag.data() + PacketOverhead + Overhead + 2); sendpkt(std::move(frag)); } idx += FragmentSize; @@ -86,9 +87,9 @@ namespace llarp OutboundMessage::IsTransmitted() const { const auto sz = m_Data.size(); - for(uint16_t idx = 0; idx < sz; idx += FragmentSize) + for (uint16_t idx = 0; idx < sz; idx += FragmentSize) { - if(not m_Acks.test(idx / FragmentSize)) + if (not m_Acks.test(idx / FragmentSize)) return false; } return true; @@ -104,32 +105,27 @@ namespace llarp void OutboundMessage::InformTimeout() { - if(m_Completed) + if (m_Completed) { m_Completed(ILinkSession::DeliveryStatus::eDeliveryDropped); } m_Completed = nullptr; } - InboundMessage::InboundMessage(uint64_t msgid, uint16_t sz, ShortHash h, - llarp_time_t now) - : m_Data(size_t{sz}) - , m_Digset{std::move(h)} - , m_MsgID(msgid) - , m_LastActiveAt{now} + InboundMessage::InboundMessage(uint64_t msgid, uint16_t sz, ShortHash h, llarp_time_t now) + : m_Data(size_t{sz}), m_Digset{std::move(h)}, m_MsgID(msgid), m_LastActiveAt{now} { } void - InboundMessage::HandleData(uint16_t idx, const llarp_buffer_t &buf, - llarp_time_t now) + InboundMessage::HandleData(uint16_t idx, const llarp_buffer_t& buf, llarp_time_t now) { - if(idx + buf.sz > m_Data.size()) + if (idx + buf.sz > m_Data.size()) { LogWarn("invalid fragment offset ", idx); return; } - byte_t *dst = m_Data.data() + idx; + byte_t* dst = m_Data.data() + idx; std::copy_n(buf.base, buf.sz, dst); m_Acks.set(idx / FragmentSize); LogDebug("got fragment ", idx / FragmentSize); @@ -155,9 +151,9 @@ namespace llarp InboundMessage::IsCompleted() const { const auto sz = m_Data.size(); - for(size_t idx = 0; idx < sz; idx += FragmentSize) + for (size_t idx = 0; idx < sz; idx += FragmentSize) { - if(not m_Acks.test(idx / FragmentSize)) + if (not m_Acks.test(idx / FragmentSize)) return false; } return true; @@ -176,8 +172,7 @@ namespace llarp } void - InboundMessage::SendACKS( - std::function< void(ILinkSession::Packet_t) > sendpkt, llarp_time_t now) + InboundMessage::SendACKS(std::function sendpkt, llarp_time_t now) { sendpkt(ACKS()); m_LastACKSent = now; diff --git a/llarp/iwp/message_buffer.hpp b/llarp/iwp/message_buffer.hpp index 78870e0e7..020d68171 100644 --- a/llarp/iwp/message_buffer.hpp +++ b/llarp/iwp/message_buffer.hpp @@ -37,13 +37,15 @@ namespace llarp struct OutboundMessage { OutboundMessage() = default; - OutboundMessage(uint64_t msgid, ILinkSession::Message_t data, - llarp_time_t now, - ILinkSession::CompletionHandler handler); + OutboundMessage( + uint64_t msgid, + ILinkSession::Message_t data, + llarp_time_t now, + ILinkSession::CompletionHandler handler); ILinkSession::Message_t m_Data; uint64_t m_MsgID = 0; - std::bitset< MAX_LINK_MSG_SIZE / FragmentSize > m_Acks; + std::bitset m_Acks; ILinkSession::CompletionHandler m_Completed; llarp_time_t m_LastFlush = 0s; ShortHash m_Digest; @@ -56,8 +58,7 @@ namespace llarp Ack(byte_t bitmask); void - FlushUnAcked(std::function< void(ILinkSession::Packet_t) > sendpkt, - llarp_time_t now); + FlushUnAcked(std::function sendpkt, llarp_time_t now); bool ShouldFlush(llarp_time_t now) const; @@ -78,15 +79,14 @@ namespace llarp struct InboundMessage { InboundMessage() = default; - InboundMessage(uint64_t msgid, uint16_t sz, ShortHash h, - llarp_time_t now); + InboundMessage(uint64_t msgid, uint16_t sz, ShortHash h, llarp_time_t now); ILinkSession::Message_t m_Data; ShortHash m_Digset; - uint64_t m_MsgID = 0; - llarp_time_t m_LastACKSent = 0s; + uint64_t m_MsgID = 0; + llarp_time_t m_LastACKSent = 0s; llarp_time_t m_LastActiveAt = 0s; - std::bitset< MAX_LINK_MSG_SIZE / FragmentSize > m_Acks; + std::bitset m_Acks; void HandleData(uint16_t idx, const llarp_buffer_t& buf, llarp_time_t now); @@ -107,8 +107,7 @@ namespace llarp ShouldSendACKS(llarp_time_t now) const; void - SendACKS(std::function< void(ILinkSession::Packet_t) > sendpkt, - llarp_time_t now); + SendACKS(std::function sendpkt, llarp_time_t now); ILinkSession::Packet_t ACKS() const; diff --git a/llarp/iwp/session.cpp b/llarp/iwp/session.cpp index aa4180e6c..841ef241f 100644 --- a/llarp/iwp/session.cpp +++ b/llarp/iwp/session.cpp @@ -11,25 +11,22 @@ namespace llarp ILinkSession::Packet_t CreatePacket(Command cmd, size_t plainsize, size_t minpad, size_t variance) { - const size_t pad = - minpad > 0 ? minpad + (variance > 0 ? randint() % variance : 0) : 0; - ILinkSession::Packet_t pkt(PacketOverhead + plainsize + pad - + CommandOverhead); + const size_t pad = minpad > 0 ? minpad + (variance > 0 ? randint() % variance : 0) : 0; + ILinkSession::Packet_t pkt(PacketOverhead + plainsize + pad + CommandOverhead); // randomize pad - if(pad) + if (pad) { CryptoManager::instance()->randbytes( pkt.data() + PacketOverhead + CommandOverhead + plainsize, pad); } // randomize nounce CryptoManager::instance()->randbytes(pkt.data() + HMACSIZE, TUNNONCESIZE); - pkt[PacketOverhead] = LLARP_PROTO_VERSION; + pkt[PacketOverhead] = LLARP_PROTO_VERSION; pkt[PacketOverhead + 1] = cmd; return pkt; } - Session::Session(LinkLayer* p, const RouterContact& rc, - const AddressInfo& ai) + Session::Session(LinkLayer* p, const RouterContact& rc, const AddressInfo& ai) : m_State{State::Initial} , m_Inbound{false} , m_Parent(p) @@ -40,8 +37,7 @@ namespace llarp { token.Zero(); GotLIM = util::memFn(&Session::GotOutboundLIM, this); - CryptoManager::instance()->shorthash(m_SessionKey, - llarp_buffer_t(rc.pubkey)); + CryptoManager::instance()->shorthash(m_SessionKey, llarp_buffer_t(rc.pubkey)); } Session::Session(LinkLayer* p, const Addr& from) @@ -52,7 +48,7 @@ namespace llarp , m_RemoteAddr(from) { token.Randomize(); - GotLIM = util::memFn(&Session::GotInboundLIM, this); + GotLIM = util::memFn(&Session::GotInboundLIM, this); const PubKey pk = m_Parent->GetOurRC().pubkey; CryptoManager::instance()->shorthash(m_SessionKey, llarp_buffer_t(pk)); } @@ -70,14 +66,19 @@ namespace llarp bool Session::GotInboundLIM(const LinkIntroMessage* msg) { - if(msg->rc.pubkey != m_ExpectedIdent) + if (msg->rc.pubkey != m_ExpectedIdent) { - LogError("ident key missmatch from ", m_RemoteAddr, " ", msg->rc.pubkey, - " != ", m_ExpectedIdent); + LogError( + "ident key missmatch from ", + m_RemoteAddr, + " ", + msg->rc.pubkey, + " != ", + m_ExpectedIdent); return false; } - m_State = State::Ready; - GotLIM = util::memFn(&Session::GotRenegLIM, this); + m_State = State::Ready; + GotLIM = util::memFn(&Session::GotRenegLIM, this); m_RemoteRC = msg->rc; m_Parent->MapAddr(m_RemoteRC.pubkey, this); return m_Parent->SessionEstablished(this); @@ -86,16 +87,16 @@ namespace llarp bool Session::GotOutboundLIM(const LinkIntroMessage* msg) { - if(msg->rc.pubkey != m_RemoteRC.pubkey) + if (msg->rc.pubkey != m_RemoteRC.pubkey) { LogError("ident key missmatch"); return false; } m_RemoteRC = msg->rc; - GotLIM = util::memFn(&Session::GotRenegLIM, this); - auto self = shared_from_this(); + GotLIM = util::memFn(&Session::GotRenegLIM, this); + auto self = shared_from_this(); SendOurLIM([self](ILinkSession::DeliveryStatus st) { - if(st == ILinkSession::DeliveryStatus::eDeliverySuccess) + if (st == ILinkSession::DeliveryStatus::eDeliverySuccess) { self->m_State = State::Ready; self->m_Parent->MapAddr(self->m_RemoteRC.pubkey, self.get()); @@ -112,18 +113,18 @@ namespace llarp msg.rc = m_Parent->GetOurRC(); msg.N.Randomize(); msg.P = 60000; - if(not msg.Sign(m_Parent->Sign)) + if (not msg.Sign(m_Parent->Sign)) { LogError("failed to sign our RC for ", m_RemoteAddr); return; } ILinkSession::Message_t data(LinkIntroMessage::MaxSize + PacketOverhead); llarp_buffer_t buf(data); - if(not msg.BEncode(&buf)) + if (not msg.BEncode(&buf)) { LogError("failed to encode LIM for ", m_RemoteAddr); } - if(!SendMessageBuffer(std::move(data), h)) + if (!SendMessageBuffer(std::move(data), h)) { LogError("failed to send LIM to ", m_RemoteAddr); } @@ -133,10 +134,10 @@ namespace llarp void Session::EncryptAndSend(ILinkSession::Packet_t data) { - if(m_EncryptNext == nullptr) - m_EncryptNext = std::make_shared< CryptoQueue_t >(); + if (m_EncryptNext == nullptr) + m_EncryptNext = std::make_shared(); m_EncryptNext->emplace_back(std::move(data)); - if(!IsEstablished()) + if (!IsEstablished()) { EncryptWorker(std::move(m_EncryptNext)); m_EncryptNext = nullptr; @@ -148,7 +149,7 @@ namespace llarp { LogDebug("encrypt worker ", msgs->size(), " messages"); auto itr = msgs->begin(); - while(itr != msgs->end()) + while (itr != msgs->end()) { Packet_t pkt = std::move(*itr); llarp_buffer_t pktbuf(pkt); @@ -158,7 +159,7 @@ namespace llarp pktbuf.sz -= PacketOverhead; CryptoManager::instance()->xchacha20(pktbuf, m_SessionKey, nonce_ptr); pktbuf.base = pkt.data() + HMACSIZE; - pktbuf.sz = pkt.size() - HMACSIZE; + pktbuf.sz = pkt.size() - HMACSIZE; CryptoManager::instance()->hmac(pkt.data(), pktbuf, m_SessionKey); Send_LL(pkt.data(), pkt.size()); ++itr; @@ -168,10 +169,10 @@ namespace llarp void Session::Close() { - if(m_State == State::Closed) + if (m_State == State::Closed) return; auto close_msg = CreatePacket(Command::eCLOS, 0, 16, 16); - if(m_State == State::Ready) + if (m_State == State::Ready) m_Parent->UnmapAddr(m_RemoteAddr); m_State = State::Closed; EncryptAndSend(std::move(close_msg)); @@ -179,21 +180,18 @@ namespace llarp } bool - Session::SendMessageBuffer(ILinkSession::Message_t buf, - ILinkSession::CompletionHandler completed) + Session::SendMessageBuffer( + ILinkSession::Message_t buf, ILinkSession::CompletionHandler completed) { - if(m_TXMsgs.size() >= MaxSendQueueSize) + if (m_TXMsgs.size() >= MaxSendQueueSize) return false; - const auto now = m_Parent->Now(); + const auto now = m_Parent->Now(); const auto msgid = m_TXID++; const auto bufsz = buf.size(); - auto& msg = - m_TXMsgs - .emplace(msgid, - OutboundMessage{msgid, std::move(buf), now, completed}) - .first->second; + auto& msg = m_TXMsgs.emplace(msgid, OutboundMessage{msgid, std::move(buf), now, completed}) + .first->second; EncryptAndSend(msg.XMIT()); - if(bufsz > FragmentSize) + if (bufsz > FragmentSize) { msg.FlushUnAcked(util::memFn(&Session::EncryptAndSend, this), now); } @@ -206,19 +204,17 @@ namespace llarp Session::SendMACK() { // send multi acks - while(m_SendMACKs.size() > 0) + while (m_SendMACKs.size() > 0) { - const auto sz = m_SendMACKs.size(); + const auto sz = m_SendMACKs.size(); const auto max = Session::MaxACKSInMACK; - auto numAcks = std::min(sz, max); - auto mack = - CreatePacket(Command::eMACK, 1 + (numAcks * sizeof(uint64_t))); - mack[PacketOverhead + CommandOverhead] = - byte_t{static_cast< byte_t >(numAcks)}; + auto numAcks = std::min(sz, max); + auto mack = CreatePacket(Command::eMACK, 1 + (numAcks * sizeof(uint64_t))); + mack[PacketOverhead + CommandOverhead] = byte_t{static_cast(numAcks)}; byte_t* ptr = mack.data() + 3 + PacketOverhead; LogDebug("send ", numAcks, " macks to ", m_RemoteAddr); auto itr = m_SendMACKs.begin(); - while(numAcks > 0) + while (numAcks > 0) { htobe64buf(ptr, *itr); itr = m_SendMACKs.erase(itr); @@ -233,41 +229,35 @@ namespace llarp Session::Pump() { const auto now = m_Parent->Now(); - if(m_State == State::Ready || m_State == State::LinkIntro) + if (m_State == State::Ready || m_State == State::LinkIntro) { - if(ShouldPing()) + if (ShouldPing()) SendKeepAlive(); - for(auto& item : m_RXMsgs) + for (auto& item : m_RXMsgs) { - if(item.second.ShouldSendACKS(now)) + if (item.second.ShouldSendACKS(now)) { - item.second.SendACKS(util::memFn(&Session::EncryptAndSend, this), - now); + item.second.SendACKS(util::memFn(&Session::EncryptAndSend, this), now); } } - for(auto& item : m_TXMsgs) + for (auto& item : m_TXMsgs) { - if(item.second.ShouldFlush(now)) + if (item.second.ShouldFlush(now)) { - item.second.FlushUnAcked( - util::memFn(&Session::EncryptAndSend, this), now); + item.second.FlushUnAcked(util::memFn(&Session::EncryptAndSend, this), now); } } } auto self = shared_from_this(); - if(m_EncryptNext && !m_EncryptNext->empty()) + if (m_EncryptNext && !m_EncryptNext->empty()) { - m_Parent->QueueWork([self, data = std::move(m_EncryptNext)] { - self->EncryptWorker(data); - }); + m_Parent->QueueWork([self, data = std::move(m_EncryptNext)] { self->EncryptWorker(data); }); m_EncryptNext = nullptr; } - if(m_DecryptNext && !m_DecryptNext->empty()) + if (m_DecryptNext && !m_DecryptNext->empty()) { - m_Parent->QueueWork([self, data = std::move(m_DecryptNext)] { - self->DecryptWorker(data); - }); + m_Parent->QueueWork([self, data = std::move(m_DecryptNext)] { self->DecryptWorker(data); }); m_DecryptNext = nullptr; } } @@ -289,7 +279,7 @@ namespace llarp bool Session::ShouldPing() const { - if(m_State == State::Ready) + if (m_State == State::Ready) { const auto now = m_Parent->Now(); return now - m_LastTX > PingInterval; @@ -328,7 +318,7 @@ namespace llarp bool Session::TimedOut(llarp_time_t now) const { - if(m_State == State::Ready || m_State == State::LinkIntro) + if (m_State == State::Ready || m_State == State::LinkIntro) { return now > m_LastRX && now - m_LastRX > SessionAliveTimeout; } @@ -346,14 +336,14 @@ namespace llarp { m_Stats.currentRateTX = m_TXRate; m_Stats.currentRateRX = m_RXRate; - m_RXRate = 0; - m_TXRate = 0; + m_RXRate = 0; + m_TXRate = 0; } void Session::Tick(llarp_time_t now) { - if(ShouldResetRates(now)) + if (ShouldResetRates(now)) { ResetRates(); m_ResetRatesAt = now + 1s; @@ -362,9 +352,9 @@ namespace llarp // inform waiters { auto itr = m_TXMsgs.begin(); - while(itr != m_TXMsgs.end()) + while (itr != m_TXMsgs.end()) { - if(itr->second.IsTimedOut(now)) + if (itr->second.IsTimedOut(now)) { m_Stats.totalDroppedTX++; m_Stats.totalInFlightTX--; @@ -379,9 +369,9 @@ namespace llarp { // remove pending inbound messages that timed out auto itr = m_RXMsgs.begin(); - while(itr != m_RXMsgs.end()) + while (itr != m_RXMsgs.end()) { - if(itr->second.IsTimedOut(now)) + if (itr->second.IsTimedOut(now)) { m_ReplayFilter.emplace(itr->first, now); itr = m_RXMsgs.erase(itr); @@ -393,9 +383,9 @@ namespace llarp { // decay replay window auto itr = m_ReplayFilter.begin(); - while(itr != m_ReplayFilter.end()) + while (itr != m_ReplayFilter.end()) { - if(itr->second + ReplayWindow <= now) + if (itr->second + ReplayWindow <= now) { itr = m_ReplayFilter.erase(itr); } @@ -405,8 +395,8 @@ namespace llarp } } - using Introduction = AlignedBuffer< PubKey::SIZE + PubKey::SIZE - + TunnelNonce::SIZE + Signature::SIZE >; + using Introduction = + AlignedBuffer; void Session::GenerateAndSendIntro() @@ -415,32 +405,29 @@ namespace llarp N.Randomize(); { ILinkSession::Packet_t req(Introduction::SIZE + PacketOverhead); - const auto pk = m_Parent->GetOurRC().pubkey; + const auto pk = m_Parent->GetOurRC().pubkey; const auto e_pk = m_Parent->RouterEncryptionSecret().toPublic(); - auto itr = req.data() + PacketOverhead; + auto itr = req.data() + PacketOverhead; std::copy_n(pk.data(), pk.size(), itr); itr += pk.size(); std::copy_n(e_pk.data(), e_pk.size(), itr); itr += e_pk.size(); std::copy_n(N.data(), N.size(), itr); Signature Z; - llarp_buffer_t signbuf(req.data() + PacketOverhead, - Introduction::SIZE - Signature::SIZE); + llarp_buffer_t signbuf(req.data() + PacketOverhead, Introduction::SIZE - Signature::SIZE); m_Parent->Sign(Z, signbuf); - std::copy_n(Z.data(), Z.size(), - req.data() + PacketOverhead - + (Introduction::SIZE - Signature::SIZE)); - CryptoManager::instance()->randbytes(req.data() + HMACSIZE, - TUNNONCESIZE); + std::copy_n( + Z.data(), + Z.size(), + req.data() + PacketOverhead + (Introduction::SIZE - Signature::SIZE)); + CryptoManager::instance()->randbytes(req.data() + HMACSIZE, TUNNONCESIZE); EncryptAndSend(std::move(req)); } m_State = State::Introduction; - if(not CryptoManager::instance()->transport_dh_client( - m_SessionKey, m_ChosenAI.pubkey, - m_Parent->RouterEncryptionSecret(), N)) + if (not CryptoManager::instance()->transport_dh_client( + m_SessionKey, m_ChosenAI.pubkey, m_Parent->RouterEncryptionSecret(), N)) { - LogError("failed to transport_dh_client on outbound session to ", - m_RemoteAddr); + LogError("failed to transport_dh_client on outbound session to ", m_RemoteAddr); return; } LogDebug("sent intro to ", m_RemoteAddr); @@ -449,32 +436,37 @@ namespace llarp void Session::HandleCreateSessionRequest(Packet_t pkt) { - if(not DecryptMessageInPlace(pkt)) + if (not DecryptMessageInPlace(pkt)) { LogError("failed to decrypt session request from ", m_RemoteAddr); return; } - if(pkt.size() < token.size() + PacketOverhead) + if (pkt.size() < token.size() + PacketOverhead) { - LogError("bad session request size, ", pkt.size(), " < ", - token.size() + PacketOverhead, " from ", m_RemoteAddr); + LogError( + "bad session request size, ", + pkt.size(), + " < ", + token.size() + PacketOverhead, + " from ", + m_RemoteAddr); return; } const auto begin = pkt.data() + PacketOverhead; - if(not std::equal(begin, begin + token.size(), token.data())) + if (not std::equal(begin, begin + token.size(), token.data())) { LogError("token missmatch from ", m_RemoteAddr); return; } m_LastRX = m_Parent->Now(); - m_State = State::LinkIntro; + m_State = State::LinkIntro; SendOurLIM(); } void Session::HandleGotIntro(Packet_t pkt) { - if(pkt.size() < (Introduction::SIZE + PacketOverhead)) + if (pkt.size() < (Introduction::SIZE + PacketOverhead)) { LogWarn("intro too small from ", m_RemoteAddr); return; @@ -489,27 +481,30 @@ namespace llarp ptr += TunnelNonce::SIZE; Signature Z; std::copy_n(ptr, Z.size(), Z.data()); - const llarp_buffer_t verifybuf(pkt.data() + PacketOverhead, - Introduction::SIZE - Signature::SIZE); - if(!CryptoManager::instance()->verify(m_ExpectedIdent, verifybuf, Z)) + const llarp_buffer_t verifybuf( + pkt.data() + PacketOverhead, Introduction::SIZE - Signature::SIZE); + if (!CryptoManager::instance()->verify(m_ExpectedIdent, verifybuf, Z)) { LogError("intro verify failed from ", m_RemoteAddr); return; } const PubKey pk = m_Parent->TransportSecretKey().toPublic(); - LogDebug("got intro: remote-pk=", m_RemoteOnionKey.ToHex(), - " N=", N.ToHex(), " local-pk=", pk.ToHex()); - if(not CryptoManager::instance()->transport_dh_server( - m_SessionKey, m_RemoteOnionKey, m_Parent->TransportSecretKey(), N)) - { - LogError("failed to transport_dh_server on inbound intro from ", - m_RemoteAddr); + LogDebug( + "got intro: remote-pk=", + m_RemoteOnionKey.ToHex(), + " N=", + N.ToHex(), + " local-pk=", + pk.ToHex()); + if (not CryptoManager::instance()->transport_dh_server( + m_SessionKey, m_RemoteOnionKey, m_Parent->TransportSecretKey(), N)) + { + LogError("failed to transport_dh_server on inbound intro from ", m_RemoteAddr); return; } Packet_t reply(token.size() + PacketOverhead); // random nonce - CryptoManager::instance()->randbytes(reply.data() + HMACSIZE, - TUNNONCESIZE); + CryptoManager::instance()->randbytes(reply.data() + HMACSIZE, TUNNONCESIZE); // set token std::copy_n(token.data(), token.size(), reply.data() + PacketOverhead); m_LastRX = m_Parent->Now(); @@ -521,14 +516,19 @@ namespace llarp void Session::HandleGotIntroAck(Packet_t pkt) { - if(pkt.size() < (token.size() + PacketOverhead)) + if (pkt.size() < (token.size() + PacketOverhead)) { - LogError("bad intro ack size ", pkt.size(), " < ", - token.size() + PacketOverhead, " from ", m_RemoteAddr); + LogError( + "bad intro ack size ", + pkt.size(), + " < ", + token.size() + PacketOverhead, + " from ", + m_RemoteAddr); return; } Packet_t reply(token.size() + PacketOverhead); - if(not DecryptMessageInPlace(pkt)) + if (not DecryptMessageInPlace(pkt)) { LogError("intro ack decrypt failed from ", m_RemoteAddr); return; @@ -537,8 +537,7 @@ namespace llarp std::copy_n(pkt.data() + PacketOverhead, token.size(), token.data()); std::copy_n(token.data(), token.size(), reply.data() + PacketOverhead); // random nounce - CryptoManager::instance()->randbytes(reply.data() + HMACSIZE, - TUNNONCESIZE); + CryptoManager::instance()->randbytes(reply.data() + HMACSIZE, TUNNONCESIZE); EncryptAndSend(std::move(reply)); LogDebug("sent session request to ", m_RemoteAddr); m_State = State::LinkIntro; @@ -547,7 +546,7 @@ namespace llarp bool Session::DecryptMessageInPlace(Packet_t& pkt) { - if(pkt.size() <= PacketOverhead) + if (pkt.size() <= PacketOverhead) { LogError("packet too small from ", m_RemoteAddr); return false; @@ -557,16 +556,25 @@ namespace llarp llarp_buffer_t curbuf(buf.base, buf.sz); curbuf.base += ShortHash::SIZE; curbuf.sz -= ShortHash::SIZE; - if(not CryptoManager::instance()->hmac(H.data(), curbuf, m_SessionKey)) + if (not CryptoManager::instance()->hmac(H.data(), curbuf, m_SessionKey)) { LogError("failed to caclulate keyed hash for ", m_RemoteAddr); return false; } const ShortHash expected{buf.base}; - if(H != expected) - { - LogError("keyed hash missmatch ", H, " != ", expected, " from ", - m_RemoteAddr, " state=", int(m_State), " size=", buf.sz); + if (H != expected) + { + LogError( + "keyed hash missmatch ", + H, + " != ", + expected, + " from ", + m_RemoteAddr, + " state=", + int(m_State), + " size=", + buf.sz); return false; } const TunnelNonce N{curbuf.base}; @@ -579,7 +587,7 @@ namespace llarp void Session::Start() { - if(m_Inbound) + if (m_Inbound) return; GenerateAndSendIntro(); } @@ -587,43 +595,42 @@ namespace llarp void Session::HandleSessionData(Packet_t pkt) { - if(m_DecryptNext == nullptr) - m_DecryptNext = std::make_shared< CryptoQueue_t >(); + if (m_DecryptNext == nullptr) + m_DecryptNext = std::make_shared(); m_DecryptNext->emplace_back(std::move(pkt)); } void Session::DecryptWorker(CryptoQueue_ptr msgs) { - CryptoQueue_ptr recvMsgs = std::make_shared< CryptoQueue_t >(); - for(auto& pkt : *msgs) + CryptoQueue_ptr recvMsgs = std::make_shared(); + for (auto& pkt : *msgs) { - if(not DecryptMessageInPlace(pkt)) + if (not DecryptMessageInPlace(pkt)) { LogError("failed to decrypt session data from ", m_RemoteAddr); continue; } - if(pkt[PacketOverhead] != LLARP_PROTO_VERSION) + if (pkt[PacketOverhead] != LLARP_PROTO_VERSION) { - LogError("protocol version missmatch ", int(pkt[PacketOverhead]), - " != ", LLARP_PROTO_VERSION); + LogError( + "protocol version missmatch ", int(pkt[PacketOverhead]), " != ", LLARP_PROTO_VERSION); continue; } recvMsgs->emplace_back(std::move(pkt)); } LogDebug("decrypted ", recvMsgs->size(), " packets from ", m_RemoteAddr); LogicCall( - m_Parent->logic(), - std::bind(&Session::HandlePlaintext, shared_from_this(), recvMsgs)); + m_Parent->logic(), std::bind(&Session::HandlePlaintext, shared_from_this(), recvMsgs)); } void Session::HandlePlaintext(CryptoQueue_ptr msgs) { - for(auto& result : *msgs) + for (auto& result : *msgs) { LogDebug("Command ", int(result[PacketOverhead + 1])); - switch(result[PacketOverhead + 1]) + switch (result[PacketOverhead + 1]) { case Command::eXMIT: HandleXMIT(std::move(result)); @@ -647,8 +654,7 @@ namespace llarp HandleMACK(std::move(result)); break; default: - LogError("invalid command ", int(result[PacketOverhead + 1]), - " from ", m_RemoteAddr); + LogError("invalid command ", int(result[PacketOverhead + 1]), " from ", m_RemoteAddr); } } SendMACK(); @@ -659,26 +665,25 @@ namespace llarp void Session::HandleMACK(Packet_t data) { - if(data.size() < (3 + PacketOverhead)) + if (data.size() < (3 + PacketOverhead)) { LogError("impossibly short mack from ", m_RemoteAddr); return; } byte_t numAcks = data[CommandOverhead + PacketOverhead]; - if(data.size() - < 1 + CommandOverhead + PacketOverhead + (numAcks * sizeof(uint64_t))) + if (data.size() < 1 + CommandOverhead + PacketOverhead + (numAcks * sizeof(uint64_t))) { LogError("short mack from ", m_RemoteAddr); return; } LogDebug("got ", int(numAcks), " mack from ", m_RemoteAddr); byte_t* ptr = data.data() + CommandOverhead + PacketOverhead + 1; - while(numAcks > 0) + while (numAcks > 0) { uint64_t acked = bufbe64toh(ptr); LogDebug("mack containing txid=", acked, " from ", m_RemoteAddr); auto itr = m_TXMsgs.find(acked); - if(itr != m_TXMsgs.end()) + if (itr != m_TXMsgs.end()) { m_Stats.totalAckedTX++; m_Stats.totalInFlightTX--; @@ -697,16 +702,15 @@ namespace llarp void Session::HandleNACK(Packet_t data) { - if(data.size() < (CommandOverhead + sizeof(uint64_t) + PacketOverhead)) + if (data.size() < (CommandOverhead + sizeof(uint64_t) + PacketOverhead)) { LogError("short nack from ", m_RemoteAddr); return; } - uint64_t txid = - bufbe64toh(data.data() + CommandOverhead + PacketOverhead); + uint64_t txid = bufbe64toh(data.data() + CommandOverhead + PacketOverhead); LogDebug("got nack on ", txid, " from ", m_RemoteAddr); auto itr = m_TXMsgs.find(txid); - if(itr != m_TXMsgs.end()) + if (itr != m_TXMsgs.end()) { EncryptAndSend(itr->second.XMIT()); } @@ -717,24 +721,23 @@ namespace llarp Session::HandleXMIT(Packet_t data) { static constexpr size_t XMITOverhead = - (CommandOverhead + PacketOverhead + sizeof(uint16_t) - + sizeof(uint64_t) + ShortHash::SIZE); - if(data.size() < XMITOverhead) + (CommandOverhead + PacketOverhead + sizeof(uint16_t) + sizeof(uint64_t) + + ShortHash::SIZE); + if (data.size() < XMITOverhead) { LogError("short XMIT from ", m_RemoteAddr); return; } uint16_t sz = bufbe16toh(data.data() + CommandOverhead + PacketOverhead); - uint64_t rxid = bufbe64toh(data.data() + CommandOverhead - + sizeof(uint16_t) + PacketOverhead); - ShortHash h{data.data() + CommandOverhead + sizeof(uint16_t) - + sizeof(uint64_t) + PacketOverhead}; + uint64_t rxid = bufbe64toh(data.data() + CommandOverhead + sizeof(uint16_t) + PacketOverhead); + ShortHash h{data.data() + CommandOverhead + sizeof(uint16_t) + sizeof(uint64_t) + + PacketOverhead}; LogDebug("rxid=", rxid, " sz=", sz, " h=", h.ToHex()); m_LastRX = m_Parent->Now(); { // check for replay auto itr = m_ReplayFilter.find(rxid); - if(itr != m_ReplayFilter.end()) + if (itr != m_ReplayFilter.end()) { m_SendMACKs.emplace(rxid); LogDebug("duplicate rxid=", rxid, " from ", m_RemoteAddr); @@ -743,25 +746,22 @@ namespace llarp } { const auto now = m_Parent->Now(); - auto itr = m_RXMsgs.find(rxid); - if(itr == m_RXMsgs.end()) + auto itr = m_RXMsgs.find(rxid); + if (itr == m_RXMsgs.end()) { - itr = m_RXMsgs - .emplace( - rxid, - InboundMessage{rxid, sz, std::move(h), m_Parent->Now()}) - .first; + itr = + m_RXMsgs.emplace(rxid, InboundMessage{rxid, sz, std::move(h), m_Parent->Now()}).first; sz = std::min(sz, uint16_t{FragmentSize}); - if((data.size() - XMITOverhead) == sz) + if ((data.size() - XMITOverhead) == sz) { { const llarp_buffer_t buf(data.data() + (data.size() - sz), sz); itr->second.HandleData(0, buf, now); - if(not itr->second.IsCompleted()) + if (not itr->second.IsCompleted()) { return; } - if(not itr->second.Verify()) + if (not itr->second.Verify()) { LogError("bad short xmit hash from ", m_RemoteAddr); return; @@ -770,7 +770,7 @@ namespace llarp auto msg = std::move(itr->second); const llarp_buffer_t buf(msg.m_Data); m_Parent->HandleMessage(this, buf); - if(m_ReplayFilter.emplace(rxid, m_Parent->Now()).second) + if (m_ReplayFilter.emplace(rxid, m_Parent->Now()).second) m_SendMACKs.emplace(rxid); m_RXMsgs.erase(rxid); } @@ -783,20 +783,18 @@ namespace llarp void Session::HandleDATA(Packet_t data) { - if(data.size() < (CommandOverhead + sizeof(uint16_t) + sizeof(uint64_t) - + PacketOverhead)) + if (data.size() < (CommandOverhead + sizeof(uint16_t) + sizeof(uint64_t) + PacketOverhead)) { LogError("short DATA from ", m_RemoteAddr, " ", data.size()); return; } - m_LastRX = m_Parent->Now(); + m_LastRX = m_Parent->Now(); uint16_t sz = bufbe16toh(data.data() + CommandOverhead + PacketOverhead); - uint64_t rxid = bufbe64toh(data.data() + CommandOverhead - + sizeof(uint16_t) + PacketOverhead); - auto itr = m_RXMsgs.find(rxid); - if(itr == m_RXMsgs.end()) + uint64_t rxid = bufbe64toh(data.data() + CommandOverhead + sizeof(uint16_t) + PacketOverhead); + auto itr = m_RXMsgs.find(rxid); + if (itr == m_RXMsgs.end()) { - if(m_ReplayFilter.find(rxid) == m_ReplayFilter.end()) + if (m_ReplayFilter.find(rxid) == m_ReplayFilter.end()) { LogDebug("no rxid=", rxid, " for ", m_RemoteAddr); auto nack = CreatePacket(Command::eNACK, 8); @@ -812,19 +810,19 @@ namespace llarp } { - const llarp_buffer_t buf(data.data() + PacketOverhead + 12, - data.size() - (PacketOverhead + 12)); + const llarp_buffer_t buf( + data.data() + PacketOverhead + 12, data.size() - (PacketOverhead + 12)); itr->second.HandleData(sz, buf, m_Parent->Now()); } - if(itr->second.IsCompleted()) + if (itr->second.IsCompleted()) { - if(itr->second.Verify()) + if (itr->second.Verify()) { auto msg = std::move(itr->second); const llarp_buffer_t buf(msg.m_Data); m_Parent->HandleMessage(this, buf); - if(m_ReplayFilter.emplace(itr->first, m_Parent->Now()).second) + if (m_ReplayFilter.emplace(itr->first, m_Parent->Now()).second) m_SendMACKs.emplace(itr->first); } else @@ -838,23 +836,23 @@ namespace llarp void Session::HandleACKS(Packet_t data) { - if(data.size() < (11 + PacketOverhead)) + if (data.size() < (11 + PacketOverhead)) { LogError("short ACKS from ", m_RemoteAddr); return; } const auto now = m_Parent->Now(); - m_LastRX = now; - uint64_t txid = bufbe64toh(data.data() + 2 + PacketOverhead); - auto itr = m_TXMsgs.find(txid); - if(itr == m_TXMsgs.end()) + m_LastRX = now; + uint64_t txid = bufbe64toh(data.data() + 2 + PacketOverhead); + auto itr = m_TXMsgs.find(txid); + if (itr == m_TXMsgs.end()) { LogDebug("no txid=", txid, " for ", m_RemoteAddr); return; } itr->second.Ack(data[10 + PacketOverhead]); - if(itr->second.IsTransmitted()) + if (itr->second.IsTransmitted()) { LogDebug("sent message ", itr->first); itr->second.Completed(); @@ -862,8 +860,7 @@ namespace llarp } else { - itr->second.FlushUnAcked(util::memFn(&Session::EncryptAndSend, this), - now); + itr->second.FlushUnAcked(util::memFn(&Session::EncryptAndSend, this), now); } } @@ -881,7 +878,7 @@ namespace llarp bool Session::SendKeepAlive() { - if(m_State == State::Ready) + if (m_State == State::Ready) { EncryptAndSend(CreatePacket(Command::ePING, 0)); return true; @@ -902,14 +899,14 @@ namespace llarp // TODO: differentiate between good and bad RX packets here m_Stats.totalPacketsRX++; - switch(m_State) + switch (m_State) { case State::Initial: - if(m_Inbound) + if (m_Inbound) { // initial data // enter introduction phase - if(DecryptMessageInPlace(data)) + if (DecryptMessageInPlace(data)) { HandleGotIntro(std::move(data)); } @@ -926,7 +923,7 @@ namespace llarp } break; case State::Introduction: - if(m_Inbound) + if (m_Inbound) { // we are replying to an intro ack HandleCreateSessionRequest(std::move(data)); @@ -949,7 +946,7 @@ namespace llarp std::string Session::StateToString(State state) { - switch(state) + switch (state) { case State::Initial: return "Initial"; diff --git a/llarp/iwp/session.hpp b/llarp/iwp/session.hpp index 64e53c680..e845b26fa 100644 --- a/llarp/iwp/session.hpp +++ b/llarp/iwp/session.hpp @@ -15,8 +15,7 @@ namespace llarp static constexpr size_t PacketOverhead = HMACSIZE + TUNNONCESIZE; /// creates a packet with plaintext size + wire overhead + random pad ILinkSession::Packet_t - CreatePacket(Command cmd, size_t plainsize, size_t min_pad = 16, - size_t pad_variance = 16); + CreatePacket(Command cmd, size_t plainsize, size_t min_pad = 16, size_t pad_variance = 16); /// Time how long we try delivery for static constexpr std::chrono::milliseconds DeliveryTimeout = 500ms; /// Time how long we wait to recieve a message @@ -32,8 +31,7 @@ namespace llarp /// How long we wait for a session to die with no tx from them static constexpr auto SessionAliveTimeout = PingInterval * 5; - struct Session : public ILinkSession, - public std::enable_shared_from_this< Session > + struct Session : public ILinkSession, public std::enable_shared_from_this { using Time_t = std::chrono::milliseconds; @@ -41,14 +39,13 @@ namespace llarp static constexpr std::size_t MaxACKSInMACK = 1024 / sizeof(uint64_t); /// outbound session - Session(LinkLayer* parent, const RouterContact& rc, - const AddressInfo& ai); + Session(LinkLayer* parent, const RouterContact& rc, const AddressInfo& ai); /// inbound session Session(LinkLayer* parent, const Addr& from); ~Session() = default; - std::shared_ptr< ILinkSession > + std::shared_ptr BorrowSelf() override { return shared_from_this(); @@ -61,8 +58,7 @@ namespace llarp Tick(llarp_time_t now) override; bool - SendMessageBuffer(ILinkSession::Message_t msg, - CompletionHandler resultHandler) override; + SendMessageBuffer(ILinkSession::Message_t msg, CompletionHandler resultHandler) override; void Send_LL(const byte_t* buf, size_t sz); @@ -157,8 +153,8 @@ namespace llarp uint64_t totalPacketsRX = 0; - uint64_t totalAckedTX = 0; - uint64_t totalDroppedTX = 0; + uint64_t totalAckedTX = 0; + uint64_t totalDroppedTX = 0; uint64_t totalInFlightTX = 0; }; Stats m_Stats; @@ -176,7 +172,7 @@ namespace llarp /// session key SharedSecret m_SessionKey; /// session token - AlignedBuffer< 24 > token; + AlignedBuffer<24> token; PubKey m_ExpectedIdent; PubKey m_RemoteOnionKey; @@ -198,16 +194,16 @@ namespace llarp void ResetRates(); - std::unordered_map< uint64_t, InboundMessage > m_RXMsgs; - std::unordered_map< uint64_t, OutboundMessage > m_TXMsgs; + std::unordered_map m_RXMsgs; + std::unordered_map m_TXMsgs; /// maps rxid to time recieved - std::unordered_map< uint64_t, llarp_time_t > m_ReplayFilter; + std::unordered_map m_ReplayFilter; /// set of rx messages to send in next round of multiacks - std::unordered_set< uint64_t > m_SendMACKs; + std::unordered_set m_SendMACKs; - using CryptoQueue_t = std::vector< Packet_t >; - using CryptoQueue_ptr = std::shared_ptr< CryptoQueue_t >; + using CryptoQueue_t = std::vector; + using CryptoQueue_ptr = std::shared_ptr; CryptoQueue_ptr m_EncryptNext; CryptoQueue_ptr m_DecryptNext; diff --git a/llarp/link/factory.cpp b/llarp/link/factory.cpp index 41785e2ac..8a8f5b2a6 100644 --- a/llarp/link/factory.cpp +++ b/llarp/link/factory.cpp @@ -6,9 +6,9 @@ namespace llarp LinkFactory::LinkType LinkFactory::TypeFromName(string_view str) { - if(str == "iwp") + if (str == "iwp") return LinkType::eLinkIWP; - if(str == "mempipe") + if (str == "mempipe") return LinkType::eLinkMempipe; return LinkType::eLinkUnknown; } @@ -16,7 +16,7 @@ namespace llarp std::string LinkFactory::NameFromType(LinkFactory::LinkType tp) { - switch(tp) + switch (tp) { case LinkType::eLinkIWP: return "iwp"; @@ -30,10 +30,10 @@ namespace llarp LinkFactory::Factory LinkFactory::Obtain(LinkFactory::LinkType tp, bool permitInbound) { - switch(tp) + switch (tp) { case LinkType::eLinkIWP: - if(permitInbound) + if (permitInbound) return llarp::iwp::NewInboundLink; return llarp::iwp::NewOutboundLink; default: diff --git a/llarp/link/factory.hpp b/llarp/link/factory.hpp index 4b4bb43ee..bf1110f73 100644 --- a/llarp/link/factory.hpp +++ b/llarp/link/factory.hpp @@ -21,10 +21,16 @@ namespace llarp eLinkUnknown }; - using Factory = std::function< LinkLayer_ptr( - std::shared_ptr< KeyManager >, GetRCFunc, LinkMessageHandler, - SignBufferFunc, SessionEstablishedHandler, SessionRenegotiateHandler, - TimeoutHandler, SessionClosedHandler, PumpDoneHandler) >; + using Factory = std::function, + GetRCFunc, + LinkMessageHandler, + SignBufferFunc, + SessionEstablishedHandler, + SessionRenegotiateHandler, + TimeoutHandler, + SessionClosedHandler, + PumpDoneHandler)>; /// get link type by name string /// if invalid returns eLinkUnspec diff --git a/llarp/link/i_link_manager.hpp b/llarp/link/i_link_manager.hpp index 88f315e05..615844f8d 100644 --- a/llarp/link/i_link_manager.hpp +++ b/llarp/link/i_link_manager.hpp @@ -11,7 +11,7 @@ struct llarp_buffer_t; namespace llarp { - using Logic_ptr = std::shared_ptr< Logic >; + using Logic_ptr = std::shared_ptr; struct RouterContact; struct ILinkSession; @@ -23,17 +23,19 @@ namespace llarp virtual ~ILinkManager() = default; virtual LinkLayer_ptr - GetCompatibleLink(const RouterContact &rc) const = 0; + GetCompatibleLink(const RouterContact& rc) const = 0; - virtual IOutboundSessionMaker * + virtual IOutboundSessionMaker* GetSessionMaker() const = 0; virtual bool - SendTo(const RouterID &remote, const llarp_buffer_t &buf, - ILinkSession::CompletionHandler completed) = 0; + SendTo( + const RouterID& remote, + const llarp_buffer_t& buf, + ILinkSession::CompletionHandler completed) = 0; virtual bool - HasSessionTo(const RouterID &remote) const = 0; + HasSessionTo(const RouterID& remote) const = 0; virtual void PumpLinks() = 0; @@ -42,24 +44,23 @@ namespace llarp AddLink(LinkLayer_ptr link, bool inbound = false) = 0; virtual bool - StartLinks(Logic_ptr logic, - std::shared_ptr< thread::ThreadPool > worker) = 0; + StartLinks(Logic_ptr logic, std::shared_ptr worker) = 0; virtual void Stop() = 0; virtual void - PersistSessionUntil(const RouterID &remote, llarp_time_t until) = 0; + PersistSessionUntil(const RouterID& remote, llarp_time_t until) = 0; virtual void - ForEachPeer(std::function< void(const ILinkSession *, bool) > visit, - bool randomize = false) const = 0; + ForEachPeer( + std::function visit, bool randomize = false) const = 0; virtual void - ForEachPeer(std::function< void(ILinkSession *) > visit) = 0; + ForEachPeer(std::function visit) = 0; virtual void - ForEachInboundLink(std::function< void(LinkLayer_ptr) > visit) const = 0; + ForEachInboundLink(std::function visit) const = 0; virtual size_t NumberOfConnectedRouters() const = 0; @@ -71,7 +72,7 @@ namespace llarp NumberOfPendingConnections() const = 0; virtual bool - GetRandomConnectedRouter(RouterContact &router) const = 0; + GetRandomConnectedRouter(RouterContact& router) const = 0; virtual void CheckPersistingSessions(llarp_time_t now) = 0; diff --git a/llarp/link/link_manager.cpp b/llarp/link/link_manager.cpp index df375a8c6..5c80bac41 100644 --- a/llarp/link/link_manager.cpp +++ b/llarp/link/link_manager.cpp @@ -9,17 +9,17 @@ namespace llarp { LinkLayer_ptr - LinkManager::GetCompatibleLink(const RouterContact &rc) const + LinkManager::GetCompatibleLink(const RouterContact& rc) const { - if(stopping) + if (stopping) return nullptr; - for(auto &link : outboundLinks) + for (auto& link : outboundLinks) { // TODO: may want to add some memory of session failures for a given // router on a given link and not return that link here for a // duration - if(!link->IsCompatable(rc)) + if (!link->IsCompatable(rc)) continue; return link; @@ -28,23 +28,23 @@ namespace llarp return nullptr; } - IOutboundSessionMaker * + IOutboundSessionMaker* LinkManager::GetSessionMaker() const { return _sessionMaker; } bool - LinkManager::SendTo(const RouterID &remote, const llarp_buffer_t &buf, - ILinkSession::CompletionHandler completed) + LinkManager::SendTo( + const RouterID& remote, const llarp_buffer_t& buf, ILinkSession::CompletionHandler completed) { - if(stopping) + if (stopping) return false; auto link = GetLinkWithSessionTo(remote); - if(link == nullptr) + if (link == nullptr) { - if(completed) + if (completed) { completed(ILinkSession::DeliveryStatus::eDeliveryDropped); } @@ -55,7 +55,7 @@ namespace llarp } bool - LinkManager::HasSessionTo(const RouterID &remote) const + LinkManager::HasSessionTo(const RouterID& remote) const { return GetLinkWithSessionTo(remote) != nullptr; } @@ -63,11 +63,11 @@ namespace llarp void LinkManager::PumpLinks() { - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) { link->Pump(); } - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) { link->Pump(); } @@ -78,7 +78,7 @@ namespace llarp { util::Lock l(_mutex); - if(inbound) + if (inbound) { inboundLinks.emplace(link); } @@ -89,13 +89,12 @@ namespace llarp } bool - LinkManager::StartLinks(Logic_ptr logic, - std::shared_ptr< thread::ThreadPool > worker) + LinkManager::StartLinks(Logic_ptr logic, std::shared_ptr worker) { LogInfo("starting ", outboundLinks.size(), " outbound links"); - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) { - if(!link->Start(logic, worker)) + if (!link->Start(logic, worker)) { LogWarn("outbound link '", link->Name(), "' failed to start"); return false; @@ -103,12 +102,12 @@ namespace llarp LogDebug("Outbound Link ", link->Name(), " started"); } - if(inboundLinks.size()) + if (inboundLinks.size()) { LogInfo("starting ", inboundLinks.size(), " inbound links"); - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) { - if(!link->Start(logic, worker)) + if (!link->Start(logic, worker)) { LogWarn("Link ", link->Name(), " failed to start"); return false; @@ -123,7 +122,7 @@ namespace llarp void LinkManager::Stop() { - if(stopping) + if (stopping) { return; } @@ -133,66 +132,62 @@ namespace llarp LogInfo("stopping links"); stopping = true; - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) link->Stop(); - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) link->Stop(); } void - LinkManager::PersistSessionUntil(const RouterID &remote, llarp_time_t until) + LinkManager::PersistSessionUntil(const RouterID& remote, llarp_time_t until) { - if(stopping) + if (stopping) return; util::Lock l(_mutex); - auto &curr = m_PersistingSessions[remote]; - if(until > curr) + auto& curr = m_PersistingSessions[remote]; + if (until > curr) curr = until; LogDebug("persist session to ", remote, " until ", curr - time_now_ms()); } void LinkManager::ForEachPeer( - std::function< void(const ILinkSession *, bool) > visit, - bool randomize) const + std::function visit, bool randomize) const { - if(stopping) + if (stopping) return; - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) { - link->ForEachSession( - [visit](const ILinkSession *peer) { visit(peer, true); }, randomize); + link->ForEachSession([visit](const ILinkSession* peer) { visit(peer, true); }, randomize); } - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) { - link->ForEachSession( - [visit](const ILinkSession *peer) { visit(peer, false); }, randomize); + link->ForEachSession([visit](const ILinkSession* peer) { visit(peer, false); }, randomize); } } void - LinkManager::ForEachPeer(std::function< void(ILinkSession *) > visit) + LinkManager::ForEachPeer(std::function visit) { - if(stopping) + if (stopping) return; - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) { - link->ForEachSession([visit](ILinkSession *peer) { visit(peer); }); + link->ForEachSession([visit](ILinkSession* peer) { visit(peer); }); } - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) { - link->ForEachSession([visit](ILinkSession *peer) { visit(peer); }); + link->ForEachSession([visit](ILinkSession* peer) { visit(peer); }); } } void - LinkManager::ForEachInboundLink( - std::function< void(LinkLayer_ptr) > visit) const + LinkManager::ForEachInboundLink(std::function visit) const { - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) { visit(link); } @@ -201,13 +196,13 @@ namespace llarp size_t LinkManager::NumberOfConnectedRouters() const { - std::set< RouterID > connectedRouters; + std::set connectedRouters; - auto fn = [&connectedRouters](const ILinkSession *session, bool) { - if(session->IsEstablished()) + auto fn = [&connectedRouters](const ILinkSession* session, bool) { + if (session->IsEstablished()) { const RouterContact rc(session->GetRemoteRC()); - if(rc.IsPublicRouter()) + if (rc.IsPublicRouter()) { connectedRouters.insert(rc.pubkey); } @@ -222,13 +217,13 @@ namespace llarp size_t LinkManager::NumberOfConnectedClients() const { - std::set< RouterID > connectedClients; + std::set connectedClients; - auto fn = [&connectedClients](const ILinkSession *session, bool) { - if(session->IsEstablished()) + auto fn = [&connectedClients](const ILinkSession* session, bool) { + if (session->IsEstablished()) { const RouterContact rc(session->GetRemoteRC()); - if(!rc.IsPublicRouter()) + if (!rc.IsPublicRouter()) { connectedClients.insert(rc.pubkey); } @@ -244,12 +239,12 @@ namespace llarp LinkManager::NumberOfPendingConnections() const { size_t pending = 0; - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) { pending += link->NumberOfPendingSessions(); } - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) { pending += link->NumberOfPendingSessions(); } @@ -258,23 +253,22 @@ namespace llarp } bool - LinkManager::GetRandomConnectedRouter(RouterContact &router) const + LinkManager::GetRandomConnectedRouter(RouterContact& router) const { - std::unordered_map< RouterID, RouterContact, RouterID::Hash > - connectedRouters; + std::unordered_map connectedRouters; ForEachPeer( - [&connectedRouters](const ILinkSession *peer, bool unused) { + [&connectedRouters](const ILinkSession* peer, bool unused) { (void)unused; connectedRouters[peer->GetPubKey()] = peer->GetRemoteRC(); }, false); const auto sz = connectedRouters.size(); - if(sz) + if (sz) { auto itr = connectedRouters.begin(); - if(sz > 1) + if (sz > 1) { std::advance(itr, randint() % sz); } @@ -290,21 +284,21 @@ namespace llarp void LinkManager::CheckPersistingSessions(llarp_time_t now) { - if(stopping) + if (stopping) return; - std::vector< RouterID > sessionsNeeded; + std::vector sessionsNeeded; { util::Lock l(_mutex); auto itr = m_PersistingSessions.begin(); - while(itr != m_PersistingSessions.end()) + while (itr != m_PersistingSessions.end()) { - if(now < itr->second) + if (now < itr->second) { auto link = GetLinkWithSessionTo(itr->first); - if(link) + if (link) { link->KeepAliveSessionTo(itr->first); } @@ -319,7 +313,7 @@ namespace llarp const RouterID r(itr->first); LogInfo("commit to ", r, " expired"); itr = m_PersistingSessions.erase(itr); - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) { link->CloseSessionTo(r); } @@ -327,7 +321,7 @@ namespace llarp } } - for(const auto &router : sessionsNeeded) + for (const auto& router : sessionsNeeded) { _sessionMaker->CreateSessionTo(router, nullptr); } @@ -336,17 +330,17 @@ namespace llarp util::StatusObject LinkManager::ExtractStatus() const { - std::vector< util::StatusObject > ob_links, ib_links; - std::transform(inboundLinks.begin(), inboundLinks.end(), - std::back_inserter(ib_links), - [](const auto &link) -> util::StatusObject { - return link->ExtractStatus(); - }); - std::transform(outboundLinks.begin(), outboundLinks.end(), - std::back_inserter(ob_links), - [](const auto &link) -> util::StatusObject { - return link->ExtractStatus(); - }); + std::vector ob_links, ib_links; + std::transform( + inboundLinks.begin(), + inboundLinks.end(), + std::back_inserter(ib_links), + [](const auto& link) -> util::StatusObject { return link->ExtractStatus(); }); + std::transform( + outboundLinks.begin(), + outboundLinks.end(), + std::back_inserter(ob_links), + [](const auto& link) -> util::StatusObject { return link->ExtractStatus(); }); util::StatusObject obj{{"outbound", ob_links}, {"inbound", ib_links}}; @@ -354,28 +348,28 @@ namespace llarp } void - LinkManager::Init(IOutboundSessionMaker *sessionMaker) + LinkManager::Init(IOutboundSessionMaker* sessionMaker) { - stopping = false; + stopping = false; _sessionMaker = sessionMaker; } LinkLayer_ptr - LinkManager::GetLinkWithSessionTo(const RouterID &remote) const + LinkManager::GetLinkWithSessionTo(const RouterID& remote) const { - if(stopping) + if (stopping) return nullptr; - for(const auto &link : outboundLinks) + for (const auto& link : outboundLinks) { - if(link->HasSessionTo(remote)) + if (link->HasSessionTo(remote)) { return link; } } - for(const auto &link : inboundLinks) + for (const auto& link : inboundLinks) { - if(link->HasSessionTo(remote)) + if (link->HasSessionTo(remote)) { return link; } diff --git a/llarp/link/link_manager.hpp b/llarp/link/link_manager.hpp index 0d3f3666d..a4a2e1f58 100644 --- a/llarp/link/link_manager.hpp +++ b/llarp/link/link_manager.hpp @@ -21,17 +21,19 @@ namespace llarp ~LinkManager() override = default; LinkLayer_ptr - GetCompatibleLink(const RouterContact &rc) const override; + GetCompatibleLink(const RouterContact& rc) const override; - IOutboundSessionMaker * + IOutboundSessionMaker* GetSessionMaker() const override; bool - SendTo(const RouterID &remote, const llarp_buffer_t &buf, - ILinkSession::CompletionHandler completed) override; + SendTo( + const RouterID& remote, + const llarp_buffer_t& buf, + ILinkSession::CompletionHandler completed) override; bool - HasSessionTo(const RouterID &remote) const override; + HasSessionTo(const RouterID& remote) const override; void PumpLinks() override; @@ -40,25 +42,23 @@ namespace llarp AddLink(LinkLayer_ptr link, bool inbound = false) override; bool - StartLinks(Logic_ptr logic, - std::shared_ptr< thread::ThreadPool > worker) override; + StartLinks(Logic_ptr logic, std::shared_ptr worker) override; void Stop() override; void - PersistSessionUntil(const RouterID &remote, llarp_time_t until) override; + PersistSessionUntil(const RouterID& remote, llarp_time_t until) override; void - ForEachPeer(std::function< void(const ILinkSession *, bool) > visit, - bool randomize = false) const override; + ForEachPeer(std::function visit, bool randomize = false) + const override; void - ForEachPeer(std::function< void(ILinkSession *) > visit) override; + ForEachPeer(std::function visit) override; void - ForEachInboundLink( - std::function< void(LinkLayer_ptr) > visit) const override; + ForEachInboundLink(std::function visit) const override; size_t NumberOfConnectedRouters() const override; @@ -70,7 +70,7 @@ namespace llarp NumberOfPendingConnections() const override; bool - GetRandomConnectedRouter(RouterContact &router) const override; + GetRandomConnectedRouter(RouterContact& router) const override; void CheckPersistingSessions(llarp_time_t now) override; @@ -79,25 +79,25 @@ namespace llarp ExtractStatus() const override; void - Init(IOutboundSessionMaker *sessionMaker); + Init(IOutboundSessionMaker* sessionMaker); private: LinkLayer_ptr - GetLinkWithSessionTo(const RouterID &remote) const; + GetLinkWithSessionTo(const RouterID& remote) const; - std::atomic< bool > stopping; + std::atomic stopping; mutable util::Mutex _mutex; // protects m_PersistingSessions - using LinkSet = std::set< LinkLayer_ptr, ComparePtr< LinkLayer_ptr > >; + using LinkSet = std::set>; LinkSet outboundLinks; LinkSet inboundLinks; // sessions to persist -> timestamp to end persist at - std::unordered_map< RouterID, llarp_time_t, RouterID::Hash > - m_PersistingSessions GUARDED_BY(_mutex); + std::unordered_map m_PersistingSessions + GUARDED_BY(_mutex); - IOutboundSessionMaker *_sessionMaker; + IOutboundSessionMaker* _sessionMaker; }; } // namespace llarp diff --git a/llarp/link/server.cpp b/llarp/link/server.cpp index b8550dbb0..45f87511e 100644 --- a/llarp/link/server.cpp +++ b/llarp/link/server.cpp @@ -13,13 +13,16 @@ namespace llarp { static constexpr size_t MaxSessionsPerKey = 16; - ILinkLayer::ILinkLayer(std::shared_ptr< KeyManager > keyManager, - GetRCFunc getrc, LinkMessageHandler handler, - SignBufferFunc signbuf, - SessionEstablishedHandler establishedSession, - SessionRenegotiateHandler reneg, - TimeoutHandler timeout, SessionClosedHandler closed, - PumpDoneHandler pumpDone) + ILinkLayer::ILinkLayer( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler handler, + SignBufferFunc signbuf, + SessionEstablishedHandler establishedSession, + SessionRenegotiateHandler reneg, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone) : HandleMessage(std::move(handler)) , HandleTimeout(std::move(timeout)) , Sign(std::move(signbuf)) @@ -43,50 +46,48 @@ namespace llarp } void - ILinkLayer::ForEachSession(std::function< void(const ILinkSession*) > visit, - bool randomize) const + ILinkLayer::ForEachSession(std::function visit, bool randomize) const { - std::vector< std::shared_ptr< ILinkSession > > sessions; + std::vector> sessions; { Lock_t l(m_AuthedLinksMutex); - if(m_AuthedLinks.size() == 0) + if (m_AuthedLinks.size() == 0) return; const size_t sz = randint() % m_AuthedLinks.size(); - auto itr = m_AuthedLinks.begin(); - auto begin = itr; - if(randomize) + auto itr = m_AuthedLinks.begin(); + auto begin = itr; + if (randomize) { std::advance(itr, sz); begin = itr; } - while(itr != m_AuthedLinks.end()) + while (itr != m_AuthedLinks.end()) { sessions.emplace_back(itr->second); ++itr; } - if(randomize) + if (randomize) { itr = m_AuthedLinks.begin(); - while(itr != begin) + while (itr != begin) { sessions.emplace_back(itr->second); ++itr; } } } - for(const auto& session : sessions) + for (const auto& session : sessions) visit(session.get()); } bool - ILinkLayer::VisitSessionByPubkey(const RouterID& pk, - std::function< bool(ILinkSession*) > visit) + ILinkLayer::VisitSessionByPubkey(const RouterID& pk, std::function visit) { - std::shared_ptr< ILinkSession > session; + std::shared_ptr session; { Lock_t l(m_AuthedLinksMutex); auto itr = m_AuthedLinks.find(pk); - if(itr == m_AuthedLinks.end()) + if (itr == m_AuthedLinks.end()) return false; session = itr->second; } @@ -94,36 +95,35 @@ namespace llarp } void - ILinkLayer::ForEachSession(std::function< void(ILinkSession*) > visit) + ILinkLayer::ForEachSession(std::function visit) { - std::vector< std::shared_ptr< ILinkSession > > sessions; + std::vector> sessions; { Lock_t l(m_AuthedLinksMutex); auto itr = m_AuthedLinks.begin(); - while(itr != m_AuthedLinks.end()) + while (itr != m_AuthedLinks.end()) { sessions.emplace_back(itr->second); ++itr; } } - for(const auto& s : sessions) + for (const auto& s : sessions) visit(s.get()); } bool - ILinkLayer::Configure(llarp_ev_loop_ptr loop, const std::string& ifname, - int af, uint16_t port) + ILinkLayer::Configure(llarp_ev_loop_ptr loop, const std::string& ifname, int af, uint16_t port) { - m_Loop = loop; - m_udp.user = this; + m_Loop = loop; + m_udp.user = this; m_udp.recvfrom = nullptr; - m_udp.tick = &ILinkLayer::udp_tick; - if(ifname == "*") + m_udp.tick = &ILinkLayer::udp_tick; + if (ifname == "*") { - if(!AllInterfaces(af, m_ourAddr)) + if (!AllInterfaces(af, m_ourAddr)) return false; } - else if(!GetIFAddr(ifname, m_ourAddr, af)) + else if (!GetIFAddr(ifname, m_ourAddr, af)) m_ourAddr = Addr(ifname); m_ourAddr.port(port); return llarp_ev_add_udp(m_Loop.get(), &m_udp, m_ourAddr) != -1; @@ -132,23 +132,22 @@ namespace llarp void ILinkLayer::Pump() { - std::unordered_set< RouterID, RouterID::Hash > closedSessions; - std::vector< std::shared_ptr< ILinkSession > > closedPending; + std::unordered_set closedSessions; + std::vector> closedPending; auto _now = Now(); { Lock_t l(m_AuthedLinksMutex); auto itr = m_AuthedLinks.begin(); - while(itr != m_AuthedLinks.end()) + while (itr != m_AuthedLinks.end()) { - if(not itr->second->TimedOut(_now)) + if (not itr->second->TimedOut(_now)) { itr->second->Pump(); ++itr; } else { - llarp::LogInfo("session to ", RouterID(itr->second->GetPubKey()), - " timed out"); + llarp::LogInfo("session to ", RouterID(itr->second->GetPubKey()), " timed out"); itr->second->Close(); closedSessions.emplace(itr->first); itr = m_AuthedLinks.erase(itr); @@ -159,9 +158,9 @@ namespace llarp Lock_t l(m_PendingMutex); auto itr = m_Pending.begin(); - while(itr != m_Pending.end()) + while (itr != m_Pending.end()) { - if(not itr->second->TimedOut(_now)) + if (not itr->second->TimedOut(_now)) { itr->second->Pump(); ++itr; @@ -177,17 +176,17 @@ namespace llarp } { Lock_t l(m_AuthedLinksMutex); - for(const auto& r : closedSessions) + for (const auto& r : closedSessions) { - if(m_AuthedLinks.count(r) == 0) + if (m_AuthedLinks.count(r) == 0) { SessionClosed(r); } } } - for(const auto& pending : closedPending) + for (const auto& pending : closedPending) { - if(pending->IsInbound()) + if (pending->IsInbound()) continue; HandleTimeout(pending.get()); } @@ -199,10 +198,10 @@ namespace llarp Lock_t l_authed(m_AuthedLinksMutex); Lock_t l_pending(m_PendingMutex); llarp::Addr addr = s->GetRemoteEndpoint(); - auto itr = m_Pending.find(addr); - if(itr != m_Pending.end()) + auto itr = m_Pending.find(addr); + if (itr != m_Pending.end()) { - if(m_AuthedLinks.count(pk) > MaxSessionsPerKey) + if (m_AuthedLinks.count(pk) > MaxSessionsPerKey) { LogWarn("too many session for ", pk); s->Close(); @@ -216,13 +215,12 @@ namespace llarp } bool - ILinkLayer::PickAddress(const RouterContact& rc, - llarp::AddressInfo& picked) const + ILinkLayer::PickAddress(const RouterContact& rc, llarp::AddressInfo& picked) const { std::string OurDialect = Name(); - for(const auto& addr : rc.addrs) + for (const auto& addr : rc.addrs) { - if(addr.dialect == OurDialect) + if (addr.dialect == OurDialect) { picked = addr; return true; @@ -234,31 +232,29 @@ namespace llarp util::StatusObject ILinkLayer::ExtractStatus() const { - std::vector< util::StatusObject > pending, established; + std::vector pending, established; { Lock_t l(m_PendingMutex); - std::transform(m_Pending.cbegin(), m_Pending.cend(), - std::back_inserter(pending), - [](const auto& item) -> util::StatusObject { - return item.second->ExtractStatus(); - }); + std::transform( + m_Pending.cbegin(), + m_Pending.cend(), + std::back_inserter(pending), + [](const auto& item) -> util::StatusObject { return item.second->ExtractStatus(); }); } { Lock_t l(m_AuthedLinksMutex); - std::transform(m_AuthedLinks.cbegin(), m_AuthedLinks.cend(), - std::back_inserter(established), - [](const auto& item) -> util::StatusObject { - return item.second->ExtractStatus(); - }); + std::transform( + m_AuthedLinks.cbegin(), + m_AuthedLinks.cend(), + std::back_inserter(established), + [](const auto& item) -> util::StatusObject { return item.second->ExtractStatus(); }); } return {{"name", Name()}, {"rank", uint64_t(Rank())}, {"addr", m_ourAddr.ToString()}, - {"sessions", - util::StatusObject{{"pending", pending}, - {"established", established}}}}; + {"sessions", util::StatusObject{{"pending", pending}, {"established", established}}}}; } bool @@ -266,29 +262,31 @@ namespace llarp { { Lock_t l(m_AuthedLinksMutex); - if(m_AuthedLinks.count(rc.pubkey) >= MaxSessionsPerKey) + if (m_AuthedLinks.count(rc.pubkey) >= MaxSessionsPerKey) { - LogDebug("Too many links to ", RouterID{rc.pubkey}, - ", not establishing another one"); + LogDebug("Too many links to ", RouterID{rc.pubkey}, ", not establishing another one"); return false; } } llarp::AddressInfo to; - if(!PickAddress(rc, to)) + if (!PickAddress(rc, to)) return false; const llarp::Addr addr(to); { Lock_t l(m_PendingMutex); - if(m_Pending.count(addr) >= MaxSessionsPerKey) + if (m_Pending.count(addr) >= MaxSessionsPerKey) { - LogDebug("Too many pending connections to ", addr, - " while establishing to ", RouterID{rc.pubkey}, - ", not establishing another"); + LogDebug( + "Too many pending connections to ", + addr, + " while establishing to ", + RouterID{rc.pubkey}, + ", not establishing another"); return false; } } - std::shared_ptr< ILinkSession > s = NewOutboundSession(rc, to); - if(PutSession(s)) + std::shared_ptr s = NewOutboundSession(rc, to); + if (PutSession(s)) { s->Start(); return true; @@ -297,11 +295,10 @@ namespace llarp } bool - ILinkLayer::Start(std::shared_ptr< Logic > l, - std::shared_ptr< thread::ThreadPool > worker) + ILinkLayer::Start(std::shared_ptr l, std::shared_ptr worker) { m_Worker = worker; - m_Logic = l; + m_Logic = l; ScheduleTick(LINK_LAYER_TICK_INTERVAL); return true; } @@ -312,7 +309,7 @@ namespace llarp { Lock_t l(m_AuthedLinksMutex); auto itr = m_AuthedLinks.begin(); - while(itr != m_AuthedLinks.end()) + while (itr != m_AuthedLinks.end()) { itr->second->Tick(now); ++itr; @@ -322,7 +319,7 @@ namespace llarp { Lock_t l(m_PendingMutex); auto itr = m_Pending.begin(); - while(itr != m_Pending.end()) + while (itr != m_Pending.end()) { itr->second->Tick(now); ++itr; @@ -331,9 +328,9 @@ namespace llarp { // decay recently closed list auto itr = m_RecentlyClosed.begin(); - while(itr != m_RecentlyClosed.end()) + while (itr != m_RecentlyClosed.end()) { - if(itr->second >= now) + if (itr->second >= now) itr = m_RecentlyClosed.erase(itr); else ++itr; @@ -344,12 +341,12 @@ namespace llarp void ILinkLayer::Stop() { - if(m_Logic && tick_id) + if (m_Logic && tick_id) m_Logic->remove_call(tick_id); { Lock_t l(m_AuthedLinksMutex); auto itr = m_AuthedLinks.begin(); - while(itr != m_AuthedLinks.end()) + while (itr != m_AuthedLinks.end()) { itr->second->Close(); ++itr; @@ -358,7 +355,7 @@ namespace llarp { Lock_t l(m_PendingMutex); auto itr = m_Pending.begin(); - while(itr != m_Pending.end()) + while (itr != m_Pending.end()) { itr->second->Close(); ++itr; @@ -370,17 +367,16 @@ namespace llarp ILinkLayer::CloseSessionTo(const RouterID& remote) { static constexpr auto CloseGraceWindow = 500ms; - const auto now = Now(); + const auto now = Now(); Lock_t l(m_AuthedLinksMutex); RouterID r = remote; llarp::LogInfo("Closing all to ", r); auto range = m_AuthedLinks.equal_range(r); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { itr->second->Close(); - m_RecentlyClosed.emplace(itr->second->GetRemoteEndpoint(), - now + CloseGraceWindow); + m_RecentlyClosed.emplace(itr->second->GetRemoteEndpoint(), now + CloseGraceWindow); itr = m_AuthedLinks.erase(itr); } } @@ -390,10 +386,10 @@ namespace llarp { Lock_t l(m_AuthedLinksMutex); auto range = m_AuthedLinks.equal_range(remote); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { - if(itr->second->ShouldPing()) + if (itr->second->ShouldPing()) { LogDebug("keepalive to ", remote); itr->second->SendKeepAlive(); @@ -403,23 +399,23 @@ namespace llarp } bool - ILinkLayer::SendTo(const RouterID& remote, const llarp_buffer_t& buf, - ILinkSession::CompletionHandler completed) + ILinkLayer::SendTo( + const RouterID& remote, const llarp_buffer_t& buf, ILinkSession::CompletionHandler completed) { - std::shared_ptr< ILinkSession > s; + std::shared_ptr s; { Lock_t l(m_AuthedLinksMutex); auto range = m_AuthedLinks.equal_range(remote); - auto itr = range.first; + auto itr = range.first; // pick lowest backlog session - size_t min = std::numeric_limits< size_t >::max(); + size_t min = std::numeric_limits::max(); - while(itr != range.second) + while (itr != range.second) { const auto backlog = itr->second->SendQueueBacklog(); - if(backlog < min) + if (backlog < min) { - s = itr->second; + s = itr->second; min = backlog; } ++itr; @@ -434,10 +430,10 @@ namespace llarp ILinkLayer::GetOurAddressInfo(llarp::AddressInfo& addr) const { addr.dialect = Name(); - addr.pubkey = TransportPubKey(); - addr.rank = Rank(); - addr.port = m_ourAddr.port(); - addr.ip = *m_ourAddr.addr6(); + addr.pubkey = TransportPubKey(); + addr.rank = Rank(); + addr.port = m_ourAddr.port(); + addr.ip = *m_ourAddr.addr6(); return true; } @@ -454,12 +450,12 @@ namespace llarp } bool - ILinkLayer::PutSession(const std::shared_ptr< ILinkSession >& s) + ILinkLayer::PutSession(const std::shared_ptr& s) { static constexpr size_t MaxSessionsPerEndpoint = 5; Lock_t lock(m_PendingMutex); llarp::Addr addr = s->GetRemoteEndpoint(); - if(m_Pending.count(addr) >= MaxSessionsPerEndpoint) + if (m_Pending.count(addr) >= MaxSessionsPerEndpoint) return false; m_Pending.emplace(addr, s); return true; @@ -476,25 +472,23 @@ namespace llarp void ILinkLayer::ScheduleTick(llarp_time_t interval) { - tick_id = - m_Logic->call_later(interval, std::bind(&ILinkLayer::OnTick, this)); + tick_id = m_Logic->call_later(interval, std::bind(&ILinkLayer::OnTick, this)); } void ILinkLayer::udp_tick(llarp_udp_io* udp) { - ILinkLayer* link = static_cast< ILinkLayer* >(udp->user); - auto pkts = std::make_shared< llarp_pkt_list >(); + ILinkLayer* link = static_cast(udp->user); + auto pkts = std::make_shared(); llarp_ev_udp_recvmany(&link->m_udp, pkts.get()); auto logic = link->logic(); - if(logic == nullptr) + if (logic == nullptr) return; LogicCall(logic, [pkts, link]() { auto itr = pkts->begin(); - while(itr != pkts->end()) + while (itr != pkts->end()) { - if(link->m_RecentlyClosed.find(itr->remote) - == link->m_RecentlyClosed.end()) + if (link->m_RecentlyClosed.find(itr->remote) == link->m_RecentlyClosed.end()) { link->RecvFrom(itr->remote, std::move(itr->pkt)); } diff --git a/llarp/link/server.hpp b/llarp/link/server.hpp index 733cbaf04..24b3db8c1 100644 --- a/llarp/link/server.hpp +++ b/llarp/link/server.hpp @@ -18,45 +18,47 @@ namespace llarp { /// handle a link layer message - using LinkMessageHandler = - std::function< bool(ILinkSession*, const llarp_buffer_t&) >; + using LinkMessageHandler = std::function; /// sign a buffer with identity key - using SignBufferFunc = - std::function< bool(Signature&, const llarp_buffer_t&) >; + using SignBufferFunc = std::function; /// handle connection timeout - using TimeoutHandler = std::function< void(ILinkSession*) >; + using TimeoutHandler = std::function; /// get our RC - using GetRCFunc = std::function< const llarp::RouterContact&(void) >; + using GetRCFunc = std::function; /// handler of session established /// return false to reject /// return true to accept - using SessionEstablishedHandler = std::function< bool(ILinkSession*) >; + using SessionEstablishedHandler = std::function; /// f(new, old) /// handler of session renegotiation /// returns true if the new rc is valid /// returns false otherwise and the session is terminated - using SessionRenegotiateHandler = - std::function< bool(llarp::RouterContact, llarp::RouterContact) >; + using SessionRenegotiateHandler = std::function; /// handles close of all sessions with pubkey - using SessionClosedHandler = std::function< void(llarp::RouterID) >; + using SessionClosedHandler = std::function; /// notifies router that a link session has ended its pump and we should flush /// messages to upper layers - using PumpDoneHandler = std::function< void(void) >; + using PumpDoneHandler = std::function; struct ILinkLayer { - ILinkLayer(std::shared_ptr< KeyManager > keyManager, GetRCFunc getrc, - LinkMessageHandler handler, SignBufferFunc signFunc, - SessionEstablishedHandler sessionEstablish, - SessionRenegotiateHandler renegotiate, TimeoutHandler timeout, - SessionClosedHandler closed, PumpDoneHandler pumpDone); + ILinkLayer( + std::shared_ptr keyManager, + GetRCFunc getrc, + LinkMessageHandler handler, + SignBufferFunc signFunc, + SessionEstablishedHandler sessionEstablish, + SessionRenegotiateHandler renegotiate, + TimeoutHandler timeout, + SessionClosedHandler closed, + PumpDoneHandler pumpDone); virtual ~ILinkLayer(); /// get current time via event loop @@ -70,12 +72,11 @@ namespace llarp HasSessionTo(const RouterID& pk); void - ForEachSession(std::function< void(const ILinkSession*) > visit, - bool randomize = false) const EXCLUDES(m_AuthedLinksMutex); + ForEachSession(std::function visit, bool randomize = false) const + EXCLUDES(m_AuthedLinksMutex); void - ForEachSession(std::function< void(ILinkSession*) > visit) - EXCLUDES(m_AuthedLinksMutex); + ForEachSession(std::function visit) EXCLUDES(m_AuthedLinksMutex); static void udp_tick(llarp_udp_io* udp); @@ -87,10 +88,9 @@ namespace llarp } virtual bool - Configure(llarp_ev_loop_ptr loop, const std::string& ifname, int af, - uint16_t port); + Configure(llarp_ev_loop_ptr loop, const std::string& ifname, int af, uint16_t port); - virtual std::shared_ptr< ILinkSession > + virtual std::shared_ptr NewOutboundSession(const RouterContact& rc, const AddressInfo& ai) = 0; virtual void @@ -106,8 +106,7 @@ namespace llarp TryEstablishTo(RouterContact rc); bool - Start(std::shared_ptr< llarp::Logic > l, - std::shared_ptr< thread::ThreadPool > worker); + Start(std::shared_ptr l, std::shared_ptr worker); virtual void Stop(); @@ -125,15 +124,16 @@ namespace llarp KeepAliveSessionTo(const RouterID& remote); virtual bool - SendTo(const RouterID& remote, const llarp_buffer_t& buf, - ILinkSession::CompletionHandler completed); + SendTo( + const RouterID& remote, + const llarp_buffer_t& buf, + ILinkSession::CompletionHandler completed); virtual bool GetOurAddressInfo(AddressInfo& addr) const; bool - VisitSessionByPubkey(const RouterID& pk, - std::function< bool(ILinkSession*) > visit) + VisitSessionByPubkey(const RouterID& pk, std::function visit) EXCLUDES(m_AuthedLinksMutex); virtual uint16_t @@ -155,8 +155,8 @@ namespace llarp IsCompatable(const llarp::RouterContact& other) const { const std::string us = Name(); - for(const auto& ai : other.addrs) - if(ai.dialect == us) + for (const auto& ai : other.addrs) + if (ai.dialect == us) return true; return false; } @@ -175,9 +175,9 @@ namespace llarp SessionClosedHandler SessionClosed; SessionRenegotiateHandler SessionRenegotiate; PumpDoneHandler PumpDone; - std::shared_ptr< KeyManager > keyManager; + std::shared_ptr keyManager; - std::shared_ptr< Logic > + std::shared_ptr logic() { return m_Logic; @@ -186,8 +186,7 @@ namespace llarp bool operator<(const ILinkLayer& other) const { - return Rank() < other.Rank() || Name() < other.Name() - || m_ourAddr < other.m_ourAddr; + return Rank() < other.Rank() || Name() < other.Name() || m_ourAddr < other.m_ourAddr; } /// called by link session to remove a pending session who is timed out @@ -214,40 +213,35 @@ namespace llarp protected: #ifdef TRACY_ENABLE - using Lock_t = std::lock_guard< LockableBase(std::mutex) >; + using Lock_t = std::lock_guard; using Mutex_t = std::mutex; #else - using Lock_t = util::NullLock; + using Lock_t = util::NullLock; using Mutex_t = util::NullMutex; #endif bool - PutSession(const std::shared_ptr< ILinkSession >& s); + PutSession(const std::shared_ptr& s); - std::shared_ptr< llarp::Logic > m_Logic = nullptr; - std::shared_ptr< llarp::thread::ThreadPool > m_Worker = nullptr; + std::shared_ptr m_Logic = nullptr; + std::shared_ptr m_Worker = nullptr; llarp_ev_loop_ptr m_Loop; Addr m_ourAddr; llarp_udp_io m_udp; SecretKey m_SecretKey; using AuthedLinks = - std::unordered_multimap< RouterID, std::shared_ptr< ILinkSession >, - RouterID::Hash >; + std::unordered_multimap, RouterID::Hash>; using Pending = - std::unordered_multimap< llarp::Addr, std::shared_ptr< ILinkSession >, - llarp::Addr::Hash >; - mutable DECLARE_LOCK(Mutex_t, m_AuthedLinksMutex, - ACQUIRED_BEFORE(m_PendingMutex)); + std::unordered_multimap, llarp::Addr::Hash>; + mutable DECLARE_LOCK(Mutex_t, m_AuthedLinksMutex, ACQUIRED_BEFORE(m_PendingMutex)); AuthedLinks m_AuthedLinks GUARDED_BY(m_AuthedLinksMutex); - mutable DECLARE_LOCK(Mutex_t, m_PendingMutex, - ACQUIRED_AFTER(m_AuthedLinksMutex)); + mutable DECLARE_LOCK(Mutex_t, m_PendingMutex, ACQUIRED_AFTER(m_AuthedLinksMutex)); Pending m_Pending GUARDED_BY(m_PendingMutex); - std::unordered_map< llarp::Addr, llarp_time_t, llarp::Addr::Hash > - m_RecentlyClosed; + std::unordered_map m_RecentlyClosed; }; - using LinkLayer_ptr = std::shared_ptr< ILinkLayer >; + using LinkLayer_ptr = std::shared_ptr; } // namespace llarp #endif diff --git a/llarp/link/session.hpp b/llarp/link/session.hpp index 16f35f0b6..ce4aa3013 100644 --- a/llarp/link/session.hpp +++ b/llarp/link/session.hpp @@ -28,12 +28,12 @@ namespace llarp /// equiv of shared_from_this but for the interface type so /// that each implementation can use shared_from_this - virtual std::shared_ptr< ILinkSession > + virtual std::shared_ptr BorrowSelf() = 0; /// hook for utp for when we have established a connection virtual void - OnLinkEstablished(ILinkLayer *){}; + OnLinkEstablished(ILinkLayer*){}; /// called every event loop tick virtual void @@ -43,10 +43,10 @@ namespace llarp virtual void Tick(llarp_time_t) = 0; /// message delivery result hook function - using CompletionHandler = std::function< void(DeliveryStatus) >; + using CompletionHandler = std::function; - using Packet_t = PacketBuffer; - using Message_t = std::vector< byte_t >; + using Packet_t = PacketBuffer; + using Message_t = std::vector; /// send a message buffer to the remote endpoint virtual bool @@ -95,14 +95,14 @@ namespace llarp GetRemoteRC() const = 0; /// handle a valid LIM - std::function< bool(const LinkIntroMessage *msg) > GotLIM; + std::function GotLIM; /// send queue current blacklog virtual size_t SendQueueBacklog() const = 0; /// get parent link layer - virtual ILinkLayer * + virtual ILinkLayer* GetLinkLayer() const = 0; /// renegotiate session when we have a new RC locally diff --git a/llarp/linux/netns.cpp b/llarp/linux/netns.cpp index 653d893d7..7cb157636 100644 --- a/llarp/linux/netns.cpp +++ b/llarp/linux/netns.cpp @@ -34,13 +34,13 @@ namespace llarp std::string mountpoint; std::ifstream inf; inf.open("/proc/mounts"); - if(!inf.is_open()) + if (!inf.is_open()) { llarp::LogError("failed to open /proc/mounts"); return false; } std::string line; - while(std::getline(inf, line)) + while (std::getline(inf, line)) { std::string part; std::stringstream parts; @@ -52,7 +52,7 @@ namespace llarp mountpoint = part; // type std::getline(parts, part); - if(part == "cgroup2") + if (part == "cgroup2") { // found cgroup2 mountpoint cgroups2_mount = mountpoint; @@ -67,14 +67,13 @@ namespace llarp GetNetNS(std::string& netns) { auto nfd = open("/proc/self/ns/net", O_RDONLY); - if(nfd < 0) + if (nfd < 0) { - llarp::LogError( - "Failed to get our own netns, could not open /proc/self/ns/net"); + llarp::LogError("Failed to get our own netns, could not open /proc/self/ns/net"); return false; } struct stat netst; - if(::fstat(nfd, &netst) < 0) + if (::fstat(nfd, &netst) < 0) { close(nfd); llarp::LogError("stat of netns failed: ", strerror(errno)); @@ -82,17 +81,17 @@ namespace llarp } close(nfd); fs::path run_dir = netns_rundir; - bool foundIt = false; + bool foundIt = false; // find corrosponding file for netns llarp::util::IterDir(run_dir, [&](const fs::path& f) -> bool { struct stat fst; - if(::stat(f.string().c_str(), &fst) >= 0) + if (::stat(f.string().c_str(), &fst) >= 0) { - if(fst.st_dev == netst.st_dev && fst.st_ino == netst.st_ino) + if (fst.st_dev == netst.st_dev && fst.st_ino == netst.st_ino) { // found it foundIt = true; - netns = f.filename().string(); + netns = f.filename().string(); // break iteration return false; } @@ -110,24 +109,24 @@ namespace llarp snprintf(p, sizeof(p), "/proc/%d/cgroup", getpid()); std::ifstream inf; inf.open(p); - if(!inf.is_open()) + if (!inf.is_open()) { llarp::LogError("could not open '", p, "': ", strerror(errno)); return false; } path = ""; std::string line; - while(std::getline(inf, line)) + while (std::getline(inf, line)) { auto pos = line.find("::/"); - if(pos != std::string::npos) + if (pos != std::string::npos) { line = line.substr(pos + 2); - pos = line.find("/vrf"); - if(pos != std::string::npos) + pos = line.find("/vrf"); + if (pos != std::string::npos) { path = line.substr(pos); - if(path == "/") + if (path == "/") path = ""; } break; @@ -140,52 +139,48 @@ namespace llarp ResetVRF() { fs::path cgroups2_mount; - if(!GetCGroups2MountPoint(cgroups2_mount)) + if (!GetCGroups2MountPoint(cgroups2_mount)) { llarp::LogError("could not find cgroup2 mount point, is it mounted?"); return false; } std::string netns; - if(!GetNetNS(netns)) + if (!GetNetNS(netns)) { llarp::LogError("could not get our netns: ", strerror(errno)); return false; } std::string vrfpath; - if(!GetVRFPath(vrfpath)) + if (!GetVRFPath(vrfpath)) { - llarp::LogError("could not determine vrf cgroup path: ", - strerror(errno)); + llarp::LogError("could not determine vrf cgroup path: ", strerror(errno)); return false; } - fs::path cgroup_path = - cgroups2_mount / vrfpath / netns / "vrf" / "default"; + fs::path cgroup_path = cgroups2_mount / vrfpath / netns / "vrf" / "default"; std::error_code ec; - if(!fs::exists(cgroup_path, ec)) + if (!fs::exists(cgroup_path, ec)) { - if(!fs::create_directories(cgroup_path, ec)) + if (!fs::create_directories(cgroup_path, ec)) { - llarp::LogError("could not create '", cgroup_path.string(), - "': ", ec); + llarp::LogError("could not create '", cgroup_path.string(), "': ", ec); return false; } } - else if(ec) + else if (ec) { llarp::LogError("Could not check '", cgroup_path.string(), "': ", ec); return false; } cgroup_path /= "cgroup.procs"; auto fd = open(cgroup_path.string().c_str(), O_RDWR | O_APPEND); - if(fd < 0) + if (fd < 0) { - llarp::LogError("could not open '", cgroup_path.string(), - "': ", strerror(errno)); + llarp::LogError("could not open '", cgroup_path.string(), "': ", strerror(errno)); return false; } - bool success = true; + bool success = true; std::string pid = std::to_string(getpid()); - if(write(fd, pid.c_str(), pid.size()) < 0) + if (write(fd, pid.c_str(), pid.size()) < 0) { llarp::LogError("failed to join cgroup"); success = false; @@ -201,7 +196,7 @@ namespace llarp fs::path etc_dir = netns_etcdir; etc_dir /= name; std::error_code ec; - if(!fs::exists(etc_dir, ec)) + if (!fs::exists(etc_dir, ec)) { errno = 0; llarp::LogInfo(etc_dir, " does not exist, skipping"); @@ -209,16 +204,19 @@ namespace llarp } bool didFail = false; llarp::util::IterDir(etc_dir, [&](const fs::path& f) -> bool { - if(fs::is_regular_file(f)) + if (fs::is_regular_file(f)) { fs::path netns_path = "/etc"; netns_path /= f.filename(); - if(mount(f.string().c_str(), netns_path.string().c_str(), "none", - MS_BIND, nullptr) - < 0) + if (mount(f.string().c_str(), netns_path.string().c_str(), "none", MS_BIND, nullptr) < 0) { - llarp::LogError("failed to bind '", f.string(), "' to '", - netns_path.string(), "': ", strerror(errno)); + llarp::LogError( + "failed to bind '", + f.string(), + "' to '", + netns_path.string(), + "': ", + strerror(errno)); didFail = true; } } @@ -231,24 +229,24 @@ namespace llarp static void DropCap() { - if(getuid() != 0 && geteuid() != 0) + if (getuid() != 0 && geteuid() != 0) { cap_t capabilities; - cap_value_t net_admin = CAP_NET_ADMIN; + cap_value_t net_admin = CAP_NET_ADMIN; cap_flag_t inheritable = CAP_INHERITABLE; cap_flag_value_t is_set; capabilities = cap_get_proc(); - if(!capabilities) + if (!capabilities) exit(EXIT_FAILURE); - if(cap_get_flag(capabilities, net_admin, inheritable, &is_set) != 0) + if (cap_get_flag(capabilities, net_admin, inheritable, &is_set) != 0) exit(EXIT_FAILURE); - if(is_set == CAP_CLEAR) + if (is_set == CAP_CLEAR) { - if(cap_clear(capabilities) != 0) + if (cap_clear(capabilities) != 0) exit(EXIT_FAILURE); - if(cap_set_proc(capabilities) != 0) + if (cap_set_proc(capabilities) != 0) exit(EXIT_FAILURE); } cap_free(capabilities); @@ -261,55 +259,53 @@ namespace llarp fs::path netns_path = netns_rundir; netns_path /= name; auto nsfd = open(netns_path.string().c_str(), O_RDONLY | O_CLOEXEC); - if(nsfd < 0) + if (nsfd < 0) { - llarp::LogError("Failed to open network namespace '", name, - "': ", strerror(errno)); + llarp::LogError("Failed to open network namespace '", name, "': ", strerror(errno)); return false; } - if(setns(nsfd, CLONE_NEWNET) < 0) + if (setns(nsfd, CLONE_NEWNET) < 0) { - llarp::LogError("Failed to enter network namespace '", name, - "': ", strerror(errno)); + llarp::LogError("Failed to enter network namespace '", name, "': ", strerror(errno)); close(nsfd); return false; } close(nsfd); - if(unshare(CLONE_NEWNS) < 0) + if (unshare(CLONE_NEWNS) < 0) { llarp::LogError("unshare failed: ", strerror(errno)); return false; } // dont let any mount points prop back to parent // iproute2 source does this - if(mount("", "/", "none", MS_SLAVE | MS_REC, nullptr)) + if (mount("", "/", "none", MS_SLAVE | MS_REC, nullptr)) { llarp::LogError("mount --make-rslave failed: ", strerror(errno)); return false; } unsigned long mountflags = 0; // ensaure /sys not mounted - if(umount2("/sys", MNT_DETACH) < 0) + if (umount2("/sys", MNT_DETACH) < 0) { struct statvfs fsstat; - if(statvfs("/sys", &fsstat) == 0) + if (statvfs("/sys", &fsstat) == 0) { - if(fsstat.f_flag & ST_RDONLY) + if (fsstat.f_flag & ST_RDONLY) mountflags = MS_RDONLY; } } // mount sysfs for our namespace - if(mount(name, "/sys", "sysfs", mountflags, nullptr) < 0) + if (mount(name, "/sys", "sysfs", mountflags, nullptr) < 0) { llarp::LogError("failed to mount sysfs: ", strerror(errno)); return false; } - if(!BindNetworkNS(name)) + if (!BindNetworkNS(name)) { llarp::LogError("failed to bind namespace directories"); return false; } - if(!ResetVRF()) + if (!ResetVRF()) { llarp::LogError("failed to reset vrf"); return false; diff --git a/llarp/messages/dht_immediate.cpp b/llarp/messages/dht_immediate.cpp index 0b7662b31..584205906 100644 --- a/llarp/messages/dht_immediate.cpp +++ b/llarp/messages/dht_immediate.cpp @@ -12,14 +12,13 @@ namespace llarp } bool - DHTImmediateMessage::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf) + DHTImmediateMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { - if(key == "m") - return llarp::dht::DecodeMesssageList(dht::Key_t(session->GetPubKey()), - buf, msgs); - if(key == "v") + if (key == "m") + return llarp::dht::DecodeMesssageList(dht::Key_t(session->GetPubKey()), buf, msgs); + if (key == "v") { - if(!bencode_read_integer(buf, &version)) + if (!bencode_read_integer(buf, &version)) return false; return version == LLARP_PROTO_VERSION; } @@ -28,52 +27,52 @@ namespace llarp } bool - DHTImmediateMessage::BEncode(llarp_buffer_t *buf) const + DHTImmediateMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; // message type - if(!bencode_write_bytestring(buf, "a", 1)) + if (!bencode_write_bytestring(buf, "a", 1)) return false; - if(!bencode_write_bytestring(buf, "m", 1)) + if (!bencode_write_bytestring(buf, "m", 1)) return false; // dht messages - if(!bencode_write_bytestring(buf, "m", 1)) + if (!bencode_write_bytestring(buf, "m", 1)) return false; // begin list - if(!bencode_start_list(buf)) + if (!bencode_start_list(buf)) return false; - for(const auto &msg : msgs) + for (const auto& msg : msgs) { - if(!msg->BEncode(buf)) + if (!msg->BEncode(buf)) return false; } // end list - if(!bencode_end(buf)) + if (!bencode_end(buf)) return false; // protocol version - if(!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) + if (!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) return false; return bencode_end(buf); } bool - DHTImmediateMessage::HandleMessage(AbstractRouter *router) const + DHTImmediateMessage::HandleMessage(AbstractRouter* router) const { DHTImmediateMessage reply; reply.session = session; - bool result = true; - for(auto &msg : msgs) + bool result = true; + for (auto& msg : msgs) { result &= msg->HandleMessage(router->dht(), reply.msgs); } - if(reply.msgs.size()) + if (reply.msgs.size()) { - if(result) + if (result) { result = router->SendToOrQueue(session->GetPubKey(), &reply); } diff --git a/llarp/messages/dht_immediate.hpp b/llarp/messages/dht_immediate.hpp index 31afbba9e..02b12f0aa 100644 --- a/llarp/messages/dht_immediate.hpp +++ b/llarp/messages/dht_immediate.hpp @@ -10,10 +10,10 @@ namespace llarp { struct DHTImmediateMessage final : public ILinkMessage { - DHTImmediateMessage() = default; + DHTImmediateMessage() = default; ~DHTImmediateMessage() override = default; - std::vector< std::unique_ptr< dht::IMessage > > msgs; + std::vector> msgs; bool DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override; diff --git a/llarp/messages/discard.hpp b/llarp/messages/discard.hpp index db118faba..0aa1b3728 100644 --- a/llarp/messages/discard.hpp +++ b/llarp/messages/discard.hpp @@ -17,11 +17,11 @@ namespace llarp bool BEncode(llarp_buffer_t* buf) const override { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!bencode_write_bytestring(buf, "a", 1)) + if (!bencode_write_bytestring(buf, "a", 1)) return false; - if(!bencode_write_bytestring(buf, "x", 1)) + if (!bencode_write_bytestring(buf, "x", 1)) return false; return bencode_end(buf); } @@ -41,12 +41,12 @@ namespace llarp bool DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override { - if(key == "a") + if (key == "a") { llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz != 1) + if (strbuf.sz != 1) return false; return *strbuf.cur == 'x'; } @@ -70,7 +70,7 @@ namespace llarp DataDiscardMessage(const PathID_t& dst, uint64_t s) : P(dst) { - S = s; + S = s; version = LLARP_PROTO_VERSION; } @@ -90,11 +90,11 @@ namespace llarp DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) override { bool read = false; - if(!BEncodeMaybeReadDictEntry("P", P, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("P", P, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("S", S, read, k, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, k, buf)) return false; return read; } @@ -102,16 +102,16 @@ namespace llarp bool BEncode(llarp_buffer_t* buf) const override { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "D")) + if (!BEncodeWriteDictMsgType(buf, "A", "D")) return false; - if(!BEncodeWriteDictEntry("P", P, buf)) + if (!BEncodeWriteDictEntry("P", P, buf)) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; return bencode_end(buf); diff --git a/llarp/messages/link_intro.cpp b/llarp/messages/link_intro.cpp index bcb502b89..c5c6a1951 100644 --- a/llarp/messages/link_intro.cpp +++ b/llarp/messages/link_intro.cpp @@ -11,48 +11,47 @@ namespace llarp bool LinkIntroMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { - if(key == "a") + if (key == "a") { llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz != 1) + if (strbuf.sz != 1) return false; return *strbuf.cur == 'i'; } - if(key == "n") + if (key == "n") { - if(N.BDecode(buf)) + if (N.BDecode(buf)) return true; llarp::LogWarn("failed to decode nonce in LIM"); return false; } - if(key == "p") + if (key == "p") { return bencode_read_integer(buf, &P); } - if(key == "r") + if (key == "r") { - if(rc.BDecode(buf)) + if (rc.BDecode(buf)) return true; llarp::LogWarn("failed to decode RC in LIM"); llarp::DumpBuffer(*buf); return false; } - if(key == "v") + if (key == "v") { - if(!bencode_read_integer(buf, &version)) + if (!bencode_read_integer(buf, &version)) return false; - if(version != LLARP_PROTO_VERSION) + if (version != LLARP_PROTO_VERSION) { - llarp::LogWarn("llarp protocol version missmatch ", version, - " != ", LLARP_PROTO_VERSION); + llarp::LogWarn("llarp protocol version missmatch ", version, " != ", LLARP_PROTO_VERSION); return false; } llarp::LogDebug("LIM version ", version); return true; } - if(key == "z") + if (key == "z") { return Z.BDecode(buf); } @@ -64,35 +63,35 @@ namespace llarp bool LinkIntroMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!bencode_write_bytestring(buf, "a", 1)) + if (!bencode_write_bytestring(buf, "a", 1)) return false; - if(!bencode_write_bytestring(buf, "i", 1)) + if (!bencode_write_bytestring(buf, "i", 1)) return false; - if(!bencode_write_bytestring(buf, "n", 1)) + if (!bencode_write_bytestring(buf, "n", 1)) return false; - if(!N.BEncode(buf)) + if (!N.BEncode(buf)) return false; - if(!bencode_write_bytestring(buf, "p", 1)) + if (!bencode_write_bytestring(buf, "p", 1)) return false; - if(!bencode_write_uint64(buf, P)) + if (!bencode_write_uint64(buf, P)) return false; - if(!bencode_write_bytestring(buf, "r", 1)) + if (!bencode_write_bytestring(buf, "r", 1)) return false; - if(!rc.BEncode(buf)) + if (!rc.BEncode(buf)) return false; - if(!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) + if (!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) return false; - if(!bencode_write_bytestring(buf, "z", 1)) + if (!bencode_write_bytestring(buf, "z", 1)) return false; - if(!Z.BEncode(buf)) + if (!Z.BEncode(buf)) return false; return bencode_end(buf); @@ -101,7 +100,7 @@ namespace llarp bool LinkIntroMessage::HandleMessage(AbstractRouter* /*router*/) const { - if(!Verify()) + if (!Verify()) return false; return session->GotLIM(this); } @@ -117,15 +116,14 @@ namespace llarp } bool - LinkIntroMessage::Sign( - std::function< bool(Signature&, const llarp_buffer_t&) > signer) + LinkIntroMessage::Sign(std::function signer) { Z.Zero(); - std::array< byte_t, MaxSize > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!BEncode(&buf)) + if (!BEncode(&buf)) return false; - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; return signer(Z, buf); } @@ -136,20 +134,20 @@ namespace llarp LinkIntroMessage copy; copy = *this; copy.Z.Zero(); - std::array< byte_t, MaxSize > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) return false; - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; // outer signature - if(!CryptoManager::instance()->verify(rc.pubkey, buf, Z)) + if (!CryptoManager::instance()->verify(rc.pubkey, buf, Z)) { llarp::LogError("outer signature failure"); return false; } // verify RC - if(!rc.Verify(llarp::time_now_ms())) + if (!rc.Verify(llarp::time_now_ms())) { llarp::LogError("invalid RC in link intro"); return false; diff --git a/llarp/messages/link_intro.hpp b/llarp/messages/link_intro.hpp index 054691384..d9fbdfd58 100644 --- a/llarp/messages/link_intro.hpp +++ b/llarp/messages/link_intro.hpp @@ -32,7 +32,7 @@ namespace llarp HandleMessage(AbstractRouter* router) const override; bool - Sign(std::function< bool(Signature&, const llarp_buffer_t&) > signer); + Sign(std::function signer); bool Verify() const; @@ -50,7 +50,7 @@ namespace llarp uint16_t Priority() const override { - return std::numeric_limits< uint16_t >::max(); + return std::numeric_limits::max(); } }; } // namespace llarp diff --git a/llarp/messages/link_message.hpp b/llarp/messages/link_message.hpp index 1c5eddf2f..4792e2273 100644 --- a/llarp/messages/link_message.hpp +++ b/llarp/messages/link_message.hpp @@ -18,7 +18,7 @@ namespace llarp { /// who did this message come from or is going to ILinkSession* session = nullptr; - uint64_t version = LLARP_PROTO_VERSION; + uint64_t version = LLARP_PROTO_VERSION; PathID_t pathid; @@ -35,7 +35,7 @@ namespace llarp // default version if not specified is 0 uint64_t v = 0; // seek for version and set it if we got it - if(BEncodeSeekDictVersion(v, buf, 'v')) + if (BEncodeSeekDictVersion(v, buf, 'v')) { version = v; } diff --git a/llarp/messages/link_message_parser.cpp b/llarp/messages/link_message_parser.cpp index 29006da4d..9e00d5419 100644 --- a/llarp/messages/link_message_parser.cpp +++ b/llarp/messages/link_message_parser.cpp @@ -29,10 +29,7 @@ namespace llarp }; LinkMessageParser::LinkMessageParser(AbstractRouter* _router) - : router(_router) - , from(nullptr) - , msg(nullptr) - , holder(std::make_unique< msg_holder_t >()) + : router(_router), from(nullptr), msg(nullptr), holder(std::make_unique()) { } @@ -42,33 +39,33 @@ namespace llarp LinkMessageParser::operator()(llarp_buffer_t* buffer, llarp_buffer_t* key) { // we are reading the first key - if(firstkey) + if (firstkey) { llarp_buffer_t strbuf; // check for empty dict - if(!key) + if (!key) return false; // we are expecting the first key to be 'a' - if(!(*key == "a")) + if (!(*key == "a")) { llarp::LogWarn("message has no message type"); return false; } - if(!bencode_read_string(buffer, &strbuf)) + if (!bencode_read_string(buffer, &strbuf)) { llarp::LogWarn("could not read value of message type"); return false; } // bad key size - if(strbuf.sz != 1) + if (strbuf.sz != 1) { llarp::LogWarn("bad mesage type size: ", strbuf.sz); return false; } // create the message to parse based off message type llarp::LogDebug("inbound message ", *strbuf.cur); - switch(*strbuf.cur) + switch (*strbuf.cur) { case 'i': msg = &holder->i; @@ -96,11 +93,11 @@ namespace llarp } msg->session = from; - firstkey = false; + firstkey = false; return true; } // check for last element - if(!key) + if (!key) return MessageDone(); return msg->DecodeKey(*key, buffer); @@ -110,7 +107,7 @@ namespace llarp LinkMessageParser::MessageDone() { bool result = false; - if(msg) + if (msg) { result = msg->HandleMessage(router); } @@ -121,13 +118,13 @@ namespace llarp bool LinkMessageParser::ProcessFrom(ILinkSession* src, const llarp_buffer_t& buf) { - if(!src) + if (!src) { llarp::LogWarn("no link session"); return false; } - from = src; + from = src; firstkey = true; ManagedBuffer copy(buf); return bencode_read_dict(*this, ©.underlying); @@ -136,7 +133,7 @@ namespace llarp void LinkMessageParser::Reset() { - if(msg) + if (msg) msg->Clear(); msg = nullptr; } diff --git a/llarp/messages/link_message_parser.hpp b/llarp/messages/link_message_parser.hpp index 6727b8297..c2077395c 100644 --- a/llarp/messages/link_message_parser.hpp +++ b/llarp/messages/link_message_parser.hpp @@ -45,7 +45,7 @@ namespace llarp struct msg_holder_t; - std::unique_ptr< msg_holder_t > holder; + std::unique_ptr holder; }; } // namespace llarp #endif diff --git a/llarp/messages/relay.cpp b/llarp/messages/relay.cpp index 3497665a8..9c39db086 100644 --- a/llarp/messages/relay.cpp +++ b/llarp/messages/relay.cpp @@ -16,46 +16,44 @@ namespace llarp } bool - RelayUpstreamMessage::BEncode(llarp_buffer_t *buf) const + RelayUpstreamMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "a", "u")) + if (!BEncodeWriteDictMsgType(buf, "a", "u")) return false; - if(!BEncodeWriteDictEntry("p", pathid, buf)) + if (!BEncodeWriteDictEntry("p", pathid, buf)) return false; - if(!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf)) + if (!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf)) return false; - if(!BEncodeWriteDictEntry("x", X, buf)) + if (!BEncodeWriteDictEntry("x", X, buf)) return false; - if(!BEncodeWriteDictEntry("y", Y, buf)) + if (!BEncodeWriteDictEntry("y", Y, buf)) return false; return bencode_end(buf); } bool - RelayUpstreamMessage::DecodeKey(const llarp_buffer_t &key, - llarp_buffer_t *buf) + RelayUpstreamMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf)) return false; - if(!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, key, - buf)) + if (!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("x", X, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("x", X, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("y", Y, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("y", Y, read, key, buf)) return false; return read; } bool - RelayUpstreamMessage::HandleMessage(AbstractRouter *r) const + RelayUpstreamMessage::HandleMessage(AbstractRouter* r) const { auto path = r->pathContext().GetByDownstream(session->GetPubKey(), pathid); - if(path) + if (path) { return path->HandleUpstream(llarp_buffer_t(X), Y, r); } @@ -72,46 +70,44 @@ namespace llarp } bool - RelayDownstreamMessage::BEncode(llarp_buffer_t *buf) const + RelayDownstreamMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "a", "d")) + if (!BEncodeWriteDictMsgType(buf, "a", "d")) return false; - if(!BEncodeWriteDictEntry("p", pathid, buf)) + if (!BEncodeWriteDictEntry("p", pathid, buf)) return false; - if(!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf)) + if (!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf)) return false; - if(!BEncodeWriteDictEntry("x", X, buf)) + if (!BEncodeWriteDictEntry("x", X, buf)) return false; - if(!BEncodeWriteDictEntry("y", Y, buf)) + if (!BEncodeWriteDictEntry("y", Y, buf)) return false; return bencode_end(buf); } bool - RelayDownstreamMessage::DecodeKey(const llarp_buffer_t &key, - llarp_buffer_t *buf) + RelayDownstreamMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf)) return false; - if(!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, key, - buf)) + if (!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("x", X, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("x", X, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("y", Y, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("y", Y, read, key, buf)) return false; return read; } bool - RelayDownstreamMessage::HandleMessage(AbstractRouter *r) const + RelayDownstreamMessage::HandleMessage(AbstractRouter* r) const { auto path = r->pathContext().GetByUpstream(session->GetPubKey(), pathid); - if(path) + if (path) { return path->HandleDownstream(llarp_buffer_t(X), Y, r); } diff --git a/llarp/messages/relay.hpp b/llarp/messages/relay.hpp index 9ef671289..5e14bc6b0 100644 --- a/llarp/messages/relay.hpp +++ b/llarp/messages/relay.hpp @@ -12,7 +12,7 @@ namespace llarp { struct RelayUpstreamMessage : public ILinkMessage { - Encrypted< MAX_LINK_MSG_SIZE - 128 > X; + Encrypted X; TunnelNonce Y; bool @@ -41,7 +41,7 @@ namespace llarp struct RelayDownstreamMessage : public ILinkMessage { - Encrypted< MAX_LINK_MSG_SIZE - 128 > X; + Encrypted X; TunnelNonce Y; bool diff --git a/llarp/messages/relay_commit.cpp b/llarp/messages/relay_commit.cpp index cac813a16..593b0c961 100644 --- a/llarp/messages/relay_commit.cpp +++ b/llarp/messages/relay_commit.cpp @@ -23,15 +23,14 @@ namespace llarp bool LR_CommitMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { - if(key == "c") + if (key == "c") { /// so we dont put it into the shitty queue pathid.Fill('c'); return BEncodeReadArray(frames, buf); } bool read = false; - if(!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, key, - buf)) + if (!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, key, buf)) return false; return read; @@ -47,16 +46,16 @@ namespace llarp bool LR_CommitMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; // msg type - if(!BEncodeWriteDictMsgType(buf, "a", "c")) + if (!BEncodeWriteDictMsgType(buf, "a", "c")) return false; // frames - if(!BEncodeWriteDictArray("c", frames, buf)) + if (!BEncodeWriteDictArray("c", frames, buf)) return false; // version - if(!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) + if (!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) return false; return bencode_end(buf); @@ -65,13 +64,12 @@ namespace llarp bool LR_CommitMessage::HandleMessage(AbstractRouter* router) const { - if(frames.size() != path::max_len) + if (frames.size() != path::max_len) { - llarp::LogError("LRCM invalid number of records, ", frames.size(), - "!=", path::max_len); + llarp::LogError("LRCM invalid number of records, ", frames.size(), "!=", path::max_len); return false; } - if(!router->pathContext().AllowingTransit()) + if (!router->pathContext().AllowingTransit()) { llarp::LogError("got LRCM when not permitting transit"); return false; @@ -82,32 +80,32 @@ namespace llarp bool LR_CommitRecord::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictEntry("c", commkey, buf)) + if (!BEncodeWriteDictEntry("c", commkey, buf)) return false; - if(!BEncodeWriteDictEntry("i", nextHop, buf)) + if (!BEncodeWriteDictEntry("i", nextHop, buf)) return false; - if(lifetime > 10s && lifetime < path::default_lifetime) + if (lifetime > 10s && lifetime < path::default_lifetime) { - if(!BEncodeWriteDictInt("i", lifetime.count(), buf)) + if (!BEncodeWriteDictInt("i", lifetime.count(), buf)) return false; } - if(!BEncodeWriteDictEntry("n", tunnelNonce, buf)) + if (!BEncodeWriteDictEntry("n", tunnelNonce, buf)) return false; - if(!BEncodeWriteDictEntry("r", rxid, buf)) + if (!BEncodeWriteDictEntry("r", rxid, buf)) return false; - if(!BEncodeWriteDictEntry("t", txid, buf)) + if (!BEncodeWriteDictEntry("t", txid, buf)) return false; - if(nextRC) + if (nextRC) { - if(!BEncodeWriteDictEntry("u", *nextRC, buf)) + if (!BEncodeWriteDictEntry("u", *nextRC, buf)) return false; } - if(!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) + if (!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) return false; - if(work && !BEncodeWriteDictEntry("w", *work, buf)) + if (work && !BEncodeWriteDictEntry("w", *work, buf)) return false; return bencode_end(buf); @@ -116,41 +114,40 @@ namespace llarp bool LR_CommitRecord::OnKey(llarp_buffer_t* buffer, llarp_buffer_t* key) { - if(!key) + if (!key) return true; bool read = false; - if(!BEncodeMaybeReadDictEntry("c", commkey, read, *key, buffer)) + if (!BEncodeMaybeReadDictEntry("c", commkey, read, *key, buffer)) return false; - if(!BEncodeMaybeReadDictEntry("i", nextHop, read, *key, buffer)) + if (!BEncodeMaybeReadDictEntry("i", nextHop, read, *key, buffer)) return false; - if(!BEncodeMaybeReadDictInt("l", lifetime, read, *key, buffer)) + if (!BEncodeMaybeReadDictInt("l", lifetime, read, *key, buffer)) return false; - if(!BEncodeMaybeReadDictEntry("n", tunnelNonce, read, *key, buffer)) + if (!BEncodeMaybeReadDictEntry("n", tunnelNonce, read, *key, buffer)) return false; - if(!BEncodeMaybeReadDictEntry("r", rxid, read, *key, buffer)) + if (!BEncodeMaybeReadDictEntry("r", rxid, read, *key, buffer)) return false; - if(!BEncodeMaybeReadDictEntry("t", txid, read, *key, buffer)) + if (!BEncodeMaybeReadDictEntry("t", txid, read, *key, buffer)) return false; - if(*key == "u") + if (*key == "u") { - nextRC = std::make_unique< RouterContact >(); + nextRC = std::make_unique(); return nextRC->BDecode(buffer); } - if(!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, *key, - buffer)) + if (!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, *key, buffer)) return false; - if(*key == "w") + if (*key == "w") { // check for duplicate - if(work) + if (work) { llarp::LogWarn("duplicate POW in LRCR"); return false; } - work = std::make_unique< PoW >(); + work = std::make_unique(); return bencode_decode_dict(*work, buffer); } return read; @@ -165,40 +162,40 @@ namespace llarp bool LR_CommitRecord::operator==(const LR_CommitRecord& other) const { - if(work && other.work) + if (work && other.work) { - if(*work != *other.work) + if (*work != *other.work) return false; } - return nextHop == other.nextHop && commkey == other.commkey - && txid == other.txid && rxid == other.rxid; + return nextHop == other.nextHop && commkey == other.commkey && txid == other.txid + && rxid == other.rxid; } struct LRCMFrameDecrypt { - using Context = llarp::path::PathContext; - using Hop = llarp::path::TransitHop; - using Decrypter = AsyncFrameDecrypter< LRCMFrameDecrypt >; - using Decrypter_ptr = std::unique_ptr< Decrypter >; + using Context = llarp::path::PathContext; + using Hop = llarp::path::TransitHop; + using Decrypter = AsyncFrameDecrypter; + using Decrypter_ptr = std::unique_ptr; Decrypter_ptr decrypter; - std::array< EncryptedFrame, 8 > frames; + std::array frames; Context* context; // decrypted record LR_CommitRecord record; // the actual hop - std::shared_ptr< Hop > hop; + std::shared_ptr hop; - const nonstd::optional< llarp::Addr > fromAddr; + const nonstd::optional fromAddr; - LRCMFrameDecrypt(Context* ctx, Decrypter_ptr dec, - const LR_CommitMessage* commit) + LRCMFrameDecrypt(Context* ctx, Decrypter_ptr dec, const LR_CommitMessage* commit) : decrypter(std::move(dec)) , frames(commit->frames) , context(ctx) - , hop(std::make_shared< Hop >()) - , fromAddr(commit->session->GetRemoteRC().IsPublicRouter() - ? nonstd::optional< llarp::Addr >{} - : commit->session->GetRemoteEndpoint()) + , hop(std::make_shared()) + , fromAddr( + commit->session->GetRemoteRC().IsPublicRouter() + ? nonstd::optional{} + : commit->session->GetRemoteEndpoint()) { hop->info.downstream = commit->session->GetPubKey(); } @@ -206,13 +203,16 @@ namespace llarp ~LRCMFrameDecrypt() = default; static void - OnForwardLRCMResult(AbstractRouter* router, const PathID_t pathid, - const RouterID nextHop, const SharedSecret pathKey, - SendStatus sendStatus) + OnForwardLRCMResult( + AbstractRouter* router, + const PathID_t pathid, + const RouterID nextHop, + const SharedSecret pathKey, + SendStatus sendStatus) { uint64_t status = LR_StatusRecord::FAIL_DEST_INVALID; - switch(sendStatus) + switch (sendStatus) { case SendStatus::Success: // do nothing, will forward success message later @@ -238,54 +238,62 @@ namespace llarp break; } - auto func = std::bind(&LR_StatusMessage::CreateAndSend, router, pathid, - nextHop, pathKey, status); + auto func = + std::bind(&LR_StatusMessage::CreateAndSend, router, pathid, nextHop, pathKey, status); router->threadpool()->addJob(func); } /// this is done from logic thread static void - SendLRCM(std::shared_ptr< LRCMFrameDecrypt > self) + SendLRCM(std::shared_ptr self) { - if(self->context->HasTransitHop(self->hop->info)) + if (self->context->HasTransitHop(self->hop->info)) { llarp::LogError("duplicate transit hop ", self->hop->info); LR_StatusMessage::CreateAndSend( - self->context->Router(), self->hop->info.rxID, - self->hop->info.downstream, self->hop->pathKey, + self->context->Router(), + self->hop->info.rxID, + self->hop->info.downstream, + self->hop->pathKey, LR_StatusRecord::FAIL_DUPLICATE_HOP); self->hop = nullptr; return; } - if(self->fromAddr.has_value()) + if (self->fromAddr.has_value()) { // only do ip limiting from non service nodes #ifndef LOKINET_HIVE - if(self->context->CheckPathLimitHitByIP(self->fromAddr.value())) + if (self->context->CheckPathLimitHitByIP(self->fromAddr.value())) { // we hit a limit so tell it to slow tf down - llarp::LogError("client path build hit limit ", - self->fromAddr.value()); - OnForwardLRCMResult(self->context->Router(), self->hop->info.rxID, - self->hop->info.downstream, self->hop->pathKey, - SendStatus::Congestion); + llarp::LogError("client path build hit limit ", self->fromAddr.value()); + OnForwardLRCMResult( + self->context->Router(), + self->hop->info.rxID, + self->hop->info.downstream, + self->hop->pathKey, + SendStatus::Congestion); self->hop = nullptr; return; } #endif } - if(!self->context->Router()->ConnectionToRouterAllowed( - self->hop->info.upstream)) + if (!self->context->Router()->ConnectionToRouterAllowed(self->hop->info.upstream)) { // we are not allowed to forward it ... now what? - llarp::LogError("path to ", self->hop->info.upstream, - "not allowed, dropping build request on the floor"); - OnForwardLRCMResult(self->context->Router(), self->hop->info.rxID, - self->hop->info.downstream, self->hop->pathKey, - SendStatus::InvalidRouter); + llarp::LogError( + "path to ", + self->hop->info.upstream, + "not allowed, dropping build request on the floor"); + OnForwardLRCMResult( + self->context->Router(), + self->hop->info.rxID, + self->hop->info.downstream, + self->hop->pathKey, + SendStatus::InvalidRouter); self->hop = nullptr; return; } @@ -298,38 +306,40 @@ namespace llarp // put hop self->context->PutTransitHop(self->hop); // if we have an rc for this hop... - if(self->record.nextRC) + if (self->record.nextRC) { // ... and it matches the next hop ... - if(self->record.nextHop == self->record.nextRC->pubkey) + if (self->record.nextHop == self->record.nextRC->pubkey) { // ... and it's valid const auto now = self->context->Router()->Now(); - if(self->record.nextRC->IsPublicRouter() - && self->record.nextRC->Verify(now)) + if (self->record.nextRC->IsPublicRouter() && self->record.nextRC->Verify(now)) { - self->context->Router()->nodedb()->UpdateAsyncIfNewer( - *self->record.nextRC.get()); + self->context->Router()->nodedb()->UpdateAsyncIfNewer(*self->record.nextRC.get()); } } } // forward to next hop using std::placeholders::_1; - auto func = std::bind(&OnForwardLRCMResult, self->context->Router(), - self->hop->info.rxID, self->hop->info.downstream, - self->hop->pathKey, _1); + auto func = std::bind( + &OnForwardLRCMResult, + self->context->Router(), + self->hop->info.rxID, + self->hop->info.downstream, + self->hop->pathKey, + _1); self->context->ForwardLRCM(self->hop->info.upstream, self->frames, func); self->hop = nullptr; } // this is called from the logic thread static void - SendPathConfirm(std::shared_ptr< LRCMFrameDecrypt > self) + SendPathConfirm(std::shared_ptr self) { // send path confirmation // TODO: other status flags? uint64_t status = LR_StatusRecord::SUCCESS; - if(self->context->HasTransitHop(self->hop->info)) + if (self->context->HasTransitHop(self->hop->info)) { status = LR_StatusRecord::FAIL_DUPLICATE_HOP; } @@ -342,12 +352,14 @@ namespace llarp self->context->PutTransitHop(self->hop); } - if(!LR_StatusMessage::CreateAndSend( - self->context->Router(), self->hop->info.rxID, - self->hop->info.downstream, self->hop->pathKey, status)) + if (!LR_StatusMessage::CreateAndSend( + self->context->Router(), + self->hop->info.rxID, + self->hop->info.downstream, + self->hop->pathKey, + status)) { - llarp::LogError("failed to send path confirmation for ", - self->hop->info); + llarp::LogError("failed to send path confirmation for ", self->hop->info); } self->hop = nullptr; } @@ -356,12 +368,11 @@ namespace llarp // want to or can't accept the path build request, send // a status message saying as much. static void - HandleDecrypted(llarp_buffer_t* buf, - std::shared_ptr< LRCMFrameDecrypt > self) + HandleDecrypted(llarp_buffer_t* buf, std::shared_ptr self) { - auto now = self->context->Router()->Now(); + auto now = self->context->Router()->Now(); auto& info = self->hop->info; - if(!buf) + if (!buf) { llarp::LogError("LRCM decrypt failed from ", info.downstream); self->decrypter = nullptr; @@ -370,7 +381,7 @@ namespace llarp buf->cur = buf->base + EncryptedFrameOverheadSize; llarp::LogDebug("decrypted LRCM from ", info.downstream); // successful decrypt - if(!self->record.BDecode(buf)) + if (!self->record.BDecode(buf)) { llarp::LogError("malformed frame inside LRCM from ", info.downstream); self->decrypter = nullptr; @@ -380,7 +391,7 @@ namespace llarp info.txID = self->record.txid; info.rxID = self->record.rxid; - if(info.txID.IsZero() || info.rxID.IsZero()) + if (info.txID.IsZero() || info.rxID.IsZero()) { llarp::LogError("LRCM refusing zero pathid"); self->decrypter = nullptr; @@ -391,40 +402,39 @@ namespace llarp // generate path key as we are in a worker thread auto crypto = CryptoManager::instance(); - if(!crypto->dh_server(self->hop->pathKey, self->record.commkey, - self->context->EncryptionSecretKey(), - self->record.tunnelNonce)) + if (!crypto->dh_server( + self->hop->pathKey, + self->record.commkey, + self->context->EncryptionSecretKey(), + self->record.tunnelNonce)) { llarp::LogError("LRCM DH Failed ", info); self->decrypter = nullptr; return; } // generate hash of hop key for nonce mutation - crypto->shorthash(self->hop->nonceXOR, - llarp_buffer_t(self->hop->pathKey)); - if(self->record.work && self->record.work->IsValid(now)) + crypto->shorthash(self->hop->nonceXOR, llarp_buffer_t(self->hop->pathKey)); + if (self->record.work && self->record.work->IsValid(now)) { - llarp::LogDebug("LRCM extended lifetime by ", - self->record.work->extendedLifetime, " for ", info); + llarp::LogDebug( + "LRCM extended lifetime by ", self->record.work->extendedLifetime, " for ", info); self->hop->lifetime += self->record.work->extendedLifetime; } - else if(self->record.lifetime < path::default_lifetime - && self->record.lifetime > 10s) + else if (self->record.lifetime < path::default_lifetime && self->record.lifetime > 10s) { self->hop->lifetime = self->record.lifetime; - llarp::LogDebug("LRCM short lifespan set to ", self->hop->lifetime, - " for ", info); + llarp::LogDebug("LRCM short lifespan set to ", self->hop->lifetime, " for ", info); } // TODO: check if we really want to accept it self->hop->started = now; - self->context->Router()->NotifyRouterEvent< tooling::PathRequestReceivedEvent >( + self->context->Router()->NotifyRouterEvent( self->context->Router()->pubkey(), self->hop); size_t sz = self->frames[0].size(); // shift - std::array< EncryptedFrame, 8 > frames; + std::array frames; frames[0] = self->frames[1]; frames[1] = self->frames[2]; frames[2] = self->frames[3]; @@ -437,7 +447,7 @@ namespace llarp // random junk for now frames[7].Randomize(); self->frames = std::move(frames); - if(self->context->HopIsUs(info.upstream)) + if (self->context->HopIsUs(info.upstream)) { // we are the farthest hop llarp::LogDebug("We are the farthest hop for ", info); @@ -462,15 +472,13 @@ namespace llarp bool LR_CommitMessage::AsyncDecrypt(llarp::path::PathContext* context) const { - auto decrypter = std::make_unique< LRCMFrameDecrypt::Decrypter >( + auto decrypter = std::make_unique( context->EncryptionSecretKey(), &LRCMFrameDecrypt::HandleDecrypted); // copy frames so we own them - auto frameDecrypt = std::make_shared< LRCMFrameDecrypt >( - context, std::move(decrypter), this); + auto frameDecrypt = std::make_shared(context, std::move(decrypter), this); // decrypt frames async - frameDecrypt->decrypter->AsyncDecrypt( - context->Worker(), frameDecrypt->frames[0], frameDecrypt); + frameDecrypt->decrypter->AsyncDecrypt(context->Worker(), frameDecrypt->frames[0], frameDecrypt); return true; } } // namespace llarp diff --git a/llarp/messages/relay_commit.hpp b/llarp/messages/relay_commit.hpp index e6b265c34..fe46ae55f 100644 --- a/llarp/messages/relay_commit.hpp +++ b/llarp/messages/relay_commit.hpp @@ -27,30 +27,30 @@ namespace llarp TunnelNonce tunnelNonce; PathID_t txid, rxid; - std::unique_ptr< RouterContact > nextRC; - std::unique_ptr< PoW > work; - uint64_t version = 0; + std::unique_ptr nextRC; + std::unique_ptr work; + uint64_t version = 0; llarp_time_t lifetime = 0s; bool - BDecode(llarp_buffer_t *buf); + BDecode(llarp_buffer_t* buf); bool - BEncode(llarp_buffer_t *buf) const; + BEncode(llarp_buffer_t* buf) const; bool - operator==(const LR_CommitRecord &other) const; + operator==(const LR_CommitRecord& other) const; private: bool - OnKey(llarp_buffer_t *buffer, llarp_buffer_t *key); + OnKey(llarp_buffer_t* buffer, llarp_buffer_t* key); }; struct LR_CommitMessage : public ILinkMessage { - std::array< EncryptedFrame, 8 > frames; + std::array frames; - LR_CommitMessage(std::array< EncryptedFrame, 8 > _frames) + LR_CommitMessage(std::array _frames) : ILinkMessage(), frames(std::move(_frames)) { } @@ -63,18 +63,18 @@ namespace llarp Clear() override; bool - DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf) override; + DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - BEncode(llarp_buffer_t *buf) const override; + BEncode(llarp_buffer_t* buf) const override; bool - HandleMessage(AbstractRouter *router) const override; + HandleMessage(AbstractRouter* router) const override; bool - AsyncDecrypt(llarp::path::PathContext *context) const; + AsyncDecrypt(llarp::path::PathContext* context) const; - const char * + const char* Name() const override { return "RelayCommit"; diff --git a/llarp/messages/relay_status.cpp b/llarp/messages/relay_status.cpp index 6ae15d861..913958f68 100644 --- a/llarp/messages/relay_status.cpp +++ b/llarp/messages/relay_status.cpp @@ -17,20 +17,22 @@ namespace llarp { - struct LRSM_AsyncHandler - : public std::enable_shared_from_this< LRSM_AsyncHandler > + struct LRSM_AsyncHandler : public std::enable_shared_from_this { - using HopHandler_ptr = std::shared_ptr< llarp::path::IHopHandler >; + using HopHandler_ptr = std::shared_ptr; - std::array< EncryptedFrame, 8 > frames; + std::array frames; uint64_t status = 0; HopHandler_ptr path; AbstractRouter* router; PathID_t pathid; - LRSM_AsyncHandler(std::array< EncryptedFrame, 8 > _frames, uint64_t _status, - HopHandler_ptr _path, AbstractRouter* _router, - const PathID_t& pathid) + LRSM_AsyncHandler( + std::array _frames, + uint64_t _status, + HopHandler_ptr _path, + AbstractRouter* _router, + const PathID_t& pathid) : frames(std::move(_frames)) , status(_status) , path(std::move(_path)) @@ -44,8 +46,7 @@ namespace llarp void handle() { - router->NotifyRouterEvent< tooling::PathStatusReceivedEvent >( - router->pubkey(), pathid, status); + router->NotifyRouterEvent(router->pubkey(), pathid, status); path->HandleLRSM(status, frames, router); } @@ -53,8 +54,7 @@ namespace llarp void queue_handle() { - auto func = - std::bind(&llarp::LRSM_AsyncHandler::handle, shared_from_this()); + auto func = std::bind(&llarp::LRSM_AsyncHandler::handle, shared_from_this()); router->threadpool()->addJob(func); } }; @@ -63,28 +63,27 @@ namespace llarp LR_StatusMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(key == "c") + if (key == "c") { return BEncodeReadArray(frames, buf); } - if(key == "p") + if (key == "p") { - if(!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("p", pathid, read, key, buf)) { return false; } } - else if(key == "s") + else if (key == "s") { - if(!BEncodeMaybeReadDictInt("s", status, read, key, buf)) + if (!BEncodeMaybeReadDictInt("s", status, read, key, buf)) { return false; } } - else if(key == "v") + else if (key == "v") { - if(!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, - key, buf)) + if (!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, key, buf)) { return false; } @@ -98,28 +97,28 @@ namespace llarp { std::for_each(frames.begin(), frames.end(), [](auto& f) { f.Clear(); }); version = 0; - status = 0; + status = 0; } bool LR_StatusMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; // msg type - if(!BEncodeWriteDictMsgType(buf, "a", "s")) + if (!BEncodeWriteDictMsgType(buf, "a", "s")) return false; // frames - if(!BEncodeWriteDictArray("c", frames, buf)) + if (!BEncodeWriteDictArray("c", frames, buf)) return false; // path id - if(!BEncodeWriteDictEntry("p", pathid, buf)) + if (!BEncodeWriteDictEntry("p", pathid, buf)) return false; // status (for now, only success bit is relevant) - if(!BEncodeWriteDictInt("s", status, buf)) + if (!BEncodeWriteDictInt("s", status, buf)) return false; // version - if(!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) + if (!bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION)) return false; return bencode_end(buf); @@ -128,27 +127,21 @@ namespace llarp bool LR_StatusMessage::HandleMessage(AbstractRouter* router) const { - llarp::LogDebug("Received LR_Status message from (", session->GetPubKey(), - ")"); - if(frames.size() != path::max_len) + llarp::LogDebug("Received LR_Status message from (", session->GetPubKey(), ")"); + if (frames.size() != path::max_len) { - llarp::LogError("LRSM invalid number of records, ", frames.size(), - "!=", path::max_len); + llarp::LogError("LRSM invalid number of records, ", frames.size(), "!=", path::max_len); return false; } - auto path = - router->pathContext().GetByUpstream(session->GetPubKey(), pathid); - if(!path) + auto path = router->pathContext().GetByUpstream(session->GetPubKey(), pathid); + if (!path) { - llarp::LogWarn( - "unhandled LR_Status message: no associated path found pathid=", - pathid); + llarp::LogWarn("unhandled LR_Status message: no associated path found pathid=", pathid); return false; } - auto handler = std::make_shared< LRSM_AsyncHandler >(frames, status, path, - router, pathid); + auto handler = std::make_shared(frames, status, path, router, pathid); handler->queue_handle(); @@ -164,18 +157,21 @@ namespace llarp // call this from a worker thread bool - LR_StatusMessage::CreateAndSend(AbstractRouter* router, const PathID_t pathid, - const RouterID nextHop, - const SharedSecret pathKey, uint64_t status) + LR_StatusMessage::CreateAndSend( + AbstractRouter* router, + const PathID_t pathid, + const RouterID nextHop, + const SharedSecret pathKey, + uint64_t status) { - auto message = std::make_shared< LR_StatusMessage >(); + auto message = std::make_shared(); message->status = status; message->pathid = pathid; message->SetDummyFrames(); - if(!message->AddFrame(pathKey, status)) + if (!message->AddFrame(pathKey, status)) { return false; } @@ -201,13 +197,13 @@ namespace llarp LR_StatusRecord record; - record.status = newStatus; + record.status = newStatus; record.version = LLARP_PROTO_VERSION; llarp_buffer_t buf(frame.data(), frame.size()); buf.cur = buf.base + EncryptedFrameOverheadSize; // encode record - if(!record.BEncode(&buf)) + if (!record.BEncode(&buf)) { // failed to encode? LogError(Name(), " Failed to generate Status Record"); @@ -215,7 +211,7 @@ namespace llarp return false; } // use ephemeral keypair for frame - if(!frame.DoEncrypt(pathKey, true)) + if (!frame.DoEncrypt(pathKey, true)) { LogError(Name(), " Failed to encrypt LRSR"); DumpBuffer(buf); @@ -226,23 +222,21 @@ namespace llarp } void - LR_StatusMessage::QueueSendMessage(AbstractRouter* router, - const RouterID nextHop, - std::shared_ptr< LR_StatusMessage > msg) + LR_StatusMessage::QueueSendMessage( + AbstractRouter* router, const RouterID nextHop, std::shared_ptr msg) { auto func = std::bind(&LR_StatusMessage::SendMessage, router, nextHop, msg); LogicCall(router->logic(), func); } void - LR_StatusMessage::SendMessage(AbstractRouter* router, const RouterID nextHop, - std::shared_ptr< LR_StatusMessage > msg) + LR_StatusMessage::SendMessage( + AbstractRouter* router, const RouterID nextHop, std::shared_ptr msg) { llarp::LogDebug("Attempting to send LR_Status message to (", nextHop, ")"); - if(not router->SendToOrQueue(nextHop, msg.get())) + if (not router->SendToOrQueue(nextHop, msg.get())) { - llarp::LogError("Sending LR_Status message, SendToOrQueue to ", nextHop, - " failed"); + llarp::LogError("Sending LR_Status message, SendToOrQueue to ", nextHop, " failed"); } } @@ -250,22 +244,20 @@ namespace llarp LR_StatusRecord::BEncode(llarp_buffer_t* buf) const { return bencode_start_dict(buf) && BEncodeWriteDictInt("s", status, buf) - && bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION) - && bencode_end(buf); + && bencode_write_uint64_entry(buf, "v", 1, LLARP_PROTO_VERSION) && bencode_end(buf); } bool LR_StatusRecord::OnKey(llarp_buffer_t* buffer, llarp_buffer_t* key) { - if(!key) + if (!key) return true; bool read = false; - if(!BEncodeMaybeReadDictInt("s", status, read, *key, buffer)) + if (!BEncodeMaybeReadDictInt("s", status, read, *key, buffer)) return false; - if(!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, *key, - buffer)) + if (!BEncodeMaybeVerifyVersion("v", version, LLARP_PROTO_VERSION, read, *key, buffer)) return false; return read; diff --git a/llarp/messages/relay_status.hpp b/llarp/messages/relay_status.hpp index 23f2f7b95..64ea7401f 100644 --- a/llarp/messages/relay_status.hpp +++ b/llarp/messages/relay_status.hpp @@ -23,42 +23,42 @@ namespace llarp struct LR_StatusRecord { - static constexpr uint64_t SUCCESS = 1 << 0; - static constexpr uint64_t FAIL_TIMEOUT = 1 << 1; - static constexpr uint64_t FAIL_CONGESTION = 1 << 2; - static constexpr uint64_t FAIL_DEST_UNKNOWN = 1 << 3; - static constexpr uint64_t FAIL_DECRYPT_ERROR = 1 << 4; + static constexpr uint64_t SUCCESS = 1 << 0; + static constexpr uint64_t FAIL_TIMEOUT = 1 << 1; + static constexpr uint64_t FAIL_CONGESTION = 1 << 2; + static constexpr uint64_t FAIL_DEST_UNKNOWN = 1 << 3; + static constexpr uint64_t FAIL_DECRYPT_ERROR = 1 << 4; static constexpr uint64_t FAIL_MALFORMED_RECORD = 1 << 5; - static constexpr uint64_t FAIL_DEST_INVALID = 1 << 6; - static constexpr uint64_t FAIL_CANNOT_CONNECT = 1 << 7; - static constexpr uint64_t FAIL_DUPLICATE_HOP = 1 << 8; + static constexpr uint64_t FAIL_DEST_INVALID = 1 << 6; + static constexpr uint64_t FAIL_CANNOT_CONNECT = 1 << 7; + static constexpr uint64_t FAIL_DUPLICATE_HOP = 1 << 8; - uint64_t status = 0; + uint64_t status = 0; uint64_t version = 0; bool - BDecode(llarp_buffer_t *buf); + BDecode(llarp_buffer_t* buf); bool - BEncode(llarp_buffer_t *buf) const; + BEncode(llarp_buffer_t* buf) const; bool - operator==(const LR_StatusRecord &other) const; + operator==(const LR_StatusRecord& other) const; private: bool - OnKey(llarp_buffer_t *buffer, llarp_buffer_t *key); + OnKey(llarp_buffer_t* buffer, llarp_buffer_t* key); }; struct LR_StatusMessage : public ILinkMessage { - std::array< EncryptedFrame, 8 > frames; + std::array frames; PathID_t pathid; uint64_t status = 0; - LR_StatusMessage(std::array< EncryptedFrame, 8 > _frames) + LR_StatusMessage(std::array _frames) : ILinkMessage(), frames(std::move(_frames)) { } @@ -71,34 +71,37 @@ namespace llarp Clear() override; bool - DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf) override; + DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) override; bool - BEncode(llarp_buffer_t *buf) const override; + BEncode(llarp_buffer_t* buf) const override; bool - HandleMessage(AbstractRouter *router) const override; + HandleMessage(AbstractRouter* router) const override; void SetDummyFrames(); static bool - CreateAndSend(AbstractRouter *router, const PathID_t pathid, - const RouterID nextHop, const SharedSecret pathKey, - uint64_t status); + CreateAndSend( + AbstractRouter* router, + const PathID_t pathid, + const RouterID nextHop, + const SharedSecret pathKey, + uint64_t status); bool - AddFrame(const SharedSecret &pathKey, uint64_t newStatus); + AddFrame(const SharedSecret& pathKey, uint64_t newStatus); static void - QueueSendMessage(AbstractRouter *router, const RouterID nextHop, - std::shared_ptr< LR_StatusMessage > msg); + QueueSendMessage( + AbstractRouter* router, const RouterID nextHop, std::shared_ptr msg); static void - SendMessage(AbstractRouter *router, const RouterID nextHop, - std::shared_ptr< LR_StatusMessage > msg); + SendMessage( + AbstractRouter* router, const RouterID nextHop, std::shared_ptr msg); - const char * + const char* Name() const override { return "RelayStatus"; diff --git a/llarp/net/address_info.cpp b/llarp/net/address_info.cpp index 6d00ab7cf..be5b2976a 100644 --- a/llarp/net/address_info.cpp +++ b/llarp/net/address_info.cpp @@ -13,21 +13,21 @@ namespace llarp { bool - operator==(const AddressInfo &lhs, const AddressInfo &rhs) + operator==(const AddressInfo& lhs, const AddressInfo& rhs) { // we don't care about rank - return lhs.pubkey == rhs.pubkey && lhs.port == rhs.port - && lhs.dialect == rhs.dialect && lhs.ip == rhs.ip; + return lhs.pubkey == rhs.pubkey && lhs.port == rhs.port && lhs.dialect == rhs.dialect + && lhs.ip == rhs.ip; } bool - operator<(const AddressInfo &lhs, const AddressInfo &rhs) + operator<(const AddressInfo& lhs, const AddressInfo& rhs) { return lhs.rank < rhs.rank || lhs.ip < rhs.ip || lhs.port < rhs.port; } bool - AddressInfo::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf) + AddressInfo::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { uint64_t i; char tmp[128] = {0}; @@ -35,12 +35,12 @@ namespace llarp llarp_buffer_t strbuf; // rank - if(key == "c") + if (key == "c") { - if(!bencode_read_integer(buf, &i)) + if (!bencode_read_integer(buf, &i)) return false; - if(i > 65536 || i <= 0) + if (i > 65536 || i <= 0) return false; rank = i; @@ -48,31 +48,31 @@ namespace llarp } // dialect - if(key == "d") + if (key == "d") { - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz > sizeof(tmp)) + if (strbuf.sz > sizeof(tmp)) return false; memcpy(tmp, strbuf.base, strbuf.sz); tmp[strbuf.sz] = 0; - dialect = std::string(tmp); + dialect = std::string(tmp); return true; } // encryption public key - if(key == "e") + if (key == "e") { return pubkey.BDecode(buf); } // ip address - if(key == "i") + if (key == "i") { - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz >= sizeof(tmp)) + if (strbuf.sz >= sizeof(tmp)) return false; memcpy(tmp, strbuf.base, strbuf.sz); @@ -81,12 +81,12 @@ namespace llarp } // port - if(key == "p") + if (key == "p") { - if(!bencode_read_integer(buf, &i)) + if (!bencode_read_integer(buf, &i)) return false; - if(i > 65536 || i <= 0) + if (i > 65536 || i <= 0) return false; port = i; @@ -94,9 +94,9 @@ namespace llarp } // version - if(key == "v") + if (key == "v") { - if(!bencode_read_integer(buf, &i)) + if (!bencode_read_integer(buf, &i)) return false; return i == LLARP_PROTO_VERSION; } @@ -106,53 +106,53 @@ namespace llarp } bool - AddressInfo::BEncode(llarp_buffer_t *buff) const + AddressInfo::BEncode(llarp_buffer_t* buff) const { char ipbuff[128] = {0}; - const char *ipstr; - if(!bencode_start_dict(buff)) + const char* ipstr; + if (!bencode_start_dict(buff)) return false; /* rank */ - if(!bencode_write_bytestring(buff, "c", 1)) + if (!bencode_write_bytestring(buff, "c", 1)) return false; - if(!bencode_write_uint64(buff, rank)) + if (!bencode_write_uint64(buff, rank)) return false; /* dialect */ - if(!bencode_write_bytestring(buff, "d", 1)) + if (!bencode_write_bytestring(buff, "d", 1)) return false; - if(!bencode_write_bytestring(buff, dialect.c_str(), dialect.size())) + if (!bencode_write_bytestring(buff, dialect.c_str(), dialect.size())) return false; /* encryption key */ - if(!bencode_write_bytestring(buff, "e", 1)) + if (!bencode_write_bytestring(buff, "e", 1)) return false; - if(!bencode_write_bytestring(buff, pubkey.data(), PUBKEYSIZE)) + if (!bencode_write_bytestring(buff, pubkey.data(), PUBKEYSIZE)) return false; /** ip */ - ipstr = inet_ntop(AF_INET6, (void *)&ip, ipbuff, sizeof(ipbuff)); - if(!ipstr) + ipstr = inet_ntop(AF_INET6, (void*)&ip, ipbuff, sizeof(ipbuff)); + if (!ipstr) return false; - if(!bencode_write_bytestring(buff, "i", 1)) + if (!bencode_write_bytestring(buff, "i", 1)) return false; - if(!bencode_write_bytestring(buff, ipstr, strnlen(ipstr, sizeof(ipbuff)))) + if (!bencode_write_bytestring(buff, ipstr, strnlen(ipstr, sizeof(ipbuff)))) return false; /** port */ - if(!bencode_write_bytestring(buff, "p", 1)) + if (!bencode_write_bytestring(buff, "p", 1)) return false; - if(!bencode_write_uint64(buff, port)) + if (!bencode_write_uint64(buff, port)) return false; /** version */ - if(!bencode_write_uint64_entry(buff, "v", 1, LLARP_PROTO_VERSION)) + if (!bencode_write_uint64_entry(buff, "v", 1, LLARP_PROTO_VERSION)) return false; /** end */ return bencode_end(buff); } - std::ostream & - AddressInfo::print(std::ostream &stream, int level, int spaces) const + std::ostream& + AddressInfo::print(std::ostream& stream, int level, int spaces) const { char tmp[128] = {0}; - inet_ntop(AF_INET6, (void *)&ip, tmp, sizeof(tmp)); + inet_ntop(AF_INET6, (void*)&ip, tmp, sizeof(tmp)); Printer printer(stream, level, spaces); printer.printAttribute("ip", tmp); @@ -162,10 +162,10 @@ namespace llarp } void - to_json(nlohmann::json &j, const AddressInfo &a) + to_json(nlohmann::json& j, const AddressInfo& a) { char tmp[128] = {0}; - inet_ntop(AF_INET6, (void *)&a.ip, tmp, sizeof(tmp)); + inet_ntop(AF_INET6, (void*)&a.ip, tmp, sizeof(tmp)); j = nlohmann::json{{"rank", a.rank}, {"dialect", a.dialect}, diff --git a/llarp/net/address_info.hpp b/llarp/net/address_info.hpp index 85087fbda..f56edc5de 100644 --- a/llarp/net/address_info.hpp +++ b/llarp/net/address_info.hpp @@ -47,7 +47,7 @@ namespace llarp size_t operator()(const AddressInfo& addr) const { - return AlignedBuffer< PUBKEYSIZE >::Hash()(addr.pubkey); + return AlignedBuffer::Hash()(addr.pubkey); } }; }; diff --git a/llarp/net/exit_info.cpp b/llarp/net/exit_info.cpp index be1e6efd3..0869d7cca 100644 --- a/llarp/net/exit_info.cpp +++ b/llarp/net/exit_info.cpp @@ -16,23 +16,23 @@ namespace llarp ExitInfo::BEncode(llarp_buffer_t* buf) const { char tmp[128] = {0}; - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!inet_ntop(AF_INET6, address.s6_addr, tmp, sizeof(tmp))) + if (!inet_ntop(AF_INET6, address.s6_addr, tmp, sizeof(tmp))) return false; - if(!BEncodeWriteDictString("a", std::string(tmp), buf)) + if (!BEncodeWriteDictString("a", std::string(tmp), buf)) return false; - if(!inet_ntop(AF_INET6, netmask.s6_addr, tmp, sizeof(tmp))) + if (!inet_ntop(AF_INET6, netmask.s6_addr, tmp, sizeof(tmp))) return false; - if(!BEncodeWriteDictString("b", std::string(tmp), buf)) + if (!BEncodeWriteDictString("b", std::string(tmp), buf)) return false; - if(!BEncodeWriteDictEntry("k", pubkey, buf)) + if (!BEncodeWriteDictEntry("k", pubkey, buf)) return false; - if(!BEncodeWriteDictInt("v", version, buf)) + if (!BEncodeWriteDictInt("v", version, buf)) return false; return bencode_end(buf); @@ -43,10 +43,10 @@ namespace llarp { char tmp[128] = {0}; llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz >= sizeof(tmp)) + if (strbuf.sz >= sizeof(tmp)) return false; memcpy(tmp, strbuf.base, strbuf.sz); @@ -58,13 +58,13 @@ namespace llarp ExitInfo::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictEntry("k", pubkey, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("k", pubkey, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, k, buf)) return false; - if(k == "a") + if (k == "a") return bdecode_ip_string(buf, address); - if(k == "b") + if (k == "b") return bdecode_ip_string(buf, netmask); return read; } @@ -77,14 +77,13 @@ namespace llarp std::ostringstream ss; char tmp[128] = {0}; - if(inet_ntop(AF_INET6, (void*)&address, tmp, sizeof(tmp))) + if (inet_ntop(AF_INET6, (void*)&address, tmp, sizeof(tmp))) ss << tmp; else return stream; ss << std::string("/"); #if defined(ANDROID) || defined(RPI) - snprintf(tmp, sizeof(tmp), "%zu", - llarp::bits::count_array_bits(netmask.s6_addr)); + snprintf(tmp, sizeof(tmp), "%zu", llarp::bits::count_array_bits(netmask.s6_addr)); ss << tmp; #else ss << std::to_string(llarp::bits::count_array_bits(netmask.s6_addr)); diff --git a/llarp/net/exit_info.hpp b/llarp/net/exit_info.hpp index d8ba133d0..c08e8642f 100644 --- a/llarp/net/exit_info.hpp +++ b/llarp/net/exit_info.hpp @@ -25,7 +25,7 @@ namespace llarp ExitInfo() = default; - ExitInfo(const PubKey &pk, const nuint32_t &ipv4_exit) : pubkey(pk) + ExitInfo(const PubKey& pk, const nuint32_t& ipv4_exit) : pubkey(pk) { memset(address.s6_addr, 0, 16); address.s6_addr[11] = 0xff; @@ -35,23 +35,23 @@ namespace llarp } bool - BEncode(llarp_buffer_t *buf) const; + BEncode(llarp_buffer_t* buf) const; bool - BDecode(llarp_buffer_t *buf) + BDecode(llarp_buffer_t* buf) { return bencode_decode_dict(*this, buf); } bool - DecodeKey(const llarp_buffer_t &k, llarp_buffer_t *buf); + DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf); - std::ostream & - print(std::ostream &stream, int level, int spaces) const; + std::ostream& + print(std::ostream& stream, int level, int spaces) const; }; - inline std::ostream & - operator<<(std::ostream &out, const ExitInfo &xi) + inline std::ostream& + operator<<(std::ostream& out, const ExitInfo& xi) { return xi.print(out, -1, -1); } diff --git a/llarp/net/ip.cpp b/llarp/net/ip.cpp index b47ebf4e6..a7031b3a9 100644 --- a/llarp/net/ip.cpp +++ b/llarp/net/ip.cpp @@ -15,24 +15,24 @@ namespace llarp { namespace net { - inline static uint32_t * - in6_uint32_ptr(in6_addr &addr) + inline static uint32_t* + in6_uint32_ptr(in6_addr& addr) { - return (uint32_t *)addr.s6_addr; + return (uint32_t*)addr.s6_addr; } - inline static const uint32_t * - in6_uint32_ptr(const in6_addr &addr) + inline static const uint32_t* + in6_uint32_ptr(const in6_addr& addr) { - return (uint32_t *)addr.s6_addr; + return (uint32_t*)addr.s6_addr; } huint128_t IPPacket::In6ToHUInt(in6_addr addr) { - uint8_t *ptr = reinterpret_cast< uint8_t * >(addr.s6_addr); + uint8_t* ptr = reinterpret_cast(addr.s6_addr); uint128_t x{0}; - for(int i = 0; i < 16; i++) + for (int i = 0; i < 16; i++) { x <<= 8; x |= ptr[i]; @@ -61,14 +61,14 @@ namespace llarp IPPacket::TruncateV6(huint128_t i) { huint32_t ret = {0}; - ret.h = (uint32_t)(i.h & (0x00000000ffffffffUL)); + ret.h = (uint32_t)(i.h & (0x00000000ffffffffUL)); return ret; } huint128_t IPPacket::srcv6() const { - if(IsV6()) + if (IsV6()) return In6ToHUInt(HeaderV6()->srcaddr); return ExpandV4(srcv4()); @@ -77,16 +77,16 @@ namespace llarp huint128_t IPPacket::dstv6() const { - if(IsV6()) + if (IsV6()) return In6ToHUInt(HeaderV6()->dstaddr); return ExpandV4(dstv4()); } bool - IPPacket::Load(const llarp_buffer_t &pkt) + IPPacket::Load(const llarp_buffer_t& pkt) { - if(pkt.sz > sizeof(buf) or pkt.sz == 0) + if (pkt.sz > sizeof(buf) or pkt.sz == 0) return false; sz = pkt.sz; std::copy_n(pkt.base, sz, buf); @@ -96,7 +96,7 @@ namespace llarp ManagedBuffer IPPacket::ConstBuffer() const { - const byte_t *ptr = buf; + const byte_t* ptr = buf; llarp_buffer_t b(ptr, sz); return ManagedBuffer(b); } @@ -104,7 +104,7 @@ namespace llarp ManagedBuffer IPPacket::Buffer() { - byte_t *ptr = buf; + byte_t* ptr = buf; llarp_buffer_t b(ptr, sz); return ManagedBuffer(b); } @@ -163,13 +163,15 @@ namespace llarp #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) + 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) { - 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 @@ -180,10 +182,12 @@ namespace llarp } static nuint16_t - deltaIPv6Checksum(nuint16_t old_sum, const uint32_t old_src_ip[4], - const uint32_t old_dst_ip[4], - const uint32_t new_src_ip[4], - const uint32_t new_dst_ip[4]) + deltaIPv6Checksum( + nuint16_t old_sum, + const uint32_t old_src_ip[4], + const uint32_t old_dst_ip[4], + const uint32_t new_src_ip[4], + const uint32_t new_dst_ip[4]) { /* we don't actually care in what way integers are arranged in memory * internally */ @@ -193,13 +197,10 @@ namespace llarp * less correct */ /* we could do 64bit ints too but then we couldn't reuse 32bit macros and * 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); +#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); #undef ADDN128CS #undef SUBN128CS @@ -215,54 +216,70 @@ namespace llarp #undef SUB32CS static void - deltaChecksumIPv4TCP(byte_t *pld, size_t psz, size_t fragoff, - size_t chksumoff, nuint32_t oSrcIP, nuint32_t oDstIP, - nuint32_t nSrcIP, nuint32_t nDstIP) + deltaChecksumIPv4TCP( + byte_t* pld, + size_t psz, + size_t fragoff, + size_t chksumoff, + nuint32_t oSrcIP, + nuint32_t oDstIP, + nuint32_t nSrcIP, + nuint32_t nDstIP) { - if(fragoff > chksumoff || psz < chksumoff - fragoff + 2) + if (fragoff > chksumoff || psz < chksumoff - fragoff + 2) return; - auto check = (nuint16_t *)(pld + chksumoff - fragoff); + auto check = (nuint16_t*)(pld + chksumoff - fragoff); *check = deltaIPv4Checksum(*check, oSrcIP, oDstIP, nSrcIP, nDstIP); // usually, TCP checksum field cannot be 0xFFff, // because one's complement addition cannot result in 0x0000, // and there's inversion in the end; // emulate that. - if(check->n == 0xFFff) + if (check->n == 0xFFff) check->n = 0x0000; } static void - deltaChecksumIPv6TCP(byte_t *pld, size_t psz, size_t fragoff, - size_t chksumoff, const uint32_t oSrcIP[4], - const uint32_t oDstIP[4], const uint32_t nSrcIP[4], - const uint32_t nDstIP[4]) + deltaChecksumIPv6TCP( + byte_t* pld, + size_t psz, + size_t fragoff, + size_t chksumoff, + const uint32_t oSrcIP[4], + const uint32_t oDstIP[4], + const uint32_t nSrcIP[4], + const uint32_t nDstIP[4]) { - if(fragoff > chksumoff || psz < chksumoff - fragoff + 2) + if (fragoff > chksumoff || psz < chksumoff - fragoff + 2) return; - auto check = (nuint16_t *)(pld + chksumoff - fragoff); + auto check = (nuint16_t*)(pld + chksumoff - fragoff); *check = deltaIPv6Checksum(*check, oSrcIP, oDstIP, nSrcIP, nDstIP); // usually, TCP checksum field cannot be 0xFFff, // because one's complement addition cannot result in 0x0000, // and there's inversion in the end; // emulate that. - if(check->n == 0xFFff) + if (check->n == 0xFFff) check->n = 0x0000; } static void - deltaChecksumIPv4UDP(byte_t *pld, size_t psz, size_t fragoff, - nuint32_t oSrcIP, nuint32_t oDstIP, nuint32_t nSrcIP, - nuint32_t nDstIP) + deltaChecksumIPv4UDP( + 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) + if (fragoff > 6 || psz < 6 + 2) return; - auto check = (nuint16_t *)(pld + 6); - if(check->n == 0x0000) + auto check = (nuint16_t*)(pld + 6); + if (check->n == 0x0000) return; // 0 is used to indicate "no checksum", don't change *check = deltaIPv4Checksum(*check, oSrcIP, oDstIP, nSrcIP, nDstIP); @@ -277,14 +294,19 @@ namespace llarp } static void - deltaChecksumIPv6UDP(byte_t *pld, size_t psz, size_t fragoff, - const uint32_t oSrcIP[4], const uint32_t oDstIP[4], - const uint32_t nSrcIP[4], const uint32_t nDstIP[4]) + deltaChecksumIPv6UDP( + byte_t* pld, + size_t psz, + size_t fragoff, + const uint32_t oSrcIP[4], + const uint32_t oDstIP[4], + const uint32_t nSrcIP[4], + const uint32_t nDstIP[4]) { - if(fragoff > 6 || psz < 6 + 2) + if (fragoff > 6 || psz < 6 + 2) return; - auto check = (nuint16_t *)(pld + 6); + auto check = (nuint16_t*)(pld + 6); // 0 is used to indicate "no checksum", don't change // even tho this shouldn't happen for IPv6, handle it properly // we actually should drop/log 0-checksum packets per spec @@ -292,7 +314,7 @@ namespace llarp // it's better to do correct thing there regardless // XXX or maybe we should change this function to be able to return error? // either way that's not a priority - if(check->n == 0x0000) + if (check->n == 0x0000) return; *check = deltaIPv6Checksum(*check, oSrcIP, oDstIP, nSrcIP, nDstIP); @@ -318,34 +340,31 @@ namespace llarp // L4 checksum auto ihs = size_t(hdr->ihl * 4); - if(ihs <= sz) + if (ihs <= sz) { auto pld = buf + ihs; auto psz = sz - ihs; auto fragoff = size_t((ntohs(hdr->frag_off) & 0x1Fff) * 8); - switch(hdr->protocol) + switch (hdr->protocol) { case 6: // TCP - deltaChecksumIPv4TCP(pld, psz, fragoff, 16, oSrcIP, oDstIP, nSrcIP, - nDstIP); + deltaChecksumIPv4TCP(pld, psz, fragoff, 16, oSrcIP, oDstIP, nSrcIP, nDstIP); break; case 17: // UDP case 136: // UDP-Lite - same checksum place, same 0->0xFFff condition - deltaChecksumIPv4UDP(pld, psz, fragoff, oSrcIP, oDstIP, nSrcIP, - nDstIP); + deltaChecksumIPv4UDP(pld, psz, fragoff, oSrcIP, oDstIP, nSrcIP, nDstIP); break; case 33: // DCCP - deltaChecksumIPv4TCP(pld, psz, fragoff, 6, oSrcIP, oDstIP, nSrcIP, - nDstIP); + deltaChecksumIPv4TCP(pld, psz, fragoff, 6, oSrcIP, oDstIP, nSrcIP, nDstIP); break; } } // IPv4 checksum - auto v4chk = (nuint16_t *)&(hdr->check); - *v4chk = deltaIPv4Checksum(*v4chk, oSrcIP, oDstIP, nSrcIP, nDstIP); + auto v4chk = (nuint16_t*)&(hdr->check); + *v4chk = deltaIPv4Checksum(*v4chk, oSrcIP, oDstIP, nSrcIP, nDstIP); // write new IP addresses hdr->saddr = nSrcIP.n; @@ -358,21 +377,21 @@ namespace llarp const size_t ihs = 4 + 4 + 16 + 16; // XXX should've been checked at upper level? - if(sz <= ihs) + if (sz <= ihs) return; auto hdr = HeaderV6(); - const auto oldSrcIP = hdr->srcaddr; - const auto oldDstIP = hdr->dstaddr; - const uint32_t *oSrcIP = in6_uint32_ptr(oldSrcIP); - const uint32_t *oDstIP = in6_uint32_ptr(oldDstIP); + const auto oldSrcIP = hdr->srcaddr; + const auto oldDstIP = hdr->dstaddr; + const uint32_t* oSrcIP = in6_uint32_ptr(oldSrcIP); + const uint32_t* oDstIP = in6_uint32_ptr(oldDstIP); // IPv6 address - hdr->srcaddr = HUIntToIn6(src); - hdr->dstaddr = HUIntToIn6(dst); - const uint32_t *nSrcIP = in6_uint32_ptr(hdr->srcaddr); - const uint32_t *nDstIP = in6_uint32_ptr(hdr->dstaddr); + hdr->srcaddr = HUIntToIn6(src); + hdr->dstaddr = HUIntToIn6(dst); + const uint32_t* nSrcIP = in6_uint32_ptr(hdr->srcaddr); + const uint32_t* nDstIP = in6_uint32_ptr(hdr->dstaddr); // TODO IPv6 header options auto pld = buf + ihs; @@ -380,17 +399,17 @@ namespace llarp size_t fragoff = 0; auto nextproto = hdr->proto; - for(;;) + for (;;) { - switch(nextproto) + switch (nextproto) { case 0: // Hop-by-Hop Options case 43: // Routing Header case 60: // Destination Options { - nextproto = pld[0]; + nextproto = pld[0]; auto addlen = (size_t(pld[1]) + 1) * 8; - if(psz < addlen) + if (psz < addlen) return; pld += addlen; psz -= addlen; @@ -406,14 +425,14 @@ namespace llarp +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ nextproto = pld[0]; - fragoff = (uint16_t(pld[2]) << 8) | (uint16_t(pld[3]) & 0xFC); - if(psz < 8) + fragoff = (uint16_t(pld[2]) << 8) | (uint16_t(pld[3]) & 0xFC); + if (psz < 8) return; pld += 8; psz -= 8; // jump straight to payload processing - if(fragoff != 0) + if (fragoff != 0) goto endprotohdrs; break; @@ -423,20 +442,17 @@ namespace llarp } endprotohdrs: - switch(nextproto) + switch (nextproto) { case 6: // TCP - deltaChecksumIPv6TCP(pld, psz, fragoff, 16, oSrcIP, oDstIP, nSrcIP, - nDstIP); + deltaChecksumIPv6TCP(pld, psz, fragoff, 16, oSrcIP, oDstIP, nSrcIP, nDstIP); break; case 17: // UDP case 136: // UDP-Lite - same checksum place, same 0->0xFFff condition - deltaChecksumIPv6UDP(pld, psz, fragoff, oSrcIP, oDstIP, nSrcIP, - nDstIP); + deltaChecksumIPv6UDP(pld, psz, fragoff, oSrcIP, oDstIP, nSrcIP, nDstIP); break; case 33: // DCCP - deltaChecksumIPv6TCP(pld, psz, fragoff, 6, oSrcIP, oDstIP, nSrcIP, - nDstIP); + deltaChecksumIPv6TCP(pld, psz, fragoff, 6, oSrcIP, oDstIP, nSrcIP, nDstIP); break; } } diff --git a/llarp/net/ip.hpp b/llarp/net/ip.hpp index fd3234704..7e61aeae9 100644 --- a/llarp/net/ip.hpp +++ b/llarp/net/ip.hpp @@ -42,13 +42,12 @@ struct ip_header #include typedef struct ip_hdr { - unsigned char - ip_header_len : 4; // 4-bit header length (in 32-bit words) normally=5 - // (Means 20 Bytes may be 24 also) - unsigned char version : 4; // 4-bit IPv4 version - unsigned char ip_tos; // IP type of service - unsigned short ip_total_length; // Total length - unsigned short ip_id; // Unique identifier + unsigned char ip_header_len : 4; // 4-bit header length (in 32-bit words) normally=5 + // (Means 20 Bytes may be 24 also) + unsigned char version : 4; // 4-bit IPv4 version + unsigned char ip_tos; // IP type of service + unsigned short ip_total_length; // Total length + unsigned short ip_id; // Unique identifier unsigned char ip_frag_offset : 5; // Fragment offset field @@ -223,9 +222,9 @@ namespace llarp inline service::ProtocolType ServiceProtocol() const { - if(IsV4()) + if (IsV4()) return service::eProtocolTrafficV4; - if(IsV6()) + if (IsV6()) return service::eProtocolTrafficV6; return service::eProtocolControl; diff --git a/llarp/net/ip_range_map.hpp b/llarp/net/ip_range_map.hpp index d598424c0..0a562911e 100644 --- a/llarp/net/ip_range_map.hpp +++ b/llarp/net/ip_range_map.hpp @@ -11,39 +11,39 @@ namespace llarp /// key by range hit /// TODO: do some kind of magic shit to ensure near constant time for /// lookups - template < typename Value_t > + template struct IPRangeMap { using Range_t = IPRange; - using IP_t = Range_t::Addr_t; + using IP_t = Range_t::Addr_t; - using Entry_t = std::pair< Range_t, Value_t >; - using Container_t = std::forward_list< Entry_t >; + using Entry_t = std::pair; + using Container_t = std::forward_list; /// get a set of all values - std::set< Value_t > + std::set Values() const { - std::set< Value_t > all; - for(const auto &entry : m_Entries) + std::set all; + for (const auto& entry : m_Entries) all.insert(entry.second); return all; } void - ForEachValue(std::function< void(const Value_t &) > functor) const + ForEachValue(std::function functor) const { - for(const auto &entry : m_Entries) + for (const auto& entry : m_Entries) functor(entry.second); } /// convert all values into type T using a transformer - template < typename T, typename Transformer > - std::set< T > + template + std::set TransformValues(Transformer transform) const { - std::set< T > transformed; - for(const auto &entry : m_Entries) + std::set transformed; + for (const auto& entry : m_Entries) { T val = transform(entry.second); transformed.insert(std::move(val)); @@ -52,13 +52,13 @@ namespace llarp } /// return a set of all values who's range contains this IP - std::set< Value_t > - FindAll(const IP_t &addr) const + std::set + FindAll(const IP_t& addr) const { - std::set< Value_t > found; - for(const auto &entry : m_Entries) + std::set found; + for (const auto& entry : m_Entries) { - if(entry.first.Contains(addr)) + if (entry.first.Contains(addr)) found.insert(entry.second); } return found; @@ -67,14 +67,14 @@ namespace llarp struct CompareEntry { bool - operator()(const Entry_t &left, const Entry_t &right) const + operator()(const Entry_t& left, const Entry_t& right) const { return left.first < right.first; } }; void - Insert(const Range_t &addr, const Value_t &val) + Insert(const Range_t& addr, const Value_t& val) { m_Entries.emplace_front(addr, val); m_Entries.sort(CompareEntry{}); diff --git a/llarp/net/net.cpp b/llarp/net/net.cpp index 555cb6258..9fae668bc 100644 --- a/llarp/net/net.cpp +++ b/llarp/net/net.cpp @@ -23,9 +23,9 @@ bool operator==(const sockaddr& a, const sockaddr& b) { - if(a.sa_family != b.sa_family) + if (a.sa_family != b.sa_family) return false; - switch(a.sa_family) + switch (a.sa_family) { case AF_INET: return *((const sockaddr_in*)&a) == *((const sockaddr_in*)&b); @@ -79,9 +79,12 @@ operator==(const sockaddr_in6& a, const sockaddr_in6& b) // the inline monkey patch for downlevel platforms #ifndef _MSC_VER extern "C" DWORD FAR PASCAL -_GetAdaptersAddresses(ULONG Family, ULONG Flags, PVOID Reserved, - PIP_ADAPTER_ADDRESSES pAdapterAddresses, - PULONG pOutBufLen); +_GetAdaptersAddresses( + ULONG Family, + ULONG Flags, + PVOID Reserved, + PIP_ADAPTER_ADDRESSES pAdapterAddresses, + PULONG pOutBufLen); #endif // in any case, we still need to implement some form of @@ -130,12 +133,12 @@ llarp_nt_sockaddr_pton(const char* src, struct sockaddr* dst) struct addrinfo hints; struct addrinfo* result = nullptr; memset(&hints, 0, sizeof(struct addrinfo)); - hints.ai_family = AF_UNSPEC; + hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_TCP; - hints.ai_flags = AI_NUMERICHOST; - const int status = getaddrinfo(src, nullptr, &hints, &result); - if(!status) + hints.ai_flags = AI_NUMERICHOST; + const int status = getaddrinfo(src, nullptr, &hints, &result); + if (!status) { memcpy(dst, result->ai_addr, result->ai_addrlen); freeaddrinfo(result); @@ -164,21 +167,21 @@ static bool _llarp_nt_getadaptersinfo(struct llarp_nt_ifaddrs_t** ifap) { DWORD dwRet; - ULONG ulOutBufLen = DEFAULT_BUFFER_SIZE; + ULONG ulOutBufLen = DEFAULT_BUFFER_SIZE; PIP_ADAPTER_INFO pAdapterInfo = nullptr; - PIP_ADAPTER_INFO pAdapter = nullptr; + PIP_ADAPTER_INFO pAdapter = nullptr; /* loop to handle interfaces coming online causing a buffer overflow * between first call to list buffer length and second call to enumerate. */ - for(unsigned i = 3; i; i--) + for (unsigned i = 3; i; i--) { #ifdef DEBUG fprintf(stderr, "IP_ADAPTER_INFO buffer length %lu bytes.\n", ulOutBufLen); #endif pAdapterInfo = (IP_ADAPTER_INFO*)_llarp_nt_heap_alloc(ulOutBufLen); - dwRet = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen); - if(ERROR_BUFFER_OVERFLOW == dwRet) + dwRet = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen); + if (ERROR_BUFFER_OVERFLOW == dwRet) { _llarp_nt_heap_free(pAdapterInfo); pAdapterInfo = nullptr; @@ -189,13 +192,13 @@ _llarp_nt_getadaptersinfo(struct llarp_nt_ifaddrs_t** ifap) } } - switch(dwRet) + switch (dwRet) { case ERROR_SUCCESS: /* NO_ERROR */ break; case ERROR_BUFFER_OVERFLOW: errno = ENOBUFS; - if(pAdapterInfo) + if (pAdapterInfo) _llarp_nt_heap_free(pAdapterInfo); return false; default: @@ -203,20 +206,19 @@ _llarp_nt_getadaptersinfo(struct llarp_nt_ifaddrs_t** ifap) #ifdef DEBUG fprintf(stderr, "system call failed: %lu\n", GetLastError()); #endif - if(pAdapterInfo) + if (pAdapterInfo) _llarp_nt_heap_free(pAdapterInfo); return false; } /* count valid adapters */ int n = 0, k = 0; - for(pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) + for (pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) { - for(IP_ADDR_STRING* pIPAddr = &pAdapter->IpAddressList; pIPAddr; - pIPAddr = pIPAddr->Next) + for (IP_ADDR_STRING* pIPAddr = &pAdapter->IpAddressList; pIPAddr; pIPAddr = pIPAddr->Next) { /* skip null adapters */ - if(strlen(pIPAddr->IpAddress.String) == 0) + if (strlen(pIPAddr->IpAddress.String) == 0) continue; ++n; } @@ -227,50 +229,45 @@ _llarp_nt_getadaptersinfo(struct llarp_nt_ifaddrs_t** ifap) #endif /* contiguous block for adapter list */ - struct _llarp_nt_ifaddrs_t* ifa = - llarp_nt_new0(struct _llarp_nt_ifaddrs_t, n); + struct _llarp_nt_ifaddrs_t* ifa = llarp_nt_new0(struct _llarp_nt_ifaddrs_t, n); struct _llarp_nt_ifaddrs_t* ift = ifa; - int val = 0; + int val = 0; /* now populate list */ - for(pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) + for (pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) { - for(IP_ADDR_STRING* pIPAddr = &pAdapter->IpAddressList; pIPAddr; - pIPAddr = pIPAddr->Next) + for (IP_ADDR_STRING* pIPAddr = &pAdapter->IpAddressList; pIPAddr; pIPAddr = pIPAddr->Next) { /* skip null adapters */ - if(strlen(pIPAddr->IpAddress.String) == 0) + if (strlen(pIPAddr->IpAddress.String) == 0) continue; /* address */ ift->_ifa.ifa_addr = (struct sockaddr*)&ift->_addr; - val = - llarp_nt_sockaddr_pton(pIPAddr->IpAddress.String, ift->_ifa.ifa_addr); + val = llarp_nt_sockaddr_pton(pIPAddr->IpAddress.String, ift->_ifa.ifa_addr); assert(1 == val); /* name */ #ifdef DEBUG - fprintf(stderr, "name:%s IPv4 index:%lu\n", pAdapter->AdapterName, - pAdapter->Index); + fprintf(stderr, "name:%s IPv4 index:%lu\n", pAdapter->AdapterName, pAdapter->Index); #endif ift->_ifa.ifa_name = ift->_name; StringCchCopyN(ift->_ifa.ifa_name, 128, pAdapter->AdapterName, 128); /* flags: assume up, broadcast and multicast */ ift->_ifa.ifa_flags = IFF_UP | IFF_BROADCAST | IFF_MULTICAST; - if(pAdapter->Type == MIB_IF_TYPE_LOOPBACK) + if (pAdapter->Type == MIB_IF_TYPE_LOOPBACK) ift->_ifa.ifa_flags |= IFF_LOOPBACK; /* netmask */ ift->_ifa.ifa_netmask = (sockaddr*)&ift->_netmask; - val = - llarp_nt_sockaddr_pton(pIPAddr->IpMask.String, ift->_ifa.ifa_netmask); + val = llarp_nt_sockaddr_pton(pIPAddr->IpMask.String, ift->_ifa.ifa_netmask); assert(1 == val); /* next */ - if(k++ < (n - 1)) + if (k++ < (n - 1)) { ift->_ifa.ifa_next = (struct llarp_nt_ifaddrs_t*)(ift + 1); - ift = (struct _llarp_nt_ifaddrs_t*)(ift->_ifa.ifa_next); + ift = (struct _llarp_nt_ifaddrs_t*)(ift->_ifa.ifa_next); } else { @@ -279,7 +276,7 @@ _llarp_nt_getadaptersinfo(struct llarp_nt_ifaddrs_t** ifap) } } - if(pAdapterInfo) + if (pAdapterInfo) _llarp_nt_heap_free(pAdapterInfo); *ifap = (struct llarp_nt_ifaddrs_t*)ifa; return true; @@ -432,8 +429,7 @@ _llarp_nt_getadaptersaddresses(struct llarp_nt_ifaddrs_t** ifap) * Windows 7 SP1 returns 64 for Teredo links which is incorrect. */ -#define IN6_IS_ADDR_TEREDO(addr) \ - (((const uint32_t*)(addr))[0] == ntohl(0x20010000)) +#define IN6_IS_ADDR_TEREDO(addr) (((const uint32_t*)(addr))[0] == ntohl(0x20010000)) if(AF_INET6 == unicast->Address.lpSockaddr->sa_family && /* TunnelType only applies to one interface on the adapter and no @@ -639,13 +635,13 @@ _llarp_nt_getadaptersaddresses_nametoindex(const char* ifname) // IP_ADAPTER_ADDRESSES *pAdapterAddresses = nullptr, *adapter; char szAdapterName[256]; - if(!ifname) + if (!ifname) return 0; StringCchCopyN(szAdapterName, sizeof(szAdapterName), ifname, 256); dwRet = GetAdapterIndex((LPWSTR)szAdapterName, &ifIndex); - if(!dwRet) + if (!dwRet) return ifIndex; else return 0; @@ -715,8 +711,7 @@ llarp_nt_getifaddrs(struct llarp_nt_ifaddrs_t** ifap) { assert(nullptr != ifap); #ifdef DEBUG - fprintf(stderr, "llarp_nt_getifaddrs (ifap:%p error:%p)\n", (void*)ifap, - (void*)errno); + fprintf(stderr, "llarp_nt_getifaddrs (ifap:%p error:%p)\n", (void*)ifap, (void*)errno); #endif return _llarp_nt_getadaptersinfo(ifap); } @@ -724,7 +719,7 @@ llarp_nt_getifaddrs(struct llarp_nt_ifaddrs_t** ifap) static void llarp_nt_freeifaddrs(struct llarp_nt_ifaddrs_t* ifa) { - if(!ifa) + if (!ifa) return; free(ifa); } @@ -733,7 +728,7 @@ llarp_nt_freeifaddrs(struct llarp_nt_ifaddrs_t* ifa) static unsigned llarp_nt_if_nametoindex(const char* ifname) { - if(!ifname) + if (!ifname) return 0; return _llarp_nt_getadaptersaddresses_nametoindex(ifname); } @@ -750,33 +745,33 @@ bool llarp_getifaddr(const char* ifname, int af, struct sockaddr* addr) { ifaddrs* ifa = nullptr; - bool found = false; + bool found = false; socklen_t sl = sizeof(sockaddr_in6); - if(af == AF_INET) + if (af == AF_INET) sl = sizeof(sockaddr_in); #ifndef _WIN32 - if(getifaddrs(&ifa) == -1) + if (getifaddrs(&ifa) == -1) #else - if(!strcmp(ifname, "lo") || !strcmp(ifname, "lo0")) + if (!strcmp(ifname, "lo") || !strcmp(ifname, "lo0")) { sockaddr_in* lo = (sockaddr_in*)addr; - lo->sin_family = af; - lo->sin_port = 0; + lo->sin_family = af; + lo->sin_port = 0; inet_pton(af, "127.0.0.1", &lo->sin_addr); return true; } - if(!getifaddrs(&ifa)) + if (!getifaddrs(&ifa)) #endif return false; ifaddrs* i = ifa; - while(i) + while (i) { - if(i->ifa_addr) + if (i->ifa_addr) { // llarp::LogInfo(__FILE__, "scanning ", i->ifa_name, " af: ", // std::to_string(i->ifa_addr->sa_family)); - if(llarp::StrEq(i->ifa_name, ifname) && i->ifa_addr->sa_family == af) + if (llarp::StrEq(i->ifa_name, ifname) && i->ifa_addr->sa_family == af) { // can't do this here // llarp::Addr a(*i->ifa_addr); @@ -784,10 +779,10 @@ llarp_getifaddr(const char* ifname, int af, struct sockaddr* addr) //{ // llarp::LogInfo(__FILE__, "found ", ifname, " af: ", af); memcpy(addr, i->ifa_addr, sl); - if(af == AF_INET6) + if (af == AF_INET6) { // set scope id - auto* ip6addr = (sockaddr_in6*)addr; + auto* ip6addr = (sockaddr_in6*)addr; ip6addr->sin6_scope_id = if_nametoindex(ifname); ip6addr->sin6_flowinfo = 0; } @@ -798,7 +793,7 @@ llarp_getifaddr(const char* ifname, int af, struct sockaddr* addr) } i = i->ifa_next; } - if(ifa) + if (ifa) freeifaddrs(ifa); return found; } @@ -806,24 +801,24 @@ llarp_getifaddr(const char* ifname, int af, struct sockaddr* addr) namespace llarp { static void - IterAllNetworkInterfaces(std::function< void(ifaddrs* const) > visit) + IterAllNetworkInterfaces(std::function visit) { ifaddrs* ifa = nullptr; #ifndef _WIN32 - if(getifaddrs(&ifa) == -1) + if (getifaddrs(&ifa) == -1) #else - if(!getifaddrs(&ifa)) + if (!getifaddrs(&ifa)) #endif return; ifaddrs* i = ifa; - while(i) + while (i) { visit(i); i = i->ifa_next; } - if(ifa) + if (ifa) freeifaddrs(ifa); } @@ -832,18 +827,18 @@ namespace llarp { bool found = false; IterAllNetworkInterfaces([&](ifaddrs* i) { - if(found) + if (found) return; - if(i->ifa_addr) + if (i->ifa_addr) { - if(i->ifa_addr->sa_family == af) + if (i->ifa_addr->sa_family == af) { llarp::Addr a(*i->ifa_addr); - if(!a.IsBogon()) + if (!a.IsBogon()) { ifname = i->ifa_name; - found = true; + found = true; } } } @@ -855,12 +850,12 @@ namespace llarp std::string FindFreeRange() { - std::vector< IPRange > currentRanges; + std::vector currentRanges; IterAllNetworkInterfaces([&](ifaddrs* i) { - if(i && i->ifa_addr) + if (i && i->ifa_addr) { const auto fam = i->ifa_addr->sa_family; - if(fam != AF_INET) + if (fam != AF_INET) return; auto* addr = (sockaddr_in*)i->ifa_addr; auto* mask = (sockaddr_in*)i->ifa_netmask; @@ -870,55 +865,54 @@ namespace llarp // do not delete, otherwise GCC will do horrible things to this lambda LogDebug("found ", ifaddr, " with mask ", ifmask); #endif - if(addr->sin_addr.s_addr) + if (addr->sin_addr.s_addr) // skip unconfig'd adapters (windows passes these through the unix-y // wrapper) - currentRanges.emplace_back( - IPRange{net::IPPacket::ExpandV4(xntohl(ifaddr)), - net::IPPacket::ExpandV4(xntohl(ifmask))}); + currentRanges.emplace_back(IPRange{net::IPPacket::ExpandV4(xntohl(ifaddr)), + net::IPPacket::ExpandV4(xntohl(ifmask))}); } }); // try 10.x.0.0/16 byte_t oct = 0; - while(oct < 255) + while (oct < 255) { const huint32_t loaddr = ipaddr_ipv4_bits(10, oct, 0, 1); const huint32_t hiaddr = ipaddr_ipv4_bits(10, oct, 255, 255); - bool hit = false; - for(const auto& range : currentRanges) + bool hit = false; + for (const auto& range : currentRanges) { hit = hit || range.ContainsV4(loaddr) || range.ContainsV4(hiaddr); } - if(!hit) + if (!hit) return loaddr.ToString() + "/16"; ++oct; } // try 192.168.x.0/24 oct = 0; - while(oct < 255) + while (oct < 255) { const huint32_t loaddr = ipaddr_ipv4_bits(192, 168, oct, 1); const huint32_t hiaddr = ipaddr_ipv4_bits(192, 168, oct, 255); - bool hit = false; - for(const auto& range : currentRanges) + bool hit = false; + for (const auto& range : currentRanges) { hit = hit || range.ContainsV4(loaddr) || range.ContainsV4(hiaddr); } - if(!hit) + if (!hit) return loaddr.ToString() + "/24"; } // try 172.16.x.0/24 oct = 0; - while(oct < 255) + while (oct < 255) { const huint32_t loaddr = ipaddr_ipv4_bits(172, 16, oct, 1); const huint32_t hiaddr = ipaddr_ipv4_bits(172, 16, oct, 255); - bool hit = false; - for(const auto& range : currentRanges) + bool hit = false; + for (const auto& range : currentRanges) { hit = hit || range.ContainsV4(loaddr) || range.ContainsV4(hiaddr); } - if(!hit) + if (!hit) return loaddr.ToString() + "/24"; ++oct; } @@ -932,22 +926,21 @@ namespace llarp FindFreeTun() { uint8_t num = 0; - while(num < 255) + while (num < 255) { std::stringstream ifname_ss; ifname_ss << "lokitun" << num; std::string iftestname = ifname_ss.str(); struct sockaddr addr; bool found = llarp_getifaddr(iftestname.c_str(), AF_INET, &addr); - if(!found) + if (!found) { - llarp::LogDebug("Detected " + iftestname - + " is available for use, configuring as such"); + llarp::LogDebug("Detected " + iftestname + " is available for use, configuring as such"); break; } num++; } - if(num == 255) + if (num == 255) { llarp::LogError("Could not find any free lokitun interface names"); return ""; @@ -967,7 +960,7 @@ namespace llarp { sockaddr_storage s; auto* sptr = (sockaddr*)&s; - if(!llarp_getifaddr(ifname.c_str(), af, sptr)) + if (!llarp_getifaddr(ifname.c_str(), af, sptr)) return false; addr = *sptr; return true; @@ -976,22 +969,22 @@ namespace llarp bool AllInterfaces(int af, Addr& result) { - if(af == AF_INET) + if (af == AF_INET) { sockaddr_in addr; - addr.sin_family = AF_INET; + addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); - addr.sin_port = htons(0); - result = addr; + addr.sin_port = htons(0); + result = addr; return true; } - if(af == AF_INET6) + if (af == AF_INET6) { sockaddr_in6 addr6; addr6.sin6_family = AF_INET6; - addr6.sin6_port = htons(0); - addr6.sin6_addr = IN6ADDR_ANY_INIT; - result = addr6; + addr6.sin6_port = htons(0); + addr6.sin6_addr = IN6ADDR_ANY_INIT; + result = addr6; return true; } @@ -1007,10 +1000,10 @@ namespace llarp (void)addr; return false; #else - if(!ipv6_is_siit(addr)) + if (!ipv6_is_siit(addr)) return false; - return IsIPv4Bogon(ipaddr_ipv4_bits(addr.s6_addr[12], addr.s6_addr[13], - addr.s6_addr[14], addr.s6_addr[15])); + return IsIPv4Bogon( + ipaddr_ipv4_bits(addr.s6_addr[12], addr.s6_addr[13], addr.s6_addr[14], addr.s6_addr[15])); #endif } @@ -1033,21 +1026,21 @@ namespace llarp const auto colinpos = str.find(":"); const auto slashpos = str.find("/"); std::string bitsstr; - if(slashpos != std::string::npos) + if (slashpos != std::string::npos) { bitsstr = str.substr(slashpos + 1); - str = str.substr(0, slashpos); + str = str.substr(0, slashpos); } - if(colinpos == std::string::npos) + if (colinpos == std::string::npos) { huint32_t ip; - if(!ip.FromString(str)) + if (!ip.FromString(str)) return false; addr = net::IPPacket::ExpandV4(ip); - if(!bitsstr.empty()) + if (!bitsstr.empty()) { auto bits = atoi(bitsstr.c_str()); - if(bits < 0 || bits > 32) + if (bits < 0 || bits > 32) return false; netmask_bits = netmask_ipv6_bits(96 + bits); } @@ -1056,12 +1049,12 @@ namespace llarp } else { - if(!addr.FromString(str)) + if (!addr.FromString(str)) return false; - if(!bitsstr.empty()) + if (!bitsstr.empty()) { auto bits = atoi(bitsstr.c_str()); - if(bits < 0 || bits > 128) + if (bits < 0 || bits > 128) return false; netmask_bits = netmask_ipv6_bits(bits); } @@ -1079,11 +1072,11 @@ namespace llarp char buf[INET6_ADDRSTRLEN + 1] = {0}; std::string str; in6_addr inaddr = {}; - size_t numset = 0; - uint128_t bits = netmask_bits.h; - while(bits) + size_t numset = 0; + uint128_t bits = netmask_bits.h; + while (bits) { - if(bits & 1) + if (bits & 1) numset++; bits >>= 1; } @@ -1101,18 +1094,25 @@ namespace llarp bool IsIPv4Bogon(const huint32_t& addr) { - static std::vector< IPRange > bogonRanges = { - iprange_ipv4(0, 0, 0, 0, 8), iprange_ipv4(10, 0, 0, 0, 8), - iprange_ipv4(21, 0, 0, 0, 8), iprange_ipv4(100, 64, 0, 0, 10), - iprange_ipv4(127, 0, 0, 0, 8), iprange_ipv4(169, 254, 0, 0, 8), - iprange_ipv4(172, 16, 0, 0, 12), iprange_ipv4(192, 0, 0, 0, 24), - iprange_ipv4(192, 0, 2, 0, 24), iprange_ipv4(192, 88, 99, 0, 24), - iprange_ipv4(192, 168, 0, 0, 16), iprange_ipv4(198, 18, 0, 0, 15), - iprange_ipv4(198, 51, 100, 0, 24), iprange_ipv4(203, 0, 113, 0, 24), - iprange_ipv4(224, 0, 0, 0, 4), iprange_ipv4(240, 0, 0, 0, 4)}; - for(const auto& bogon : bogonRanges) + static std::vector bogonRanges = {iprange_ipv4(0, 0, 0, 0, 8), + iprange_ipv4(10, 0, 0, 0, 8), + iprange_ipv4(21, 0, 0, 0, 8), + iprange_ipv4(100, 64, 0, 0, 10), + iprange_ipv4(127, 0, 0, 0, 8), + iprange_ipv4(169, 254, 0, 0, 8), + iprange_ipv4(172, 16, 0, 0, 12), + iprange_ipv4(192, 0, 0, 0, 24), + iprange_ipv4(192, 0, 2, 0, 24), + iprange_ipv4(192, 88, 99, 0, 24), + iprange_ipv4(192, 168, 0, 0, 16), + iprange_ipv4(198, 18, 0, 0, 15), + iprange_ipv4(198, 51, 100, 0, 24), + iprange_ipv4(203, 0, 113, 0, 24), + iprange_ipv4(224, 0, 0, 0, 4), + iprange_ipv4(240, 0, 0, 0, 4)}; + for (const auto& bogon : bogonRanges) { - if(bogon.ContainsV4(addr)) + if (bogon.ContainsV4(addr)) { #if defined(TESTNET) return false; diff --git a/llarp/net/net.hpp b/llarp/net/net.hpp index 9143c6d79..aa6bb5c5a 100644 --- a/llarp/net/net.hpp +++ b/llarp/net/net.hpp @@ -59,8 +59,8 @@ namespace llarp { struct IPRange { - using Addr_t = huint128_t; - huint128_t addr = {0}; + using Addr_t = huint128_t; + huint128_t addr = {0}; huint128_t netmask_bits = {0}; /// return true if ip is contained in this ip range @@ -83,16 +83,14 @@ namespace llarp huint128_t HighestAddr() const { - return (addr & netmask_bits) - + (huint128_t{1} << (128 - bits::count_bits_128(netmask_bits.h))) + return (addr & netmask_bits) + (huint128_t{1} << (128 - bits::count_bits_128(netmask_bits.h))) - huint128_t{1}; } bool operator<(const IPRange& other) const { - return (this->addr & this->netmask_bits) - < (other.addr & other.netmask_bits) + return (this->addr & this->netmask_bits) < (other.addr & other.netmask_bits) || this->netmask_bits < other.netmask_bits; } @@ -110,9 +108,8 @@ namespace llarp 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 @@ -150,11 +147,10 @@ namespace llarp constexpr bool ipv6_is_siit(const in6_addr& addr) { - return addr.s6_addr[11] == 0xff && addr.s6_addr[10] == 0xff - && addr.s6_addr[9] == 0 && addr.s6_addr[8] == 0 && addr.s6_addr[7] == 0 - && addr.s6_addr[6] == 0 && addr.s6_addr[5] == 0 && addr.s6_addr[4] == 0 - && addr.s6_addr[3] == 0 && addr.s6_addr[2] == 0 && addr.s6_addr[1] == 0 - && addr.s6_addr[0] == 0; + return addr.s6_addr[11] == 0xff && addr.s6_addr[10] == 0xff && addr.s6_addr[9] == 0 + && addr.s6_addr[8] == 0 && addr.s6_addr[7] == 0 && addr.s6_addr[6] == 0 + && addr.s6_addr[5] == 0 && addr.s6_addr[4] == 0 && addr.s6_addr[3] == 0 + && addr.s6_addr[2] == 0 && addr.s6_addr[1] == 0 && addr.s6_addr[0] == 0; } bool diff --git a/llarp/net/net_addr.cpp b/llarp/net/net_addr.cpp index 31660af45..7df970959 100644 --- a/llarp/net/net_addr.cpp +++ b/llarp/net/net_addr.cpp @@ -28,7 +28,7 @@ namespace llarp void Addr::port(uint16_t port) { - if(af() == AF_INET) + if (af() == AF_INET) { _addr4.sin_port = htons(port); } @@ -78,11 +78,10 @@ namespace llarp Addr::from_char_array(string_view in) { auto pPosition = in.find(':'); - if(pPosition != string_view::npos) + if (pPosition != string_view::npos) { // parse port - uint16_t port = - std::atoi(std::string(in.begin() + pPosition + 1, in.end()).c_str()); + uint16_t port = std::atoi(std::string(in.begin() + pPosition + 1, in.end()).c_str()); LogDebug("Setting port ", std::to_string(port)); this->port(port); } @@ -93,30 +92,30 @@ namespace llarp memset(&hint, '\0', sizeof hint); hint.ai_family = PF_UNSPEC; - hint.ai_flags = AI_NUMERICHOST; + hint.ai_flags = AI_NUMERICHOST; - if(pPosition != string_view::npos) + if (pPosition != string_view::npos) { - ret = getaddrinfo(std::string(in.begin(), in.begin() + pPosition).c_str(), - nullptr, &hint, &res); + ret = getaddrinfo( + std::string(in.begin(), in.begin() + pPosition).c_str(), nullptr, &hint, &res); } else { ret = getaddrinfo(std::string(in).c_str(), nullptr, &hint, &res); } - if(ret) + if (ret) { LogError("failed to determine address family: ", in); return false; } - if(res->ai_family == AF_INET6) + if (res->ai_family == AF_INET6) { LogError("IPv6 address not supported yet", in); return false; } - if(res->ai_family != AF_INET) + if (res->ai_family != AF_INET) { LogError("Address family not supported yet", in); return false; @@ -124,7 +123,7 @@ namespace llarp // put it in _addr4 struct in_addr* addr = &_addr4.sin_addr; - if(inet_aton(std::string(in).c_str(), addr) == 0) + if (inet_aton(std::string(in).c_str(), addr) == 0) { LogError("failed to parse ", in); return false; @@ -132,14 +131,14 @@ namespace llarp _addr.sin6_family = res->ai_family; _addr4.sin_family = res->ai_family; - _addr4.sin_port = 0; // save a call, 0 is 0 no matter how u arrange it -#if((__APPLE__ && __MACH__) || __FreeBSD__) + _addr4.sin_port = 0; // save a call, 0 is 0 no matter how u arrange it +#if ((__APPLE__ && __MACH__) || __FreeBSD__) _addr4.sin_len = sizeof(in_addr); #endif // set up SIIT uint8_t* addrptr = _addr.sin6_addr.s6_addr; - addrptr[11] = 0xff; - addrptr[10] = 0xff; + addrptr[11] = 0xff; + addrptr[10] = 0xff; memcpy(12 + addrptr, &addr->s_addr, sizeof(in_addr)); freeaddrinfo(res); @@ -147,18 +146,17 @@ namespace llarp } bool - Addr::from_4int(const uint8_t one, const uint8_t two, const uint8_t three, - const uint8_t four) + Addr::from_4int(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four) { Zero(&_addr, sizeof(sockaddr_in6)); struct in_addr* addr = &_addr4.sin_addr; - auto* ip = (unsigned char*)&(addr->s_addr); + auto* ip = (unsigned char*)&(addr->s_addr); _addr.sin6_family = AF_INET; // set ipv4 mode _addr4.sin_family = AF_INET; - _addr4.sin_port = 0; + _addr4.sin_port = 0; -#if((__APPLE__ && __MACH__) || __FreeBSD__) +#if ((__APPLE__ && __MACH__) || __FreeBSD__) _addr4.sin_len = sizeof(in_addr); #endif // FIXME: watch endian @@ -168,23 +166,25 @@ namespace llarp ip[3] = four; // set up SIIT uint8_t* addrptr = _addr.sin6_addr.s6_addr; - addrptr[11] = 0xff; - addrptr[10] = 0xff; + addrptr[11] = 0xff; + addrptr[10] = 0xff; memcpy(12 + addrptr, &addr->s_addr, sizeof(in_addr)); // copy ipv6 SIIT into _addr4 memcpy(&_addr4.sin_addr.s_addr, addr4(), sizeof(in_addr)); return true; } - Addr::Addr(const uint8_t one, const uint8_t two, const uint8_t three, - const uint8_t four) - : Addr() + Addr::Addr(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four) : Addr() { this->from_4int(one, two, three, four); } - Addr::Addr(const uint8_t one, const uint8_t two, const uint8_t three, - const uint8_t four, const uint16_t p_port) + Addr::Addr( + const uint8_t one, + const uint8_t two, + const uint8_t three, + const uint8_t four, + const uint16_t p_port) : Addr() { this->from_4int(one, two, three, four); @@ -195,10 +195,10 @@ namespace llarp { memcpy(addr6(), other.ip.s6_addr, 16); _addr.sin6_port = htons(other.port); - if(ipv6_is_siit(other.ip)) + if (ipv6_is_siit(other.ip)) { _addr4.sin_family = AF_INET; - _addr4.sin_port = htons(other.port); + _addr4.sin_port = htons(other.port); _addr.sin6_family = AF_INET; memcpy(&_addr4.sin_addr.s_addr, addr4(), sizeof(in_addr)); } @@ -210,16 +210,15 @@ namespace llarp { Zero(&_addr, sizeof(sockaddr_in6)); _addr.sin6_family = AF_INET; - uint8_t* addrptr = _addr.sin6_addr.s6_addr; - uint16_t* port = &_addr.sin6_port; + uint8_t* addrptr = _addr.sin6_addr.s6_addr; + uint16_t* port = &_addr.sin6_port; // SIIT - memcpy(12 + addrptr, &((const sockaddr_in*)(&other))->sin_addr, - sizeof(in_addr)); - addrptr[11] = 0xff; - addrptr[10] = 0xff; - *port = ((sockaddr_in*)(&other))->sin_port; + memcpy(12 + addrptr, &((const sockaddr_in*)(&other))->sin_addr, sizeof(in_addr)); + addrptr[11] = 0xff; + addrptr[10] = 0xff; + *port = ((sockaddr_in*)(&other))->sin_port; _addr4.sin_family = AF_INET; - _addr4.sin_port = *port; + _addr4.sin_port = *port; memcpy(&_addr4.sin_addr.s_addr, addr4(), sizeof(in_addr)); } @@ -227,14 +226,14 @@ namespace llarp { memcpy(addr6(), other.sin6_addr.s6_addr, 16); _addr.sin6_port = htons(other.sin6_port); - auto ptr = &_addr.sin6_addr.s6_addr[0]; + auto ptr = &_addr.sin6_addr.s6_addr[0]; // TODO: detect SIIT better - if(ptr[11] == 0xff && ptr[10] == 0xff && ptr[9] == 0 && ptr[8] == 0 - && ptr[7] == 0 && ptr[6] == 0 && ptr[5] == 0 && ptr[4] == 0 - && ptr[3] == 0 && ptr[2] == 0 && ptr[1] == 0 && ptr[0] == 0) + if (ptr[11] == 0xff && ptr[10] == 0xff && ptr[9] == 0 && ptr[8] == 0 && ptr[7] == 0 + && ptr[6] == 0 && ptr[5] == 0 && ptr[4] == 0 && ptr[3] == 0 && ptr[2] == 0 && ptr[1] == 0 + && ptr[0] == 0) { _addr4.sin_family = AF_INET; - _addr4.sin_port = htons(other.sin6_port); + _addr4.sin_port = htons(other.sin6_port); _addr.sin6_family = AF_INET; memcpy(&_addr4.sin_addr.s_addr, addr4(), sizeof(in_addr)); } @@ -246,24 +245,22 @@ namespace llarp { Zero(&_addr, sizeof(sockaddr_in6)); _addr.sin6_family = other.sa_family; - uint8_t* addrptr = _addr.sin6_addr.s6_addr; - uint16_t* port = &_addr.sin6_port; - switch(other.sa_family) + uint8_t* addrptr = _addr.sin6_addr.s6_addr; + uint16_t* port = &_addr.sin6_port; + switch (other.sa_family) { case AF_INET: // SIIT - memcpy(12 + addrptr, &((const sockaddr_in*)(&other))->sin_addr, - sizeof(in_addr)); - addrptr[11] = 0xff; - addrptr[10] = 0xff; - *port = ((sockaddr_in*)(&other))->sin_port; + memcpy(12 + addrptr, &((const sockaddr_in*)(&other))->sin_addr, sizeof(in_addr)); + addrptr[11] = 0xff; + addrptr[10] = 0xff; + *port = ((sockaddr_in*)(&other))->sin_port; _addr4.sin_family = AF_INET; - _addr4.sin_port = *port; + _addr4.sin_port = *port; memcpy(&_addr4.sin_addr.s_addr, addr4(), sizeof(in_addr)); break; case AF_INET6: - memcpy(addrptr, &((const sockaddr_in6*)(&other))->sin6_addr.s6_addr, - 16); + memcpy(addrptr, &((const sockaddr_in6*)(&other))->sin6_addr.s6_addr, 16); *port = ((sockaddr_in6*)(&other))->sin6_port; break; // TODO : sockaddr_ll @@ -283,9 +280,9 @@ namespace llarp std::ostream& operator<<(std::ostream& out, const Addr& a) { - char tmp[128] = {0}; + char tmp[128] = {0}; const void* ptr = nullptr; - if(a.af() == AF_INET6) + if (a.af() == AF_INET6) { out << "["; ptr = a.addr6(); @@ -294,10 +291,10 @@ namespace llarp { ptr = a.addr4(); } - if(inet_ntop(a.af(), (void*)ptr, tmp, sizeof(tmp))) + if (inet_ntop(a.af(), (void*)ptr, tmp, sizeof(tmp))) { out << tmp; - if(a.af() == AF_INET6) + if (a.af() == AF_INET6) out << "]"; } return out << ":" << a.port(); @@ -309,22 +306,22 @@ namespace llarp void *dst, *src; uint16_t* ptr; size_t slen; - switch(af()) + switch (af()) { case AF_INET: { auto* ipv4_dst = (sockaddr_in*)other; - dst = (void*)&ipv4_dst->sin_addr.s_addr; - src = (void*)&_addr4.sin_addr.s_addr; - ptr = &((sockaddr_in*)other)->sin_port; - slen = sizeof(in_addr); + dst = (void*)&ipv4_dst->sin_addr.s_addr; + src = (void*)&_addr4.sin_addr.s_addr; + ptr = &((sockaddr_in*)other)->sin_port; + slen = sizeof(in_addr); break; } case AF_INET6: { - dst = (void*)((sockaddr_in6*)other)->sin6_addr.s6_addr; - src = (void*)_addr.sin6_addr.s6_addr; - ptr = &((sockaddr_in6*)other)->sin6_port; + dst = (void*)((sockaddr_in6*)other)->sin6_addr.s6_addr; + src = (void*)_addr.sin6_addr.s6_addr; + ptr = &((sockaddr_in6*)other)->sin6_port; slen = sizeof(in6_addr); break; } @@ -334,7 +331,7 @@ namespace llarp } } memcpy(dst, src, slen); - *ptr = htons(port()); + *ptr = htons(port()); other->sa_family = af(); } @@ -352,7 +349,7 @@ namespace llarp Addr::operator const sockaddr*() const { - if(af() == AF_INET) + if (af() == AF_INET) return (const sockaddr*)&_addr4; return (const sockaddr*)&_addr; @@ -360,7 +357,7 @@ namespace llarp Addr::operator sockaddr*() const { - if(af() == AF_INET) + if (af() == AF_INET) return (sockaddr*)&_addr4; return (sockaddr*)&_addr; @@ -369,20 +366,19 @@ namespace llarp bool Addr::operator<(const Addr& other) const { - if(af() == AF_INET && other.af() == AF_INET) + if (af() == AF_INET && other.af() == AF_INET) return port() < other.port() || addr4()->s_addr < other.addr4()->s_addr; - return port() < other.port() || *addr6() < *other.addr6() - || af() < other.af(); + return port() < other.port() || *addr6() < *other.addr6() || af() < other.af(); } bool Addr::operator==(const Addr& other) const { - if(af() != other.af() || port() != other.port()) + if (af() != other.af() || port() != other.port()) return false; - if(af() == AF_INET) + if (af() == AF_INET) return addr4()->s_addr == other.addr4()->s_addr; return memcmp(addr6(), other.addr6(), 16) == 0; @@ -393,24 +389,22 @@ namespace llarp { Zero(&_addr, sizeof(sockaddr_in6)); _addr.sin6_family = other.sa_family; - uint8_t* addrptr = _addr.sin6_addr.s6_addr; - uint16_t* port = &_addr.sin6_port; - switch(other.sa_family) + uint8_t* addrptr = _addr.sin6_addr.s6_addr; + uint16_t* port = &_addr.sin6_port; + switch (other.sa_family) { case AF_INET: // SIIT - memcpy(12 + addrptr, &((const sockaddr_in*)(&other))->sin_addr, - sizeof(in_addr)); - addrptr[11] = 0xff; - addrptr[10] = 0xff; - *port = ((sockaddr_in*)(&other))->sin_port; + memcpy(12 + addrptr, &((const sockaddr_in*)(&other))->sin_addr, sizeof(in_addr)); + addrptr[11] = 0xff; + addrptr[10] = 0xff; + *port = ((sockaddr_in*)(&other))->sin_port; _addr4.sin_family = AF_INET; - _addr4.sin_port = *port; + _addr4.sin_port = *port; memcpy(&_addr4.sin_addr.s_addr, addr4(), sizeof(in_addr)); break; case AF_INET6: - memcpy(addrptr, &((const sockaddr_in6*)(&other))->sin6_addr.s6_addr, - 16); + memcpy(addrptr, &((const sockaddr_in6*)(&other))->sin6_addr.s6_addr, 16); *port = ((sockaddr_in6*)(&other))->sin6_port; break; // TODO : sockaddr_ll @@ -466,7 +460,7 @@ namespace llarp socklen_t Addr::SockLen() const { - if(af() == AF_INET) + if (af() == AF_INET) return sizeof(sockaddr_in); return sizeof(sockaddr_in6); @@ -489,7 +483,7 @@ namespace llarp std::size_t operator()(Addr const& a) const noexcept { - if(a.af() == AF_INET) + if (a.af() == AF_INET) { return a.port() ^ a.addr4()->s_addr; } diff --git a/llarp/net/net_addr.hpp b/llarp/net/net_addr.hpp index 62e6ff150..5fb820811 100644 --- a/llarp/net/net_addr.hpp +++ b/llarp/net/net_addr.hpp @@ -46,14 +46,16 @@ namespace llarp from_char_array(string_view str); bool - from_4int(const uint8_t one, const uint8_t two, const uint8_t three, - const uint8_t four); + from_4int(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four); - Addr(const uint8_t one, const uint8_t two, const uint8_t three, - const uint8_t four); + Addr(const uint8_t one, const uint8_t two, const uint8_t three, const uint8_t four); - Addr(const uint8_t one, const uint8_t two, const uint8_t three, - const uint8_t four, const uint16_t p_port); + Addr( + const uint8_t one, + const uint8_t two, + const uint8_t three, + const uint8_t four, + const uint16_t p_port); Addr(const AddressInfo& other); Addr(const sockaddr_in& other); @@ -122,7 +124,7 @@ namespace llarp getHostLong() { in_addr_t addr = this->addr4()->s_addr; - uint32_t byte = ntohl(addr); + uint32_t byte = ntohl(addr); return byte; } @@ -154,7 +156,7 @@ namespace llarp std::size_t operator()(Addr const& a) const noexcept { - if(a.af() == AF_INET) + if (a.af() == AF_INET) { return a.port() ^ a.addr4()->s_addr; } diff --git a/llarp/net/net_int.cpp b/llarp/net/net_int.cpp index e33d0873c..91dfcd7e3 100644 --- a/llarp/net/net_int.cpp +++ b/llarp/net/net_int.cpp @@ -28,9 +28,9 @@ namespace llarp std::string huint32_t::ToString() const { - uint32_t n = htonl(h); + uint32_t n = htonl(h); char tmp[INET_ADDRSTRLEN] = {0}; - if(!inet_ntop(AF_INET, (void*)&n, tmp, sizeof(tmp))) + if (!inet_ntop(AF_INET, (void*)&n, tmp, sizeof(tmp))) return ""; return tmp; } @@ -39,9 +39,9 @@ namespace llarp std::string huint128_t::ToString() const { - auto addr = ntoh128(h); + auto addr = ntoh128(h); char tmp[INET6_ADDRSTRLEN] = {0}; - if(!inet_ntop(AF_INET6, (void*)&addr, tmp, sizeof(tmp))) + if (!inet_ntop(AF_INET6, (void*)&addr, tmp, sizeof(tmp))) return ""; return tmp; } @@ -51,7 +51,7 @@ namespace llarp huint32_t::FromString(const std::string& str) { uint32_t n; - if(!inet_pton(AF_INET, str.c_str(), &n)) + if (!inet_pton(AF_INET, str.c_str(), &n)) return false; h = ntohl(n); return true; @@ -62,7 +62,7 @@ namespace llarp huint128_t::FromString(const std::string& str) { llarp::uint128_t i; - if(!inet_pton(AF_INET6, str.c_str(), &i)) + if (!inet_pton(AF_INET6, str.c_str(), &i)) return false; h = ntoh128(i); return true; @@ -73,7 +73,7 @@ namespace llarp nuint32_t::ToString() const { char tmp[INET_ADDRSTRLEN] = {0}; - if(!inet_ntop(AF_INET, (void*)&n, tmp, sizeof(tmp))) + if (!inet_ntop(AF_INET, (void*)&n, tmp, sizeof(tmp))) return ""; return tmp; } diff --git a/llarp/net/net_int.hpp b/llarp/net/net_int.hpp index d8281942b..ea0d5b843 100644 --- a/llarp/net/net_int.hpp +++ b/llarp/net/net_int.hpp @@ -23,7 +23,7 @@ namespace llarp { - template < typename UInt_t > + template struct huint_t { UInt_t h; @@ -103,7 +103,7 @@ namespace llarp return h == x.h; } - using V6Container = std::vector< uint8_t >; + using V6Container = std::vector; void ToV6(V6Container& c); @@ -120,11 +120,11 @@ namespace llarp } }; - using huint32_t = huint_t< uint32_t >; - using huint16_t = huint_t< uint16_t >; - using huint128_t = huint_t< llarp::uint128_t >; + using huint32_t = huint_t; + using huint16_t = huint_t; + using huint128_t = huint_t; - template < typename UInt_t > + template struct nuint_t { UInt_t n; @@ -177,7 +177,7 @@ namespace llarp return n == x.n; } - using V6Container = std::vector< uint8_t >; + using V6Container = std::vector; void ToV6(V6Container& c); @@ -191,9 +191,9 @@ namespace llarp } }; - using nuint32_t = nuint_t< uint32_t >; - using nuint16_t = nuint_t< uint16_t >; - using nuint128_t = nuint_t< llarp::uint128_t >; + using nuint32_t = nuint_t; + using nuint16_t = nuint_t; + using nuint128_t = nuint_t; static inline nuint32_t xhtonl(huint32_t x) @@ -222,23 +222,23 @@ namespace llarp namespace std { - template < typename UInt_t > - struct hash< llarp::nuint_t< UInt_t > > + template + struct hash> { size_t - operator()(const llarp::nuint_t< UInt_t >& x) const + operator()(const llarp::nuint_t& x) const { - return std::hash< UInt_t >{}(x.n); + return std::hash{}(x.n); } }; - template < typename UInt_t > - struct hash< llarp::huint_t< UInt_t > > + template + struct hash> { size_t - operator()(const llarp::huint_t< UInt_t >& x) const + operator()(const llarp::huint_t& x) const { - return std::hash< UInt_t >{}(x.h); + return std::hash{}(x.h); } }; } // namespace std diff --git a/llarp/net/uint128.hpp b/llarp/net/uint128.hpp index 6760f2541..8f13053f5 100644 --- a/llarp/net/uint128.hpp +++ b/llarp/net/uint128.hpp @@ -45,7 +45,7 @@ namespace llarp } constexpr uint128_t(const uint128_t&) = default; - constexpr uint128_t(uint128_t&&) = default; + constexpr uint128_t(uint128_t&&) = default; constexpr uint128_t& operator=(const uint128_t&) = default; constexpr uint128_t& @@ -108,21 +108,21 @@ namespace llarp // bool: true if any bit set explicit constexpr operator bool() const { - return static_cast< bool >(lower) || static_cast< bool >(upper); + return static_cast(lower) || static_cast(upper); } // Casting to basic unsigned int types: casts away upper bits explicit constexpr operator uint8_t() const { - return static_cast< uint8_t >(lower); + return static_cast(lower); } explicit constexpr operator uint16_t() const { - return static_cast< uint16_t >(lower); + return static_cast(lower); } explicit constexpr operator uint32_t() const { - return static_cast< uint32_t >(lower); + return static_cast(lower); } explicit constexpr operator uint64_t() const { @@ -168,7 +168,7 @@ namespace llarp constexpr uint128_t& operator++() { - if(++lower == 0) + if (++lower == 0) ++upper; return *this; } @@ -185,7 +185,7 @@ namespace llarp operator+=(const uint128_t& b) { lower += b.lower; - if(lower < b.lower) + if (lower < b.lower) ++upper; upper += b.upper; return *this; @@ -201,7 +201,7 @@ namespace llarp constexpr uint128_t& operator-=(const uint128_t& b) { - if(b.lower > lower) + if (b.lower > lower) --upper; lower -= b.lower; upper -= b.upper; @@ -218,20 +218,20 @@ namespace llarp constexpr uint128_t& operator<<=(uint64_t shift) { - if(shift == 0) + if (shift == 0) { } - else if(shift < 64) + else if (shift < 64) { upper = upper << shift | (lower >> (64 - shift)); lower <<= shift; } - else if(shift == 64) + else if (shift == 64) { upper = lower; lower = 0; } - else if(shift < 128) + else if (shift < 128) { upper = lower << (shift - 64); lower = 0; @@ -253,20 +253,20 @@ namespace llarp constexpr uint128_t& operator>>=(uint64_t shift) { - if(shift == 0) + if (shift == 0) { } - else if(shift < 64) + else if (shift < 64) { lower = lower >> shift | upper << (64 - shift); upper >>= shift; } - else if(shift == 64) + else if (shift == 64) { lower = upper; upper = 0; } - else if(shift < 128) + else if (shift < 128) { lower = upper >> (shift - 64); upper = 0; @@ -287,8 +287,7 @@ namespace llarp } }; - static_assert(sizeof(uint128_t) == 16, - "uint128_t has unexpected size (padding?)"); + static_assert(sizeof(uint128_t) == 16, "uint128_t has unexpected size (padding?)"); } // namespace llarp @@ -296,13 +295,13 @@ namespace std { // Hash function for uint128_t template <> - struct hash< llarp::uint128_t > + struct hash { size_t operator()(const llarp::uint128_t& i) const { - size_t h = std::hash< uint64_t >()(i.lower); - h ^= std::hash< uint64_t >()(i.upper) + 0x9e3779b9 + (h << 6) + (h >> 2); + size_t h = std::hash()(i.lower); + h ^= std::hash()(i.upper) + 0x9e3779b9 + (h << 6) + (h >> 2); return h; } }; diff --git a/llarp/nodedb.cpp b/llarp/nodedb.cpp index f16153bc7..6761ddd6d 100644 --- a/llarp/nodedb.cpp +++ b/llarp/nodedb.cpp @@ -26,11 +26,11 @@ llarp_nodedb::NetDBEntry::NetDBEntry(llarp::RouterContact value) } bool -llarp_nodedb::Remove(const llarp::RouterID &pk) +llarp_nodedb::Remove(const llarp::RouterID& pk) { bool removed = false; - RemoveIf([&](const llarp::RouterContact &rc) -> bool { - if(rc.pubkey == pk) + RemoveIf([&](const llarp::RouterContact& rc) -> bool { + if (rc.pubkey == pk) { removed = true; return true; @@ -48,34 +48,33 @@ llarp_nodedb::Clear() } bool -llarp_nodedb::Get(const llarp::RouterID &pk, llarp::RouterContact &result) +llarp_nodedb::Get(const llarp::RouterID& pk, llarp::RouterContact& result) { llarp::util::Lock l(access); auto itr = entries.find(pk); - if(itr == entries.end()) + if (itr == entries.end()) return false; result = itr->second.rc; return true; } void -KillRCJobs(const std::set< std::string > &files) +KillRCJobs(const std::set& files) { - for(const auto &file : files) + for (const auto& file : files) fs::remove(file); } void -llarp_nodedb::RemoveIf( - std::function< bool(const llarp::RouterContact &rc) > filter) +llarp_nodedb::RemoveIf(std::function filter) { - std::set< std::string > files; + std::set files; { llarp::util::Lock l(access); auto itr = entries.begin(); - while(itr != entries.end()) + while (itr != entries.end()) { - if(filter(itr->second.rc)) + if (filter(itr->second.rc)) { files.insert(getRCFilePath(itr->second.rc.pubkey)); itr = entries.erase(itr); @@ -89,52 +88,53 @@ llarp_nodedb::RemoveIf( } bool -llarp_nodedb::Has(const llarp::RouterID &pk) +llarp_nodedb::Has(const llarp::RouterID& pk) { llarp::util::Lock lock(access); return entries.find(pk) != entries.end(); } llarp::RouterContact -llarp_nodedb::FindClosestTo(const llarp::dht::Key_t &location) +llarp_nodedb::FindClosestTo(const llarp::dht::Key_t& location) { llarp::RouterContact rc; const llarp::dht::XorMetric compare(location); - visit([&rc, compare](const auto &otherRC) -> bool { - if(rc.pubkey.IsZero()) + visit([&rc, compare](const auto& otherRC) -> bool { + if (rc.pubkey.IsZero()) { rc = otherRC; return true; } - if(compare(llarp::dht::Key_t{otherRC.pubkey.as_array()}, - llarp::dht::Key_t{rc.pubkey.as_array()})) + if (compare( + llarp::dht::Key_t{otherRC.pubkey.as_array()}, llarp::dht::Key_t{rc.pubkey.as_array()})) rc = otherRC; return true; }); return rc; } -std::vector< llarp::RouterContact > -llarp_nodedb::FindClosestTo(const llarp::dht::Key_t &location, - uint32_t numRouters) +std::vector +llarp_nodedb::FindClosestTo(const llarp::dht::Key_t& location, uint32_t numRouters) { llarp::util::Lock lock(access); - std::vector< const llarp::RouterContact * > all; + std::vector all; all.reserve(entries.size()); - for(auto &entry : entries) + for (auto& entry : entries) { all.push_back(&entry.second.rc); } auto it_mid = numRouters < all.size() ? all.begin() + numRouters : all.end(); - std::partial_sort(all.begin(), it_mid, all.end(), - [compare = llarp::dht::XorMetric{location}]( - auto *a, auto *b) { return compare(*a, *b); }); + std::partial_sort( + all.begin(), + it_mid, + all.end(), + [compare = llarp::dht::XorMetric{location}](auto* a, auto* b) { return compare(*a, *b); }); - std::vector< llarp::RouterContact > closest; + std::vector closest; closest.reserve(numRouters); - for(auto it = all.begin(); it != it_mid; ++it) + for (auto it = all.begin(); it != it_mid; ++it) closest.push_back(**it); return closest; @@ -143,12 +143,10 @@ llarp_nodedb::FindClosestTo(const llarp::dht::Key_t &location, /// skiplist directory is hex encoded first nibble /// skiplist filename is .snode.signed std::string -llarp_nodedb::getRCFilePath(const llarp::RouterID &pubkey) const +llarp_nodedb::getRCFilePath(const llarp::RouterID& pubkey) const { char ftmp[68] = {0}; - const char *hexname = - llarp::HexEncode< llarp::AlignedBuffer< 32 >, decltype(ftmp) >(pubkey, - ftmp); + const char* hexname = llarp::HexEncode, decltype(ftmp)>(pubkey, ftmp); std::string hexString(hexname); std::string skiplistDir; @@ -162,13 +160,14 @@ llarp_nodedb::getRCFilePath(const llarp::RouterID &pubkey) const } void -llarp_nodedb::InsertAsync(llarp::RouterContact rc, - std::shared_ptr< llarp::Logic > logic, - std::function< void(void) > completionHandler) +llarp_nodedb::InsertAsync( + llarp::RouterContact rc, + std::shared_ptr logic, + std::function completionHandler) { disk->addJob([this, rc, logic, completionHandler]() { this->Insert(rc); - if(logic && completionHandler) + if (logic && completionHandler) { LogicCall(logic, completionHandler); } @@ -176,18 +175,19 @@ llarp_nodedb::InsertAsync(llarp::RouterContact rc, } bool -llarp_nodedb::UpdateAsyncIfNewer(llarp::RouterContact rc, - std::shared_ptr< llarp::Logic > logic, - std::function< void(void) > completionHandler) +llarp_nodedb::UpdateAsyncIfNewer( + llarp::RouterContact rc, + std::shared_ptr logic, + std::function completionHandler) { llarp::util::Lock lock(access); auto itr = entries.find(rc.pubkey); - if(itr == entries.end() || itr->second.rc.OtherIsNewer(rc)) + if (itr == entries.end() || itr->second.rc.OtherIsNewer(rc)) { InsertAsync(rc, logic, completionHandler); return true; } - if(itr != entries.end()) + if (itr != entries.end()) { // insertion time is set on...insertion. But it should be updated here // even if there is no insertion of a new RC, to show that the existing one @@ -199,38 +199,41 @@ llarp_nodedb::UpdateAsyncIfNewer(llarp::RouterContact rc, /// insert bool -llarp_nodedb::Insert(const llarp::RouterContact &rc) +llarp_nodedb::Insert(const llarp::RouterContact& rc) { llarp::util::Lock lock(access); auto itr = entries.find(rc.pubkey.as_array()); - if(itr != entries.end()) + if (itr != entries.end()) entries.erase(itr); entries.emplace(rc.pubkey.as_array(), rc); - LogDebug("Added or updated RC for ", llarp::RouterID(rc.pubkey), - " to nodedb. Current nodedb count is: ", entries.size()); + LogDebug( + "Added or updated RC for ", + llarp::RouterID(rc.pubkey), + " to nodedb. Current nodedb count is: ", + entries.size()); return true; } ssize_t -llarp_nodedb::Load(const fs::path &path) +llarp_nodedb::Load(const fs::path& path) { std::error_code ec; - if(!fs::exists(path, ec)) + if (!fs::exists(path, ec)) { return -1; } ssize_t loaded = 0; - for(const char &ch : skiplist_subdirs) + for (const char& ch : skiplist_subdirs) { - if(!ch) + if (!ch) continue; std::string p; p += ch; fs::path sub = path / p; ssize_t l = loadSubdir(sub); - if(l > 0) + if (l > 0) loaded += l; } m_NextSaveToDisk = llarp::time_now_ms() + m_SaveInterval; @@ -240,24 +243,23 @@ llarp_nodedb::Load(const fs::path &path) void llarp_nodedb::SaveAll() { - std::array< byte_t, MAX_RC_SIZE > tmp; + std::array tmp; llarp::util::Lock lock(access); - for(const auto &item : entries) + for (const auto& item : entries) { llarp_buffer_t buf(tmp); - if(!item.second.rc.BEncode(&buf)) + if (!item.second.rc.BEncode(&buf)) continue; - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; const auto filepath = getRCFilePath(item.second.rc.pubkey); - auto optional_ofs = llarp::util::OpenFileStream< std::ofstream >( - filepath, - std::ofstream::out | std::ofstream::binary | std::ofstream::trunc); - if(!optional_ofs) + auto optional_ofs = llarp::util::OpenFileStream( + filepath, std::ofstream::out | std::ofstream::binary | std::ofstream::trunc); + if (!optional_ofs) continue; - auto &ofs = optional_ofs.value(); - ofs.write((char *)buf.base, buf.sz); + auto& ofs = optional_ofs.value(); + ofs.write((char*)buf.base, buf.sz); ofs.flush(); ofs.close(); } @@ -266,7 +268,7 @@ llarp_nodedb::SaveAll() bool llarp_nodedb::ShouldSaveToDisk(llarp_time_t now) const { - if(now == 0s) + if (now == 0s) now = llarp::time_now_ms(); return m_NextSaveToDisk > 0s && m_NextSaveToDisk <= now; } @@ -279,11 +281,11 @@ llarp_nodedb::AsyncFlushToDisk() } ssize_t -llarp_nodedb::loadSubdir(const fs::path &dir) +llarp_nodedb::loadSubdir(const fs::path& dir) { ssize_t sz = 0; - llarp::util::IterDir(dir, [&](const fs::path &f) -> bool { - if(fs::is_regular_file(f) && loadfile(f)) + llarp::util::IterDir(dir, [&](const fs::path& f) -> bool { + if (fs::is_regular_file(f) && loadfile(f)) sz++; return true; }); @@ -291,17 +293,17 @@ llarp_nodedb::loadSubdir(const fs::path &dir) } bool -llarp_nodedb::loadfile(const fs::path &fpath) +llarp_nodedb::loadfile(const fs::path& fpath) { - if(fpath.extension() != RC_FILE_EXT) + if (fpath.extension() != RC_FILE_EXT) return false; llarp::RouterContact rc; - if(!rc.Read(fpath.string().c_str())) + if (!rc.Read(fpath.string().c_str())) { llarp::LogError("failed to read file ", fpath); return false; } - if(!rc.Verify(llarp::time_now_ms())) + if (!rc.Verify(llarp::time_now_ms())) { llarp::LogError(fpath, " contains invalid RC"); return false; @@ -314,13 +316,13 @@ llarp_nodedb::loadfile(const fs::path &fpath) } void -llarp_nodedb::visit(std::function< bool(const llarp::RouterContact &) > visit) +llarp_nodedb::visit(std::function visit) { llarp::util::Lock lock(access); auto itr = entries.begin(); - while(itr != entries.end()) + while (itr != entries.end()) { - if(!visit(itr->second.rc)) + if (!visit(itr->second.rc)) return; ++itr; } @@ -328,35 +330,33 @@ llarp_nodedb::visit(std::function< bool(const llarp::RouterContact &) > visit) void llarp_nodedb::VisitInsertedBefore( - std::function< void(const llarp::RouterContact &) > visit, - llarp_time_t insertedAfter) + std::function visit, llarp_time_t insertedAfter) { llarp::util::Lock lock(access); auto itr = entries.begin(); - while(itr != entries.end()) + while (itr != entries.end()) { - if(itr->second.inserted < insertedAfter) + if (itr->second.inserted < insertedAfter) visit(itr->second.rc); ++itr; } } void -llarp_nodedb::RemoveStaleRCs(const std::set< llarp::RouterID > &keep, - llarp_time_t cutoff) +llarp_nodedb::RemoveStaleRCs(const std::set& keep, llarp_time_t cutoff) { - std::set< llarp::RouterID > removeStale; + std::set removeStale; // remove stale routers VisitInsertedBefore( - [&](const llarp::RouterContact &rc) { - if(keep.find(rc.pubkey) != keep.end()) + [&](const llarp::RouterContact& rc) { + if (keep.find(rc.pubkey) != keep.end()) return; LogInfo("removing stale router: ", llarp::RouterID(rc.pubkey)); removeStale.insert(rc.pubkey); }, cutoff); - RemoveIf([&removeStale](const llarp::RouterContact &rc) -> bool { + RemoveIf([&removeStale](const llarp::RouterContact& rc) -> bool { return removeStale.count(rc.pubkey) > 0; }); } @@ -379,67 +379,64 @@ llarp_nodedb::Save() // call request hook void -logic_threadworker_callback(void *user) +logic_threadworker_callback(void* user) { - auto *verify_request = static_cast< llarp_async_verify_rc * >(user); - if(verify_request->hook) + auto* verify_request = static_cast(user); + if (verify_request->hook) verify_request->hook(verify_request); } // write it to disk void -disk_threadworker_setRC(llarp_async_verify_rc *verify_request) +disk_threadworker_setRC(llarp_async_verify_rc* verify_request) { verify_request->valid = verify_request->nodedb->Insert(verify_request->rc); - if(verify_request->logic) - verify_request->logic->queue_job( - {verify_request, &logic_threadworker_callback}); + if (verify_request->logic) + verify_request->logic->queue_job({verify_request, &logic_threadworker_callback}); } // we run the crypto verify in the crypto threadpool worker void -crypto_threadworker_verifyrc(void *user) +crypto_threadworker_verifyrc(void* user) { - auto *verify_request = static_cast< llarp_async_verify_rc * >(user); + auto* verify_request = static_cast(user); llarp::RouterContact rc = verify_request->rc; - verify_request->valid = rc.Verify(llarp::time_now_ms()); + verify_request->valid = rc.Verify(llarp::time_now_ms()); // if it's valid we need to set it - if(verify_request->valid && rc.IsPublicRouter()) + if (verify_request->valid && rc.IsPublicRouter()) { - if(verify_request->diskworker) + if (verify_request->diskworker) { llarp::LogDebug("RC is valid, saving to disk"); - verify_request->diskworker->addJob( - std::bind(&disk_threadworker_setRC, verify_request)); + verify_request->diskworker->addJob(std::bind(&disk_threadworker_setRC, verify_request)); return; } } // callback to logic thread - verify_request->logic->queue_job( - {verify_request, &logic_threadworker_callback}); + verify_request->logic->queue_job({verify_request, &logic_threadworker_callback}); } void -nodedb_inform_load_rc(void *user) +nodedb_inform_load_rc(void* user) { - auto *job = static_cast< llarp_async_load_rc * >(user); + auto* job = static_cast(user); job->hook(job); } void -llarp_nodedb_async_verify(struct llarp_async_verify_rc *job) +llarp_nodedb_async_verify(struct llarp_async_verify_rc* job) { job->cryptoworker->addJob(std::bind(&crypto_threadworker_verifyrc, job)); } void -nodedb_async_load_rc(void *user) +nodedb_async_load_rc(void* user) { - auto *job = static_cast< llarp_async_load_rc * >(user); + auto* job = static_cast(user); - auto fpath = job->nodedb->getRCFilePath(job->pubkey); + auto fpath = job->nodedb->getRCFilePath(job->pubkey); job->loaded = job->nodedb->loadfile(fpath); - if(job->loaded) + if (job->loaded) { job->nodedb->Get(job->pubkey, job->result); } @@ -447,32 +444,32 @@ nodedb_async_load_rc(void *user) } bool -llarp_nodedb::ensure_dir(const char *dir) +llarp_nodedb::ensure_dir(const char* dir) { fs::path path(dir); std::error_code ec; - if(!fs::exists(dir, ec)) + if (!fs::exists(dir, ec)) fs::create_directory(path, ec); - if(ec) + if (ec) return false; - if(!fs::is_directory(path)) + if (!fs::is_directory(path)) return false; - for(const char &ch : skiplist_subdirs) + for (const char& ch : skiplist_subdirs) { // this seems to be a problem on all targets // perhaps cpp17::fs is just as screwed-up // attempting to create a folder with no name - if(!ch) + if (!ch) return true; std::string p; p += ch; fs::path sub = path / p; fs::create_directory(sub, ec); - if(ec) + if (ec) return false; } return true; @@ -492,19 +489,19 @@ llarp_nodedb::num_loaded() const } bool -llarp_nodedb::select_random_exit(llarp::RouterContact &result) +llarp_nodedb::select_random_exit(llarp::RouterContact& result) { llarp::util::Lock lock(access); const auto sz = entries.size(); - auto itr = entries.begin(); - if(sz < 3) + auto itr = entries.begin(); + if (sz < 3) return false; auto idx = llarp::randint() % sz; - if(idx) + if (idx) std::advance(itr, idx - 1); - while(itr != entries.end()) + while (itr != entries.end()) { - if(itr->second.rc.IsExit()) + if (itr->second.rc.IsExit()) { result = itr->second.rc; return true; @@ -513,9 +510,9 @@ llarp_nodedb::select_random_exit(llarp::RouterContact &result) } // wrap around itr = entries.begin(); - while(idx--) + while (idx--) { - if(itr->second.rc.IsExit()) + if (itr->second.rc.IsExit()) { result = itr->second.rc; return true; @@ -527,30 +524,30 @@ llarp_nodedb::select_random_exit(llarp::RouterContact &result) bool llarp_nodedb::select_random_hop_excluding( - llarp::RouterContact &result, const std::set< llarp::RouterID > &exclude) + llarp::RouterContact& result, const std::set& exclude) { llarp::util::Lock lock(access); /// checking for "guard" status for N = 0 is done by caller inside of /// pathbuilder's scope const size_t sz = entries.size(); - if(sz < 3) + if (sz < 3) { return false; } const size_t pos = llarp::randint() % sz; const auto start = std::next(entries.begin(), pos); - for(auto itr = start; itr != entries.end(); ++itr) + for (auto itr = start; itr != entries.end(); ++itr) { - if(exclude.count(itr->first) == 0 and itr->second.rc.IsPublicRouter()) + if (exclude.count(itr->first) == 0 and itr->second.rc.IsPublicRouter()) { result = itr->second.rc; return true; } } - for(auto itr = entries.begin(); itr != start; ++itr) + for (auto itr = entries.begin(); itr != start; ++itr) { - if(exclude.count(itr->first) == 0 and itr->second.rc.IsPublicRouter()) + if (exclude.count(itr->first) == 0 and itr->second.rc.IsPublicRouter()) { result = itr->second.rc; return true; diff --git a/llarp/nodedb.hpp b/llarp/nodedb.hpp index 90790e460..3f79948f5 100644 --- a/llarp/nodedb.hpp +++ b/llarp/nodedb.hpp @@ -32,8 +32,8 @@ namespace llarp struct llarp_nodedb { - explicit llarp_nodedb(std::shared_ptr< llarp::thread::ThreadPool > diskworker, - const std::string rootdir) + explicit llarp_nodedb( + std::shared_ptr diskworker, const std::string rootdir) : disk(std::move(diskworker)), nodePath(rootdir) { @@ -44,7 +44,7 @@ struct llarp_nodedb Clear(); } - std::shared_ptr< llarp::thread::ThreadPool > disk; + std::shared_ptr disk; mutable llarp::util::Mutex access; // protects entries /// time for next save to disk event, 0 if never happened llarp_time_t m_NextSaveToDisk = 0s; @@ -59,108 +59,106 @@ struct llarp_nodedb NetDBEntry(llarp::RouterContact data); }; - using NetDBMap_t = - std::unordered_map< llarp::RouterID, NetDBEntry, llarp::RouterID::Hash >; + using NetDBMap_t = std::unordered_map; NetDBMap_t entries GUARDED_BY(access); fs::path nodePath; llarp::RouterContact - FindClosestTo(const llarp::dht::Key_t &location); + FindClosestTo(const llarp::dht::Key_t& location); /// find the $numRouters closest routers to the given DHT key - std::vector< llarp::RouterContact > - FindClosestTo(const llarp::dht::Key_t &location, uint32_t numRouters); + std::vector + FindClosestTo(const llarp::dht::Key_t& location, uint32_t numRouters); /// return true if we should save our nodedb to disk bool ShouldSaveToDisk(llarp_time_t now = 0s) const; bool - Remove(const llarp::RouterID &pk) EXCLUDES(access); + Remove(const llarp::RouterID& pk) EXCLUDES(access); void - RemoveIf(std::function< bool(const llarp::RouterContact &) > filter) - EXCLUDES(access); + RemoveIf(std::function filter) EXCLUDES(access); void Clear() EXCLUDES(access); bool - Get(const llarp::RouterID &pk, llarp::RouterContact &result) EXCLUDES(access); + Get(const llarp::RouterID& pk, llarp::RouterContact& result) EXCLUDES(access); bool - Has(const llarp::RouterID &pk) EXCLUDES(access); + Has(const llarp::RouterID& pk) EXCLUDES(access); std::string - getRCFilePath(const llarp::RouterID &pubkey) const; + getRCFilePath(const llarp::RouterID& pubkey) const; /// insert without writing to disk bool - Insert(const llarp::RouterContact &rc) EXCLUDES(access); + Insert(const llarp::RouterContact& rc) EXCLUDES(access); /// invokes Insert() asynchronously with an optional completion /// callback void - InsertAsync(llarp::RouterContact rc, - std::shared_ptr< llarp::Logic > l = nullptr, - std::function< void(void) > completionHandler = nullptr); + InsertAsync( + llarp::RouterContact rc, + std::shared_ptr l = nullptr, + std::function completionHandler = nullptr); /// update rc if newer /// return true if we started to put this rc in the database /// retur false if not newer bool - UpdateAsyncIfNewer(llarp::RouterContact rc, - std::shared_ptr< llarp::Logic > l = nullptr, - std::function< void(void) > completionHandler = nullptr) - EXCLUDES(access); + UpdateAsyncIfNewer( + llarp::RouterContact rc, + std::shared_ptr l = nullptr, + std::function completionHandler = nullptr) EXCLUDES(access); ssize_t - Load(const fs::path &path); + Load(const fs::path& path); ssize_t - loadSubdir(const fs::path &dir); + loadSubdir(const fs::path& dir); /// save all entries to disk async void AsyncFlushToDisk(); bool - loadfile(const fs::path &fpath) EXCLUDES(access); + loadfile(const fs::path& fpath) EXCLUDES(access); void - visit(std::function< bool(const llarp::RouterContact &) > visit) - EXCLUDES(access); + visit(std::function visit) EXCLUDES(access); void - set_dir(const char *dir); + set_dir(const char* dir); ssize_t LoadAll(); ssize_t - store_dir(const char *dir); + store_dir(const char* dir); /// visit all entries inserted into nodedb cache before a timestamp void - VisitInsertedBefore(std::function< void(const llarp::RouterContact &) > visit, - llarp_time_t insertedAfter) EXCLUDES(access); + VisitInsertedBefore( + std::function visit, llarp_time_t insertedAfter) + EXCLUDES(access); void - RemoveStaleRCs(const std::set< llarp::RouterID > &keep, llarp_time_t cutoff); + RemoveStaleRCs(const std::set& keep, llarp_time_t cutoff); size_t num_loaded() const EXCLUDES(access); bool - select_random_exit(llarp::RouterContact &rc) EXCLUDES(access); + select_random_exit(llarp::RouterContact& rc) EXCLUDES(access); bool - select_random_hop_excluding(llarp::RouterContact &result, - const std::set< llarp::RouterID > &exclude) - EXCLUDES(access); + select_random_hop_excluding( + llarp::RouterContact& result, const std::set& exclude) EXCLUDES(access); static bool - ensure_dir(const char *dir); + ensure_dir(const char* dir); void SaveAll() EXCLUDES(access); @@ -169,20 +167,19 @@ struct llarp_nodedb /// struct for async rc verification struct llarp_async_verify_rc; -using llarp_async_verify_rc_hook_func = - std::function< void(struct llarp_async_verify_rc *) >; +using llarp_async_verify_rc_hook_func = std::function; /// verify rc request struct llarp_async_verify_rc { /// async_verify_context - void *user; + void* user; /// nodedb storage - llarp_nodedb *nodedb; + llarp_nodedb* nodedb; // llarp::Logic for queue_job - std::shared_ptr< llarp::Logic > logic; - std::shared_ptr< llarp::thread::ThreadPool > cryptoworker; - std::shared_ptr< llarp::thread::ThreadPool > diskworker; + std::shared_ptr logic; + std::shared_ptr cryptoworker; + std::shared_ptr diskworker; /// router contact llarp::RouterContact rc; @@ -199,23 +196,22 @@ struct llarp_async_verify_rc result is called on the logic thread */ void -llarp_nodedb_async_verify(struct llarp_async_verify_rc *job); +llarp_nodedb_async_verify(struct llarp_async_verify_rc* job); struct llarp_async_load_rc; -using llarp_async_load_rc_hook_func = - std::function< void(struct llarp_async_load_rc *) >; +using llarp_async_load_rc_hook_func = std::function; struct llarp_async_load_rc { /// async_verify_context - void *user; + void* user; /// nodedb storage - llarp_nodedb *nodedb; + llarp_nodedb* nodedb; /// llarp::Logic for calling hook - llarp::Logic *logic; + llarp::Logic* logic; /// disk worker threadpool - llarp::thread::ThreadPool *diskworker; + llarp::thread::ThreadPool* diskworker; /// target pubkey llarp::PubKey pubkey; /// router contact result @@ -228,6 +224,6 @@ struct llarp_async_load_rc /// asynchronously load an rc from disk void -llarp_nodedb_async_load_rc(struct llarp_async_load_rc *job); +llarp_nodedb_async_load_rc(struct llarp_async_load_rc* job); #endif diff --git a/llarp/path/ihophandler.cpp b/llarp/path/ihophandler.cpp index ad4f06230..cfbe359ac 100644 --- a/llarp/path/ihophandler.cpp +++ b/llarp/path/ihophandler.cpp @@ -6,11 +6,10 @@ namespace llarp { // handle data in upstream direction bool - IHopHandler::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter*) + IHopHandler::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) { - if(m_UpstreamQueue == nullptr) - m_UpstreamQueue = std::make_shared< TrafficQueue_t >(); + if (m_UpstreamQueue == nullptr) + m_UpstreamQueue = std::make_shared(); m_UpstreamQueue->emplace_back(); auto& pkt = m_UpstreamQueue->back(); pkt.first.resize(X.sz); @@ -21,11 +20,10 @@ namespace llarp // handle data in downstream direction bool - IHopHandler::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter*) + IHopHandler::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) { - if(m_DownstreamQueue == nullptr) - m_DownstreamQueue = std::make_shared< TrafficQueue_t >(); + if (m_DownstreamQueue == nullptr) + m_DownstreamQueue = std::make_shared(); m_DownstreamQueue->emplace_back(); auto& pkt = m_DownstreamQueue->back(); pkt.first.resize(X.sz); diff --git a/llarp/path/ihophandler.hpp b/llarp/path/ihophandler.hpp index 9e228f050..49ee1ba11 100644 --- a/llarp/path/ihophandler.hpp +++ b/llarp/path/ihophandler.hpp @@ -24,9 +24,9 @@ namespace llarp { struct IHopHandler { - using TrafficEvent_t = std::pair< std::vector< byte_t >, TunnelNonce >; - using TrafficQueue_t = std::vector< TrafficEvent_t >; - using TrafficQueue_ptr = std::shared_ptr< TrafficQueue_t >; + using TrafficEvent_t = std::pair, TunnelNonce>; + using TrafficQueue_t = std::vector; + using TrafficQueue_ptr = std::shared_ptr; virtual ~IHopHandler() = default; @@ -42,20 +42,17 @@ namespace llarp // handle data in upstream direction virtual bool - HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter*); + HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*); // handle data in downstream direction virtual bool - HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter*); + HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*); /// return timestamp last remote activity happened at virtual llarp_time_t LastRemoteActivityAt() const = 0; virtual bool - HandleLRSM(uint64_t status, std::array< EncryptedFrame, 8 >& frames, - AbstractRouter* r) = 0; + HandleLRSM(uint64_t status, std::array& frames, AbstractRouter* r) = 0; uint64_t NextSeqNo() @@ -81,14 +78,12 @@ namespace llarp DownstreamWork(TrafficQueue_ptr queue, AbstractRouter* r) = 0; virtual void - HandleAllUpstream(std::vector< RelayUpstreamMessage > msgs, - AbstractRouter* r) = 0; + HandleAllUpstream(std::vector msgs, AbstractRouter* r) = 0; virtual void - HandleAllDownstream(std::vector< RelayDownstreamMessage > msgs, - AbstractRouter* r) = 0; + HandleAllDownstream(std::vector msgs, AbstractRouter* r) = 0; }; - using HopHandler_ptr = std::shared_ptr< IHopHandler >; + using HopHandler_ptr = std::shared_ptr; } // namespace path } // namespace llarp #endif diff --git a/llarp/path/path.cpp b/llarp/path/path.cpp index 40188c01e..b6daf0572 100644 --- a/llarp/path/path.cpp +++ b/llarp/path/path.cpp @@ -23,55 +23,52 @@ namespace llarp { namespace path { - Path::Path(const std::vector< RouterContact >& h, PathSet* parent, - PathRole startingRoles, std::string shortName) - : m_PathSet(parent) - , _role(startingRoles) - , m_shortName(std::move(shortName)) + Path::Path( + const std::vector& h, + PathSet* parent, + PathRole startingRoles, + std::string shortName) + : m_PathSet(parent), _role(startingRoles), m_shortName(std::move(shortName)) { hops.resize(h.size()); size_t hsz = h.size(); - for(size_t idx = 0; idx < hsz; ++idx) + for (size_t idx = 0; idx < hsz; ++idx) { hops[idx].rc = h[idx]; do { hops[idx].txID.Randomize(); - } while(hops[idx].txID.IsZero()); + } while (hops[idx].txID.IsZero()); do { hops[idx].rxID.Randomize(); - } while(hops[idx].rxID.IsZero()); + } while (hops[idx].rxID.IsZero()); } - for(size_t idx = 0; idx < hsz - 1; ++idx) + for (size_t idx = 0; idx < hsz - 1; ++idx) { hops[idx].txID = hops[idx + 1].rxID; } // initialize parts of the introduction intro.router = hops[hsz - 1].rc.pubkey; intro.pathID = hops[hsz - 1].txID; - if(parent) + if (parent) EnterState(ePathBuilding, parent->Now()); } bool - Path::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter* r) + Path::HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter* r) { - return m_UpstreamReplayFilter.Insert(Y) - and IHopHandler::HandleUpstream(X, Y, r); + return m_UpstreamReplayFilter.Insert(Y) and IHopHandler::HandleUpstream(X, Y, r); } bool - Path::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter* r) + Path::HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter* r) { - return m_DownstreamReplayFilter.Insert(Y) - and IHopHandler::HandleDownstream(X, Y, r); + return m_DownstreamReplayFilter.Insert(Y) and IHopHandler::HandleDownstream(X, Y, r); } void @@ -107,7 +104,7 @@ namespace llarp bool Path::IsReady() const { - if(Expired(llarp::time_now_ms())) + if (Expired(llarp::time_now_ms())) return false; return intro.latency > 0s && _status == ePathEstablished; } @@ -115,8 +112,7 @@ namespace llarp bool Path::IsEndpoint(const RouterID& r, const PathID_t& id) const { - return hops[hops.size() - 1].rc.pubkey == r - && hops[hops.size() - 1].txID == id; + return hops[hops.size() - 1].rc.pubkey == r && hops[hops.size() - 1].txID == id; } RouterID @@ -135,51 +131,47 @@ namespace llarp Path::HopsString() const { std::stringstream ss; - for(const auto& hop : hops) + for (const auto& hop : hops) ss << RouterID(hop.rc.pubkey) << " -> "; return ss.str(); } bool - Path::HandleLRSM(uint64_t status, std::array< EncryptedFrame, 8 >& frames, - AbstractRouter* r) + Path::HandleLRSM(uint64_t status, std::array& frames, AbstractRouter* r) { uint64_t currentStatus = status; size_t index = 0; - nonstd::optional< RouterID > failedAt; - while(index < hops.size()) + nonstd::optional failedAt; + while (index < hops.size()) { - if(!frames[index].DoDecrypt(hops[index].shared)) + if (!frames[index].DoDecrypt(hops[index].shared)) { currentStatus = LR_StatusRecord::FAIL_DECRYPT_ERROR; - failedAt = hops[index].rc.pubkey; + failedAt = hops[index].rc.pubkey; break; } llarp::LogDebug("decrypted LRSM frame from ", hops[index].rc.pubkey); llarp_buffer_t* buf = frames[index].Buffer(); - buf->cur = buf->base + EncryptedFrameOverheadSize; + buf->cur = buf->base + EncryptedFrameOverheadSize; LR_StatusRecord record; // successful decrypt - if(!record.BDecode(buf)) + if (!record.BDecode(buf)) { - llarp::LogWarn("malformed frame inside LRCM from ", - hops[index].rc.pubkey); + llarp::LogWarn("malformed frame inside LRCM from ", hops[index].rc.pubkey); currentStatus = LR_StatusRecord::FAIL_MALFORMED_RECORD; - failedAt = hops[index].rc.pubkey; + failedAt = hops[index].rc.pubkey; break; } - llarp::LogDebug("Decoded LR Status Record from ", - hops[index].rc.pubkey); + llarp::LogDebug("Decoded LR Status Record from ", hops[index].rc.pubkey); currentStatus = record.status; - if((record.status & LR_StatusRecord::SUCCESS) - != LR_StatusRecord::SUCCESS) + if ((record.status & LR_StatusRecord::SUCCESS) != LR_StatusRecord::SUCCESS) { // failed at next hop - if(index + 1 < hops.size()) + if (index + 1 < hops.size()) { failedAt = hops[index + 1].rc.pubkey; } @@ -192,7 +184,7 @@ namespace llarp ++index; } - if((currentStatus & LR_StatusRecord::SUCCESS) == LR_StatusRecord::SUCCESS) + if ((currentStatus & LR_StatusRecord::SUCCESS) == LR_StatusRecord::SUCCESS) { llarp::LogDebug("LR_Status message processed, path build successful"); auto self = shared_from_this(); @@ -200,12 +192,10 @@ namespace llarp } else { - if(failedAt.has_value()) + if (failedAt.has_value()) { - r->NotifyRouterEvent< tooling::PathBuildRejectedEvent >( - Endpoint(), - RXID(), - failedAt.value()); + r->NotifyRouterEvent( + Endpoint(), RXID(), failedAt.value()); LogWarn(Name(), " build failed at ", failedAt.value()); r->routerProfiling().MarkHopFail(failedAt.value()); } @@ -213,39 +203,39 @@ namespace llarp r->routerProfiling().MarkPathFail(this); llarp::LogDebug("LR_Status message processed, path build failed"); - if(currentStatus & LR_StatusRecord::FAIL_TIMEOUT) + if (currentStatus & LR_StatusRecord::FAIL_TIMEOUT) { llarp::LogDebug("Path build failed due to timeout"); } - else if(currentStatus & LR_StatusRecord::FAIL_CONGESTION) + else if (currentStatus & LR_StatusRecord::FAIL_CONGESTION) { llarp::LogDebug("Path build failed due to congestion"); } - else if(currentStatus & LR_StatusRecord::FAIL_DEST_UNKNOWN) + else if (currentStatus & LR_StatusRecord::FAIL_DEST_UNKNOWN) { llarp::LogDebug( "Path build failed due to one or more nodes giving destination " "unknown"); } - else if(currentStatus & LR_StatusRecord::FAIL_DEST_INVALID) + else if (currentStatus & LR_StatusRecord::FAIL_DEST_INVALID) { llarp::LogDebug( "Path build failed due to one or more nodes considered an " "invalid destination"); } - else if(currentStatus & LR_StatusRecord::FAIL_CANNOT_CONNECT) + else if (currentStatus & LR_StatusRecord::FAIL_CANNOT_CONNECT) { llarp::LogDebug( "Path build failed due to a node being unable to connect to the " "next hop"); } - else if(currentStatus & LR_StatusRecord::FAIL_MALFORMED_RECORD) + else if (currentStatus & LR_StatusRecord::FAIL_MALFORMED_RECORD) { llarp::LogDebug( "Path build failed due to a malformed record in the build status " "message"); } - else if(currentStatus & LR_StatusRecord::FAIL_DECRYPT_ERROR) + else if (currentStatus & LR_StatusRecord::FAIL_DECRYPT_ERROR) { llarp::LogDebug( "Path build failed due to a decrypt error in the build status " @@ -256,8 +246,7 @@ namespace llarp llarp::LogDebug("Path build failed for an unspecified reason"); } auto self = shared_from_this(); - LogicCall(r->logic(), - [=]() { self->EnterState(ePathFailed, r->Now()); }); + LogicCall(r->logic(), [=]() { self->EnterState(ePathFailed, r->Now()); }); } // TODO: meaningful return value? @@ -267,33 +256,33 @@ namespace llarp void Path::EnterState(PathStatus st, llarp_time_t now) { - if(st == ePathFailed) + if (st == ePathFailed) { _status = st; m_PathSet->HandlePathBuildFailed(shared_from_this()); return; } - if(st == ePathExpired && _status == ePathBuilding) + if (st == ePathExpired && _status == ePathBuilding) { _status = st; m_PathSet->HandlePathBuildTimeout(shared_from_this()); } - else if(st == ePathBuilding) + else if (st == ePathBuilding) { LogInfo("path ", Name(), " is building"); buildStarted = now; } - else if(st == ePathEstablished && _status == ePathBuilding) + else if (st == ePathEstablished && _status == ePathBuilding) { LogInfo("path ", Name(), " is built, took ", now - buildStarted); } - else if(st == ePathTimeout && _status == ePathEstablished) + else if (st == ePathTimeout && _status == ePathEstablished) { LogInfo("path ", Name(), " died"); _status = st; m_PathSet->HandlePathDied(shared_from_this()); } - else if(st == ePathEstablished && _status == ePathTimeout) + else if (st == ePathEstablished && _status == ePathTimeout) { LogInfo("path ", Name(), " reanimated"); } @@ -315,27 +304,27 @@ namespace llarp { auto now = llarp::time_now_ms(); - util::StatusObject obj{ - {"intro", intro.ExtractStatus()}, - {"lastRecvMsg", to_json(m_LastRecvMessage)}, - {"lastLatencyTest", to_json(m_LastLatencyTestTime)}, - {"buildStarted", to_json(buildStarted)}, - {"expired", Expired(now)}, - {"expiresSoon", ExpiresSoon(now)}, - {"expiresAt", to_json(ExpireTime())}, - {"ready", IsReady()}, - {"txRateCurrent", m_LastTXRate}, - {"rxRateCurrent", m_LastRXRate}, - {"hasExit", SupportsAnyRoles(ePathRoleExit)}}; - - std::vector< util::StatusObject > hopsObj; - std::transform(hops.begin(), hops.end(), std::back_inserter(hopsObj), - [](const auto& hop) -> util::StatusObject { - return hop.ExtractStatus(); - }); + util::StatusObject obj{{"intro", intro.ExtractStatus()}, + {"lastRecvMsg", to_json(m_LastRecvMessage)}, + {"lastLatencyTest", to_json(m_LastLatencyTestTime)}, + {"buildStarted", to_json(buildStarted)}, + {"expired", Expired(now)}, + {"expiresSoon", ExpiresSoon(now)}, + {"expiresAt", to_json(ExpireTime())}, + {"ready", IsReady()}, + {"txRateCurrent", m_LastTXRate}, + {"rxRateCurrent", m_LastRXRate}, + {"hasExit", SupportsAnyRoles(ePathRoleExit)}}; + + std::vector hopsObj; + std::transform( + hops.begin(), + hops.end(), + std::back_inserter(hopsObj), + [](const auto& hop) -> util::StatusObject { return hop.ExtractStatus(); }); obj["hops"] = hopsObj; - switch(_status) + switch (_status) { case ePathBuilding: obj["status"] = "building"; @@ -365,8 +354,8 @@ namespace llarp void Path::Rebuild() { - std::vector< RouterContact > newHops; - for(const auto& hop : hops) + std::vector newHops; + for (const auto& hop : hops) newHops.emplace_back(hop.rc); LogInfo(Name(), " rebuilding on ", ShortName()); m_PathSet->Build(newHops); @@ -375,7 +364,7 @@ namespace llarp void Path::Tick(llarp_time_t now, AbstractRouter* r) { - if(Expired(now)) + if (Expired(now)) return; m_LastRXRate = m_RXRate; @@ -387,14 +376,14 @@ namespace llarp m_UpstreamReplayFilter.Decay(now); m_DownstreamReplayFilter.Decay(now); - if(_status == ePathBuilding) + if (_status == ePathBuilding) { - if(buildStarted == 0s) + if (buildStarted == 0s) return; - if(now >= buildStarted) + if (now >= buildStarted) { const auto dlt = now - buildStarted; - if(dlt >= path::build_timeout) + if (dlt >= path::build_timeout) { LogWarn(Name(), " waited for ", dlt, " and no path was built"); r->routerProfiling().MarkPathFail(this); @@ -404,32 +393,32 @@ namespace llarp } } // check to see if this path is dead - if(_status == ePathEstablished) + if (_status == ePathEstablished) { const auto dlt = now - m_LastLatencyTestTime; - if(dlt > path::latency_interval && m_LastLatencyTestID == 0) + if (dlt > path::latency_interval && m_LastLatencyTestID == 0) { routing::PathLatencyMessage latency; - latency.T = randint(); - m_LastLatencyTestID = latency.T; + latency.T = randint(); + m_LastLatencyTestID = latency.T; m_LastLatencyTestTime = now; SendRoutingMessage(latency, r); FlushUpstream(r); return; } - if(m_LastRecvMessage > 0s && now > m_LastRecvMessage) + if (m_LastRecvMessage > 0s && now > m_LastRecvMessage) { const auto delay = now - m_LastRecvMessage; - if(m_CheckForDead && m_CheckForDead(shared_from_this(), delay)) + if (m_CheckForDead && m_CheckForDead(shared_from_this(), delay)) { LogWarn(Name(), " waited for ", dlt, " and path is unresponsive"); r->routerProfiling().MarkPathFail(this); EnterState(ePathTimeout, now); } } - else if(dlt >= path::alive_timeout && m_LastRecvMessage == 0s) + else if (dlt >= path::alive_timeout && m_LastRecvMessage == 0s) { - if(m_CheckForDead && m_CheckForDead(shared_from_this(), dlt)) + if (m_CheckForDead && m_CheckForDead(shared_from_this(), dlt)) { LogWarn(Name(), " waited for ", dlt, " and path looks dead"); r->routerProfiling().MarkPathFail(this); @@ -440,12 +429,11 @@ namespace llarp } void - Path::HandleAllUpstream(std::vector< RelayUpstreamMessage > msgs, - AbstractRouter* r) + Path::HandleAllUpstream(std::vector msgs, AbstractRouter* r) { - for(const auto& msg : msgs) + for (const auto& msg : msgs) { - if(r->SendToOrQueue(Upstream(), &msg)) + if (r->SendToOrQueue(Upstream(), &msg)) { m_TXRate += msg.X.size(); } @@ -460,36 +448,35 @@ namespace llarp void Path::UpstreamWork(TrafficQueue_ptr msgs, AbstractRouter* r) { - std::vector< RelayUpstreamMessage > sendmsgs(msgs->size()); + std::vector sendmsgs(msgs->size()); size_t idx = 0; - for(auto& ev : *msgs) + for (auto& ev : *msgs) { const llarp_buffer_t buf(ev.first); TunnelNonce n = ev.second; - for(const auto& hop : hops) + for (const auto& hop : hops) { CryptoManager::instance()->xchacha20(buf, hop.shared, n); n ^= hop.nonceXOR; } - auto& msg = sendmsgs[idx]; - msg.X = buf; - msg.Y = ev.second; + auto& msg = sendmsgs[idx]; + msg.X = buf; + msg.Y = ev.second; msg.pathid = TXID(); ++idx; } - LogicCall(r->logic(), - std::bind(&Path::HandleAllUpstream, shared_from_this(), - std::move(sendmsgs), r)); + LogicCall( + r->logic(), + std::bind(&Path::HandleAllUpstream, shared_from_this(), std::move(sendmsgs), r)); } void Path::FlushUpstream(AbstractRouter* r) { - if(m_UpstreamQueue && !m_UpstreamQueue->empty()) + if (m_UpstreamQueue && !m_UpstreamQueue->empty()) { - r->threadpool()->addJob(std::bind(&Path::UpstreamWork, - shared_from_this(), - std::move(m_UpstreamQueue), r)); + r->threadpool()->addJob( + std::bind(&Path::UpstreamWork, shared_from_this(), std::move(m_UpstreamQueue), r)); } m_UpstreamQueue = nullptr; } @@ -497,11 +484,10 @@ namespace llarp void Path::FlushDownstream(AbstractRouter* r) { - if(m_DownstreamQueue && !m_DownstreamQueue->empty()) + if (m_DownstreamQueue && !m_DownstreamQueue->empty()) { - r->threadpool()->addJob(std::bind(&Path::DownstreamWork, - shared_from_this(), - std::move(m_DownstreamQueue), r)); + r->threadpool()->addJob( + std::bind(&Path::DownstreamWork, shared_from_this(), std::move(m_DownstreamQueue), r)); } m_DownstreamQueue = nullptr; } @@ -509,11 +495,11 @@ namespace llarp bool Path::Expired(llarp_time_t now) const { - if(_status == ePathFailed) + if (_status == ePathFailed) return true; - if(_status == ePathBuilding) + if (_status == ePathBuilding) return false; - if(_status == ePathEstablished || _status == ePathTimeout) + if (_status == ePathEstablished || _status == ePathTimeout) { return now >= ExpireTime(); } @@ -525,7 +511,7 @@ namespace llarp { std::stringstream ss; ss << "TX=" << TXID() << " RX=" << RXID(); - if(m_PathSet) + if (m_PathSet) ss << " on " << m_PathSet->Name(); return ss.str(); } @@ -533,35 +519,33 @@ namespace llarp void Path::DownstreamWork(TrafficQueue_ptr msgs, AbstractRouter* r) { - std::vector< RelayDownstreamMessage > sendMsgs(msgs->size()); + std::vector sendMsgs(msgs->size()); size_t idx = 0; - for(auto& ev : *msgs) + for (auto& ev : *msgs) { const llarp_buffer_t buf(ev.first); sendMsgs[idx].Y = ev.second; - for(const auto& hop : hops) + for (const auto& hop : hops) { sendMsgs[idx].Y ^= hop.nonceXOR; - CryptoManager::instance()->xchacha20(buf, hop.shared, - sendMsgs[idx].Y); + CryptoManager::instance()->xchacha20(buf, hop.shared, sendMsgs[idx].Y); } sendMsgs[idx].X = buf; ++idx; } - LogicCall(r->logic(), - std::bind(&Path::HandleAllDownstream, shared_from_this(), - std::move(sendMsgs), r)); + LogicCall( + r->logic(), + std::bind(&Path::HandleAllDownstream, shared_from_this(), std::move(sendMsgs), r)); } void - Path::HandleAllDownstream(std::vector< RelayDownstreamMessage > msgs, - AbstractRouter* r) + Path::HandleAllDownstream(std::vector msgs, AbstractRouter* r) { - for(const auto& msg : msgs) + for (const auto& msg : msgs) { const llarp_buffer_t buf(msg.X); m_RXRate += buf.sz; - if(!HandleRoutingMessage(buf, r)) + if (!HandleRoutingMessage(buf, r)) { LogWarn("failed to handle downstream message"); continue; @@ -574,7 +558,7 @@ namespace llarp bool Path::HandleRoutingMessage(const llarp_buffer_t& buf, AbstractRouter* r) { - if(!r->ParseRoutingMessageBuffer(buf, this, RXID())) + if (!r->ParseRoutingMessageBuffer(buf, this, RXID())) { LogWarn("Failed to parse inbound routing message"); return false; @@ -587,14 +571,14 @@ namespace llarp const routing::UpdateExitVerifyMessage& msg, AbstractRouter* r) { (void)r; - if(m_UpdateExitTX && msg.T == m_UpdateExitTX) + if (m_UpdateExitTX && msg.T == m_UpdateExitTX) { - if(m_ExitUpdated) + if (m_ExitUpdated) return m_ExitUpdated(shared_from_this()); } - if(m_CloseExitTX && msg.T == m_CloseExitTX) + if (m_CloseExitTX && msg.T == m_CloseExitTX) { - if(m_ExitClosed) + if (m_ExitClosed) return m_ExitClosed(shared_from_this()); } return false; @@ -603,13 +587,13 @@ namespace llarp bool Path::SendRoutingMessage(const routing::IMessage& msg, AbstractRouter* r) { - std::array< byte_t, MAX_LINK_MSG_SIZE / 2 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); // should help prevent bad paths with uninitialized members // FIXME: Why would we get uninitialized IMessages? - if(msg.version != LLARP_PROTO_VERSION) + if (msg.version != LLARP_PROTO_VERSION) return false; - if(!msg.BEncode(&buf)) + if (!msg.BEncode(&buf)) { LogError("Bencode failed"); DumpBuffer(buf); @@ -620,7 +604,7 @@ namespace llarp N.Randomize(); buf.sz = buf.cur - buf.base; // pad smaller messages - if(buf.sz < pad_size) + if (buf.sz < pad_size) { // randomize padding CryptoManager::instance()->randbytes(buf.cur, pad_size - buf.sz); @@ -631,20 +615,18 @@ namespace llarp } bool - Path::HandlePathTransferMessage(const routing::PathTransferMessage& /*msg*/, - AbstractRouter* /*r*/) + Path::HandlePathTransferMessage( + const routing::PathTransferMessage& /*msg*/, AbstractRouter* /*r*/) { - LogWarn("unwarranted path transfer message on tx=", TXID(), - " rx=", RXID()); + LogWarn("unwarranted path transfer message on tx=", TXID(), " rx=", RXID()); return false; } bool - Path::HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, - AbstractRouter* r) + Path::HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, AbstractRouter* r) { MarkActive(r->Now()); - if(m_DropHandler) + if (m_DropHandler) return m_DropHandler(shared_from_this(), msg.P, msg.S); return true; } @@ -654,7 +636,7 @@ namespace llarp { LogDebug("Path Build Confirm, path: ", ShortName()); const auto now = llarp::time_now_ms(); - if(_status == ePathBuilding) + if (_status == ePathBuilding) { // finish initializing introduction intro.expiresAt = buildStarted + hops[0].lifetime; @@ -666,22 +648,20 @@ namespace llarp MarkActive(now); // send path latency test routing::PathLatencyMessage latency; - latency.T = randint(); - m_LastLatencyTestID = latency.T; + latency.T = randint(); + m_LastLatencyTestID = latency.T; m_LastLatencyTestTime = now; - if(!SendRoutingMessage(latency, r)) + if (!SendRoutingMessage(latency, r)) return false; FlushUpstream(r); return true; } - LogWarn("got unwarranted path confirm message on tx=", RXID(), - " rx=", RXID()); + LogWarn("got unwarranted path confirm message on tx=", RXID(), " rx=", RXID()); return false; } bool - Path::HandlePathConfirmMessage(const routing::PathConfirmMessage& /*msg*/, - AbstractRouter* r) + Path::HandlePathConfirmMessage(const routing::PathConfirmMessage& /*msg*/, AbstractRouter* r) { return HandlePathConfirmMessage(r); } @@ -694,17 +674,16 @@ namespace llarp } bool - Path::HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, - AbstractRouter* r) + Path::HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, AbstractRouter* r) { const auto now = r->Now(); MarkActive(now); - if(msg.L == m_LastLatencyTestID) + if (msg.L == m_LastLatencyTestID) { - intro.latency = now - m_LastLatencyTestTime; + intro.latency = now - m_LastLatencyTestTime; m_LastLatencyTestID = 0; EnterState(ePathEstablished, now); - if(m_BuiltHook) + if (m_BuiltHook) m_BuiltHook(shared_from_this()); m_BuiltHook = nullptr; LogDebug("path latency is now ", intro.latency, " for ", Name()); @@ -722,21 +701,20 @@ namespace llarp { MarkActive(r->Now()); routing::DHTMessage reply; - if(!msg.HandleMessage(r->dht(), reply.M)) + if (!msg.HandleMessage(r->dht(), reply.M)) return false; - if(reply.M.size()) + if (reply.M.size()) return SendRoutingMessage(reply, r); return true; } bool - Path::HandleCloseExitMessage(const routing::CloseExitMessage& msg, - AbstractRouter* /*r*/) + Path::HandleCloseExitMessage(const routing::CloseExitMessage& msg, AbstractRouter* /*r*/) { /// allows exits to close from their end - if(SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) + if (SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) { - if(msg.Verify(EndpointPubKey())) + if (msg.Verify(EndpointPubKey())) { LogInfo(Name(), " had its exit closed"); _role &= ~ePathRoleExit; @@ -751,8 +729,7 @@ namespace llarp } bool - Path::SendExitRequest(const routing::ObtainExitMessage& msg, - AbstractRouter* r) + Path::SendExitRequest(const routing::ObtainExitMessage& msg, AbstractRouter* r) { LogInfo(Name(), " sending exit request to ", Endpoint()); m_ExitObtainTX = msg.T; @@ -769,8 +746,7 @@ namespace llarp } bool - Path::HandleObtainExitMessage(const routing::ObtainExitMessage& msg, - AbstractRouter* r) + Path::HandleObtainExitMessage(const routing::ObtainExitMessage& msg, AbstractRouter* r) { (void)msg; (void)r; @@ -779,8 +755,7 @@ namespace llarp } bool - Path::HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, - AbstractRouter* r) + Path::HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, AbstractRouter* r) { (void)msg; (void)r; @@ -789,12 +764,11 @@ namespace llarp } bool - Path::HandleRejectExitMessage(const routing::RejectExitMessage& msg, - AbstractRouter* r) + Path::HandleRejectExitMessage(const routing::RejectExitMessage& msg, AbstractRouter* r) { - if(m_ExitObtainTX && msg.T == m_ExitObtainTX) + if (m_ExitObtainTX && msg.T == m_ExitObtainTX) { - if(!msg.Verify(EndpointPubKey())) + if (!msg.Verify(EndpointPubKey())) { LogError(Name(), "RXM invalid signature"); return false; @@ -808,12 +782,11 @@ namespace llarp } bool - Path::HandleGrantExitMessage(const routing::GrantExitMessage& msg, - AbstractRouter* r) + Path::HandleGrantExitMessage(const routing::GrantExitMessage& msg, AbstractRouter* r) { - if(m_ExitObtainTX && msg.T == m_ExitObtainTX) + if (m_ExitObtainTX && msg.T == m_ExitObtainTX) { - if(!msg.Verify(EndpointPubKey())) + if (!msg.Verify(EndpointPubKey())) { LogError(Name(), " GXM signature failed"); return false; @@ -831,9 +804,9 @@ namespace llarp bool Path::InformExitResult(llarp_time_t B) { - auto self = shared_from_this(); + auto self = shared_from_this(); bool result = true; - for(const auto& hook : m_ObtainedExitHooks) + for (const auto& hook : m_ObtainedExitHooks) result &= hook(self, B); m_ObtainedExitHooks.clear(); return result; @@ -844,20 +817,19 @@ namespace llarp const routing::TransferTrafficMessage& msg, AbstractRouter* r) { // check if we can handle exit data - if(!SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) + if (!SupportsAnyRoles(ePathRoleExit | ePathRoleSVC)) return false; // handle traffic if we have a handler - if(!m_ExitTrafficHandler) + if (!m_ExitTrafficHandler) return false; bool sent = msg.X.size() > 0; auto self = shared_from_this(); - for(const auto& pkt : msg.X) + for (const auto& pkt : msg.X) { - if(pkt.size() <= 8) + if (pkt.size() <= 8) return false; uint64_t counter = bufbe64toh(pkt.data()); - if(m_ExitTrafficHandler( - self, llarp_buffer_t(pkt.data() + 8, pkt.size() - 8), counter)) + if (m_ExitTrafficHandler(self, llarp_buffer_t(pkt.data() + 8, pkt.size() - 8), counter)) { MarkActive(r->Now()); EnterState(ePathEstablished, r->Now()); diff --git a/llarp/path/path.hpp b/llarp/path/path.hpp index c59128056..42a61ed49 100644 --- a/llarp/path/path.hpp +++ b/llarp/path/path.hpp @@ -39,7 +39,7 @@ namespace llarp struct TransitHop; struct TransitHopInfo; - using TransitHop_ptr = std::shared_ptr< TransitHop >; + using TransitHop_ptr = std::shared_ptr; /// configuration for a single hop when building a path struct PathHopConfig @@ -75,21 +75,18 @@ namespace llarp /// A path we made struct Path final : public IHopHandler, public routing::IMessageHandler, - public std::enable_shared_from_this< Path > + public std::enable_shared_from_this { - using BuildResultHookFunc = std::function< void(Path_ptr) >; - using CheckForDeadFunc = std::function< bool(Path_ptr, llarp_time_t) >; - using DropHandlerFunc = - std::function< bool(Path_ptr, const PathID_t&, uint64_t) >; - using HopList = std::vector< PathHopConfig >; - using DataHandlerFunc = - std::function< bool(Path_ptr, const service::ProtocolFrame&) >; - using ExitUpdatedFunc = std::function< bool(Path_ptr) >; - using ExitClosedFunc = std::function< bool(Path_ptr) >; - using ExitTrafficHandlerFunc = - std::function< bool(Path_ptr, const llarp_buffer_t&, uint64_t) >; + using BuildResultHookFunc = std::function; + using CheckForDeadFunc = std::function; + using DropHandlerFunc = std::function; + using HopList = std::vector; + using DataHandlerFunc = std::function; + using ExitUpdatedFunc = std::function; + using ExitClosedFunc = std::function; + using ExitTrafficHandlerFunc = std::function; /// (path, backoff) backoff is 0 on success - using ObtainedExitHandler = std::function< bool(Path_ptr, llarp_time_t) >; + using ObtainedExitHandler = std::function; HopList hops; @@ -99,8 +96,11 @@ namespace llarp llarp_time_t buildStarted = 0s; - Path(const std::vector< RouterContact >& routers, PathSet* parent, - PathRole startingRoles, std::string shortName); + Path( + const std::vector& routers, + PathSet* parent, + PathRole startingRoles, + std::string shortName); util::StatusObject ExtractStatus() const; @@ -118,13 +118,13 @@ namespace llarp { const auto& tx = p.hops[0].txID; const auto& rx = p.hops[0].rxID; - const auto& r = p.hops[0].upstream; - const size_t rhash = - std::accumulate(r.begin(), r.end(), 0, std::bit_xor< size_t >()); - return std::accumulate(rx.begin(), rx.begin(), - std::accumulate(tx.begin(), tx.end(), rhash, - std::bit_xor< size_t >()), - std::bit_xor< size_t >()); + const auto& r = p.hops[0].upstream; + const size_t rhash = std::accumulate(r.begin(), r.end(), 0, std::bit_xor()); + return std::accumulate( + rx.begin(), + rx.begin(), + std::accumulate(tx.begin(), tx.end(), rhash, std::bit_xor()), + std::bit_xor()); } }; @@ -134,7 +134,7 @@ namespace llarp size_t operator()(const Path_ptr& p) const { - if(p == nullptr) + if (p == nullptr) return 0; return Hash{}(*p); } @@ -146,7 +146,7 @@ namespace llarp size_t operator()(const Path_ptr& p) const { - if(p == nullptr) + if (p == nullptr) return 0; return RouterID::Hash{}(p->Endpoint()); } @@ -163,8 +163,7 @@ namespace llarp }; /// unordered set of paths with unique endpoints - using UniqueEndpointSet_t = - std::unordered_set< Path_ptr, Endpoint_Hash, Endpoint_Equals >; + using UniqueEndpointSet_t = std::unordered_set; bool operator<(const Path& other) const @@ -218,8 +217,8 @@ namespace llarp } bool - HandleLRSM(uint64_t status, std::array< EncryptedFrame, 8 >& frames, - AbstractRouter* r) override; + HandleLRSM( + uint64_t status, std::array& frames, AbstractRouter* r) override; void SetBuildResultHook(BuildResultHookFunc func); @@ -284,63 +283,52 @@ namespace llarp Rebuild(); bool - HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter*) override; + HandleUpstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) override; bool - HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, - AbstractRouter*) override; + HandleDownstream(const llarp_buffer_t& X, const TunnelNonce& Y, AbstractRouter*) override; void Tick(llarp_time_t now, AbstractRouter* r); bool - SendRoutingMessage(const routing::IMessage& msg, - AbstractRouter* r) override; + SendRoutingMessage(const routing::IMessage& msg, AbstractRouter* r) override; bool - HandleObtainExitMessage(const routing::ObtainExitMessage& msg, - AbstractRouter* r) override; + HandleObtainExitMessage(const routing::ObtainExitMessage& msg, AbstractRouter* r) override; bool - HandleUpdateExitVerifyMessage(const routing::UpdateExitVerifyMessage& msg, - AbstractRouter* r) override; + HandleUpdateExitVerifyMessage( + const routing::UpdateExitVerifyMessage& msg, AbstractRouter* r) override; bool - HandleTransferTrafficMessage(const routing::TransferTrafficMessage& msg, - AbstractRouter* r) override; + HandleTransferTrafficMessage( + const routing::TransferTrafficMessage& msg, AbstractRouter* r) override; bool - HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, - AbstractRouter* r) override; + HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, AbstractRouter* r) override; bool - HandleCloseExitMessage(const routing::CloseExitMessage& msg, - AbstractRouter* r) override; + HandleCloseExitMessage(const routing::CloseExitMessage& msg, AbstractRouter* r) override; bool - HandleGrantExitMessage(const routing::GrantExitMessage& msg, - AbstractRouter* r) override; + HandleGrantExitMessage(const routing::GrantExitMessage& msg, AbstractRouter* r) override; bool - HandleRejectExitMessage(const routing::RejectExitMessage& msg, - AbstractRouter* r) override; + HandleRejectExitMessage(const routing::RejectExitMessage& msg, AbstractRouter* r) override; bool - HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, - AbstractRouter* r) override; + HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, AbstractRouter* r) override; bool HandlePathConfirmMessage(AbstractRouter* r); bool - HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, - AbstractRouter* r) override; + HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, AbstractRouter* r) override; bool - HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, - AbstractRouter* r) override; + HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, AbstractRouter* r) override; bool - HandlePathTransferMessage(const routing::PathTransferMessage& msg, - AbstractRouter* r) override; + HandlePathTransferMessage( + const routing::PathTransferMessage& msg, AbstractRouter* r) override; bool HandleHiddenServiceFrame(const service::ProtocolFrame& frame) override; @@ -406,12 +394,10 @@ namespace llarp DownstreamWork(TrafficQueue_ptr queue, AbstractRouter* r) override; void - HandleAllUpstream(std::vector< RelayUpstreamMessage > msgs, - AbstractRouter* r) override; + HandleAllUpstream(std::vector msgs, AbstractRouter* r) override; void - HandleAllDownstream(std::vector< RelayDownstreamMessage > msgs, - AbstractRouter* r) override; + HandleAllDownstream(std::vector msgs, AbstractRouter* r) override; private: /// call obtained exit hooks @@ -425,21 +411,21 @@ namespace llarp ExitUpdatedFunc m_ExitUpdated; ExitClosedFunc m_ExitClosed; ExitTrafficHandlerFunc m_ExitTrafficHandler; - std::vector< ObtainedExitHandler > m_ObtainedExitHooks; - llarp_time_t m_LastRecvMessage = 0s; + std::vector m_ObtainedExitHooks; + llarp_time_t m_LastRecvMessage = 0s; llarp_time_t m_LastLatencyTestTime = 0s; - uint64_t m_LastLatencyTestID = 0; - uint64_t m_UpdateExitTX = 0; - uint64_t m_CloseExitTX = 0; - uint64_t m_ExitObtainTX = 0; + uint64_t m_LastLatencyTestID = 0; + uint64_t m_UpdateExitTX = 0; + uint64_t m_CloseExitTX = 0; + uint64_t m_ExitObtainTX = 0; PathStatus _status; PathRole _role; - util::DecayingHashSet< TunnelNonce > m_UpstreamReplayFilter; - util::DecayingHashSet< TunnelNonce > m_DownstreamReplayFilter; + util::DecayingHashSet m_UpstreamReplayFilter; + util::DecayingHashSet m_DownstreamReplayFilter; uint64_t m_LastRXRate = 0; - uint64_t m_RXRate = 0; + uint64_t m_RXRate = 0; uint64_t m_LastTXRate = 0; - uint64_t m_TXRate = 0; + uint64_t m_TXRate = 0; const std::string m_shortName; }; diff --git a/llarp/path/path_context.cpp b/llarp/path/path_context.cpp index 9b0785c90..fe1a04766 100644 --- a/llarp/path/path_context.cpp +++ b/llarp/path/path_context.cpp @@ -12,9 +12,7 @@ namespace llarp static constexpr auto DefaultPathBuildLimit = 500ms; PathContext::PathContext(AbstractRouter* router) - : m_Router(router) - , m_AllowTransit(false) - , m_PathLimits(DefaultPathBuildLimit) + : m_Router(router), m_AllowTransit(false), m_PathLimits(DefaultPathBuildLimit) { } @@ -30,7 +28,7 @@ namespace llarp return m_AllowTransit; } - std::shared_ptr< thread::ThreadPool > + std::shared_ptr PathContext::Worker() { return m_Router->threadpool(); @@ -51,7 +49,7 @@ namespace llarp #endif } - std::shared_ptr< Logic > + std::shared_ptr PathContext::logic() { return m_Router->logic(); @@ -66,8 +64,7 @@ namespace llarp bool PathContext::HopIsUs(const RouterID& k) const { - return std::equal(m_Router->pubkey(), m_Router->pubkey() + PUBKEYSIZE, - k.begin()); + return std::equal(m_Router->pubkey(), m_Router->pubkey() + PUBKEYSIZE, k.begin()); } PathContext::EndpointPathPtrSet @@ -75,24 +72,25 @@ namespace llarp { EndpointPathPtrSet found; m_OurPaths.ForEach([&](const Path_ptr& p) { - if(p->Endpoint() == r && p->IsReady()) + if (p->Endpoint() == r && p->IsReady()) found.insert(p); }); return found; } bool - PathContext::ForwardLRCM(const RouterID& nextHop, - const std::array< EncryptedFrame, 8 >& frames, - SendStatusHandler handler) + PathContext::ForwardLRCM( + const RouterID& nextHop, + const std::array& frames, + SendStatusHandler handler) { - if(handler == nullptr) + if (handler == nullptr) { LogError("Calling ForwardLRCM without passing result handler"); return false; } - auto msg = std::make_shared< const LR_CommitMessage >(frames); + auto msg = std::make_shared(frames); LogDebug("forwarding LRCM to ", nextHop); @@ -100,38 +98,40 @@ namespace llarp return true; } - template < typename Lock_t, typename Map_t, typename Key_t, - typename CheckValue_t, typename GetFunc_t > + template < + typename Lock_t, + typename Map_t, + typename Key_t, + typename CheckValue_t, + typename GetFunc_t> HopHandler_ptr MapGet(Map_t& map, const Key_t& k, CheckValue_t check, GetFunc_t get) { Lock_t lock(map.first); auto range = map.second.equal_range(k); - for(auto i = range.first; i != range.second; ++i) + for (auto i = range.first; i != range.second; ++i) { - if(check(i->second)) + if (check(i->second)) return get(i->second); } return nullptr; } - template < typename Lock_t, typename Map_t, typename Key_t, - typename CheckValue_t > + template bool MapHas(Map_t& map, const Key_t& k, CheckValue_t check) { Lock_t lock(map.first); auto range = map.second.equal_range(k); - for(auto i = range.first; i != range.second; ++i) + for (auto i = range.first; i != range.second; ++i) { - if(check(i->second)) + if (check(i->second)) return true; } return false; } - template < typename Lock_t, typename Map_t, typename Key_t, - typename Value_t > + template void MapPut(Map_t& map, const Key_t& k, const Value_t& v) { @@ -139,25 +139,24 @@ namespace llarp map.second.emplace(k, v); } - template < typename Lock_t, typename Map_t, typename Visit_t > + template void MapIter(Map_t& map, Visit_t v) { Lock_t lock(map.first); - for(const auto& item : map.second) + for (const auto& item : map.second) v(item); } - template < typename Lock_t, typename Map_t, typename Key_t, - typename Check_t > + template void MapDel(Map_t& map, const Key_t& k, Check_t check) { Lock_t lock(map.first); auto range = map.second.equal_range(k); - for(auto i = range.first; i != range.second;) + for (auto i = range.first; i != range.second;) { - if(check(i->second)) + if (check(i->second)) i = map.second.erase(i); else ++i; @@ -168,16 +167,15 @@ namespace llarp PathContext::AddOwnPath(PathSet_ptr set, Path_ptr path) { set->AddPath(path); - MapPut< util::Lock >(m_OurPaths, path->TXID(), path); - MapPut< util::Lock >(m_OurPaths, path->RXID(), path); + MapPut(m_OurPaths, path->TXID(), path); + MapPut(m_OurPaths, path->RXID(), path); } bool PathContext::HasTransitHop(const TransitHopInfo& info) { - return MapHas< SyncTransitMap_t::Lock_t >( - m_TransitPaths, info.txID, - [info](const std::shared_ptr< TransitHop >& hop) -> bool { + return MapHas( + m_TransitPaths, info.txID, [info](const std::shared_ptr& hop) -> bool { return info == hop->info; }); } @@ -185,33 +183,32 @@ namespace llarp HopHandler_ptr PathContext::GetByUpstream(const RouterID& remote, const PathID_t& id) { - auto own = MapGet< util::Lock >( - m_OurPaths, id, + auto own = MapGet( + m_OurPaths, + id, [](const Path_ptr) -> bool { // TODO: is this right? return true; }, [](Path_ptr p) -> HopHandler_ptr { return p; }); - if(own) + if (own) return own; - return MapGet< SyncTransitMap_t::Lock_t >( - m_TransitPaths, id, - [remote](const std::shared_ptr< TransitHop >& hop) -> bool { + return MapGet( + m_TransitPaths, + id, + [remote](const std::shared_ptr& hop) -> bool { return hop->info.upstream == remote; }, - [](const std::shared_ptr< TransitHop >& h) -> HopHandler_ptr { - return h; - }); + [](const std::shared_ptr& h) -> HopHandler_ptr { return h; }); } bool - PathContext::TransitHopPreviousIsRouter(const PathID_t& path, - const RouterID& otherRouter) + PathContext::TransitHopPreviousIsRouter(const PathID_t& path, const RouterID& otherRouter) { SyncTransitMap_t::Lock_t lock(m_TransitPaths.first); auto itr = m_TransitPaths.second.find(path); - if(itr == m_TransitPaths.second.end()) + if (itr == m_TransitPaths.second.end()) return false; return itr->second->info.downstream == otherRouter; } @@ -219,14 +216,13 @@ namespace llarp HopHandler_ptr PathContext::GetByDownstream(const RouterID& remote, const PathID_t& id) { - return MapGet< SyncTransitMap_t::Lock_t >( - m_TransitPaths, id, - [remote](const std::shared_ptr< TransitHop >& hop) -> bool { + return MapGet( + m_TransitPaths, + id, + [remote](const std::shared_ptr& hop) -> bool { return hop->info.downstream == remote; }, - [](const std::shared_ptr< TransitHop >& h) -> HopHandler_ptr { - return h; - }); + [](const std::shared_ptr& h) -> HopHandler_ptr { return h; }); } PathSet_ptr @@ -235,7 +231,7 @@ namespace llarp auto& map = m_OurPaths; util::Lock lock(map.first); auto itr = map.second.find(id); - if(itr != map.second.end()) + if (itr != map.second.end()) { return itr->second->m_PathSet->GetSelf(); } @@ -262,9 +258,9 @@ namespace llarp { SyncTransitMap_t::Lock_t lock(map.first); auto range = map.second.equal_range(id); - for(auto i = range.first; i != range.second; ++i) + for (auto i = range.first; i != range.second; ++i) { - if(i->second->info.upstream == us) + if (i->second->info.upstream == us) return i->second; } } @@ -281,8 +277,7 @@ namespace llarp void PathContext::PumpDownstream() { - m_TransitPaths.ForEach( - [&](auto& ptr) { ptr->FlushDownstream(m_Router); }); + m_TransitPaths.ForEach([&](auto& ptr) { ptr->FlushDownstream(m_Router); }); m_OurPaths.ForEach([&](auto& ptr) { ptr->FlushDownstream(m_Router); }); } @@ -295,10 +290,10 @@ namespace llarp } void - PathContext::PutTransitHop(std::shared_ptr< TransitHop > hop) + PathContext::PutTransitHop(std::shared_ptr hop) { - MapPut< SyncTransitMap_t::Lock_t >(m_TransitPaths, hop->info.txID, hop); - MapPut< SyncTransitMap_t::Lock_t >(m_TransitPaths, hop->info.rxID, hop); + MapPut(m_TransitPaths, hop->info.txID, hop); + MapPut(m_TransitPaths, hop->info.rxID, hop); } void @@ -310,10 +305,10 @@ namespace llarp { SyncTransitMap_t::Lock_t lock(m_TransitPaths.first); auto& map = m_TransitPaths.second; - auto itr = map.begin(); - while(itr != map.end()) + auto itr = map.begin(); + while (itr != map.end()) { - if(itr->second->Expired(now)) + if (itr->second->Expired(now)) { m_Router->outboundMessageHandler().QueueRemoveEmptyPath(itr->first); itr = map.erase(itr); @@ -325,10 +320,10 @@ namespace llarp { util::Lock lock(m_OurPaths.first); auto& map = m_OurPaths.second; - auto itr = map.begin(); - while(itr != map.end()) + auto itr = map.begin(); + while (itr != map.end()) { - if(itr->second->Expired(now)) + if (itr->second->Expired(now)) { itr = map.erase(itr); } @@ -342,21 +337,21 @@ namespace llarp PathContext::GetHandler(const PathID_t& id) { routing::MessageHandler_ptr h = nullptr; - auto pathset = GetLocalPathSet(id); - if(pathset) + auto pathset = GetLocalPathSet(id); + if (pathset) { h = pathset->GetPathByID(id); } - if(h) + if (h) return h; const RouterID us(OurRouterID()); auto& map = m_TransitPaths; { SyncTransitMap_t::Lock_t lock(map.first); auto range = map.second.equal_range(id); - for(auto i = range.first; i != range.second; ++i) + for (auto i = range.first; i != range.second; ++i) { - if(i->second->info.upstream == us) + if (i->second->info.upstream == us) return i->second; } } diff --git a/llarp/path/path_context.hpp b/llarp/path/path_context.hpp index 7f6bcb0db..7d7ea86bf 100644 --- a/llarp/path/path_context.hpp +++ b/llarp/path/path_context.hpp @@ -29,7 +29,7 @@ namespace llarp struct TransitHop; struct TransitHopInfo; - using TransitHop_ptr = std::shared_ptr< TransitHop >; + using TransitHop_ptr = std::shared_ptr; struct PathContext { @@ -64,7 +64,7 @@ namespace llarp HandleRelayCommit(const LR_CommitMessage& msg); void - PutTransitHop(std::shared_ptr< TransitHop > hop); + PutTransitHop(std::shared_ptr hop); HopHandler_ptr GetByUpstream(const RouterID& id, const PathID_t& path); @@ -84,15 +84,16 @@ namespace llarp routing::MessageHandler_ptr GetHandler(const PathID_t& id); - using EndpointPathPtrSet = std::set< Path_ptr, ComparePtr< Path_ptr > >; + using EndpointPathPtrSet = std::set>; /// get a set of all paths that we own who's endpoint is r EndpointPathPtrSet FindOwnedPathsWithEndpoint(const RouterID& r); bool - ForwardLRCM(const RouterID& nextHop, - const std::array< EncryptedFrame, 8 >& frames, - SendStatusHandler handler); + ForwardLRCM( + const RouterID& nextHop, + const std::array& frames, + SendStatusHandler handler); bool HopIsUs(const RouterID& k) const; @@ -109,30 +110,27 @@ namespace llarp void RemovePathSet(PathSet_ptr set); - using TransitHopsMap_t = - std::unordered_multimap< PathID_t, TransitHop_ptr, PathID_t::Hash >; + using TransitHopsMap_t = std::unordered_multimap; struct SyncTransitMap_t { using Mutex_t = util::NullMutex; - using Lock_t = util::NullLock; + using Lock_t = util::NullLock; Mutex_t first; // protects second TransitHopsMap_t second GUARDED_BY(first); void - ForEach(std::function< void(const TransitHop_ptr&) > visit) - EXCLUDES(first) + ForEach(std::function visit) EXCLUDES(first) { Lock_t lock(first); - for(const auto& item : second) + for (const auto& item : second) visit(item.second); } }; // maps path id -> pathset owner of path - using OwnedPathsMap_t = - std::unordered_map< PathID_t, Path_ptr, PathID_t::Hash >; + using OwnedPathsMap_t = std::unordered_map; struct SyncOwnedPathsMap_t { @@ -140,18 +138,18 @@ namespace llarp OwnedPathsMap_t second GUARDED_BY(first); void - ForEach(std::function< void(const Path_ptr&) > visit) + ForEach(std::function visit) { util::Lock lock(first); - for(const auto& item : second) + for (const auto& item : second) visit(item.second); } }; - std::shared_ptr< thread::ThreadPool > + std::shared_ptr Worker(); - std::shared_ptr< Logic > + std::shared_ptr logic(); AbstractRouter* @@ -172,7 +170,7 @@ namespace llarp SyncTransitMap_t m_TransitPaths; SyncOwnedPathsMap_t m_OurPaths; bool m_AllowTransit; - util::DecayingHashSet< llarp::Addr > m_PathLimits; + util::DecayingHashSet m_PathLimits; }; } // namespace path } // namespace llarp diff --git a/llarp/path/path_types.hpp b/llarp/path/path_types.hpp index ecf3d4e82..ebddc706d 100644 --- a/llarp/path/path_types.hpp +++ b/llarp/path/path_types.hpp @@ -6,9 +6,9 @@ namespace llarp { - struct PathID_t final : public AlignedBuffer< PATHIDSIZE > + struct PathID_t final : public AlignedBuffer { - using Hash = AlignedBuffer< PATHIDSIZE >::Hash; + using Hash = AlignedBuffer::Hash; }; } // namespace llarp diff --git a/llarp/path/pathbuilder.cpp b/llarp/path/pathbuilder.cpp index 04e25f22a..6643411f3 100644 --- a/llarp/path/pathbuilder.cpp +++ b/llarp/path/pathbuilder.cpp @@ -14,28 +14,26 @@ namespace llarp { - struct AsyncPathKeyExchangeContext - : std::enable_shared_from_this< AsyncPathKeyExchangeContext > + struct AsyncPathKeyExchangeContext : std::enable_shared_from_this { - using Path_t = path::Path_ptr; - using PathSet_t = path::PathSet_ptr; + using Path_t = path::Path_ptr; + using PathSet_t = path::PathSet_ptr; PathSet_t pathset = nullptr; - Path_t path = nullptr; - using Handler = - std::function< void(std::shared_ptr< AsyncPathKeyExchangeContext >) >; + Path_t path = nullptr; + using Handler = std::function)>; Handler result; - size_t idx = 0; + size_t idx = 0; AbstractRouter* router = nullptr; - std::shared_ptr< thread::ThreadPool > worker; - std::shared_ptr< Logic > logic; + std::shared_ptr worker; + std::shared_ptr logic; LR_CommitMessage LRCM; void GenerateNextKey() { // current hop - auto& hop = path->hops[idx]; + auto& hop = path->hops[idx]; auto& frame = LRCM.frames[idx]; auto crypto = CryptoManager::instance(); @@ -44,10 +42,9 @@ namespace llarp crypto->encryption_keygen(hop.commkey); hop.nonce.Randomize(); // do key exchange - if(!crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, hop.nonce)) + if (!crypto->dh_client(hop.shared, hop.rc.enckey, hop.commkey, hop.nonce)) { - LogError(pathset->Name(), - " Failed to generate shared key for path build"); + LogError(pathset->Name(), " Failed to generate shared key for path build"); return; } // generate nonceXOR valueself->hop->pathKey @@ -57,28 +54,28 @@ namespace llarp bool isFarthestHop = idx == path->hops.size(); LR_CommitRecord record; - if(isFarthestHop) + if (isFarthestHop) { hop.upstream = hop.rc.pubkey; } else { - hop.upstream = path->hops[idx].rc.pubkey; - record.nextRC = std::make_unique< RouterContact >(path->hops[idx].rc); + hop.upstream = path->hops[idx].rc.pubkey; + record.nextRC = std::make_unique(path->hops[idx].rc); } // build record - record.lifetime = path::default_lifetime; - record.version = LLARP_PROTO_VERSION; - record.txid = hop.txID; - record.rxid = hop.rxID; + record.lifetime = path::default_lifetime; + record.version = LLARP_PROTO_VERSION; + record.txid = hop.txID; + record.rxid = hop.rxID; record.tunnelNonce = hop.nonce; - record.nextHop = hop.upstream; - record.commkey = seckey_topublic(hop.commkey); + record.nextHop = hop.upstream; + record.commkey = seckey_topublic(hop.commkey); llarp_buffer_t buf(frame.data(), frame.size()); buf.cur = buf.base + EncryptedFrameOverheadSize; // encode record - if(!record.BEncode(&buf)) + if (!record.BEncode(&buf)) { // failed to encode? LogError(pathset->Name(), " Failed to generate Commit Record"); @@ -88,13 +85,13 @@ namespace llarp // use ephemeral keypair for frame SecretKey framekey; crypto->encryption_keygen(framekey); - if(!frame.EncryptInPlace(framekey, hop.rc.enckey)) + if (!frame.EncryptInPlace(framekey, hop.rc.enckey)) { LogError(pathset->Name(), " Failed to encrypt LRCR"); return; } - if(isFarthestHop) + if (isFarthestHop) { // farthest hop // TODO: encrypt junk frames because our public keys are not eligator @@ -103,55 +100,51 @@ namespace llarp else { // next hop - worker->addJob(std::bind(&AsyncPathKeyExchangeContext::GenerateNextKey, - shared_from_this())); + worker->addJob( + std::bind(&AsyncPathKeyExchangeContext::GenerateNextKey, shared_from_this())); } } /// Generate all keys asynchronously and call handler when done void - AsyncGenerateKeys(Path_t p, std::shared_ptr< Logic > l, - std::shared_ptr< thread::ThreadPool > pool, Handler func) + AsyncGenerateKeys( + Path_t p, std::shared_ptr l, std::shared_ptr pool, Handler func) { - path = p; - logic = l; + path = p; + logic = l; result = func; worker = pool; - for(size_t i = 0; i < path::max_len; ++i) + for (size_t i = 0; i < path::max_len; ++i) { LRCM.frames[i].Randomize(); } - pool->addJob(std::bind(&AsyncPathKeyExchangeContext::GenerateNextKey, - shared_from_this())); + pool->addJob(std::bind(&AsyncPathKeyExchangeContext::GenerateNextKey, shared_from_this())); } }; static void - PathBuilderKeysGenerated(std::shared_ptr< AsyncPathKeyExchangeContext > ctx) + PathBuilderKeysGenerated(std::shared_ptr ctx) { - if(!ctx->pathset->IsStopped()) + if (!ctx->pathset->IsStopped()) { - ctx->router->NotifyRouterEvent< tooling::PathAttemptEvent >( - ctx->router->pubkey(), - ctx->path); + ctx->router->NotifyRouterEvent(ctx->router->pubkey(), ctx->path); - const RouterID remote = ctx->path->Upstream(); + const RouterID remote = ctx->path->Upstream(); const ILinkMessage* msg = &ctx->LRCM; - auto sentHandler = [ctx](auto status) { - if(status == SendStatus::Success) + auto sentHandler = [ctx](auto status) { + if (status == SendStatus::Success) { ctx->router->pathContext().AddOwnPath(ctx->pathset, ctx->path); ctx->pathset->PathBuildStarted(ctx->path); } else { - LogError(ctx->pathset->Name(), " failed to send LRCM to ", - ctx->path->Upstream()); + LogError(ctx->pathset->Name(), " failed to send LRCM to ", ctx->path->Upstream()); ctx->pathset->HandlePathBuildFailed(ctx->path); } }; - if(ctx->router->SendToOrQueue(remote, msg, sentHandler)) + if (ctx->router->SendToOrQueue(remote, msg, sentHandler)) { // persist session with router until this path is done ctx->router->PersistSessionUntil(remote, ctx->path->ExpireTime()); @@ -173,20 +166,19 @@ namespace llarp Builder::ResetInternalState() { buildIntervalLimit = MIN_PATH_BUILD_INTERVAL; - lastBuild = 0s; + lastBuild = 0s; } void Builder::Tick(llarp_time_t) { const auto now = llarp::time_now_ms(); ExpirePaths(now, m_router); - if(ShouldBuildMore(now)) + if (ShouldBuildMore(now)) BuildOne(); TickPaths(m_router); - if(m_BuildStats.attempts > 50) + if (m_BuildStats.attempts > 50) { - if(m_BuildStats.SuccessRatio() <= BuildStats::MinGoodRatio - && now - m_LastWarn > 5s) + if (m_BuildStats.SuccessRatio() <= BuildStats::MinGoodRatio && now - m_LastWarn > 5s) { LogWarn(Name(), " has a low path build success. ", m_BuildStats); m_LastWarn = now; @@ -200,23 +192,27 @@ namespace llarp util::StatusObject obj{{"buildStats", m_BuildStats.ExtractStatus()}, {"numHops", uint64_t(numHops)}, {"numPaths", uint64_t(numPaths)}}; - std::transform(m_Paths.begin(), m_Paths.end(), - std::back_inserter(obj["paths"]), - [](const auto& item) -> util::StatusObject { - return item.second->ExtractStatus(); - }); + std::transform( + m_Paths.begin(), + m_Paths.end(), + std::back_inserter(obj["paths"]), + [](const auto& item) -> util::StatusObject { return item.second->ExtractStatus(); }); return obj; } bool - Builder::SelectHop(llarp_nodedb* db, const std::set< RouterID >& exclude, - RouterContact& cur, size_t hop, PathRole roles) + Builder::SelectHop( + llarp_nodedb* db, + const std::set& exclude, + RouterContact& cur, + size_t hop, + PathRole roles) { (void)roles; size_t tries = 10; - if(hop == 0) + if (hop == 0) { - if(m_router->NumberOfConnectedRouters() == 0) + if (m_router->NumberOfConnectedRouters() == 0) { // persist connection m_router->ConnectToRandomRouters(1); @@ -225,14 +221,13 @@ namespace llarp bool got = false; m_router->ForEachPeer( [&](const ILinkSession* s, bool isOutbound) { - if(s && s->IsEstablished() && isOutbound && !got) + if (s && s->IsEstablished() && isOutbound && !got) { const RouterContact rc = s->GetRemoteRC(); #ifdef TESTNET - if(got || exclude.count(rc.pubkey)) + if (got || exclude.count(rc.pubkey)) #else - if(got || exclude.count(rc.pubkey) - || m_router->IsBootstrapNode(rc.pubkey)) + if (got || exclude.count(rc.pubkey) || m_router->IsBootstrapNode(rc.pubkey)) #endif return; cur = rc; @@ -247,14 +242,14 @@ namespace llarp { cur.Clear(); --tries; - std::set< RouterID > excluding = exclude; - if(db->select_random_hop_excluding(cur, excluding)) + std::set excluding = exclude; + if (db->select_random_hop_excluding(cur, excluding)) { excluding.insert(cur.pubkey); - if(!m_router->routerProfiling().IsBadForPath(cur.pubkey)) + if (!m_router->routerProfiling().IsBadForPath(cur.pubkey)) return true; } - } while(tries > 0); + } while (tries > 0); return false; } @@ -293,9 +288,9 @@ namespace llarp bool Builder::ShouldBuildMore(llarp_time_t now) const { - if(IsStopped()) + if (IsStopped()) return false; - if(BuildCooldownHit(now)) + if (BuildCooldownHit(now)) return false; return PathSet::ShouldBuildMore(now); } @@ -303,8 +298,8 @@ namespace llarp void Builder::BuildOne(PathRole roles) { - std::vector< RouterContact > hops(numHops); - if(SelectHops(m_router->nodedb(), hops, roles)) + std::vector hops(numHops); + if (SelectHops(m_router->nodedb(), hops, roles)) Build(hops, roles); } @@ -314,28 +309,26 @@ namespace llarp } bool - Builder::DoUrgentBuildAlignedTo(const RouterID remote, - std::vector< RouterContact >& hops) + Builder::DoUrgentBuildAlignedTo(const RouterID remote, std::vector& hops) { - const auto aligned = - m_router->pathContext().FindOwnedPathsWithEndpoint(remote); + const auto aligned = m_router->pathContext().FindOwnedPathsWithEndpoint(remote); /// pick the lowest latency path that aligns to remote /// note: peer exhaustion is made worse happen here Path_ptr p; - llarp_time_t min = std::numeric_limits< llarp_time_t >::max(); - for(const auto& path : aligned) + llarp_time_t min = std::numeric_limits::max(); + for (const auto& path : aligned) { - if(path->intro.latency < min && path->hops.size() == numHops) + if (path->intro.latency < min && path->hops.size() == numHops) { - p = path; + p = path; min = path->intro.latency; } } - if(p) + if (p) { - for(const auto& hop : p->hops) + for (const auto& hop : p->hops) { - if(hop.rc.pubkey.IsZero()) + if (hop.rc.pubkey.IsZero()) return false; hops.emplace_back(hop.rc); } @@ -345,20 +338,19 @@ namespace llarp } bool - Builder::DoBuildAlignedTo(const RouterID remote, - std::vector< RouterContact >& hops) + Builder::DoBuildAlignedTo(const RouterID remote, std::vector& hops) { - std::set< RouterID > routers{remote}; + std::set routers{remote}; hops.resize(numHops); auto nodedb = m_router->nodedb(); - for(size_t idx = 0; idx < hops.size(); idx++) + for (size_t idx = 0; idx < hops.size(); idx++) { hops[idx].Clear(); - if(idx == numHops - 1) + if (idx == numHops - 1) { // last hop - if(!nodedb->Get(remote, hops[idx])) + if (!nodedb->Get(remote, hops[idx])) { m_router->LookupRouter(remote, nullptr); return false; @@ -366,12 +358,12 @@ namespace llarp } else { - if(!SelectHop(nodedb, routers, hops[idx], idx, path::ePathRoleAny)) + if (!SelectHop(nodedb, routers, hops[idx], idx, path::ePathRoleAny)) { return false; } } - if(hops[idx].pubkey.IsZero()) + if (hops[idx].pubkey.IsZero()) return false; routers.insert(hops[idx].pubkey); } @@ -382,19 +374,19 @@ namespace llarp bool Builder::BuildOneAlignedTo(const RouterID remote) { - std::vector< RouterContact > hops; + std::vector hops; /// if we really need this path build it "dangerously" - if(UrgentBuild(m_router->Now())) + if (UrgentBuild(m_router->Now())) { - if(!DoUrgentBuildAlignedTo(remote, hops)) + if (!DoUrgentBuildAlignedTo(remote, hops)) { return false; } } - if(hops.empty()) + if (hops.empty()) { - if(!DoBuildAlignedTo(remote, hops)) + if (!DoBuildAlignedTo(remote, hops)) { return false; } @@ -405,19 +397,18 @@ namespace llarp } bool - Builder::SelectHops(llarp_nodedb* nodedb, - std::vector< RouterContact >& hops, PathRole roles) + Builder::SelectHops(llarp_nodedb* nodedb, std::vector& hops, PathRole roles) { - std::set< RouterID > exclude; - for(size_t idx = 0; idx < hops.size(); ++idx) + std::set exclude; + for (size_t idx = 0; idx < hops.size(); ++idx) { hops[idx].Clear(); size_t tries = 32; - while(tries > 0 && !SelectHop(nodedb, exclude, hops[idx], idx, roles)) + while (tries > 0 && !SelectHop(nodedb, exclude, hops[idx], idx, roles)) { --tries; } - if(tries == 0 || hops[idx].pubkey.IsZero()) + if (tries == 0 || hops[idx].pubkey.IsZero()) { LogWarn(Name(), " failed to select hop ", idx); return false; @@ -434,27 +425,24 @@ namespace llarp } void - Builder::Build(const std::vector< RouterContact >& hops, PathRole roles) + Builder::Build(const std::vector& hops, PathRole roles) { - if(IsStopped()) + if (IsStopped()) return; lastBuild = Now(); // async generate keys - auto ctx = std::make_shared< AsyncPathKeyExchangeContext >(); - ctx->router = m_router; - auto self = GetSelf(); + auto ctx = std::make_shared(); + ctx->router = m_router; + auto self = GetSelf(); ctx->pathset = self; std::string path_shortName = "[path " + m_router->ShortName() + "-"; - path_shortName = path_shortName - + std::to_string(m_router->NextPathBuildNumber()) + "]"; - auto path = std::make_shared< path::Path >(hops, self.get(), roles, - std::move(path_shortName)); + path_shortName = path_shortName + std::to_string(m_router->NextPathBuildNumber()) + "]"; + auto path = std::make_shared(hops, self.get(), roles, std::move(path_shortName)); LogInfo(Name(), " build ", path->ShortName(), ": ", path->HopsString()); - path->SetBuildResultHook( - [self](Path_ptr p) { self->HandlePathBuilt(p); }); - ctx->AsyncGenerateKeys(path, m_router->logic(), m_router->threadpool(), - &PathBuilderKeysGenerated); + path->SetBuildResultHook([self](Path_ptr p) { self->HandlePathBuilt(p); }); + ctx->AsyncGenerateKeys( + path, m_router->logic(), m_router->threadpool(), &PathBuilderKeysGenerated); } void @@ -480,8 +468,7 @@ namespace llarp { static constexpr std::chrono::milliseconds MaxBuildInterval = 30s; // linear backoff - buildIntervalLimit = std::min( - MIN_PATH_BUILD_INTERVAL + buildIntervalLimit, MaxBuildInterval); + buildIntervalLimit = std::min(MIN_PATH_BUILD_INTERVAL + buildIntervalLimit, MaxBuildInterval); LogWarn(Name(), " build interval is now ", buildIntervalLimit); } @@ -497,7 +484,7 @@ namespace llarp Builder::ManualRebuild(size_t num, PathRole roles) { LogDebug(Name(), " manual rebuild ", num); - while(num--) + while (num--) BuildOne(roles); } diff --git a/llarp/path/pathbuilder.hpp b/llarp/path/pathbuilder.hpp index 614756fd1..7deb4ee61 100644 --- a/llarp/path/pathbuilder.hpp +++ b/llarp/path/pathbuilder.hpp @@ -21,7 +21,7 @@ namespace llarp protected: /// flag for PathSet::Stop() - std::atomic< bool > _run; + std::atomic _run; virtual bool UrgentBuild(llarp_time_t now) const; @@ -31,18 +31,16 @@ namespace llarp DoPathBuildBackoff(); bool - DoUrgentBuildAlignedTo(const RouterID remote, - std::vector< RouterContact >& hops); + DoUrgentBuildAlignedTo(const RouterID remote, std::vector& hops); bool - DoBuildAlignedTo(const RouterID remote, - std::vector< RouterContact >& hops); + DoBuildAlignedTo(const RouterID remote, std::vector& hops); public: AbstractRouter* m_router; SecretKey enckey; size_t numHops; - llarp_time_t lastBuild = 0s; + llarp_time_t lastBuild = 0s; llarp_time_t buildIntervalLimit = MIN_PATH_BUILD_INTERVAL; /// construct @@ -54,8 +52,12 @@ namespace llarp ExtractStatus() const; bool - SelectHop(llarp_nodedb* db, const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, PathRole roles) override; + SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + PathRole roles) override; bool ShouldBuildMore(llarp_time_t now) const override; @@ -106,12 +108,10 @@ namespace llarp BuildOneAlignedTo(const RouterID endpoint) override; void - Build(const std::vector< RouterContact >& hops, - PathRole roles = ePathRoleAny) override; + Build(const std::vector& hops, PathRole roles = ePathRoleAny) override; bool - SelectHops(llarp_nodedb* db, std::vector< RouterContact >& hops, - PathRole roles = ePathRoleAny); + SelectHops(llarp_nodedb* db, std::vector& hops, PathRole roles = ePathRoleAny); void ManualRebuild(size_t N, PathRole roles = ePathRoleAny); @@ -129,7 +129,7 @@ namespace llarp HandlePathBuildFailed(Path_ptr p) override; }; - using Builder_ptr = std::shared_ptr< Builder >; + using Builder_ptr = std::shared_ptr; } // namespace path diff --git a/llarp/path/pathset.cpp b/llarp/path/pathset.cpp index 81d0c4534..0614e6cef 100644 --- a/llarp/path/pathset.cpp +++ b/llarp/path/pathset.cpp @@ -18,7 +18,7 @@ namespace llarp { (void)now; const auto building = NumInStatus(ePathBuilding); - if(building >= numPaths) + if (building >= numPaths) return false; const auto established = NumInStatus(ePathEstablished); return established < numPaths; @@ -29,12 +29,12 @@ namespace llarp { Lock_t l(m_PathsMutex); const size_t required = MinRequiredForRoles(roles); - size_t has = 0; - for(const auto& item : m_Paths) + size_t has = 0; + for (const auto& item : m_Paths) { - if(item.second->SupportsAnyRoles(roles)) + if (item.second->SupportsAnyRoles(roles)) { - if(!item.second->ExpiresSoon(now)) + if (!item.second->ExpiresSoon(now)) ++has; } } @@ -53,9 +53,9 @@ namespace llarp { size_t num = 0; Lock_t l(m_PathsMutex); - for(const auto& item : m_Paths) + for (const auto& item : m_Paths) { - if(item.second->IsReady() && !item.second->Expired(futureTime)) + if (item.second->IsReady() && !item.second->Expired(futureTime)) ++num; } return num; @@ -66,7 +66,7 @@ namespace llarp { const auto now = llarp::time_now_ms(); Lock_t l(m_PathsMutex); - for(auto& item : m_Paths) + for (auto& item : m_Paths) { item.second->Tick(now, r); } @@ -76,15 +76,14 @@ namespace llarp PathSet::ExpirePaths(llarp_time_t now, AbstractRouter* router) { Lock_t l(m_PathsMutex); - if(m_Paths.size() == 0) + if (m_Paths.size() == 0) return; auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { - if(itr->second->Expired(now)) + if (itr->second->Expired(now)) { - router->outboundMessageHandler().QueueRemoveEmptyPath( - itr->second->TXID()); + router->outboundMessageHandler().QueueRemoveEmptyPath(itr->second->TXID()); itr = m_Paths.erase(itr); } else @@ -97,17 +96,17 @@ namespace llarp { Lock_t l(m_PathsMutex); Path_ptr path = nullptr; - AlignedBuffer< 32 > dist; - AlignedBuffer< 32 > to = id; + AlignedBuffer<32> dist; + AlignedBuffer<32> to = id; dist.Fill(0xff); - for(const auto& item : m_Paths) + for (const auto& item : m_Paths) { - if(!item.second->IsReady()) + if (!item.second->IsReady()) continue; - if(!item.second->SupportsAnyRoles(roles)) + if (!item.second->SupportsAnyRoles(roles)) continue; - AlignedBuffer< 32 > localDist = item.second->Endpoint() ^ to; - if(localDist < dist) + AlignedBuffer<32> localDist = item.second->Endpoint() ^ to; + if (localDist < dist) { dist = localDist; path = item.second; @@ -121,16 +120,16 @@ namespace llarp { Lock_t l(m_PathsMutex); Path_ptr chosen = nullptr; - auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + auto itr = m_Paths.begin(); + while (itr != m_Paths.end()) { - if(itr->second->IsReady() && itr->second->SupportsAnyRoles(roles)) + if (itr->second->IsReady() && itr->second->SupportsAnyRoles(roles)) { - if(itr->second->Endpoint() == id) + if (itr->second->Endpoint() == id) { - if(chosen == nullptr) + if (chosen == nullptr) chosen = itr->second; - else if(chosen->intro.expiresAt < itr->second->intro.expiresAt) + else if (chosen->intro.expiresAt < itr->second->intro.expiresAt) chosen = itr->second; } } @@ -144,16 +143,16 @@ namespace llarp { Lock_t l(m_PathsMutex); Path_ptr chosen = nullptr; - auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + auto itr = m_Paths.begin(); + while (itr != m_Paths.end()) { - if(itr->second->IsReady() && itr->second->SupportsAnyRoles(roles)) + if (itr->second->IsReady() && itr->second->SupportsAnyRoles(roles)) { - if(itr->second->Endpoint() == id) + if (itr->second->Endpoint() == id) { - if(chosen == nullptr) + if (chosen == nullptr) chosen = itr->second; - else if(chosen->intro.latency > itr->second->intro.latency) + else if (chosen->intro.latency > itr->second->intro.latency) chosen = itr->second; } } @@ -167,9 +166,9 @@ namespace llarp { Lock_t l(m_PathsMutex); auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { - if(itr->second->IsEndpoint(ep, id)) + if (itr->second->IsEndpoint(ep, id)) { return itr->second; } @@ -183,9 +182,9 @@ namespace llarp { Lock_t l(m_PathsMutex); auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { - if(itr->second->RXID() == id) + if (itr->second->RXID() == id) return itr->second; ++itr; } @@ -197,11 +196,10 @@ namespace llarp { Lock_t l(m_PathsMutex); size_t count = 0; - auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + auto itr = m_Paths.begin(); + while (itr != m_Paths.end()) { - if(itr->second->Status() == ePathEstablished - && itr->second->SupportsAnyRoles(roles)) + if (itr->second->Status() == ePathEstablished && itr->second->SupportsAnyRoles(roles)) ++count; ++itr; } @@ -213,10 +211,10 @@ namespace llarp { Lock_t l(m_PathsMutex); size_t count = 0; - auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + auto itr = m_Paths.begin(); + while (itr != m_Paths.end()) { - if(itr->second->Status() == st) + if (itr->second->Status() == st) ++count; ++itr; } @@ -228,12 +226,15 @@ namespace llarp { Lock_t l(m_PathsMutex); const auto upstream = path->Upstream(); // RouterID - const auto RXID = path->RXID(); // PathID - if(not m_Paths.emplace(std::make_pair(upstream, RXID), path).second) + const auto RXID = path->RXID(); // PathID + if (not m_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); } } @@ -249,23 +250,23 @@ namespace llarp { Lock_t l(m_PathsMutex); auto itr = m_Paths.find({remote, rxid}); - if(itr == m_Paths.end()) + if (itr == m_Paths.end()) return nullptr; return itr->second; } bool PathSet::GetCurrentIntroductionsWithFilter( - std::set< service::Introduction >& intros, - std::function< bool(const service::Introduction&) > filter) const + std::set& intros, + std::function filter) const { intros.clear(); size_t count = 0; Lock_t l(m_PathsMutex); auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { - if(itr->second->IsReady() && filter(itr->second->intro)) + if (itr->second->IsReady() && filter(itr->second->intro)) { intros.insert(itr->second->intro); ++count; @@ -276,16 +277,15 @@ namespace llarp } bool - PathSet::GetCurrentIntroductions( - std::set< service::Introduction >& intros) const + PathSet::GetCurrentIntroductions(std::set& intros) const { intros.clear(); size_t count = 0; Lock_t l(m_PathsMutex); auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { - if(itr->second->IsReady()) + if (itr->second->IsReady()) { intros.insert(itr->second->intro); ++count; @@ -319,10 +319,8 @@ namespace llarp util::StatusObject BuildStats::ExtractStatus() const { - return util::StatusObject{{"success", success}, - {"attempts", attempts}, - {"timeouts", timeouts}, - {"fails", fails}}; + return util::StatusObject{ + {"success", success}, {"attempts", attempts}, {"timeouts", timeouts}, {"fails", fails}}; } std::string @@ -340,7 +338,7 @@ namespace llarp double BuildStats::SuccessRatio() const { - if(attempts) + if (attempts) return double(success) / double(attempts); return 0.0; } @@ -352,10 +350,9 @@ namespace llarp bool found = false; Lock_t l(m_PathsMutex); auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { - if(itr->second->IsReady() - && itr->second->intro.expiresAt > intro.expiresAt) + if (itr->second->IsReady() && itr->second->intro.expiresAt > intro.expiresAt) { intro = itr->second->intro; found = true; @@ -368,17 +365,17 @@ namespace llarp Path_ptr PathSet::PickRandomEstablishedPath(PathRole roles) const { - std::vector< Path_ptr > established; + std::vector established; Lock_t l(m_PathsMutex); auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { - if(itr->second->IsReady() && itr->second->SupportsAnyRoles(roles)) + if (itr->second->IsReady() && itr->second->SupportsAnyRoles(roles)) established.push_back(itr->second); ++itr; } auto sz = established.size(); - if(sz) + if (sz) { return established[randint() % sz]; } diff --git a/llarp/path/pathset.hpp b/llarp/path/pathset.hpp index cad5d504d..13a07f432 100644 --- a/llarp/path/pathset.hpp +++ b/llarp/path/pathset.hpp @@ -45,8 +45,8 @@ namespace llarp static constexpr double MinGoodRatio = 0.25; uint64_t attempts = 0; - uint64_t success = 0; - uint64_t fails = 0; + uint64_t success = 0; + uint64_t fails = 0; uint64_t timeouts = 0; util::StatusObject @@ -84,11 +84,11 @@ namespace llarp // forward declare struct Path; - using Path_ptr = std::shared_ptr< Path >; + using Path_ptr = std::shared_ptr; struct PathSet; - using PathSet_ptr = std::shared_ptr< PathSet >; + using PathSet_ptr = std::shared_ptr; /// a set of paths owned by an entity struct PathSet @@ -108,8 +108,7 @@ namespace llarp /// manual build on these hops virtual void - Build(const std::vector< RouterContact >& hops, - PathRole roles = ePathRoleAny) = 0; + Build(const std::vector& hops, PathRole roles = ePathRoleAny) = 0; /// tick owned paths virtual void @@ -199,15 +198,13 @@ namespace llarp } /// override me in subtype - virtual bool - HandleGotIntroMessage(std::shared_ptr< const dht::GotIntroMessage >) + virtual bool HandleGotIntroMessage(std::shared_ptr) { return false; } /// override me in subtype - virtual bool - HandleGotRouterMessage(std::shared_ptr< const dht::GotRouterMessage >) + virtual bool HandleGotRouterMessage(std::shared_ptr) { return false; } @@ -219,8 +216,7 @@ namespace llarp } Path_ptr - GetEstablishedPathClosestTo(RouterID router, - PathRole roles = ePathRoleAny) const; + GetEstablishedPathClosestTo(RouterID router, PathRole roles = ePathRoleAny) const; Path_ptr PickRandomEstablishedPath(PathRole roles = ePathRoleAny) const; @@ -229,8 +225,7 @@ namespace llarp GetPathByRouter(RouterID router, PathRole roles = ePathRoleAny) const; Path_ptr - GetNewestPathByRouter(RouterID router, - PathRole roles = ePathRoleAny) const; + GetNewestPathByRouter(RouterID router, PathRole roles = ePathRoleAny) const; Path_ptr GetPathByID(PathID_t id) const; @@ -240,11 +235,11 @@ namespace llarp bool GetCurrentIntroductionsWithFilter( - std::set< service::Introduction >& intros, - std::function< bool(const service::Introduction&) > filter) const; + std::set& intros, + std::function filter) const; bool - GetCurrentIntroductions(std::set< service::Introduction >& intros) const; + GetCurrentIntroductions(std::set& intros) const; virtual bool PublishIntroSet(const service::EncryptedIntroSet&, AbstractRouter*) @@ -257,18 +252,22 @@ namespace llarp ResetInternalState() = 0; virtual bool - SelectHop(llarp_nodedb* db, const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, PathRole roles) = 0; + SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + PathRole roles) = 0; virtual bool BuildOneAlignedTo(const RouterID endpoint) = 0; void - ForEachPath(std::function< void(const Path_ptr&) > visit) const + ForEachPath(std::function visit) const { Lock_t lock(m_PathsMutex); auto itr = m_Paths.begin(); - while(itr != m_Paths.end()) + while (itr != m_Paths.end()) { visit(itr->second); ++itr; @@ -289,7 +288,7 @@ namespace llarp void TickPaths(AbstractRouter* r); - using PathInfo_t = std::pair< RouterID, PathID_t >; + using PathInfo_t = std::pair; struct PathInfoHash { @@ -309,10 +308,9 @@ namespace llarp } }; - using Mtx_t = util::NullMutex; - using Lock_t = util::NullLock; - using PathMap_t = std::unordered_map< PathInfo_t, Path_ptr, PathInfoHash, - PathInfoEquals >; + using Mtx_t = util::NullMutex; + using Lock_t = util::NullLock; + using PathMap_t = std::unordered_map; mutable Mtx_t m_PathsMutex; PathMap_t m_Paths; }; diff --git a/llarp/path/transit_hop.cpp b/llarp/path/transit_hop.cpp index 577c7ac39..2ef55c574 100644 --- a/llarp/path/transit_hop.cpp +++ b/llarp/path/transit_hop.cpp @@ -36,7 +36,7 @@ namespace llarp { m_UpstreamGather.enable(); m_DownstreamGather.enable(); - m_UpstreamWorkCounter = 0; + m_UpstreamWorkCounter = 0; m_DownstreamWorkCounter = 0; } @@ -53,25 +53,24 @@ namespace llarp } bool - TransitHop::HandleLRSM(uint64_t status, - std::array< EncryptedFrame, 8 >& frames, - AbstractRouter* r) + TransitHop::HandleLRSM( + uint64_t status, std::array& frames, AbstractRouter* r) { - auto msg = std::make_shared< LR_StatusMessage >(frames); + auto msg = std::make_shared(frames); msg->status = status; msg->pathid = info.rxID; // TODO: add to IHopHandler some notion of "path status" const uint64_t ourStatus = LR_StatusRecord::SUCCESS; - if(!msg->AddFrame(pathKey, ourStatus)) + if (!msg->AddFrame(pathKey, ourStatus)) { return false; } LR_StatusMessage::QueueSendMessage(r, info.downstream, msg); - if((status & LR_StatusRecord::SUCCESS) != LR_StatusRecord::SUCCESS) + if ((status & LR_StatusRecord::SUCCESS) != LR_StatusRecord::SUCCESS) { LogWarn( "TransitHop received non-successful LR_StatusMessage, queueing " @@ -83,25 +82,20 @@ namespace llarp return true; } - TransitHopInfo::TransitHopInfo(const RouterID& down, - const LR_CommitRecord& record) - : txID(record.txid) - , rxID(record.rxid) - , upstream(record.nextHop) - , downstream(down) + TransitHopInfo::TransitHopInfo(const RouterID& down, const LR_CommitRecord& record) + : txID(record.txid), rxID(record.rxid), upstream(record.nextHop), downstream(down) { } bool - TransitHop::SendRoutingMessage(const routing::IMessage& msg, - AbstractRouter* r) + TransitHop::SendRoutingMessage(const routing::IMessage& msg, AbstractRouter* r) { - if(!IsEndpoint(r->pubkey())) + if (!IsEndpoint(r->pubkey())) return false; - std::array< byte_t, MAX_LINK_MSG_SIZE - 128 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!msg.BEncode(&buf)) + if (!msg.BEncode(&buf)) { llarp::LogError("failed to encode routing message"); return false; @@ -111,7 +105,7 @@ namespace llarp buf.sz = buf.cur - buf.base; // pad to nearest MESSAGE_PAD_SIZE bytes auto dlt = buf.sz % pad_size; - if(dlt) + if (dlt) { dlt = pad_size - dlt; // randomize padding @@ -127,35 +121,40 @@ namespace llarp { m_DownstreamWorkCounter++; auto flushIt = [self = shared_from_this(), r]() { - std::vector< RelayDownstreamMessage > msgs; + std::vector msgs; do { auto maybe = self->m_DownstreamGather.tryPopFront(); - if(not maybe.has_value()) + if (not maybe.has_value()) break; msgs.emplace_back(maybe.value()); - } while(true); + } while (true); self->HandleAllDownstream(std::move(msgs), r); }; - for(auto& ev : *msgs) + for (auto& ev : *msgs) { RelayDownstreamMessage msg; const llarp_buffer_t buf(ev.first); msg.pathid = info.rxID; - msg.Y = ev.second ^ nonceXOR; + msg.Y = ev.second ^ nonceXOR; CryptoManager::instance()->xchacha20(buf, pathKey, ev.second); msg.X = buf; - llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ", - info.upstream, " to ", info.downstream); - if(m_DownstreamGather.full()) + llarp::LogDebug( + "relay ", + msg.X.size(), + " bytes downstream from ", + info.upstream, + " to ", + info.downstream); + if (m_DownstreamGather.full()) { LogicCall(r->logic(), flushIt); } - if(m_DownstreamGather.enabled()) + if (m_DownstreamGather.enabled()) m_DownstreamGather.pushBack(msg); } m_DownstreamWorkCounter--; - if(m_DownstreamWorkCounter == 0) + if (m_DownstreamWorkCounter == 0) LogicCall(r->logic(), flushIt); } @@ -164,53 +163,52 @@ namespace llarp { m_UpstreamWorkCounter++; auto flushIt = [self = shared_from_this(), r]() { - std::vector< RelayUpstreamMessage > msgs; + std::vector msgs; do { auto maybe = self->m_UpstreamGather.tryPopFront(); - if(not maybe.has_value()) + if (not maybe.has_value()) break; msgs.emplace_back(maybe.value()); - } while(true); + } while (true); self->HandleAllUpstream(std::move(msgs), r); }; - for(auto& ev : *msgs) + for (auto& ev : *msgs) { const llarp_buffer_t buf(ev.first); RelayUpstreamMessage msg; CryptoManager::instance()->xchacha20(buf, pathKey, ev.second); msg.pathid = info.txID; - msg.Y = ev.second ^ nonceXOR; - msg.X = buf; - if(m_UpstreamGather.full()) + msg.Y = ev.second ^ nonceXOR; + msg.X = buf; + if (m_UpstreamGather.full()) { LogicCall(r->logic(), flushIt); } - if(m_UpstreamGather.enabled()) + if (m_UpstreamGather.enabled()) m_UpstreamGather.pushBack(msg); } m_UpstreamWorkCounter--; - if(m_UpstreamWorkCounter == 0) + if (m_UpstreamWorkCounter == 0) LogicCall(r->logic(), flushIt); } void - TransitHop::HandleAllUpstream(std::vector< RelayUpstreamMessage > msgs, - AbstractRouter* r) + TransitHop::HandleAllUpstream(std::vector msgs, AbstractRouter* r) { - if(IsEndpoint(r->pubkey())) + if (IsEndpoint(r->pubkey())) { - for(const auto& msg : msgs) + for (const auto& msg : msgs) { const llarp_buffer_t buf(msg.X); - if(!r->ParseRoutingMessageBuffer(buf, this, info.rxID)) + if (!r->ParseRoutingMessageBuffer(buf, this, info.rxID)) { LogWarn("invalid upstream data on endpoint ", info); } m_LastActivity = r->Now(); } FlushDownstream(r); - for(const auto& other : m_FlushOthers) + for (const auto& other : m_FlushOthers) { other->FlushUpstream(r); } @@ -218,10 +216,15 @@ namespace llarp } else { - for(const auto& msg : msgs) + for (const auto& msg : msgs) { - llarp::LogDebug("relay ", msg.X.size(), " bytes upstream from ", - info.downstream, " to ", info.upstream); + llarp::LogDebug( + "relay ", + msg.X.size(), + " bytes upstream from ", + info.downstream, + " to ", + info.upstream); r->SendToOrQueue(info.upstream, &msg); } } @@ -229,13 +232,17 @@ namespace llarp } void - TransitHop::HandleAllDownstream(std::vector< RelayDownstreamMessage > msgs, - AbstractRouter* r) + TransitHop::HandleAllDownstream(std::vector msgs, AbstractRouter* r) { - for(const auto& msg : msgs) + for (const auto& msg : msgs) { - llarp::LogDebug("relay ", msg.X.size(), " bytes downstream from ", - info.upstream, " to ", info.downstream); + llarp::LogDebug( + "relay ", + msg.X.size(), + " bytes downstream from ", + info.upstream, + " to ", + info.downstream); r->SendToOrQueue(info.downstream, &msg); } r->linkManager().PumpLinks(); @@ -244,10 +251,9 @@ namespace llarp void TransitHop::FlushUpstream(AbstractRouter* r) { - if(m_UpstreamQueue && !m_UpstreamQueue->empty()) - r->threadpool()->addJob(std::bind(&TransitHop::UpstreamWork, - shared_from_this(), - std::move(m_UpstreamQueue), r)); + if (m_UpstreamQueue && !m_UpstreamQueue->empty()) + r->threadpool()->addJob(std::bind( + &TransitHop::UpstreamWork, shared_from_this(), std::move(m_UpstreamQueue), r)); m_UpstreamQueue = nullptr; } @@ -255,18 +261,16 @@ namespace llarp void TransitHop::FlushDownstream(AbstractRouter* r) { - if(m_DownstreamQueue && !m_DownstreamQueue->empty()) - r->threadpool()->addJob(std::bind(&TransitHop::DownstreamWork, - shared_from_this(), - std::move(m_DownstreamQueue), r)); + if (m_DownstreamQueue && !m_DownstreamQueue->empty()) + r->threadpool()->addJob(std::bind( + &TransitHop::DownstreamWork, shared_from_this(), std::move(m_DownstreamQueue), r)); m_DownstreamQueue = nullptr; } /// this is where a DHT message is handled at the end of a path, that is, /// where a SNode receives a DHT message from a client along a path. bool - TransitHop::HandleDHTMessage(const llarp::dht::IMessage& msg, - AbstractRouter* r) + TransitHop::HandleDHTMessage(const llarp::dht::IMessage& msg, AbstractRouter* r) { return r->dht()->impl->RelayRequestForPath(info.rxID, msg); } @@ -302,13 +306,12 @@ namespace llarp TransitHop::HandleObtainExitMessage( const llarp::routing::ObtainExitMessage& msg, AbstractRouter* r) { - if(msg.Verify() - && r->exitContext().ObtainNewExit(msg.I, info.rxID, msg.E != 0)) + if (msg.Verify() && r->exitContext().ObtainNewExit(msg.I, info.rxID, msg.E != 0)) { llarp::routing::GrantExitMessage grant; grant.S = NextSeqNo(); grant.T = msg.T; - if(!grant.Sign(r->identity())) + if (!grant.Sign(r->identity())) { llarp::LogError("Failed to sign grant exit message"); return false; @@ -320,7 +323,7 @@ namespace llarp llarp::routing::RejectExitMessage reject; reject.S = NextSeqNo(); reject.T = msg.T; - if(!reject.Sign(r->identity())) + if (!reject.Sign(r->identity())) { llarp::LogError("Failed to sign reject exit message"); return false; @@ -334,14 +337,14 @@ namespace llarp { const llarp::routing::DataDiscardMessage discard(info.rxID, msg.S); auto ep = r->exitContext().FindEndpointForPath(info.rxID); - if(ep && msg.Verify(ep->PubKey())) + if (ep && msg.Verify(ep->PubKey())) { llarp::routing::CloseExitMessage reply; reply.Y = msg.Y; reply.S = NextSeqNo(); - if(reply.Sign(r->identity())) + if (reply.Sign(r->identity())) { - if(SendRoutingMessage(reply, r)) + if (SendRoutingMessage(reply, r)) { ep->Close(); return true; @@ -366,12 +369,12 @@ namespace llarp const llarp::routing::UpdateExitMessage& msg, AbstractRouter* r) { auto ep = r->exitContext().FindEndpointForPath(msg.P); - if(ep) + if (ep) { - if(!msg.Verify(ep->PubKey())) + if (!msg.Verify(ep->PubKey())) return false; - if(ep->UpdateLocalPath(info.rxID)) + if (ep->UpdateLocalPath(info.rxID)) { llarp::routing::UpdateExitVerifyMessage reply; reply.T = msg.T; @@ -409,18 +412,17 @@ namespace llarp const llarp::routing::TransferTrafficMessage& msg, AbstractRouter* r) { auto endpoint = r->exitContext().FindEndpointForPath(info.rxID); - if(endpoint) + if (endpoint) { bool sent = true; - for(const auto& pkt : msg.X) + for (const auto& pkt : msg.X) { // check short packet buffer - if(pkt.size() <= 8) + if (pkt.size() <= 8) continue; uint64_t counter = bufbe64toh(pkt.data()); sent &= endpoint->QueueOutboundTraffic( - ManagedBuffer(llarp_buffer_t(pkt.data() + 8, pkt.size() - 8)), - counter); + ManagedBuffer(llarp_buffer_t(pkt.data() + 8, pkt.size() - 8)), counter); } return sent; } @@ -437,23 +439,23 @@ namespace llarp { auto path = r->pathContext().GetPathForTransfer(msg.P); llarp::routing::DataDiscardMessage discarded(msg.P, msg.S); - if(path == nullptr || msg.T.F != info.txID) + if (path == nullptr || msg.T.F != info.txID) { return SendRoutingMessage(discarded, r); } - std::array< byte_t, service::MAX_PROTOCOL_MESSAGE_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!msg.T.BEncode(&buf)) + if (!msg.T.BEncode(&buf)) { llarp::LogWarn(info, " failed to transfer data message, encode failed"); return SendRoutingMessage(discarded, r); } // rewind - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; // send - if(path->HandleDownstream(buf, msg.Y, r)) + if (path->HandleDownstream(buf, msg.Y, r)) { m_FlushOthers.emplace(path); return true; diff --git a/llarp/path/transit_hop.hpp b/llarp/path/transit_hop.hpp index b5bb6015d..eab437e2c 100644 --- a/llarp/path/transit_hop.hpp +++ b/llarp/path/transit_hop.hpp @@ -36,7 +36,7 @@ namespace llarp std::size_t operator()(const PathID_t& a) const { - return AlignedBuffer< PathID_t::SIZE >::Hash()(a); + return AlignedBuffer::Hash()(a); } }; @@ -82,7 +82,7 @@ namespace llarp struct TransitHop : public IHopHandler, public routing::IMessageHandler, - std::enable_shared_from_this< TransitHop > + std::enable_shared_from_this { TransitHop(); @@ -122,8 +122,8 @@ namespace llarp } bool - HandleLRSM(uint64_t status, std::array< EncryptedFrame, 8 >& frames, - AbstractRouter* r) override; + HandleLRSM( + uint64_t status, std::array& frames, AbstractRouter* r) override; std::ostream& print(std::ostream& stream, int level, int spaces) const; @@ -139,56 +139,47 @@ namespace llarp // send routing message when end of path bool - SendRoutingMessage(const routing::IMessage& msg, - AbstractRouter* r) override; + SendRoutingMessage(const routing::IMessage& msg, AbstractRouter* r) override; // handle routing message when end of path bool HandleRoutingMessage(const routing::IMessage& msg, AbstractRouter* r); bool - HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, - AbstractRouter* r) override; + HandleDataDiscardMessage(const routing::DataDiscardMessage& msg, AbstractRouter* r) override; bool HandlePathConfirmMessage(AbstractRouter* r); bool - HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, - AbstractRouter* r) override; + HandlePathConfirmMessage(const routing::PathConfirmMessage& msg, AbstractRouter* r) override; bool - HandlePathTransferMessage(const routing::PathTransferMessage& msg, - AbstractRouter* r) override; + HandlePathTransferMessage( + const routing::PathTransferMessage& msg, AbstractRouter* r) override; bool - HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, - AbstractRouter* r) override; + HandlePathLatencyMessage(const routing::PathLatencyMessage& msg, AbstractRouter* r) override; bool - HandleObtainExitMessage(const routing::ObtainExitMessage& msg, - AbstractRouter* r) override; + HandleObtainExitMessage(const routing::ObtainExitMessage& msg, AbstractRouter* r) override; bool - HandleUpdateExitVerifyMessage(const routing::UpdateExitVerifyMessage& msg, - AbstractRouter* r) override; + HandleUpdateExitVerifyMessage( + const routing::UpdateExitVerifyMessage& msg, AbstractRouter* r) override; bool - HandleTransferTrafficMessage(const routing::TransferTrafficMessage& msg, - AbstractRouter* r) override; + HandleTransferTrafficMessage( + const routing::TransferTrafficMessage& msg, AbstractRouter* r) override; bool - HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, - AbstractRouter* r) override; + HandleUpdateExitMessage(const routing::UpdateExitMessage& msg, AbstractRouter* r) override; bool - HandleGrantExitMessage(const routing::GrantExitMessage& msg, - AbstractRouter* r) override; + HandleGrantExitMessage(const routing::GrantExitMessage& msg, AbstractRouter* r) override; bool - HandleRejectExitMessage(const routing::RejectExitMessage& msg, - AbstractRouter* r) override; + HandleRejectExitMessage(const routing::RejectExitMessage& msg, AbstractRouter* r) override; bool - HandleCloseExitMessage(const routing::CloseExitMessage& msg, - AbstractRouter* r) override; + HandleCloseExitMessage(const routing::CloseExitMessage& msg, AbstractRouter* r) override; bool HandleHiddenServiceFrame(const service::ProtocolFrame& /*frame*/) override @@ -218,12 +209,10 @@ namespace llarp DownstreamWork(TrafficQueue_ptr queue, AbstractRouter* r) override; void - HandleAllUpstream(std::vector< RelayUpstreamMessage > msgs, - AbstractRouter* r) override; + HandleAllUpstream(std::vector msgs, AbstractRouter* r) override; void - HandleAllDownstream(std::vector< RelayDownstreamMessage > msgs, - AbstractRouter* r) override; + HandleAllDownstream(std::vector msgs, AbstractRouter* r) override; private: void @@ -232,13 +221,11 @@ namespace llarp void QueueDestroySelf(AbstractRouter* r); - std::set< std::shared_ptr< TransitHop >, - ComparePtr< std::shared_ptr< TransitHop > > > - m_FlushOthers; - thread::Queue< RelayUpstreamMessage > m_UpstreamGather; - thread::Queue< RelayDownstreamMessage > m_DownstreamGather; - std::atomic< uint32_t > m_UpstreamWorkCounter; - std::atomic< uint32_t > m_DownstreamWorkCounter; + std::set, ComparePtr>> m_FlushOthers; + thread::Queue m_UpstreamGather; + thread::Queue m_DownstreamGather; + std::atomic m_UpstreamWorkCounter; + std::atomic m_DownstreamWorkCounter; }; inline std::ostream& diff --git a/llarp/pow.cpp b/llarp/pow.cpp index 93b03a403..510bfddb5 100644 --- a/llarp/pow.cpp +++ b/llarp/pow.cpp @@ -20,7 +20,7 @@ namespace llarp PoW::BEncode(llarp_buffer_t* buf) const { // TODO: implement me - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; return bencode_end(buf); } @@ -28,26 +28,26 @@ namespace llarp bool PoW::IsValid(llarp_time_t now) const { - if(now - timestamp > extendedLifetime) + if (now - timestamp > extendedLifetime) return false; ShortHash digest; - std::array< byte_t, MaxSize > tmp; + std::array tmp; llarp_buffer_t buf(tmp); // encode - if(!BEncode(&buf)) + if (!BEncode(&buf)) return false; // rewind - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; // hash - if(!CryptoManager::instance()->shorthash(digest, buf)) + if (!CryptoManager::instance()->shorthash(digest, buf)) return false; // check bytes required uint32_t required = std::floor(std::log(extendedLifetime.count())); - for(uint32_t idx = 0; idx < required; ++idx) + for (uint32_t idx = 0; idx < required; ++idx) { - if(digest[idx]) + if (digest[idx]) return false; } return true; diff --git a/llarp/pow.hpp b/llarp/pow.hpp index d9a90f2f3..2d4c867ef 100644 --- a/llarp/pow.hpp +++ b/llarp/pow.hpp @@ -10,9 +10,9 @@ namespace llarp struct PoW { static constexpr size_t MaxSize = 128; - llarp_time_t timestamp = 0s; - llarp_time_t extendedLifetime = 0s; - AlignedBuffer< 32 > nonce; + llarp_time_t timestamp = 0s; + llarp_time_t extendedLifetime = 0s; + AlignedBuffer<32> nonce; uint64_t version = LLARP_PROTO_VERSION; ~PoW(); diff --git a/llarp/profiling.cpp b/llarp/profiling.cpp index be1b547ee..377c1cb5c 100644 --- a/llarp/profiling.cpp +++ b/llarp/profiling.cpp @@ -8,20 +8,20 @@ namespace llarp bool RouterProfile::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictInt("g", connectGoodCount, buf)) + if (!BEncodeWriteDictInt("g", connectGoodCount, buf)) return false; - if(!BEncodeWriteDictInt("p", pathSuccessCount, buf)) + if (!BEncodeWriteDictInt("p", pathSuccessCount, buf)) return false; - if(!BEncodeWriteDictInt("s", pathFailCount, buf)) + if (!BEncodeWriteDictInt("s", pathFailCount, buf)) return false; - if(!BEncodeWriteDictInt("t", connectTimeoutCount, buf)) + if (!BEncodeWriteDictInt("t", connectTimeoutCount, buf)) return false; - if(!BEncodeWriteDictInt("u", lastUpdated.count(), buf)) + if (!BEncodeWriteDictInt("u", lastUpdated.count(), buf)) return false; - if(!BEncodeWriteDictInt("v", version, buf)) + if (!BEncodeWriteDictInt("v", version, buf)) return false; return bencode_end(buf); @@ -31,17 +31,17 @@ namespace llarp RouterProfile::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("g", connectGoodCount, read, k, buf)) + if (!BEncodeMaybeReadDictInt("g", connectGoodCount, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("t", connectTimeoutCount, read, k, buf)) + if (!BEncodeMaybeReadDictInt("t", connectTimeoutCount, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("u", lastUpdated, read, k, buf)) + if (!BEncodeMaybeReadDictInt("u", lastUpdated, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("s", pathFailCount, read, k, buf)) + if (!BEncodeMaybeReadDictInt("s", pathFailCount, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("p", pathSuccessCount, read, k, buf)) + if (!BEncodeMaybeReadDictInt("p", pathSuccessCount, read, k, buf)) return false; return read; } @@ -61,26 +61,24 @@ namespace llarp { // 15 seconds static constexpr auto updateInterval = 15s; - const auto now = llarp::time_now_ms(); - if(lastDecay < now && now - lastDecay > updateInterval) + const auto now = llarp::time_now_ms(); + if (lastDecay < now && now - lastDecay > updateInterval) Decay(); } bool RouterProfile::IsGood(uint64_t chances) const { - if(connectTimeoutCount > chances) - return connectTimeoutCount < connectGoodCount - && (pathSuccessCount * chances) > pathFailCount; + if (connectTimeoutCount > chances) + return connectTimeoutCount < connectGoodCount && (pathSuccessCount * chances) > pathFailCount; return (pathSuccessCount * chances) > pathFailCount; } - static bool constexpr checkIsGood(uint64_t fails, uint64_t success, - uint64_t chances) + static bool constexpr checkIsGood(uint64_t fails, uint64_t success, uint64_t chances) { - if(fails > 0 && (fails + success) >= chances) + if (fails > 0 && (fails + success) >= chances) return (success / fails) > 1; - if(success == 0) + if (success == 0) return fails < chances; return true; } @@ -116,11 +114,11 @@ namespace llarp bool Profiling::IsBadForConnect(const RouterID& r, uint64_t chances) { - if(m_DisableProfiling.load()) + if (m_DisableProfiling.load()) return false; util::Lock lock(m_ProfilesMutex); auto itr = m_Profiles.find(r); - if(itr == m_Profiles.end()) + if (itr == m_Profiles.end()) return false; return !itr->second.IsGoodForConnect(chances); } @@ -128,11 +126,11 @@ namespace llarp bool Profiling::IsBadForPath(const RouterID& r, uint64_t chances) { - if(m_DisableProfiling.load()) + if (m_DisableProfiling.load()) return false; util::Lock lock(m_ProfilesMutex); auto itr = m_Profiles.find(r); - if(itr == m_Profiles.end()) + if (itr == m_Profiles.end()) return false; return !itr->second.IsGoodForPath(chances); } @@ -140,11 +138,11 @@ namespace llarp bool Profiling::IsBad(const RouterID& r, uint64_t chances) { - if(m_DisableProfiling.load()) + if (m_DisableProfiling.load()) return false; util::Lock lock(m_ProfilesMutex); auto itr = m_Profiles.find(r); - if(itr == m_Profiles.end()) + if (itr == m_Profiles.end()) return false; return !itr->second.IsGood(chances); } @@ -153,8 +151,7 @@ namespace llarp Profiling::Tick() { util::Lock lock(m_ProfilesMutex); - std::for_each(m_Profiles.begin(), m_Profiles.end(), - [](auto& item) { item.second.Tick(); }); + std::for_each(m_Profiles.begin(), m_Profiles.end(), [](auto& item) { item.second.Tick(); }); } void @@ -193,10 +190,10 @@ namespace llarp { util::Lock lock(m_ProfilesMutex); size_t idx = 0; - for(const auto& hop : p->hops) + for (const auto& hop : p->hops) { // don't mark first hop as failure because we are connected to it directly - if(idx) + if (idx) { m_Profiles[hop.rc.pubkey].pathFailCount += 1; m_Profiles[hop.rc.pubkey].lastUpdated = llarp::time_now_ms(); @@ -210,7 +207,7 @@ namespace llarp { util::Lock lock(m_ProfilesMutex); const auto sz = p->hops.size(); - for(const auto& hop : p->hops) + for (const auto& hop : p->hops) { m_Profiles[hop.rc.pubkey].pathSuccessCount += sz; m_Profiles[hop.rc.pubkey].lastUpdated = llarp::time_now_ms(); @@ -223,19 +220,18 @@ namespace llarp auto lock = util::shared_lock(m_ProfilesMutex); size_t sz = (m_Profiles.size() * (RouterProfile::MaxSize + 32 + 8)) + 8; - std::vector< byte_t > tmp(sz, 0); + std::vector tmp(sz, 0); llarp_buffer_t buf(tmp); auto res = BEncodeNoLock(&buf); - if(res) + if (res) { - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; const fs::path fpath = std::string(fname); - auto optional_f = - util::OpenFileStream< std::ofstream >(fpath, std::ios::binary); - if(!optional_f) + auto optional_f = util::OpenFileStream(fpath, std::ios::binary); + if (!optional_f) return false; auto& f = optional_f.value(); - if(f.is_open()) + if (f.is_open()) { f.write((char*)buf.base, buf.sz); m_LastSave = llarp::time_now_ms(); @@ -254,15 +250,15 @@ namespace llarp bool Profiling::BEncodeNoLock(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; auto itr = m_Profiles.begin(); - while(itr != m_Profiles.end()) + while (itr != m_Profiles.end()) { - if(!itr->first.BEncode(buf)) + if (!itr->first.BEncode(buf)) return false; - if(!itr->second.BEncode(buf)) + if (!itr->second.BEncode(buf)) return false; ++itr; } @@ -272,10 +268,10 @@ namespace llarp bool Profiling::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { - if(k.sz != 32) + if (k.sz != 32) return false; RouterProfile profile; - if(!bencode_decode_dict(profile, buf)) + if (!bencode_decode_dict(profile, buf)) return false; RouterID pk = k.base; return m_Profiles.emplace(pk, profile).second; @@ -286,7 +282,7 @@ namespace llarp { util::Lock lock(m_ProfilesMutex); m_Profiles.clear(); - if(!BDecodeReadFromFile(fname, *this)) + if (!BDecodeReadFromFile(fname, *this)) { llarp::LogWarn("failed to load router profiles from ", fname); return false; diff --git a/llarp/profiling.hpp b/llarp/profiling.hpp index 2edf6147d..13b52ab0d 100644 --- a/llarp/profiling.hpp +++ b/llarp/profiling.hpp @@ -14,13 +14,13 @@ namespace llarp struct RouterProfile { static constexpr size_t MaxSize = 256; - uint64_t connectTimeoutCount = 0; - uint64_t connectGoodCount = 0; - uint64_t pathSuccessCount = 0; - uint64_t pathFailCount = 0; - llarp_time_t lastUpdated = 0s; - llarp_time_t lastDecay = 0s; - uint64_t version = LLARP_PROTO_VERSION; + uint64_t connectTimeoutCount = 0; + uint64_t connectGoodCount = 0; + uint64_t pathSuccessCount = 0; + uint64_t pathFailCount = 0; + llarp_time_t lastUpdated = 0s; + llarp_time_t lastDecay = 0s; + uint64_t version = LLARP_PROTO_VERSION; bool BEncode(llarp_buffer_t* buf) const; @@ -56,13 +56,11 @@ namespace llarp /// check if this router should have paths built over it bool - IsBadForPath(const RouterID& r, uint64_t chances = 8) - EXCLUDES(m_ProfilesMutex); + IsBadForPath(const RouterID& r, uint64_t chances = 8) EXCLUDES(m_ProfilesMutex); /// check if this router should be connected directly to bool - IsBadForConnect(const RouterID& r, uint64_t chances = 8) - EXCLUDES(m_ProfilesMutex); + IsBadForConnect(const RouterID& r, uint64_t chances = 8) EXCLUDES(m_ProfilesMutex); void MarkConnectTimeout(const RouterID& r) EXCLUDES(m_ProfilesMutex); @@ -89,8 +87,7 @@ namespace llarp BEncode(llarp_buffer_t* buf) const EXCLUDES(m_ProfilesMutex); bool - DecodeKey(const llarp_buffer_t& k, - llarp_buffer_t* buf) NO_THREAD_SAFETY_ANALYSIS; + DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) NO_THREAD_SAFETY_ANALYSIS; // disabled because we do load -> bencode::BDecodeReadFromFile -> DecodeKey bool @@ -112,9 +109,9 @@ namespace llarp bool BEncodeNoLock(llarp_buffer_t* buf) const REQUIRES_SHARED(m_ProfilesMutex); mutable util::Mutex m_ProfilesMutex; // protects m_Profiles - std::map< RouterID, RouterProfile > m_Profiles GUARDED_BY(m_ProfilesMutex); + std::map m_Profiles GUARDED_BY(m_ProfilesMutex); llarp_time_t m_LastSave = 0s; - std::atomic< bool > m_DisableProfiling; + std::atomic m_DisableProfiling; }; } // namespace llarp diff --git a/llarp/router/abstractrouter.hpp b/llarp/router/abstractrouter.hpp index b6fe0abb1..6f2e4c7ad 100644 --- a/llarp/router/abstractrouter.hpp +++ b/llarp/router/abstractrouter.hpp @@ -65,80 +65,79 @@ namespace llarp struct AbstractRouter { #ifdef LOKINET_HIVE - tooling::RouterHive *hive; + tooling::RouterHive* hive; #endif virtual ~AbstractRouter() = default; virtual bool - HandleRecvLinkMessageBuffer(ILinkSession *from, - const llarp_buffer_t &msg) = 0; + HandleRecvLinkMessageBuffer(ILinkSession* from, const llarp_buffer_t& msg) = 0; - virtual std::shared_ptr< Logic > + virtual std::shared_ptr logic() const = 0; - virtual llarp_dht_context * + virtual llarp_dht_context* dht() const = 0; - virtual llarp_nodedb * + virtual llarp_nodedb* nodedb() const = 0; - virtual const path::PathContext & + virtual const path::PathContext& pathContext() const = 0; - virtual path::PathContext & + virtual path::PathContext& pathContext() = 0; - virtual const RouterContact & + virtual const RouterContact& rc() const = 0; - virtual exit::Context & + virtual exit::Context& exitContext() = 0; - virtual std::shared_ptr< KeyManager > + virtual std::shared_ptr keyManager() const = 0; - virtual const SecretKey & + virtual const SecretKey& identity() const = 0; - virtual const SecretKey & + virtual const SecretKey& encryption() const = 0; - virtual Profiling & + virtual Profiling& routerProfiling() = 0; virtual llarp_ev_loop_ptr netloop() const = 0; - virtual std::shared_ptr< thread::ThreadPool > + virtual std::shared_ptr threadpool() = 0; - virtual std::shared_ptr< thread::ThreadPool > + virtual std::shared_ptr diskworker() = 0; - virtual service::Context & + virtual service::Context& hiddenServiceContext() = 0; - virtual const service::Context & + virtual const service::Context& hiddenServiceContext() const = 0; - virtual IOutboundMessageHandler & + virtual IOutboundMessageHandler& outboundMessageHandler() = 0; - virtual IOutboundSessionMaker & + virtual IOutboundSessionMaker& outboundSessionMaker() = 0; - virtual ILinkManager & + virtual ILinkManager& linkManager() = 0; - virtual I_RCLookupHandler & + virtual I_RCLookupHandler& rcLookupHandler() = 0; virtual bool - Sign(Signature &sig, const llarp_buffer_t &buf) const = 0; + Sign(Signature& sig, const llarp_buffer_t& buf) const = 0; virtual bool - Configure(Config *conf, llarp_nodedb *nodedb) = 0; + Configure(Config* conf, llarp_nodedb* nodedb) = 0; virtual bool IsServiceNode() const = 0; @@ -166,7 +165,7 @@ namespace llarp virtual bool IsBootstrapNode(RouterID r) const = 0; - virtual const byte_t * + virtual const byte_t* pubkey() const = 0; /// connect to N random routers @@ -174,7 +173,7 @@ namespace llarp ConnectToRandomRouters(int N) = 0; /// inject configuration and reconfigure router virtual bool - Reconfigure(Config *conf) = 0; + Reconfigure(Config* conf) = 0; virtual bool TryConnectAsync(RouterContact rc, uint16_t tries) = 0; @@ -183,7 +182,7 @@ namespace llarp /// return true on 100% valid /// return false if not 100% valid virtual bool - ValidateConfig(Config *conf) const = 0; + ValidateConfig(Config* conf) const = 0; /// called by link when a remote session has no more sessions open virtual void @@ -198,19 +197,18 @@ namespace llarp Uptime() const = 0; virtual bool - GetRandomGoodRouter(RouterID &r) = 0; + GetRandomGoodRouter(RouterID& r) = 0; virtual bool - SendToOrQueue(const RouterID &remote, const ILinkMessage *msg, - SendStatusHandler handler = nullptr) = 0; + SendToOrQueue( + const RouterID& remote, const ILinkMessage* msg, SendStatusHandler handler = nullptr) = 0; virtual void - PersistSessionUntil(const RouterID &remote, llarp_time_t until) = 0; + PersistSessionUntil(const RouterID& remote, llarp_time_t until) = 0; virtual bool - ParseRoutingMessageBuffer(const llarp_buffer_t &buf, - routing::IMessageHandler *h, - const PathID_t &rxid) = 0; + ParseRoutingMessageBuffer( + const llarp_buffer_t& buf, routing::IMessageHandler* h, const PathID_t& rxid) = 0; /// count the number of service nodes we are connected to virtual size_t @@ -221,11 +219,10 @@ namespace llarp NumberOfConnectedClients() const = 0; virtual bool - GetRandomConnectedRouter(RouterContact &result) const = 0; + GetRandomConnectedRouter(RouterContact& result) const = 0; virtual void - HandleDHTLookupForExplore(RouterID remote, - const std::vector< RouterContact > &results) = 0; + HandleDHTLookupForExplore(RouterID remote, const std::vector& results) = 0; /// lookup router by pubkey /// if we are a service node this is done direct otherwise it's done via @@ -242,20 +239,19 @@ namespace llarp /// set router's service node whitelist virtual void - SetRouterWhitelist(const std::vector< RouterID > &routers) = 0; + SetRouterWhitelist(const std::vector& routers) = 0; /// visit each connected link session virtual void - ForEachPeer(std::function< void(const ILinkSession *, bool) > visit, - bool randomize) const = 0; + ForEachPeer(std::function visit, bool randomize) const = 0; virtual bool - ConnectionToRouterAllowed(const RouterID &router) const = 0; + ConnectionToRouterAllowed(const RouterID& router) const = 0; /// return true if we have at least 1 session to this router in either /// direction virtual bool - HasSessionTo(const RouterID &router) const = 0; + HasSessionTo(const RouterID& router) const = 0; virtual uint32_t NextPathBuildNumber() = 0; @@ -270,12 +266,12 @@ namespace llarp virtual void GossipRCIfNeeded(const RouterContact rc) = 0; - template + template void NotifyRouterEvent(Params&&... args) const { // TODO: no-op when appropriate - auto event = std::make_unique< EventType >(args...); + auto event = std::make_unique(args...); #ifdef LOKINET_HIVE hive->NotifyEvent(std::move(event)); #elif LOKINET_DEBUG diff --git a/llarp/router/i_gossiper.hpp b/llarp/router/i_gossiper.hpp index e54c50e33..27c84d98f 100644 --- a/llarp/router/i_gossiper.hpp +++ b/llarp/router/i_gossiper.hpp @@ -11,7 +11,7 @@ namespace llarp /// return false if we hit a cooldown for this rc /// return true if we gossiped this rc to at least 1 peer virtual bool - GossipRC(const RouterContact &rc) = 0; + GossipRC(const RouterContact& rc) = 0; using Time_t = std::chrono::milliseconds; @@ -24,7 +24,7 @@ namespace llarp /// return true if that rc is owned by us virtual bool - IsOurRC(const RouterContact &rc) const = 0; + IsOurRC(const RouterContact& rc) const = 0; }; } // namespace llarp diff --git a/llarp/router/i_outbound_message_handler.hpp b/llarp/router/i_outbound_message_handler.hpp index 91de04d50..9ffa784a7 100644 --- a/llarp/router/i_outbound_message_handler.hpp +++ b/llarp/router/i_outbound_message_handler.hpp @@ -22,10 +22,10 @@ namespace llarp struct RouterID; struct PathID_t; - using SendStatusHandler = std::function< void(SendStatus) >; + using SendStatusHandler = std::function; - static const size_t MAX_PATH_QUEUE_SIZE = 40; - static const size_t MAX_OUTBOUND_QUEUE_SIZE = 200; + static const size_t MAX_PATH_QUEUE_SIZE = 40; + static const size_t MAX_OUTBOUND_QUEUE_SIZE = 200; static const size_t MAX_OUTBOUND_MESSAGES_PER_TICK = 20; struct IOutboundMessageHandler @@ -33,14 +33,13 @@ namespace llarp virtual ~IOutboundMessageHandler() = default; virtual bool - QueueMessage(const RouterID &remote, const ILinkMessage *msg, - SendStatusHandler callback) = 0; + QueueMessage(const RouterID& remote, const ILinkMessage* msg, SendStatusHandler callback) = 0; virtual void Tick() = 0; virtual void - QueueRemoveEmptyPath(const PathID_t &pathid) = 0; + QueueRemoveEmptyPath(const PathID_t& pathid) = 0; virtual util::StatusObject ExtractStatus() const = 0; diff --git a/llarp/router/i_outbound_session_maker.hpp b/llarp/router/i_outbound_session_maker.hpp index c01710c01..ef009221d 100644 --- a/llarp/router/i_outbound_session_maker.hpp +++ b/llarp/router/i_outbound_session_maker.hpp @@ -21,27 +21,26 @@ namespace llarp NoLink }; - using RouterCallback = - std::function< void(const RouterID &, const SessionResult) >; + using RouterCallback = std::function; struct IOutboundSessionMaker { virtual ~IOutboundSessionMaker() = default; virtual bool - OnSessionEstablished(ILinkSession *session) = 0; + OnSessionEstablished(ILinkSession* session) = 0; virtual void - OnConnectTimeout(ILinkSession *session) = 0; + OnConnectTimeout(ILinkSession* session) = 0; virtual void - CreateSessionTo(const RouterID &router, RouterCallback on_result) = 0; + CreateSessionTo(const RouterID& router, RouterCallback on_result) = 0; virtual void - CreateSessionTo(const RouterContact &rc, RouterCallback on_result) = 0; + CreateSessionTo(const RouterContact& rc, RouterCallback on_result) = 0; virtual bool - HavePendingSessionTo(const RouterID &router) const = 0; + HavePendingSessionTo(const RouterID& router) const = 0; virtual void ConnectToRandomRouters(int numDesired) = 0; @@ -50,7 +49,7 @@ namespace llarp ExtractStatus() const = 0; virtual bool - ShouldConnectTo(const RouterID &router) const = 0; + ShouldConnectTo(const RouterID& router) const = 0; }; } // namespace llarp diff --git a/llarp/router/i_rc_lookup_handler.hpp b/llarp/router/i_rc_lookup_handler.hpp index 24318def1..d786fb693 100644 --- a/llarp/router/i_rc_lookup_handler.hpp +++ b/llarp/router/i_rc_lookup_handler.hpp @@ -20,34 +20,33 @@ namespace llarp BadRC }; - using RCRequestCallback = std::function< void( - const RouterID &, const RouterContact *const, const RCRequestResult) >; + using RCRequestCallback = + std::function; struct I_RCLookupHandler { virtual ~I_RCLookupHandler() = default; virtual void - AddValidRouter(const RouterID &router) = 0; + AddValidRouter(const RouterID& router) = 0; virtual void - RemoveValidRouter(const RouterID &router) = 0; + RemoveValidRouter(const RouterID& router) = 0; virtual void - SetRouterWhitelist(const std::vector< RouterID > &routers) = 0; + SetRouterWhitelist(const std::vector& routers) = 0; virtual void - GetRC(const RouterID &router, RCRequestCallback callback, - bool forceLookup = false) = 0; + GetRC(const RouterID& router, RCRequestCallback callback, bool forceLookup = false) = 0; virtual bool - RemoteIsAllowed(const RouterID &remote) const = 0; + RemoteIsAllowed(const RouterID& remote) const = 0; virtual bool - CheckRC(const RouterContact &rc) const = 0; + CheckRC(const RouterContact& rc) const = 0; virtual bool - GetRandomWhitelistRouter(RouterID &router) const = 0; + GetRandomWhitelistRouter(RouterID& router) const = 0; virtual bool CheckRenegotiateValid(RouterContact newrc, RouterContact oldrc) = 0; diff --git a/llarp/router/outbound_message_handler.cpp b/llarp/router/outbound_message_handler.cpp index 12e221409..ab0c4ec75 100644 --- a/llarp/router/outbound_message_handler.cpp +++ b/llarp/router/outbound_message_handler.cpp @@ -20,15 +20,14 @@ namespace llarp } bool - OutboundMessageHandler::QueueMessage(const RouterID &remote, - const ILinkMessage *msg, - SendStatusHandler callback) + OutboundMessageHandler::QueueMessage( + const RouterID& remote, const ILinkMessage* msg, SendStatusHandler callback) { const uint16_t priority = msg->Priority(); - std::array< byte_t, MAX_LINK_MSG_SIZE > linkmsg_buffer; + std::array linkmsg_buffer; llarp_buffer_t buf(linkmsg_buffer); - if(!EncodeBuffer(msg, buf)) + if (!EncodeBuffer(msg, buf)) { return false; } @@ -39,7 +38,7 @@ namespace llarp std::copy_n(buf.base, buf.sz, message.first.data()); - if(_linkManager->HasSessionTo(remote)) + if (_linkManager->HasSessionTo(remote)) { QueueOutboundMessage(remote, std::move(message), msg->pathid, priority); return true; @@ -50,19 +49,18 @@ namespace llarp util::Lock l(_mutex); // create queue for if it doesn't exist, and get iterator - auto itr_pair = - pendingSessionMessageQueues.emplace(remote, MessageQueue()); + auto itr_pair = pendingSessionMessageQueues.emplace(remote, MessageQueue()); MessageQueueEntry entry; entry.priority = priority; - entry.message = message; - entry.router = remote; + entry.message = message; + entry.router = remote; itr_pair.first->second.push(std::move(entry)); shouldCreateSession = itr_pair.second; } - if(shouldCreateSession) + if (shouldCreateSession) { QueueSessionCreation(remote); } @@ -81,10 +79,10 @@ namespace llarp } void - OutboundMessageHandler::QueueRemoveEmptyPath(const PathID_t &pathid) + OutboundMessageHandler::QueueRemoveEmptyPath(const PathID_t& pathid) { m_Killer.TryAccess([self = this, pathid]() { - if(self->removedPaths.full()) + if (self->removedPaths.full()) { self->RemoveEmptyPathQueues(); } @@ -108,50 +106,48 @@ namespace llarp } void - OutboundMessageHandler::Init(ILinkManager *linkManager, - std::shared_ptr< Logic > logic) + OutboundMessageHandler::Init(ILinkManager* linkManager, std::shared_ptr logic) { _linkManager = linkManager; - _logic = logic; + _logic = logic; outboundMessageQueues.emplace(zeroID, MessageQueue()); } void - OutboundMessageHandler::OnSessionEstablished(const RouterID &router) + OutboundMessageHandler::OnSessionEstablished(const RouterID& router) { FinalizeSessionRequest(router, SendStatus::Success); } void - OutboundMessageHandler::OnConnectTimeout(const RouterID &router) + OutboundMessageHandler::OnConnectTimeout(const RouterID& router) { FinalizeSessionRequest(router, SendStatus::Timeout); } void - OutboundMessageHandler::OnRouterNotFound(const RouterID &router) + OutboundMessageHandler::OnRouterNotFound(const RouterID& router) { FinalizeSessionRequest(router, SendStatus::RouterNotFound); } void - OutboundMessageHandler::OnInvalidRouter(const RouterID &router) + OutboundMessageHandler::OnInvalidRouter(const RouterID& router) { FinalizeSessionRequest(router, SendStatus::InvalidRouter); } void - OutboundMessageHandler::OnNoLink(const RouterID &router) + OutboundMessageHandler::OnNoLink(const RouterID& router) { FinalizeSessionRequest(router, SendStatus::NoLink); } void - OutboundMessageHandler::OnSessionResult(const RouterID &router, - const SessionResult result) + OutboundMessageHandler::OnSessionResult(const RouterID& router, const SessionResult result) { - switch(result) + switch (result) { case SessionResult::Establish: OnSessionEstablished(router); @@ -176,10 +172,9 @@ namespace llarp } void - OutboundMessageHandler::DoCallback(SendStatusHandler callback, - SendStatus status) + OutboundMessageHandler::DoCallback(SendStatusHandler callback, SendStatus status) { - if(callback) + if (callback) { auto f = std::bind(callback, status); LogicCall(_logic, [self = this, f]() { self->m_Killer.TryAccess(f); }); @@ -187,52 +182,48 @@ namespace llarp } void - OutboundMessageHandler::QueueSessionCreation(const RouterID &remote) + OutboundMessageHandler::QueueSessionCreation(const RouterID& remote) { auto fn = util::memFn(&OutboundMessageHandler::OnSessionResult, this); _linkManager->GetSessionMaker()->CreateSessionTo(remote, fn); } bool - OutboundMessageHandler::EncodeBuffer(const ILinkMessage *msg, - llarp_buffer_t &buf) + OutboundMessageHandler::EncodeBuffer(const ILinkMessage* msg, llarp_buffer_t& buf) { - if(!msg->BEncode(&buf)) + if (!msg->BEncode(&buf)) { - LogWarn("failed to encode outbound message, buffer size left: ", - buf.size_left()); + LogWarn("failed to encode outbound message, buffer size left: ", buf.size_left()); return false; } // set size of message - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; return true; } bool - OutboundMessageHandler::Send(const RouterID &remote, const Message &msg) + OutboundMessageHandler::Send(const RouterID& remote, const Message& msg) { const llarp_buffer_t buf(msg.first); auto callback = msg.second; m_queueStats.sent++; - return _linkManager->SendTo( - remote, buf, [=](ILinkSession::DeliveryStatus status) { - if(status == ILinkSession::DeliveryStatus::eDeliverySuccess) - DoCallback(callback, SendStatus::Success); - else - { - LogWarn("Send outbound message handler dropped message"); - DoCallback(callback, SendStatus::Congestion); - } - }); + return _linkManager->SendTo(remote, buf, [=](ILinkSession::DeliveryStatus status) { + if (status == ILinkSession::DeliveryStatus::eDeliverySuccess) + DoCallback(callback, SendStatus::Success); + else + { + LogWarn("Send outbound message handler dropped message"); + DoCallback(callback, SendStatus::Congestion); + } + }); } bool - OutboundMessageHandler::SendIfSession(const RouterID &remote, - const Message &msg) + OutboundMessageHandler::SendIfSession(const RouterID& remote, const Message& msg) { - if(_linkManager->HasSessionTo(remote)) + if (_linkManager->HasSessionTo(remote)) { return Send(remote, msg); } @@ -240,19 +231,16 @@ namespace llarp } bool - OutboundMessageHandler::QueueOutboundMessage(const RouterID &remote, - Message &&msg, - const PathID_t &pathid, - uint16_t priority) + OutboundMessageHandler::QueueOutboundMessage( + const RouterID& remote, Message&& msg, const PathID_t& pathid, uint16_t priority) { MessageQueueEntry entry; - entry.message = std::move(msg); + entry.message = std::move(msg); auto callback_copy = entry.message.second; - entry.router = remote; - entry.pathid = pathid; - entry.priority = priority; - if(outboundQueue.tryPushBack(std::move(entry)) - != llarp::thread::QueueReturn::Success) + entry.router = remote; + entry.pathid = pathid; + entry.priority = priority; + if (outboundQueue.tryPushBack(std::move(entry)) != llarp::thread::QueueReturn::Success) { m_queueStats.dropped++; LogWarn( @@ -266,8 +254,7 @@ namespace llarp m_queueStats.queued++; uint32_t queueSize = outboundQueue.size(); - m_queueStats.queueWatermark = - std::max(queueSize, m_queueStats.queueWatermark); + m_queueStats.queueWatermark = std::max(queueSize, m_queueStats.queueWatermark); } return true; @@ -276,22 +263,21 @@ namespace llarp void OutboundMessageHandler::ProcessOutboundQueue() { - while(not outboundQueue.empty()) + while (not outboundQueue.empty()) { // TODO: can we add util::thread::Queue::front() for move semantics here? MessageQueueEntry entry = outboundQueue.popFront(); - auto itr_pair = - outboundMessageQueues.emplace(entry.pathid, MessageQueue()); + auto itr_pair = outboundMessageQueues.emplace(entry.pathid, MessageQueue()); - if(itr_pair.second && !entry.pathid.IsZero()) + if (itr_pair.second && !entry.pathid.IsZero()) { roundRobinOrder.push(entry.pathid); } - MessageQueue &path_queue = itr_pair.first->second; + MessageQueue& path_queue = itr_pair.first->second; - if(path_queue.size() < MAX_PATH_QUEUE_SIZE || entry.pathid.IsZero()) + if (path_queue.size() < MAX_PATH_QUEUE_SIZE || entry.pathid.IsZero()) { path_queue.push(std::move(entry)); } @@ -311,13 +297,13 @@ namespace llarp OutboundMessageHandler::RemoveEmptyPathQueues() { removedSomePaths = false; - if(removedPaths.empty()) + if (removedPaths.empty()) return; - while(not removedPaths.empty()) + while (not removedPaths.empty()) { auto itr = outboundMessageQueues.find(removedPaths.popFront()); - if(itr != outboundMessageQueues.end()) + if (itr != outboundMessageQueues.end()) { outboundMessageQueues.erase(itr); } @@ -331,48 +317,47 @@ namespace llarp m_queueStats.numTicks++; // send non-routing messages first priority - auto &non_routing_mq = outboundMessageQueues[zeroID]; - while(not non_routing_mq.empty()) + auto& non_routing_mq = outboundMessageQueues[zeroID]; + while (not non_routing_mq.empty()) { - const MessageQueueEntry &entry = non_routing_mq.top(); + const MessageQueueEntry& entry = non_routing_mq.top(); Send(entry.router, entry.message); non_routing_mq.pop(); } size_t empty_count = 0; - size_t num_queues = roundRobinOrder.size(); + size_t num_queues = roundRobinOrder.size(); - if(removedSomePaths) + if (removedSomePaths) { - for(size_t i = 0; i < num_queues; i++) + for (size_t i = 0; i < num_queues; i++) { PathID_t pathid = std::move(roundRobinOrder.front()); roundRobinOrder.pop(); - if(outboundMessageQueues.find(pathid) != outboundMessageQueues.end()) + if (outboundMessageQueues.find(pathid) != outboundMessageQueues.end()) { roundRobinOrder.push(std::move(pathid)); } } } - num_queues = roundRobinOrder.size(); + num_queues = roundRobinOrder.size(); size_t sent_count = 0; - if(num_queues == 0) // if no queues, return + if (num_queues == 0) // if no queues, return { return; } - while(sent_count - < MAX_OUTBOUND_MESSAGES_PER_TICK) // TODO: better stop condition + while (sent_count < MAX_OUTBOUND_MESSAGES_PER_TICK) // TODO: better stop condition { PathID_t pathid = std::move(roundRobinOrder.front()); roundRobinOrder.pop(); - auto &message_queue = outboundMessageQueues[pathid]; - if(message_queue.size() > 0) + auto& message_queue = outboundMessageQueues[pathid]; + if (message_queue.size() > 0) { - const MessageQueueEntry &entry = message_queue.top(); + const MessageQueueEntry& entry = message_queue.top(); Send(entry.router, entry.message); message_queue.pop(); @@ -388,26 +373,24 @@ namespace llarp roundRobinOrder.push(std::move(pathid)); // if num_queues empty queues in a row, all queues empty. - if(empty_count == num_queues) + if (empty_count == num_queues) { break; } } - m_queueStats.perTickMax = - std::max((uint32_t)sent_count, m_queueStats.perTickMax); + m_queueStats.perTickMax = std::max((uint32_t)sent_count, m_queueStats.perTickMax); } void - OutboundMessageHandler::FinalizeSessionRequest(const RouterID &router, - SendStatus status) + OutboundMessageHandler::FinalizeSessionRequest(const RouterID& router, SendStatus status) { MessageQueue movedMessages; { util::Lock l(_mutex); auto itr = pendingSessionMessageQueues.find(router); - if(itr == pendingSessionMessageQueues.end()) + if (itr == pendingSessionMessageQueues.end()) { return; } @@ -417,11 +400,11 @@ namespace llarp pendingSessionMessageQueues.erase(itr); } - while(!movedMessages.empty()) + while (!movedMessages.empty()) { - const MessageQueueEntry &entry = movedMessages.top(); + const MessageQueueEntry& entry = movedMessages.top(); - if(status == SendStatus::Success) + if (status == SendStatus::Success) { Send(entry.router, entry.message); } diff --git a/llarp/router/outbound_message_handler.hpp b/llarp/router/outbound_message_handler.hpp index 7ee05ceb1..6a113d821 100644 --- a/llarp/router/outbound_message_handler.hpp +++ b/llarp/router/outbound_message_handler.hpp @@ -29,23 +29,23 @@ namespace llarp OutboundMessageHandler(size_t maxQueueSize = MAX_OUTBOUND_QUEUE_SIZE); bool - QueueMessage(const RouterID &remote, const ILinkMessage *msg, - SendStatusHandler callback) override EXCLUDES(_mutex); + QueueMessage(const RouterID& remote, const ILinkMessage* msg, SendStatusHandler callback) + override EXCLUDES(_mutex); void Tick() override; void - QueueRemoveEmptyPath(const PathID_t &pathid) override; + QueueRemoveEmptyPath(const PathID_t& pathid) override; util::StatusObject ExtractStatus() const override; void - Init(ILinkManager *linkManager, std::shared_ptr< Logic > logic); + Init(ILinkManager* linkManager, std::shared_ptr logic); private: - using Message = std::pair< std::vector< byte_t >, SendStatusHandler >; + using Message = std::pair, SendStatusHandler>; struct MessageQueueEntry { @@ -55,7 +55,7 @@ namespace llarp RouterID router; bool - operator<(const MessageQueueEntry &other) const + operator<(const MessageQueueEntry& other) const { return other.priority < priority; } @@ -63,53 +63,53 @@ namespace llarp struct MessageQueueStats { - uint64_t queued = 0; - uint64_t dropped = 0; - uint64_t sent = 0; + uint64_t queued = 0; + uint64_t dropped = 0; + uint64_t sent = 0; uint32_t queueWatermark = 0; uint32_t perTickMax = 0; - uint32_t numTicks = 0; + uint32_t numTicks = 0; }; - using MessageQueue = std::priority_queue< MessageQueueEntry >; + using MessageQueue = std::priority_queue; void - OnSessionEstablished(const RouterID &router); + OnSessionEstablished(const RouterID& router); void - OnConnectTimeout(const RouterID &router); + OnConnectTimeout(const RouterID& router); void - OnRouterNotFound(const RouterID &router); + OnRouterNotFound(const RouterID& router); void - OnInvalidRouter(const RouterID &router); + OnInvalidRouter(const RouterID& router); void - OnNoLink(const RouterID &router); + OnNoLink(const RouterID& router); void - OnSessionResult(const RouterID &router, const SessionResult result); + OnSessionResult(const RouterID& router, const SessionResult result); void DoCallback(SendStatusHandler callback, SendStatus status); void - QueueSessionCreation(const RouterID &remote); + QueueSessionCreation(const RouterID& remote); bool - EncodeBuffer(const ILinkMessage *msg, llarp_buffer_t &buf); + EncodeBuffer(const ILinkMessage* msg, llarp_buffer_t& buf); bool - Send(const RouterID &remote, const Message &msg); + Send(const RouterID& remote, const Message& msg); bool - SendIfSession(const RouterID &remote, const Message &msg); + SendIfSession(const RouterID& remote, const Message& msg); bool - QueueOutboundMessage(const RouterID &remote, Message &&msg, - const PathID_t &pathid, uint16_t priority = 0); + QueueOutboundMessage( + const RouterID& remote, Message&& msg, const PathID_t& pathid, uint16_t priority = 0); void ProcessOutboundQueue(); @@ -121,25 +121,23 @@ namespace llarp SendRoundRobin(); void - FinalizeSessionRequest(const RouterID &router, SendStatus status) - EXCLUDES(_mutex); + FinalizeSessionRequest(const RouterID& router, SendStatus status) EXCLUDES(_mutex); - llarp::thread::Queue< MessageQueueEntry > outboundQueue; - llarp::thread::Queue< PathID_t > removedPaths; + llarp::thread::Queue outboundQueue; + llarp::thread::Queue removedPaths; bool removedSomePaths; mutable util::Mutex _mutex; // protects pendingSessionMessageQueues - std::unordered_map< RouterID, MessageQueue, RouterID::Hash > - pendingSessionMessageQueues GUARDED_BY(_mutex); + std::unordered_map pendingSessionMessageQueues + GUARDED_BY(_mutex); - std::unordered_map< PathID_t, MessageQueue, PathID_t::Hash > - outboundMessageQueues; + std::unordered_map outboundMessageQueues; - std::queue< PathID_t > roundRobinOrder; + std::queue roundRobinOrder; - ILinkManager *_linkManager; - std::shared_ptr< Logic > _logic; + ILinkManager* _linkManager; + std::shared_ptr _logic; util::ContentionKiller m_Killer; diff --git a/llarp/router/outbound_session_maker.cpp b/llarp/router/outbound_session_maker.cpp index 9962ca682..10ba1d7d1 100644 --- a/llarp/router/outbound_session_maker.cpp +++ b/llarp/router/outbound_session_maker.cpp @@ -30,43 +30,43 @@ namespace llarp }; bool - OutboundSessionMaker::OnSessionEstablished(ILinkSession *session) + OutboundSessionMaker::OnSessionEstablished(ILinkSession* session) { // TODO: do we want to keep it const auto router = RouterID(session->GetPubKey()); - const std::string remoteType = - session->GetRemoteRC().IsPublicRouter() ? "router" : "client"; + const std::string remoteType = session->GetRemoteRC().IsPublicRouter() ? "router" : "client"; LogInfo("session with ", remoteType, " [", router, "] established"); - if(not _rcLookup->RemoteIsAllowed(router)) + if (not _rcLookup->RemoteIsAllowed(router)) { FinalizeRequest(router, SessionResult::InvalidRouter); return false; } - auto func = std::bind(&OutboundSessionMaker::VerifyRC, this, - session->GetRemoteRC()); + auto func = std::bind(&OutboundSessionMaker::VerifyRC, this, session->GetRemoteRC()); _threadpool->addJob(func); return true; } void - OutboundSessionMaker::OnConnectTimeout(ILinkSession *session) + OutboundSessionMaker::OnConnectTimeout(ILinkSession* session) { // TODO: retry/num attempts - LogWarn("Session establish attempt to ", RouterID(session->GetPubKey()), - " timed out.", session->GetRemoteEndpoint()); + LogWarn( + "Session establish attempt to ", + RouterID(session->GetPubKey()), + " timed out.", + session->GetRemoteEndpoint()); FinalizeRequest(session->GetPubKey(), SessionResult::Timeout); } void - OutboundSessionMaker::CreateSessionTo(const RouterID &router, - RouterCallback on_result) + OutboundSessionMaker::CreateSessionTo(const RouterID& router, RouterCallback on_result) { - if(on_result) + if (on_result) { util::Lock l(_mutex); @@ -74,7 +74,7 @@ namespace llarp itr_pair.first->second.push_back(on_result); } - if(HavePendingSessionTo(router)) + if (HavePendingSessionTo(router)) { return; } @@ -89,10 +89,9 @@ namespace llarp } void - OutboundSessionMaker::CreateSessionTo(const RouterContact &rc, - RouterCallback on_result) + OutboundSessionMaker::CreateSessionTo(const RouterContact& rc, RouterCallback on_result) { - if(on_result) + if (on_result) { util::Lock l(_mutex); @@ -100,7 +99,7 @@ namespace llarp itr_pair.first->second.push_back(on_result); } - if(not HavePendingSessionTo(rc.pubkey)) + if (not HavePendingSessionTo(rc.pubkey)) { LogDebug("Creating session establish attempt to ", rc.pubkey, " ."); CreatePendingSession(rc.pubkey); @@ -110,7 +109,7 @@ namespace llarp } bool - OutboundSessionMaker::HavePendingSessionTo(const RouterID &router) const + OutboundSessionMaker::HavePendingSessionTo(const RouterID& router) const { util::Lock l(_mutex); return pendingSessions.find(router) != pendingSessions.end(); @@ -120,28 +119,27 @@ namespace llarp OutboundSessionMaker::ConnectToRandomRouters(int numDesired) { int remainingDesired = numDesired; - std::set< RouterID > exclude; + std::set exclude; do { RouterContact other; - if(not _nodedb->select_random_hop_excluding(other, exclude)) + if (not _nodedb->select_random_hop_excluding(other, exclude)) break; exclude.insert(other.pubkey); - if(not _rcLookup->RemoteIsAllowed(other.pubkey)) + if (not _rcLookup->RemoteIsAllowed(other.pubkey)) { continue; } - if(not(_linkManager->HasSessionTo(other.pubkey) - || HavePendingSessionTo(other.pubkey))) + if (not(_linkManager->HasSessionTo(other.pubkey) || HavePendingSessionTo(other.pubkey))) { CreateSessionTo(other, nullptr); --remainingDesired; } - } while(remainingDesired > 0); - LogDebug("connecting to ", numDesired - remainingDesired, " out of ", - numDesired, " random routers"); + } while (remainingDesired > 0); + LogDebug( + "connecting to ", numDesired - remainingDesired, " out of ", numDesired, " random routers"); } // TODO: this @@ -154,32 +152,35 @@ namespace llarp void OutboundSessionMaker::Init( - ILinkManager *linkManager, I_RCLookupHandler *rcLookup, - Profiling *profiler, std::shared_ptr< Logic > logic, llarp_nodedb *nodedb, - std::shared_ptr< llarp::thread::ThreadPool > threadpool) + ILinkManager* linkManager, + I_RCLookupHandler* rcLookup, + Profiling* profiler, + std::shared_ptr logic, + llarp_nodedb* nodedb, + std::shared_ptr threadpool) { _linkManager = linkManager; - _rcLookup = rcLookup; - _logic = logic; - _nodedb = nodedb; - _threadpool = threadpool; - _profiler = profiler; + _rcLookup = rcLookup; + _logic = logic; + _nodedb = nodedb; + _threadpool = threadpool; + _profiler = profiler; } void - OutboundSessionMaker::DoEstablish(const RouterID &router) + OutboundSessionMaker::DoEstablish(const RouterID& router) { auto l = util::unique_lock(_mutex); auto itr = pendingSessions.find(router); - if(itr == pendingSessions.end()) + if (itr == pendingSessions.end()) { return; } - const auto &job = itr->second; - if(!job->link->TryEstablishTo(job->rc)) + const auto& job = itr->second; + if (!job->link->TryEstablishTo(job->rc)) { // TODO: maybe different failure type? @@ -189,8 +190,7 @@ namespace llarp } void - OutboundSessionMaker::GotRouterContact(const RouterID &router, - const RouterContact &rc) + OutboundSessionMaker::GotRouterContact(const RouterID& router, const RouterContact& rc) { { auto l = util::unique_lock(_mutex); @@ -198,25 +198,25 @@ namespace llarp // in case other request found RC for this router after this request was // made auto itr = pendingSessions.find(router); - if(itr == pendingSessions.end()) + if (itr == pendingSessions.end()) { return; } LinkLayer_ptr link = _linkManager->GetCompatibleLink(rc); - if(!link) + if (!link) { l.unlock(); FinalizeRequest(router, SessionResult::NoLink); return; } - auto session = std::make_shared< PendingSession >(rc, link); + auto session = std::make_shared(rc, link); itr->second = session; } - if(ShouldConnectTo(router)) + if (ShouldConnectTo(router)) { auto fn = std::bind(&OutboundSessionMaker::DoEstablish, this, router); LogicCall(_logic, fn); @@ -224,48 +224,46 @@ namespace llarp } bool - OutboundSessionMaker::ShouldConnectTo(const RouterID &router) const + OutboundSessionMaker::ShouldConnectTo(const RouterID& router) const { - if(router == us) + if (router == us) return false; size_t numPending = 0; { util::Lock lock(_mutex); - if(pendingSessions.find(router) == pendingSessions.end()) + if (pendingSessions.find(router) == pendingSessions.end()) numPending += pendingSessions.size(); } - if(_linkManager->HasSessionTo(router)) + if (_linkManager->HasSessionTo(router)) return false; - return _linkManager->NumberOfConnectedRouters() + numPending - < maxConnectedRouters; + return _linkManager->NumberOfConnectedRouters() + numPending < maxConnectedRouters; } void - OutboundSessionMaker::InvalidRouter(const RouterID &router) + OutboundSessionMaker::InvalidRouter(const RouterID& router) { FinalizeRequest(router, SessionResult::InvalidRouter); } void - OutboundSessionMaker::RouterNotFound(const RouterID &router) + OutboundSessionMaker::RouterNotFound(const RouterID& router) { FinalizeRequest(router, SessionResult::RouterNotFound); } void - OutboundSessionMaker::OnRouterContactResult(const RouterID &router, - const RouterContact *const rc, - const RCRequestResult result) + OutboundSessionMaker::OnRouterContactResult( + const RouterID& router, const RouterContact* const rc, const RCRequestResult result) { - if(not HavePendingSessionTo(router)) + if (not HavePendingSessionTo(router)) { return; } - switch(result) + switch (result) { case RCRequestResult::Success: - if(rc) + if (rc) { GotRouterContact(router, *rc); } @@ -288,7 +286,7 @@ namespace llarp void OutboundSessionMaker::VerifyRC(const RouterContact rc) { - if(not _rcLookup->CheckRC(rc)) + if (not _rcLookup->CheckRC(rc)) { FinalizeRequest(rc.pubkey, SessionResult::InvalidRouter); return; @@ -298,21 +296,20 @@ namespace llarp } void - OutboundSessionMaker::CreatePendingSession(const RouterID &router) + OutboundSessionMaker::CreatePendingSession(const RouterID& router) { util::Lock l(_mutex); pendingSessions.emplace(router, nullptr); } void - OutboundSessionMaker::FinalizeRequest(const RouterID &router, - const SessionResult type) + OutboundSessionMaker::FinalizeRequest(const RouterID& router, const SessionResult type) { CallbacksQueue movedCallbacks; { util::Lock l(_mutex); - if(type == SessionResult::Establish) + if (type == SessionResult::Establish) { _profiler->MarkConnectSuccess(router); } @@ -324,14 +321,14 @@ namespace llarp auto itr = pendingCallbacks.find(router); - if(itr != pendingCallbacks.end()) + if (itr != pendingCallbacks.end()) { movedCallbacks.splice(movedCallbacks.begin(), itr->second); pendingCallbacks.erase(itr); } } - for(const auto &callback : movedCallbacks) + for (const auto& callback : movedCallbacks) { auto func = std::bind(callback, router, type); LogicCall(_logic, func); diff --git a/llarp/router/outbound_session_maker.hpp b/llarp/router/outbound_session_maker.hpp index 6a503612e..4501267e8 100644 --- a/llarp/router/outbound_session_maker.hpp +++ b/llarp/router/outbound_session_maker.hpp @@ -25,28 +25,25 @@ namespace llarp struct OutboundSessionMaker final : public IOutboundSessionMaker { - using CallbacksQueue = std::list< RouterCallback >; + using CallbacksQueue = std::list; public: ~OutboundSessionMaker() override = default; bool - OnSessionEstablished(ILinkSession *session) override; + OnSessionEstablished(ILinkSession* session) override; void - OnConnectTimeout(ILinkSession *session) override; + OnConnectTimeout(ILinkSession* session) override; void - CreateSessionTo(const RouterID &router, RouterCallback on_result) override - EXCLUDES(_mutex); + CreateSessionTo(const RouterID& router, RouterCallback on_result) override EXCLUDES(_mutex); void - CreateSessionTo(const RouterContact &rc, RouterCallback on_result) override - EXCLUDES(_mutex); + CreateSessionTo(const RouterContact& rc, RouterCallback on_result) override EXCLUDES(_mutex); bool - HavePendingSessionTo(const RouterID &router) const override - EXCLUDES(_mutex); + HavePendingSessionTo(const RouterID& router) const override EXCLUDES(_mutex); void ConnectToRandomRouters(int numDesired) override; @@ -55,13 +52,16 @@ namespace llarp ExtractStatus() const override; bool - ShouldConnectTo(const RouterID &router) const override EXCLUDES(_mutex); + ShouldConnectTo(const RouterID& router) const override EXCLUDES(_mutex); void - Init(ILinkManager *linkManager, I_RCLookupHandler *rcLookup, - Profiling *profiler, std::shared_ptr< Logic > logic, - llarp_nodedb *nodedb, - std::shared_ptr< llarp::thread::ThreadPool > threadpool); + Init( + ILinkManager* linkManager, + I_RCLookupHandler* rcLookup, + Profiling* profiler, + std::shared_ptr logic, + llarp_nodedb* nodedb, + std::shared_ptr threadpool); void SetOurRouter(RouterID r) @@ -76,47 +76,44 @@ namespace llarp private: void - DoEstablish(const RouterID &router) EXCLUDES(_mutex); + DoEstablish(const RouterID& router) EXCLUDES(_mutex); void - GotRouterContact(const RouterID &router, const RouterContact &rc) - EXCLUDES(_mutex); + GotRouterContact(const RouterID& router, const RouterContact& rc) EXCLUDES(_mutex); void - InvalidRouter(const RouterID &router); + InvalidRouter(const RouterID& router); void - RouterNotFound(const RouterID &router); + RouterNotFound(const RouterID& router); void - OnRouterContactResult(const RouterID &router, const RouterContact *const rc, - const RCRequestResult result); + OnRouterContactResult( + const RouterID& router, const RouterContact* const rc, const RCRequestResult result); void VerifyRC(const RouterContact rc); void - CreatePendingSession(const RouterID &router) EXCLUDES(_mutex); + CreatePendingSession(const RouterID& router) EXCLUDES(_mutex); void - FinalizeRequest(const RouterID &router, const SessionResult type) - EXCLUDES(_mutex); + FinalizeRequest(const RouterID& router, const SessionResult type) EXCLUDES(_mutex); mutable util::Mutex _mutex; // protects pendingSessions, pendingCallbacks - std::unordered_map< RouterID, std::shared_ptr< PendingSession >, - RouterID::Hash > - pendingSessions GUARDED_BY(_mutex); + std::unordered_map, RouterID::Hash> pendingSessions + GUARDED_BY(_mutex); - std::unordered_map< RouterID, CallbacksQueue, RouterID::Hash > - pendingCallbacks GUARDED_BY(_mutex); + std::unordered_map pendingCallbacks + GUARDED_BY(_mutex); - ILinkManager *_linkManager = nullptr; - I_RCLookupHandler *_rcLookup = nullptr; - Profiling *_profiler = nullptr; - llarp_nodedb *_nodedb = nullptr; - std::shared_ptr< Logic > _logic; - std::shared_ptr< llarp::thread::ThreadPool > _threadpool; + ILinkManager* _linkManager = nullptr; + I_RCLookupHandler* _rcLookup = nullptr; + Profiling* _profiler = nullptr; + llarp_nodedb* _nodedb = nullptr; + std::shared_ptr _logic; + std::shared_ptr _threadpool; RouterID us; }; diff --git a/llarp/router/rc_gossiper.cpp b/llarp/router/rc_gossiper.cpp index b754a9cb1..e8d535a2a 100644 --- a/llarp/router/rc_gossiper.cpp +++ b/llarp/router/rc_gossiper.cpp @@ -10,23 +10,19 @@ namespace llarp // 30 minutes static constexpr auto RCGossipFilterDecayInterval = 30min; // (30 minutes * 2) - 5 minutes - static constexpr auto GossipOurRCInterval = - (RCGossipFilterDecayInterval * 2) - (5min); + static constexpr auto GossipOurRCInterval = (RCGossipFilterDecayInterval * 2) - (5min); RCGossiper::RCGossiper() - : I_RCGossiper() - , m_Filter( - std::chrono::duration_cast< Time_t >(RCGossipFilterDecayInterval)) + : I_RCGossiper(), m_Filter(std::chrono::duration_cast(RCGossipFilterDecayInterval)) { } void - RCGossiper::Init(ILinkManager* l, const RouterID& ourID, - AbstractRouter* router) + RCGossiper::Init(ILinkManager* l, const RouterID& ourID, AbstractRouter* router) { m_OurRouterID = ourID; m_LinkManager = l; - m_router = router; + m_router = router; } bool @@ -53,22 +49,22 @@ namespace llarp RCGossiper::GossipRC(const RouterContact& rc) { // only distribute public routers - if(not rc.IsPublicRouter()) + if (not rc.IsPublicRouter()) return false; - if(m_LinkManager == nullptr) + if (m_LinkManager == nullptr) return false; const RouterID pubkey(rc.pubkey); // filter check - if(m_Filter.Contains(pubkey)) + if (m_Filter.Contains(pubkey)) return false; m_Filter.Insert(pubkey); const auto now = time_now_ms(); // is this our rc? - if(IsOurRC(rc)) + if (IsOurRC(rc)) { // should we gossip our rc? - if(not ShouldGossipOurRC(now)) + if (not ShouldGossipOurRC(now)) { // nah drop it return false; @@ -79,29 +75,26 @@ namespace llarp // send a GRCM as gossip method DHTImmediateMessage gossip; - gossip.msgs.emplace_back( - new dht::GotRouterMessage(dht::Key_t{}, 0, {rc}, false)); + gossip.msgs.emplace_back(new dht::GotRouterMessage(dht::Key_t{}, 0, {rc}, false)); // send it to everyone m_LinkManager->ForEachPeer([&](ILinkSession* peerSession) { // ensure connected session - if(not(peerSession && peerSession->IsEstablished())) + if (not(peerSession && peerSession->IsEstablished())) return; // check if public router const auto other_rc = peerSession->GetRemoteRC(); - if(not other_rc.IsPublicRouter()) + if (not other_rc.IsPublicRouter()) return; // encode message ILinkSession::Message_t msg; msg.resize(MAX_LINK_MSG_SIZE / 2); llarp_buffer_t buf(msg); - if(not gossip.BEncode(&buf)) + if (not gossip.BEncode(&buf)) return; msg.resize(buf.cur - buf.base); - m_router->NotifyRouterEvent< tooling::RCGossipSentEvent >( - m_router->pubkey(), - rc); + m_router->NotifyRouterEvent(m_router->pubkey(), rc); // send message peerSession->SendMessageBuffer(std::move(msg), nullptr); diff --git a/llarp/router/rc_gossiper.hpp b/llarp/router/rc_gossiper.hpp index 702ef2a96..ba9734051 100644 --- a/llarp/router/rc_gossiper.hpp +++ b/llarp/router/rc_gossiper.hpp @@ -16,7 +16,7 @@ namespace llarp ~RCGossiper() override = default; bool - GossipRC(const RouterContact &rc) override; + GossipRC(const RouterContact& rc) override; void Decay(Time_t now) override; @@ -25,18 +25,18 @@ namespace llarp ShouldGossipOurRC(Time_t now) const override; bool - IsOurRC(const RouterContact &rc) const override; + IsOurRC(const RouterContact& rc) const override; void - Init(ILinkManager *, const RouterID &, AbstractRouter *); + Init(ILinkManager*, const RouterID&, AbstractRouter*); private: RouterID m_OurRouterID; - Time_t m_LastGossipedOurRC = 0s; - ILinkManager *m_LinkManager = nullptr; - util::DecayingHashSet< RouterID > m_Filter; + Time_t m_LastGossipedOurRC = 0s; + ILinkManager* m_LinkManager = nullptr; + util::DecayingHashSet m_Filter; - AbstractRouter *m_router; + AbstractRouter* m_router; }; } // namespace llarp diff --git a/llarp/router/rc_lookup_handler.cpp b/llarp/router/rc_lookup_handler.cpp index b98d65beb..c4c2c4200 100644 --- a/llarp/router/rc_lookup_handler.cpp +++ b/llarp/router/rc_lookup_handler.cpp @@ -19,34 +19,33 @@ namespace llarp { void - RCLookupHandler::AddValidRouter(const RouterID &router) + RCLookupHandler::AddValidRouter(const RouterID& router) { util::Lock l(_mutex); whitelistRouters.insert(router); } void - RCLookupHandler::RemoveValidRouter(const RouterID &router) + RCLookupHandler::RemoveValidRouter(const RouterID& router) { util::Lock l(_mutex); whitelistRouters.erase(router); } void - RCLookupHandler::SetRouterWhitelist(const std::vector< RouterID > &routers) + RCLookupHandler::SetRouterWhitelist(const std::vector& routers) { - if(routers.empty()) + if (routers.empty()) return; util::Lock l(_mutex); whitelistRouters.clear(); - for(auto &router : routers) + for (auto& router : routers) { whitelistRouters.emplace(router); } - LogInfo("lokinet service node list now has ", whitelistRouters.size(), - " routers"); + LogInfo("lokinet service node list now has ", whitelistRouters.size(), " routers"); } bool @@ -57,15 +56,14 @@ namespace llarp } void - RCLookupHandler::GetRC(const RouterID &router, RCRequestCallback callback, - bool forceLookup) + RCLookupHandler::GetRC(const RouterID& router, RCRequestCallback callback, bool forceLookup) { RouterContact remoteRC; - if(not forceLookup) + if (not forceLookup) { - if(_nodedb->Get(router, remoteRC)) + if (_nodedb->Get(router, remoteRC)) { - if(callback) + if (callback) { callback(router, &remoteRC, RCRequestResult::Success); } @@ -80,36 +78,35 @@ namespace llarp auto itr_pair = pendingCallbacks.emplace(router, CallbacksQueue{}); - if(callback) + if (callback) { itr_pair.first->second.push_back(callback); } shouldDoLookup = itr_pair.second; } - if(shouldDoLookup) + if (shouldDoLookup) { - auto fn = std::bind(&RCLookupHandler::HandleDHTLookupResult, this, router, - std::placeholders::_1); + auto fn = + std::bind(&RCLookupHandler::HandleDHTLookupResult, this, router, std::placeholders::_1); // if we are a client try using the hidden service endpoints - if(!isServiceNode) + if (!isServiceNode) { bool sent = false; LogInfo("Lookup ", router, " anonymously"); _hiddenServiceContext->ForEachService( - [&](const std::string &, - const std::shared_ptr< service::Endpoint > &ep) -> bool { + [&](const std::string&, const std::shared_ptr& ep) -> bool { const bool success = ep->LookupRouterAnon(router, fn); - sent = sent || success; + sent = sent || success; return !success; }); - if(sent) + if (sent) return; LogWarn("cannot lookup ", router, " anonymously"); } - if(!_dht->impl->LookupRouter(router, fn)) + if (!_dht->impl->LookupRouter(router, fn)) { FinalizeRequest(router, nullptr, RCRequestResult::RouterNotFound); } @@ -121,17 +118,17 @@ namespace llarp } bool - RCLookupHandler::RemoteIsAllowed(const RouterID &remote) const + RCLookupHandler::RemoteIsAllowed(const RouterID& remote) const { - if(_strictConnectPubkeys.size() && _strictConnectPubkeys.count(remote) == 0 - && !RemoteInBootstrap(remote)) + if (_strictConnectPubkeys.size() && _strictConnectPubkeys.count(remote) == 0 + && !RemoteInBootstrap(remote)) { return false; } util::Lock l(_mutex); - if(useWhitelist && whitelistRouters.find(remote) == whitelistRouters.end()) + if (useWhitelist && whitelistRouters.find(remote) == whitelistRouters.end()) { return false; } @@ -140,25 +137,24 @@ namespace llarp } bool - RCLookupHandler::CheckRC(const RouterContact &rc) const + RCLookupHandler::CheckRC(const RouterContact& rc) const { - if(not RemoteIsAllowed(rc.pubkey)) + if (not RemoteIsAllowed(rc.pubkey)) { _dht->impl->DelRCNodeAsync(dht::Key_t{rc.pubkey}); return false; } - if(not rc.Verify(_dht->impl->Now())) + if (not rc.Verify(_dht->impl->Now())) { LogWarn("RC for ", RouterID(rc.pubkey), " is invalid"); return false; } // update nodedb if required - if(rc.IsPublicRouter()) + if (rc.IsPublicRouter()) { - LogDebug("Adding or updating RC for ", RouterID(rc.pubkey), - " to nodedb and dht."); + LogDebug("Adding or updating RC for ", RouterID(rc.pubkey), " to nodedb and dht."); _nodedb->UpdateAsyncIfNewer(rc); _dht->impl->PutRCNodeAsync(rc); } @@ -173,36 +169,35 @@ namespace llarp } bool - RCLookupHandler::GetRandomWhitelistRouter(RouterID &router) const + RCLookupHandler::GetRandomWhitelistRouter(RouterID& router) const { util::Lock l(_mutex); const auto sz = whitelistRouters.size(); - auto itr = whitelistRouters.begin(); - if(sz == 0) + auto itr = whitelistRouters.begin(); + if (sz == 0) return false; - if(sz > 1) + if (sz > 1) std::advance(itr, randint() % sz); router = *itr; return true; } bool - RCLookupHandler::CheckRenegotiateValid(RouterContact newrc, - RouterContact oldrc) + RCLookupHandler::CheckRenegotiateValid(RouterContact newrc, RouterContact oldrc) { // missmatch of identity ? - if(newrc.pubkey != oldrc.pubkey) + if (newrc.pubkey != oldrc.pubkey) return false; - if(!RemoteIsAllowed(newrc.pubkey)) + if (!RemoteIsAllowed(newrc.pubkey)) return false; auto func = std::bind(&RCLookupHandler::CheckRC, this, newrc); _threadpool->addJob(func); // update dht if required - if(_dht->impl->Nodes()->HasNode(dht::Key_t{newrc.pubkey})) + if (_dht->impl->Nodes()->HasNode(dht::Key_t{newrc.pubkey})) { _dht->impl->Nodes()->PutNode(newrc); } @@ -215,48 +210,47 @@ namespace llarp RCLookupHandler::PeriodicUpdate(llarp_time_t now) { // try looking up stale routers - std::set< RouterID > routersToLookUp; + std::set routersToLookUp; _nodedb->VisitInsertedBefore( - [&](const RouterContact &rc) { - if(HavePendingLookup(rc.pubkey)) + [&](const RouterContact& rc) { + if (HavePendingLookup(rc.pubkey)) return; routersToLookUp.insert(rc.pubkey); }, now - RouterContact::UpdateInterval); - for(const auto &router : routersToLookUp) + for (const auto& router : routersToLookUp) { GetRC(router, nullptr, true); } - _nodedb->RemoveStaleRCs(_bootstrapRouterIDList, - now - RouterContact::StaleInsertionAge); + _nodedb->RemoveStaleRCs(_bootstrapRouterIDList, now - RouterContact::StaleInsertionAge); } void RCLookupHandler::ExploreNetwork() { const size_t known = _nodedb->num_loaded(); - if(_bootstrapRCList.empty() && known == 0) + if (_bootstrapRCList.empty() && known == 0) { LogError("we have no bootstrap nodes specified"); } - else if(known <= _bootstrapRCList.size()) + else if (known <= _bootstrapRCList.size()) { - for(const auto &rc : _bootstrapRCList) + for (const auto& rc : _bootstrapRCList) { LogInfo("Doing explore via bootstrap node: ", RouterID(rc.pubkey)); _dht->impl->ExploreNetworkVia(dht::Key_t{rc.pubkey}); } } - if(useWhitelist) + if (useWhitelist) { static constexpr auto RerequestInterval = 10min; - static constexpr size_t LookupPerTick = 5; + static constexpr size_t LookupPerTick = 5; - std::vector< RouterID > lookupRouters; + std::vector lookupRouters; lookupRouters.reserve(LookupPerTick); const auto now = std::chrono::steady_clock::now(); @@ -264,38 +258,36 @@ namespace llarp { // if we are using a whitelist look up a few routers we don't have util::Lock l(_mutex); - for(const auto &r : whitelistRouters) + for (const auto& r : whitelistRouters) { - if(now > _routerLookupTimes[r] + RerequestInterval - and not _nodedb->Has(r)) + if (now > _routerLookupTimes[r] + RerequestInterval and not _nodedb->Has(r)) { lookupRouters.emplace_back(r); } } } - if(lookupRouters.size() > LookupPerTick) + if (lookupRouters.size() > LookupPerTick) { static std::mt19937_64 rng{llarp::randint()}; std::shuffle(lookupRouters.begin(), lookupRouters.end(), rng); lookupRouters.resize(LookupPerTick); } - for(const auto &r : lookupRouters) + for (const auto& r : lookupRouters) GetRC(r, nullptr, true); return; } // service nodes gossip, not explore - if(_dht->impl->GetRouter()->IsServiceNode()) + if (_dht->impl->GetRouter()->IsServiceNode()) return; // explore via every connected peer - _linkManager->ForEachPeer([&](ILinkSession *s) { - if(!s->IsEstablished()) + _linkManager->ForEachPeer([&](ILinkSession* s) { + if (!s->IsEstablished()) return; const RouterContact rc = s->GetRemoteRC(); - if(rc.IsPublicRouter() - && (_bootstrapRCList.find(rc) == _bootstrapRCList.end())) + if (rc.IsPublicRouter() && (_bootstrapRCList.find(rc) == _bootstrapRCList.end())) { LogDebug("Doing explore via public node: ", RouterID(rc.pubkey)); _dht->impl->ExploreNetworkVia(dht::Key_t{rc.pubkey}); @@ -304,47 +296,49 @@ namespace llarp } void - RCLookupHandler::Init(llarp_dht_context *dht, llarp_nodedb *nodedb, - std::shared_ptr< llarp::thread::ThreadPool > threadpool, - ILinkManager *linkManager, - service::Context *hiddenServiceContext, - const std::set< RouterID > &strictConnectPubkeys, - const std::set< RouterContact > &bootstrapRCList, - bool useWhitelist_arg, bool isServiceNode_arg) + RCLookupHandler::Init( + llarp_dht_context* dht, + llarp_nodedb* nodedb, + std::shared_ptr threadpool, + ILinkManager* linkManager, + service::Context* hiddenServiceContext, + const std::set& strictConnectPubkeys, + const std::set& bootstrapRCList, + bool useWhitelist_arg, + bool isServiceNode_arg) { - _dht = dht; - _nodedb = nodedb; - _threadpool = threadpool; + _dht = dht; + _nodedb = nodedb; + _threadpool = threadpool; _hiddenServiceContext = hiddenServiceContext; _strictConnectPubkeys = strictConnectPubkeys; - _bootstrapRCList = bootstrapRCList; - _linkManager = linkManager; - useWhitelist = useWhitelist_arg; - isServiceNode = isServiceNode_arg; + _bootstrapRCList = bootstrapRCList; + _linkManager = linkManager; + useWhitelist = useWhitelist_arg; + isServiceNode = isServiceNode_arg; - for(const auto &rc : _bootstrapRCList) + for (const auto& rc : _bootstrapRCList) { _bootstrapRouterIDList.insert(rc.pubkey); } } void - RCLookupHandler::HandleDHTLookupResult( - RouterID remote, const std::vector< RouterContact > &results) + RCLookupHandler::HandleDHTLookupResult(RouterID remote, const std::vector& results) { - if(not results.size()) + if (not results.size()) { FinalizeRequest(remote, nullptr, RCRequestResult::RouterNotFound); return; } - if(not RemoteIsAllowed(remote)) + if (not RemoteIsAllowed(remote)) { FinalizeRequest(remote, &results[0], RCRequestResult::InvalidRouter); return; } - if(not CheckRC(results[0])) + if (not CheckRC(results[0])) { FinalizeRequest(remote, &results[0], RCRequestResult::BadRC); return; @@ -361,11 +355,11 @@ namespace llarp } bool - RCLookupHandler::RemoteInBootstrap(const RouterID &remote) const + RCLookupHandler::RemoteInBootstrap(const RouterID& remote) const { - for(const auto &rc : _bootstrapRCList) + for (const auto& rc : _bootstrapRCList) { - if(rc.pubkey == remote) + if (rc.pubkey == remote) { return true; } @@ -374,9 +368,8 @@ namespace llarp } void - RCLookupHandler::FinalizeRequest(const RouterID &router, - const RouterContact *const rc, - RCRequestResult result) + RCLookupHandler::FinalizeRequest( + const RouterID& router, const RouterContact* const rc, RCRequestResult result) { CallbacksQueue movedCallbacks; { @@ -384,14 +377,14 @@ namespace llarp auto itr = pendingCallbacks.find(router); - if(itr != pendingCallbacks.end()) + if (itr != pendingCallbacks.end()) { movedCallbacks.splice(movedCallbacks.begin(), itr->second); pendingCallbacks.erase(itr); } } // lock - for(const auto &callback : movedCallbacks) + for (const auto& callback : movedCallbacks) { callback(router, rc, result); } diff --git a/llarp/router/rc_lookup_handler.hpp b/llarp/router/rc_lookup_handler.hpp index 067ffd88c..85453b566 100644 --- a/llarp/router/rc_lookup_handler.hpp +++ b/llarp/router/rc_lookup_handler.hpp @@ -27,35 +27,34 @@ namespace llarp struct RCLookupHandler final : public I_RCLookupHandler { public: - using CallbacksQueue = std::list< RCRequestCallback >; + using CallbacksQueue = std::list; ~RCLookupHandler() override = default; void - AddValidRouter(const RouterID &router) override EXCLUDES(_mutex); + AddValidRouter(const RouterID& router) override EXCLUDES(_mutex); void - RemoveValidRouter(const RouterID &router) override EXCLUDES(_mutex); + RemoveValidRouter(const RouterID& router) override EXCLUDES(_mutex); void - SetRouterWhitelist(const std::vector< RouterID > &routers) override - EXCLUDES(_mutex); + SetRouterWhitelist(const std::vector& routers) override EXCLUDES(_mutex); bool HaveReceivedWhitelist(); void - GetRC(const RouterID &router, RCRequestCallback callback, - bool forceLookup = false) override EXCLUDES(_mutex); + GetRC(const RouterID& router, RCRequestCallback callback, bool forceLookup = false) override + EXCLUDES(_mutex); bool - RemoteIsAllowed(const RouterID &remote) const override EXCLUDES(_mutex); + RemoteIsAllowed(const RouterID& remote) const override EXCLUDES(_mutex); bool - CheckRC(const RouterContact &rc) const override; + CheckRC(const RouterContact& rc) const override; bool - GetRandomWhitelistRouter(RouterID &router) const override EXCLUDES(_mutex); + GetRandomWhitelistRouter(RouterID& router) const override EXCLUDES(_mutex); bool CheckRenegotiateValid(RouterContact newrc, RouterContact oldrc) override; @@ -70,54 +69,56 @@ namespace llarp NumberOfStrictConnectRouters() const override; void - Init(llarp_dht_context *dht, llarp_nodedb *nodedb, - std::shared_ptr< llarp::thread::ThreadPool > threadpool, - ILinkManager *linkManager, service::Context *hiddenServiceContext, - const std::set< RouterID > &strictConnectPubkeys, - const std::set< RouterContact > &bootstrapRCList, - bool useWhitelist_arg, bool isServiceNode_arg); + Init( + llarp_dht_context* dht, + llarp_nodedb* nodedb, + std::shared_ptr threadpool, + ILinkManager* linkManager, + service::Context* hiddenServiceContext, + const std::set& strictConnectPubkeys, + const std::set& bootstrapRCList, + bool useWhitelist_arg, + bool isServiceNode_arg); private: void - HandleDHTLookupResult(RouterID remote, - const std::vector< RouterContact > &results); + HandleDHTLookupResult(RouterID remote, const std::vector& results); bool HavePendingLookup(RouterID remote) const EXCLUDES(_mutex); bool - RemoteInBootstrap(const RouterID &remote) const; + RemoteInBootstrap(const RouterID& remote) const; void - FinalizeRequest(const RouterID &router, const RouterContact *const rc, - RCRequestResult result) EXCLUDES(_mutex); + FinalizeRequest(const RouterID& router, const RouterContact* const rc, RCRequestResult result) + EXCLUDES(_mutex); mutable util::Mutex _mutex; // protects pendingCallbacks, whitelistRouters - llarp_dht_context *_dht = nullptr; - llarp_nodedb *_nodedb = nullptr; - std::shared_ptr< llarp::thread::ThreadPool > _threadpool = nullptr; - service::Context *_hiddenServiceContext = nullptr; - ILinkManager *_linkManager = nullptr; + llarp_dht_context* _dht = nullptr; + llarp_nodedb* _nodedb = nullptr; + std::shared_ptr _threadpool = nullptr; + service::Context* _hiddenServiceContext = nullptr; + ILinkManager* _linkManager = nullptr; /// explicit whitelist of routers we will connect to directly (not for /// service nodes) - std::set< RouterID > _strictConnectPubkeys; + std::set _strictConnectPubkeys; - std::set< RouterContact > _bootstrapRCList; - std::set< RouterID > _bootstrapRouterIDList; + std::set _bootstrapRCList; + std::set _bootstrapRouterIDList; - std::unordered_map< RouterID, CallbacksQueue, RouterID::Hash > - pendingCallbacks GUARDED_BY(_mutex); + std::unordered_map pendingCallbacks + GUARDED_BY(_mutex); - bool useWhitelist = false; + bool useWhitelist = false; bool isServiceNode = false; - std::set< RouterID > whitelistRouters GUARDED_BY(_mutex); + std::set whitelistRouters GUARDED_BY(_mutex); using TimePoint = std::chrono::steady_clock::time_point; - std::unordered_map< RouterID, TimePoint, RouterID::Hash > - _routerLookupTimes; + std::unordered_map _routerLookupTimes; }; } // namespace llarp diff --git a/llarp/router/router.cpp b/llarp/router/router.cpp index 5f07c22be..569e83679 100644 --- a/llarp/router/router.cpp +++ b/llarp/router/router.cpp @@ -42,35 +42,35 @@ static constexpr std::chrono::milliseconds ROUTER_TICK_INTERVAL = 1s; namespace llarp { - Router::Router(std::shared_ptr< llarp::thread::ThreadPool > _tp, - llarp_ev_loop_ptr __netloop, std::shared_ptr< Logic > l) + Router::Router( + std::shared_ptr _tp, + llarp_ev_loop_ptr __netloop, + std::shared_ptr l) : ready(false) , _netloop(std::move(__netloop)) , cryptoworker(std::move(_tp)) , _logic(std::move(l)) , paths(this) , _exitContext(this) - , disk(std::make_shared< llarp::thread::ThreadPool >(1, 1000, - "diskworker")) + , disk(std::make_shared(1, 1000, "diskworker")) , _dht(llarp_dht_context_new(this)) , inbound_link_msg_parser(this) , _hiddenServiceContext(this) #ifdef LOKINET_HIVE - , _randomStartDelay( - std::chrono::milliseconds((llarp::randint() % 1250) + 2000)) + , _randomStartDelay(std::chrono::milliseconds((llarp::randint() % 1250) + 2000)) #else , _randomStartDelay(std::chrono::seconds((llarp::randint() % 30) + 10)) #endif { - m_keyManager = std::make_shared< KeyManager >(); + m_keyManager = std::make_shared(); // set rational defaults this->ip4addr.sin_family = AF_INET; - this->ip4addr.sin_port = htons(1090); + this->ip4addr.sin_port = htons(1090); _stopping.store(false); _running.store(false); - _lastTick = llarp::time_now_ms(); + _lastTick = llarp::time_now_ms(); m_NextExploreAt = Clock_t::now(); } @@ -82,16 +82,15 @@ namespace llarp util::StatusObject Router::ExtractStatus() const { - if(_running) + if (_running) { - return util::StatusObject{ - {"running", true}, - {"numNodesKnown", _nodedb->num_loaded()}, - {"dht", _dht->impl->ExtractStatus()}, - {"services", _hiddenServiceContext.ExtractStatus()}, - {"exit", _exitContext.ExtractStatus()}, - {"links", _linkManager.ExtractStatus()}, - {"outboundMessages", _outboundMessageHandler.ExtractStatus()}}; + return util::StatusObject{{"running", true}, + {"numNodesKnown", _nodedb->num_loaded()}, + {"dht", _dht->impl->ExtractStatus()}, + {"services", _hiddenServiceContext.ExtractStatus()}, + {"exit", _exitContext.ExtractStatus()}, + {"links", _linkManager.ExtractStatus()}, + {"outboundMessages", _outboundMessageHandler.ExtractStatus()}}; } else { @@ -100,13 +99,12 @@ namespace llarp } bool - Router::HandleRecvLinkMessageBuffer(ILinkSession *session, - const llarp_buffer_t &buf) + Router::HandleRecvLinkMessageBuffer(ILinkSession* session, const llarp_buffer_t& buf) { - if(_stopping) + if (_stopping) return true; - if(!session) + if (!session) { LogWarn("no link session"); return false; @@ -115,7 +113,7 @@ namespace llarp } void - Router::PersistSessionUntil(const RouterID &remote, llarp_time_t until) + Router::PersistSessionUntil(const RouterID& remote, llarp_time_t until) { _linkManager.PersistSessionUntil(remote, until); } @@ -124,28 +122,28 @@ namespace llarp Router::GossipRCIfNeeded(const RouterContact rc) { /// if we are not a service node forget about gossip - if(not IsServiceNode()) + if (not IsServiceNode()) return; /// wait for random uptime - if(std::chrono::milliseconds{Uptime()} < _randomStartDelay) + if (std::chrono::milliseconds{Uptime()} < _randomStartDelay) return; _rcGossiper.GossipRC(rc); } bool - Router::GetRandomGoodRouter(RouterID &router) + Router::GetRandomGoodRouter(RouterID& router) { - if(whitelistRouters) + if (whitelistRouters) { return _rcLookupHandler.GetRandomWhitelistRouter(router); } - auto pick_router = [&](auto &collection) -> bool { + auto pick_router = [&](auto& collection) -> bool { const auto sz = collection.size(); - auto itr = collection.begin(); - if(sz == 0) + auto itr = collection.begin(); + if (sz == 0) return false; - if(sz > 1) + if (sz > 1) std::advance(itr, randint() % sz); router = itr->first; return true; @@ -159,12 +157,11 @@ namespace llarp Router::PumpLL() { static constexpr size_t PumpJobThreshhold = 50; - static constexpr auto PumpInterval = 25ms; - const auto now = Now(); - if(_stopping.load()) + static constexpr auto PumpInterval = 25ms; + const auto now = Now(); + if (_stopping.load()) return; - if(_logic->numPendingJobs() >= PumpJobThreshhold - && _lastPump + PumpInterval >= now) + if (_logic->numPendingJobs() >= PumpJobThreshhold && _lastPump + PumpInterval >= now) { return; } @@ -178,10 +175,9 @@ namespace llarp } bool - Router::SendToOrQueue(const RouterID &remote, const ILinkMessage *msg, - SendStatusHandler handler) + Router::SendToOrQueue(const RouterID& remote, const ILinkMessage* msg, SendStatusHandler handler) { - if(handler == nullptr) + if (handler == nullptr) { using std::placeholders::_1; handler = std::bind(&Router::MessageSent, this, remote, _1); @@ -190,14 +186,13 @@ namespace llarp } void - Router::ForEachPeer(std::function< void(const ILinkSession *, bool) > visit, - bool randomize) const + Router::ForEachPeer(std::function visit, bool randomize) const { _linkManager.ForEachPeer(visit, randomize); } void - Router::ForEachPeer(std::function< void(ILinkSession *) > visit) + Router::ForEachPeer(std::function visit) { _linkManager.ForEachPeer(visit); } @@ -206,12 +201,12 @@ namespace llarp Router::try_connect(fs::path rcfile) { RouterContact remote; - if(!remote.Read(rcfile.string().c_str())) + if (!remote.Read(rcfile.string().c_str())) { LogError("failure to decode or verify of remote RC"); return; } - if(remote.Verify(Now())) + if (remote.Verify(Now())) { LogDebug("verified signature"); _outboundSessionMaker.CreateSessionTo(remote, nullptr); @@ -223,7 +218,7 @@ namespace llarp bool Router::EnsureIdentity() { - if(whitelistRouters) + if (whitelistRouters) { #if defined(ANDROID) || defined(IOS) LogError("running a service node on mobile device is not possible."); @@ -236,35 +231,34 @@ namespace llarp #endif } - _identity = m_keyManager->identityKey; + _identity = m_keyManager->identityKey; _encryption = m_keyManager->encryptionKey; - if(_identity.IsZero()) + if (_identity.IsZero()) return false; - if(_encryption.IsZero()) + if (_encryption.IsZero()) return false; return true; } bool - Router::Configure(Config *conf, llarp_nodedb *nodedb) + Router::Configure(Config* conf, llarp_nodedb* nodedb) { - if(nodedb == nullptr) + if (nodedb == nullptr) { - LogError( - "Attempting to Router::Configure but passed null nodedb pointer"); + LogError("Attempting to Router::Configure but passed null nodedb pointer"); return false; } _nodedb = nodedb; - if(not m_keyManager->initialize(*conf, true)) + if (not m_keyManager->initialize(*conf, true)) return false; - if(!FromConfig(conf)) + if (!FromConfig(conf)) return false; - if(!InitOutboundLinks()) + if (!InitOutboundLinks()) return false; return EnsureIdentity(); @@ -282,9 +276,9 @@ namespace llarp Router::SaveRC() { LogDebug("verify RC signature"); - if(!_rc.Verify(Now())) + if (!_rc.Verify(Now())) { - Dump< MAX_RC_SIZE >(rc()); + Dump(rc()); LogError("RC is invalid, not saving"); return false; } @@ -317,15 +311,14 @@ namespace llarp } bool - Router::ParseRoutingMessageBuffer(const llarp_buffer_t &buf, - routing::IMessageHandler *h, - const PathID_t &rxid) + Router::ParseRoutingMessageBuffer( + const llarp_buffer_t& buf, routing::IMessageHandler* h, const PathID_t& rxid) { return inbound_routing_msg_parser.ParseMessageBuffer(buf, h, rxid, this); } bool - Router::ConnectionToRouterAllowed(const RouterID &router) const + Router::ConnectionToRouterAllowed(const RouterID& router) const { return _rcLookupHandler.RemoteIsAllowed(router); } @@ -347,27 +340,27 @@ namespace llarp { SecretKey nextOnionKey; RouterContact nextRC = _rc; - if(rotateKeys) + if (rotateKeys) { CryptoManager::instance()->encryption_keygen(nextOnionKey); std::string f = encryption_keyfile.string(); // TODO: use disk worker - if(nextOnionKey.SaveToFile(f.c_str())) + if (nextOnionKey.SaveToFile(f.c_str())) { nextRC.enckey = seckey_topublic(nextOnionKey); - _encryption = nextOnionKey; + _encryption = nextOnionKey; } } - if(!nextRC.Sign(identity())) + if (!nextRC.Sign(identity())) return false; - if(!nextRC.Verify(time_now_ms(), false)) + if (!nextRC.Verify(time_now_ms(), false)) return false; _rc = std::move(nextRC); - if(rotateKeys) + if (rotateKeys) { // propagate RC by renegotiating sessions - ForEachPeer([](ILinkSession *s) { - if(s->RenegotiateSession()) + ForEachPeer([](ILinkSession* s) { + if (s->RenegotiateSession()) LogInfo("renegotiated session"); else LogWarn("failed to renegotiate session"); @@ -377,88 +370,86 @@ namespace llarp } bool - Router::FromConfig(Config *conf) + Router::FromConfig(Config* conf) { // Set netid before anything else - if(!conf->router.netId().empty() - && strcmp(conf->router.netId().c_str(), llarp::DEFAULT_NETID)) + if (!conf->router.netId().empty() && strcmp(conf->router.netId().c_str(), llarp::DEFAULT_NETID)) { - const auto &netid = conf->router.netId(); - llarp::LogWarn("!!!! you have manually set netid to be '", netid, - "' which does not equal '", llarp::DEFAULT_NETID, - "' you will run as a different network, good luck " - "and don't forget: something something MUH traffic " - "shape correlation !!!!"); - NetID::DefaultValue() = - NetID(reinterpret_cast< const byte_t * >(netid.c_str())); + const auto& netid = conf->router.netId(); + llarp::LogWarn( + "!!!! you have manually set netid to be '", + netid, + "' which does not equal '", + llarp::DEFAULT_NETID, + "' you will run as a different network, good luck " + "and don't forget: something something MUH traffic " + "shape correlation !!!!"); + NetID::DefaultValue() = NetID(reinterpret_cast(netid.c_str())); // reset netid in our rc _rc.netID = llarp::NetID(); } const auto linktypename = conf->router.defaultLinkProto(); - _defaultLinkType = LinkFactory::TypeFromName(linktypename); - if(_defaultLinkType == LinkFactory::LinkType::eLinkUnknown) + _defaultLinkType = LinkFactory::TypeFromName(linktypename); + if (_defaultLinkType == LinkFactory::LinkType::eLinkUnknown) { - LogError("failed to set link type to '", linktypename, - "' as that is invalid"); + LogError("failed to set link type to '", linktypename, "' as that is invalid"); return false; } // IWP config - m_OutboundPort = std::get< LinksConfig::Port >(conf->links.outboundLink()); + m_OutboundPort = std::get(conf->links.outboundLink()); // Router config _rc.SetNick(conf->router.nickname()); - _outboundSessionMaker.maxConnectedRouters = - conf->router.maxConnectedRouters(); - _outboundSessionMaker.minConnectedRouters = - conf->router.minConnectedRouters(); + _outboundSessionMaker.maxConnectedRouters = conf->router.maxConnectedRouters(); + _outboundSessionMaker.minConnectedRouters = conf->router.minConnectedRouters(); encryption_keyfile = conf->router.encryptionKeyfile(); - our_rc_file = conf->router.ourRcFile(); - transport_keyfile = conf->router.transportKeyfile(); - addrInfo = conf->router.addrInfo(); - publicOverride = conf->router.publicOverride(); - ip4addr = conf->router.ip4addr(); + our_rc_file = conf->router.ourRcFile(); + transport_keyfile = conf->router.transportKeyfile(); + addrInfo = conf->router.addrInfo(); + publicOverride = conf->router.publicOverride(); + ip4addr = conf->router.ip4addr(); - if(!conf->router.blockBogons().value_or(true)) + if (!conf->router.blockBogons().value_or(true)) { RouterContact::BlockBogons = false; } // Lokid Config - usingSNSeed = conf->lokid.usingSNSeed; - ident_keyfile = conf->lokid.ident_keyfile; + usingSNSeed = conf->lokid.usingSNSeed; + ident_keyfile = conf->lokid.ident_keyfile; whitelistRouters = conf->lokid.whitelistRouters; - lokidRPCAddr = conf->lokid.lokidRPCAddr; - lokidRPCUser = conf->lokid.lokidRPCUser; + lokidRPCAddr = conf->lokid.lokidRPCAddr; + lokidRPCUser = conf->lokid.lokidRPCUser; lokidRPCPassword = conf->lokid.lokidRPCPassword; // TODO: add config flag for "is service node" - if(conf->links.inboundLinks().size()) + if (conf->links.inboundLinks().size()) { m_isServiceNode = true; } - std::set< RouterID > strictConnectPubkeys; + std::set strictConnectPubkeys; - if(!conf->network.strictConnect().empty()) + if (!conf->network.strictConnect().empty()) { - const auto &val = conf->network.strictConnect(); - if(IsServiceNode()) + const auto& val = conf->network.strictConnect(); + if (IsServiceNode()) { llarp::LogError("cannot use strict-connect option as service node"); return false; } llarp::RouterID snode; llarp::PubKey pk; - if(pk.FromString(val)) + if (pk.FromString(val)) { - if(strictConnectPubkeys.emplace(pk).second) + if (strictConnectPubkeys.emplace(pk).second) llarp::LogInfo("added ", pk, " to strict connect list"); else llarp::LogWarn("duplicate key for strict connect: ", pk); } - else if(snode.FromString(val)) + else if (snode.FromString(val)) { - if(strictConnectPubkeys.insert(snode).second) + if (strictConnectPubkeys.insert(snode).second) { llarp::LogInfo("added ", snode, " to strict connect list"); netConfig.emplace("strict-connect", val); @@ -470,26 +461,25 @@ namespace llarp llarp::LogError("invalid key for strict-connect: ", val); } - llarp::LogWarn("Bootstrap routers list size: ", - conf->bootstrap.routers.size()); - std::vector< std::string > configRouters = conf->connect.routers; - configRouters.insert(configRouters.end(), conf->bootstrap.routers.begin(), - conf->bootstrap.routers.end()); + llarp::LogWarn("Bootstrap routers list size: ", conf->bootstrap.routers.size()); + std::vector configRouters = conf->connect.routers; + configRouters.insert( + configRouters.end(), conf->bootstrap.routers.begin(), conf->bootstrap.routers.end()); BootstrapList b_list; - for(const auto &router : configRouters) + for (const auto& router : configRouters) { bool isListFile = false; { std::ifstream inf(router, std::ios::binary); - if(inf.is_open()) + if (inf.is_open()) { const char ch = inf.get(); - isListFile = ch == 'l'; + isListFile = ch == 'l'; } } - if(isListFile) + if (isListFile) { - if(not BDecodeReadFile(router.c_str(), b_list)) + if (not BDecodeReadFile(router.c_str(), b_list)) { LogWarn("failed to read bootstrap list file '", router, "'"); return false; @@ -498,19 +488,18 @@ namespace llarp else { RouterContact rc; - if(not rc.Read(router.c_str())) + if (not rc.Read(router.c_str())) { - llarp::LogWarn("failed to decode bootstrap RC, file='", router, - "' rc=", rc); + llarp::LogWarn("failed to decode bootstrap RC, file='", router, "' rc=", rc); return false; } b_list.insert(rc); } } - for(auto &rc : b_list) + for (auto& rc : b_list) { - if(not rc.Verify(Now())) + if (not rc.Verify(Now())) { LogWarn("ignoring invalid RC: ", RouterID(rc.pubkey)); continue; @@ -522,34 +511,40 @@ namespace llarp // Init components after relevant config settings loaded _outboundMessageHandler.Init(&_linkManager, _logic); - _outboundSessionMaker.Init(&_linkManager, &_rcLookupHandler, - &_routerProfiling, _logic, _nodedb, - threadpool()); + _outboundSessionMaker.Init( + &_linkManager, &_rcLookupHandler, &_routerProfiling, _logic, _nodedb, threadpool()); _linkManager.Init(&_outboundSessionMaker); - _rcLookupHandler.Init(_dht, _nodedb, threadpool(), &_linkManager, - &_hiddenServiceContext, strictConnectPubkeys, - bootstrapRCList, whitelistRouters, m_isServiceNode); - - if(!usingSNSeed) + _rcLookupHandler.Init( + _dht, + _nodedb, + threadpool(), + &_linkManager, + &_hiddenServiceContext, + strictConnectPubkeys, + bootstrapRCList, + whitelistRouters, + m_isServiceNode); + + if (!usingSNSeed) { ident_keyfile = conf->router.identKeyfile(); } // create inbound links, if we are a service node - for(const auto &serverConfig : conf->links.inboundLinks()) + for (const auto& serverConfig : conf->links.inboundLinks()) { // get default factory auto inboundLinkFactory = LinkFactory::Obtain(_defaultLinkType, true); // for each option if provided ... - for(const auto &opt : std::get< LinksConfig::Options >(serverConfig)) + for (const auto& opt : std::get(serverConfig)) { // try interpreting it as a link type const auto linktype = LinkFactory::TypeFromName(opt); - if(linktype != LinkFactory::LinkType::eLinkUnknown) + if (linktype != LinkFactory::LinkType::eLinkUnknown) { // override link factory if it's a valid link type auto factory = LinkFactory::Obtain(linktype, true); - if(factory) + if (factory) { inboundLinkFactory = std::move(factory); break; @@ -558,22 +553,21 @@ namespace llarp } auto server = inboundLinkFactory( - m_keyManager, util::memFn(&AbstractRouter::rc, this), + m_keyManager, + util::memFn(&AbstractRouter::rc, this), util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this), util::memFn(&AbstractRouter::Sign, this), - util::memFn(&IOutboundSessionMaker::OnSessionEstablished, - &_outboundSessionMaker), + util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker), util::memFn(&AbstractRouter::CheckRenegotiateValid, this), - util::memFn(&IOutboundSessionMaker::OnConnectTimeout, - &_outboundSessionMaker), + util::memFn(&IOutboundSessionMaker::OnConnectTimeout, &_outboundSessionMaker), util::memFn(&AbstractRouter::SessionClosed, this), util::memFn(&AbstractRouter::PumpLL, this)); - const auto &key = std::get< LinksConfig::Interface >(serverConfig); - int af = std::get< LinksConfig::AddressFamily >(serverConfig); - uint16_t port = std::get< LinksConfig::Port >(serverConfig); + const auto& key = std::get(serverConfig); + int af = std::get(serverConfig); + uint16_t port = std::get(serverConfig); llarp::LogWarn("tun: ", key, " -- af: ", af, " -- port: ", port); - if(!server->Configure(netloop(), key, af, port)) + if (!server->Configure(netloop(), key, af, port)) { LogError("failed to bind inbound link on ", key, " port ", port); return false; @@ -585,16 +579,16 @@ namespace llarp netConfig = conf->network.netConfig(); // Network config - if(conf->network.enableProfiling().has_value()) + if (conf->network.enableProfiling().has_value()) { - if(not conf->network.enableProfiling().value()) + if (not conf->network.enableProfiling().value()) { routerProfiling().Disable(); LogWarn("router profiling explicitly disabled"); } } - if(!conf->network.routerProfilesFile().empty()) + if (!conf->network.routerProfilesFile().empty()) { routerProfilesFile = conf->network.routerProfilesFile(); routerProfiling().Load(routerProfilesFile.c_str()); @@ -603,19 +597,18 @@ namespace llarp // API config enableRPCServer = conf->api.enableRPCServer(); - rpcBindAddr = conf->api.rpcBindAddr(); + rpcBindAddr = conf->api.rpcBindAddr(); // Services config - for(const auto &service : conf->services.services) + for (const auto& service : conf->services.services) { - if(LoadHiddenServiceConfig(service.second)) + if (LoadHiddenServiceConfig(service.second)) { llarp::LogInfo("loaded hidden service config for ", service.first); } else { - llarp::LogWarn("failed to load hidden service config for ", - service.first); + llarp::LogWarn("failed to load hidden service config for ", service.first); } } @@ -623,15 +616,15 @@ namespace llarp auto logfile = conf->logging.m_LogFile; - if(conf->logging.m_LogJSON) + if (conf->logging.m_LogJSON) { - LogContext::Instance().logStream = std::make_unique< JSONLogStream >( - diskworker(), logfile, 100ms, logfile != stdout); + LogContext::Instance().logStream = + std::make_unique(diskworker(), logfile, 100ms, logfile != stdout); } - else if(logfile != stdout) + else if (logfile != stdout) { LogContext::Instance().logStream = - std::make_unique< FileLogStream >(diskworker(), logfile, 100ms, true); + std::make_unique(diskworker(), logfile, 100ms, true); } netConfig.insert(conf->dns.netConfig.begin(), conf->dns.netConfig.end()); @@ -649,8 +642,9 @@ namespace llarp Router::IsBootstrapNode(const RouterID r) const { return std::count_if( - bootstrapRCList.begin(), bootstrapRCList.end(), - [r](const RouterContact &rc) -> bool { return rc.pubkey == r; }) + bootstrapRCList.begin(), + bootstrapRCList.end(), + [r](const RouterContact& rc) -> bool { return rc.pubkey == r; }) > 0; } @@ -668,7 +662,7 @@ namespace llarp LogInfo(nodedb()->num_loaded(), " RCs loaded"); LogInfo(bootstrapRCList.size(), " bootstrap peers"); LogInfo(NumberOfConnectedRouters(), " router connections"); - if(IsServiceNode()) + if (IsServiceNode()) { LogInfo(NumberOfConnectedClients(), " client connections"); LogInfo(_rc.Age(now), " since we last updated our RC"); @@ -681,7 +675,7 @@ namespace llarp void Router::Tick() { - if(_stopping) + if (_stopping) return; // LogDebug("tick router"); const auto now = Now(); @@ -690,22 +684,21 @@ namespace llarp { std::stringstream ss; ss << "WATCHDOG=1\nSTATUS=v" << llarp::VERSION_STR; - if(IsServiceNode()) + if (IsServiceNode()) { ss << " snode | known/svc/clients: " << nodedb()->num_loaded() << "/" - << NumberOfConnectedRouters() << "/" << NumberOfConnectedClients() - << " | " << pathContext().CurrentTransitPaths() << " active paths"; + << NumberOfConnectedRouters() << "/" << NumberOfConnectedClients() << " | " + << pathContext().CurrentTransitPaths() << " active paths"; } else { ss << " client | known/connected: " << nodedb()->num_loaded() << "/" << NumberOfConnectedRouters() << " | path success: "; - hiddenServiceContext().ForEachService( - [&ss](const auto &name, const auto &ep) { - ss << " [" << name << " " << std::setprecision(4) - << (100.0 * ep->CurrentBuildStats().SuccessRatio()) << "%]"; - return true; - }); + hiddenServiceContext().ForEachService([&ss](const auto& name, const auto& ep) { + ss << " [" << name << " " << std::setprecision(4) + << (100.0 * ep->CurrentBuildStats().SuccessRatio()) << "%]"; + return true; + }); } const auto status = ss.str(); ::sd_notify(0, status.c_str()); @@ -714,7 +707,7 @@ namespace llarp routerProfiling().Tick(); - if(ShouldReportStats(now)) + if (ShouldReportStats(now)) { ReportStats(); } @@ -725,11 +718,11 @@ namespace llarp const bool isSvcNode = IsServiceNode(); - if(_rc.ExpiresSoon(now, std::chrono::milliseconds(randint() % 10000)) - || (now - _rc.last_updated) > rcRegenInterval) + if (_rc.ExpiresSoon(now, std::chrono::milliseconds(randint() % 10000)) + || (now - _rc.last_updated) > rcRegenInterval) { LogInfo("regenerating RC"); - if(!UpdateOurRC(false)) + if (!UpdateOurRC(false)) LogError("Failed to update our RC"); } else @@ -738,22 +731,22 @@ namespace llarp } const bool gotWhitelist = _rcLookupHandler.HaveReceivedWhitelist(); // remove RCs for nodes that are no longer allowed by network policy - nodedb()->RemoveIf([&](const RouterContact &rc) -> bool { + nodedb()->RemoveIf([&](const RouterContact& rc) -> bool { // don't purge bootstrap nodes from nodedb - if(IsBootstrapNode(rc.pubkey)) + if (IsBootstrapNode(rc.pubkey)) return false; // if for some reason we stored an RC that isn't a valid router // purge this entry - if(not rc.IsPublicRouter()) + if (not rc.IsPublicRouter()) return true; // clients have a notion of a whilelist // we short circuit logic here so we dont remove // routers that are not whitelisted for first hops - if(not isSvcNode) + if (not isSvcNode) return false; // if we have a whitelist enabled and we don't // have the whitelist yet don't remove the entry - if(whitelistRouters and not gotWhitelist) + if (whitelistRouters and not gotWhitelist) return false; // if we have no whitelist enabled or we have // the whitelist enabled and we got the whitelist @@ -765,26 +758,26 @@ namespace llarp _linkManager.CheckPersistingSessions(now); size_t connected = NumberOfConnectedRouters(); - if(not isSvcNode) + if (not isSvcNode) { connected += _linkManager.NumberOfPendingConnections(); } - const int interval = isSvcNode ? 5 : 2; + const int interval = isSvcNode ? 5 : 2; const auto timepoint_now = Clock_t::now(); - if(timepoint_now >= m_NextExploreAt) + if (timepoint_now >= m_NextExploreAt) { _rcLookupHandler.ExploreNetwork(); m_NextExploreAt = timepoint_now + std::chrono::seconds(interval); } - size_t connectToNum = _outboundSessionMaker.minConnectedRouters; + size_t connectToNum = _outboundSessionMaker.minConnectedRouters; const auto strictConnect = _rcLookupHandler.NumberOfStrictConnectRouters(); - if(strictConnect > 0 && connectToNum > strictConnect) + if (strictConnect > 0 && connectToNum > strictConnect) { connectToNum = strictConnect; } - if(connected < connectToNum) + if (connected < connectToNum) { size_t dlt = connectToNum - connected; LogInfo("connecting to ", dlt, " random routers to keep alive"); @@ -794,31 +787,29 @@ namespace llarp _hiddenServiceContext.Tick(now); _exitContext.Tick(now); - if(rpcCaller) + if (rpcCaller) rpcCaller->Tick(now); // save profiles - if(routerProfiling().ShouldSave(now)) + if (routerProfiling().ShouldSave(now)) { - diskworker()->addJob( - [&]() { routerProfiling().Save(routerProfilesFile.c_str()); }); + diskworker()->addJob([&]() { routerProfiling().Save(routerProfilesFile.c_str()); }); } // save nodedb - if(nodedb()->ShouldSaveToDisk(now)) + if (nodedb()->ShouldSaveToDisk(now)) { nodedb()->AsyncFlushToDisk(); } // get connected peers - std::set< dht::Key_t > peersWeHave; - _linkManager.ForEachPeer([&peersWeHave](ILinkSession *s) { - if(!s->IsEstablished()) + std::set peersWeHave; + _linkManager.ForEachPeer([&peersWeHave](ILinkSession* s) { + if (!s->IsEstablished()) return; peersWeHave.emplace(s->GetPubKey()); }); // remove any nodes we don't have connections to - _dht->impl->Nodes()->RemoveIf([&peersWeHave](const dht::Key_t &k) -> bool { - return peersWeHave.count(k) == 0; - }); + _dht->impl->Nodes()->RemoveIf( + [&peersWeHave](const dht::Key_t& k) -> bool { return peersWeHave.count(k) == 0; }); // expire paths paths.ExpirePaths(now); // update tick timestamp @@ -826,7 +817,7 @@ namespace llarp } bool - Router::Sign(Signature &sig, const llarp_buffer_t &buf) const + Router::Sign(Signature& sig, const llarp_buffer_t& buf) const { return CryptoManager::instance()->sign(sig, identity(), buf); } @@ -834,8 +825,7 @@ namespace llarp void Router::ScheduleTicker(llarp_time_t interval) { - ticker_job_id = _logic->call_later( - interval, std::bind(&Router::handle_router_ticker, this)); + ticker_job_id = _logic->call_later(interval, std::bind(&Router::handle_router_ticker, this)); } void @@ -848,16 +838,15 @@ namespace llarp } bool - Router::GetRandomConnectedRouter(RouterContact &result) const + Router::GetRandomConnectedRouter(RouterContact& result) const { return _linkManager.GetRandomConnectedRouter(result); } void - Router::HandleDHTLookupForExplore(RouterID /*remote*/, - const std::vector< RouterContact > &results) + Router::HandleDHTLookupForExplore(RouterID /*remote*/, const std::vector& results) { - for(const auto &rc : results) + for (const auto& rc : results) { _rcLookupHandler.CheckRC(rc); } @@ -869,13 +858,12 @@ namespace llarp { _rcLookupHandler.GetRC( remote, - [=](const RouterID &id, const RouterContact *const rc, - const RCRequestResult result) { + [=](const RouterID& id, const RouterContact* const rc, const RCRequestResult result) { (void)id; - if(resultHandler) + if (resultHandler) { - std::vector< RouterContact > routers; - if(result == RCRequestResult::Success && rc != nullptr) + std::vector routers; + if (result == RCRequestResult::Success && rc != nullptr) { routers.push_back(*rc); } @@ -885,31 +873,28 @@ namespace llarp } void - Router::SetRouterWhitelist(const std::vector< RouterID > &routers) + Router::SetRouterWhitelist(const std::vector& routers) { _rcLookupHandler.SetRouterWhitelist(routers); } /// this function ensure there are sane defualts in a net config static void - EnsureNetConfigDefaultsSane( - std::unordered_multimap< std::string, std::string > &netConfig) + EnsureNetConfigDefaultsSane(std::unordered_multimap& netConfig) { - static const std::unordered_map< std::string, - std::function< std::string(void) > > - netConfigDefaults = { - {"ifname", llarp::FindFreeTun}, - {"ifaddr", llarp::FindFreeRange}, - {"local-dns", []() -> std::string { return "127.0.0.1:53"; }}}; + static const std::unordered_map> + netConfigDefaults = {{"ifname", llarp::FindFreeTun}, + {"ifaddr", llarp::FindFreeRange}, + {"local-dns", []() -> std::string { return "127.0.0.1:53"; }}}; // populate with fallback defaults if values not present auto itr = netConfigDefaults.begin(); - while(itr != netConfigDefaults.end()) + while (itr != netConfigDefaults.end()) { auto found = netConfig.find(itr->first); - if(found == netConfig.end() || found->second.empty()) + if (found == netConfig.end() || found->second.empty()) { auto val = itr->second(); - if(!val.empty()) + if (!val.empty()) netConfig.emplace(itr->first, std::move(val)); } ++itr; @@ -919,17 +904,17 @@ namespace llarp bool Router::StartJsonRpc() { - if(_running || _stopping) + if (_running || _stopping) return false; - if(enableRPCServer) + if (enableRPCServer) { - if(rpcBindAddr.empty()) + if (rpcBindAddr.empty()) { rpcBindAddr = DefaultRPCBindAddr; } - rpcServer = std::make_unique< rpc::Server >(this); - while(!rpcServer->Start(rpcBindAddr)) + rpcServer = std::make_unique(this); + while (!rpcServer->Start(rpcBindAddr)) { LogError("failed to bind jsonrpc to ", rpcBindAddr); #if defined(ANDROID) || defined(RPI) @@ -947,14 +932,14 @@ namespace llarp bool Router::Run() { - if(_running || _stopping) + if (_running || _stopping) return false; - if(whitelistRouters) + if (whitelistRouters) { - rpcCaller = std::make_unique< rpc::Caller >(this); + rpcCaller = std::make_unique(this); rpcCaller->SetAuth(lokidRPCUser, lokidRPCPassword); - while(!rpcCaller->Start(lokidRPCAddr)) + while (!rpcCaller->Start(lokidRPCAddr)) { LogError("failed to start jsonrpc caller to ", lokidRPCAddr); #if defined(ANDROID) || defined(RPI) @@ -966,13 +951,13 @@ namespace llarp LogInfo("RPC Caller to ", lokidRPCAddr, " started"); } - if(!cryptoworker->start()) + if (!cryptoworker->start()) { LogError("crypto worker failed to start"); return false; } - if(!disk->start()) + if (!disk->start()) { LogError("disk worker failed to start"); return false; @@ -982,7 +967,7 @@ namespace llarp Addr publicAddr(this->addrInfo); - if(this->publicOverride) + if (this->publicOverride) { LogDebug("public address:port ", publicAddr); } @@ -990,25 +975,25 @@ namespace llarp // set public signing key _rc.pubkey = seckey_topublic(identity()); // set router version if service node - if(IsServiceNode()) + if (IsServiceNode()) { _rc.routerVersion = RouterVersion(llarp::VERSION, LLARP_PROTO_VERSION); } AddressInfo ai; _linkManager.ForEachInboundLink([&](LinkLayer_ptr link) { - if(link->GetOurAddressInfo(ai)) + if (link->GetOurAddressInfo(ai)) { // override ip and port - if(this->publicOverride) + if (this->publicOverride) { - ai.ip = *publicAddr.addr6(); + ai.ip = *publicAddr.addr6(); ai.port = publicAddr.port(); } - if(RouterContact::BlockBogons && IsBogon(ai.ip)) + if (RouterContact::BlockBogons && IsBogon(ai.ip)) return; _rc.addrs.push_back(ai); - if(ExitEnabled()) + if (ExitEnabled()) { const llarp::Addr addr(ai); const nuint32_t a{addr.addr4()->s_addr}; @@ -1022,19 +1007,19 @@ namespace llarp _rc.enckey = seckey_topublic(encryption()); LogInfo("Signing rc..."); - if(!_rc.Sign(identity())) + if (!_rc.Sign(identity())) { LogError("failed to sign rc"); return false; } - if(!SaveRC()) + if (!SaveRC()) { LogError("failed to save RC"); return false; } _outboundSessionMaker.SetOurRouter(pubkey()); - if(!_linkManager.StartLinks(_logic, cryptoworker)) + if (!_linkManager.StartLinks(_logic, cryptoworker)) { LogWarn("One or more links failed to start."); return false; @@ -1042,18 +1027,17 @@ namespace llarp EnsureNetConfigDefaultsSane(netConfig); - const auto limits = - IsServiceNode() ? llarp::limits::snode : llarp::limits::client; + const auto limits = IsServiceNode() ? llarp::limits::snode : llarp::limits::client; - _outboundSessionMaker.minConnectedRouters = std::max( - _outboundSessionMaker.minConnectedRouters, limits.DefaultMinRouters); - _outboundSessionMaker.maxConnectedRouters = std::max( - _outboundSessionMaker.maxConnectedRouters, limits.DefaultMaxRouters); + _outboundSessionMaker.minConnectedRouters = + std::max(_outboundSessionMaker.minConnectedRouters, limits.DefaultMinRouters); + _outboundSessionMaker.maxConnectedRouters = + std::max(_outboundSessionMaker.maxConnectedRouters, limits.DefaultMaxRouters); - if(IsServiceNode()) + if (IsServiceNode()) { // initialize as service node - if(!InitServiceNode()) + if (!InitServiceNode()) { LogError("Failed to initialize service node"); return false; @@ -1073,13 +1057,13 @@ namespace llarp CryptoManager::instance()->encryption_keygen(_encryption); _rc.pubkey = seckey_topublic(identity()); _rc.enckey = seckey_topublic(encryption()); - if(!_rc.Sign(identity())) + if (!_rc.Sign(identity())) { LogError("failed to regenerate keys and sign RC"); return false; } - if(!CreateDefaultHiddenService()) + if (!CreateDefaultHiddenService()) { LogError("failed to set up default network endpoint"); return false; @@ -1087,7 +1071,7 @@ namespace llarp } LogInfo("starting hidden service context..."); - if(!hiddenServiceContext().StartAll()) + if (!hiddenServiceContext().StartAll()) { LogError("Failed to start hidden service context"); return false; @@ -1096,7 +1080,7 @@ namespace llarp { ssize_t loaded = _nodedb->LoadAll(); llarp::LogInfo("loaded ", loaded, " RCs"); - if(loaded < 0) + if (loaded < 0) { // shouldn't be possible return false; @@ -1105,9 +1089,9 @@ namespace llarp llarp_dht_context_start(dht(), pubkey()); - for(const auto &rc : bootstrapRCList) + for (const auto& rc : bootstrapRCList) { - if(this->nodedb()->Insert(rc)) + if (this->nodedb()->Insert(rc)) { LogInfo("added bootstrap node ", RouterID(rc.pubkey)); } @@ -1142,7 +1126,7 @@ namespace llarp Router::Uptime() const { const llarp_time_t _now = Now(); - if(_startedAt > 0s && _now > _startedAt) + if (_startedAt > 0s && _now > _startedAt) return _now - _startedAt; return 0s; } @@ -1170,9 +1154,9 @@ namespace llarp void Router::Stop() { - if(!_running) + if (!_running) return; - if(_stopping) + if (_stopping) return; _stopping.store(true); @@ -1183,7 +1167,7 @@ namespace llarp #endif hiddenServiceContext().StopAll(); _exitContext.Stop(); - if(rpcServer) + if (rpcServer) rpcServer->Stop(); paths.PumpUpstream(); _linkManager.PumpLinks(); @@ -1191,7 +1175,7 @@ namespace llarp } bool - Router::HasSessionTo(const RouterID &remote) const + Router::HasSessionTo(const RouterID& remote) const { return _linkManager.HasSessionTo(remote); } @@ -1212,12 +1196,12 @@ namespace llarp Router::ConnectToRandomRouters(int _want) { const size_t want = _want; - auto connected = NumberOfConnectedRouters(); - if(not IsServiceNode()) + auto connected = NumberOfConnectedRouters(); + if (not IsServiceNode()) { connected += _linkManager.NumberOfPendingConnections(); } - if(connected >= want) + if (connected >= want) return; _outboundSessionMaker.ConnectToRandomRouters(want); } @@ -1232,13 +1216,13 @@ namespace llarp } bool - Router::ValidateConfig(Config * /*conf*/) const + Router::ValidateConfig(Config* /*conf*/) const { return true; } bool - Router::Reconfigure(Config *) + Router::Reconfigure(Config*) { // TODO: implement me return true; @@ -1249,12 +1233,12 @@ namespace llarp { (void)tries; - if(rc.pubkey == pubkey()) + if (rc.pubkey == pubkey()) { return false; } - if(!_rcLookupHandler.RemoteIsAllowed(rc.pubkey)) + if (!_rcLookupHandler.RemoteIsAllowed(rc.pubkey)) { return false; } @@ -1270,32 +1254,33 @@ namespace llarp const auto linkTypeName = LinkFactory::NameFromType(_defaultLinkType); LogInfo("initialize outbound link: ", linkTypeName); auto factory = LinkFactory::Obtain(_defaultLinkType, false); - if(factory == nullptr) + if (factory == nullptr) { - LogError("cannot initialize outbound link of type '", linkTypeName, - "' as it has no implementation"); + LogError( + "cannot initialize outbound link of type '", + linkTypeName, + "' as it has no implementation"); return false; } - auto link = - factory(m_keyManager, util::memFn(&AbstractRouter::rc, this), - util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this), - util::memFn(&AbstractRouter::Sign, this), - util::memFn(&IOutboundSessionMaker::OnSessionEstablished, - &_outboundSessionMaker), - util::memFn(&AbstractRouter::CheckRenegotiateValid, this), - util::memFn(&IOutboundSessionMaker::OnConnectTimeout, - &_outboundSessionMaker), - util::memFn(&AbstractRouter::SessionClosed, this), - util::memFn(&AbstractRouter::PumpLL, this)); - - if(!link) + auto link = factory( + m_keyManager, + util::memFn(&AbstractRouter::rc, this), + util::memFn(&AbstractRouter::HandleRecvLinkMessageBuffer, this), + util::memFn(&AbstractRouter::Sign, this), + util::memFn(&IOutboundSessionMaker::OnSessionEstablished, &_outboundSessionMaker), + util::memFn(&AbstractRouter::CheckRenegotiateValid, this), + util::memFn(&IOutboundSessionMaker::OnConnectTimeout, &_outboundSessionMaker), + util::memFn(&AbstractRouter::SessionClosed, this), + util::memFn(&AbstractRouter::PumpLL, this)); + + if (!link) return false; const auto afs = {AF_INET, AF_INET6}; - for(const auto af : afs) + for (const auto af : afs) { - if(!link->Configure(netloop(), "*", af, m_OutboundPort)) + if (!link->Configure(netloop(), "*", af, m_OutboundPort)) continue; _linkManager.AddLink(std::move(link), false); return true; @@ -1315,23 +1300,23 @@ namespace llarp { LogDebug("opening hidden service config ", fname); service::Config conf; - if(!conf.Load(fname)) + if (!conf.Load(fname)) return false; - for(const auto &config : conf.services) + for (const auto& config : conf.services) { service::Config::section_t filteredConfig; mergeHiddenServiceConfig(config.second, filteredConfig.second); filteredConfig.first = config.first; - if(!hiddenServiceContext().AddEndpoint(filteredConfig)) + if (!hiddenServiceContext().AddEndpoint(filteredConfig)) return false; } return true; } void - Router::MessageSent(const RouterID &remote, SendStatus status) + Router::MessageSent(const RouterID& remote, SendStatus status) { - if(status == SendStatus::Success) + if (status == SendStatus::Success) { LogDebug("Message successfully sent to ", remote); } diff --git a/llarp/router/router.hpp b/llarp/router/router.hpp index 982822b9b..b7333ebcd 100644 --- a/llarp/router/router.hpp +++ b/llarp/router/router.hpp @@ -81,13 +81,13 @@ namespace llarp /// should we obey the service node whitelist? bool whitelistRouters = false; - std::shared_ptr< Logic > + std::shared_ptr logic() const override { return _logic; } - llarp_dht_context * + llarp_dht_context* dht() const override { return _dht; @@ -96,58 +96,58 @@ namespace llarp util::StatusObject ExtractStatus() const override; - llarp_nodedb * + llarp_nodedb* nodedb() const override { return _nodedb; } - const path::PathContext & + const path::PathContext& pathContext() const override { return paths; } - path::PathContext & + path::PathContext& pathContext() override { return paths; } - const RouterContact & + const RouterContact& rc() const override { return _rc; } void - SetRouterWhitelist(const std::vector< RouterID > &routers) override; + SetRouterWhitelist(const std::vector& routers) override; - exit::Context & + exit::Context& exitContext() override { return _exitContext; } - std::shared_ptr< KeyManager > + std::shared_ptr keyManager() const override { return m_keyManager; } - const SecretKey & + const SecretKey& identity() const override { return _identity; } - const SecretKey & + const SecretKey& encryption() const override { return _encryption; } - Profiling & + Profiling& routerProfiling() override { return _routerProfiling; @@ -159,13 +159,13 @@ namespace llarp return _netloop; } - std::shared_ptr< llarp::thread::ThreadPool > + std::shared_ptr threadpool() override { return cryptoworker; } - std::shared_ptr< llarp::thread::ThreadPool > + std::shared_ptr diskworker() override { return disk; @@ -179,22 +179,22 @@ namespace llarp LinkFactory::LinkType _defaultLinkType; llarp_ev_loop_ptr _netloop; - std::shared_ptr< llarp::thread::ThreadPool > cryptoworker; - std::shared_ptr< Logic > _logic; + std::shared_ptr cryptoworker; + std::shared_ptr _logic; path::PathContext paths; exit::Context _exitContext; SecretKey _identity; SecretKey _encryption; - std::shared_ptr< thread::ThreadPool > disk; - llarp_dht_context *_dht = nullptr; - llarp_nodedb *_nodedb; + std::shared_ptr disk; + llarp_dht_context* _dht = nullptr; + llarp_nodedb* _nodedb; llarp_time_t _startedAt; llarp_time_t Uptime() const override; bool - Sign(Signature &sig, const llarp_buffer_t &buf) const override; + Sign(Signature& sig, const llarp_buffer_t& buf) const override; uint16_t m_OutboundPort = 0; /// how often do we resign our RC? milliseconds. @@ -211,13 +211,13 @@ namespace llarp service::Context _hiddenServiceContext; - service::Context & + service::Context& hiddenServiceContext() override { return _hiddenServiceContext; } - const service::Context & + const service::Context& hiddenServiceContext() const override { return _hiddenServiceContext; @@ -232,7 +232,7 @@ namespace llarp return now <= _lastTick || (now - _lastTick) <= llarp_time_t{30000}; } - using NetConfig_t = std::unordered_multimap< std::string, std::string >; + using NetConfig_t = std::unordered_multimap; /// default network config for default network interface NetConfig_t netConfig; @@ -245,7 +245,7 @@ namespace llarp { // TODO: use equal_range ? auto itr = netConfig.find("exit"); - if(itr == netConfig.end()) + if (itr == netConfig.end()) return false; return IsTrueValue(itr->second.c_str()); } @@ -257,13 +257,13 @@ namespace llarp CreateDefaultHiddenService(); const std::string DefaultRPCBindAddr = "127.0.0.1:1190"; - bool enableRPCServer = false; - std::unique_ptr< rpc::Server > rpcServer; + bool enableRPCServer = false; + std::unique_ptr rpcServer; std::string rpcBindAddr = DefaultRPCBindAddr; const llarp_time_t _randomStartDelay; /// lokid caller - std::unique_ptr< rpc::Caller > rpcCaller; + std::unique_ptr rpcCaller; std::string lokidRPCAddr = "127.0.0.1:22023"; std::string lokidRPCUser; std::string lokidRPCPassword; @@ -277,30 +277,30 @@ namespace llarp RCLookupHandler _rcLookupHandler; RCGossiper _rcGossiper; - using Clock_t = std::chrono::steady_clock; + using Clock_t = std::chrono::steady_clock; using TimePoint_t = Clock_t::time_point; TimePoint_t m_NextExploreAt; - IOutboundMessageHandler & + IOutboundMessageHandler& outboundMessageHandler() override { return _outboundMessageHandler; } - IOutboundSessionMaker & + IOutboundSessionMaker& outboundSessionMaker() override { return _outboundSessionMaker; } - ILinkManager & + ILinkManager& linkManager() override { return _linkManager; } - I_RCLookupHandler & + I_RCLookupHandler& rcLookupHandler() override { return _rcLookupHandler; @@ -309,20 +309,21 @@ namespace llarp void GossipRCIfNeeded(const RouterContact rc) override; - Router(std::shared_ptr< llarp::thread::ThreadPool > worker, - llarp_ev_loop_ptr __netloop, std::shared_ptr< Logic > logic); + Router( + std::shared_ptr worker, + llarp_ev_loop_ptr __netloop, + std::shared_ptr logic); ~Router() override; bool - HandleRecvLinkMessageBuffer(ILinkSession *from, - const llarp_buffer_t &msg) override; + HandleRecvLinkMessageBuffer(ILinkSession* from, const llarp_buffer_t& msg) override; bool InitOutboundLinks(); bool - GetRandomGoodRouter(RouterID &r) override; + GetRandomGoodRouter(RouterID& r) override; /// initialize us as a service node /// return true on success @@ -343,10 +344,10 @@ namespace llarp LoadHiddenServiceConfig(string_view fname); bool - AddHiddenService(const service::Config::section_t &config); + AddHiddenService(const service::Config::section_t& config); bool - Configure(Config *conf, llarp_nodedb *nodedb = nullptr) override; + Configure(Config* conf, llarp_nodedb* nodedb = nullptr) override; bool StartJsonRpc() override; @@ -363,7 +364,7 @@ namespace llarp StopLinks(); void - PersistSessionUntil(const RouterID &remote, llarp_time_t until) override; + PersistSessionUntil(const RouterID& remote, llarp_time_t until) override; bool EnsureIdentity(); @@ -372,7 +373,7 @@ namespace llarp EnsureEncryptionKey(); bool - ConnectionToRouterAllowed(const RouterID &router) const override; + ConnectionToRouterAllowed(const RouterID& router) const override; void HandleSaveRC() const; @@ -380,7 +381,7 @@ namespace llarp bool SaveRC(); - const byte_t * + const byte_t* pubkey() const override { return seckey_topublic(_identity); @@ -391,7 +392,7 @@ namespace llarp /// inject configuration and reconfigure router bool - Reconfigure(Config *conf) override; + Reconfigure(Config* conf) override; bool TryConnectAsync(RouterContact rc, uint16_t tries) override; @@ -400,7 +401,7 @@ namespace llarp /// return true on 100% valid /// return false if not 100% valid bool - ValidateConfig(Config *conf) const override; + ValidateConfig(Config* conf) const override; /// send to remote router or queue for sending /// returns false on overflow @@ -408,15 +409,15 @@ namespace llarp /// NOT threadsafe /// MUST be called in the logic thread bool - SendToOrQueue(const RouterID &remote, const ILinkMessage *msg, - SendStatusHandler handler) override; + SendToOrQueue( + const RouterID& remote, const ILinkMessage* msg, SendStatusHandler handler) override; void - ForEachPeer(std::function< void(const ILinkSession *, bool) > visit, - bool randomize = false) const override; + ForEachPeer(std::function visit, bool randomize = false) + const override; void - ForEachPeer(std::function< void(ILinkSession *) > visit); + ForEachPeer(std::function visit); bool IsBootstrapNode(RouterID) const override; @@ -449,9 +450,8 @@ namespace llarp /// successful parsing return true on parse and handle success otherwise /// return false bool - ParseRoutingMessageBuffer(const llarp_buffer_t &buf, - routing::IMessageHandler *h, - const PathID_t &rxid) override; + ParseRoutingMessageBuffer( + const llarp_buffer_t& buf, routing::IMessageHandler* h, const PathID_t& rxid) override; void ConnectToRandomRouters(int N) override; @@ -465,17 +465,16 @@ namespace llarp NumberOfConnectedClients() const override; bool - GetRandomConnectedRouter(RouterContact &result) const override; + GetRandomConnectedRouter(RouterContact& result) const override; void - HandleDHTLookupForExplore( - RouterID remote, const std::vector< RouterContact > &results) override; + HandleDHTLookupForExplore(RouterID remote, const std::vector& results) override; void LookupRouter(RouterID remote, RouterLookupHandler resultHandler) override; bool - HasSessionTo(const RouterID &remote) const override; + HasSessionTo(const RouterID& remote) const override; std::string ShortName() const; @@ -493,14 +492,14 @@ namespace llarp AfterStopIssued(); private: - std::atomic< bool > _stopping; - std::atomic< bool > _running; + std::atomic _stopping; + std::atomic _running; bool m_isServiceNode = false; llarp_time_t m_LastStatsReport = 0s; - std::shared_ptr< llarp::KeyManager > m_keyManager; + std::shared_ptr m_keyManager; uint32_t path_build_count = 0; @@ -513,21 +512,21 @@ namespace llarp bool UpdateOurRC(bool rotateKeys = false); - template < typename Config > + template void - mergeHiddenServiceConfig(const Config &in, Config &out) + mergeHiddenServiceConfig(const Config& in, Config& out) { - for(const auto &item : netConfig) + for (const auto& item : netConfig) out.push_back({item.first, item.second}); - for(const auto &item : in) + for (const auto& item : in) out.push_back({item.first, item.second}); } bool - FromConfig(Config *conf); + FromConfig(Config* conf); void - MessageSent(const RouterID &remote, SendStatus status); + MessageSent(const RouterID& remote, SendStatus status); }; } // namespace llarp diff --git a/llarp/router_contact.cpp b/llarp/router_contact.cpp index 614e38b97..3b0248aae 100644 --- a/llarp/router_contact.cpp +++ b/llarp/router_contact.cpp @@ -15,11 +15,10 @@ namespace llarp { - NetID & + NetID& NetID::DefaultValue() { - static NetID defaultID( - reinterpret_cast< const byte_t * >(llarp::DEFAULT_NETID)); + static NetID defaultID(reinterpret_cast(llarp::DEFAULT_NETID)); return defaultID; } @@ -35,12 +34,11 @@ namespace llarp /// an RC inserted long enough ago (4 hrs) is considered stale and is removed llarp_time_t RouterContact::StaleInsertionAge = 4h; /// update RCs shortly before they are about to expire - llarp_time_t RouterContact::UpdateInterval = - RouterContact::StaleInsertionAge - 5min; + llarp_time_t RouterContact::UpdateInterval = RouterContact::StaleInsertionAge - 5min; - NetID::NetID(const byte_t *val) + NetID::NetID(const byte_t* val) { - size_t len = strnlen(reinterpret_cast< const char * >(val), size()); + size_t len = strnlen(reinterpret_cast(val), size()); std::copy(val, val + len, begin()); } @@ -49,7 +47,7 @@ namespace llarp } bool - NetID::operator==(const NetID &other) const + NetID::operator==(const NetID& other) const { return ToString() == other.ToString(); } @@ -62,14 +60,14 @@ namespace llarp } bool - NetID::BDecode(llarp_buffer_t *buf) + NetID::BDecode(llarp_buffer_t* buf) { Zero(); llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz > size()) + if (strbuf.sz > size()) return false; std::copy(strbuf.base, strbuf.base + strbuf.sz, begin()); @@ -77,81 +75,81 @@ namespace llarp } bool - NetID::BEncode(llarp_buffer_t *buf) const + NetID::BEncode(llarp_buffer_t* buf) const { auto term = std::find(begin(), end(), '\0'); return bencode_write_bytestring(buf, data(), std::distance(begin(), term)); } bool - RouterContact::BEncode(llarp_buffer_t *buf) const + RouterContact::BEncode(llarp_buffer_t* buf) const { /* write dict begin */ - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; /* write ai if they exist */ - if(!bencode_write_bytestring(buf, "a", 1)) + if (!bencode_write_bytestring(buf, "a", 1)) return false; - if(!BEncodeWriteList(addrs.begin(), addrs.end(), buf)) + if (!BEncodeWriteList(addrs.begin(), addrs.end(), buf)) return false; /* write netid */ - if(!bencode_write_bytestring(buf, "i", 1)) + if (!bencode_write_bytestring(buf, "i", 1)) return false; - if(!netID.BEncode(buf)) + if (!netID.BEncode(buf)) return false; /* write signing pubkey */ - if(!bencode_write_bytestring(buf, "k", 1)) + if (!bencode_write_bytestring(buf, "k", 1)) return false; - if(!pubkey.BEncode(buf)) + if (!pubkey.BEncode(buf)) return false; std::string nick = Nick(); - if(!nick.empty()) + if (!nick.empty()) { /* write nickname */ - if(!bencode_write_bytestring(buf, "n", 1)) + if (!bencode_write_bytestring(buf, "n", 1)) { return false; } - if(!bencode_write_bytestring(buf, nick.c_str(), nick.size())) + if (!bencode_write_bytestring(buf, nick.c_str(), nick.size())) { return false; } } /* write encryption pubkey */ - if(!bencode_write_bytestring(buf, "p", 1)) + if (!bencode_write_bytestring(buf, "p", 1)) return false; - if(!enckey.BEncode(buf)) + if (!enckey.BEncode(buf)) return false; // write router version if present - if(routerVersion.has_value()) + if (routerVersion.has_value()) { - if(not BEncodeWriteDictEntry("r", routerVersion.value(), buf)) + if (not BEncodeWriteDictEntry("r", routerVersion.value(), buf)) return false; } /* write last updated */ - if(!bencode_write_bytestring(buf, "u", 1)) + if (!bencode_write_bytestring(buf, "u", 1)) return false; - if(!bencode_write_uint64(buf, last_updated.count())) + if (!bencode_write_uint64(buf, last_updated.count())) return false; /* write versions */ - if(!bencode_write_uint64_entry(buf, "v", 1, version)) + if (!bencode_write_uint64_entry(buf, "v", 1, version)) return false; /* write xi if they exist */ - if(!bencode_write_bytestring(buf, "x", 1)) + if (!bencode_write_bytestring(buf, "x", 1)) return false; - if(!BEncodeWriteList(exits.begin(), exits.end(), buf)) + if (!BEncodeWriteList(exits.begin(), exits.end(), buf)) return false; /* write signature */ - if(!bencode_write_bytestring(buf, "z", 1)) + if (!bencode_write_bytestring(buf, "z", 1)) return false; - if(!signature.BEncode(buf)) + if (!signature.BEncode(buf)) return false; return bencode_end(buf); } @@ -165,8 +163,8 @@ namespace llarp nickname.Zero(); enckey.Zero(); pubkey.Zero(); - routerVersion = nonstd::optional< RouterVersion >{}; - last_updated = 0s; + routerVersion = nonstd::optional{}; + last_updated = 0s; } util::StatusObject @@ -178,11 +176,11 @@ namespace llarp {"identity", pubkey.ToString()}, {"addresses", addrs}}; - if(HasNick()) + if (HasNick()) { obj["nickname"] = Nick(); } - if(routerVersion.has_value()) + if (routerVersion.has_value()) { obj["routerVersion"] = routerVersion->ToString(); } @@ -190,35 +188,35 @@ namespace llarp } bool - RouterContact::DecodeKey(const llarp_buffer_t &key, llarp_buffer_t *buf) + RouterContact::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictList("a", addrs, read, key, buf)) + if (!BEncodeMaybeReadDictList("a", addrs, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("i", netID, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("i", netID, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("k", pubkey, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("k", pubkey, read, key, buf)) return false; - if(key == "r") + if (key == "r") { RouterVersion r; - if(not r.BDecode(buf)) + if (not r.BDecode(buf)) return false; routerVersion = r; return true; } - if(key == "n") + if (key == "n") { llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) { return false; } - if(strbuf.sz > llarp::AlignedBuffer< (32) >::size()) + if (strbuf.sz > llarp::AlignedBuffer<(32)>::size()) { return false; } @@ -227,19 +225,19 @@ namespace llarp return true; } - if(!BEncodeMaybeReadDictEntry("p", enckey, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("p", enckey, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("u", last_updated, read, key, buf)) + if (!BEncodeMaybeReadDictInt("u", last_updated, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, key, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, key, buf)) return false; - if(!BEncodeMaybeReadDictList("x", exits, read, key, buf)) + if (!BEncodeMaybeReadDictList("x", exits, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("z", signature, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("z", signature, read, key, buf)) return false; return read; @@ -248,7 +246,7 @@ namespace llarp bool RouterContact::IsPublicRouter() const { - if(not routerVersion.has_value()) + if (not routerVersion.has_value()) return false; return !addrs.empty(); } @@ -263,9 +261,8 @@ namespace llarp RouterContact::SetNick(string_view nick) { nickname.Zero(); - std::copy(nick.begin(), - nick.begin() + std::min(nick.size(), nickname.size()), - nickname.begin()); + std::copy( + nick.begin(), nick.begin() + std::min(nick.size(), nickname.size()), nickname.begin()); } bool @@ -303,18 +300,18 @@ namespace llarp } bool - RouterContact::Sign(const SecretKey &secretkey) + RouterContact::Sign(const SecretKey& secretkey) { pubkey = llarp::seckey_topublic(secretkey); - std::array< byte_t, MAX_RC_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); signature.Zero(); last_updated = time_now_ms(); - if(!BEncode(&buf)) + if (!BEncode(&buf)) { return false; } - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; return CryptoManager::instance()->sign(signature, secretkey, buf); } @@ -322,38 +319,37 @@ namespace llarp bool RouterContact::Verify(llarp_time_t now, bool allowExpired) const { - if(netID != NetID::DefaultValue()) + if (netID != NetID::DefaultValue()) { - llarp::LogError("netid missmatch: '", netID, "' != '", - NetID::DefaultValue(), "'"); + llarp::LogError("netid missmatch: '", netID, "' != '", NetID::DefaultValue(), "'"); return false; } - if(IsExpired(now)) + if (IsExpired(now)) { - if(!allowExpired) + if (!allowExpired) { llarp::LogError("RC is expired"); return false; } llarp::LogWarn("RC is expired"); } - for(const auto &a : addrs) + for (const auto& a : addrs) { - if(IsBogon(a.ip) && BlockBogons) + if (IsBogon(a.ip) && BlockBogons) { llarp::LogError("invalid address info: ", a); return false; } } - for(const auto &exit : exits) + for (const auto& exit : exits) { - if(IsBogonRange(exit.address, exit.netmask)) + if (IsBogonRange(exit.address, exit.netmask)) { llarp::LogError("bogon exit: ", exit); return false; } } - if(!VerifySignature()) + if (!VerifySignature()) { llarp::LogError("invalid signature: ", *this); return false; @@ -367,70 +363,69 @@ namespace llarp RouterContact copy; copy = *this; copy.signature.Zero(); - std::array< byte_t, MAX_RC_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) { llarp::LogError("bencode failed"); return false; } - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; return CryptoManager::instance()->verify(pubkey, buf, signature); } bool - RouterContact::Write(const char *fname) const + RouterContact::Write(const char* fname) const { - std::array< byte_t, MAX_RC_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!BEncode(&buf)) + if (!BEncode(&buf)) { return false; } - buf.sz = buf.cur - buf.base; - buf.cur = buf.base; + buf.sz = buf.cur - buf.base; + buf.cur = buf.base; const fs::path fpath = std::string(fname); /* */ - auto optional_f = - llarp::util::OpenFileStream< std::ofstream >(fpath, std::ios::binary); - if(!optional_f) + auto optional_f = llarp::util::OpenFileStream(fpath, std::ios::binary); + if (!optional_f) { return false; } - auto &f = optional_f.value(); - if(!f.is_open()) + auto& f = optional_f.value(); + if (!f.is_open()) { return false; } - f.write((char *)buf.base, buf.sz); + f.write((char*)buf.base, buf.sz); return true; } bool - RouterContact::Read(const char *fname) + RouterContact::Read(const char* fname) { - std::array< byte_t, MAX_RC_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); std::ifstream f; f.open(fname, std::ios::binary); - if(!f.is_open()) + if (!f.is_open()) { llarp::LogError("Failed to open ", fname); return false; } f.seekg(0, std::ios::end); auto l = f.tellg(); - if(l > static_cast< std::streamoff >(sizeof tmp)) + if (l > static_cast(sizeof tmp)) { return false; } f.seekg(0, std::ios::beg); - f.read((char *)tmp.data(), l); + f.read((char*)tmp.data(), l); return BDecode(&buf); } - std::ostream & - RouterContact::print(std::ostream &stream, int level, int spaces) const + std::ostream& + RouterContact::print(std::ostream& stream, int level, int spaces) const { Printer printer(stream, level, spaces); printer.printAttribute("k", pubkey); diff --git a/llarp/router_contact.hpp b/llarp/router_contact.hpp index 475c473ce..797f7e058 100644 --- a/llarp/router_contact.hpp +++ b/llarp/router_contact.hpp @@ -20,28 +20,28 @@ namespace llarp { /// NetID - struct NetID final : public AlignedBuffer< 8 > + struct NetID final : public AlignedBuffer<8> { - static NetID & + static NetID& DefaultValue(); NetID(); - explicit NetID(const byte_t *val); + explicit NetID(const byte_t* val); - explicit NetID(const NetID &other) = default; + explicit NetID(const NetID& other) = default; bool - operator==(const NetID &other) const; + operator==(const NetID& other) const; bool - operator!=(const NetID &other) const + operator!=(const NetID& other) const { return !(*this == other); } - std::ostream & - print(std::ostream &stream, int level, int spaces) const + std::ostream& + print(std::ostream& stream, int level, int spaces) const { Printer printer(stream, level, spaces); printer.printValue(ToString()); @@ -52,14 +52,14 @@ namespace llarp ToString() const; bool - BDecode(llarp_buffer_t *buf); + BDecode(llarp_buffer_t* buf); bool - BEncode(llarp_buffer_t *buf) const; + BEncode(llarp_buffer_t* buf) const; }; - inline std::ostream & - operator<<(std::ostream &out, const NetID &id) + inline std::ostream& + operator<<(std::ostream& out, const NetID& id) { return id.print(out, -1, -1); } @@ -82,14 +82,14 @@ namespace llarp struct Hash { size_t - operator()(const RouterContact &r) const + operator()(const RouterContact& r) const { return PubKey::Hash()(r.pubkey); } }; // advertised addresses - std::vector< AddressInfo > addrs; + std::vector addrs; // network identifier NetID netID; // public encryption public key @@ -97,15 +97,15 @@ namespace llarp // public signing public key llarp::PubKey pubkey; // advertised exits - std::vector< ExitInfo > exits; + std::vector exits; // signature llarp::Signature signature; /// node nickname, yw kee - llarp::AlignedBuffer< NICKLEN > nickname; + llarp::AlignedBuffer nickname; llarp_time_t last_updated = 0s; - uint64_t version = LLARP_PROTO_VERSION; - nonstd::optional< RouterVersion > routerVersion; + uint64_t version = LLARP_PROTO_VERSION; + nonstd::optional routerVersion; util::StatusObject ExtractStatus() const; @@ -123,25 +123,24 @@ namespace llarp } bool - BEncode(llarp_buffer_t *buf) const; + BEncode(llarp_buffer_t* buf) const; bool - operator==(const RouterContact &other) const + operator==(const RouterContact& other) const { - return addrs == other.addrs && enckey == other.enckey - && pubkey == other.pubkey && signature == other.signature - && nickname == other.nickname && last_updated == other.last_updated - && netID == other.netID; + return addrs == other.addrs && enckey == other.enckey && pubkey == other.pubkey + && signature == other.signature && nickname == other.nickname + && last_updated == other.last_updated && netID == other.netID; } bool - operator<(const RouterContact &other) const + operator<(const RouterContact& other) const { return pubkey < other.pubkey; } bool - operator!=(const RouterContact &other) const + operator!=(const RouterContact& other) const { return !(*this == other); } @@ -156,14 +155,14 @@ namespace llarp } bool - BDecode(llarp_buffer_t *buf) + BDecode(llarp_buffer_t* buf) { Clear(); return bencode_decode_dict(*this, buf); } bool - DecodeKey(const llarp_buffer_t &k, llarp_buffer_t *buf); + DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf); bool HasNick() const; @@ -181,7 +180,7 @@ namespace llarp Verify(llarp_time_t now, bool allowExpired = true) const; bool - Sign(const llarp::SecretKey &secret); + Sign(const llarp::SecretKey& secret); /// does this RC expire soon? default delta is 1 minute bool @@ -200,32 +199,31 @@ namespace llarp Age(llarp_time_t now) const; bool - OtherIsNewer(const RouterContact &other) const + OtherIsNewer(const RouterContact& other) const { return last_updated < other.last_updated; } - std::ostream & - print(std::ostream &stream, int level, int spaces) const; + std::ostream& + print(std::ostream& stream, int level, int spaces) const; bool - Read(const char *fname); + Read(const char* fname); bool - Write(const char *fname) const; + Write(const char* fname) const; bool VerifySignature() const; }; - inline std::ostream & - operator<<(std::ostream &out, const RouterContact &rc) + inline std::ostream& + operator<<(std::ostream& out, const RouterContact& rc) { return rc.print(out, -1, -1); } - using RouterLookupHandler = - std::function< void(const std::vector< RouterContact > &) >; + using RouterLookupHandler = std::function&)>; } // namespace llarp #endif diff --git a/llarp/router_id.cpp b/llarp/router_id.cpp index cceda8cbb..c22556d18 100644 --- a/llarp/router_id.cpp +++ b/llarp/router_id.cpp @@ -26,7 +26,7 @@ namespace llarp RouterID::FromString(const std::string& str) { auto pos = str.find(".snode"); - if(pos == std::string::npos || pos == 0) + if (pos == std::string::npos || pos == 0) { return false; } diff --git a/llarp/router_id.hpp b/llarp/router_id.hpp index 142f79ab3..ef58d92a4 100644 --- a/llarp/router_id.hpp +++ b/llarp/router_id.hpp @@ -6,21 +6,21 @@ namespace llarp { - struct RouterID : public AlignedBuffer< 32 > + struct RouterID : public AlignedBuffer<32> { static constexpr size_t SIZE = 32; - using Data = std::array< byte_t, SIZE >; + using Data = std::array; RouterID() { } - RouterID(const byte_t* buf) : AlignedBuffer< SIZE >(buf) + RouterID(const byte_t* buf) : AlignedBuffer(buf) { } - RouterID(const Data& data) : AlignedBuffer< SIZE >(data) + RouterID(const Data& data) : AlignedBuffer(data) { } @@ -49,7 +49,7 @@ namespace llarp return out << id.ToString(); } - using Hash = AlignedBuffer< SIZE >::Hash; + using Hash = AlignedBuffer::Hash; }; inline bool diff --git a/llarp/router_version.cpp b/llarp/router_version.cpp index 78fc56be6..5b9823cd7 100644 --- a/llarp/router_version.cpp +++ b/llarp/router_version.cpp @@ -21,15 +21,15 @@ namespace llarp bool RouterVersion::BEncode(llarp_buffer_t* buf) const { - if(not bencode_start_list(buf)) + if (not bencode_start_list(buf)) return false; - if(not IsEmpty()) + if (not IsEmpty()) { - if(not bencode_write_uint64(buf, m_ProtoVersion)) + if (not bencode_write_uint64(buf, m_ProtoVersion)) return false; - for(const auto& i : m_Version) + for (const auto& i : m_Version) { - if(not bencode_write_uint64(buf, i)) + if (not bencode_write_uint64(buf, i)) return false; } } @@ -56,32 +56,32 @@ namespace llarp // clear before hand Clear(); size_t idx = 0; - if(not bencode_read_list( - [self = this, &idx](llarp_buffer_t* buffer, bool has) { - if(has) - { - uint64_t i; - if(idx == 0) - { - uint64_t val = -1; - if(not bencode_read_integer(buffer, &val)) - return false; - self->m_ProtoVersion = val; - } - else if(bencode_read_integer(buffer, &i)) - { - // prevent overflow (note that idx includes version too) - if(idx > self->m_Version.max_size()) - return false; - self->m_Version[idx - 1] = i; - } - else - return false; - ++idx; - } - return true; - }, - buf)) + if (not bencode_read_list( + [self = this, &idx](llarp_buffer_t* buffer, bool has) { + if (has) + { + uint64_t i; + if (idx == 0) + { + uint64_t val = -1; + if (not bencode_read_integer(buffer, &val)) + return false; + self->m_ProtoVersion = val; + } + else if (bencode_read_integer(buffer, &i)) + { + // prevent overflow (note that idx includes version too) + if (idx > self->m_Version.max_size()) + return false; + self->m_Version[idx - 1] = i; + } + else + return false; + ++idx; + } + return true; + }, + buf)) return false; // either full list or empty list is valid return idx == 4 || idx == 0; @@ -90,10 +90,8 @@ namespace llarp std::string RouterVersion::ToString() const { - return std::to_string(m_Version.at(0)) + "." - + std::to_string(m_Version.at(1)) + "." - + std::to_string(m_Version.at(2)) + " protocol version " - + std::to_string(m_ProtoVersion); + return std::to_string(m_Version.at(0)) + "." + std::to_string(m_Version.at(1)) + "." + + std::to_string(m_Version.at(2)) + " protocol version " + std::to_string(m_ProtoVersion); } } // namespace llarp diff --git a/llarp/router_version.hpp b/llarp/router_version.hpp index bf1c862ec..28412ad8d 100644 --- a/llarp/router_version.hpp +++ b/llarp/router_version.hpp @@ -10,12 +10,11 @@ namespace llarp { struct RouterVersion { - using Version_t = std::array< uint16_t, 3 >; + using Version_t = std::array; RouterVersion() = default; - explicit RouterVersion(const Version_t& routerVersion, - uint64_t protoVersion); + explicit RouterVersion(const Version_t& routerVersion, uint64_t protoVersion); bool BEncode(llarp_buffer_t* buf) const; @@ -42,8 +41,7 @@ namespace llarp bool operator<(const RouterVersion& other) const { - return m_ProtoVersion < other.m_ProtoVersion - || m_Version < other.m_Version; + return m_ProtoVersion < other.m_ProtoVersion || m_Version < other.m_Version; } bool @@ -55,12 +53,11 @@ namespace llarp bool operator==(const RouterVersion& other) const { - return m_ProtoVersion == other.m_ProtoVersion - && m_Version == other.m_Version; + return m_ProtoVersion == other.m_ProtoVersion && m_Version == other.m_Version; } private: - Version_t m_Version = {{0, 0, 0}}; + Version_t m_Version = {{0, 0, 0}}; int64_t m_ProtoVersion = LLARP_PROTO_VERSION; }; diff --git a/llarp/routing/dht_message.cpp b/llarp/routing/dht_message.cpp index cf5080acc..63bf4e7e6 100644 --- a/llarp/routing/dht_message.cpp +++ b/llarp/routing/dht_message.cpp @@ -10,17 +10,17 @@ namespace llarp bool DHTMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { - if(key == "M") + if (key == "M") { llarp::dht::Key_t fromKey; fromKey.Zero(); return llarp::dht::DecodeMesssageList(fromKey, val, M, true); } - if(key == "S") + if (key == "S") { return bencode_read_integer(val, &S); } - if(key == "V") + if (key == "V") { return bencode_read_integer(val, &V); } @@ -30,16 +30,16 @@ namespace llarp bool DHTMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "M")) + if (!BEncodeWriteDictMsgType(buf, "A", "M")) return false; - if(!BEncodeWriteDictBEncodeList("M", M, buf)) + if (!BEncodeWriteDictBEncodeList("M", M, buf)) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) + if (!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) return false; return bencode_end(buf); @@ -55,11 +55,11 @@ namespace llarp { // set source as us const llarp::dht::Key_t us(r->pubkey()); - for(const auto& msg : M) + for (const auto& msg : M) { - msg->From = us; + msg->From = us; msg->pathID = from; - if(!h->HandleDHTMessage(*msg, r)) + if (!h->HandleDHTMessage(*msg, r)) return false; } return true; diff --git a/llarp/routing/dht_message.hpp b/llarp/routing/dht_message.hpp index 24534087b..509d5dd4c 100644 --- a/llarp/routing/dht_message.hpp +++ b/llarp/routing/dht_message.hpp @@ -12,7 +12,7 @@ namespace llarp { struct DHTMessage final : public IMessage { - std::vector< llarp::dht::IMessage::Ptr_t > M; + std::vector M; uint64_t V = 0; ~DHTMessage() override = default; diff --git a/llarp/routing/handler.hpp b/llarp/routing/handler.hpp index b98b71a18..008d74091 100644 --- a/llarp/routing/handler.hpp +++ b/llarp/routing/handler.hpp @@ -35,56 +35,45 @@ namespace llarp struct IMessageHandler { virtual bool - HandleObtainExitMessage(const ObtainExitMessage& msg, - AbstractRouter* r) = 0; + HandleObtainExitMessage(const ObtainExitMessage& msg, AbstractRouter* r) = 0; virtual bool - HandleGrantExitMessage(const GrantExitMessage& msg, - AbstractRouter* r) = 0; + HandleGrantExitMessage(const GrantExitMessage& msg, AbstractRouter* r) = 0; virtual bool - HandleRejectExitMessage(const RejectExitMessage& msg, - AbstractRouter* r) = 0; + HandleRejectExitMessage(const RejectExitMessage& msg, AbstractRouter* r) = 0; virtual bool - HandleTransferTrafficMessage(const TransferTrafficMessage& msg, - AbstractRouter* r) = 0; + HandleTransferTrafficMessage(const TransferTrafficMessage& msg, AbstractRouter* r) = 0; virtual bool - HandleUpdateExitMessage(const UpdateExitMessage& msg, - AbstractRouter* r) = 0; + HandleUpdateExitMessage(const UpdateExitMessage& msg, AbstractRouter* r) = 0; virtual bool - HandleUpdateExitVerifyMessage(const UpdateExitVerifyMessage& msg, - AbstractRouter* r) = 0; + HandleUpdateExitVerifyMessage(const UpdateExitVerifyMessage& msg, AbstractRouter* r) = 0; virtual bool - HandleCloseExitMessage(const CloseExitMessage& msg, - AbstractRouter* r) = 0; + HandleCloseExitMessage(const CloseExitMessage& msg, AbstractRouter* r) = 0; virtual bool - HandleDataDiscardMessage(const DataDiscardMessage& msg, - AbstractRouter* r) = 0; + HandleDataDiscardMessage(const DataDiscardMessage& msg, AbstractRouter* r) = 0; virtual bool - HandlePathTransferMessage(const PathTransferMessage& msg, - AbstractRouter* r) = 0; + HandlePathTransferMessage(const PathTransferMessage& msg, AbstractRouter* r) = 0; virtual bool HandleHiddenServiceFrame(const service::ProtocolFrame& msg) = 0; virtual bool - HandlePathConfirmMessage(const PathConfirmMessage& msg, - AbstractRouter* r) = 0; + HandlePathConfirmMessage(const PathConfirmMessage& msg, AbstractRouter* r) = 0; virtual bool - HandlePathLatencyMessage(const PathLatencyMessage& msg, - AbstractRouter* r) = 0; + HandlePathLatencyMessage(const PathLatencyMessage& msg, AbstractRouter* r) = 0; virtual bool HandleDHTMessage(const dht::IMessage& msg, AbstractRouter* r) = 0; }; - using MessageHandler_ptr = std::shared_ptr< IMessageHandler >; + using MessageHandler_ptr = std::shared_ptr; } // namespace routing } // namespace llarp diff --git a/llarp/routing/message_parser.cpp b/llarp/routing/message_parser.cpp index ea655cec6..28b907863 100644 --- a/llarp/routing/message_parser.cpp +++ b/llarp/routing/message_parser.cpp @@ -30,36 +30,34 @@ namespace llarp CloseExitMessage C; }; - InboundMessageParser::InboundMessageParser() - : m_Holder(std::make_unique< MessageHolder >()) + InboundMessageParser::InboundMessageParser() : m_Holder(std::make_unique()) { } InboundMessageParser::~InboundMessageParser() = default; bool - InboundMessageParser::operator()(llarp_buffer_t* buffer, - llarp_buffer_t* key) + InboundMessageParser::operator()(llarp_buffer_t* buffer, llarp_buffer_t* key) { - if(key == nullptr && firstKey) + if (key == nullptr && firstKey) { // empty dict return false; } - if(!key) + if (!key) return true; - if(firstKey) + if (firstKey) { llarp_buffer_t strbuf; - if(!(*key == "A")) + if (!(*key == "A")) return false; - if(!bencode_read_string(buffer, &strbuf)) + if (!bencode_read_string(buffer, &strbuf)) return false; - if(strbuf.sz != 1) + if (strbuf.sz != 1) return false; ourKey = *strbuf.cur; LogDebug("routing message '", key, "'"); - switch(ourKey) + switch (ourKey) { case 'D': msg = &m_Holder->D; @@ -100,7 +98,7 @@ namespace llarp default: llarp::LogError("invalid routing message id: ", *strbuf.cur); } - if(msg) + if (msg) msg->version = version; firstKey = false; return msg != nullptr; @@ -110,26 +108,24 @@ namespace llarp } bool - InboundMessageParser::ParseMessageBuffer(const llarp_buffer_t& buf, - IMessageHandler* h, - const PathID_t& from, - AbstractRouter* r) + InboundMessageParser::ParseMessageBuffer( + const llarp_buffer_t& buf, IMessageHandler* h, const PathID_t& from, AbstractRouter* r) { bool result = false; - msg = nullptr; - firstKey = true; + msg = nullptr; + firstKey = true; ManagedBuffer copiedBuf(buf); auto& copy = copiedBuf.underlying; uint64_t v = 0; - if(BEncodeSeekDictVersion(v, ©, 'V')) + if (BEncodeSeekDictVersion(v, ©, 'V')) { version = v; } - if(bencode_read_dict(*this, ©)) + if (bencode_read_dict(*this, ©)) { msg->from = from; - result = msg->HandleMessage(h, r); - if(!result) + result = msg->HandleMessage(h, r); + if (!result) { llarp::LogWarn("Failed to handle inbound routing message ", ourKey); } @@ -137,11 +133,11 @@ namespace llarp else { llarp::LogError("read dict failed in routing layer"); - llarp::DumpBuffer< llarp_buffer_t, 128 >(buf); + llarp::DumpBuffer(buf); } - if(msg) + if (msg) msg->Clear(); - msg = nullptr; + msg = nullptr; version = 0; return result; } diff --git a/llarp/routing/message_parser.hpp b/llarp/routing/message_parser.hpp index 1877e3a3d..b0761a967 100644 --- a/llarp/routing/message_parser.hpp +++ b/llarp/routing/message_parser.hpp @@ -22,8 +22,11 @@ namespace llarp ~InboundMessageParser(); bool - ParseMessageBuffer(const llarp_buffer_t& buf, IMessageHandler* handler, - const PathID_t& from, AbstractRouter* r); + ParseMessageBuffer( + const llarp_buffer_t& buf, + IMessageHandler* handler, + const PathID_t& from, + AbstractRouter* r); bool operator()(llarp_buffer_t* buffer, llarp_buffer_t* key); @@ -35,7 +38,7 @@ namespace llarp struct MessageHolder; IMessage* msg{nullptr}; - std::unique_ptr< MessageHolder > m_Holder; + std::unique_ptr m_Holder; }; } // namespace routing } // namespace llarp diff --git a/llarp/routing/path_confirm_message.cpp b/llarp/routing/path_confirm_message.cpp index b0fab5f4a..1e568c3c5 100644 --- a/llarp/routing/path_confirm_message.cpp +++ b/llarp/routing/path_confirm_message.cpp @@ -14,17 +14,16 @@ namespace llarp } bool - PathConfirmMessage::DecodeKey(const llarp_buffer_t& key, - llarp_buffer_t* val) + PathConfirmMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { bool read = false; - if(!BEncodeMaybeReadDictInt("L", pathLifetime, read, key, val)) + if (!BEncodeMaybeReadDictInt("L", pathLifetime, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("S", S, read, key, val)) + if (!BEncodeMaybeReadDictInt("S", S, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("T", pathCreated, read, key, val)) + if (!BEncodeMaybeReadDictInt("T", pathCreated, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, key, val)) + if (!BEncodeMaybeReadDictInt("V", version, read, key, val)) return false; return read; } @@ -32,24 +31,23 @@ namespace llarp bool PathConfirmMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "P")) + if (!BEncodeWriteDictMsgType(buf, "A", "P")) return false; - if(!BEncodeWriteDictInt("L", pathLifetime.count(), buf)) + if (!BEncodeWriteDictInt("L", pathLifetime.count(), buf)) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("T", pathCreated.count(), buf)) + if (!BEncodeWriteDictInt("T", pathCreated.count(), buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; return bencode_end(buf); } bool - PathConfirmMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + PathConfirmMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h && h->HandlePathConfirmMessage(*this, r); } diff --git a/llarp/routing/path_confirm_message.hpp b/llarp/routing/path_confirm_message.hpp index d51368096..f2f4eae0f 100644 --- a/llarp/routing/path_confirm_message.hpp +++ b/llarp/routing/path_confirm_message.hpp @@ -10,7 +10,7 @@ namespace llarp struct PathConfirmMessage final : public IMessage { llarp_time_t pathLifetime = 0s; - llarp_time_t pathCreated = 0s; + llarp_time_t pathCreated = 0s; PathConfirmMessage() = default; PathConfirmMessage(llarp_time_t lifetime); @@ -29,8 +29,8 @@ namespace llarp Clear() override { pathLifetime = 0s; - pathCreated = 0s; - version = 0; + pathCreated = 0s; + version = 0; } }; } // namespace routing diff --git a/llarp/routing/path_latency_message.cpp b/llarp/routing/path_latency_message.cpp index 906f36497..eb3dc9a1c 100644 --- a/llarp/routing/path_latency_message.cpp +++ b/llarp/routing/path_latency_message.cpp @@ -10,15 +10,14 @@ namespace llarp PathLatencyMessage::PathLatencyMessage() = default; bool - PathLatencyMessage::DecodeKey(const llarp_buffer_t& key, - llarp_buffer_t* val) + PathLatencyMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { bool read = false; - if(!BEncodeMaybeReadDictInt("L", L, read, key, val)) + if (!BEncodeMaybeReadDictInt("L", L, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("S", S, read, key, val)) + if (!BEncodeMaybeReadDictInt("S", S, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("T", T, read, key, val)) + if (!BEncodeMaybeReadDictInt("T", T, read, key, val)) return false; return read; } @@ -26,28 +25,27 @@ namespace llarp bool PathLatencyMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "L")) + if (!BEncodeWriteDictMsgType(buf, "A", "L")) return false; - if(L) + if (L) { - if(!BEncodeWriteDictInt("L", L, buf)) + if (!BEncodeWriteDictInt("L", L, buf)) return false; } - if(T) + if (T) { - if(!BEncodeWriteDictInt("T", T, buf)) + if (!BEncodeWriteDictInt("T", T, buf)) return false; } - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; return bencode_end(buf); } bool - PathLatencyMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + PathLatencyMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h && h->HandlePathLatencyMessage(*this, r); } diff --git a/llarp/routing/path_latency_message.hpp b/llarp/routing/path_latency_message.hpp index 56c9316a6..be05fc50c 100644 --- a/llarp/routing/path_latency_message.hpp +++ b/llarp/routing/path_latency_message.hpp @@ -22,8 +22,8 @@ namespace llarp void Clear() override { - T = 0; - L = 0; + T = 0; + L = 0; version = 0; } diff --git a/llarp/routing/path_transfer_message.cpp b/llarp/routing/path_transfer_message.cpp index 3d131c24b..4c70ddbd0 100644 --- a/llarp/routing/path_transfer_message.cpp +++ b/llarp/routing/path_transfer_message.cpp @@ -8,19 +8,18 @@ namespace llarp namespace routing { bool - PathTransferMessage::DecodeKey(const llarp_buffer_t& key, - llarp_buffer_t* val) + PathTransferMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { bool read = false; - if(!BEncodeMaybeReadDictEntry("P", P, read, key, val)) + if (!BEncodeMaybeReadDictEntry("P", P, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("S", S, read, key, val)) + if (!BEncodeMaybeReadDictInt("S", S, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("T", T, read, key, val)) + if (!BEncodeMaybeReadDictEntry("T", T, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, key, val)) + if (!BEncodeMaybeReadDictInt("V", version, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("Y", Y, read, key, val)) + if (!BEncodeMaybeReadDictEntry("Y", Y, read, key, val)) return false; return read; } @@ -28,30 +27,29 @@ namespace llarp bool PathTransferMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "T")) + if (!BEncodeWriteDictMsgType(buf, "A", "T")) return false; - if(!BEncodeWriteDictEntry("P", P, buf)) + if (!BEncodeWriteDictEntry("P", P, buf)) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictEntry("T", T, buf)) + if (!BEncodeWriteDictEntry("T", T, buf)) return false; - if(!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) + if (!BEncodeWriteDictInt("V", LLARP_PROTO_VERSION, buf)) return false; - if(!BEncodeWriteDictEntry("Y", Y, buf)) + if (!BEncodeWriteDictEntry("Y", Y, buf)) return false; return bencode_end(buf); } bool - PathTransferMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + PathTransferMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h->HandlePathTransferMessage(*this, r); } diff --git a/llarp/routing/path_transfer_message.hpp b/llarp/routing/path_transfer_message.hpp index 0dcfe6e48..cb464a452 100644 --- a/llarp/routing/path_transfer_message.hpp +++ b/llarp/routing/path_transfer_message.hpp @@ -17,8 +17,7 @@ namespace llarp TunnelNonce Y; PathTransferMessage() = default; - PathTransferMessage(const service::ProtocolFrame& f, const PathID_t& p) - : P(p), T(f) + PathTransferMessage(const service::ProtocolFrame& f, const PathID_t& p) : P(p), T(f) { Y.Randomize(); } diff --git a/llarp/routing/transfer_traffic_message.cpp b/llarp/routing/transfer_traffic_message.cpp index a7a26cf99..3524f2c88 100644 --- a/llarp/routing/transfer_traffic_message.cpp +++ b/llarp/routing/transfer_traffic_message.cpp @@ -9,10 +9,9 @@ namespace llarp namespace routing { bool - TransferTrafficMessage::PutBuffer(const llarp_buffer_t& buf, - uint64_t counter) + TransferTrafficMessage::PutBuffer(const llarp_buffer_t& buf, uint64_t counter) { - if(buf.sz > MaxExitMTU) + if (buf.sz > MaxExitMTU) return false; X.emplace_back(buf.sz + 8); byte_t* ptr = X.back().data(); @@ -27,36 +26,34 @@ namespace llarp bool TransferTrafficMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "I")) + if (!BEncodeWriteDictMsgType(buf, "A", "I")) return false; - if(!BEncodeWriteDictInt("S", S, buf)) + if (!BEncodeWriteDictInt("S", S, buf)) return false; - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; - if(!BEncodeWriteDictList("X", X, buf)) + if (!BEncodeWriteDictList("X", X, buf)) return false; return bencode_end(buf); } bool - TransferTrafficMessage::DecodeKey(const llarp_buffer_t& key, - llarp_buffer_t* buf) + TransferTrafficMessage::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("S", S, read, key, buf)) + if (!BEncodeMaybeReadDictInt("S", S, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("V", version, read, key, buf)) + if (!BEncodeMaybeReadDictInt("V", version, read, key, buf)) return false; - if(!BEncodeMaybeReadDictList("X", X, read, key, buf)) + if (!BEncodeMaybeReadDictList("X", X, read, key, buf)) return false; return read; } bool - TransferTrafficMessage::HandleMessage(IMessageHandler* h, - AbstractRouter* r) const + TransferTrafficMessage::HandleMessage(IMessageHandler* h, AbstractRouter* r) const { return h->HandleTransferTrafficMessage(*this, r); } diff --git a/llarp/routing/transfer_traffic_message.hpp b/llarp/routing/transfer_traffic_message.hpp index 527d2cfdc..505f350d8 100644 --- a/llarp/routing/transfer_traffic_message.hpp +++ b/llarp/routing/transfer_traffic_message.hpp @@ -10,19 +10,19 @@ namespace llarp { namespace routing { - constexpr size_t ExitPadSize = 512 - 48; - constexpr size_t MaxExitMTU = 1500; + constexpr size_t ExitPadSize = 512 - 48; + constexpr size_t MaxExitMTU = 1500; constexpr size_t ExitOverhead = sizeof(uint64_t); struct TransferTrafficMessage final : public IMessage { - std::vector< llarp::Encrypted< MaxExitMTU + ExitOverhead > > X; + std::vector> X; size_t _size = 0; void Clear() override { X.clear(); - _size = 0; + _size = 0; version = 0; } diff --git a/llarp/rpc/rpc.cpp b/llarp/rpc/rpc.cpp index 5b2b603a9..1994d50f4 100644 --- a/llarp/rpc/rpc.cpp +++ b/llarp/rpc/rpc.cpp @@ -32,16 +32,16 @@ namespace llarp bool HandleResponse(::abyss::http::RPC_Response response) override { - if(!response.is_object()) + if (!response.is_object()) { return HandleJSONResult({}); } const auto itr = response.find("result"); - if(itr == response.end()) + if (itr == response.end()) { return HandleJSONResult({}); } - if(itr.value().is_object()) + if (itr.value().is_object()) { return HandleJSONResult(itr.value()); } @@ -63,24 +63,24 @@ namespace llarp bool HandleJSONResult(const nlohmann::json& result) override { - if(not result.is_object()) + if (not result.is_object()) { LogError("invalid result from lokid ping, not an object"); return false; } const auto itr = result.find("status"); - if(itr == result.end()) + if (itr == result.end()) { LogError("invalid result from lokid ping, no result"); return false; } - if(not itr->is_string()) + if (not itr->is_string()) { LogError("invalid result from lokid ping, status not an string"); return false; } - const auto status = itr->get< std::string >(); - if(status != "OK") + const auto status = itr->get(); + if (status != "OK") { LogError("lokid ping failed: '", status, "'"); return false; @@ -97,14 +97,13 @@ namespace llarp struct GetServiceNodeListHandler final : public CallerHandler { - using PubkeyList_t = std::vector< RouterID >; - using Callback_t = std::function< void(const PubkeyList_t&, bool) >; + using PubkeyList_t = std::vector; + using Callback_t = std::function; ~GetServiceNodeListHandler() override = default; Callback_t handler; - GetServiceNodeListHandler(::abyss::http::ConnImpl* impl, - CallerImpl* parent, Callback_t h) + GetServiceNodeListHandler(::abyss::http::ConnImpl* impl, CallerImpl* parent, Callback_t h) : CallerHandler(impl, parent), handler(std::move(h)) { } @@ -124,9 +123,9 @@ namespace llarp AbstractRouter* router; llarp_time_t m_NextKeyUpdate = 0s; std::string m_LastBlockHash; - llarp_time_t m_NextPing = 0s; + llarp_time_t m_NextPing = 0s; const llarp_time_t KeyUpdateInterval = 5s; - const llarp_time_t PingInterval = 5min; + const llarp_time_t PingInterval = 5min; using PubkeyList_t = GetServiceNodeListHandler::PubkeyList_t; CallerImpl(AbstractRouter* r) : ::abyss::http::JSONRPC(), router(r) @@ -136,16 +135,16 @@ namespace llarp void Tick(llarp_time_t now) { - if(not router->IsRunning()) + if (not router->IsRunning()) return; - if(not router->IsServiceNode()) + if (not router->IsServiceNode()) return; - if(now >= m_NextKeyUpdate) + if (now >= m_NextKeyUpdate) { AsyncUpdatePubkeyList(); m_NextKeyUpdate = now + KeyUpdateInterval; } - if(now >= m_NextPing) + if (now >= m_NextPing) { AsyncLokiPing(); m_NextPing = now + PingInterval; @@ -166,8 +165,8 @@ namespace llarp LogInfo("Pinging Lokid"); nlohmann::json version(llarp::VERSION); nlohmann::json params({{"version", version}}); - QueueRPC("lokinet_ping", std::move(params), - util::memFn(&CallerImpl::NewLokinetPingConn, this)); + QueueRPC( + "lokinet_ping", std::move(params), util::memFn(&CallerImpl::NewLokinetPingConn, this)); } void @@ -182,8 +181,10 @@ namespace llarp {"block_hash", true}, }}, {"poll_block_hash", m_LastBlockHash}}; - QueueRPC("get_n_service_nodes", std::move(params), - util::memFn(&CallerImpl::NewAsyncUpdatePubkeyListConn, this)); + QueueRPC( + "get_n_service_nodes", + std::move(params), + util::memFn(&CallerImpl::NewAsyncUpdatePubkeyListConn, this)); } bool @@ -202,14 +203,13 @@ namespace llarp NewAsyncUpdatePubkeyListConn(abyss::http::ConnImpl* impl) { return new GetServiceNodeListHandler( - impl, this, - util::memFn(&CallerImpl::HandleServiceNodeListUpdated, this)); + impl, this, util::memFn(&CallerImpl::HandleServiceNodeListUpdated, this)); } void HandleServiceNodeListUpdated(const PubkeyList_t& list, bool updated) { - if(updated) + if (updated) { router->SetRouterWhitelist(list); } @@ -224,7 +224,7 @@ namespace llarp GetServiceNodeListHandler::HandleJSONResult(const nlohmann::json& result) { PubkeyList_t keys; - if(not result.is_object()) + if (not result.is_object()) { LogWarn("Invalid result: not an object"); handler({}, false); @@ -232,45 +232,45 @@ namespace llarp } // If lokid says tells us the block didn't change then nothing to do const auto unchanged_it = result.find("unchanged"); - if(unchanged_it != result.end() and unchanged_it->get< bool >()) + if (unchanged_it != result.end() and unchanged_it->get()) return true; const auto hash_it = result.find("block_hash"); - if(hash_it == result.end()) + if (hash_it == result.end()) { LogWarn("Invalid result: no block_hash member"); handler({}, false); return false; } else - m_Parent->m_LastBlockHash = hash_it->get< std::string >(); + m_Parent->m_LastBlockHash = hash_it->get(); const auto itr = result.find("service_node_states"); - if(itr == result.end()) + if (itr == result.end()) { LogWarn("Invalid result: no service_node_states member"); handler({}, false); return false; } - if(not itr.value().is_array()) + if (not itr.value().is_array()) { LogWarn("Invalid result: service_node_states is not an array"); handler({}, false); return false; } - for(const auto item : itr.value()) + for (const auto item : itr.value()) { - if(not item.is_object()) + if (not item.is_object()) continue; - if(not item.value("active", false)) + if (not item.value("active", false)) continue; - if(not item.value("funded", false)) + if (not item.value("funded", false)) continue; const std::string pk = item.value("pubkey_ed25519", ""); - if(pk.empty()) + if (pk.empty()) continue; PubKey k; - if(k.FromString(pk)) + if (k.FromString(pk)) keys.emplace_back(std::move(k)); } handler(keys, not keys.empty()); @@ -287,22 +287,19 @@ namespace llarp { std::string expectedHostname; AbstractRouter* router; - std::unordered_map< std::string, std::function< Response() > > m_dispatch; - Handler(::abyss::httpd::ConnImpl* conn, AbstractRouter* r, - std::string hostname) + std::unordered_map> m_dispatch; + Handler(::abyss::httpd::ConnImpl* conn, AbstractRouter* r, std::string hostname) : ::abyss::httpd::IRPCHandler(conn) , expectedHostname(std::move(hostname)) , router(r) - , m_dispatch{ - {"llarp.admin.die", [=]() { return KillRouter(); }}, - {"llarp.admin.wakeup", [=]() { return StartRouter(); }}, - {"llarp.admin.link.neighbor", - [=]() { return ListNeighbors(); }}, - {"llarp.admin.exit.list", [=]() { return ListExitLevels(); }}, - {"llarp.admin.dumpstate", [=]() { return DumpState(); }}, - {"llarp.admin.status", [=]() { return DumpStatus(); }}, - {"llarp.our.addresses", [=]() { return OurAddresses(); }}, - {"llarp.version", [=]() { return DumpVersion(); }}} + , m_dispatch{{"llarp.admin.die", [=]() { return KillRouter(); }}, + {"llarp.admin.wakeup", [=]() { return StartRouter(); }}, + {"llarp.admin.link.neighbor", [=]() { return ListNeighbors(); }}, + {"llarp.admin.exit.list", [=]() { return ListExitLevels(); }}, + {"llarp.admin.dumpstate", [=]() { return DumpState(); }}, + {"llarp.admin.status", [=]() { return DumpStatus(); }}, + {"llarp.our.addresses", [=]() { return OurAddresses(); }}, + {"llarp.version", [=]() { return DumpVersion(); }}} { } @@ -330,7 +327,7 @@ namespace llarp Response KillRouter() const { - if(not router->IsRunning()) + if (not router->IsRunning()) return {{"error", "already stopping"}}; router->Stop(); return {{"status", "OK"}}; @@ -343,7 +340,7 @@ namespace llarp router->exitContext().CalculateExitTraffic(stats); Response resp; - for(const auto& stat : stats) + for (const auto& stat : stats) { resp.emplace_back(Response{ {"ident", stat.first.ToHex()}, @@ -360,10 +357,9 @@ namespace llarp Response resp = Response::array(); router->ForEachPeer( [&](const ILinkSession* session, bool outbound) { - resp.emplace_back( - Response{{"ident", RouterID(session->GetPubKey()).ToString()}, - {"svcnode", session->GetRemoteRC().IsPublicRouter()}, - {"outbound", outbound}}); + resp.emplace_back(Response{{"ident", RouterID(session->GetPubKey()).ToString()}, + {"svcnode", session->GetRemoteRC().IsPublicRouter()}, + {"outbound", outbound}}); }, false); return resp; @@ -372,14 +368,13 @@ namespace llarp Response DumpStatus() const { - size_t numServices = 0; + size_t numServices = 0; size_t numServicesReady = 0; - Response services = Response::array(); - auto visitor = - [&](const std::string& name, - const std::shared_ptr< service::Endpoint >& ptr) -> bool { + Response services = Response::array(); + auto visitor = [&](const std::string& name, + const std::shared_ptr& ptr) -> bool { numServices++; - if(ptr->IsReady()) + if (ptr->IsReady()) numServicesReady++; const Response status{{"ready", ptr->IsReady()}, {"stopped", ptr->IsStopped()}, @@ -400,8 +395,7 @@ namespace llarp { Response services; router->hiddenServiceContext().ForEachService( - [&](const std::string&, - const std::shared_ptr< service::Endpoint >& service) { + [&](const std::string&, const std::shared_ptr& service) { const service::Address addr = service->GetIdentity().pub.Addr(); services.push_back(addr.ToString()); return true; @@ -421,7 +415,7 @@ namespace llarp HandleJSONRPC(Method_t method, const Params& /*params*/) override { auto it = m_dispatch.find(method); - if(it != m_dispatch.end()) + if (it != m_dispatch.end()) { return it->second(); } @@ -469,28 +463,26 @@ namespace llarp { sockaddr_in saddr; saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - saddr.sin_family = AF_INET; - saddr.sin_port = 1190; + saddr.sin_family = AF_INET; + saddr.sin_port = 1190; auto idx = addr.find_first_of(':'); - if(idx != std::string::npos) + if (idx != std::string::npos) { _handler.expectedHostname = addr.substr(0, idx); Addr netaddr{addr.substr(0, idx), addr.substr(1 + idx)}; saddr.sin_addr.s_addr = netaddr.ton(); - saddr.sin_port = htons(netaddr.port()); + saddr.sin_port = htons(netaddr.port()); } else { _handler.expectedHostname = addr; } - return _handler.ServeAsync(router->netloop(), router->logic(), - (const sockaddr*)&saddr); + return _handler.ServeAsync(router->netloop(), router->logic(), (const sockaddr*)&saddr); } }; - Caller::Caller(AbstractRouter* r) - : m_Impl(std::make_unique< CallerImpl >(r)) + Caller::Caller(AbstractRouter* r) : m_Impl(std::make_unique(r)) { } @@ -520,8 +512,7 @@ namespace llarp m_Impl->SetAuth(user, passwd); } - Server::Server(AbstractRouter* r) - : m_Impl(std::make_unique< ServerImpl >(r)) + Server::Server(AbstractRouter* r) : m_Impl(std::make_unique(r)) { } diff --git a/llarp/rpc/rpc.hpp b/llarp/rpc/rpc.hpp index 50509c7ea..d31cac9fb 100644 --- a/llarp/rpc/rpc.hpp +++ b/llarp/rpc/rpc.hpp @@ -30,7 +30,7 @@ namespace llarp Stop(); private: - std::unique_ptr< ServerImpl > m_Impl; + std::unique_ptr m_Impl; }; struct CallerImpl; @@ -58,7 +58,7 @@ namespace llarp Tick(llarp_time_t now); private: - std::unique_ptr< CallerImpl > m_Impl; + std::unique_ptr m_Impl; }; } // namespace rpc diff --git a/llarp/service/address.cpp b/llarp/service/address.cpp index 4ec315d61..44ff33153 100644 --- a/llarp/service/address.cpp +++ b/llarp/service/address.cpp @@ -6,7 +6,7 @@ namespace llarp { namespace service { - const std::set< std::string > Address::AllowedTLDs = {".loki", ".snode"}; + const std::set Address::AllowedTLDs = {".loki", ".snode"}; bool Address::PermitTLD(const char* tld) @@ -19,11 +19,11 @@ namespace llarp std::string Address::ToString(const char* tld) const { - if(!PermitTLD(tld)) + if (!PermitTLD(tld)) return ""; char tmp[(1 + 32) * 2] = {0}; - std::string str = Base32Encode(*this, tmp); - if(subdomain.size()) + std::string str = Base32Encode(*this, tmp); + if (subdomain.size()) str = subdomain + "." + str; return str + tld; } @@ -31,31 +31,29 @@ namespace llarp bool Address::FromString(const std::string& str, const char* tld) { - if(!PermitTLD(tld)) + if (!PermitTLD(tld)) return false; - static auto lowercase = [](const std::string s, - bool stripDots) -> std::string { + static auto lowercase = [](const std::string s, bool stripDots) -> std::string { std::string ret(s.size(), ' '); - std::transform(s.begin(), s.end(), ret.begin(), - [stripDots](const char& ch) -> char { - if(ch == '.' && stripDots) - return ' '; - return ::tolower(ch); - }); + std::transform(s.begin(), s.end(), ret.begin(), [stripDots](const char& ch) -> char { + if (ch == '.' && stripDots) + return ' '; + return ::tolower(ch); + }); return ret.substr(0, ret.find_last_of(' ')); }; const auto pos = str.find_last_of('.'); - if(pos == std::string::npos) + if (pos == std::string::npos) return false; - if(str.substr(pos) != tld) + if (str.substr(pos) != tld) return false; auto sub = str.substr(0, pos); // set subdomains if they are there const auto idx = sub.find_last_of('.'); - if(idx != std::string::npos) + if (idx != std::string::npos) { subdomain = lowercase(sub.substr(0, idx), false); - sub = sub.substr(idx + 1); + sub = sub.substr(idx + 1); } // make sure it's lowercase return Base32Decode(lowercase(sub, true), *this); diff --git a/llarp/service/address.hpp b/llarp/service/address.hpp index 5500ba70a..1633c30f3 100644 --- a/llarp/service/address.hpp +++ b/llarp/service/address.hpp @@ -15,14 +15,14 @@ namespace llarp namespace service { /// Snapp Address - struct Address : public AlignedBuffer< 32 > + struct Address : public AlignedBuffer<32> { /// if parsed using FromString this contains the subdomain /// this member is not used when comparing it's extra data for dns std::string subdomain; /// list of whitelisted gtld to permit - static const std::set< std::string > AllowedTLDs; + static const std::set AllowedTLDs; /// return true if we permit using this tld /// otherwise return false @@ -35,27 +35,26 @@ namespace llarp bool FromString(const std::string& str, const char* tld = ".loki"); - Address() : AlignedBuffer< 32 >() + Address() : AlignedBuffer<32>() { } - explicit Address(const std::string& str) : AlignedBuffer< 32 >() + explicit Address(const std::string& str) : AlignedBuffer<32>() { - if(not FromString(str)) + if (not FromString(str)) throw std::runtime_error("invalid address"); } - explicit Address(const Data& buf) : AlignedBuffer< 32 >(buf) + explicit Address(const Data& buf) : AlignedBuffer<32>(buf) { } Address(const Address& other) - : AlignedBuffer< 32 >(other.as_array()), subdomain(other.subdomain) + : AlignedBuffer<32>(other.as_array()), subdomain(other.subdomain) { } - explicit Address(const AlignedBuffer< 32 >& other) - : AlignedBuffer< 32 >(other) + explicit Address(const AlignedBuffer<32>& other) : AlignedBuffer<32>(other) { } @@ -100,8 +99,7 @@ namespace llarp size_t operator()(const Address& buf) const { - return std::accumulate(buf.begin(), buf.end(), 0, - std::bit_xor< size_t >()); + return std::accumulate(buf.begin(), buf.end(), 0, std::bit_xor()); } }; }; diff --git a/llarp/service/async_key_exchange.cpp b/llarp/service/async_key_exchange.cpp index ed45ff256..bb9f226f8 100644 --- a/llarp/service/async_key_exchange.cpp +++ b/llarp/service/async_key_exchange.cpp @@ -11,9 +11,14 @@ namespace llarp namespace service { AsyncKeyExchange::AsyncKeyExchange( - std::shared_ptr< Logic > l, ServiceInfo r, const Identity& localident, - const PQPubKey& introsetPubKey, const Introduction& remote, - IDataHandler* h, const ConvoTag& t, ProtocolType proto) + std::shared_ptr l, + ServiceInfo r, + const Identity& localident, + const PQPubKey& introsetPubKey, + const Introduction& remote, + IDataHandler* h, + const ConvoTag& t, + ProtocolType proto) : logic(std::move(l)) , m_remote(std::move(r)) , m_LocalIdentity(localident) @@ -26,8 +31,8 @@ namespace llarp } void - AsyncKeyExchange::Result(std::shared_ptr< AsyncKeyExchange > self, - std::shared_ptr< ProtocolFrame > frame) + AsyncKeyExchange::Result( + std::shared_ptr self, std::shared_ptr frame) { // put values self->handler->PutSenderFor(self->msg.tag, self->m_remote, false); @@ -38,8 +43,8 @@ namespace llarp } void - AsyncKeyExchange::Encrypt(std::shared_ptr< AsyncKeyExchange > self, - std::shared_ptr< ProtocolFrame > frame) + AsyncKeyExchange::Encrypt( + std::shared_ptr self, std::shared_ptr frame) { // derive ntru session key component SharedSecret K; @@ -51,12 +56,11 @@ namespace llarp // PKE (A, B, N) SharedSecret sharedSecret; path_dh_func dh_client = util::memFn(&Crypto::dh_client, crypto); - if(!self->m_LocalIdentity.KeyExchange(dh_client, sharedSecret, - self->m_remote, frame->N)) + if (!self->m_LocalIdentity.KeyExchange(dh_client, sharedSecret, self->m_remote, frame->N)) { LogError("failed to derive x25519 shared key component"); } - std::array< byte_t, 64 > tmp = {{0}}; + std::array tmp = {{0}}; // K std::copy(K.begin(), K.end(), tmp.begin()); // H (K + PKE(A, B, N)) @@ -69,9 +73,8 @@ namespace llarp // set version self->msg.version = LLARP_PROTO_VERSION; // encrypt and sign - if(frame->EncryptAndSign(self->msg, K, self->m_LocalIdentity)) - LogicCall(self->logic, - std::bind(&AsyncKeyExchange::Result, self, frame)); + if (frame->EncryptAndSign(self->msg, K, self->m_LocalIdentity)) + LogicCall(self->logic, std::bind(&AsyncKeyExchange::Result, self, frame)); else { LogError("failed to encrypt and sign"); diff --git a/llarp/service/async_key_exchange.hpp b/llarp/service/async_key_exchange.hpp index 854047300..1b401f660 100644 --- a/llarp/service/async_key_exchange.hpp +++ b/llarp/service/async_key_exchange.hpp @@ -11,10 +11,9 @@ namespace llarp namespace service { - struct AsyncKeyExchange - : public std::enable_shared_from_this< AsyncKeyExchange > + struct AsyncKeyExchange : public std::enable_shared_from_this { - std::shared_ptr< Logic > logic; + std::shared_ptr logic; SharedSecret sharedKey; ServiceInfo m_remote; const Identity& m_LocalIdentity; @@ -22,24 +21,26 @@ namespace llarp Introduction intro; const PQPubKey introPubKey; Introduction remoteIntro; - std::function< void(std::shared_ptr< ProtocolFrame >) > hook; + std::function)> hook; IDataHandler* handler; ConvoTag tag; - AsyncKeyExchange(std::shared_ptr< Logic > l, ServiceInfo r, - const Identity& localident, - const PQPubKey& introsetPubKey, - const Introduction& remote, IDataHandler* h, - const ConvoTag& t, ProtocolType proto); + AsyncKeyExchange( + std::shared_ptr l, + ServiceInfo r, + const Identity& localident, + const PQPubKey& introsetPubKey, + const Introduction& remote, + IDataHandler* h, + const ConvoTag& t, + ProtocolType proto); static void - Result(std::shared_ptr< AsyncKeyExchange > user, - std::shared_ptr< ProtocolFrame > frame); + Result(std::shared_ptr user, std::shared_ptr frame); /// given protocol message make protocol frame static void - Encrypt(std::shared_ptr< AsyncKeyExchange > user, - std::shared_ptr< ProtocolFrame > frame); + Encrypt(std::shared_ptr user, std::shared_ptr frame); }; } // namespace service diff --git a/llarp/service/config.cpp b/llarp/service/config.cpp index 7d0e3d65f..0bed10e3c 100644 --- a/llarp/service/config.cpp +++ b/llarp/service/config.cpp @@ -10,16 +10,15 @@ namespace llarp Config::Load(string_view fname) { ConfigParser parser; - if(!parser.LoadFile(fname)) + if (!parser.LoadFile(fname)) return false; - parser.IterAll( - [&](string_view name, const ConfigParser::Section_t& section) { - Config::section_t values; - values.first.assign(name.begin(), name.end()); - for(const auto& item : section) - values.second.emplace_back(item.first, item.second); - services.emplace_back(values); - }); + parser.IterAll([&](string_view name, const ConfigParser::Section_t& section) { + Config::section_t values; + values.first.assign(name.begin(), name.end()); + for (const auto& item : section) + values.second.emplace_back(item.first, item.second); + services.emplace_back(values); + }); return services.size() > 0; } diff --git a/llarp/service/config.hpp b/llarp/service/config.hpp index ec0401bc8..3f1074f8a 100644 --- a/llarp/service/config.hpp +++ b/llarp/service/config.hpp @@ -12,11 +12,10 @@ namespace llarp { struct Config { - using section_values_t = - std::list< std::pair< std::string, std::string > >; - using section_t = std::pair< std::string, section_values_t >; + using section_values_t = std::list>; + using section_t = std::pair; - std::list< section_t > services; + std::list services; bool Load(string_view fname); diff --git a/llarp/service/context.cpp b/llarp/service/context.cpp index bd4da3d77..ea4822263 100644 --- a/llarp/service/context.cpp +++ b/llarp/service/context.cpp @@ -12,35 +12,34 @@ namespace llarp { namespace { - using EndpointConstructor = std::function< service::Endpoint_ptr( - const std::string &, AbstractRouter *, service::Context *) >; - using EndpointConstructors = std::map< std::string, EndpointConstructor >; + using EndpointConstructor = std::function; + using EndpointConstructors = std::map; static EndpointConstructors endpointConstructors = { {"tun", - [](const std::string &nick, AbstractRouter *r, - service::Context *c) -> service::Endpoint_ptr { - return std::make_shared< handlers::TunEndpoint >(nick, r, c, - false); + [](const std::string& nick, AbstractRouter* r, service::Context* c) + -> service::Endpoint_ptr { + return std::make_shared(nick, r, c, false); }}, {"android", - [](const std::string &nick, AbstractRouter *r, - service::Context *c) -> service::Endpoint_ptr { - return std::make_shared< handlers::TunEndpoint >(nick, r, c, true); + [](const std::string& nick, AbstractRouter* r, service::Context* c) + -> service::Endpoint_ptr { + return std::make_shared(nick, r, c, true); }}, {"ios", - [](const std::string &nick, AbstractRouter *r, - service::Context *c) -> service::Endpoint_ptr { - return std::make_shared< handlers::TunEndpoint >(nick, r, c, true); + [](const std::string& nick, AbstractRouter* r, service::Context* c) + -> service::Endpoint_ptr { + return std::make_shared(nick, r, c, true); }}, {"null", - [](const std::string &nick, AbstractRouter *r, - service::Context *c) -> service::Endpoint_ptr { - return std::make_shared< handlers::NullEndpoint >(nick, r, c); + [](const std::string& nick, AbstractRouter* r, service::Context* c) + -> service::Endpoint_ptr { + return std::make_shared(nick, r, c); }}}; } // namespace - Context::Context(AbstractRouter *r) : m_Router(r) + Context::Context(AbstractRouter* r) : m_Router(r) { } @@ -50,7 +49,7 @@ namespace llarp Context::StopAll() { auto itr = m_Endpoints.begin(); - while(itr != m_Endpoints.end()) + while (itr != m_Endpoints.end()) { itr->second->Stop(); m_Stopped.emplace_back(std::move(itr->second)); @@ -64,7 +63,7 @@ namespace llarp { util::StatusObject obj{}; auto itr = m_Endpoints.begin(); - while(itr != m_Endpoints.end()) + while (itr != m_Endpoints.end()) { obj[itr->first] = itr->second->ExtractStatus(); ++itr; @@ -74,14 +73,12 @@ namespace llarp void Context::ForEachService( - std::function< bool(const std::string &, - const std::shared_ptr< Endpoint > &) > - visit) const + std::function&)> visit) const { auto itr = m_Endpoints.begin(); - while(itr != m_Endpoints.end()) + while (itr != m_Endpoints.end()) { - if(visit(itr->first, itr->second)) + if (visit(itr->first, itr->second)) ++itr; else return; @@ -89,12 +86,12 @@ namespace llarp } bool - Context::RemoveEndpoint(const std::string &name) + Context::RemoveEndpoint(const std::string& name) { auto itr = m_Endpoints.find(name); - if(itr == m_Endpoints.end()) + if (itr == m_Endpoints.end()) return false; - std::shared_ptr< Endpoint > ep = std::move(itr->second); + std::shared_ptr ep = std::move(itr->second); m_Endpoints.erase(itr); ep->Stop(); m_Stopped.emplace_back(std::move(ep)); @@ -107,16 +104,16 @@ namespace llarp // erase stopped endpoints that are done { auto itr = m_Stopped.begin(); - while(itr != m_Stopped.end()) + while (itr != m_Stopped.end()) { - if((*itr)->ShouldRemove()) + if ((*itr)->ShouldRemove()) itr = m_Stopped.erase(itr); else ++itr; } } // tick active endpoints - for(const auto &item : m_Endpoints) + for (const auto& item : m_Endpoints) { item.second->Tick(now); } @@ -128,7 +125,7 @@ namespace llarp return m_Endpoints.size() ? true : false; } - static const char * + static const char* DefaultEndpointType() { #ifdef ANDROID @@ -143,21 +140,20 @@ namespace llarp } bool - Context::AddDefaultEndpoint( - const std::unordered_multimap< std::string, std::string > &opts) + Context::AddDefaultEndpoint(const std::unordered_multimap& opts) { Config::section_values_t configOpts; configOpts.push_back({"type", DefaultEndpointType()}); // non reachable by default as this is the default endpoint // but only if no keyfile option provided - if(opts.count("keyfile") == 0) + if (opts.count("keyfile") == 0) { configOpts.push_back({"reachable", "false"}); } { auto itr = opts.begin(); - while(itr != opts.end()) + while (itr != opts.end()) { configOpts.push_back({itr->first, itr->second}); ++itr; @@ -170,9 +166,9 @@ namespace llarp Context::StartAll() { auto itr = m_Endpoints.begin(); - while(itr != m_Endpoints.end()) + while (itr != m_Endpoints.end()) { - if(!itr->second->Start()) + if (!itr->second->Start()) { LogError(itr->first, " failed to start"); return false; @@ -184,44 +180,43 @@ namespace llarp } Endpoint_ptr - Context::GetEndpointByName(const std::string &name) + Context::GetEndpointByName(const std::string& name) { auto itr = m_Endpoints.find(name); - if(itr != m_Endpoints.end()) + if (itr != m_Endpoints.end()) return itr->second; return nullptr; } void - Context::InjectEndpoint(std::string name, std::shared_ptr< Endpoint > ep) + Context::InjectEndpoint(std::string name, std::shared_ptr ep) { ep->LoadKeyFile(); - if(ep->Start()) + if (ep->Start()) { m_Endpoints.emplace(std::move(name), std::move(ep)); } } bool - Context::AddEndpoint(const Config::section_t &conf, bool autostart) + Context::AddEndpoint(const Config::section_t& conf, bool autostart) { { auto itr = m_Endpoints.find(conf.first); - if(itr != m_Endpoints.end()) + if (itr != m_Endpoints.end()) { - LogError("cannot add hidden service with duplicate name: ", - conf.first); + LogError("cannot add hidden service with duplicate name: ", conf.first); return false; } } // extract type std::string endpointType = DefaultEndpointType(); std::string keyfile; - for(const auto &option : conf.second) + for (const auto& option : conf.second) { - if(option.first == "type") + if (option.first == "type") endpointType = option.second; - if(option.first == "keyfile") + if (option.first == "keyfile") keyfile = option.second; } @@ -230,7 +225,7 @@ namespace llarp { // detect type const auto itr = endpointConstructors.find(endpointType); - if(itr == endpointConstructors.end()) + if (itr == endpointConstructors.end()) { LogError("no such endpoint type: ", endpointType); return false; @@ -238,11 +233,11 @@ namespace llarp // construct service = itr->second(conf.first, m_Router, this); - if(service) + if (service) { // if ephemeral, then we need to regen key // if privkey file, then set it and load it - if(!keyfile.empty()) + if (!keyfile.empty()) { service->SetOption("keyfile", keyfile); // load keyfile, so we have the correct name for logging @@ -252,26 +247,25 @@ namespace llarp // now Name() will be correct } } - if(service == nullptr) + if (service == nullptr) return false; // configure - for(const auto &option : conf.second) + for (const auto& option : conf.second) { - auto &k = option.first; - if(k == "type") + auto& k = option.first; + if (k == "type") continue; - auto &v = option.second; - if(!service->SetOption(k, v)) + auto& v = option.second; + if (!service->SetOption(k, v)) { - LogError("failed to set ", k, "=", v, " for hidden service endpoint ", - conf.first); + LogError("failed to set ", k, "=", v, " for hidden service endpoint ", conf.first); return false; } } - if(autostart) + if (autostart) { // start - if(service->Start()) + if (service->Start()) { LogInfo("autostarting hidden service endpoint ", service->Name()); m_Endpoints.emplace(conf.first, service); diff --git a/llarp/service/context.hpp b/llarp/service/context.hpp index c4905ddc7..8acf342b1 100644 --- a/llarp/service/context.hpp +++ b/llarp/service/context.hpp @@ -15,7 +15,7 @@ namespace llarp /// holds all the hidden service endpoints we own struct Context { - explicit Context(AbstractRouter *r); + explicit Context(AbstractRouter* r); ~Context(); void @@ -33,30 +33,27 @@ namespace llarp /// function visitor returns false to prematurely break iteration void - ForEachService( - std::function< bool(const std::string &, const Endpoint_ptr &) > - visit) const; + ForEachService(std::function visit) const; /// add default endpoint with options bool - AddDefaultEndpoint( - const std::unordered_multimap< std::string, std::string > &opts); + AddDefaultEndpoint(const std::unordered_multimap& opts); /// add endpoint via config bool - AddEndpoint(const Config::section_t &conf, bool autostart = false); + AddEndpoint(const Config::section_t& conf, bool autostart = false); /// inject endpoint instance void - InjectEndpoint(std::string name, std::shared_ptr< Endpoint > ep); + InjectEndpoint(std::string name, std::shared_ptr ep); /// stop and remove an endpoint by name /// return false if we don't have the hidden service with that name bool - RemoveEndpoint(const std::string &name); + RemoveEndpoint(const std::string& name); Endpoint_ptr - GetEndpointByName(const std::string &name); + GetEndpointByName(const std::string& name); Endpoint_ptr GetDefault() @@ -68,10 +65,9 @@ namespace llarp StartAll(); private: - AbstractRouter *const m_Router; - std::unordered_map< std::string, std::shared_ptr< Endpoint > > - m_Endpoints; - std::list< std::shared_ptr< Endpoint > > m_Stopped; + AbstractRouter* const m_Router; + std::unordered_map> m_Endpoints; + std::list> m_Stopped; }; } // namespace service } // namespace llarp diff --git a/llarp/service/endpoint.cpp b/llarp/service/endpoint.cpp index 64327d197..4925067b1 100644 --- a/llarp/service/endpoint.cpp +++ b/llarp/service/endpoint.cpp @@ -33,15 +33,12 @@ namespace llarp { namespace service { - Endpoint::Endpoint(const std::string& name, AbstractRouter* r, - Context* parent) - : path::Builder(r, 3, path::default_len) - , context(parent) - , m_RecvQueue(128) + Endpoint::Endpoint(const std::string& name, AbstractRouter* r, Context* parent) + : path::Builder(r, 3, path::default_len), context(parent), m_RecvQueue(128) { - m_state = std::make_unique< EndpointState >(); + m_state = std::make_unique(); m_state->m_Router = r; - m_state->m_Name = name; + m_state->m_Name = name; m_state->m_Tag.Zero(); m_RecvQueue.enable(); } @@ -55,7 +52,7 @@ namespace llarp llarp_ev_loop_ptr Endpoint::EndpointNetLoop() { - if(m_state->m_IsolatedNetLoop) + if (m_state->m_IsolatedNetLoop) return m_state->m_IsolatedNetLoop; return Router()->netloop(); @@ -64,53 +61,53 @@ namespace llarp bool Endpoint::NetworkIsIsolated() const { - return m_state->m_IsolatedLogic.get() != nullptr - && m_state->m_IsolatedNetLoop != nullptr; + return m_state->m_IsolatedLogic.get() != nullptr && m_state->m_IsolatedNetLoop != nullptr; } bool Endpoint::HasPendingPathToService(const Address& addr) const { - return m_state->m_PendingServiceLookups.find(addr) - != m_state->m_PendingServiceLookups.end(); + return m_state->m_PendingServiceLookups.find(addr) != m_state->m_PendingServiceLookups.end(); } void Endpoint::RegenAndPublishIntroSet(bool forceRebuild) { const auto now = llarp::time_now_ms(); - std::set< Introduction > introset; - if(!GetCurrentIntroductionsWithFilter( - introset, [now](const service::Introduction& intro) -> bool { - return not intro.ExpiresSoon(now, path::min_intro_lifetime); - })) + std::set introset; + if (!GetCurrentIntroductionsWithFilter( + introset, [now](const service::Introduction& intro) -> bool { + return not intro.ExpiresSoon(now, path::min_intro_lifetime); + })) { - LogWarn("could not publish descriptors for endpoint ", Name(), - " because we couldn't get enough valid introductions"); - if(ShouldBuildMore(now) || forceRebuild) + LogWarn( + "could not publish descriptors for endpoint ", + Name(), + " because we couldn't get enough valid introductions"); + if (ShouldBuildMore(now) || forceRebuild) ManualRebuild(1); return; } introSet().I.clear(); - for(auto& intro : introset) + for (auto& intro : introset) { introSet().I.emplace_back(std::move(intro)); } - if(introSet().I.size() == 0) + if (introSet().I.size() == 0) { LogWarn("not enough intros to publish introset for ", Name()); - if(ShouldBuildMore(now) || forceRebuild) + if (ShouldBuildMore(now) || forceRebuild) ManualRebuild(1); return; } introSet().topic = m_state->m_Tag; - auto maybe = m_Identity.EncryptAndSignIntroSet(introSet(), now); - if(not maybe.has_value()) + auto maybe = m_Identity.EncryptAndSignIntroSet(introSet(), now); + if (not maybe.has_value()) { LogWarn("failed to generate introset for endpoint ", Name()); return; } - if(PublishIntroSet(maybe.value(), Router())) + if (PublishIntroSet(maybe.value(), Router())) { LogInfo("(re)publishing introset for endpoint ", Name()); } @@ -124,9 +121,9 @@ namespace llarp Endpoint::IsReady() const { const auto now = Now(); - if(introSet().I.size() == 0) + if (introSet().I.size() == 0) return false; - if(introSet().IsExpired(now)) + if (introSet().IsExpired(now)) return false; return true; } @@ -139,24 +136,23 @@ namespace llarp } bool - Endpoint::GetEndpointWithConvoTag(const ConvoTag tag, - llarp::AlignedBuffer< 32 >& addr, - bool& snode) const + Endpoint::GetEndpointWithConvoTag( + const ConvoTag tag, llarp::AlignedBuffer<32>& addr, bool& snode) const { auto itr = Sessions().find(tag); - if(itr != Sessions().end()) + if (itr != Sessions().end()) { snode = false; - addr = itr->second.remote.Addr(); + addr = itr->second.remote.Addr(); return true; } - for(const auto& item : m_state->m_SNodeSessions) + for (const auto& item : m_state->m_SNodeSessions) { - if(item.second.second == tag) + if (item.second.second == tag) { snode = true; - addr = item.first; + addr = item.first; return true; } } @@ -173,7 +169,7 @@ namespace llarp util::StatusObject Endpoint::ExtractStatus() const { - auto obj = path::Builder::ExtractStatus(); + auto obj = path::Builder::ExtractStatus(); obj["identity"] = m_Identity.pub.Addr().ToString(); return m_state->ExtractStatus(obj); } @@ -183,7 +179,7 @@ namespace llarp const auto now = llarp::time_now_ms(); path::Builder::Tick(now); // publish descriptors - if(ShouldPublishDescriptors(now)) + if (ShouldPublishDescriptors(now)) { RegenAndPublishIntroSet(); } @@ -198,16 +194,15 @@ namespace llarp EndpointUtil::ExpirePendingRouterLookups(now, m_state->m_PendingRouters); // prefetch addrs - for(const auto& addr : m_state->m_PrefetchAddrs) + for (const auto& addr : m_state->m_PrefetchAddrs) { EnsurePathToService( addr, [](Address, OutboundContext* ctx) { #ifdef LOKINET_HIVE - std::vector< byte_t > discard; + std::vector discard; discard.resize(128); - ctx->AsyncEncryptAndSendTo(llarp_buffer_t(discard), - eProtocolControl); + ctx->AsyncEncryptAndSendTo(llarp_buffer_t(discard), eProtocolControl); #else (void)ctx; #endif @@ -218,8 +213,8 @@ namespace llarp // deregister dead sessions EndpointUtil::DeregisterDeadSessions(now, m_state->m_DeadSessions); // tick remote sessions - EndpointUtil::TickRemoteSessions(now, m_state->m_RemoteSessions, - m_state->m_DeadSessions, Sessions()); + EndpointUtil::TickRemoteSessions( + now, m_state->m_RemoteSessions, m_state->m_DeadSessions, Sessions()); // expire convotags EndpointUtil::ExpireConvoSessions(now, Sessions()); } @@ -231,7 +226,7 @@ namespace llarp EndpointUtil::StopRemoteSessions(m_state->m_RemoteSessions); // stop snode sessions EndpointUtil::StopSnodeSessions(m_state->m_SNodeSessions); - if(m_OnDown) + if (m_OnDown) m_OnDown->NotifyAsync(NotifyParams()); return path::Builder::Stop(); } @@ -239,9 +234,9 @@ namespace llarp uint64_t Endpoint::GenTXID() { - uint64_t txid = randint(); + uint64_t txid = randint(); const auto& lookups = m_state->m_PendingLookups; - while(lookups.find(txid) != lookups.end()) + while (lookups.find(txid) != lookups.end()) ++txid; return txid; } @@ -255,17 +250,16 @@ namespace llarp void Endpoint::PutLookup(IServiceLookup* lookup, uint64_t txid) { - m_state->m_PendingLookups.emplace( - txid, std::unique_ptr< IServiceLookup >(lookup)); + m_state->m_PendingLookups.emplace(txid, std::unique_ptr(lookup)); } bool Endpoint::HandleGotIntroMessage(dht::GotIntroMessage_constptr msg) { - std::set< EncryptedIntroSet > remote; - for(const auto& introset : msg->found) + std::set remote; + for (const auto& introset : msg->found) { - if(not introset.Verify(Now())) + if (not introset.Verify(Now())) { LogError(Name(), " got invalid introset"); return false; @@ -273,16 +267,16 @@ namespace llarp remote.insert(introset); } auto& lookups = m_state->m_PendingLookups; - auto itr = lookups.find(msg->txid); - if(itr == lookups.end()) + auto itr = lookups.find(msg->txid); + if (itr == lookups.end()) { - LogWarn("invalid lookup response for hidden service endpoint ", Name(), - " txid=", msg->txid); + LogWarn( + "invalid lookup response for hidden service endpoint ", Name(), " txid=", msg->txid); return true; } - std::unique_ptr< IServiceLookup > lookup = std::move(itr->second); + std::unique_ptr lookup = std::move(itr->second); lookups.erase(itr); - if(not lookup->HandleResponse(remote)) + if (not lookup->HandleResponse(remote)) lookups.emplace(msg->txid, std::move(lookup)); return true; } @@ -290,24 +284,23 @@ namespace llarp bool Endpoint::HasInboundConvo(const Address& addr) const { - for(const auto& item : Sessions()) + for (const auto& item : Sessions()) { - if(item.second.remote.Addr() == addr && item.second.inbound) + if (item.second.remote.Addr() == addr && item.second.inbound) return true; } return false; } void - Endpoint::PutSenderFor(const ConvoTag& tag, const ServiceInfo& info, - bool inbound) + Endpoint::PutSenderFor(const ConvoTag& tag, const ServiceInfo& info, bool inbound) { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) { - itr = Sessions().emplace(tag, Session{}).first; + itr = Sessions().emplace(tag, Session{}).first; itr->second.inbound = inbound; - itr->second.remote = info; + itr->second.remote = info; } itr->second.lastUsed = Now(); } @@ -316,7 +309,7 @@ namespace llarp Endpoint::GetSenderFor(const ConvoTag& tag, ServiceInfo& si) const { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) return false; si = itr->second.remote; return true; @@ -326,11 +319,11 @@ namespace llarp Endpoint::PutIntroFor(const ConvoTag& tag, const Introduction& intro) { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) { return; } - itr->second.intro = intro; + itr->second.intro = intro; itr->second.lastUsed = Now(); } @@ -338,7 +331,7 @@ namespace llarp Endpoint::GetIntroFor(const ConvoTag& tag, Introduction& intro) const { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) return false; intro = itr->second.intro; return true; @@ -348,37 +341,35 @@ namespace llarp Endpoint::PutReplyIntroFor(const ConvoTag& tag, const Introduction& intro) { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) { return; } itr->second.replyIntro = intro; - itr->second.lastUsed = Now(); + itr->second.lastUsed = Now(); } bool Endpoint::GetReplyIntroFor(const ConvoTag& tag, Introduction& intro) const { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) return false; intro = itr->second.replyIntro; return true; } bool - Endpoint::GetConvoTagsForService(const Address& addr, - std::set< ConvoTag >& tags) const + Endpoint::GetConvoTagsForService(const Address& addr, std::set& tags) const { return EndpointUtil::GetConvoTagsForService(Sessions(), addr, tags); } bool - Endpoint::GetCachedSessionKeyFor(const ConvoTag& tag, - SharedSecret& secret) const + Endpoint::GetCachedSessionKeyFor(const ConvoTag& tag, SharedSecret& secret) const { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) return false; secret = itr->second.sharedKey; return true; @@ -388,19 +379,19 @@ namespace llarp Endpoint::PutCachedSessionKeyFor(const ConvoTag& tag, const SharedSecret& k) { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) { itr = Sessions().emplace(tag, Session{}).first; } itr->second.sharedKey = k; - itr->second.lastUsed = Now(); + itr->second.lastUsed = Now(); } void Endpoint::MarkConvoTagActive(const ConvoTag& tag) { auto itr = Sessions().find(tag); - if(itr != Sessions().end()) + if (itr != Sessions().end()) { itr->second.lastUsed = Now(); } @@ -410,10 +401,9 @@ namespace llarp Endpoint::LoadKeyFile() { const auto& keyfile = m_state->m_Keyfile; - if(!keyfile.empty()) + if (!keyfile.empty()) { - if(!m_Identity.EnsureKeys(keyfile, - Router()->keyManager()->needBackup())) + if (!m_Identity.EnsureKeys(keyfile, Router()->keyManager()->needBackup())) { LogError("Can't ensure keyfile [", keyfile, "]"); return false; @@ -431,14 +421,14 @@ namespace llarp { m_state->m_RemoteLookupFilter.DecayInterval(500ms); // how can I tell if a m_Identity isn't loaded? - if(!m_DataHandler) + if (!m_DataHandler) { m_DataHandler = this; } // this does network isolation - while(m_state->m_OnInit.size()) + while (m_state->m_OnInit.size()) { - if(m_state->m_OnInit.front()()) + if (m_state->m_OnInit.front()()) m_state->m_OnInit.pop_front(); else { @@ -451,46 +441,51 @@ namespace llarp Endpoint::~Endpoint() { - if(m_OnUp) + if (m_OnUp) m_OnUp->Stop(); - if(m_OnDown) + if (m_OnDown) m_OnDown->Stop(); - if(m_OnReady) + if (m_OnReady) m_OnReady->Stop(); } bool - Endpoint::PublishIntroSet(const EncryptedIntroSet& introset, - AbstractRouter* r) + Endpoint::PublishIntroSet(const EncryptedIntroSet& introset, AbstractRouter* r) { - const auto paths = GetManyPathsWithUniqueEndpoints( - this, llarp::dht::IntroSetRelayRedundancy); + const auto paths = GetManyPathsWithUniqueEndpoints(this, llarp::dht::IntroSetRelayRedundancy); - if(paths.size() != llarp::dht::IntroSetRelayRedundancy) + if (paths.size() != llarp::dht::IntroSetRelayRedundancy) { - LogWarn("Cannot publish intro set because we only have ", paths.size(), - " paths, but need ", llarp::dht::IntroSetRelayRedundancy); + LogWarn( + "Cannot publish intro set because we only have ", + paths.size(), + " paths, but need ", + llarp::dht::IntroSetRelayRedundancy); return false; } // do publishing for each path selected size_t published = 0; - for(const auto& path : paths) + for (const auto& path : paths) { - for(size_t i = 0; i < llarp::dht::IntroSetRequestsPerRelay; ++i) + for (size_t i = 0; i < llarp::dht::IntroSetRequestsPerRelay; ++i) { - r->NotifyRouterEvent< tooling::PubIntroSentEvent >( + r->NotifyRouterEvent( r->pubkey(), llarp::dht::Key_t{introset.derivedSigningKey.as_array()}, - RouterID(path->hops[path->hops.size() - 1].rc.pubkey), published); - if(PublishIntroSetVia(introset, r, path, published)) + RouterID(path->hops[path->hops.size() - 1].rc.pubkey), + published); + if (PublishIntroSetVia(introset, r, path, published)) published++; } } - if(published != llarp::dht::IntroSetStorageRedundancy) - LogWarn("Publish introset failed: could only publish ", published, - " copies but wanted ", llarp::dht::IntroSetStorageRedundancy); + if (published != llarp::dht::IntroSetStorageRedundancy) + LogWarn( + "Publish introset failed: could only publish ", + published, + " copies but wanted ", + llarp::dht::IntroSetStorageRedundancy); return published == llarp::dht::IntroSetStorageRedundancy; } @@ -499,8 +494,8 @@ namespace llarp EncryptedIntroSet m_IntroSet; Endpoint* m_Endpoint; uint64_t m_relayOrder; - PublishIntroSetJob(Endpoint* parent, uint64_t id, - EncryptedIntroSet introset, uint64_t relayOrder) + PublishIntroSetJob( + Endpoint* parent, uint64_t id, EncryptedIntroSet introset, uint64_t relayOrder) : IServiceLookup(parent, id, "PublishIntroSet") , m_IntroSet(std::move(introset)) , m_Endpoint(parent) @@ -508,19 +503,19 @@ namespace llarp { } - std::shared_ptr< routing::IMessage > + std::shared_ptr BuildRequestMessage() override { - auto msg = std::make_shared< routing::DHTMessage >(); - msg->M.emplace_back(std::make_unique< dht::PublishIntroMessage >( - m_IntroSet, txid, true, m_relayOrder)); + auto msg = std::make_shared(); + msg->M.emplace_back( + std::make_unique(m_IntroSet, txid, true, m_relayOrder)); return msg; } bool - HandleResponse(const std::set< EncryptedIntroSet >& response) override + HandleResponse(const std::set& response) override { - if(not response.empty()) + if (not response.empty()) m_Endpoint->IntroSetPublished(); else m_Endpoint->IntroSetPublishFail(); @@ -533,24 +528,26 @@ namespace llarp Endpoint::IntroSetPublishFail() { auto now = Now(); - if(ShouldPublishDescriptors(now)) + if (ShouldPublishDescriptors(now)) { RegenAndPublishIntroSet(); } - else if(NumInStatus(path::ePathEstablished) < 3) + else if (NumInStatus(path::ePathEstablished) < 3) { - if(introSet().HasExpiredIntros(now)) + if (introSet().HasExpiredIntros(now)) ManualRebuild(1); } } bool - Endpoint::PublishIntroSetVia(const EncryptedIntroSet& introset, - AbstractRouter* r, path::Path_ptr path, - uint64_t relayOrder) + Endpoint::PublishIntroSetVia( + const EncryptedIntroSet& introset, + AbstractRouter* r, + path::Path_ptr path, + uint64_t relayOrder) { auto job = new PublishIntroSetJob(this, GenTXID(), introset, relayOrder); - if(job->SendRequestViaPath(path, r)) + if (job->SendRequestViaPath(path, r)) { m_state->m_LastPublishAttempt = Now(); return true; @@ -567,22 +564,19 @@ namespace llarp getter(item)->ResetInternalState(); }); }; - resetState(m_state->m_RemoteSessions, - [](const auto& item) { return item.second; }); - resetState(m_state->m_SNodeSessions, - [](const auto& item) { return item.second.first; }); + resetState(m_state->m_RemoteSessions, [](const auto& item) { return item.second; }); + resetState(m_state->m_SNodeSessions, [](const auto& item) { return item.second.first; }); } bool Endpoint::ShouldPublishDescriptors(llarp_time_t now) const { - if(not m_PublishIntroSet) + if (not m_PublishIntroSet) return false; auto next_pub = m_state->m_LastPublishAttempt - + (m_state->m_IntroSet.HasExpiredIntros(now) - ? INTROSET_PUBLISH_RETRY_INTERVAL - : INTROSET_PUBLISH_INTERVAL); + + (m_state->m_IntroSet.HasExpiredIntros(now) ? INTROSET_PUBLISH_RETRY_INTERVAL + : INTROSET_PUBLISH_INTERVAL); return now >= next_pub; } @@ -594,13 +588,13 @@ namespace llarp // We usually get 4 confirmations back (one for each DHT location), which // is noisy: suppress this log message if we already had a confirmation in // the last second. - if(m_state->m_LastPublish < now - 1s) + if (m_state->m_LastPublish < now - 1s) LogInfo(Name(), " IntroSet publish confirmed"); else LogDebug(Name(), " Additional IntroSet publish confirmed"); m_state->m_LastPublish = now; - if(m_OnReady) + if (m_OnReady) m_OnReady->NotifyAsync(NotifyParams()); m_OnReady = nullptr; } @@ -609,10 +603,9 @@ namespace llarp Endpoint::IsolatedNetworkMainLoop() { m_state->m_IsolatedNetLoop = llarp_make_ev_loop(); - m_state->m_IsolatedLogic = std::make_shared< llarp::Logic >(); - if(SetupNetworking()) - llarp_ev_loop_run_single_process(m_state->m_IsolatedNetLoop, - m_state->m_IsolatedLogic); + m_state->m_IsolatedLogic = std::make_shared(); + if (SetupNetworking()) + llarp_ev_loop_run_single_process(m_state->m_IsolatedNetLoop, m_state->m_IsolatedLogic); else { m_state->m_IsolatedNetLoop.reset(); @@ -621,25 +614,27 @@ namespace llarp } bool - Endpoint::SelectHop(llarp_nodedb* db, const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, path::PathRole roles) + Endpoint::SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + path::PathRole roles) { - std::set< RouterID > exclude = prev; - for(const auto& snode : SnodeBlacklist()) + std::set exclude = prev; + for (const auto& snode : SnodeBlacklist()) exclude.insert(snode); - if(hop == 0) + if (hop == 0) { const auto exits = GetExitRouters(); // exclude exit node as first hop in any paths exclude.insert(exits.begin(), exits.end()); } - if(hop == numHops - 1) + if (hop == numHops - 1) { // diversify endpoints - ForEachPath([&exclude](const path::Path_ptr& path) { - exclude.insert(path->Endpoint()); - }); + ForEachPath([&exclude](const path::Path_ptr& path) { exclude.insert(path->Endpoint()); }); } return path::Builder::SelectHop(db, exclude, cur, hop, roles); } @@ -650,13 +645,11 @@ namespace llarp path::Builder::PathBuildStarted(path); } - std::set< RouterID > + std::set Endpoint::GetExitRouters() const { - return m_ExitMap.TransformValues< RouterID >( - [](const exit::BaseSession_ptr& ptr) -> RouterID { - return ptr->Endpoint(); - }); + return m_ExitMap.TransformValues( + [](const exit::BaseSession_ptr& ptr) -> RouterID { return ptr->Endpoint(); }); } bool @@ -674,13 +667,13 @@ namespace llarp auto& remoteSessions = m_state->m_RemoteSessions; auto& serviceLookups = m_state->m_PendingServiceLookups; - if(remoteSessions.count(addr) >= MAX_OUTBOUND_CONTEXT_COUNT) + if (remoteSessions.count(addr) >= MAX_OUTBOUND_CONTEXT_COUNT) { auto itr = remoteSessions.find(addr); auto range = serviceLookups.equal_range(addr); - auto i = range.first; - while(i != range.second) + auto i = range.first; + while (i != range.second) { i->second(addr, itr->second.get()); ++i; @@ -689,14 +682,13 @@ namespace llarp return; } - auto it = remoteSessions.emplace( - addr, std::make_shared< OutboundContext >(introset, this)); + auto it = remoteSessions.emplace(addr, std::make_shared(introset, this)); LogInfo("Created New outbound context for ", addr.ToString()); // inform pending auto range = serviceLookups.equal_range(addr); - auto itr = range.first; - if(itr != range.second) + auto itr = range.first; + if (itr != range.second) { itr->second(addr, it->second.get()); ++itr; @@ -705,14 +697,13 @@ namespace llarp } void - Endpoint::HandleVerifyGotRouter(dht::GotRouterMessage_constptr msg, - llarp_async_verify_rc* j) + Endpoint::HandleVerifyGotRouter(dht::GotRouterMessage_constptr msg, llarp_async_verify_rc* j) { auto& pendingRouters = m_state->m_PendingRouters; - auto itr = pendingRouters.find(j->rc.pubkey); - if(itr != pendingRouters.end()) + auto itr = pendingRouters.find(j->rc.pubkey); + if (itr != pendingRouters.end()) { - if(j->valid) + if (j->valid) itr->second.InformResult(msg->foundRCs); else itr->second.InformResult({}); @@ -724,28 +715,27 @@ namespace llarp bool Endpoint::HandleGotRouterMessage(dht::GotRouterMessage_constptr msg) { - if(not msg->foundRCs.empty()) + if (not msg->foundRCs.empty()) { - for(const auto& rc : msg->foundRCs) + for (const auto& rc : msg->foundRCs) { llarp_async_verify_rc* job = new llarp_async_verify_rc(); - job->nodedb = Router()->nodedb(); - job->cryptoworker = Router()->threadpool(); - job->diskworker = Router()->diskworker(); - job->logic = Router()->logic(); - job->hook = std::bind(&Endpoint::HandleVerifyGotRouter, this, msg, - std::placeholders::_1); - job->rc = rc; + job->nodedb = Router()->nodedb(); + job->cryptoworker = Router()->threadpool(); + job->diskworker = Router()->diskworker(); + job->logic = Router()->logic(); + job->hook = std::bind(&Endpoint::HandleVerifyGotRouter, this, msg, std::placeholders::_1); + job->rc = rc; llarp_nodedb_async_verify(job); } } else { auto& routers = m_state->m_PendingRouters; - auto itr = routers.begin(); - while(itr != routers.end()) + auto itr = routers.begin(); + while (itr != routers.end()) { - if(itr->second.txid == msg->txid) + if (itr->second.txid == msg->txid) { itr->second.InformResult({}); itr = routers.erase(itr); @@ -760,9 +750,9 @@ namespace llarp void Endpoint::EnsureRouterIsKnown(const RouterID& router) { - if(router.IsZero()) + if (router.IsZero()) return; - if(!Router()->nodedb()->Has(router)) + if (!Router()->nodedb()->Has(router)) { LookupRouterAnon(router, nullptr); } @@ -774,25 +764,21 @@ namespace llarp using llarp::dht::FindRouterMessage; auto& routers = m_state->m_PendingRouters; - if(routers.find(router) == routers.end()) + if (routers.find(router) == routers.end()) { auto path = GetEstablishedPathClosestTo(router); routing::DHTMessage msg; auto txid = GenTXID(); - msg.M.emplace_back( - std::make_unique< FindRouterMessage >(txid, router)); + msg.M.emplace_back(std::make_unique(txid, router)); - if(path && path->SendRoutingMessage(msg, Router())) + if (path && path->SendRoutingMessage(msg, Router())) { - RouterLookupJob job(this, handler); assert(msg.M.size() == 1); - auto dhtMsg = dynamic_cast< FindRouterMessage* >(msg.M[0].get()); + auto dhtMsg = dynamic_cast(msg.M[0].get()); - m_router->NotifyRouterEvent< tooling::FindRouterSentEvent >( - m_router->pubkey(), - dhtMsg); + m_router->NotifyRouterEvent(m_router->pubkey(), dhtMsg); routers.emplace(router, RouterLookupJob(this, handler)); return true; @@ -811,15 +797,13 @@ namespace llarp } bool - Endpoint::HandleDataDrop(path::Path_ptr p, const PathID_t& dst, - uint64_t seq) + Endpoint::HandleDataDrop(path::Path_ptr p, const PathID_t& dst, uint64_t seq) { - LogWarn(Name(), " message ", seq, " dropped by endpoint ", p->Endpoint(), - " via ", dst); + LogWarn(Name(), " message ", seq, " dropped by endpoint ", p->Endpoint(), " via ", dst); return true; } - std::unordered_map< std::string, std::string > + std::unordered_map Endpoint::NotifyParams() const { return {{"LOKINET_ADDR", m_Identity.pub.Addr().ToString()}}; @@ -831,17 +815,17 @@ namespace llarp do { auto maybe = m_RecvQueue.tryPopFront(); - if(not maybe.has_value()) + if (not maybe.has_value()) return; auto ev = std::move(maybe.value()); ProtocolMessage::ProcessAsync(ev.fromPath, ev.pathid, ev.msg); - } while(true); + } while (true); } void Endpoint::QueueRecvData(RecvDataEvent ev) { - if(m_RecvQueue.full() || m_RecvQueue.empty()) + if (m_RecvQueue.full() || m_RecvQueue.empty()) { auto self = this; LogicCall(m_router->logic(), [self]() { self->FlushRecvData(); }); @@ -850,15 +834,15 @@ namespace llarp } bool - Endpoint::HandleDataMessage(path::Path_ptr path, const PathID_t from, - std::shared_ptr< ProtocolMessage > msg) + Endpoint::HandleDataMessage( + path::Path_ptr path, const PathID_t from, std::shared_ptr msg) { msg->sender.UpdateAddr(); PutSenderFor(msg->tag, msg->sender, true); PutReplyIntroFor(msg->tag, path->intro); Introduction intro; - intro.pathID = from; - intro.router = PubKey(path->Endpoint()); + intro.pathID = from; + intro.router = PubKey(path->Endpoint()); intro.expiresAt = std::min(path->ExpireTime(), msg->introReply.expiresAt); PutIntroFor(msg->tag, intro); return ProcessDataMessage(msg); @@ -868,10 +852,10 @@ namespace llarp Endpoint::HasPathToSNode(const RouterID ident) const { auto range = m_state->m_SNodeSessions.equal_range(ident); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { - if(itr->second.first->IsReady()) + if (itr->second.first->IsReady()) { return true; } @@ -881,15 +865,15 @@ namespace llarp } bool - Endpoint::ProcessDataMessage(std::shared_ptr< ProtocolMessage > msg) + Endpoint::ProcessDataMessage(std::shared_ptr msg) { - if(msg->proto == eProtocolTrafficV4 || msg->proto == eProtocolTrafficV6) + if (msg->proto == eProtocolTrafficV4 || msg->proto == eProtocolTrafficV6) { util::Lock l(m_state->m_InboundTrafficQueueMutex); m_state->m_InboundTrafficQueue.emplace(msg); return true; } - if(msg->proto == eProtocolControl) + if (msg->proto == eProtocolControl) { // TODO: implement me (?) // right now it's just random noise @@ -905,25 +889,24 @@ namespace llarp } bool - Endpoint::HandleHiddenServiceFrame(path::Path_ptr p, - const ProtocolFrame& frame) + Endpoint::HandleHiddenServiceFrame(path::Path_ptr p, const ProtocolFrame& frame) { - if(frame.R) + if (frame.R) { // handle discard ServiceInfo si; - if(!GetSenderFor(frame.T, si)) + if (!GetSenderFor(frame.T, si)) return false; // verify source - if(!frame.Verify(si)) + if (!frame.Verify(si)) return false; // remove convotag it doesn't exist LogWarn("remove convotag T=", frame.T); RemoveConvoTag(frame.T); return true; } - if(!frame.AsyncDecryptAndVerify(EndpointLogic(), p, CryptoWorker(), - m_Identity, m_DataHandler)) + if (!frame.AsyncDecryptAndVerify( + EndpointLogic(), p, CryptoWorker(), m_Identity, m_DataHandler)) { // send discard ProtocolFrame f; @@ -931,15 +914,13 @@ namespace llarp f.T = frame.T; f.F = p->intro.pathID; - if(!f.Sign(m_Identity)) + if (!f.Sign(m_Identity)) return false; { LogWarn("invalidating convotag T=", frame.T); util::Lock lock(m_state->m_SendQueueMutex); m_state->m_SendQueue.emplace_back( - std::make_shared< const routing::PathTransferMessage >(f, - frame.F), - p); + std::make_shared(f, frame.F), p); } return true; } @@ -958,22 +939,20 @@ namespace llarp } bool - Endpoint::OnLookup(const Address& addr, - nonstd::optional< IntroSet > introset, - const RouterID& endpoint) + Endpoint::OnLookup( + const Address& addr, nonstd::optional introset, const RouterID& endpoint) { const auto now = Router()->Now(); - auto& fails = m_state->m_ServiceLookupFails; - auto& lookups = m_state->m_PendingServiceLookups; - if(not introset.has_value() || introset->IsExpired(now)) + auto& fails = m_state->m_ServiceLookupFails; + auto& lookups = m_state->m_PendingServiceLookups; + if (not introset.has_value() || introset->IsExpired(now)) { - LogError(Name(), " failed to lookup ", addr.ToString(), " from ", - endpoint); + LogError(Name(), " failed to lookup ", addr.ToString(), " from ", endpoint); fails[endpoint] = fails[endpoint] + 1; // inform one auto range = lookups.equal_range(addr); - auto itr = range.first; - if(itr != range.second) + auto itr = range.first; + if (itr != range.second) { itr->second(addr, nullptr); itr = lookups.erase(itr); @@ -982,7 +961,7 @@ namespace llarp } // check for established outbound context - if(m_state->m_RemoteSessions.count(addr) > 0) + if (m_state->m_RemoteSessions.count(addr) > 0) return true; PutNewOutboundContext(introset.value()); @@ -1002,8 +981,8 @@ namespace llarp } bool - Endpoint::EnsurePathToService(const Address remote, PathEnsureHook hook, - llarp_time_t /*timeoutMS*/) + Endpoint::EnsurePathToService( + const Address remote, PathEnsureHook hook, llarp_time_t /*timeoutMS*/) { /// how many routers to use for lookups static constexpr size_t NumParallelLookups = 2; @@ -1017,7 +996,7 @@ namespace llarp { auto itr = sessions.find(remote); - if(itr != sessions.end()) + if (itr != sessions.end()) { hook(itr->first, itr->second.get()); return true; @@ -1025,29 +1004,39 @@ namespace llarp } // filter check for address - if(not m_state->m_RemoteLookupFilter.Insert(remote)) + if (not m_state->m_RemoteLookupFilter.Insert(remote)) return false; auto& lookups = m_state->m_PendingServiceLookups; - const auto paths = - GetManyPathsWithUniqueEndpoints(this, NumParallelLookups); + const auto paths = GetManyPathsWithUniqueEndpoints(this, NumParallelLookups); using namespace std::placeholders; - size_t lookedUp = 0; + size_t lookedUp = 0; const dht::Key_t location = remote.ToKey(); - uint64_t order = 0; - for(const auto& path : paths) + uint64_t order = 0; + for (const auto& path : paths) { - for(size_t count = 0; count < RequestsPerLookup; ++count) + for (size_t count = 0; count < RequestsPerLookup; ++count) { HiddenServiceAddressLookup* job = new HiddenServiceAddressLookup( - this, util::memFn(&Endpoint::OnLookup, this), location, - PubKey{remote.as_array()}, order, GenTXID()); - LogInfo("doing lookup for ", remote, " via ", path->Endpoint(), - " at ", location, " order=", order); + this, + util::memFn(&Endpoint::OnLookup, this), + location, + PubKey{remote.as_array()}, + order, + GenTXID()); + LogInfo( + "doing lookup for ", + remote, + " via ", + path->Endpoint(), + " at ", + location, + " order=", + order); order++; - if(job->SendRequestViaPath(path, Router())) + if (job->SendRequestViaPath(path, Router())) { lookups.emplace(remote, hook); lookedUp++; @@ -1064,35 +1053,39 @@ namespace llarp { static constexpr size_t MaxConcurrentSNodeSessions = 16; auto& nodeSessions = m_state->m_SNodeSessions; - if(nodeSessions.size() >= MaxConcurrentSNodeSessions) + if (nodeSessions.size() >= MaxConcurrentSNodeSessions) { // a quick client side work arround before we do proper limiting LogError(Name(), " has too many snode sessions"); return false; } using namespace std::placeholders; - if(nodeSessions.count(snode) == 0) + if (nodeSessions.count(snode) == 0) { ConvoTag tag; // TODO: check for collision lol no we don't but maybe we will... // some day :DDDDD tag.Randomize(); - auto session = std::make_shared< exit::SNodeSession >( + auto session = std::make_shared( snode, [=](const llarp_buffer_t& pkt) -> bool { /// TODO: V6 return HandleInboundPacket(tag, pkt, eProtocolTrafficV4); }, - Router(), numPaths, numHops, false, ShouldBundleRC()); + Router(), + numPaths, + numHops, + false, + ShouldBundleRC()); m_state->m_SNodeSessions.emplace(snode, std::make_pair(session, tag)); } EnsureRouterIsKnown(snode); auto range = nodeSessions.equal_range(snode); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { - if(itr->second.first->IsReady()) + if (itr->second.first->IsReady()) h(snode, itr->second.first); else { @@ -1105,14 +1098,13 @@ namespace llarp } bool - Endpoint::SendToSNodeOrQueue(const RouterID& addr, - const llarp_buffer_t& buf) + Endpoint::SendToSNodeOrQueue(const RouterID& addr, const llarp_buffer_t& buf) { - auto pkt = std::make_shared< net::IPPacket >(); - if(!pkt->Load(buf)) + auto pkt = std::make_shared(); + if (!pkt->Load(buf)) return false; EnsurePathToSNode(addr, [pkt](RouterID, exit::BaseSession_ptr s) { - if(s) + if (s) s->QueueUpstreamTraffic(*pkt, routing::ExitPadSize); }); return true; @@ -1121,16 +1113,16 @@ namespace llarp void Endpoint::Pump(llarp_time_t) { const auto& sessions = m_state->m_SNodeSessions; - auto& queue = m_state->m_InboundTrafficQueue; + auto& queue = m_state->m_InboundTrafficQueue; auto epPump = [&]() { FlushRecvData(); // send downstream packets to user for snode - for(const auto& item : sessions) + for (const auto& item : sessions) item.second.first->FlushDownstream(); // send downstream traffic to user for hidden service util::Lock lock(m_state->m_InboundTrafficQueueMutex); - while(not queue.empty()) + while (not queue.empty()) { const auto& msg = queue.top(); const llarp_buffer_t buf(msg->payload); @@ -1139,7 +1131,7 @@ namespace llarp } }; - if(NetworkIsIsolated()) + if (NetworkIsIsolated()) { LogicCall(EndpointLogic(), epPump); } @@ -1149,15 +1141,15 @@ namespace llarp } auto router = Router(); // TODO: locking on this container - for(const auto& item : m_state->m_RemoteSessions) + for (const auto& item : m_state->m_RemoteSessions) item.second->FlushUpstream(); // TODO: locking on this container - for(const auto& item : sessions) + for (const auto& item : sessions) item.second.first->FlushUpstream(); { util::Lock lock(m_state->m_SendQueueMutex); // send outbound traffic - for(const auto& item : m_state->m_SendQueue) + for (const auto& item : m_state->m_SendQueue) { item.second->SendRoutingMessage(*item.first, router); MarkConvoTagActive(item.first->T.T); @@ -1169,10 +1161,10 @@ namespace llarp } bool - Endpoint::EnsureConvo(const AlignedBuffer< 32 > /*addr*/, bool snode, - ConvoEventListener_ptr /*ev*/) + Endpoint::EnsureConvo( + const AlignedBuffer<32> /*addr*/, bool snode, ConvoEventListener_ptr /*ev*/) { - if(snode) + if (snode) { } @@ -1181,74 +1173,74 @@ namespace llarp } bool - Endpoint::SendToServiceOrQueue(const service::Address& remote, - const llarp_buffer_t& data, ProtocolType t) + Endpoint::SendToServiceOrQueue( + const service::Address& remote, const llarp_buffer_t& data, ProtocolType t) { - if(data.sz == 0) + if (data.sz == 0) return false; // inbound converstation const auto now = Now(); - if(HasInboundConvo(remote)) + if (HasInboundConvo(remote)) { - auto transfer = std::make_shared< routing::PathTransferMessage >(); + auto transfer = std::make_shared(); ProtocolFrame& f = transfer->T; - std::shared_ptr< path::Path > p; - std::set< ConvoTag > tags; - if(GetConvoTagsForService(remote, tags)) + std::shared_ptr p; + std::set tags; + if (GetConvoTagsForService(remote, tags)) { // the remote guy's intro Introduction remoteIntro; Introduction replyPath; SharedSecret K; // pick tag - for(const auto& tag : tags) + for (const auto& tag : tags) { - if(tag.IsZero()) + if (tag.IsZero()) continue; - if(!GetCachedSessionKeyFor(tag, K)) + if (!GetCachedSessionKeyFor(tag, K)) continue; - if(!GetReplyIntroFor(tag, replyPath)) + if (!GetReplyIntroFor(tag, replyPath)) continue; - if(!GetIntroFor(tag, remoteIntro)) + if (!GetIntroFor(tag, remoteIntro)) continue; // get path for intro ForEachPath([&](path::Path_ptr path) { - if(path->intro == replyPath) + if (path->intro == replyPath) { p = path; return; } - if(p && p->ExpiresSoon(now) && path->IsReady() - && path->intro.router == replyPath.router) + if (p && p->ExpiresSoon(now) && path->IsReady() + && path->intro.router == replyPath.router) { p = path; } }); - if(p) + if (p) { f.T = tag; } } - if(p) + if (p) { // TODO: check expiration of our end - auto m = std::make_shared< ProtocolMessage >(f.T); + auto m = std::make_shared(f.T); m->PutBuffer(data); f.N.Randomize(); f.C.Zero(); transfer->Y.Randomize(); - m->proto = t; + m->proto = t; m->introReply = p->intro; PutReplyIntroFor(f.T, m->introReply); - m->sender = m_Identity.pub; - m->seqno = GetSeqNoForConvo(f.T); - f.S = 1; - f.F = m->introReply.pathID; + m->sender = m_Identity.pub; + m->seqno = GetSeqNoForConvo(f.T); + f.S = 1; + f.F = m->introReply.pathID; transfer->P = remoteIntro.pathID; - auto self = this; + auto self = this; return CryptoWorker()->addJob([transfer, p, m, K, self]() { - if(not transfer->T.EncryptAndSign(*m, K, self->m_Identity)) + if (not transfer->T.EncryptAndSign(*m, K, self->m_Identity)) { LogError("failed to encrypt and sign"); return; @@ -1263,11 +1255,11 @@ namespace llarp else { auto& sessions = m_state->m_RemoteSessions; - auto range = sessions.equal_range(remote); - auto itr = range.first; - while(itr != range.second) + auto range = sessions.equal_range(remote); + auto itr = range.first; + while (itr != range.second) { - if(itr->second->ReadyToSend()) + if (itr->second->ReadyToSend()) { itr->second->AsyncEncryptAndSendTo(data, t); return true; @@ -1275,7 +1267,7 @@ namespace llarp ++itr; } // if we want to make an outbound session - if(WantsOutboundSession(remote)) + if (WantsOutboundSession(remote)) { // add pending traffic auto& traffic = m_state->m_PendingTraffic; @@ -1283,13 +1275,12 @@ namespace llarp return EnsurePathToService( remote, [self = this](Address addr, OutboundContext* ctx) { - if(ctx) + if (ctx) { ctx->UpdateIntroSet(); - for(auto& pending : self->m_state->m_PendingTraffic[addr]) + for (auto& pending : self->m_state->m_PendingTraffic[addr]) { - ctx->AsyncEncryptAndSendTo(pending.Buffer(), - pending.protocol); + ctx->AsyncEncryptAndSendTo(pending.Buffer(), pending.protocol); } } self->m_state->m_PendingTraffic.erase(addr); @@ -1310,7 +1301,7 @@ namespace llarp Endpoint::GetSeqNoForConvo(const ConvoTag& tag) { auto itr = Sessions().find(tag); - if(itr == Sessions().end()) + if (itr == Sessions().end()) return 0; return ++(itr->second.seqno); } @@ -1318,31 +1309,30 @@ namespace llarp bool Endpoint::ShouldBuildMore(llarp_time_t now) const { - if(path::Builder::BuildCooldownHit(now)) + if (path::Builder::BuildCooldownHit(now)) return false; size_t numBuilding = NumInStatus(path::ePathBuilding); - if(numBuilding > 0) + if (numBuilding > 0) return false; return ((now - lastBuild) > path::intro_path_spread) || NumInStatus(path::ePathEstablished) < path::min_intro_paths; } - std::shared_ptr< Logic > + std::shared_ptr Endpoint::RouterLogic() { return Router()->logic(); } - std::shared_ptr< Logic > + std::shared_ptr Endpoint::EndpointLogic() { - return m_state->m_IsolatedLogic ? m_state->m_IsolatedLogic - : Router()->logic(); + return m_state->m_IsolatedLogic ? m_state->m_IsolatedLogic : Router()->logic(); } - std::shared_ptr< llarp::thread::ThreadPool > + std::shared_ptr Endpoint::CryptoWorker() { return Router()->threadpool(); @@ -1354,7 +1344,7 @@ namespace llarp return m_state->m_Router; } - const std::set< RouterID >& + const std::set& Endpoint::SnodeBlacklist() const { return m_state->m_SnodeBlacklist; diff --git a/llarp/service/endpoint.hpp b/llarp/service/endpoint.hpp index 574fe85db..2a2dc0077 100644 --- a/llarp/service/endpoint.hpp +++ b/llarp/service/endpoint.hpp @@ -57,7 +57,7 @@ namespace llarp virtual void MadeConvo(const ConvoTag) = 0; }; - using ConvoEventListener_ptr = std::shared_ptr< IConvoEventListener >; + using ConvoEventListener_ptr = std::shared_ptr; /// minimum interval for publishing introsets static constexpr auto INTROSET_PUBLISH_INTERVAL = @@ -65,9 +65,7 @@ namespace llarp static constexpr auto INTROSET_PUBLISH_RETRY_INTERVAL = 5s; - struct Endpoint : public path::Builder, - public ILookupHolder, - public IDataHandler + struct Endpoint : public path::Builder, public ILookupHolder, public IDataHandler { static const size_t MAX_OUTBOUND_CONTEXT_COUNT = 4; @@ -86,7 +84,7 @@ namespace llarp IntrosetIsStale() const; /// construct parameters for notify hooks - virtual std::unordered_map< std::string, std::string > + virtual std::unordered_map NotifyParams() const; util::StatusObject @@ -128,12 +126,12 @@ namespace llarp /// router's logic /// use when sending any data on a path - std::shared_ptr< Logic > + std::shared_ptr RouterLogic(); /// endpoint's logic /// use when writing any data to local network interfaces - std::shared_ptr< Logic > + std::shared_ptr EndpointLogic(); /// borrow endpoint's net loop for sending data to user on local network @@ -142,7 +140,7 @@ namespace llarp EndpointNetLoop(); /// crypto worker threadpool - std::shared_ptr< llarp::thread::ThreadPool > + std::shared_ptr CryptoWorker(); AbstractRouter* @@ -158,7 +156,7 @@ namespace llarp Name() const override; /// get a set of all the routers we use as exit node - std::set< RouterID > + std::set GetExitRouters() const; bool @@ -171,20 +169,17 @@ namespace llarp PublishIntroSet(const EncryptedIntroSet& i, AbstractRouter* r) override; bool - PublishIntroSetVia(const EncryptedIntroSet& i, AbstractRouter* r, - path::Path_ptr p, uint64_t relayOrder); + PublishIntroSetVia( + const EncryptedIntroSet& i, AbstractRouter* r, path::Path_ptr p, uint64_t relayOrder); bool - HandleGotIntroMessage( - std::shared_ptr< const dht::GotIntroMessage > msg) override; + HandleGotIntroMessage(std::shared_ptr msg) override; bool - HandleGotRouterMessage( - std::shared_ptr< const dht::GotRouterMessage > msg) override; + HandleGotRouterMessage(std::shared_ptr msg) override; bool - HandleHiddenServiceFrame(path::Path_ptr p, - const service::ProtocolFrame& msg); + HandleHiddenServiceFrame(path::Path_ptr p, const service::ProtocolFrame& msg); // virtual huint128_t // ObtainIPForAddr(const AlignedBuffer< 32 >& addr, bool serviceNode) = 0; @@ -198,20 +193,19 @@ namespace llarp HasPendingPathToService(const Address& remote) const; bool - HandleDataMessage(path::Path_ptr path, const PathID_t from, - std::shared_ptr< ProtocolMessage > msg) override; + HandleDataMessage( + path::Path_ptr path, const PathID_t from, std::shared_ptr msg) override; /// handle packet io from service node or hidden service to frontend virtual bool - HandleInboundPacket(const ConvoTag tag, const llarp_buffer_t& pkt, - ProtocolType t) = 0; + HandleInboundPacket(const ConvoTag tag, const llarp_buffer_t& pkt, ProtocolType t) = 0; // virtual bool // HandleWriteIPPacket(const llarp_buffer_t& pkt, // std::function< huint128_t(void) > getFromIP) = 0; bool - ProcessDataMessage(std::shared_ptr< ProtocolMessage > msg); + ProcessDataMessage(std::shared_ptr msg); /// ensure that we know a router, looks up if it doesn't void @@ -242,8 +236,7 @@ namespace llarp HandlePathBuilt(path::Path_ptr path) override; bool - EnsureConvo(const AlignedBuffer< 32 > addr, bool snode, - ConvoEventListener_ptr ev); + EnsureConvo(const AlignedBuffer<32> addr, bool snode, ConvoEventListener_ptr ev); bool SendTo(const ConvoTag tag, const llarp_buffer_t& pkt, ProtocolType t); @@ -254,7 +247,7 @@ namespace llarp bool CheckPathIsDead(path::Path_ptr p, llarp_time_t latency); - using PendingBufferQueue = std::deque< PendingBuffer >; + using PendingBufferQueue = std::deque; bool WantsOutboundSession(const Address&) const override; @@ -271,8 +264,7 @@ namespace llarp /// /// return false if we don't have either bool - GetEndpointWithConvoTag(const ConvoTag t, AlignedBuffer< 32 >& addr, - bool& issnode) const; + GetEndpointWithConvoTag(const ConvoTag t, AlignedBuffer<32>& addr, bool& issnode) const; bool HasConvoTag(const ConvoTag& t) const override; @@ -282,16 +274,14 @@ namespace llarp // passed a sendto context when we have a path established otherwise // nullptr if the path was not made before the timeout - using PathEnsureHook = std::function< void(Address, OutboundContext*) >; + using PathEnsureHook = std::function; /// return false if we have already called this function before for this /// address bool - EnsurePathToService(const Address remote, PathEnsureHook h, - llarp_time_t timeoutMS); + EnsurePathToService(const Address remote, PathEnsureHook h, llarp_time_t timeoutMS); - using SNodeEnsureHook = - std::function< void(const RouterID, exit::BaseSession_ptr) >; + using SNodeEnsureHook = std::function; /// ensure a path to a service node by public key bool @@ -305,18 +295,15 @@ namespace llarp HasPathToSNode(const RouterID remote) const; void - PutSenderFor(const ConvoTag& tag, const ServiceInfo& info, - bool inbound) override; + PutSenderFor(const ConvoTag& tag, const ServiceInfo& info, bool inbound) override; bool HasInboundConvo(const Address& addr) const override; bool - GetCachedSessionKeyFor(const ConvoTag& remote, - SharedSecret& secret) const override; + GetCachedSessionKeyFor(const ConvoTag& remote, SharedSecret& secret) const override; void - PutCachedSessionKeyFor(const ConvoTag& remote, - const SharedSecret& secret) override; + PutCachedSessionKeyFor(const ConvoTag& remote, const SharedSecret& secret) override; bool GetSenderFor(const ConvoTag& remote, ServiceInfo& si) const override; @@ -334,16 +321,13 @@ namespace llarp MarkConvoTagActive(const ConvoTag& remote) override; void - PutReplyIntroFor(const ConvoTag& remote, - const Introduction& intro) override; + PutReplyIntroFor(const ConvoTag& remote, const Introduction& intro) override; bool - GetReplyIntroFor(const ConvoTag& remote, - Introduction& intro) const override; + GetReplyIntroFor(const ConvoTag& remote, Introduction& intro) const override; bool - GetConvoTagsForService(const Address& si, - std::set< ConvoTag >& tag) const override; + GetConvoTagsForService(const Address& si, std::set& tag) const override; void PutNewOutboundContext(const IntroSet& introset); @@ -352,8 +336,12 @@ namespace llarp GetSeqNoForConvo(const ConvoTag& tag); bool - SelectHop(llarp_nodedb* db, const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, path::PathRole roles) override; + SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + path::PathRole roles) override; virtual void PathBuildStarted(path::Path_ptr path) override; @@ -366,12 +354,12 @@ namespace llarp uint64_t GenTXID(); - const std::set< RouterID >& + const std::set& SnodeBlacklist() const; bool - SendToServiceOrQueue(const service::Address& addr, - const llarp_buffer_t& payload, ProtocolType t); + SendToServiceOrQueue( + const service::Address& addr, const llarp_buffer_t& payload, ProtocolType t); bool SendToSNodeOrQueue(const RouterID& addr, const llarp_buffer_t& payload); @@ -409,12 +397,13 @@ namespace llarp private: void - HandleVerifyGotRouter(dht::GotRouterMessage_constptr msg, - llarp_async_verify_rc* j); + HandleVerifyGotRouter(dht::GotRouterMessage_constptr msg, llarp_async_verify_rc* j); bool - OnLookup(const service::Address& addr, nonstd::optional< IntroSet > i, - const RouterID& endpoint); /* */ + OnLookup( + const service::Address& addr, + nonstd::optional i, + const RouterID& endpoint); /* */ bool DoNetworkIsolation(bool failed); @@ -436,7 +425,7 @@ namespace llarp protected: IDataHandler* m_DataHandler = nullptr; Identity m_Identity; - net::IPRangeMap< exit::BaseSession_ptr > m_ExitMap; + net::IPRangeMap m_ExitMap; hooks::Backend_ptr m_OnUp; hooks::Backend_ptr m_OnDown; hooks::Backend_ptr m_OnReady; @@ -457,11 +446,11 @@ namespace llarp ConvoMap& Sessions(); // clang-format on - std::unique_ptr< EndpointState > m_state; - thread::Queue< RecvDataEvent > m_RecvQueue; + std::unique_ptr m_state; + thread::Queue m_RecvQueue; }; - using Endpoint_ptr = std::shared_ptr< Endpoint >; + using Endpoint_ptr = std::shared_ptr; } // namespace service } // namespace llarp diff --git a/llarp/service/endpoint_state.cpp b/llarp/service/endpoint_state.cpp index ffdfdec07..2d92bc566 100644 --- a/llarp/service/endpoint_state.cpp +++ b/llarp/service/endpoint_state.cpp @@ -11,39 +11,38 @@ namespace llarp namespace service { bool - EndpointState::SetOption(const std::string& k, const std::string& v, - Endpoint& ep) + EndpointState::SetOption(const std::string& k, const std::string& v, Endpoint& ep) { const auto name = ep.Name(); - if(k == "keyfile") + if (k == "keyfile") { m_Keyfile = v; } - if(k == "tag") + if (k == "tag") { m_Tag = v; LogInfo("Setting tag to ", v); } - if(k == "prefetch-tag") + if (k == "prefetch-tag") { m_PrefetchTags.insert(v); } - if(k == "prefetch-addr") + if (k == "prefetch-addr") { Address addr; - if(addr.FromString(v)) + if (addr.FromString(v)) m_PrefetchAddrs.insert(addr); } - if(k == "min-latency") + if (k == "min-latency") { const auto val = atoi(v.c_str()); - if(val > 0) + if (val > 0) m_MinPathLatency = std::chrono::milliseconds(val); } - if(k == "paths") + if (k == "paths") { const auto val = atoi(v.c_str()); - if(val >= 1 && val <= static_cast< int >(path::PathSet::max_paths)) + if (val >= 1 && val <= static_cast(path::PathSet::max_paths)) { ep.numPaths = val; LogInfo(name, " set number of paths to ", ep.numHops); @@ -53,10 +52,10 @@ namespace llarp LogWarn(name, " invalid number of paths: ", v); } } - if(k == "hops") + if (k == "hops") { const auto val = atoi(v.c_str()); - if(val >= 1 && val <= static_cast< int >(path::max_len)) + if (val >= 1 && val <= static_cast(path::max_len)) { ep.numHops = val; LogInfo(name, " set number of hops to ", ep.numHops); @@ -66,46 +65,46 @@ namespace llarp LogWarn(name, " invalid number of hops: ", v); } } - if(k == "bundle-rc") + if (k == "bundle-rc") { m_BundleRC = IsTrueValue(v.c_str()); } - if(k == "blacklist-snode") + if (k == "blacklist-snode") { RouterID snode; - if(!snode.FromString(v)) + if (!snode.FromString(v)) { LogError(name, " invalid snode value: ", v); return false; } const auto result = m_SnodeBlacklist.insert(snode); - if(!result.second) + if (!result.second) { LogError(name, " duplicate blacklist-snode: ", snode.ToString()); return false; } LogInfo(name, " adding ", snode.ToString(), " to blacklist"); } - if(k == "on-up") + if (k == "on-up") { m_OnUp = hooks::ExecShellBackend(v); - if(m_OnUp) + if (m_OnUp) LogInfo(name, " added on up script: ", v); else LogError(name, " failed to add on up script"); } - if(k == "on-down") + if (k == "on-down") { m_OnDown = hooks::ExecShellBackend(v); - if(m_OnDown) + if (m_OnDown) LogInfo(name, " added on down script: ", v); else LogError(name, " failed to add on down script"); } - if(k == "on-ready") + if (k == "on-ready") { m_OnReady = hooks::ExecShellBackend(v); - if(m_OnReady) + if (m_OnReady) LogInfo(name, " added on ready script: ", v); else LogError(name, " failed to add on ready script"); @@ -116,11 +115,11 @@ namespace llarp util::StatusObject EndpointState::ExtractStatus(util::StatusObject& obj) const { - obj["lastPublished"] = to_json(m_LastPublish); + obj["lastPublished"] = to_json(m_LastPublish); obj["lastPublishAttempt"] = to_json(m_LastPublishAttempt); - obj["introset"] = m_IntroSet.ExtractStatus(); + obj["introset"] = m_IntroSet.ExtractStatus(); - if(!m_Tag.IsZero()) + if (!m_Tag.IsZero()) { obj["tag"] = m_Tag.ToString(); } @@ -130,20 +129,30 @@ namespace llarp return item.second->ExtractStatus(); }; - std::transform(m_DeadSessions.begin(), m_DeadSessions.end(), - std::back_inserter(obj["deadSessions"]), getSecond); - std::transform(m_RemoteSessions.begin(), m_RemoteSessions.end(), - std::back_inserter(obj["remoteSessions"]), getSecond); - std::transform(m_PendingLookups.begin(), m_PendingLookups.end(), - std::back_inserter(obj["lookups"]), getSecond); std::transform( - m_SNodeSessions.begin(), m_SNodeSessions.end(), + m_DeadSessions.begin(), + m_DeadSessions.end(), + std::back_inserter(obj["deadSessions"]), + getSecond); + std::transform( + m_RemoteSessions.begin(), + m_RemoteSessions.end(), + std::back_inserter(obj["remoteSessions"]), + getSecond); + std::transform( + m_PendingLookups.begin(), + m_PendingLookups.end(), + std::back_inserter(obj["lookups"]), + getSecond); + std::transform( + m_SNodeSessions.begin(), + m_SNodeSessions.end(), std::back_inserter(obj["snodeSessions"]), [](const auto& item) { return item.second.first->ExtractStatus(); }); util::StatusObject sessionObj{}; - for(const auto& item : m_Sessions) + for (const auto& item : m_Sessions) { std::string k = item.first.ToHex(); sessionObj[k] = item.second.ExtractStatus(); diff --git a/llarp/service/endpoint_state.hpp b/llarp/service/endpoint_state.hpp index e0d7e8127..089276257 100644 --- a/llarp/service/endpoint_state.hpp +++ b/llarp/service/endpoint_state.hpp @@ -18,7 +18,7 @@ #include struct llarp_ev_loop; -using llarp_ev_loop_ptr = std::shared_ptr< llarp_ev_loop >; +using llarp_ev_loop_ptr = std::shared_ptr; namespace llarp { @@ -42,63 +42,60 @@ namespace llarp util::Mutex m_InboundTrafficQueueMutex; // protects m_InboundTrafficQueue /// ordered queue for inbound hidden service traffic - RecvPacketQueue_t m_InboundTrafficQueue - GUARDED_BY(m_InboundTrafficQueueMutex); + RecvPacketQueue_t m_InboundTrafficQueue GUARDED_BY(m_InboundTrafficQueueMutex); - std::set< RouterID > m_SnodeBlacklist; + std::set m_SnodeBlacklist; AbstractRouter* m_Router; - std::shared_ptr< Logic > m_IsolatedLogic = nullptr; - llarp_ev_loop_ptr m_IsolatedNetLoop = nullptr; + std::shared_ptr m_IsolatedLogic = nullptr; + llarp_ev_loop_ptr m_IsolatedNetLoop = nullptr; std::string m_Keyfile; std::string m_Name; std::string m_NetNS; bool m_BundleRC = false; util::Mutex m_SendQueueMutex; // protects m_SendQueue - std::deque< SendEvent_t > m_SendQueue GUARDED_BY(m_SendQueueMutex); + std::deque m_SendQueue GUARDED_BY(m_SendQueueMutex); PendingTraffic m_PendingTraffic; Sessions m_RemoteSessions; Sessions m_DeadSessions; - std::set< ConvoTag > m_InboundConvos; + std::set m_InboundConvos; SNodeSessions m_SNodeSessions; - std::unordered_multimap< Address, PathEnsureHook, Address::Hash > - m_PendingServiceLookups; + std::unordered_multimap m_PendingServiceLookups; - std::unordered_map< RouterID, uint32_t, RouterID::Hash > - m_ServiceLookupFails; + std::unordered_map m_ServiceLookupFails; PendingRouters m_PendingRouters; - llarp_time_t m_LastPublish = 0s; + llarp_time_t m_LastPublish = 0s; llarp_time_t m_LastPublishAttempt = 0s; - llarp_time_t m_MinPathLatency = 1s; + llarp_time_t m_MinPathLatency = 1s; /// our introset IntroSet m_IntroSet; /// pending remote service lookups by id PendingLookups m_PendingLookups; /// prefetch remote address list - std::set< Address > m_PrefetchAddrs; + std::set
m_PrefetchAddrs; /// hidden service tag Tag m_Tag; /// prefetch descriptors for these hidden service tags - std::set< Tag > m_PrefetchTags; + std::set m_PrefetchTags; /// on initialize functions - std::list< std::function< bool(void) > > m_OnInit; + std::list> m_OnInit; /// conversations ConvoMap m_Sessions; OutboundSessions_t m_OutboundSessions; - std::unordered_map< Tag, CachedTagResult, Tag::Hash > m_PrefetchedTags; + std::unordered_map m_PrefetchedTags; - util::DecayingHashSet< Address > m_RemoteLookupFilter; + util::DecayingHashSet
m_RemoteLookupFilter; bool SetOption(const std::string& k, const std::string& v, Endpoint& ep); diff --git a/llarp/service/endpoint_types.hpp b/llarp/service/endpoint_types.hpp index 0cb850ea4..5494b8efe 100644 --- a/llarp/service/endpoint_types.hpp +++ b/llarp/service/endpoint_types.hpp @@ -24,40 +24,34 @@ namespace llarp struct IServiceLookup; struct OutboundContext; - using Msg_ptr = std::shared_ptr< const routing::PathTransferMessage >; - using SendEvent_t = std::pair< Msg_ptr, path::Path_ptr >; - using PendingBufferQueue = std::deque< PendingBuffer >; - using PendingTraffic = - std::unordered_map< Address, PendingBufferQueue, Address::Hash >; + using Msg_ptr = std::shared_ptr; + using SendEvent_t = std::pair; + using PendingBufferQueue = std::deque; + using PendingTraffic = std::unordered_map; - using ProtocolMessagePtr = std::shared_ptr< ProtocolMessage >; - using RecvPacketQueue_t = - std::priority_queue< ProtocolMessagePtr, - std::vector< ProtocolMessagePtr >, - ComparePtr< ProtocolMessagePtr > >; + using ProtocolMessagePtr = std::shared_ptr; + using RecvPacketQueue_t = std::priority_queue< + ProtocolMessagePtr, + std::vector, + ComparePtr>; - using PendingRouters = - std::unordered_map< RouterID, RouterLookupJob, RouterID::Hash >; + using PendingRouters = std::unordered_map; - using PendingLookups = - std::unordered_map< uint64_t, std::unique_ptr< IServiceLookup > >; + using PendingLookups = std::unordered_map>; using Sessions = - std::unordered_multimap< Address, std::shared_ptr< OutboundContext >, - Address::Hash >; + std::unordered_multimap, Address::Hash>; - using SNodeSessionValue = - std::pair< std::shared_ptr< exit::BaseSession >, ConvoTag >; + using SNodeSessionValue = std::pair, ConvoTag>; - using SNodeSessions = - std::unordered_multimap< RouterID, SNodeSessionValue, RouterID::Hash >; + using SNodeSessions = std::unordered_multimap; - using ConvoMap = std::unordered_map< ConvoTag, Session, ConvoTag::Hash >; + using ConvoMap = std::unordered_map; /// set of outbound addresses to maintain to - using OutboundSessions_t = std::unordered_set< Address, Address::Hash >; + using OutboundSessions_t = std::unordered_set; - using PathEnsureHook = std::function< void(Address, OutboundContext*) >; + using PathEnsureHook = std::function; } // namespace service } // namespace llarp diff --git a/llarp/service/endpoint_util.cpp b/llarp/service/endpoint_util.cpp index 0314d5886..7e4061649 100644 --- a/llarp/service/endpoint_util.cpp +++ b/llarp/service/endpoint_util.cpp @@ -13,15 +13,15 @@ namespace llarp EndpointUtil::ExpireSNodeSessions(llarp_time_t now, SNodeSessions& sessions) { auto itr = sessions.begin(); - while(itr != sessions.end()) + while (itr != sessions.end()) { - if(itr->second.first->ShouldRemove() && itr->second.first->IsStopped()) + if (itr->second.first->ShouldRemove() && itr->second.first->IsStopped()) { itr = sessions.erase(itr); continue; } // expunge next tick - if(itr->second.first->IsExpired(now)) + if (itr->second.first->IsExpired(now)) { itr->second.first->Stop(); } @@ -37,14 +37,14 @@ namespace llarp void EndpointUtil::ExpirePendingTx(llarp_time_t now, PendingLookups& lookups) { - for(auto itr = lookups.begin(); itr != lookups.end();) + for (auto itr = lookups.begin(); itr != lookups.end();) { - if(!itr->second->IsTimedOut(now)) + if (!itr->second->IsTimedOut(now)) { ++itr; continue; } - std::unique_ptr< IServiceLookup > lookup = std::move(itr->second); + std::unique_ptr lookup = std::move(itr->second); LogWarn(lookup->name, " timed out txid=", lookup->txid); lookup->HandleResponse({}); @@ -53,12 +53,11 @@ namespace llarp } void - EndpointUtil::ExpirePendingRouterLookups(llarp_time_t now, - PendingRouters& routers) + EndpointUtil::ExpirePendingRouterLookups(llarp_time_t now, PendingRouters& routers) { - for(auto itr = routers.begin(); itr != routers.end();) + for (auto itr = routers.begin(); itr != routers.end();) { - if(!itr->second.IsExpired(now)) + if (!itr->second.IsExpired(now)) { ++itr; continue; @@ -73,9 +72,9 @@ namespace llarp EndpointUtil::DeregisterDeadSessions(llarp_time_t now, Sessions& sessions) { auto itr = sessions.begin(); - while(itr != sessions.end()) + while (itr != sessions.end()) { - if(itr->second->IsDone(now)) + if (itr->second->IsDone(now)) { itr = sessions.erase(itr); } @@ -87,14 +86,14 @@ namespace llarp } void - EndpointUtil::TickRemoteSessions(llarp_time_t now, Sessions& remoteSessions, - Sessions& deadSessions, ConvoMap& sessions) + EndpointUtil::TickRemoteSessions( + llarp_time_t now, Sessions& remoteSessions, Sessions& deadSessions, ConvoMap& sessions) { auto itr = remoteSessions.begin(); - while(itr != remoteSessions.end()) + while (itr != remoteSessions.end()) { itr->second->Tick(now); - if(itr->second->Pump(now)) + if (itr->second->Pump(now)) { LogInfo("marking session as dead T=", itr->first); itr->second->Stop(); @@ -113,9 +112,9 @@ namespace llarp EndpointUtil::ExpireConvoSessions(llarp_time_t now, ConvoMap& sessions) { auto itr = sessions.begin(); - while(itr != sessions.end()) + while (itr != sessions.end()) { - if(itr->second.IsExpired(now)) + if (itr->second.IsExpired(now)) { LogInfo("Expire session T=", itr->first); itr = sessions.erase(itr); @@ -128,7 +127,7 @@ namespace llarp void EndpointUtil::StopRemoteSessions(Sessions& remoteSessions) { - for(auto& item : remoteSessions) + for (auto& item : remoteSessions) { item.second->Stop(); } @@ -137,21 +136,20 @@ namespace llarp void EndpointUtil::StopSnodeSessions(SNodeSessions& sessions) { - for(auto& item : sessions) + for (auto& item : sessions) { item.second.first->Stop(); } } bool - EndpointUtil::HasPathToService(const Address& addr, - const Sessions& remoteSessions) + EndpointUtil::HasPathToService(const Address& addr, const Sessions& remoteSessions) { auto range = remoteSessions.equal_range(addr); - auto itr = range.first; - while(itr != range.second) + auto itr = range.first; + while (itr != range.second) { - if(itr->second->ReadyToSend()) + if (itr->second->ReadyToSend()) return true; ++itr; } @@ -159,17 +157,16 @@ namespace llarp } bool - EndpointUtil::GetConvoTagsForService(const ConvoMap& sessions, - const Address& info, - std::set< ConvoTag >& tags) + EndpointUtil::GetConvoTagsForService( + const ConvoMap& sessions, const Address& info, std::set& tags) { bool inserted = false; - auto itr = sessions.begin(); - while(itr != sessions.end()) + auto itr = sessions.begin(); + while (itr != sessions.end()) { - if(itr->second.remote.Addr() == info) + if (itr->second.remote.Addr() == info) { - if(tags.emplace(itr->first).second) + if (tags.emplace(itr->first).second) { inserted = true; } diff --git a/llarp/service/endpoint_util.hpp b/llarp/service/endpoint_util.hpp index fdc1c7b7d..bdaf62c1c 100644 --- a/llarp/service/endpoint_util.hpp +++ b/llarp/service/endpoint_util.hpp @@ -22,8 +22,8 @@ namespace llarp DeregisterDeadSessions(llarp_time_t now, Sessions& sessions); static void - TickRemoteSessions(llarp_time_t now, Sessions& remoteSessions, - Sessions& deadSessions, ConvoMap& sessions); + TickRemoteSessions( + llarp_time_t now, Sessions& remoteSessions, Sessions& deadSessions, ConvoMap& sessions); static void ExpireConvoSessions(llarp_time_t now, ConvoMap& sessions); @@ -38,11 +38,11 @@ namespace llarp HasPathToService(const Address& addr, const Sessions& remoteSessions); static bool - GetConvoTagsForService(const ConvoMap& sessions, const Address& addr, - std::set< ConvoTag >& tags); + GetConvoTagsForService( + const ConvoMap& sessions, const Address& addr, std::set& tags); }; - template < typename Endpoint_t > + template static path::Path::UniqueEndpointSet_t GetManyPathsWithUniqueEndpoints(Endpoint_t* ep, size_t N, size_t tries = 10) { @@ -51,9 +51,9 @@ namespace llarp { --tries; const auto path = ep->PickRandomEstablishedPath(); - if(path) + if (path) paths.emplace(path); - } while(tries > 0 and paths.size() < N); + } while (tries > 0 and paths.size() < N); return paths; } } // namespace service diff --git a/llarp/service/handler.hpp b/llarp/service/handler.hpp index 1b5a11a57..92f511d48 100644 --- a/llarp/service/handler.hpp +++ b/llarp/service/handler.hpp @@ -13,29 +13,27 @@ namespace llarp { namespace service { - using ConvoTag = AlignedBuffer< 16 >; + using ConvoTag = AlignedBuffer<16>; struct ProtocolMessage; struct RecvDataEvent { path::Path_ptr fromPath; PathID_t pathid; - std::shared_ptr< ProtocolMessage > msg; + std::shared_ptr msg; }; struct ProtocolMessage; struct IDataHandler { virtual bool - HandleDataMessage(path::Path_ptr path, const PathID_t from, - std::shared_ptr< ProtocolMessage > msg) = 0; + HandleDataMessage( + path::Path_ptr path, const PathID_t from, std::shared_ptr msg) = 0; virtual bool - GetCachedSessionKeyFor(const ConvoTag& remote, - SharedSecret& secret) const = 0; + GetCachedSessionKeyFor(const ConvoTag& remote, SharedSecret& secret) const = 0; virtual void - PutCachedSessionKeyFor(const ConvoTag& remote, - const SharedSecret& secret) = 0; + PutCachedSessionKeyFor(const ConvoTag& remote, const SharedSecret& secret) = 0; virtual void MarkConvoTagActive(const ConvoTag& tag) = 0; @@ -47,8 +45,7 @@ namespace llarp HasConvoTag(const ConvoTag& remote) const = 0; virtual void - PutSenderFor(const ConvoTag& remote, const ServiceInfo& si, - bool inbound) = 0; + PutSenderFor(const ConvoTag& remote, const ServiceInfo& si, bool inbound) = 0; virtual bool GetSenderFor(const ConvoTag& remote, ServiceInfo& si) const = 0; @@ -66,8 +63,7 @@ namespace llarp GetReplyIntroFor(const ConvoTag& remote, Introduction& intro) const = 0; virtual bool - GetConvoTagsForService(const Address& si, - std::set< ConvoTag >& tag) const = 0; + GetConvoTagsForService(const Address& si, std::set& tag) const = 0; virtual bool HasInboundConvo(const Address& addr) const = 0; diff --git a/llarp/service/hidden_service_address_lookup.cpp b/llarp/service/hidden_service_address_lookup.cpp index d1e2759d0..6edeb942f 100644 --- a/llarp/service/hidden_service_address_lookup.cpp +++ b/llarp/service/hidden_service_address_lookup.cpp @@ -9,8 +9,12 @@ namespace llarp namespace service { HiddenServiceAddressLookup::HiddenServiceAddressLookup( - Endpoint* p, HandlerFunc h, const dht::Key_t& l, const PubKey& k, - uint64_t order, uint64_t tx) + Endpoint* p, + HandlerFunc h, + const dht::Key_t& l, + const PubKey& k, + uint64_t order, + uint64_t tx) : IServiceLookup(p, tx, "HSLookup") , rootkey(k) , relayOrder(order) @@ -20,33 +24,31 @@ namespace llarp } bool - HiddenServiceAddressLookup::HandleResponse( - const std::set< EncryptedIntroSet >& results) + HiddenServiceAddressLookup::HandleResponse(const std::set& results) { - nonstd::optional< IntroSet > found; + nonstd::optional found; const Address remote(rootkey); LogInfo("found ", results.size(), " for ", remote.ToString()); - if(results.size() > 0) + if (results.size() > 0) { EncryptedIntroSet selected; - for(const auto& introset : results) + for (const auto& introset : results) { - if(selected.OtherIsNewer(introset)) + if (selected.OtherIsNewer(introset)) selected = introset; } const auto maybe = selected.MaybeDecrypt(rootkey); - if(maybe.has_value()) + if (maybe.has_value()) found = maybe.value(); } return handle(remote, found, endpoint); } - std::shared_ptr< routing::IMessage > + std::shared_ptr HiddenServiceAddressLookup::BuildRequestMessage() { - auto msg = std::make_shared< routing::DHTMessage >(); - msg->M.emplace_back(std::make_unique< dht::FindIntroMessage >( - txid, location, relayOrder)); + auto msg = std::make_shared(); + msg->M.emplace_back(std::make_unique(txid, location, relayOrder)); return msg; } diff --git a/llarp/service/hidden_service_address_lookup.hpp b/llarp/service/hidden_service_address_lookup.hpp index 55be3df13..50140404d 100644 --- a/llarp/service/hidden_service_address_lookup.hpp +++ b/llarp/service/hidden_service_address_lookup.hpp @@ -15,21 +15,24 @@ namespace llarp const PubKey rootkey; uint64_t relayOrder; const dht::Key_t location; - using HandlerFunc = std::function< bool( - const Address&, nonstd::optional< IntroSet >, const RouterID&) >; + using HandlerFunc = + std::function, const RouterID&)>; HandlerFunc handle; - HiddenServiceAddressLookup(Endpoint* p, HandlerFunc h, - const dht::Key_t& location, - const PubKey& rootkey, uint64_t relayOrder, - uint64_t tx); + HiddenServiceAddressLookup( + Endpoint* p, + HandlerFunc h, + const dht::Key_t& location, + const PubKey& rootkey, + uint64_t relayOrder, + uint64_t tx); ~HiddenServiceAddressLookup() override = default; bool - HandleResponse(const std::set< EncryptedIntroSet >& results) override; + HandleResponse(const std::set& results) override; - std::shared_ptr< routing::IMessage > + std::shared_ptr BuildRequestMessage() override; }; } // namespace service diff --git a/llarp/service/identity.cpp b/llarp/service/identity.cpp index dcf39ebdd..a791ffe6d 100644 --- a/llarp/service/identity.cpp +++ b/llarp/service/identity.cpp @@ -11,17 +11,17 @@ namespace llarp bool Identity::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictEntry("e", enckey, buf)) + if (!BEncodeWriteDictEntry("e", enckey, buf)) return false; - if(!BEncodeWriteDictEntry("q", pq, buf)) + if (!BEncodeWriteDictEntry("q", pq, buf)) return false; - if(!BEncodeWriteDictEntry("s", signkey, buf)) + if (!BEncodeWriteDictEntry("s", signkey, buf)) return false; - if(!BEncodeWriteDictInt("v", version, buf)) + if (!BEncodeWriteDictInt("v", version, buf)) return false; - if(!BEncodeWriteDictEntry("x", vanity, buf)) + if (!BEncodeWriteDictEntry("x", vanity, buf)) return false; return bencode_end(buf); } @@ -30,14 +30,14 @@ namespace llarp Identity::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictEntry("e", enckey, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("e", enckey, read, key, buf)) return false; - if(key == "q") + if (key == "q") { llarp_buffer_t str; - if(!bencode_read_string(buf, &str)) + if (!bencode_read_string(buf, &str)) return false; - if(str.sz == 3200 || str.sz == 2818) + if (str.sz == 3200 || str.sz == 2818) { pq = str.base; return true; @@ -45,11 +45,11 @@ namespace llarp return false; } - if(!BEncodeMaybeReadDictEntry("s", signkey, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("s", signkey, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, key, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("x", vanity, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("x", vanity, read, key, buf)) return false; return read; } @@ -62,16 +62,18 @@ namespace llarp crypto->encryption_keygen(enckey); pub.Update(seckey_topublic(signkey), seckey_topublic(enckey)); crypto->pqe_keygen(pq); - if(not crypto->derive_subkey_private(derivedSignKey, signkey, 1)) + if (not crypto->derive_subkey_private(derivedSignKey, signkey, 1)) { LogError("failed to generate derived key"); } } bool - Identity::KeyExchange(path_dh_func dh, SharedSecret& result, - const ServiceInfo& other, - const KeyExchangeNonce& N) const + Identity::KeyExchange( + path_dh_func dh, + SharedSecret& result, + const ServiceInfo& other, + const KeyExchangeNonce& N) const { return dh(result, other.EncryptionPublicKey(), enckey, N); } @@ -85,45 +87,44 @@ namespace llarp bool Identity::EnsureKeys(const std::string& fname, bool needBackup) { - std::array< byte_t, 4096 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); std::error_code ec; bool exists = fs::exists(fname, ec); - if(ec) + if (ec) { LogError("Could not query file status for ", fname, ": ", ec.message()); return false; } - if(exists and needBackup) + if (exists and needBackup) { KeyManager::backupFileByMoving(fname); exists = false; } // check for file - if(!exists) + if (!exists) { // regen and encode RegenerateKeys(); - if(!BEncode(&buf)) + if (!BEncode(&buf)) return false; // rewind - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; // write - auto optional_f = - util::OpenFileStream< std::ofstream >(fname, std::ios::binary); - if(!optional_f) + auto optional_f = util::OpenFileStream(fname, std::ios::binary); + if (!optional_f) return false; auto& f = optional_f.value(); - if(!f.is_open()) + if (!f.is_open()) return false; f.write((char*)buf.cur, buf.sz); } - if(!fs::is_regular_file(fname)) + if (!fs::is_regular_file(fname)) { LogError("keyfile ", fname, " is not a regular file"); return false; @@ -135,15 +136,15 @@ namespace llarp size_t sz = inf.tellg(); inf.seekg(0, std::ios::beg); - if(sz > sizeof(tmp)) + if (sz > sizeof(tmp)) return false; // decode inf.read((char*)buf.base, sz); - if(!bencode_decode_dict(*this, &buf)) + if (!bencode_decode_dict(*this, &buf)) return false; ServiceInfo::OptNonce van; - if(!vanity.IsZero()) + if (!vanity.IsZero()) van = vanity; // update pubkeys pub.Update(seckey_topublic(signkey), seckey_topublic(enckey), van); @@ -151,36 +152,35 @@ namespace llarp return crypto->derive_subkey_private(derivedSignKey, signkey, 1); } - nonstd::optional< EncryptedIntroSet > - Identity::EncryptAndSignIntroSet(const IntroSet& other_i, - llarp_time_t now) const + nonstd::optional + Identity::EncryptAndSignIntroSet(const IntroSet& other_i, llarp_time_t now) const { EncryptedIntroSet encrypted; - if(other_i.I.size() == 0) + if (other_i.I.size() == 0) return {}; IntroSet i(other_i); encrypted.nounce.Randomize(); // set timestamp // TODO: round to nearest 1000 ms - i.T = now; + i.T = now; encrypted.signedAt = now; // set service info i.A = pub; // set public encryption key i.K = pq_keypair_to_public(pq); - std::array< byte_t, MAX_INTROSET_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(not i.BEncode(&buf)) + if (not i.BEncode(&buf)) return {}; // rewind and resize buffer - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; const SharedSecret k(i.A.Addr()); CryptoManager::instance()->xchacha20(buf, k, encrypted.nounce); encrypted.introsetPayload.resize(buf.sz); std::copy_n(buf.base, buf.sz, encrypted.introsetPayload.data()); - if(not encrypted.Sign(derivedSignKey)) + if (not encrypted.Sign(derivedSignKey)) return {}; return encrypted; } diff --git a/llarp/service/identity.hpp b/llarp/service/identity.hpp index c31f8bcf4..1185aa42c 100644 --- a/llarp/service/identity.hpp +++ b/llarp/service/identity.hpp @@ -41,13 +41,16 @@ namespace llarp EnsureKeys(const std::string& fpath, bool needBackup); bool - KeyExchange(path_dh_func dh, SharedSecret& sharedkey, - const ServiceInfo& other, const KeyExchangeNonce& N) const; + KeyExchange( + path_dh_func dh, + SharedSecret& sharedkey, + const ServiceInfo& other, + const KeyExchangeNonce& N) const; bool DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf); - nonstd::optional< EncryptedIntroSet > + nonstd::optional EncryptAndSignIntroSet(const IntroSet& i, llarp_time_t now) const; bool diff --git a/llarp/service/info.cpp b/llarp/service/info.cpp index fa444b5a6..a37110613 100644 --- a/llarp/service/info.cpp +++ b/llarp/service/info.cpp @@ -14,19 +14,17 @@ namespace llarp namespace service { bool - ServiceInfo::Verify(const llarp_buffer_t& payload, - const Signature& sig) const + ServiceInfo::Verify(const llarp_buffer_t& payload, const Signature& sig) const { return CryptoManager::instance()->verify(signkey, payload, sig); } bool - ServiceInfo::Update(const byte_t* sign, const byte_t* enc, - const OptNonce& nonce) + ServiceInfo::Update(const byte_t* sign, const byte_t* enc, const OptNonce& nonce) { signkey = sign; - enckey = enc; - if(nonce) + enckey = enc; + if (nonce) { vanity = nonce.value(); } @@ -37,13 +35,13 @@ namespace llarp ServiceInfo::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { bool read = false; - if(!BEncodeMaybeReadDictEntry("e", enckey, read, key, val)) + if (!BEncodeMaybeReadDictEntry("e", enckey, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("s", signkey, read, key, val)) + if (!BEncodeMaybeReadDictEntry("s", signkey, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, key, val)) + if (!BEncodeMaybeReadDictInt("v", version, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("x", vanity, read, key, val)) + if (!BEncodeMaybeReadDictEntry("x", vanity, read, key, val)) return false; return read; } @@ -51,17 +49,17 @@ namespace llarp bool ServiceInfo::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictEntry("e", enckey, buf)) + if (!BEncodeWriteDictEntry("e", enckey, buf)) return false; - if(!BEncodeWriteDictEntry("s", signkey, buf)) + if (!BEncodeWriteDictEntry("s", signkey, buf)) return false; - if(!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf)) + if (!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf)) return false; - if(!vanity.IsZero()) + if (!vanity.IsZero()) { - if(!BEncodeWriteDictEntry("x", vanity, buf)) + if (!BEncodeWriteDictEntry("x", vanity, buf)) return false; } return bencode_end(buf); @@ -70,7 +68,7 @@ namespace llarp std::string ServiceInfo::Name() const { - if(m_CachedAddr.IsZero()) + if (m_CachedAddr.IsZero()) { Address addr; CalculateAddress(addr.as_array()); @@ -79,7 +77,8 @@ namespace llarp return m_CachedAddr.ToString(); } - bool ServiceInfo::CalculateAddress(std::array< byte_t, 32 >& data) const + bool + ServiceInfo::CalculateAddress(std::array& data) const { data = signkey.as_array(); return true; @@ -88,7 +87,7 @@ namespace llarp bool ServiceInfo::UpdateAddr() { - if(m_CachedAddr.IsZero()) + if (m_CachedAddr.IsZero()) { return CalculateAddress(m_CachedAddr.as_array()); } diff --git a/llarp/service/info.hpp b/llarp/service/info.hpp index 4db312640..ab619bdf7 100644 --- a/llarp/service/info.hpp +++ b/llarp/service/info.hpp @@ -23,7 +23,7 @@ namespace llarp VanityNonce vanity; uint64_t version = LLARP_PROTO_VERSION; - using OptNonce = nonstd::optional< VanityNonce >; + using OptNonce = nonstd::optional; void RandomizeVanity() @@ -37,7 +37,7 @@ namespace llarp const PubKey& EncryptionPublicKey() const { - if(m_CachedAddr.IsZero()) + if (m_CachedAddr.IsZero()) { CalculateAddress(m_CachedAddr.as_array()); } @@ -45,14 +45,13 @@ namespace llarp } bool - Update(const byte_t* sign, const byte_t* enc, - const OptNonce& nonce = OptNonce()); + Update(const byte_t* sign, const byte_t* enc, const OptNonce& nonce = OptNonce()); bool operator==(const ServiceInfo& other) const { - return enckey == other.enckey && signkey == other.signkey - && version == other.version && vanity == other.vanity; + return enckey == other.enckey && signkey == other.signkey && version == other.version + && vanity == other.vanity; } bool @@ -80,7 +79,7 @@ namespace llarp const Address& Addr() const { - if(m_CachedAddr.IsZero()) + if (m_CachedAddr.IsZero()) { CalculateAddress(m_CachedAddr.as_array()); } @@ -88,12 +87,13 @@ namespace llarp } /// calculate our address - bool CalculateAddress(std::array< byte_t, 32 >& data) const; + bool + CalculateAddress(std::array& data) const; bool BDecode(llarp_buffer_t* buf) { - if(not bencode_decode_dict(*this, buf)) + if (not bencode_decode_dict(*this, buf)) return false; return UpdateAddr(); } diff --git a/llarp/service/intro.cpp b/llarp/service/intro.cpp index 58442d34e..8b748e62d 100644 --- a/llarp/service/intro.cpp +++ b/llarp/service/intro.cpp @@ -18,15 +18,15 @@ namespace llarp Introduction::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictEntry("k", router, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("k", router, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("l", latency, read, key, buf)) + if (!BEncodeMaybeReadDictInt("l", latency, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("p", pathID, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("p", pathID, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, key, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("x", expiresAt, read, key, buf)) + if (!BEncodeMaybeReadDictInt("x", expiresAt, read, key, buf)) return false; return read; } @@ -34,21 +34,21 @@ namespace llarp bool Introduction::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictEntry("k", router, buf)) + if (!BEncodeWriteDictEntry("k", router, buf)) return false; - if(latency > 0s) + if (latency > 0s) { - if(!BEncodeWriteDictInt("l", latency.count(), buf)) + if (!BEncodeWriteDictInt("l", latency.count(), buf)) return false; } - if(!BEncodeWriteDictEntry("p", pathID, buf)) + if (!BEncodeWriteDictEntry("p", pathID, buf)) return false; - if(!BEncodeWriteDictInt("v", version, buf)) + if (!BEncodeWriteDictInt("v", version, buf)) return false; - if(!BEncodeWriteDictInt("x", expiresAt.count(), buf)) + if (!BEncodeWriteDictInt("x", expiresAt.count(), buf)) return false; return bencode_end(buf); } @@ -58,7 +58,7 @@ namespace llarp { router.Zero(); pathID.Zero(); - latency = 0s; + latency = 0s; expiresAt = 0s; } diff --git a/llarp/service/intro.hpp b/llarp/service/intro.hpp index dea0e0ea8..48021548b 100644 --- a/llarp/service/intro.hpp +++ b/llarp/service/intro.hpp @@ -16,9 +16,9 @@ namespace llarp { PubKey router; PathID_t pathID; - llarp_time_t latency = 0s; + llarp_time_t latency = 0s; llarp_time_t expiresAt = 0s; - uint64_t version = LLARP_PROTO_VERSION; + uint64_t version = LLARP_PROTO_VERSION; util::StatusObject ExtractStatus() const; @@ -56,9 +56,8 @@ namespace llarp bool operator<(const Introduction& other) const { - return expiresAt < other.expiresAt || pathID < other.pathID - || router < other.router || version < other.version - || latency < other.latency; + return expiresAt < other.expiresAt || pathID < other.pathID || router < other.router + || version < other.version || latency < other.latency; } bool diff --git a/llarp/service/intro_set.cpp b/llarp/service/intro_set.cpp index fcce85160..4e4e6cebc 100644 --- a/llarp/service/intro_set.cpp +++ b/llarp/service/intro_set.cpp @@ -18,20 +18,19 @@ namespace llarp bool EncryptedIntroSet::BEncode(llarp_buffer_t* buf) const { - if(not bencode_start_dict(buf)) + if (not bencode_start_dict(buf)) return false; - if(not BEncodeWriteDictEntry("d", derivedSigningKey, buf)) + if (not BEncodeWriteDictEntry("d", derivedSigningKey, buf)) return false; - if(not BEncodeWriteDictEntry("n", nounce, buf)) + if (not BEncodeWriteDictEntry("n", nounce, buf)) return false; - if(not BEncodeWriteDictInt("s", signedAt.count(), buf)) + if (not BEncodeWriteDictInt("s", signedAt.count(), buf)) return false; - if(not bencode_write_bytestring(buf, "x", 1)) + if (not bencode_write_bytestring(buf, "x", 1)) return false; - if(not bencode_write_bytestring(buf, introsetPayload.data(), - introsetPayload.size())) + if (not bencode_write_bytestring(buf, introsetPayload.data(), introsetPayload.size())) return false; - if(not BEncodeWriteDictEntry("z", sig, buf)) + if (not BEncodeWriteDictEntry("z", sig, buf)) return false; return bencode_end(buf); } @@ -40,27 +39,27 @@ namespace llarp EncryptedIntroSet::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(key == "x") + if (key == "x") { llarp_buffer_t strbuf; - if(not bencode_read_string(buf, &strbuf)) + if (not bencode_read_string(buf, &strbuf)) return false; - if(strbuf.sz > MAX_INTROSET_SIZE) + if (strbuf.sz > MAX_INTROSET_SIZE) return false; introsetPayload.resize(strbuf.sz); std::copy_n(strbuf.base, strbuf.sz, introsetPayload.data()); return true; } - if(not BEncodeMaybeReadDictEntry("d", derivedSigningKey, read, key, buf)) + if (not BEncodeMaybeReadDictEntry("d", derivedSigningKey, read, key, buf)) return false; - if(not BEncodeMaybeReadDictEntry("n", nounce, read, key, buf)) + if (not BEncodeMaybeReadDictEntry("n", nounce, read, key, buf)) return false; - if(not BEncodeMaybeReadDictInt("s", signedAt, read, key, buf)) + if (not BEncodeMaybeReadDictInt("s", signedAt, read, key, buf)) return false; - if(not BEncodeMaybeReadDictEntry("z", sig, read, key, buf)) + if (not BEncodeMaybeReadDictEntry("z", sig, read, key, buf)) return false; return read; } @@ -78,21 +77,20 @@ namespace llarp printer.printAttribute("d", derivedSigningKey); printer.printAttribute("n", nounce); printer.printAttribute("s", signedAt.count()); - printer.printAttribute( - "x", "[" + std::to_string(introsetPayload.size()) + " bytes]"); + printer.printAttribute("x", "[" + std::to_string(introsetPayload.size()) + " bytes]"); printer.printAttribute("z", sig); return out; } - nonstd::optional< IntroSet > + nonstd::optional EncryptedIntroSet::MaybeDecrypt(const PubKey& root) const { SharedSecret k(root); IntroSet i; - std::vector< byte_t > payload = introsetPayload; + std::vector payload = introsetPayload; llarp_buffer_t buf(payload); CryptoManager::instance()->xchacha20(buf, k, nounce); - if(not i.BDecode(&buf)) + if (not i.BDecode(&buf)) return {}; return i; } @@ -107,16 +105,16 @@ namespace llarp EncryptedIntroSet::Sign(const PrivateKey& k) { signedAt = llarp::time_now_ms(); - if(not k.toPublic(derivedSigningKey)) + if (not k.toPublic(derivedSigningKey)) return false; sig.Zero(); - std::array< byte_t, MAX_INTROSET_SIZE + 128 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(not BEncode(&buf)) + if (not BEncode(&buf)) return false; - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; - if(not CryptoManager::instance()->sign(sig, k, buf)) + if (not CryptoManager::instance()->sign(sig, k, buf)) return false; LogDebug("signed encrypted introset: ", *this); return true; @@ -125,16 +123,16 @@ namespace llarp bool EncryptedIntroSet::Verify(llarp_time_t now) const { - if(IsExpired(now)) + if (IsExpired(now)) return false; - std::array< byte_t, MAX_INTROSET_SIZE + 128 > tmp; + std::array tmp; llarp_buffer_t buf(tmp); EncryptedIntroSet copy(*this); copy.sig.Zero(); - if(not copy.BEncode(&buf)) + if (not copy.BEncode(&buf)) return false; LogDebug("verify encrypted introset: ", copy, " sig = ", sig); - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; return CryptoManager::instance()->verify(derivedSigningKey, buf, sig); } @@ -143,13 +141,14 @@ namespace llarp IntroSet::ExtractStatus() const { util::StatusObject obj{{"published", to_json(T)}}; - std::vector< util::StatusObject > introsObjs; - std::transform(I.begin(), I.end(), std::back_inserter(introsObjs), - [](const auto& intro) -> util::StatusObject { - return intro.ExtractStatus(); - }); + std::vector introsObjs; + std::transform( + I.begin(), + I.end(), + std::back_inserter(introsObjs), + [](const auto& intro) -> util::StatusObject { return intro.ExtractStatus(); }); obj["intros"] = introsObjs; - if(!topic.IsZero()) + if (!topic.IsZero()) obj["topic"] = topic.ToString(); return obj; } @@ -158,35 +157,35 @@ namespace llarp IntroSet::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictEntry("a", A, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("a", A, read, key, buf)) return false; - if(key == "i") + if (key == "i") { return BEncodeReadList(I, buf); } - if(!BEncodeMaybeReadDictEntry("k", K, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("k", K, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("n", topic, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("n", topic, read, key, buf)) return false; - if(!BEncodeMaybeReadDictInt("t", T, read, key, buf)) + if (!BEncodeMaybeReadDictInt("t", T, read, key, buf)) return false; - if(key == "w") + if (key == "w") { W.emplace(); return bencode_decode_dict(*W, buf); } - if(!BEncodeMaybeReadDictInt("v", version, read, key, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, key, buf)) return false; - if(!BEncodeMaybeReadDictEntry("z", Z, read, key, buf)) + if (!BEncodeMaybeReadDictEntry("z", Z, read, key, buf)) return false; - if(read) + if (read) return true; return bencode_discard(buf); @@ -195,40 +194,40 @@ namespace llarp bool IntroSet::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictEntry("a", A, buf)) + if (!BEncodeWriteDictEntry("a", A, buf)) return false; // start introduction list - if(!bencode_write_bytestring(buf, "i", 1)) + if (!bencode_write_bytestring(buf, "i", 1)) return false; - if(!BEncodeWriteList(I.begin(), I.end(), buf)) + if (!BEncodeWriteList(I.begin(), I.end(), buf)) return false; // end introduction list // pq pubkey - if(!BEncodeWriteDictEntry("k", K, buf)) + if (!BEncodeWriteDictEntry("k", K, buf)) return false; // topic tag - if(topic.ToString().size()) + if (topic.ToString().size()) { - if(!BEncodeWriteDictEntry("n", topic, buf)) + if (!BEncodeWriteDictEntry("n", topic, buf)) return false; } // Timestamp published - if(!BEncodeWriteDictInt("t", T.count(), buf)) + if (!BEncodeWriteDictInt("t", T.count(), buf)) return false; // write version - if(!BEncodeWriteDictInt("v", version, buf)) + if (!BEncodeWriteDictInt("v", version, buf)) return false; - if(W) + if (W) { - if(!BEncodeWriteDictEntry("w", *W, buf)) + if (!BEncodeWriteDictEntry("w", *W, buf)) return false; } - if(!BEncodeWriteDictEntry("z", Z, buf)) + if (!BEncodeWriteDictEntry("z", Z, buf)) return false; return bencode_end(buf); @@ -237,8 +236,8 @@ namespace llarp bool IntroSet::HasExpiredIntros(llarp_time_t now) const { - for(const auto& i : I) - if(now >= i.expiresAt) + for (const auto& i : I) + if (now >= i.expiresAt) return true; return false; } @@ -252,48 +251,46 @@ namespace llarp bool IntroSet::Verify(llarp_time_t now) const { - std::array< byte_t, MAX_INTROSET_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); IntroSet copy; copy = *this; copy.Z.Zero(); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) { return false; } // rewind and resize buffer - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; - if(!A.Verify(buf, Z)) + if (!A.Verify(buf, Z)) { return false; } // validate PoW - if(W && !W->IsValid(now)) + if (W && !W->IsValid(now)) { return false; } // valid timestamps // add max clock skew now += MAX_INTROSET_TIME_DELTA; - for(const auto& intro : I) + for (const auto& intro : I) { - if(intro.expiresAt > now - && intro.expiresAt - now > path::default_lifetime) + if (intro.expiresAt > now && intro.expiresAt - now > path::default_lifetime) { - if(W - && intro.expiresAt - W->extendedLifetime > path::default_lifetime) + if (W && intro.expiresAt - W->extendedLifetime > path::default_lifetime) { return false; } - if(!W.has_value()) + if (!W.has_value()) { LogWarn("intro has too high expire time"); return false; } } } - if(IsExpired(now)) + if (IsExpired(now)) { LogWarn("introset expired: ", *this); return false; @@ -305,7 +302,7 @@ namespace llarp IntroSet::GetNewestIntroExpiration() const { llarp_time_t t = 0s; - for(const auto& intro : I) + for (const auto& intro : I) t = std::max(intro.expiresAt, t); return t; } @@ -320,7 +317,7 @@ namespace llarp std::string _topic = topic.ToString(); - if(!_topic.empty()) + if (!_topic.empty()) { printer.printAttribute("topic", _topic); } @@ -330,7 +327,7 @@ namespace llarp } printer.printAttribute("T", T.count()); - if(W) + if (W) { printer.printAttribute("W", W.value()); } diff --git a/llarp/service/intro_set.hpp b/llarp/service/intro_set.hpp index 8e223f90c..b15b6bd77 100644 --- a/llarp/service/intro_set.hpp +++ b/llarp/service/intro_set.hpp @@ -27,11 +27,11 @@ namespace llarp struct IntroSet { ServiceInfo A; - std::vector< Introduction > I; + std::vector I; PQPubKey K; Tag topic; llarp_time_t T = 0s; - nonstd::optional< PoW > W; + nonstd::optional W; Signature Z; uint64_t version = LLARP_PROTO_VERSION; @@ -84,10 +84,8 @@ namespace llarp inline bool operator==(const IntroSet& lhs, const IntroSet& rhs) { - return std::tie(lhs.A, lhs.I, lhs.K, lhs.T, lhs.version, lhs.topic, lhs.W, - lhs.Z) - == std::tie(rhs.A, rhs.I, rhs.K, rhs.T, rhs.version, rhs.topic, rhs.W, - rhs.Z); + return std::tie(lhs.A, lhs.I, lhs.K, lhs.T, lhs.version, lhs.topic, lhs.W, lhs.Z) + == std::tie(rhs.A, rhs.I, rhs.K, rhs.T, rhs.version, rhs.topic, rhs.W, rhs.Z); } inline bool @@ -105,13 +103,13 @@ namespace llarp /// public version of the introset that is encrypted struct EncryptedIntroSet { - using Payload_t = std::vector< byte_t >; + using Payload_t = std::vector; PubKey derivedSigningKey; llarp_time_t signedAt = 0s; Payload_t introsetPayload; TunnelNonce nounce; - nonstd::optional< Tag > topic; + nonstd::optional topic; Signature sig; bool @@ -145,7 +143,7 @@ namespace llarp util::StatusObject ExtractStatus() const; - nonstd::optional< IntroSet > + nonstd::optional MaybeDecrypt(const PubKey& rootKey) const; }; @@ -175,9 +173,8 @@ namespace llarp } using EncryptedIntroSetLookupHandler = - std::function< void(const std::vector< EncryptedIntroSet >&) >; - using IntroSetLookupHandler = - std::function< void(const std::vector< IntroSet >&) >; + std::function&)>; + using IntroSetLookupHandler = std::function&)>; } // namespace service } // namespace llarp diff --git a/llarp/service/lookup.cpp b/llarp/service/lookup.cpp index 6ffbebd71..982e45010 100644 --- a/llarp/service/lookup.cpp +++ b/llarp/service/lookup.cpp @@ -12,7 +12,7 @@ namespace llarp namespace service { - IServiceLookup::IServiceLookup(ILookupHolder *p, uint64_t tx, std::string n) + IServiceLookup::IServiceLookup(ILookupHolder* p, uint64_t tx, std::string n) : m_parent(p), txid(tx), name(std::move(n)) { m_created = time_now_ms(); @@ -20,10 +20,10 @@ namespace llarp } bool - IServiceLookup::SendRequestViaPath(path::Path_ptr path, AbstractRouter *r) + IServiceLookup::SendRequestViaPath(path::Path_ptr path, AbstractRouter* r) { auto msg = BuildRequestMessage(); - if(!msg) + if (!msg) return false; endpoint = path->Endpoint(); LogicCall(r->logic(), [=]() { path->SendRoutingMessage(*msg, r); }); diff --git a/llarp/service/lookup.hpp b/llarp/service/lookup.hpp index 628469ae8..c5005242b 100644 --- a/llarp/service/lookup.hpp +++ b/llarp/service/lookup.hpp @@ -23,12 +23,12 @@ namespace llarp struct IServiceLookup { - IServiceLookup() = delete; + IServiceLookup() = delete; virtual ~IServiceLookup() = default; /// handle lookup result virtual bool - HandleResponse(const std::set< EncryptedIntroSet >&) + HandleResponse(const std::set&) { return false; } @@ -37,13 +37,13 @@ namespace llarp bool IsTimedOut(llarp_time_t now, llarp_time_t timeout = 20s) const { - if(now <= m_created) + if (now <= m_created) return false; return now - m_created > timeout; } /// build request message for service lookup - virtual std::shared_ptr< routing::IMessage > + virtual std::shared_ptr BuildRequestMessage() = 0; /// build a new request message and send it via a path diff --git a/llarp/service/outbound_context.cpp b/llarp/service/outbound_context.cpp index ea6f08395..d4549d43b 100644 --- a/llarp/service/outbound_context.cpp +++ b/llarp/service/outbound_context.cpp @@ -38,15 +38,13 @@ namespace llarp } bool - OutboundContext::HandleDataDrop(path::Path_ptr p, const PathID_t& dst, - uint64_t seq) + OutboundContext::HandleDataDrop(path::Path_ptr p, const PathID_t& dst, uint64_t seq) { // pick another intro - if(dst == remoteIntro.pathID && remoteIntro.router == p->Endpoint()) + if (dst == remoteIntro.pathID && remoteIntro.router == p->Endpoint()) { - LogWarn(Name(), " message ", seq, " dropped by endpoint ", - p->Endpoint(), " via ", dst); - if(MarkCurrentIntroBad(Now())) + LogWarn(Name(), " message ", seq, " dropped by endpoint ", p->Endpoint(), " via ", dst); + if (MarkCurrentIntroBad(Now())) { SwapIntros(); } @@ -63,9 +61,9 @@ namespace llarp { updatingIntroSet = false; - for(const auto& intro : introset.I) + for (const auto& intro : introset.I) { - if(intro.expiresAt > m_NextIntro.expiresAt) + if (intro.expiresAt > m_NextIntro.expiresAt) m_NextIntro = intro; } } @@ -76,7 +74,7 @@ namespace llarp void OutboundContext::SwapIntros() { - if(remoteIntro != m_NextIntro) + if (remoteIntro != m_NextIntro) { LogInfo(Name(), " swap intro to use ", RouterID(m_NextIntro.router)); remoteIntro = m_NextIntro; @@ -86,29 +84,27 @@ namespace llarp } bool - OutboundContext::OnIntroSetUpdate(const Address&, - nonstd::optional< IntroSet > foundIntro, - const RouterID& endpoint) + OutboundContext::OnIntroSetUpdate( + const Address&, nonstd::optional foundIntro, const RouterID& endpoint) { - if(markedBad) + if (markedBad) return true; updatingIntroSet = false; - if(foundIntro.has_value()) + if (foundIntro.has_value()) { - if(foundIntro->T == 0s) + if (foundIntro->T == 0s) { - LogWarn(Name(), - " got introset with zero timestamp: ", foundIntro.value()); + LogWarn(Name(), " got introset with zero timestamp: ", foundIntro.value()); return true; } - if(currentIntroSet.T > foundIntro->T) + if (currentIntroSet.T > foundIntro->T) { LogInfo("introset is old, dropping"); return true; } const llarp_time_t now = Now(); - if(foundIntro->IsExpired(now)) + if (foundIntro->IsExpired(now)) { LogError("got expired introset from lookup from ", endpoint); return true; @@ -127,8 +123,7 @@ namespace llarp bool OutboundContext::ReadyToSend() const { - return (!remoteIntro.router.IsZero()) - && GetPathByRouter(remoteIntro.router) != nullptr; + return (!remoteIntro.router.IsZero()) && GetPathByRouter(remoteIntro.router) != nullptr; } void @@ -136,17 +131,16 @@ namespace llarp { const auto now = Now(); Introduction selectedIntro; - for(const auto& intro : currentIntroSet.I) + for (const auto& intro : currentIntroSet.I) { - if(intro.expiresAt > selectedIntro.expiresAt && intro.router != r) + if (intro.expiresAt > selectedIntro.expiresAt && intro.router != r) { selectedIntro = intro; } } - if(selectedIntro.router.IsZero() || selectedIntro.ExpiresSoon(now)) + if (selectedIntro.router.IsZero() || selectedIntro.ExpiresSoon(now)) return; - LogWarn(Name(), " shfiting intro off of ", r, " to ", - RouterID(selectedIntro.router)); + LogWarn(Name(), " shfiting intro off of ", r, " to ", RouterID(selectedIntro.router)); m_NextIntro = selectedIntro; } @@ -162,13 +156,12 @@ namespace llarp { path::Builder::HandlePathBuilt(p); /// don't use it if we are marked bad - if(markedBad) + if (markedBad) return; - p->SetDataHandler( - util::memFn(&OutboundContext::HandleHiddenServiceFrame, this)); + p->SetDataHandler(util::memFn(&OutboundContext::HandleHiddenServiceFrame, this)); p->SetDropHandler(util::memFn(&OutboundContext::HandleDataDrop, this)); // we now have a path to the next intro, swap intros - if(p->Endpoint() == m_NextIntro.router) + if (p->Endpoint() == m_NextIntro.router) SwapIntros(); else { @@ -177,70 +170,73 @@ namespace llarp } void - OutboundContext::AsyncGenIntro(const llarp_buffer_t& payload, - ProtocolType t) + OutboundContext::AsyncGenIntro(const llarp_buffer_t& payload, ProtocolType t) { - if(not currentConvoTag.IsZero()) + if (not currentConvoTag.IsZero()) return; - if(remoteIntro.router.IsZero()) + if (remoteIntro.router.IsZero()) SwapIntros(); auto path = m_PathSet->GetNewestPathByRouter(remoteIntro.router); - if(path == nullptr) + if (path == nullptr) { // try parent as fallback path = m_Endpoint->GetPathByRouter(remoteIntro.router); - if(path == nullptr) + if (path == nullptr) { - if(!BuildCooldownHit(Now())) + if (!BuildCooldownHit(Now())) BuildOneAlignedTo(remoteIntro.router); - LogWarn(Name(), " dropping intro frame, no path to ", - remoteIntro.router); + LogWarn(Name(), " dropping intro frame, no path to ", remoteIntro.router); return; } } currentConvoTag.Randomize(); - auto frame = std::make_shared< ProtocolFrame >(); - auto ex = std::make_shared< AsyncKeyExchange >( - m_Endpoint->RouterLogic(), remoteIdent, m_Endpoint->GetIdentity(), - currentIntroSet.K, remoteIntro, m_DataHandler, currentConvoTag, t); - - ex->hook = std::bind(&OutboundContext::Send, shared_from_this(), - std::placeholders::_1, path); + auto frame = std::make_shared(); + auto ex = std::make_shared( + m_Endpoint->RouterLogic(), + remoteIdent, + m_Endpoint->GetIdentity(), + currentIntroSet.K, + remoteIntro, + m_DataHandler, + currentConvoTag, + t); + + ex->hook = std::bind(&OutboundContext::Send, shared_from_this(), std::placeholders::_1, path); ex->msg.PutBuffer(payload); ex->msg.introReply = path->intro; - frame->F = ex->msg.introReply.pathID; - m_Endpoint->CryptoWorker()->addJob( - std::bind(&AsyncKeyExchange::Encrypt, ex, frame)); + frame->F = ex->msg.introReply.pathID; + m_Endpoint->CryptoWorker()->addJob(std::bind(&AsyncKeyExchange::Encrypt, ex, frame)); } std::string OutboundContext::Name() const { - return "OBContext:" + m_Endpoint->Name() + "-" - + currentIntroSet.A.Addr().ToString(); + return "OBContext:" + m_Endpoint->Name() + "-" + currentIntroSet.A.Addr().ToString(); } void OutboundContext::UpdateIntroSet() { - if(updatingIntroSet || markedBad) + if (updatingIntroSet || markedBad) return; const auto addr = currentIntroSet.A.Addr(); // we want to use the parent endpoint's paths because outbound context // does not implement path::PathSet::HandleGotIntroMessage - const auto paths = GetManyPathsWithUniqueEndpoints(m_Endpoint, 2); + const auto paths = GetManyPathsWithUniqueEndpoints(m_Endpoint, 2); uint64_t relayOrder = 0; - for(const auto& path : paths) + for (const auto& path : paths) { HiddenServiceAddressLookup* job = new HiddenServiceAddressLookup( m_Endpoint, util::memFn(&OutboundContext::OnIntroSetUpdate, shared_from_this()), - location, PubKey{addr.as_array()}, relayOrder, + location, + PubKey{addr.as_array()}, + relayOrder, m_Endpoint->GenTXID()); relayOrder++; - if(job->SendRequestViaPath(path, m_Endpoint->Router())) + if (job->SendRequestViaPath(path, m_Endpoint->Router())) updatingIntroSet = true; } } @@ -248,23 +244,23 @@ namespace llarp util::StatusObject OutboundContext::ExtractStatus() const { - auto obj = path::Builder::ExtractStatus(); - obj["currentConvoTag"] = currentConvoTag.ToHex(); - obj["remoteIntro"] = remoteIntro.ExtractStatus(); - obj["sessionCreatedAt"] = to_json(createdAt); - obj["lastGoodSend"] = to_json(lastGoodSend); - obj["seqno"] = sequenceNo; - obj["markedBad"] = markedBad; - obj["lastShift"] = to_json(lastShift); - obj["remoteIdentity"] = remoteIdent.Addr().ToString(); + auto obj = path::Builder::ExtractStatus(); + obj["currentConvoTag"] = currentConvoTag.ToHex(); + obj["remoteIntro"] = remoteIntro.ExtractStatus(); + obj["sessionCreatedAt"] = to_json(createdAt); + obj["lastGoodSend"] = to_json(lastGoodSend); + obj["seqno"] = sequenceNo; + obj["markedBad"] = markedBad; + obj["lastShift"] = to_json(lastShift); + obj["remoteIdentity"] = remoteIdent.Addr().ToString(); obj["currentRemoteIntroset"] = currentIntroSet.ExtractStatus(); - obj["nextIntro"] = m_NextIntro.ExtractStatus(); + obj["nextIntro"] = m_NextIntro.ExtractStatus(); - std::transform(m_BadIntros.begin(), m_BadIntros.end(), - std::back_inserter(obj["badIntros"]), - [](const auto& item) -> util::StatusObject { - return item.first.ExtractStatus(); - }); + std::transform( + m_BadIntros.begin(), + m_BadIntros.end(), + std::back_inserter(obj["badIntros"]), + [](const auto& item) -> util::StatusObject { return item.first.ExtractStatus(); }); return obj; } @@ -272,41 +268,41 @@ namespace llarp OutboundContext::Pump(llarp_time_t now) { // we are probably dead af - if(m_LookupFails > 16 || m_BuildFails > 10) + if (m_LookupFails > 16 || m_BuildFails > 10) return true; // check for expiration - if(remoteIntro.ExpiresSoon(now)) + if (remoteIntro.ExpiresSoon(now)) { UpdateIntroSet(); // shift intro if it expires "soon" - if(ShiftIntroduction()) + if (ShiftIntroduction()) SwapIntros(); // swap intros if we shifted } // lookup router in intro if set and unknown m_Endpoint->EnsureRouterIsKnown(remoteIntro.router); // expire bad intros auto itr = m_BadIntros.begin(); - while(itr != m_BadIntros.end()) + while (itr != m_BadIntros.end()) { - if(now > itr->second && now - itr->second > path::default_lifetime) + if (now > itr->second && now - itr->second > path::default_lifetime) itr = m_BadIntros.erase(itr); else ++itr; } // send control message if we look too quiet - if(lastGoodSend > 0s) + if (lastGoodSend > 0s) { - if(now - lastGoodSend > (sendTimeout / 2)) + if (now - lastGoodSend > (sendTimeout / 2)) { - if(!GetNewestPathByRouter(remoteIntro.router)) + if (!GetNewestPathByRouter(remoteIntro.router)) { - if(!BuildCooldownHit(now)) + if (!BuildCooldownHit(now)) BuildOneAlignedTo(remoteIntro.router); } else { - Encrypted< 64 > tmp; + Encrypted<64> tmp; tmp.Randomize(); llarp_buffer_t buf(tmp.data(), tmp.size()); AsyncEncryptAndSendTo(buf, eProtocolControl); @@ -314,37 +310,38 @@ namespace llarp } } // if we are dead return true so we are removed - return lastGoodSend > 0s - ? (now >= lastGoodSend && now - lastGoodSend > sendTimeout) - : (now >= createdAt && now - createdAt > connectTimeout); + return lastGoodSend > 0s ? (now >= lastGoodSend && now - lastGoodSend > sendTimeout) + : (now >= createdAt && now - createdAt > connectTimeout); } bool - OutboundContext::SelectHop(llarp_nodedb* db, - const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, - path::PathRole roles) + OutboundContext::SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + path::PathRole roles) { - if(m_NextIntro.router.IsZero() || prev.count(m_NextIntro.router)) + if (m_NextIntro.router.IsZero() || prev.count(m_NextIntro.router)) { ShiftIntroduction(false); } - if(m_NextIntro.router.IsZero()) + if (m_NextIntro.router.IsZero()) return false; - std::set< RouterID > exclude = prev; + std::set exclude = prev; exclude.insert(m_NextIntro.router); - for(const auto& snode : m_Endpoint->SnodeBlacklist()) + for (const auto& snode : m_Endpoint->SnodeBlacklist()) exclude.insert(snode); - if(hop == 0) + if (hop == 0) { // exclude any exits as our first hop const auto exits = m_Endpoint->GetExitRouters(); exclude.insert(exits.begin(), exits.end()); } - if(hop == numHops - 1) + if (hop == numHops - 1) { m_Endpoint->EnsureRouterIsKnown(m_NextIntro.router); - if(db->Get(m_NextIntro.router, cur)) + if (db->Get(m_NextIntro.router, cur)) return true; ++m_BuildFails; return false; @@ -355,15 +352,15 @@ namespace llarp bool OutboundContext::ShouldBuildMore(llarp_time_t now) const { - if(markedBad || path::Builder::BuildCooldownHit(now)) + if (markedBad || path::Builder::BuildCooldownHit(now)) return false; - const bool canBuild = NumInStatus(path::ePathBuilding) == 0 - and path::Builder::ShouldBuildMore(now); - if(not canBuild) + const bool canBuild = + NumInStatus(path::ePathBuilding) == 0 and path::Builder::ShouldBuildMore(now); + if (not canBuild) return false; llarp_time_t t = 0s; ForEachPath([&t](path::Path_ptr path) { - if(path->IsReady()) + if (path->IsReady()) t = std::max(path->ExpireTime(), t); }); return t >= now + path::default_lifetime / 4; @@ -381,22 +378,21 @@ namespace llarp // insert bad intro m_BadIntros[intro] = now; // try shifting intro without rebuild - if(ShiftIntroduction(false)) + if (ShiftIntroduction(false)) { // we shifted // check if we have a path to the next intro router - if(GetNewestPathByRouter(m_NextIntro.router)) + if (GetNewestPathByRouter(m_NextIntro.router)) return true; // we don't have a path build one if we aren't building too fast - if(!BuildCooldownHit(now)) + if (!BuildCooldownHit(now)) BuildOneAlignedTo(m_NextIntro.router); return true; } // we didn't shift check if we should update introset - if(now - lastShift >= MIN_SHIFT_INTERVAL - || currentIntroSet.HasExpiredIntros(now) - || currentIntroSet.IsExpired(now)) + if (now - lastShift >= MIN_SHIFT_INTERVAL || currentIntroSet.HasExpiredIntros(now) + || currentIntroSet.IsExpired(now)) { // update introset LogInfo(Name(), " updating introset"); @@ -410,12 +406,12 @@ namespace llarp OutboundContext::ShiftIntroduction(bool rebuild) { bool success = false; - auto now = Now(); - if(now - lastShift < MIN_SHIFT_INTERVAL) + auto now = Now(); + if (now - lastShift < MIN_SHIFT_INTERVAL) return false; - bool shifted = false; - std::vector< Introduction > intros = currentIntroSet.I; - if(intros.size() > 1) + bool shifted = false; + std::vector intros = currentIntroSet.I; + if (intros.size() > 1) { std::random_device rd; std::mt19937 g(rd()); @@ -423,50 +419,48 @@ namespace llarp } // to find a intro on the same router as before that is newer - for(const auto& intro : intros) + for (const auto& intro : intros) { - if(intro.ExpiresSoon(now)) + if (intro.ExpiresSoon(now)) continue; - if(m_Endpoint->SnodeBlacklist().count(intro.router)) + if (m_Endpoint->SnodeBlacklist().count(intro.router)) continue; - if(m_BadIntros.find(intro) == m_BadIntros.end() - && remoteIntro.router == intro.router) + if (m_BadIntros.find(intro) == m_BadIntros.end() && remoteIntro.router == intro.router) { - if(intro.expiresAt > m_NextIntro.expiresAt) + if (intro.expiresAt > m_NextIntro.expiresAt) { - success = true; + success = true; m_NextIntro = intro; return true; } } } - if(!success) + if (!success) { /// pick newer intro not on same router - for(const auto& intro : intros) + for (const auto& intro : intros) { - if(m_Endpoint->SnodeBlacklist().count(intro.router)) + if (m_Endpoint->SnodeBlacklist().count(intro.router)) continue; m_Endpoint->EnsureRouterIsKnown(intro.router); - if(intro.ExpiresSoon(now)) + if (intro.ExpiresSoon(now)) continue; - if(m_BadIntros.find(intro) == m_BadIntros.end() - && m_NextIntro != intro) + if (m_BadIntros.find(intro) == m_BadIntros.end() && m_NextIntro != intro) { - if(intro.expiresAt > m_NextIntro.expiresAt) + if (intro.expiresAt > m_NextIntro.expiresAt) { - shifted = intro.router != m_NextIntro.router; + shifted = intro.router != m_NextIntro.router; m_NextIntro = intro; - success = true; + success = true; } } } } - if(m_NextIntro.router.IsZero()) + if (m_NextIntro.router.IsZero()) return false; - if(shifted) + if (shifted) lastShift = now; - if(rebuild && !BuildCooldownHit(Now())) + if (rebuild && !BuildCooldownHit(Now())) BuildOneAlignedTo(m_NextIntro.router); return success; } @@ -478,45 +472,45 @@ namespace llarp UpdateIntroSet(); const RouterID endpoint(path->Endpoint()); // if a path to our current intro died... - if(endpoint == remoteIntro.router) + if (endpoint == remoteIntro.router) { // figure out how many paths to this router we have size_t num = 0; ForEachPath([&](const path::Path_ptr& p) { - if(p->Endpoint() == endpoint && p->IsReady()) + if (p->Endpoint() == endpoint && p->IsReady()) ++num; }); // if we have more than two then we are probably fine - if(num > 2) + if (num > 2) return; // if we have one working one ... - if(num == 1) + if (num == 1) { num = 0; ForEachPath([&](const path::Path_ptr& p) { - if(p->Endpoint() == endpoint) + if (p->Endpoint() == endpoint) ++num; }); // if we have 2 or more established or pending don't do anything - if(num > 2) + if (num > 2) return; BuildOneAlignedTo(endpoint); } - else if(num == 0) + else if (num == 0) { // we have no paths to this router right now // hop off it Introduction picked; // get the latest intro that isn't on that endpoint - for(const auto& intro : currentIntroSet.I) + for (const auto& intro : currentIntroSet.I) { - if(intro.router == endpoint) + if (intro.router == endpoint) continue; - if(intro.expiresAt > picked.expiresAt) + if (intro.expiresAt > picked.expiresAt) picked = intro; } // we got nothing - if(picked.router.IsZero()) + if (picked.router.IsZero()) { return; } @@ -525,8 +519,7 @@ namespace llarp num = 0; ForEachPath([&](const path::Path_ptr& p) { // don't count timed out paths - if(p->Status() != path::ePathTimeout - && p->Endpoint() == m_NextIntro.router) + if (p->Status() != path::ePathTimeout && p->Endpoint() == m_NextIntro.router) ++num; }); // build a path if one isn't already pending build or established @@ -536,8 +529,7 @@ namespace llarp } bool - OutboundContext::HandleHiddenServiceFrame(path::Path_ptr p, - const ProtocolFrame& frame) + OutboundContext::HandleHiddenServiceFrame(path::Path_ptr p, const ProtocolFrame& frame) { return m_Endpoint->HandleHiddenServiceFrame(p, frame); } diff --git a/llarp/service/outbound_context.hpp b/llarp/service/outbound_context.hpp index 5d8e2ace3..d30cf04f2 100644 --- a/llarp/service/outbound_context.hpp +++ b/llarp/service/outbound_context.hpp @@ -16,10 +16,9 @@ namespace llarp struct Endpoint; /// context needed to initiate an outbound hidden service session - struct OutboundContext - : public path::Builder, - public SendContext, - public std::enable_shared_from_this< OutboundContext > + struct OutboundContext : public path::Builder, + public SendContext, + public std::enable_shared_from_this { OutboundContext(const IntroSet& introSet, Endpoint* parent); ~OutboundContext() override; @@ -97,8 +96,12 @@ namespace llarp HandlePathBuildTimeout(path::Path_ptr path) override; bool - SelectHop(llarp_nodedb* db, const std::set< RouterID >& prev, - RouterContact& cur, size_t hop, path::PathRole roles) override; + SelectHop( + llarp_nodedb* db, + const std::set& prev, + RouterContact& cur, + size_t hop, + path::PathRole roles) override; bool HandleHiddenServiceFrame(path::Path_ptr p, const ProtocolFrame& frame); @@ -115,18 +118,16 @@ namespace llarp OnGeneratedIntroFrame(AsyncKeyExchange* k, PathID_t p); bool - OnIntroSetUpdate(const Address& addr, nonstd::optional< IntroSet > i, - const RouterID& endpoint); + OnIntroSetUpdate(const Address& addr, nonstd::optional i, const RouterID& endpoint); const dht::Key_t location; uint64_t m_UpdateIntrosetTX = 0; IntroSet currentIntroSet; Introduction m_NextIntro; - std::unordered_map< Introduction, llarp_time_t, Introduction::Hash > - m_BadIntros; + std::unordered_map m_BadIntros; llarp_time_t lastShift = 0s; uint16_t m_LookupFails = 0; - uint16_t m_BuildFails = 0; + uint16_t m_BuildFails = 0; }; } // namespace service diff --git a/llarp/service/pendingbuffer.hpp b/llarp/service/pendingbuffer.hpp index 11a0ce37c..9e0b8f4f0 100644 --- a/llarp/service/pendingbuffer.hpp +++ b/llarp/service/pendingbuffer.hpp @@ -14,11 +14,10 @@ namespace llarp { struct PendingBuffer { - std::vector< byte_t > payload; + std::vector payload; ProtocolType protocol; - PendingBuffer(const llarp_buffer_t& buf, ProtocolType t) - : payload(buf.sz), protocol(t) + PendingBuffer(const llarp_buffer_t& buf, ProtocolType t) : payload(buf.sz), protocol(t) { std::copy(buf.base, buf.base + buf.sz, std::back_inserter(payload)); } diff --git a/llarp/service/protocol.cpp b/llarp/service/protocol.cpp index 9e7b97d1a..59876a81d 100644 --- a/llarp/service/protocol.cpp +++ b/llarp/service/protocol.cpp @@ -31,10 +31,10 @@ namespace llarp } void - ProtocolMessage::ProcessAsync(path::Path_ptr path, PathID_t from, - std::shared_ptr< ProtocolMessage > self) + ProtocolMessage::ProcessAsync( + path::Path_ptr path, PathID_t from, std::shared_ptr self) { - if(!self->handler->HandleDataMessage(path, from, self)) + if (!self->handler->HandleDataMessage(path, from, self)) LogWarn("failed to handle data message from ", path->Name()); } @@ -42,25 +42,25 @@ namespace llarp ProtocolMessage::DecodeKey(const llarp_buffer_t& k, llarp_buffer_t* buf) { bool read = false; - if(!BEncodeMaybeReadDictInt("a", proto, read, k, buf)) + if (!BEncodeMaybeReadDictInt("a", proto, read, k, buf)) return false; - if(k == "d") + if (k == "d") { llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) return false; PutBuffer(strbuf); return true; } - if(!BEncodeMaybeReadDictEntry("i", introReply, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("i", introReply, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("n", seqno, read, k, buf)) + if (!BEncodeMaybeReadDictInt("n", seqno, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("s", sender, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("s", sender, read, k, buf)) return false; - if(!BEncodeMaybeReadDictEntry("t", tag, read, k, buf)) + if (!BEncodeMaybeReadDictEntry("t", tag, read, k, buf)) return false; - if(!BEncodeMaybeReadDictInt("v", version, read, k, buf)) + if (!BEncodeMaybeReadDictInt("v", version, read, k, buf)) return false; return read; } @@ -68,26 +68,26 @@ namespace llarp bool ProtocolMessage::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictInt("a", proto, buf)) + if (!BEncodeWriteDictInt("a", proto, buf)) return false; - if(!bencode_write_bytestring(buf, "d", 1)) + if (!bencode_write_bytestring(buf, "d", 1)) return false; - if(!bencode_write_bytestring(buf, payload.data(), payload.size())) + if (!bencode_write_bytestring(buf, payload.data(), payload.size())) return false; - if(!BEncodeWriteDictEntry("i", introReply, buf)) + if (!BEncodeWriteDictEntry("i", introReply, buf)) return false; - if(!BEncodeWriteDictInt("n", seqno, buf)) + if (!BEncodeWriteDictInt("n", seqno, buf)) return false; - if(!BEncodeWriteDictEntry("s", sender, buf)) + if (!BEncodeWriteDictEntry("s", sender, buf)) return false; - if(!tag.IsZero()) + if (!tag.IsZero()) { - if(!BEncodeWriteDictEntry("t", tag, buf)) + if (!BEncodeWriteDictEntry("t", tag, buf)) return false; } - if(!BEncodeWriteDictInt("v", version, buf)) + if (!BEncodeWriteDictInt("v", version, buf)) return false; return bencode_end(buf); } @@ -97,41 +97,41 @@ namespace llarp bool ProtocolFrame::BEncode(llarp_buffer_t* buf) const { - if(!bencode_start_dict(buf)) + if (!bencode_start_dict(buf)) return false; - if(!BEncodeWriteDictMsgType(buf, "A", "H")) + if (!BEncodeWriteDictMsgType(buf, "A", "H")) return false; - if(!C.IsZero()) + if (!C.IsZero()) { - if(!BEncodeWriteDictEntry("C", C, buf)) + if (!BEncodeWriteDictEntry("C", C, buf)) return false; } - if(D.size() > 0) + if (D.size() > 0) { - if(!BEncodeWriteDictEntry("D", D, buf)) + if (!BEncodeWriteDictEntry("D", D, buf)) return false; } - if(!BEncodeWriteDictEntry("F", F, buf)) + if (!BEncodeWriteDictEntry("F", F, buf)) return false; - if(!N.IsZero()) + if (!N.IsZero()) { - if(!BEncodeWriteDictEntry("N", N, buf)) + if (!BEncodeWriteDictEntry("N", N, buf)) return false; } - if(R) + if (R) { - if(!BEncodeWriteDictInt("R", R, buf)) + if (!BEncodeWriteDictInt("R", R, buf)) return false; } - if(!T.IsZero()) + if (!T.IsZero()) { - if(!BEncodeWriteDictEntry("T", T, buf)) + if (!BEncodeWriteDictEntry("T", T, buf)) return false; } - if(!BEncodeWriteDictInt("V", version, buf)) + if (!BEncodeWriteDictInt("V", version, buf)) return false; - if(!BEncodeWriteDictEntry("Z", Z, buf)) + if (!BEncodeWriteDictEntry("Z", Z, buf)) return false; return bencode_end(buf); } @@ -140,43 +140,41 @@ namespace llarp ProtocolFrame::DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) { bool read = false; - if(key == "A") + if (key == "A") { llarp_buffer_t strbuf; - if(!bencode_read_string(val, &strbuf)) + if (!bencode_read_string(val, &strbuf)) return false; - if(strbuf.sz != 1) + if (strbuf.sz != 1) return false; return *strbuf.cur == 'H'; } - if(!BEncodeMaybeReadDictEntry("D", D, read, key, val)) + if (!BEncodeMaybeReadDictEntry("D", D, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("F", F, read, key, val)) + if (!BEncodeMaybeReadDictEntry("F", F, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("C", C, read, key, val)) + if (!BEncodeMaybeReadDictEntry("C", C, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("N", N, read, key, val)) + if (!BEncodeMaybeReadDictEntry("N", N, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("S", S, read, key, val)) + if (!BEncodeMaybeReadDictInt("S", S, read, key, val)) return false; - if(!BEncodeMaybeReadDictInt("R", R, read, key, val)) + if (!BEncodeMaybeReadDictInt("R", R, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("T", T, read, key, val)) + if (!BEncodeMaybeReadDictEntry("T", T, read, key, val)) return false; - if(!BEncodeMaybeVerifyVersion("V", version, LLARP_PROTO_VERSION, read, - key, val)) + if (!BEncodeMaybeVerifyVersion("V", version, LLARP_PROTO_VERSION, read, key, val)) return false; - if(!BEncodeMaybeReadDictEntry("Z", Z, read, key, val)) + if (!BEncodeMaybeReadDictEntry("Z", Z, read, key, val)) return false; return read; } bool - ProtocolFrame::DecryptPayloadInto(const SharedSecret& sharedkey, - ProtocolMessage& msg) const + ProtocolFrame::DecryptPayloadInto(const SharedSecret& sharedkey, ProtocolMessage& msg) const { Encrypted_t tmp = D; - auto buf = tmp.Buffer(); + auto buf = tmp.Buffer(); CryptoManager::instance()->xchacha20(*buf, sharedkey, N); return bencode_decode_dict(msg, buf); } @@ -185,36 +183,35 @@ namespace llarp ProtocolFrame::Sign(const Identity& localIdent) { Z.Zero(); - std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); // encode - if(!BEncode(&buf)) + if (!BEncode(&buf)) { LogError("message too big to encode"); return false; } // rewind - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; // sign return localIdent.Sign(Z, buf); } bool - ProtocolFrame::EncryptAndSign(const ProtocolMessage& msg, - const SharedSecret& sessionKey, - const Identity& localIdent) + ProtocolFrame::EncryptAndSign( + const ProtocolMessage& msg, const SharedSecret& sessionKey, const Identity& localIdent) { - std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); // encode message - if(!msg.BEncode(&buf)) + if (!msg.BEncode(&buf)) { LogError("message too big to encode"); return false; } // rewind - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; // encrypt CryptoManager::instance()->xchacha20(buf, sessionKey, N); @@ -224,17 +221,17 @@ namespace llarp Z.Zero(); llarp_buffer_t buf2(tmp); // encode frame - if(!BEncode(&buf2)) + if (!BEncode(&buf2)) { LogError("frame too big to encode"); DumpBuffer(buf2); return false; } // rewind - buf2.sz = buf2.cur - buf2.base; + buf2.sz = buf2.cur - buf2.base; buf2.cur = buf2.base; // sign - if(!localIdent.Sign(Z, buf2)) + if (!localIdent.Sign(Z, buf2)) { LogError("failed to sign? wtf?!"); return false; @@ -245,16 +242,20 @@ namespace llarp struct AsyncFrameDecrypt { path::Path_ptr path; - std::shared_ptr< Logic > logic; - std::shared_ptr< ProtocolMessage > msg; + std::shared_ptr logic; + std::shared_ptr msg; const Identity& m_LocalIdentity; IDataHandler* handler; const ProtocolFrame frame; const Introduction fromIntro; - AsyncFrameDecrypt(std::shared_ptr< Logic > l, const Identity& localIdent, - IDataHandler* h, std::shared_ptr< ProtocolMessage > m, - const ProtocolFrame& f, const Introduction& recvIntro) + AsyncFrameDecrypt( + std::shared_ptr l, + const Identity& localIdent, + IDataHandler* h, + std::shared_ptr m, + const ProtocolFrame& f, + const Introduction& recvIntro) : logic(std::move(l)) , msg(std::move(m)) , m_LocalIdentity(localIdent) @@ -267,14 +268,13 @@ namespace llarp static void Work(void* user) { - auto* self = static_cast< AsyncFrameDecrypt* >(user); + auto* self = static_cast(user); auto crypto = CryptoManager::instance(); SharedSecret K; SharedSecret sharedKey; // copy ProtocolFrame frame(self->frame); - if(!crypto->pqe_decrypt(self->frame.C, K, - pq_keypair_to_secret(self->m_LocalIdentity.pq))) + if (!crypto->pqe_decrypt(self->frame.C, K, pq_keypair_to_secret(self->m_LocalIdentity.pq))) { LogError("pqke failed C=", self->frame.C); self->msg.reset(); @@ -284,7 +284,7 @@ namespace llarp // decrypt auto buf = frame.D.Buffer(); crypto->xchacha20(*buf, K, self->frame.N); - if(!bencode_decode_dict(*self->msg, buf)) + if (!bencode_decode_dict(*self->msg, buf)) { LogError("failed to decode inner protocol message"); DumpBuffer(*buf); @@ -293,18 +293,21 @@ namespace llarp return; } // verify signature of outer message after we parsed the inner message - if(!self->frame.Verify(self->msg->sender)) + if (!self->frame.Verify(self->msg->sender)) { - LogError("intro frame has invalid signature Z=", self->frame.Z, - " from ", self->msg->sender.Addr()); - Dump< MAX_PROTOCOL_MESSAGE_SIZE >(self->frame); - Dump< MAX_PROTOCOL_MESSAGE_SIZE >(*self->msg); + LogError( + "intro frame has invalid signature Z=", + self->frame.Z, + " from ", + self->msg->sender.Addr()); + Dump(self->frame); + Dump(*self->msg); self->msg.reset(); delete self; return; } - if(self->handler->HasConvoTag(self->msg->tag)) + if (self->handler->HasConvoTag(self->msg->tag)) { LogError("dropping duplicate convo tag T=", self->msg->tag); // TODO: send convotag reset @@ -315,19 +318,18 @@ namespace llarp // PKE (A, B, N) SharedSecret sharedSecret; - path_dh_func dh_server = - util::memFn(&Crypto::dh_server, CryptoManager::instance()); + path_dh_func dh_server = util::memFn(&Crypto::dh_server, CryptoManager::instance()); - if(!self->m_LocalIdentity.KeyExchange(dh_server, sharedSecret, - self->msg->sender, self->frame.N)) + if (!self->m_LocalIdentity.KeyExchange( + dh_server, sharedSecret, self->msg->sender, self->frame.N)) { LogError("x25519 key exchange failed"); - Dump< MAX_PROTOCOL_MESSAGE_SIZE >(self->frame); + Dump(self->frame); self->msg.reset(); delete self; return; } - std::array< byte_t, 64 > tmp; + std::array tmp; // K std::copy(K.begin(), K.end(), tmp.begin()); // S = HS( K + PKE( A, B, N)) @@ -339,12 +341,11 @@ namespace llarp self->handler->PutSenderFor(self->msg->tag, self->msg->sender, true); self->handler->PutCachedSessionKeyFor(self->msg->tag, sharedKey); - self->msg->handler = self->handler; - std::shared_ptr< ProtocolMessage > msg = std::move(self->msg); - path::Path_ptr path = std::move(self->path); - const PathID_t from = self->frame.F; - LogicCall(self->logic, - [=]() { ProtocolMessage::ProcessAsync(path, from, msg); }); + self->msg->handler = self->handler; + std::shared_ptr msg = std::move(self->msg); + path::Path_ptr path = std::move(self->path); + const PathID_t from = self->frame.F; + LogicCall(self->logic, [=]() { ProtocolMessage::ProcessAsync(path, from, msg); }); delete self; } }; @@ -352,14 +353,14 @@ namespace llarp ProtocolFrame& ProtocolFrame::operator=(const ProtocolFrame& other) { - C = other.C; - D = other.D; - F = other.F; - N = other.N; - Z = other.Z; - T = other.T; - R = other.R; - S = other.S; + C = other.C; + D = other.D; + F = other.F; + N = other.N; + Z = other.Z; + T = other.T; + R = other.R; + S = other.S; version = other.version; return *this; } @@ -373,66 +374,66 @@ namespace llarp bool ProtocolFrame::AsyncDecryptAndVerify( - std::shared_ptr< Logic > logic, path::Path_ptr recvPath, - const std::shared_ptr< llarp::thread::ThreadPool >& worker, - const Identity& localIdent, IDataHandler* handler) const + std::shared_ptr logic, + path::Path_ptr recvPath, + const std::shared_ptr& worker, + const Identity& localIdent, + IDataHandler* handler) const { - auto msg = std::make_shared< ProtocolMessage >(); + auto msg = std::make_shared(); msg->handler = handler; - if(T.IsZero()) + if (T.IsZero()) { LogInfo("Got protocol frame with new convo"); // we need to dh - auto dh = new AsyncFrameDecrypt(logic, localIdent, handler, msg, *this, - recvPath->intro); + auto dh = new AsyncFrameDecrypt(logic, localIdent, handler, msg, *this, recvPath->intro); dh->path = recvPath; return worker->addJob(std::bind(&AsyncFrameDecrypt::Work, dh)); } auto v = new AsyncDecrypt(); - if(!handler->GetCachedSessionKeyFor(T, v->shared)) + if (!handler->GetCachedSessionKeyFor(T, v->shared)) { LogError("No cached session for T=", T); delete v; return false; } - if(!handler->GetSenderFor(T, v->si)) + if (!handler->GetSenderFor(T, v->si)) { LogError("No sender for T=", T); delete v; return false; } v->frame = *this; - return worker->addJob( - [v, msg = std::move(msg), recvPath = std::move(recvPath)]() { - if(not v->frame.Verify(v->si)) - { - LogError("Signature failure from ", v->si.Addr()); - delete v; - return; - } - if(not v->frame.DecryptPayloadInto(v->shared, *msg)) - { - LogError("failed to decrypt message"); - delete v; - return; - } - RecvDataEvent ev; - ev.fromPath = std::move(recvPath); - ev.pathid = v->frame.F; - ev.msg = std::move(msg); - msg->handler->QueueRecvData(std::move(ev)); - delete v; - }); + return worker->addJob([v, msg = std::move(msg), recvPath = std::move(recvPath)]() { + if (not v->frame.Verify(v->si)) + { + LogError("Signature failure from ", v->si.Addr()); + delete v; + return; + } + if (not v->frame.DecryptPayloadInto(v->shared, *msg)) + { + LogError("failed to decrypt message"); + delete v; + return; + } + RecvDataEvent ev; + ev.fromPath = std::move(recvPath); + ev.pathid = v->frame.F; + ev.msg = std::move(msg); + msg->handler->QueueRecvData(std::move(ev)); + delete v; + }); } bool ProtocolFrame::operator==(const ProtocolFrame& other) const { - return C == other.C && D == other.D && N == other.N && Z == other.Z - && T == other.T && S == other.S && version == other.version; + return C == other.C && D == other.D && N == other.N && Z == other.Z && T == other.T + && S == other.S && version == other.version; } bool @@ -443,24 +444,23 @@ namespace llarp // zero out signature for verify copy.Z.Zero(); // serialize - std::array< byte_t, MAX_PROTOCOL_MESSAGE_SIZE > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!copy.BEncode(&buf)) + if (!copy.BEncode(&buf)) { LogError("bencode fail"); return false; } // rewind buffer - buf.sz = buf.cur - buf.base; + buf.sz = buf.cur - buf.base; buf.cur = buf.base; // verify return svc.Verify(buf, Z); } bool - ProtocolFrame::HandleMessage(routing::IMessageHandler* h, - AbstractRouter* /*r*/) const + ProtocolFrame::HandleMessage(routing::IMessageHandler* h, AbstractRouter* /*r*/) const { return h->HandleHiddenServiceFrame(*this); } diff --git a/llarp/service/protocol.hpp b/llarp/service/protocol.hpp index 39a4b5ebc..47e145187 100644 --- a/llarp/service/protocol.hpp +++ b/llarp/service/protocol.hpp @@ -33,7 +33,7 @@ namespace llarp using ProtocolType = uint64_t; - constexpr ProtocolType eProtocolControl = 0UL; + constexpr ProtocolType eProtocolControl = 0UL; constexpr ProtocolType eProtocolTrafficV4 = 1UL; constexpr ProtocolType eProtocolTrafficV6 = 2UL; @@ -43,14 +43,14 @@ namespace llarp ProtocolMessage(const ConvoTag& tag); ProtocolMessage(); ~ProtocolMessage(); - ProtocolType proto = eProtocolTrafficV4; + ProtocolType proto = eProtocolTrafficV4; llarp_time_t queued = 0s; - std::vector< byte_t > payload; + std::vector payload; Introduction introReply; ServiceInfo sender; IDataHandler* handler = nullptr; ConvoTag tag; - uint64_t seqno = 0; + uint64_t seqno = 0; uint64_t version = LLARP_PROTO_VERSION; bool @@ -63,8 +63,7 @@ namespace llarp PutBuffer(const llarp_buffer_t& payload); static void - ProcessAsync(path::Path_ptr p, PathID_t from, - std::shared_ptr< ProtocolMessage > self); + ProcessAsync(path::Path_ptr p, PathID_t from, std::shared_ptr self); bool operator<(const ProtocolMessage& other) const @@ -76,7 +75,7 @@ namespace llarp /// outer message struct ProtocolFrame final : public routing::IMessage { - using Encrypted_t = Encrypted< 2048 >; + using Encrypted_t = Encrypted<2048>; PQCipherBlock C; Encrypted_t D; uint64_t R; @@ -95,7 +94,7 @@ namespace llarp , F(other.F) , T(other.T) { - S = other.S; + S = other.S; version = other.version; } @@ -119,21 +118,22 @@ namespace llarp operator=(const ProtocolFrame& other); bool - EncryptAndSign(const ProtocolMessage& msg, const SharedSecret& sharedkey, - const Identity& localIdent); + EncryptAndSign( + const ProtocolMessage& msg, const SharedSecret& sharedkey, const Identity& localIdent); bool Sign(const Identity& localIdent); bool AsyncDecryptAndVerify( - std::shared_ptr< Logic > logic, path::Path_ptr fromPath, - const std::shared_ptr< llarp::thread::ThreadPool >& worker, - const Identity& localIdent, IDataHandler* handler) const; + std::shared_ptr logic, + path::Path_ptr fromPath, + const std::shared_ptr& worker, + const Identity& localIdent, + IDataHandler* handler) const; bool - DecryptPayloadInto(const SharedSecret& sharedkey, - ProtocolMessage& into) const; + DecryptPayloadInto(const SharedSecret& sharedkey, ProtocolMessage& into) const; bool DecodeKey(const llarp_buffer_t& key, llarp_buffer_t* val) override; @@ -156,7 +156,7 @@ namespace llarp T.Zero(); N.Zero(); Z.Zero(); - R = 0; + R = 0; version = LLARP_PROTO_VERSION; } @@ -164,8 +164,7 @@ namespace llarp Verify(const ServiceInfo& from) const; bool - HandleMessage(routing::IMessageHandler* h, - AbstractRouter* r) const override; + HandleMessage(routing::IMessageHandler* h, AbstractRouter* r) const override; }; } // namespace service } // namespace llarp diff --git a/llarp/service/router_lookup_job.hpp b/llarp/service/router_lookup_job.hpp index 167b2dd60..0725ac628 100644 --- a/llarp/service/router_lookup_job.hpp +++ b/llarp/service/router_lookup_job.hpp @@ -20,15 +20,15 @@ namespace llarp bool IsExpired(llarp_time_t now) const { - if(now < started) + if (now < started) return false; return now - started > 30s; } void - InformResult(std::vector< RouterContact > result) + InformResult(std::vector result) { - if(handler) + if (handler) handler(result); } }; diff --git a/llarp/service/sendcontext.cpp b/llarp/service/sendcontext.cpp index 4b230d884..dcf06b478 100644 --- a/llarp/service/sendcontext.cpp +++ b/llarp/service/sendcontext.cpp @@ -13,8 +13,8 @@ namespace llarp { static constexpr size_t SendContextQueueSize = 512; - SendContext::SendContext(ServiceInfo ident, const Introduction& intro, - path::PathSet* send, Endpoint* ep) + SendContext::SendContext( + ServiceInfo ident, const Introduction& intro, path::PathSet* send, Endpoint* ep) : remoteIdent(std::move(ident)) , remoteIntro(intro) , m_PathSet(send) @@ -26,17 +26,14 @@ namespace llarp } bool - SendContext::Send(std::shared_ptr< ProtocolFrame > msg, path::Path_ptr path) + SendContext::Send(std::shared_ptr msg, path::Path_ptr path) { - if(m_SendQueue.empty() or m_SendQueue.full()) + if (m_SendQueue.empty() or m_SendQueue.full()) { - LogicCall(m_Endpoint->RouterLogic(), - [self = this]() { self->FlushUpstream(); }); + LogicCall(m_Endpoint->RouterLogic(), [self = this]() { self->FlushUpstream(); }); } - m_SendQueue.pushBack( - std::make_pair(std::make_shared< const routing::PathTransferMessage >( - *msg, remoteIntro.pathID), - path)); + m_SendQueue.pushBack(std::make_pair( + std::make_shared(*msg, remoteIntro.pathID), path)); return true; } @@ -44,24 +41,24 @@ namespace llarp SendContext::FlushUpstream() { auto r = m_Endpoint->Router(); - std::unordered_set< path::Path_ptr, path::Path::Ptr_Hash > flushpaths; + std::unordered_set flushpaths; { do { auto maybe = m_SendQueue.tryPopFront(); - if(not maybe.has_value()) + if (not maybe.has_value()) break; auto& item = maybe.value(); - if(item.second->SendRoutingMessage(*item.first, r)) + if (item.second->SendRoutingMessage(*item.first, r)) { lastGoodSend = r->Now(); flushpaths.emplace(item.second); m_Endpoint->MarkConvoTagActive(item.first->T.T); } - } while(not m_SendQueue.empty()); + } while (not m_SendQueue.empty()); } // flush the select path's upstream - for(const auto& path : flushpaths) + for (const auto& path : flushpaths) { path->FlushUpstream(r); } @@ -72,39 +69,37 @@ namespace llarp SendContext::EncryptAndSendTo(const llarp_buffer_t& payload, ProtocolType t) { SharedSecret shared; - auto f = std::make_shared< ProtocolFrame >(); + auto f = std::make_shared(); f->N.Randomize(); f->T = currentConvoTag; f->S = ++sequenceNo; auto path = m_PathSet->GetNewestPathByRouter(remoteIntro.router); - if(!path) + if (!path) { - LogError(m_Endpoint->Name(), - " cannot encrypt and send: no path for intro ", remoteIntro); + LogError(m_Endpoint->Name(), " cannot encrypt and send: no path for intro ", remoteIntro); return; } - if(!m_DataHandler->GetCachedSessionKeyFor(f->T, shared)) + if (!m_DataHandler->GetCachedSessionKeyFor(f->T, shared)) { - LogError(m_Endpoint->Name(), - " has no cached session key on session T=", f->T); + LogError(m_Endpoint->Name(), " has no cached session key on session T=", f->T); return; } - auto m = std::make_shared< ProtocolMessage >(); + auto m = std::make_shared(); m_DataHandler->PutIntroFor(f->T, remoteIntro); m_DataHandler->PutReplyIntroFor(f->T, path->intro); - m->proto = t; - m->seqno = m_Endpoint->GetSeqNoForConvo(f->T); + m->proto = t; + m->seqno = m_Endpoint->GetSeqNoForConvo(f->T); m->introReply = path->intro; - f->F = m->introReply.pathID; - m->sender = m_Endpoint->GetIdentity().pub; - m->tag = f->T; + f->F = m->introReply.pathID; + m->sender = m_Endpoint->GetIdentity().pub; + m->tag = f->T; m->PutBuffer(payload); auto self = this; m_Endpoint->CryptoWorker()->addJob([f, m, shared, path, self]() { - if(not f->EncryptAndSign(*m, shared, self->m_Endpoint->GetIdentity())) + if (not f->EncryptAndSign(*m, shared, self->m_Endpoint->GetIdentity())) { LogError(self->m_Endpoint->Name(), " failed to sign message"); return; @@ -114,10 +109,9 @@ namespace llarp } void - SendContext::AsyncEncryptAndSendTo(const llarp_buffer_t& data, - ProtocolType protocol) + SendContext::AsyncEncryptAndSendTo(const llarp_buffer_t& data, ProtocolType protocol) { - if(lastGoodSend != 0s) + if (lastGoodSend != 0s) { EncryptAndSendTo(data, protocol); } diff --git a/llarp/service/sendcontext.hpp b/llarp/service/sendcontext.hpp index 463234d18..351cad4e0 100644 --- a/llarp/service/sendcontext.hpp +++ b/llarp/service/sendcontext.hpp @@ -21,8 +21,7 @@ namespace llarp struct SendContext { - SendContext(ServiceInfo ident, const Introduction& intro, - path::PathSet* send, Endpoint* ep); + SendContext(ServiceInfo ident, const Introduction& intro, path::PathSet* send, Endpoint* ep); void AsyncEncryptAndSendTo(const llarp_buffer_t& payload, ProtocolType t); @@ -30,7 +29,7 @@ namespace llarp /// queue send a fully encrypted hidden service frame /// via a path bool - Send(std::shared_ptr< ProtocolFrame > f, path::Path_ptr path); + Send(std::shared_ptr f, path::Path_ptr path); /// flush upstream traffic when in router thread void @@ -43,15 +42,15 @@ namespace llarp path::PathSet* const m_PathSet; IDataHandler* const m_DataHandler; Endpoint* const m_Endpoint; - uint64_t sequenceNo = 0; + uint64_t sequenceNo = 0; llarp_time_t lastGoodSend = 0s; const llarp_time_t createdAt; - llarp_time_t sendTimeout = 40s; + llarp_time_t sendTimeout = 40s; llarp_time_t connectTimeout = 60s; - bool markedBad = false; - using Msg_ptr = std::shared_ptr< const routing::PathTransferMessage >; - using SendEvent_t = std::pair< Msg_ptr, path::Path_ptr >; - thread::Queue< SendEvent_t > m_SendQueue; + bool markedBad = false; + using Msg_ptr = std::shared_ptr; + using SendEvent_t = std::pair; + thread::Queue m_SendQueue; virtual bool ShiftIntroduction(bool rebuild = true) diff --git a/llarp/service/session.cpp b/llarp/service/session.cpp index 6a8ffb4d8..2f84d6e1a 100644 --- a/llarp/service/session.cpp +++ b/llarp/service/session.cpp @@ -18,8 +18,7 @@ namespace llarp bool Session::IsExpired(llarp_time_t now, llarp_time_t lifetime) const { - return now > lastUsed - && (now - lastUsed > lifetime || intro.IsExpired(now)); + return now > lastUsed && (now - lastUsed > lifetime || intro.IsExpired(now)); } } // namespace service diff --git a/llarp/service/session.hpp b/llarp/service/session.hpp index 4f08617e6..f92535c11 100644 --- a/llarp/service/session.hpp +++ b/llarp/service/session.hpp @@ -25,14 +25,13 @@ namespace llarp /// the intro remoet last sent on Introduction lastInboundIntro; llarp_time_t lastUsed = 0s; - uint64_t seqno = 0; - bool inbound = false; + uint64_t seqno = 0; + bool inbound = false; util::StatusObject ExtractStatus() const; bool - IsExpired(llarp_time_t now, - llarp_time_t lifetime = SessionLifetime) const; + IsExpired(llarp_time_t now, llarp_time_t lifetime = SessionLifetime) const; }; } // namespace service diff --git a/llarp/service/tag.hpp b/llarp/service/tag.hpp index a1b035206..a2b677e1d 100644 --- a/llarp/service/tag.hpp +++ b/llarp/service/tag.hpp @@ -15,13 +15,13 @@ namespace llarp { namespace service { - struct Tag : public AlignedBuffer< 16 > + struct Tag : public AlignedBuffer<16> { - Tag() : AlignedBuffer< SIZE >() + Tag() : AlignedBuffer() { } - Tag(const byte_t* d) : AlignedBuffer< SIZE >(d) + Tag(const byte_t* d) : AlignedBuffer(d) { } @@ -31,18 +31,14 @@ namespace llarp // unsigned long but zero-extends this on LLP64 systems // 2Jan19: reeee someone undid the patch std::copy( - str.begin(), - str.begin() + std::min(std::string::size_type(16), str.size()), - begin()); + str.begin(), str.begin() + std::min(std::string::size_type(16), str.size()), begin()); } Tag& operator=(const std::string& str) { std::copy( - str.begin(), - str.begin() + std::min(std::string::size_type(16), str.size()), - begin()); + str.begin(), str.begin() + std::min(std::string::size_type(16), str.size()), begin()); return *this; } @@ -61,7 +57,7 @@ namespace llarp return data()[0] == 0; } - using Hash = AlignedBuffer< SIZE >::Hash; + using Hash = AlignedBuffer::Hash; }; } // namespace service } // namespace llarp diff --git a/llarp/service/tag_lookup_job.cpp b/llarp/service/tag_lookup_job.cpp index 2cf411b7f..32ddbb8fe 100644 --- a/llarp/service/tag_lookup_job.cpp +++ b/llarp/service/tag_lookup_job.cpp @@ -9,7 +9,7 @@ namespace llarp namespace service { bool - CachedTagResult::HandleResponse(const std::set< EncryptedIntroSet >&) + CachedTagResult::HandleResponse(const std::set&) { return true; } @@ -18,11 +18,11 @@ namespace llarp CachedTagResult::Expire(llarp_time_t now) { auto itr = result.begin(); - while(itr != result.end()) + while (itr != result.end()) { - if(itr->IsExpired(now)) + if (itr->IsExpired(now)) { - itr = result.erase(itr); + itr = result.erase(itr); lastModified = now; } else @@ -32,18 +32,17 @@ namespace llarp } } - std::shared_ptr< routing::IMessage > + std::shared_ptr CachedTagResult::BuildRequestMessage(uint64_t txid) { - auto msg = std::make_shared< routing::DHTMessage >(); - msg->M.emplace_back(std::make_unique< dht::FindIntroMessage >(tag, txid)); + auto msg = std::make_shared(); + msg->M.emplace_back(std::make_unique(tag, txid)); lastRequest = m_parent->Now(); return msg; } TagLookupJob::TagLookupJob(Endpoint* parent, CachedTagResult* result) - : IServiceLookup(parent, parent->GenTXID(), "taglookup") - , m_result(result) + : IServiceLookup(parent, parent->GenTXID(), "taglookup"), m_result(result) { } } // namespace service diff --git a/llarp/service/tag_lookup_job.hpp b/llarp/service/tag_lookup_job.hpp index a67ce8c8f..3d0db9fa7 100644 --- a/llarp/service/tag_lookup_job.hpp +++ b/llarp/service/tag_lookup_job.hpp @@ -18,9 +18,9 @@ namespace llarp struct CachedTagResult { static constexpr auto TTL = 10s; - llarp_time_t lastRequest = 0s; + llarp_time_t lastRequest = 0s; llarp_time_t lastModified = 0s; - std::set< EncryptedIntroSet > result; + std::set result; Tag tag; Endpoint* m_parent; @@ -36,16 +36,16 @@ namespace llarp bool ShouldRefresh(llarp_time_t now) const { - if(now <= lastRequest) + if (now <= lastRequest) return false; return (now - lastRequest) > TTL; } - std::shared_ptr< routing::IMessage > + std::shared_ptr BuildRequestMessage(uint64_t txid); bool - HandleResponse(const std::set< EncryptedIntroSet >& results); + HandleResponse(const std::set& results); }; struct TagLookupJob : public IServiceLookup @@ -54,14 +54,14 @@ namespace llarp ~TagLookupJob() override = default; - std::shared_ptr< routing::IMessage > + std::shared_ptr BuildRequestMessage() override { return m_result->BuildRequestMessage(txid); } bool - HandleResponse(const std::set< EncryptedIntroSet >& results) override + HandleResponse(const std::set& results) override { return m_result->HandleResponse(results); } diff --git a/llarp/service/vanity.hpp b/llarp/service/vanity.hpp index 15944a46a..131a77037 100644 --- a/llarp/service/vanity.hpp +++ b/llarp/service/vanity.hpp @@ -10,7 +10,7 @@ namespace llarp { /// hidden service address - using VanityNonce = AlignedBuffer< 16 >; + using VanityNonce = AlignedBuffer<16>; } // namespace service } // namespace llarp #endif diff --git a/llarp/simulation/sim_context.cpp b/llarp/simulation/sim_context.cpp index 0b6f64175..924192617 100644 --- a/llarp/simulation/sim_context.cpp +++ b/llarp/simulation/sim_context.cpp @@ -10,27 +10,23 @@ namespace llarp } void - Simulation::NodeUp(llarp::Context *) + Simulation::NodeUp(llarp::Context*) { } Node_ptr - Simulation::AddNode(const std::string &name) + Simulation::AddNode(const std::string& name) { auto itr = m_Nodes.find(name); - if(itr == m_Nodes.end()) + if (itr == m_Nodes.end()) { - itr = - m_Nodes - .emplace(name, - std::make_shared< llarp::Context >(shared_from_this())) - .first; + itr = m_Nodes.emplace(name, std::make_shared(shared_from_this())).first; } return itr->second; } void - Simulation::DelNode(const std::string &name) + Simulation::DelNode(const std::string& name) { m_Nodes.erase(name); } diff --git a/llarp/simulation/sim_context.hpp b/llarp/simulation/sim_context.hpp index da8e0252b..6d9a3338b 100644 --- a/llarp/simulation/sim_context.hpp +++ b/llarp/simulation/sim_context.hpp @@ -6,18 +6,18 @@ namespace llarp { // forward declair struct Context; - using Node_ptr = std::shared_ptr< llarp::Context >; + using Node_ptr = std::shared_ptr; namespace simulate { - struct Simulation : public std::enable_shared_from_this< Simulation > + struct Simulation : public std::enable_shared_from_this { Simulation(); llarp::CryptoManager m_CryptoManager; llarp_ev_loop_ptr m_NetLoop; - std::unordered_map< std::string, Node_ptr > m_Nodes; + std::unordered_map m_Nodes; void NodeUp(llarp::Context* node); @@ -29,6 +29,6 @@ namespace llarp DelNode(const std::string& name); }; - using Sim_ptr = std::shared_ptr< Simulation >; + using Sim_ptr = std::shared_ptr; } // namespace simulate } // namespace llarp diff --git a/llarp/tooling/dht_event.hpp b/llarp/tooling/dht_event.hpp index d2e6858ff..45b8bb53b 100644 --- a/llarp/tooling/dht_event.hpp +++ b/llarp/tooling/dht_event.hpp @@ -28,9 +28,8 @@ namespace tooling std::string ToString() const { - return RouterEvent::ToString() + " ---- introset pubkey: " - + introsetPubkey.ShortHex() + ", relay: " + relay.ShortString() - + ", relayIndex: " + std::to_string(relayIndex); + return RouterEvent::ToString() + " ---- introset pubkey: " + introsetPubkey.ShortHex() + + ", relay: " + relay.ShortString() + ", relayIndex: " + std::to_string(relayIndex); } }; @@ -58,8 +57,8 @@ namespace tooling std::string ToString() const override { - return RouterEvent::ToString() + "from " + from.ShortHex() + " location=" - + location.ShortHex() + " order=" + std::to_string(relayOrder) + return RouterEvent::ToString() + "from " + from.ShortHex() + + " location=" + location.ShortHex() + " order=" + std::to_string(relayOrder) + " txid=" + std::to_string(txid); } }; @@ -87,8 +86,8 @@ namespace tooling ToString() const override { return RouterEvent::ToString() + "from " + From.ShortHex() - + " location=" + Introset.derivedSigningKey.ShortHex() + " order=" - + std::to_string(RelayOrder) + " txid=" + std::to_string(TxID); + + " location=" + Introset.derivedSigningKey.ShortHex() + + " order=" + std::to_string(RelayOrder) + " txid=" + std::to_string(TxID); } }; @@ -101,9 +100,7 @@ namespace tooling uint64_t txid; uint64_t version; - FindRouterEvent( - const llarp::RouterID& ourRouter, - const llarp::dht::FindRouterMessage& msg) + FindRouterEvent(const llarp::RouterID& ourRouter, const llarp::dht::FindRouterMessage& msg) : RouterEvent("DHT: FindRouterEvent", ourRouter, true) , from(msg.From) , targetKey(msg.targetKey) @@ -117,13 +114,10 @@ namespace tooling std::string ToString() const override { - return RouterEvent::ToString() - +" from "+ from.ShortHex() - +", targetKey: "+ targetKey.ToString() - +", iterative: "+ std::to_string(iterative) - +", exploritory "+ std::to_string(exploritory) - +", txid "+ std::to_string(txid) - +", version "+ std::to_string(version); + return RouterEvent::ToString() + " from " + from.ShortHex() + + ", targetKey: " + targetKey.ToString() + ", iterative: " + std::to_string(iterative) + + ", exploritory " + std::to_string(exploritory) + ", txid " + std::to_string(txid) + + ", version " + std::to_string(version); } }; diff --git a/llarp/tooling/path_event.hpp b/llarp/tooling/path_event.hpp index 499f27b39..de8711cd2 100644 --- a/llarp/tooling/path_event.hpp +++ b/llarp/tooling/path_event.hpp @@ -8,19 +8,16 @@ namespace tooling { struct PathAttemptEvent : public RouterEvent { - std::vector< llarp::path::PathHopConfig > hops; + std::vector hops; llarp::PathID_t pathid; - PathAttemptEvent( - const llarp::RouterID& routerID, - std::shared_ptr< const llarp::path::Path > path) + PathAttemptEvent(const llarp::RouterID& routerID, std::shared_ptr path) : RouterEvent("PathAttemptEvent", routerID, false) , hops(path->hops) , pathid(path->hops[0].rxID) { } - std::string ToString() const { @@ -28,14 +25,14 @@ namespace tooling result += "---- ["; size_t i = 0; - for(const auto& hop : hops) + for (const auto& hop : hops) { i++; result += llarp::RouterID(hop.rc.pubkey).ShortString(); result += "]"; - if(i != hops.size()) + if (i != hops.size()) { result += " -> ["; } @@ -43,7 +40,6 @@ namespace tooling return result; } - }; struct PathRequestReceivedEvent : public RouterEvent @@ -55,8 +51,7 @@ namespace tooling bool isEndpoint = false; PathRequestReceivedEvent( - const llarp::RouterID& routerID, - std::shared_ptr< const llarp::path::TransitHop > hop) + const llarp::RouterID& routerID, std::shared_ptr hop) : RouterEvent("PathRequestReceivedEvent", routerID, true) , prevHop(hop->info.downstream) , nextHop(hop->info.upstream) @@ -66,7 +61,6 @@ namespace tooling { } - std::string ToString() const { @@ -77,7 +71,7 @@ namespace tooling result += routerID.ShortString(); result += "] -> ["; - if(isEndpoint) + if (isEndpoint) { result += "nowhere]"; } @@ -89,7 +83,6 @@ namespace tooling return result; } - }; struct PathStatusReceivedEvent : public RouterEvent @@ -98,12 +91,8 @@ namespace tooling uint64_t status; PathStatusReceivedEvent( - const llarp::RouterID& routerID, - const llarp::PathID_t rxid_, - uint64_t status_) - : RouterEvent("PathStatusReceivedEvent", routerID, true) - , rxid(rxid_) - , status(status_) + const llarp::RouterID& routerID, const llarp::PathID_t rxid_, uint64_t status_) + : RouterEvent("PathStatusReceivedEvent", routerID, true), rxid(rxid_), status(status_) { } diff --git a/llarp/tooling/rc_event.hpp b/llarp/tooling/rc_event.hpp index 47b53083b..b735ed4d7 100644 --- a/llarp/tooling/rc_event.hpp +++ b/llarp/tooling/rc_event.hpp @@ -8,8 +8,7 @@ namespace tooling { struct RCGossipReceivedEvent : public RouterEvent { - RCGossipReceivedEvent(const llarp::RouterID& routerID, - const llarp::RouterContact& rc_) + RCGossipReceivedEvent(const llarp::RouterID& routerID, const llarp::RouterContact& rc_) : RouterEvent("RCGossipReceivedEvent", routerID, true), rc(rc_) { } @@ -32,8 +31,7 @@ namespace tooling struct RCGossipSentEvent : public RouterEvent { - RCGossipSentEvent(const llarp::RouterID& routerID, - const llarp::RouterContact& rc_) + RCGossipSentEvent(const llarp::RouterID& routerID, const llarp::RouterContact& rc_) : RouterEvent("RCGossipSentEvent", routerID, true), rc(rc_) { } @@ -41,8 +39,8 @@ namespace tooling std::string ToString() const override { - return RouterEvent::ToString() + " ---- sending RC for RouterID: " - + llarp::RouterID(rc.pubkey).ShortString(); + return RouterEvent::ToString() + + " ---- sending RC for RouterID: " + llarp::RouterID(rc.pubkey).ShortString(); } std::string diff --git a/llarp/tooling/router_event.hpp b/llarp/tooling/router_event.hpp index 0673b989b..dd4971a79 100644 --- a/llarp/tooling/router_event.hpp +++ b/llarp/tooling/router_event.hpp @@ -27,8 +27,7 @@ namespace tooling struct RouterEvent { - RouterEvent(std::string eventType, llarp::RouterID routerID, - bool triggered) + RouterEvent(std::string eventType, llarp::RouterID routerID, bool triggered) : eventType(eventType), routerID(routerID), triggered(triggered) { } @@ -53,6 +52,6 @@ namespace tooling bool triggered = false; }; - using RouterEventPtr = std::unique_ptr< RouterEvent >; + using RouterEventPtr = std::unique_ptr; } // namespace tooling diff --git a/llarp/tooling/router_hive.cpp b/llarp/tooling/router_hive.cpp index 87f7c33b6..85bb57a24 100644 --- a/llarp/tooling/router_hive.cpp +++ b/llarp/tooling/router_hive.cpp @@ -13,11 +13,11 @@ using namespace std::chrono_literals; namespace tooling { void - RouterHive::AddRouter(const std::shared_ptr< llarp::Config >& config, - std::vector< llarp_main* >* routers) + RouterHive::AddRouter( + const std::shared_ptr& config, std::vector* routers) { llarp_main* ctx = llarp_main_init_from_config(config->Copy()); - if(llarp_main_setup(ctx) == 0) + if (llarp_main_setup(ctx) == 0) { llarp::Context::Get(ctx)->InjectHive(this); routers->push_back(ctx); @@ -25,21 +25,21 @@ namespace tooling } void - RouterHive::AddRelay(const std::shared_ptr< llarp::Config >& config) + RouterHive::AddRelay(const std::shared_ptr& config) { AddRouter(config, &relays); } void - RouterHive::AddClient(const std::shared_ptr< llarp::Config >& config) + RouterHive::AddClient(const std::shared_ptr& config) { AddRouter(config, &clients); } void - RouterHive::StartRouters(std::vector< llarp_main* >* routers) + RouterHive::StartRouters(std::vector* routers) { - for(llarp_main* ctx : *routers) + for (llarp_main* ctx : *routers) { routerMainThreads.emplace_back([ctx]() { llarp_main_run(ctx, llarp_main_runtime_opts{false, false, false}); @@ -64,35 +64,35 @@ namespace tooling RouterHive::StopRouters() { llarp::LogInfo("Signalling all routers to stop"); - for(llarp_main* ctx : relays) + for (llarp_main* ctx : relays) { llarp_main_signal(ctx, 2 /* SIGINT */); } - for(llarp_main* ctx : clients) + for (llarp_main* ctx : clients) { llarp_main_signal(ctx, 2 /* SIGINT */); } llarp::LogInfo("Waiting on routers to be stopped"); - for(llarp_main* ctx : relays) + for (llarp_main* ctx : relays) { - while(llarp_main_is_running(ctx)) + while (llarp_main_is_running(ctx)) { std::this_thread::sleep_for(10ms); } } - for(llarp_main* ctx : clients) + for (llarp_main* ctx : clients) { - while(llarp_main_is_running(ctx)) + while (llarp_main_is_running(ctx)) { std::this_thread::sleep_for(10ms); } } llarp::LogInfo("Joining all router threads"); - for(auto& thread : routerMainThreads) + for (auto& thread : routerMainThreads) { - while(not thread.joinable()) + while (not thread.joinable()) { std::this_thread::sleep_for(500ms); } @@ -105,7 +105,7 @@ namespace tooling void RouterHive::NotifyEvent(RouterEventPtr event) { - std::lock_guard< std::mutex > guard{eventQueueMutex}; + std::lock_guard guard{eventQueueMutex}; eventQueue.push_back(std::move(event)); } @@ -113,9 +113,9 @@ namespace tooling RouterEventPtr RouterHive::GetNextEvent() { - std::lock_guard< std::mutex > guard{eventQueueMutex}; + std::lock_guard guard{eventQueueMutex}; - if(not eventQueue.empty()) + if (not eventQueue.empty()) { auto ptr = std::move(eventQueue.front()); eventQueue.pop_front(); @@ -124,13 +124,13 @@ namespace tooling return nullptr; } - std::deque< RouterEventPtr > + std::deque RouterHive::GetAllEvents() { - std::lock_guard< std::mutex > guard{eventQueueMutex}; + std::lock_guard guard{eventQueueMutex}; - std::deque< RouterEventPtr > events; - if(not eventQueue.empty()) + std::deque events; + if (not eventQueue.empty()) { eventQueue.swap(events); } @@ -138,17 +138,16 @@ namespace tooling } void - RouterHive::VisitRouter(llarp_main* router, - std::function< void(Context_ptr) > visit) + RouterHive::VisitRouter(llarp_main* router, std::function visit) { auto ctx = llarp::Context::Get(router); LogicCall(ctx->logic, [visit, ctx]() { visit(ctx); }); } void - RouterHive::VisitRelay(size_t index, std::function< void(Context_ptr) > visit) + RouterHive::VisitRelay(size_t index, std::function visit) { - if(index >= relays.size()) + if (index >= relays.size()) { visit(nullptr); return; @@ -157,10 +156,9 @@ namespace tooling } void - RouterHive::VisitClient(size_t index, - std::function< void(Context_ptr) > visit) + RouterHive::VisitClient(size_t index, std::function visit) { - if(index >= clients.size()) + if (index >= clients.size()) { visit(nullptr); return; @@ -168,35 +166,35 @@ namespace tooling VisitRouter(clients[index], visit); } - std::vector< size_t > + std::vector RouterHive::RelayConnectedRelays() { - std::vector< size_t > results; + std::vector results; results.resize(relays.size()); std::mutex results_lock; - size_t i = 0; + size_t i = 0; size_t done_count = 0; - for(auto relay : relays) + for (auto relay : relays) { auto ctx = llarp::Context::Get(relay); LogicCall(ctx->logic, [&, i, ctx]() { size_t count = ctx->router->NumberOfConnectedRouters(); - std::lock_guard< std::mutex > guard{results_lock}; + std::lock_guard guard{results_lock}; results[i] = count; done_count++; }); i++; } - while(true) + while (true) { size_t read_done_count = 0; { - std::lock_guard< std::mutex > guard{results_lock}; + std::lock_guard guard{results_lock}; read_done_count = done_count; } - if(read_done_count == relays.size()) + if (read_done_count == relays.size()) break; std::this_thread::sleep_for(100ms); @@ -204,35 +202,35 @@ namespace tooling return results; } - std::vector< llarp::RouterContact > + std::vector RouterHive::GetRelayRCs() { - std::vector< llarp::RouterContact > results; + std::vector results; results.resize(relays.size()); std::mutex results_lock; - size_t i = 0; + size_t i = 0; size_t done_count = 0; - for(auto relay : relays) + for (auto relay : relays) { auto ctx = llarp::Context::Get(relay); LogicCall(ctx->logic, [&, i, ctx]() { llarp::RouterContact rc = ctx->router->rc(); - std::lock_guard< std::mutex > guard{results_lock}; + std::lock_guard guard{results_lock}; results[i] = std::move(rc); done_count++; }); i++; } - while(true) + while (true) { size_t read_done_count = 0; { - std::lock_guard< std::mutex > guard{results_lock}; + std::lock_guard guard{results_lock}; read_done_count = done_count; } - if(read_done_count == relays.size()) + if (read_done_count == relays.size()) break; std::this_thread::sleep_for(100ms); diff --git a/llarp/tooling/router_hive.hpp b/llarp/tooling/router_hive.hpp index cba42049c..04ee6f80e 100644 --- a/llarp/tooling/router_hive.hpp +++ b/llarp/tooling/router_hive.hpp @@ -22,36 +22,35 @@ namespace tooling { struct RouterHive { - using Context_ptr = std::shared_ptr< llarp::Context >; + using Context_ptr = std::shared_ptr; private: void - StartRouters(std::vector< llarp_main * > *routers); + StartRouters(std::vector* routers); void - AddRouter(const std::shared_ptr< llarp::Config > &config, - std::vector< llarp_main * > *routers); + AddRouter(const std::shared_ptr& config, std::vector* routers); /// safely visit router void - VisitRouter(llarp_main *router, std::function< void(Context_ptr) > visit); + VisitRouter(llarp_main* router, std::function visit); /// safely visit relay at index N void - VisitRelay(size_t index, std::function< void(Context_ptr) > visit); + VisitRelay(size_t index, std::function visit); /// safely visit client at index N void - VisitClient(size_t index, std::function< void(Context_ptr) > visit); + VisitClient(size_t index, std::function visit); public: RouterHive() = default; void - AddRelay(const std::shared_ptr< llarp::Config > &conf); + AddRelay(const std::shared_ptr& conf); void - AddClient(const std::shared_ptr< llarp::Config > &conf); + AddClient(const std::shared_ptr& conf); void StartRelays(); @@ -68,22 +67,22 @@ namespace tooling RouterEventPtr GetNextEvent(); - std::deque< RouterEventPtr > + std::deque GetAllEvents(); void - ForEachRelay(std::function< void(Context_ptr) > visit) + ForEachRelay(std::function visit) { - for(size_t idx = 0; idx < relays.size(); ++idx) + for (size_t idx = 0; idx < relays.size(); ++idx) { VisitRelay(idx, visit); } } void - ForEachClient(std::function< void(Context_ptr) > visit) + ForEachClient(std::function visit) { - for(size_t idx = 0; idx < clients.size(); ++idx) + for (size_t idx = 0; idx < clients.size(); ++idx) { VisitClient(idx, visit); } @@ -91,25 +90,25 @@ namespace tooling /// safely visit every router context void - ForEachRouter(std::function< void(Context_ptr) > visit) + ForEachRouter(std::function visit) { ForEachRelay(visit); ForEachClient(visit); } - std::vector< size_t > + std::vector RelayConnectedRelays(); - std::vector< llarp::RouterContact > + std::vector GetRelayRCs(); - std::vector< llarp_main * > relays; - std::vector< llarp_main * > clients; + std::vector relays; + std::vector clients; - std::vector< std::thread > routerMainThreads; + std::vector routerMainThreads; std::mutex eventQueueMutex; - std::deque< RouterEventPtr > eventQueue; + std::deque eventQueue; }; } // namespace tooling diff --git a/llarp/util/aligned.hpp b/llarp/util/aligned.hpp index ce9503438..199003871 100644 --- a/llarp/util/aligned.hpp +++ b/llarp/util/aligned.hpp @@ -27,7 +27,7 @@ extern "C" namespace llarp { /// aligned buffer that is sz bytes long and aligns to the nearest Alignment - template < size_t sz > + template #ifdef _WIN32 // We CANNOT align on a 128-bit boundary, malloc(3C) on win32 // only hands out 64-bit aligned pointers @@ -36,13 +36,14 @@ namespace llarp struct alignas(std::max_align_t) AlignedBuffer #endif { - static_assert(sz >= 8, - "AlignedBuffer cannot be used with buffers smaller than 8 " - "bytes"); + static_assert( + sz >= 8, + "AlignedBuffer cannot be used with buffers smaller than 8 " + "bytes"); static constexpr size_t SIZE = sz; - using Data = std::array< byte_t, SIZE >; + using Data = std::array; AlignedBuffer() { @@ -74,10 +75,10 @@ namespace llarp } /// bitwise NOT - AlignedBuffer< sz > + AlignedBuffer operator~() const { - AlignedBuffer< sz > ret; + AlignedBuffer ret; std::transform(begin(), end(), ret.begin(), [](byte_t a) { return ~a; }); return ret; @@ -122,9 +123,8 @@ namespace llarp AlignedBuffer operator^(const AlignedBuffer& other) const { - AlignedBuffer< sz > ret; - std::transform(begin(), end(), other.begin(), ret.begin(), - std::bit_xor< byte_t >()); + AlignedBuffer ret; + std::transform(begin(), end(), other.begin(), ret.begin(), std::bit_xor()); return ret; } @@ -132,7 +132,7 @@ namespace llarp operator^=(const AlignedBuffer& other) { // Mutate in place instead. - for(size_t i = 0; i < sz; ++i) + for (size_t i = 0; i < sz; ++i) { m_data[i] ^= other.m_data[i]; } @@ -239,11 +239,11 @@ namespace llarp BDecode(llarp_buffer_t* buf) { llarp_buffer_t strbuf; - if(!bencode_read_string(buf, &strbuf)) + if (!bencode_read_string(buf, &strbuf)) { return false; } - if(strbuf.sz != sz) + if (strbuf.sz != sz) { llarp::LogError("bdecode buffer size missmatch ", strbuf.sz, "!=", sz); return false; diff --git a/llarp/util/bencode.cpp b/llarp/util/bencode.cpp index 5d2049048..23f906551 100644 --- a/llarp/util/bencode.cpp +++ b/llarp/util/bencode.cpp @@ -8,7 +8,7 @@ bool bencode_read_integer(struct llarp_buffer_t* buffer, uint64_t* result) { size_t len; - if(*buffer->cur != 'i') + if (*buffer->cur != 'i') return false; char numbuf[32]; @@ -16,7 +16,7 @@ bencode_read_integer(struct llarp_buffer_t* buffer, uint64_t* result) buffer->cur++; len = buffer->read_until('e', (byte_t*)numbuf, sizeof(numbuf) - 1); - if(!len) + if (!len) { return false; } @@ -24,7 +24,7 @@ bencode_read_integer(struct llarp_buffer_t* buffer, uint64_t* result) buffer->cur++; numbuf[len] = '\0'; - if(result) + if (result) *result = std::strtoull(numbuf, nullptr, 10); return true; } @@ -35,12 +35,12 @@ bencode_read_string(llarp_buffer_t* buffer, llarp_buffer_t* result) char numbuf[10]; size_t len = buffer->read_until(':', (byte_t*)numbuf, sizeof(numbuf) - 1); - if(!len) + if (!len) return false; - numbuf[len] = '\0'; + numbuf[len] = '\0'; const int num = atoi(numbuf); - if(num < 0) + if (num < 0) { return false; } @@ -50,15 +50,15 @@ bencode_read_string(llarp_buffer_t* buffer, llarp_buffer_t* result) buffer->cur++; len = buffer->size_left(); - if(len < slen) + if (len < slen) { return false; } - if(result) + if (result) { result->base = buffer->cur; - result->cur = buffer->cur; - result->sz = slen; + result->cur = buffer->cur; + result->sz = slen; } buffer->cur += slen; return true; @@ -67,18 +67,17 @@ bencode_read_string(llarp_buffer_t* buffer, llarp_buffer_t* result) bool bencode_write_bytestring(llarp_buffer_t* buff, const void* data, size_t sz) { - if(!buff->writef("%zu:", sz)) + if (!buff->writef("%zu:", sz)) { return false; } - return buff->write(reinterpret_cast< const char* >(data), - reinterpret_cast< const char* >(data) + sz); + return buff->write(reinterpret_cast(data), reinterpret_cast(data) + sz); } bool bencode_write_uint64(llarp_buffer_t* buff, uint64_t i) { - if(!buff->writef("i%" PRIu64, i)) + if (!buff->writef("i%" PRIu64, i)) { return false; } @@ -91,14 +90,14 @@ bencode_write_uint64(llarp_buffer_t* buff, uint64_t i) bool bencode_discard(llarp_buffer_t* buf) { - if(buf->size_left() == 0) + if (buf->size_left() == 0) return true; - switch(*buf->cur) + switch (*buf->cur) { case 'l': return llarp::bencode_read_list( [](llarp_buffer_t* buffer, bool more) -> bool { - if(more) + if (more) { return bencode_discard(buffer); } @@ -110,7 +109,7 @@ bencode_discard(llarp_buffer_t* buf) case 'd': return llarp::bencode_read_dict( [](llarp_buffer_t* buffer, llarp_buffer_t* key) -> bool { - if(key) + if (key) return bencode_discard(buffer); return true; }, @@ -132,10 +131,9 @@ bencode_discard(llarp_buffer_t* buf) } bool -bencode_write_uint64_entry(llarp_buffer_t* buff, const void* name, size_t sz, - uint64_t i) +bencode_write_uint64_entry(llarp_buffer_t* buff, const void* name, size_t sz, uint64_t i) { - if(!bencode_write_bytestring(buff, name, sz)) + if (!bencode_write_bytestring(buff, name, sz)) return false; return bencode_write_uint64(buff, i); diff --git a/llarp/util/bencode.h b/llarp/util/bencode.h index 4caac8dcf..07a612338 100644 --- a/llarp/util/bencode.h +++ b/llarp/util/bencode.h @@ -31,8 +31,7 @@ bencode_write_uint64(llarp_buffer_t* buff, uint64_t i); /// Write a dictionary entry with a uint64_t value bool -bencode_write_uint64_entry(llarp_buffer_t* buff, const void* name, size_t sz, - uint64_t i); +bencode_write_uint64_entry(llarp_buffer_t* buff, const void* name, size_t sz, uint64_t i); bool bencode_start_list(llarp_buffer_t* buff); diff --git a/llarp/util/bencode.hpp b/llarp/util/bencode.hpp index 8b0a74538..360570ce2 100644 --- a/llarp/util/bencode.hpp +++ b/llarp/util/bencode.hpp @@ -13,18 +13,17 @@ namespace llarp { - template < typename List_t > + template bool BEncodeReadList(List_t& result, llarp_buffer_t* buf); inline bool BEncodeWriteDictMsgType(llarp_buffer_t* buf, const char* k, const char* t) { - return bencode_write_bytestring(buf, k, 1) - && bencode_write_bytestring(buf, t, 1); + return bencode_write_bytestring(buf, k, 1) && bencode_write_bytestring(buf, t, 1); } - template < typename Obj_t > + template bool BEncodeWriteDictString(const char* k, const Obj_t& str, llarp_buffer_t* buf) { @@ -32,28 +31,28 @@ namespace llarp && bencode_write_bytestring(buf, str.data(), str.size()); } - template < typename Obj_t > + template bool BEncodeWriteDictEntry(const char* k, const Obj_t& o, llarp_buffer_t* buf) { return bencode_write_bytestring(buf, k, 1) && o.BEncode(buf); } - template < typename Int_t > + template bool BEncodeWriteDictInt(const char* k, const Int_t& i, llarp_buffer_t* buf) { return bencode_write_bytestring(buf, k, 1) && bencode_write_uint64(buf, i); } - template < typename List_t > + template bool - BEncodeMaybeReadDictList(const char* k, List_t& item, bool& read, - const llarp_buffer_t& key, llarp_buffer_t* buf) + BEncodeMaybeReadDictList( + const char* k, List_t& item, bool& read, const llarp_buffer_t& key, llarp_buffer_t* buf) { - if(key == k) + if (key == k) { - if(!BEncodeReadList(item, buf)) + if (!BEncodeReadList(item, buf)) { return false; } @@ -62,17 +61,16 @@ namespace llarp return true; } - template < typename Item_t > + template bool - BEncodeMaybeReadDictEntry(const char* k, Item_t& item, bool& read, - const llarp_buffer_t& key, llarp_buffer_t* buf) + BEncodeMaybeReadDictEntry( + const char* k, Item_t& item, bool& read, const llarp_buffer_t& key, llarp_buffer_t* buf) { - if(key == k) + if (key == k) { - if(!item.BDecode(buf)) + if (!item.BDecode(buf)) { - llarp::LogWarnTag("llarp/bencode.hpp", "failed to decode key ", k, - " for entry in dict"); + llarp::LogWarnTag("llarp/bencode.hpp", "failed to decode key ", k, " for entry in dict"); return false; } @@ -81,22 +79,21 @@ namespace llarp return true; } - template < typename Int_t > + template bool - BEncodeMaybeReadDictInt(const char* k, Int_t& i, bool& read, - const llarp_buffer_t& key, llarp_buffer_t* buf) + BEncodeMaybeReadDictInt( + const char* k, Int_t& i, bool& read, const llarp_buffer_t& key, llarp_buffer_t* buf) { - if(key == k) + if (key == k) { uint64_t read_i; - if(!bencode_read_integer(buf, &read_i)) + if (!bencode_read_integer(buf, &read_i)) { - llarp::LogWarnTag("llarp/BEncode.hpp", "failed to decode key ", k, - " for integer in dict"); + llarp::LogWarnTag("llarp/BEncode.hpp", "failed to decode key ", k, " for integer in dict"); return false; } - i = Int_t(read_i); + i = Int_t(read_i); read = true; } return true; @@ -104,88 +101,91 @@ namespace llarp /// If the key matches, reads in the version and ensures that it equals the /// expected version - template < typename Item_t > + template bool - BEncodeMaybeVerifyVersion(const char* k, Item_t& item, uint64_t expect, - bool& read, const llarp_buffer_t& key, - llarp_buffer_t* buf) + BEncodeMaybeVerifyVersion( + const char* k, + Item_t& item, + uint64_t expect, + bool& read, + const llarp_buffer_t& key, + llarp_buffer_t* buf) { - if(key == k) + if (key == k) { - if(!bencode_read_integer(buf, &item)) + if (!bencode_read_integer(buf, &item)) return false; read = item == expect; } return true; } - template < typename List_t > + template bool - BEncodeWriteDictBEncodeList(const char* k, const List_t& l, - llarp_buffer_t* buf) + BEncodeWriteDictBEncodeList(const char* k, const List_t& l, llarp_buffer_t* buf) { - if(!bencode_write_bytestring(buf, k, 1)) + if (!bencode_write_bytestring(buf, k, 1)) return false; - if(!bencode_start_list(buf)) + if (!bencode_start_list(buf)) return false; - for(const auto& item : l) - if(!item->BEncode(buf)) + for (const auto& item : l) + if (!item->BEncode(buf)) return false; return bencode_end(buf); } - template < typename Array > + template bool BEncodeWriteDictArray(const char* k, const Array& array, llarp_buffer_t* buf) { - if(!bencode_write_bytestring(buf, k, 1)) + if (!bencode_write_bytestring(buf, k, 1)) return false; - if(!bencode_start_list(buf)) + if (!bencode_start_list(buf)) return false; - for(size_t idx = 0; idx < array.size(); ++idx) - if(!array[idx].BEncode(buf)) + for (size_t idx = 0; idx < array.size(); ++idx) + if (!array[idx].BEncode(buf)) return false; return bencode_end(buf); } - template < typename Iter > + template bool BEncodeWriteList(Iter itr, Iter end, llarp_buffer_t* buf) { - if(!bencode_start_list(buf)) + if (!bencode_start_list(buf)) return false; - while(itr != end) - if(!itr->BEncode(buf)) + while (itr != end) + if (!itr->BEncode(buf)) return false; else ++itr; return bencode_end(buf); } - template < typename Sink > + template bool bencode_read_dict(Sink&& sink, llarp_buffer_t* buffer) { - if(buffer->size_left() < 2) // minimum case is 'de' + if (buffer->size_left() < 2) // minimum case is 'de' return false; - if(*buffer->cur != 'd') // ensure is a dictionary + if (*buffer->cur != 'd') // ensure is a dictionary return false; buffer->cur++; - while(buffer->size_left() && *buffer->cur != 'e') + while (buffer->size_left() && *buffer->cur != 'e') { llarp_buffer_t strbuf; // temporary buffer for current element - if(bencode_read_string(buffer, &strbuf)) + if (bencode_read_string(buffer, &strbuf)) { - if(!sink(buffer, &strbuf)) // check for early abort + if (!sink(buffer, &strbuf)) // check for early abort return false; } else return false; } - if(*buffer->cur != 'e') + if (*buffer->cur != 'e') { llarp::LogWarn("reading dict not ending on 'e'"); // make sure we're at dictionary end @@ -195,61 +195,60 @@ namespace llarp return sink(buffer, nullptr); } - template < typename Sink > + template bool bencode_decode_dict(Sink&& sink, llarp_buffer_t* buff) { return bencode_read_dict( [&](llarp_buffer_t* buffer, llarp_buffer_t* key) { - if(key == nullptr) + if (key == nullptr) return true; - if(sink.DecodeKey(*key, buffer)) + if (sink.DecodeKey(*key, buffer)) return true; - llarp::LogWarnTag("llarp/bencode.hpp", "undefined key '", *key->cur, - "' for entry in dict"); + llarp::LogWarnTag( + "llarp/bencode.hpp", "undefined key '", *key->cur, "' for entry in dict"); return false; }, buff); } - template < typename Sink > + template bool bencode_read_list(Sink&& sink, llarp_buffer_t* buffer) { - if(buffer->size_left() < 2) // minimum case is 'le' + if (buffer->size_left() < 2) // minimum case is 'le' return false; - if(*buffer->cur != 'l') // ensure is a list + if (*buffer->cur != 'l') // ensure is a list { - llarp::LogWarn("bencode::bencode_read_list - expecting list got ", - *buffer->cur); + llarp::LogWarn("bencode::bencode_read_list - expecting list got ", *buffer->cur); return false; } buffer->cur++; - while(buffer->size_left() && *buffer->cur != 'e') + while (buffer->size_left() && *buffer->cur != 'e') { - if(!sink(buffer, true)) // check for early abort + if (!sink(buffer, true)) // check for early abort return false; } - if(*buffer->cur != 'e') // make sure we're at a list end + if (*buffer->cur != 'e') // make sure we're at a list end return false; buffer->cur++; return sink(buffer, false); } - template < typename Array > + template bool BEncodeReadArray(Array& array, llarp_buffer_t* buf) { size_t idx = 0; return bencode_read_list( [&array, &idx](llarp_buffer_t* buffer, bool has) { - if(has) + if (has) { - if(idx >= array.size()) + if (idx >= array.size()) return false; - if(!array[idx++].BDecode(buffer)) + if (!array[idx++].BDecode(buffer)) return false; } return true; @@ -257,15 +256,15 @@ namespace llarp buf); } - template < typename List_t > + template bool BEncodeReadList(List_t& result, llarp_buffer_t* buf) { return bencode_read_list( [&result](llarp_buffer_t* buffer, bool has) { - if(has) + if (has) { - if(!result.emplace(result.end())->BDecode(buffer)) + if (!result.emplace(result.end())->BDecode(buffer)) { return false; } @@ -275,36 +274,35 @@ namespace llarp buf); } - template < typename List_t > + template bool BEncodeWriteDictList(const char* k, List_t& list, llarp_buffer_t* buf) { - return bencode_write_bytestring(buf, k, 1) - && BEncodeWriteList(list.begin(), list.end(), buf); + return bencode_write_bytestring(buf, k, 1) && BEncodeWriteList(list.begin(), list.end(), buf); } - template < size_t bufsz, typename T > + template void Dump(const T& val) { - std::array< byte_t, bufsz > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(val.BEncode(&buf)) + if (val.BEncode(&buf)) { - llarp::DumpBuffer< decltype(buf), 128 >(buf); + llarp::DumpBuffer(buf); } } /// read entire file and decode its contents into t - template < typename T > + template bool BDecodeReadFile(const char* fpath, T& t) { - std::vector< byte_t > ptr; + std::vector ptr; { std::ifstream f; f.open(fpath); - if(!f.is_open()) + if (!f.is_open()) { return false; } @@ -319,15 +317,15 @@ namespace llarp } /// read entire file and decode its contents into t - template < typename T > + template bool BDecodeReadFromFile(const char* fpath, T& t) { - std::vector< byte_t > ptr; + std::vector ptr; { std::ifstream f; f.open(fpath); - if(!f.is_open()) + if (!f.is_open()) { return false; } @@ -339,7 +337,7 @@ namespace llarp } llarp_buffer_t buf(ptr); auto result = bencode_decode_dict(t, &buf); - if(!result) + if (!result) { LogError("BDecodeReadFromFile() failed for file ", fpath, " contents:"); DumpBuffer(buf); @@ -348,23 +346,22 @@ namespace llarp } /// bencode and write to file - template < typename T, size_t bufsz > + template bool BEncodeWriteFile(const char* fpath, const T& t) { - std::array< byte_t, bufsz > tmp; + std::array tmp; llarp_buffer_t buf(tmp); - if(!t.BEncode(&buf)) + if (!t.BEncode(&buf)) return false; buf.sz = buf.cur - buf.base; { const fs::path path = std::string(fpath); - auto optional_f = - llarp::util::OpenFileStream< std::ofstream >(path, std::ios::binary); - if(!optional_f) + auto optional_f = llarp::util::OpenFileStream(path, std::ios::binary); + if (!optional_f) return false; auto& f = optional_f.value(); - if(!f.is_open()) + if (!f.is_open()) return false; f.write((char*)buf.base, buf.sz); } @@ -375,15 +372,15 @@ namespace llarp /// set v to parsed value if found /// this call rewinds the buffer unconditionally before return /// returns false only if there was - template < typename Int_t > + template bool BEncodeSeekDictVersion(Int_t& v, llarp_buffer_t* buf, const byte_t k) { const auto ret = bencode_read_dict( [&v, k](llarp_buffer_t* buffer, llarp_buffer_t* key) -> bool { - if(key == nullptr) + if (key == nullptr) return true; - if(key->sz == 1 && *key->cur == k) + if (key->sz == 1 && *key->cur == k) { return bencode_read_integer(buffer, &v); } diff --git a/llarp/util/bits.hpp b/llarp/util/bits.hpp index 169630db2..20a1e0987 100644 --- a/llarp/util/bits.hpp +++ b/llarp/util/bits.hpp @@ -12,15 +12,13 @@ namespace llarp { namespace bits { - template < typename Int_t > + template constexpr std::size_t count_bits(Int_t i) { - static_assert(std::is_integral< Int_t >::value, - "Int_t should be an integer"); - static_assert(std::is_unsigned< Int_t >::value, - "Int_t should be unsigned"); - return std::bitset< std::numeric_limits< Int_t >::digits >(i).count(); + static_assert(std::is_integral::value, "Int_t should be an integer"); + static_assert(std::is_unsigned::value, "Int_t should be unsigned"); + return std::bitset::digits>(i).count(); } constexpr std::size_t @@ -29,16 +27,15 @@ namespace llarp return count_bits(i.upper) + count_bits(i.lower); } - template < typename InputIt > + template constexpr std::size_t count_array_bits_impl(InputIt begin, InputIt end) { - return std::accumulate(begin, end, 0, [](auto acc, auto val) { - return acc + count_bits(val); - }); + return std::accumulate( + begin, end, 0, [](auto acc, auto val) { return acc + count_bits(val); }); } - template < typename T > + template constexpr std::size_t count_array_bits(const T& array) { diff --git a/llarp/util/buffer.cpp b/llarp/util/buffer.cpp index aca4fa1ae..6f6bb8831 100644 --- a/llarp/util/buffer.cpp +++ b/llarp/util/buffer.cpp @@ -8,7 +8,7 @@ size_t llarp_buffer_t::size_left() const { size_t diff = cur - base; - if(diff > sz) + if (diff > sz) { return 0; } @@ -23,11 +23,11 @@ llarp_buffer_t::writef(const char* fmt, ...) size_t toWrite = size_left(); va_list args; va_start(args, fmt); - written = vsnprintf(reinterpret_cast< char* >(cur), toWrite, fmt, args); + written = vsnprintf(reinterpret_cast(cur), toWrite, fmt, args); va_end(args); - if(written <= 0) + if (written <= 0) return false; - if(toWrite < static_cast< size_t >(written)) + if (toWrite < static_cast(written)) return false; cur += written; return true; @@ -36,7 +36,7 @@ llarp_buffer_t::writef(const char* fmt, ...) bool llarp_buffer_t::put_uint16(uint16_t i) { - if(size_left() < sizeof(uint16_t)) + if (size_left() < sizeof(uint16_t)) return false; htobe16buf(cur, i); cur += sizeof(uint16_t); @@ -46,7 +46,7 @@ llarp_buffer_t::put_uint16(uint16_t i) bool llarp_buffer_t::put_uint64(uint64_t i) { - if(size_left() < sizeof(uint64_t)) + if (size_left() < sizeof(uint64_t)) return false; htobe64buf(cur, i); cur += sizeof(uint64_t); @@ -56,7 +56,7 @@ llarp_buffer_t::put_uint64(uint64_t i) bool llarp_buffer_t::put_uint32(uint32_t i) { - if(size_left() < sizeof(uint32_t)) + if (size_left() < sizeof(uint32_t)) return false; htobe32buf(cur, i); cur += sizeof(uint32_t); @@ -66,7 +66,7 @@ llarp_buffer_t::put_uint32(uint32_t i) bool llarp_buffer_t::read_uint16(uint16_t& i) { - if(size_left() < sizeof(uint16_t)) + if (size_left() < sizeof(uint16_t)) return false; i = bufbe16toh(cur); cur += sizeof(uint16_t); @@ -76,7 +76,7 @@ llarp_buffer_t::read_uint16(uint16_t& i) bool llarp_buffer_t::read_uint32(uint32_t& i) { - if(size_left() < sizeof(uint32_t)) + if (size_left() < sizeof(uint32_t)) return false; i = bufbe32toh(cur); cur += sizeof(uint32_t); @@ -86,7 +86,7 @@ llarp_buffer_t::read_uint32(uint32_t& i) bool llarp_buffer_t::read_uint64(uint64_t& i) { - if(size_left() < sizeof(uint64_t)) + if (size_left() < sizeof(uint64_t)) return false; i = bufbe64toh(cur); cur += sizeof(uint64_t); @@ -99,7 +99,7 @@ llarp_buffer_t::read_until(char delim, byte_t* result, size_t resultsize) size_t read = 0; // do the bound check first, to avoid over running - while((cur != base + sz) && *cur != delim && resultsize) + while ((cur != base + sz) && *cur != delim && resultsize) { *result = *cur; cur++; @@ -108,7 +108,7 @@ llarp_buffer_t::read_until(char delim, byte_t* result, size_t resultsize) read++; } - if(size_left()) + if (size_left()) return read; return 0; @@ -118,10 +118,9 @@ bool operator==(const llarp_buffer_t& buff, const char* str) { ManagedBuffer copy{buff}; - while(*str - && copy.underlying.cur != (copy.underlying.base + copy.underlying.sz)) + while (*str && copy.underlying.cur != (copy.underlying.base + copy.underlying.sz)) { - if(*copy.underlying.cur != *str) + if (*copy.underlying.cur != *str) return false; copy.underlying.cur++; str++; diff --git a/llarp/util/buffer.hpp b/llarp/util/buffer.hpp index e9a635378..60c244354 100644 --- a/llarp/util/buffer.hpp +++ b/llarp/util/buffer.hpp @@ -64,9 +64,9 @@ struct ManagedBuffer; struct llarp_buffer_t { /// starting memory address - byte_t *base{nullptr}; + byte_t* base{nullptr}; /// memory address of stream position - byte_t *cur{nullptr}; + byte_t* cur{nullptr}; /// max size of buffer size_t sz{0}; @@ -77,38 +77,35 @@ struct llarp_buffer_t llarp_buffer_t() = default; - llarp_buffer_t(byte_t *b, byte_t *c, size_t s) : base(b), cur(c), sz(s) + llarp_buffer_t(byte_t* b, byte_t* c, size_t s) : base(b), cur(c), sz(s) { } - llarp_buffer_t(const ManagedBuffer &) = delete; - llarp_buffer_t(ManagedBuffer &&) = delete; + llarp_buffer_t(const ManagedBuffer&) = delete; + llarp_buffer_t(ManagedBuffer&&) = delete; - template < typename T > - llarp_buffer_t(T *buf, size_t _sz) - : base(reinterpret_cast< byte_t * >(buf)), cur(base), sz(_sz) + template + llarp_buffer_t(T* buf, size_t _sz) : base(reinterpret_cast(buf)), cur(base), sz(_sz) { } - template < typename T > - llarp_buffer_t(const T *buf, size_t _sz) - : base(reinterpret_cast< byte_t * >(const_cast< T * >(buf))) - , cur(base) - , sz(_sz) + template + llarp_buffer_t(const T* buf, size_t _sz) + : base(reinterpret_cast(const_cast(buf))), cur(base), sz(_sz) { } /** initialize llarp_buffer_t from container */ - template < typename T > - llarp_buffer_t(T &t) : base(t.data()), cur(t.data()), sz(t.size()) + template + llarp_buffer_t(T& t) : base(t.data()), cur(t.data()), sz(t.size()) { // use data over the first element to "enforce" the container used has // contiguous memory. (Note this isn't required by the standard, but a // reasonable test on most standard library implementations). } - template < typename T > - llarp_buffer_t(const T &t) : llarp_buffer_t(t.data(), t.size()) + template + llarp_buffer_t(const T& t) : llarp_buffer_t(t.data(), t.size()) { } @@ -122,25 +119,24 @@ struct llarp_buffer_t size_t size_left() const; - template < typename OutputIt > + template bool read_into(OutputIt begin, OutputIt end); - template < typename InputIt > + template bool write(InputIt begin, InputIt end); #ifndef _WIN32 bool - writef(const char *fmt, ...) __attribute__((format(printf, 2, 3))); + writef(const char* fmt, ...) __attribute__((format(printf, 2, 3))); #elif defined(__MINGW64__) || defined(__MINGW32__) bool - writef(const char *fmt, ...) - __attribute__((__format__(__MINGW_PRINTF_FORMAT, 2, 3))); + writef(const char* fmt, ...) __attribute__((__format__(__MINGW_PRINTF_FORMAT, 2, 3))); #else bool - writef(const char *fmt, ...); + writef(const char* fmt, ...); #endif bool @@ -152,31 +148,31 @@ struct llarp_buffer_t put_uint64(uint64_t i); bool - read_uint16(uint16_t &i); + read_uint16(uint16_t& i); bool - read_uint32(uint32_t &i); + read_uint32(uint32_t& i); bool - read_uint64(uint64_t &i); + read_uint64(uint64_t& i); size_t - read_until(char delim, byte_t *result, size_t resultlen); + read_until(char delim, byte_t* result, size_t resultlen); private: friend struct ManagedBuffer; - llarp_buffer_t(const llarp_buffer_t &) = default; - llarp_buffer_t(llarp_buffer_t &&) = default; + llarp_buffer_t(const llarp_buffer_t&) = default; + llarp_buffer_t(llarp_buffer_t&&) = default; }; bool -operator==(const llarp_buffer_t &buff, const char *data); +operator==(const llarp_buffer_t& buff, const char* data); -template < typename OutputIt > +template bool llarp_buffer_t::read_into(OutputIt begin, OutputIt end) { auto dist = std::distance(begin, end); - if(static_cast< decltype(dist) >(size_left()) >= dist) + if (static_cast(size_left()) >= dist) { std::copy_n(cur, dist, begin); cur += dist; @@ -185,12 +181,12 @@ llarp_buffer_t::read_into(OutputIt begin, OutputIt end) return false; } -template < typename InputIt > +template bool llarp_buffer_t::write(InputIt begin, InputIt end) { auto dist = std::distance(begin, end); - if(static_cast< decltype(dist) >(size_left()) >= dist) + if (static_cast(size_left()) >= dist) { cur = std::copy(begin, end, cur); return true; @@ -207,14 +203,14 @@ struct ManagedBuffer ManagedBuffer() = delete; - explicit ManagedBuffer(const llarp_buffer_t &b) : underlying(b) + explicit ManagedBuffer(const llarp_buffer_t& b) : underlying(b) { } - ManagedBuffer(ManagedBuffer &&) = default; - ManagedBuffer(const ManagedBuffer &) = default; + ManagedBuffer(ManagedBuffer&&) = default; + ManagedBuffer(const ManagedBuffer&) = default; - operator const llarp_buffer_t &() const + operator const llarp_buffer_t&() const { return underlying; } diff --git a/llarp/util/codel.hpp b/llarp/util/codel.hpp index 5580548bb..4addc6ffe 100644 --- a/llarp/util/codel.hpp +++ b/llarp/util/codel.hpp @@ -26,10 +26,15 @@ namespace llarp } }; - template < typename T, typename GetTime, typename PutTime, typename Compare, - typename GetNow = GetNowSyscall, typename Mutex_t = util::Mutex, - typename Lock_t = std::lock_guard< Mutex_t >, - size_t MaxSize = 1024 > + template < + typename T, + typename GetTime, + typename PutTime, + typename Compare, + typename GetNow = GetNowSyscall, + typename Mutex_t = util::Mutex, + typename Lock_t = std::lock_guard, + size_t MaxSize = 1024> struct CoDelQueue { CoDelQueue(std::string name, PutTime put, GetNow now) @@ -47,116 +52,114 @@ namespace llarp return m_QueueIdx; } - template < typename... Args > + template bool - EmplaceIf(std::function< bool(T&) > pred, Args&&... args) - EXCLUDES(m_QueueMutex) + EmplaceIf(std::function pred, Args&&... args) EXCLUDES(m_QueueMutex) { Lock_t lock(m_QueueMutex); - if(m_QueueIdx == MaxSize) + if (m_QueueIdx == MaxSize) return false; T* t = &m_Queue[m_QueueIdx]; - new(t) T(std::forward< Args >(args)...); - if(!pred(*t)) + new (t) T(std::forward(args)...); + if (!pred(*t)) { t->~T(); return false; } _putTime(m_Queue[m_QueueIdx]); - if(firstPut == 0s) + if (firstPut == 0s) firstPut = _getTime(m_Queue[m_QueueIdx]); ++m_QueueIdx; return true; } - template < typename... Args > + template void Emplace(Args&&... args) EXCLUDES(m_QueueMutex) { Lock_t lock(m_QueueMutex); - if(m_QueueIdx == MaxSize) + if (m_QueueIdx == MaxSize) return; T* t = &m_Queue[m_QueueIdx]; - new(t) T(std::forward< Args >(args)...); + new (t) T(std::forward(args)...); _putTime(m_Queue[m_QueueIdx]); - if(firstPut == 0s) + if (firstPut == 0s) firstPut = _getTime(m_Queue[m_QueueIdx]); ++m_QueueIdx; } - template < typename Visit > + template void Process(Visit v) { return Process(v, [](T&) -> bool { return false; }); } - template < typename Visit, typename Filter > + template void Process(Visit visitor, Filter f) EXCLUDES(m_QueueMutex) { - llarp_time_t lowest = std::numeric_limits< llarp_time_t >::max(); - if(_getNow() < nextTickAt) + llarp_time_t lowest = std::numeric_limits::max(); + if (_getNow() < nextTickAt) return; // llarp::LogInfo("CoDelQueue::Process - start at ", start); Lock_t lock(m_QueueMutex); auto start = firstPut; - if(m_QueueIdx == 1) + if (m_QueueIdx == 1) { visitor(m_Queue[0]); T* t = &m_Queue[0]; t->~T(); m_QueueIdx = 0; - firstPut = 0s; + firstPut = 0s; return; } size_t idx = 0; - while(m_QueueIdx) + while (m_QueueIdx) { llarp::LogDebug(m_name, " - queue has ", m_QueueIdx); T* item = &m_Queue[idx++]; - if(f(*item)) + if (f(*item)) break; --m_QueueIdx; const llarp_time_t dlt = start - _getTime(*item); // llarp::LogInfo("CoDelQueue::Process - dlt ", dlt); lowest = std::min(dlt, lowest); - if(m_QueueIdx == 0) + if (m_QueueIdx == 0) { // llarp::LogInfo("CoDelQueue::Process - single item: lowest ", // lowest, " dropMs: ", dropMs); - if(lowest > dropMs) + if (lowest > dropMs) { item->~T(); - nextTickInterval += - initialIntervalMs / uint64_t(std::sqrt(++dropNum)); - firstPut = 0s; + nextTickInterval += initialIntervalMs / uint64_t(std::sqrt(++dropNum)); + firstPut = 0s; nextTickAt = start + nextTickInterval; return; } nextTickInterval = initialIntervalMs; - dropNum = 0; + dropNum = 0; } visitor(*item); item->~T(); } - firstPut = 0s; + firstPut = 0s; nextTickAt = start + nextTickInterval; } const llarp_time_t initialIntervalMs = 5ms; - const llarp_time_t dropMs = 100ms; - llarp_time_t firstPut = 0s; - size_t dropNum = 0; - llarp_time_t nextTickInterval = initialIntervalMs; - llarp_time_t nextTickAt = 0s; + const llarp_time_t dropMs = 100ms; + llarp_time_t firstPut = 0s; + size_t dropNum = 0; + llarp_time_t nextTickInterval = initialIntervalMs; + llarp_time_t nextTickAt = 0s; Mutex_t m_QueueMutex; size_t m_QueueIdx GUARDED_BY(m_QueueMutex); - std::array< T, MaxSize > m_Queue GUARDED_BY(m_QueueMutex); + std::array m_Queue GUARDED_BY(m_QueueMutex); std::string m_name; GetTime _getTime; PutTime _putTime; diff --git a/llarp/util/compare_ptr.hpp b/llarp/util/compare_ptr.hpp index 7078291fc..8c5141f36 100644 --- a/llarp/util/compare_ptr.hpp +++ b/llarp/util/compare_ptr.hpp @@ -5,13 +5,13 @@ namespace llarp { /// type for comparing smart pointer's managed values - template < typename Ptr_t, typename Compare = std::less<> > + template > struct ComparePtr { bool operator()(const Ptr_t& left, const Ptr_t& right) const { - if(left && right) + if (left && right) return Compare()(*left, *right); return Compare()(left, right); diff --git a/llarp/util/copy_or_nullptr.hpp b/llarp/util/copy_or_nullptr.hpp index 1a17a96df..752075407 100644 --- a/llarp/util/copy_or_nullptr.hpp +++ b/llarp/util/copy_or_nullptr.hpp @@ -2,12 +2,12 @@ #define LLARP_UTIL_COPY_OR_NULLPTR_HPP #include -template < typename T > -static constexpr std::unique_ptr< T > -copy_or_nullptr(const std::unique_ptr< T >& other) +template +static constexpr std::unique_ptr +copy_or_nullptr(const std::unique_ptr& other) { - if(other) - return std::make_unique< T >(*other); + if (other) + return std::make_unique(*other); return nullptr; } diff --git a/llarp/util/decaying_hashset.hpp b/llarp/util/decaying_hashset.hpp index 3ca0d0df7..4778e175c 100644 --- a/llarp/util/decaying_hashset.hpp +++ b/llarp/util/decaying_hashset.hpp @@ -8,13 +8,12 @@ namespace llarp { namespace util { - template < typename Val_t, typename Hash_t = typename Val_t::Hash > + template struct DecayingHashSet { using Time_t = std::chrono::milliseconds; - DecayingHashSet(Time_t cacheInterval = 5s) - : m_CacheInterval(cacheInterval) + DecayingHashSet(Time_t cacheInterval = 5s) : m_CacheInterval(cacheInterval) { } /// determine if we have v contained in our decaying hashset @@ -29,7 +28,7 @@ namespace llarp bool Insert(const Val_t& v, Time_t now = 0s) { - if(now == 0s) + if (now == 0s) now = llarp::time_now_ms(); return m_Values.emplace(v, now).second; } @@ -38,13 +37,13 @@ namespace llarp void Decay(Time_t now = 0s) { - if(now == 0s) + if (now == 0s) now = llarp::time_now_ms(); auto itr = m_Values.begin(); - while(itr != m_Values.end()) + while (itr != m_Values.end()) { - if((m_CacheInterval + itr->second) <= now) + if ((m_CacheInterval + itr->second) <= now) itr = m_Values.erase(itr); else ++itr; @@ -65,7 +64,7 @@ namespace llarp private: Time_t m_CacheInterval; - std::unordered_map< Val_t, Time_t, Hash_t > m_Values; + std::unordered_map m_Values; }; } // namespace util } // namespace llarp diff --git a/llarp/util/encode.cpp b/llarp/util/encode.cpp index 92efa65e2..a8de4cfdf 100644 --- a/llarp/util/encode.cpp +++ b/llarp/util/encode.cpp @@ -7,11 +7,11 @@ namespace llarp int char2int(char input) { - if(input >= '0' && input <= '9') + if (input >= '0' && input <= '9') return input - '0'; - if(input >= 'A' && input <= 'F') + if (input >= 'A' && input <= 'F') return input - 'A' + 10; - if(input >= 'a' && input <= 'f') + if (input >= 'a' && input <= 'f') return input - 'a' + 10; return 0; } diff --git a/llarp/util/encode.hpp b/llarp/util/encode.hpp index 472007f61..58cd1f09e 100644 --- a/llarp/util/encode.hpp +++ b/llarp/util/encode.hpp @@ -8,25 +8,22 @@ namespace llarp { // from https://en.wikipedia.org/wiki/Base32#z-base-32 - static const char zbase32_alpha[] = {'y', 'b', 'n', 'd', 'r', 'f', 'g', '8', - 'e', 'j', 'k', 'm', 'c', 'p', 'q', 'x', - 'o', 't', '1', 'u', 'w', 'i', 's', 'z', - 'a', '3', '4', '5', 'h', '7', '6', '9'}; - - static const std::unordered_map< char, uint8_t > zbase32_reverse_alpha = { - {'y', 0}, {'b', 1}, {'n', 2}, {'d', 3}, {'r', 4}, {'f', 5}, - {'g', 6}, {'8', 7}, {'e', 8}, {'j', 9}, {'k', 10}, {'m', 11}, - {'c', 12}, {'p', 13}, {'q', 14}, {'x', 15}, {'o', 16}, {'t', 17}, - {'1', 18}, {'u', 19}, {'w', 20}, {'i', 21}, {'s', 22}, {'z', 23}, - {'a', 24}, {'3', 25}, {'4', 26}, {'5', 27}, {'h', 28}, {'7', 29}, - {'6', 30}, {'9', 31}}; - - template < int a, int b > + static const char zbase32_alpha[] = {'y', 'b', 'n', 'd', 'r', 'f', 'g', '8', 'e', 'j', 'k', + 'm', 'c', 'p', 'q', 'x', 'o', 't', '1', 'u', 'w', 'i', + 's', 'z', 'a', '3', '4', '5', 'h', '7', '6', '9'}; + + static const std::unordered_map zbase32_reverse_alpha = { + {'y', 0}, {'b', 1}, {'n', 2}, {'d', 3}, {'r', 4}, {'f', 5}, {'g', 6}, {'8', 7}, + {'e', 8}, {'j', 9}, {'k', 10}, {'m', 11}, {'c', 12}, {'p', 13}, {'q', 14}, {'x', 15}, + {'o', 16}, {'t', 17}, {'1', 18}, {'u', 19}, {'w', 20}, {'i', 21}, {'s', 22}, {'z', 23}, + {'a', 24}, {'3', 25}, {'4', 26}, {'5', 27}, {'h', 28}, {'7', 29}, {'6', 30}, {'9', 31}}; + + template static size_t DecodeSize(size_t sz) { auto d = div(sz, a); - if(d.rem) + if (d.rem) d.quot++; return b * d.quot; } @@ -34,24 +31,24 @@ namespace llarp static size_t Base32DecodeSize(size_t sz) { - return DecodeSize< 5, 8 >(sz); + return DecodeSize<5, 8>(sz); } - template < typename Stack, typename V > + template bool Base32Decode(const Stack& stack, V& value) { int tmp = 0, bits = 0; - size_t idx = 0; - const size_t len = Base32DecodeSize(value.size()); + size_t idx = 0; + const size_t len = Base32DecodeSize(value.size()); const size_t outLen = value.size(); - for(size_t i = 0; i < len; i++) + for (size_t i = 0; i < len; i++) { char ch = stack[i]; - if(ch) + if (ch) { auto itr = zbase32_reverse_alpha.find(ch); - if(itr == zbase32_reverse_alpha.end()) + if (itr == zbase32_reverse_alpha.end()) return false; ch = itr->second; } @@ -61,9 +58,9 @@ namespace llarp } tmp |= ch; bits += 5; - if(bits >= 8) + if (bits >= 8) { - if(idx >= outLen) + if (idx >= outLen) return false; value[idx] = tmp >> (bits - 8); bits -= 8; @@ -75,19 +72,19 @@ namespace llarp } /// adapted from i2pd - template < typename V, typename Stack > + template const char* Base32Encode(const V& value, Stack& stack) { size_t ret = 0, pos = 1; - int bits = 8; + int bits = 8; uint32_t tmp = value[0]; - size_t len = value.size(); - while(ret < sizeof(stack) && (bits > 0 || pos < len)) + size_t len = value.size(); + while (ret < sizeof(stack) && (bits > 0 || pos < len)) { - if(bits < 5) + if (bits < 5) { - if(pos < len) + if (pos < len) { tmp <<= 8; tmp |= value[pos] & 0xFF; @@ -103,7 +100,7 @@ namespace llarp bits -= 5; int ind = (tmp >> bits) & 0x1F; - if(ret < sizeof(stack)) + if (ret < sizeof(stack)) { stack[ret] = zbase32_alpha[ind]; ret++; @@ -118,17 +115,17 @@ namespace llarp /// null terminate /// return pointer to base of stack buffer on success otherwise returns /// nullptr - template < typename V, typename Stack > + template const char* HexEncode(const V& value, Stack& stack) { size_t idx = 0; - char* ptr = &stack[0]; - char* end = ptr + sizeof(stack); - while(idx < value.size()) + char* ptr = &stack[0]; + char* end = ptr + sizeof(stack); + while (idx < value.size()) { auto wrote = snprintf(ptr, end - ptr, "%.2x", value[idx]); - if(wrote == -1) + if (wrote == -1) return nullptr; ptr += wrote; idx++; @@ -140,11 +137,11 @@ namespace llarp int char2int(char input); - template < typename OutputIt > + template bool HexDecode(const char* src, OutputIt target, size_t sz) { - while(*src && src[1] && sz) + while (*src && src[1] && sz) { *(target++) = char2int(*src) * 16 + char2int(src[1]); src += 2; @@ -154,24 +151,23 @@ namespace llarp } static const char base64_table[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; - template < typename OStream_t > + template void Base64Encode(OStream_t& out, const uint8_t* src, size_t len) { - size_t i = 0; - size_t j = 0; + size_t i = 0; + size_t j = 0; uint8_t buf[4] = {0}; uint8_t tmp[3] = {0}; - while(len--) + while (len--) { tmp[i++] = *(src++); - if(3 == i) + if (3 == i) { buf[0] = (tmp[0] & 0xfc) >> 2; buf[1] = ((tmp[0] & 0x03) << 4) + ((tmp[1] & 0xf0) >> 4); @@ -179,7 +175,7 @@ namespace llarp buf[3] = tmp[2] & 0x3f; // encode - for(i = 0; i < 4; ++i) + for (i = 0; i < 4; ++i) { out << base64_table[buf[i]]; } @@ -189,10 +185,10 @@ namespace llarp } // remainder - if(i > 0) + if (i > 0) { // fill `tmp' with `\0' at most 3 times - for(j = i; j < 3; ++j) + for (j = i; j < 3; ++j) { tmp[j] = 0; } @@ -202,13 +198,13 @@ namespace llarp buf[1] = ((tmp[0] & 0x03) << 4) + ((tmp[1] & 0xf0) >> 4); buf[2] = ((tmp[1] & 0x0f) << 2) + ((tmp[2] & 0xc0) >> 6); buf[3] = tmp[2] & 0x3f; - for(j = 0; (j < i + 1); ++j) + for (j = 0; (j < i + 1); ++j) { out << base64_table[buf[j]]; } // pad - while((i++ < 3)) + while ((i++ < 3)) { out << '='; } diff --git a/llarp/util/endian.hpp b/llarp/util/endian.hpp index f2b5a1cef..3ff140386 100644 --- a/llarp/util/endian.hpp +++ b/llarp/util/endian.hpp @@ -97,18 +97,18 @@ be64toh(uint64_t big64); #endif -#if !defined(__LITTLE_ENDIAN__) && defined(__BYTE_ORDER) \ - && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN +#if !defined(__LITTLE_ENDIAN__) && defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) \ + && __BYTE_ORDER == __LITTLE_ENDIAN #define __LITTLE_ENDIAN__ -#elif !defined(__BIG_ENDIAN__) && defined(__BYTE_ORDER) \ - && defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN +#elif !defined(__BIG_ENDIAN__) && defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) \ + && __BYTE_ORDER == __BIG_ENDIAN #define __BIG_ENDIAN__ #elif !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) #error "Error: don't know which endian this is" #endif inline uint16_t -buf16toh(const void *buf) +buf16toh(const void* buf) { uint16_t b16; memcpy(&b16, buf, sizeof(uint16_t)); @@ -116,7 +116,7 @@ buf16toh(const void *buf) } inline uint32_t -buf32toh(const void *buf) +buf32toh(const void* buf) { uint32_t b32; memcpy(&b32, buf, sizeof(uint32_t)); @@ -124,7 +124,7 @@ buf32toh(const void *buf) } inline uint64_t -buf64toh(const void *buf) +buf64toh(const void* buf) { uint64_t b64; memcpy(&b64, buf, sizeof(uint64_t)); @@ -132,73 +132,73 @@ buf64toh(const void *buf) } inline uint16_t -bufbe16toh(const void *buf) +bufbe16toh(const void* buf) { return be16toh(buf16toh(buf)); } inline uint32_t -bufbe32toh(const void *buf) +bufbe32toh(const void* buf) { return be32toh(buf32toh(buf)); } inline uint64_t -bufbe64toh(const void *buf) +bufbe64toh(const void* buf) { return be64toh(buf64toh(buf)); } inline void -htobuf16(void *buf, uint16_t b16) +htobuf16(void* buf, uint16_t b16) { memcpy(buf, &b16, sizeof(uint16_t)); } inline void -htobuf32(void *buf, uint32_t b32) +htobuf32(void* buf, uint32_t b32) { memcpy(buf, &b32, sizeof(uint32_t)); } inline void -htobuf64(void *buf, uint64_t b64) +htobuf64(void* buf, uint64_t b64) { memcpy(buf, &b64, sizeof(uint64_t)); } inline void -htobe16buf(void *buf, uint16_t big16) +htobe16buf(void* buf, uint16_t big16) { htobuf16(buf, htobe16(big16)); } inline void -htobe32buf(void *buf, uint32_t big32) +htobe32buf(void* buf, uint32_t big32) { htobuf32(buf, htobe32(big32)); } inline void -htobe64buf(void *buf, uint64_t big64) +htobe64buf(void* buf, uint64_t big64) { htobuf64(buf, htobe64(big64)); } inline void -htole16buf(void *buf, uint16_t big16) +htole16buf(void* buf, uint16_t big16) { htobuf16(buf, htole16(big16)); } inline void -htole32buf(void *buf, uint32_t big32) +htole32buf(void* buf, uint32_t big32) { htobuf32(buf, htole32(big32)); } inline void -htole64buf(void *buf, uint64_t big64) +htole64buf(void* buf, uint64_t big64) { htobuf64(buf, htole64(big64)); } diff --git a/llarp/util/fs.cpp b/llarp/util/fs.cpp index e0c2b5657..30aa148e2 100644 --- a/llarp/util/fs.cpp +++ b/llarp/util/fs.cpp @@ -18,8 +18,8 @@ namespace cpp17 namespace filesystem { #ifdef LOKINET_USE_CPPBACKPORT - const fs::perms active_bits(fs::perms::all | fs::perms::set_uid - | fs::perms::set_gid | fs::perms::sticky_bit); + const fs::perms active_bits( + fs::perms::all | fs::perms::set_uid | fs::perms::set_gid | fs::perms::sticky_bit); inline mode_t mode_cast(fs::perms prms) { @@ -43,17 +43,15 @@ namespace cpp17 // "http://man7.org/linux/man-pages/man7/symlink.7.html" // - See the fchmodat() Linux man page: // "http://man7.org/linux/man-pages/man2/fchmodat.2.html" -#if defined(AT_FDCWD) && defined(AT_SYMLINK_NOFOLLOW) \ - && !(defined(__SUNPRO_CC) || defined(__sun) || defined(sun)) \ - && !(defined(linux) || defined(__linux) || defined(__linux__)) \ - && !(defined(__MAC_OS_X_VERSION_MIN_REQUIRED) \ - && __MAC_OS_X_VERSION_MIN_REQUIRED < 101000) \ - && !(defined(__IPHONE_OS_VERSION_MIN_REQUIRED) \ - && __IPHONE_OS_VERSION_MIN_REQUIRED < 80000) \ +#if defined(AT_FDCWD) && defined(AT_SYMLINK_NOFOLLOW) \ + && !(defined(__SUNPRO_CC) || defined(__sun) || defined(sun)) \ + && !(defined(linux) || defined(__linux) || defined(__linux__)) \ + && !(defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101000) \ + && !(defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 80000) \ && !(defined(__QNX__) && (_NTO_VERSION <= 700)) - if(::fchmodat(AT_FDCWD, p.c_str(), mode_cast(prms), 0)) + if (::fchmodat(AT_FDCWD, p.c_str(), mode_cast(prms), 0)) #else // fallback if fchmodat() not supported - if(::chmod(p.c_str(), mode_cast(prms))) + if (::chmod(p.c_str(), mode_cast(prms))) #endif { const int err = errno; @@ -73,49 +71,49 @@ namespace llarp { int e = errno; errno = 0; - return std::make_error_code(static_cast< std::errc >(e)); + return std::make_error_code(static_cast(e)); } error_code_t EnsurePrivateFile(fs::path pathname) { - errno = 0; + errno = 0; error_code_t ec = errno_error(); - const auto str = pathname.string(); - if(fs::exists(pathname, ec)) // file exists + const auto str = pathname.string(); + if (fs::exists(pathname, ec)) // file exists { - auto st = fs::status(pathname); + auto st = fs::status(pathname); auto perms = st.permissions(); - if((perms & fs::perms::others_exec) != fs::perms::none) + if ((perms & fs::perms::others_exec) != fs::perms::none) perms = perms ^ fs::perms::others_exec; - if((perms & fs::perms::others_write) != fs::perms::none) + if ((perms & fs::perms::others_write) != fs::perms::none) perms = perms ^ fs::perms::others_write; - if((perms & fs::perms::others_write) != fs::perms::none) + if ((perms & fs::perms::others_write) != fs::perms::none) perms = perms ^ fs::perms::others_write; - if((perms & fs::perms::group_read) != fs::perms::none) + if ((perms & fs::perms::group_read) != fs::perms::none) perms = perms ^ fs::perms::group_read; - if((perms & fs::perms::others_read) != fs::perms::none) + if ((perms & fs::perms::others_read) != fs::perms::none) perms = perms ^ fs::perms::others_read; - if((perms & fs::perms::owner_exec) != fs::perms::none) + if ((perms & fs::perms::owner_exec) != fs::perms::none) perms = perms ^ fs::perms::owner_exec; fs::permissions(pathname, perms, ec); - if(ec) + if (ec) llarp::LogError("failed to set permissions on ", pathname); } else // file is not there { - errno = 0; + errno = 0; int fd = ::open(str.c_str(), O_RDWR | O_CREAT, 0600); - ec = errno_error(); - if(fd != -1) + ec = errno_error(); + if (fd != -1) { ::close(fd); } } #ifndef WIN32 - if(ec) + if (ec) llarp::LogError("failed to ensure ", str, ", ", ec.message()); return ec; #else diff --git a/llarp/util/fs.hpp b/llarp/util/fs.hpp index 772f728aa..40ab0a052 100644 --- a/llarp/util/fs.hpp +++ b/llarp/util/fs.hpp @@ -31,45 +31,45 @@ namespace llarp /// open a stream to a file and ensure it exists before open /// sets any permissions on creation - template < typename T > - nonstd::optional< T > + template + nonstd::optional OpenFileStream(fs::path pathname, std::ios::openmode mode) { - if(EnsurePrivateFile(pathname)) + if (EnsurePrivateFile(pathname)) return {}; std::string f = pathname.string(); return T{pathname, mode}; } - using PathVisitor = std::function< bool(const fs::path &) >; - using PathIter = std::function< void(const fs::path &, PathVisitor) >; + using PathVisitor = std::function; + using PathIter = std::function; - static PathIter IterDir = [](const fs::path &path, PathVisitor visit) { + static PathIter IterDir = [](const fs::path& path, PathVisitor visit) { #ifdef _MSC_VER - for(auto &p : fs::directory_iterator(path)) + for (auto& p : fs::directory_iterator(path)) { - if(!visit(p.path())) + if (!visit(p.path())) { break; } } #else - DIR *d = opendir(path.string().c_str()); - if(d == nullptr) + DIR* d = opendir(path.string().c_str()); + if (d == nullptr) return; - struct dirent *ent = nullptr; + struct dirent* ent = nullptr; do { ent = readdir(d); - if(!ent) + if (!ent) break; - if(ent->d_name[0] == '.') + if (ent->d_name[0] == '.') continue; fs::path p = path / fs::path(ent->d_name); - if(!visit(p)) + if (!visit(p)) break; - } while(ent); + } while (ent); closedir(d); #endif }; diff --git a/llarp/util/json.cpp b/llarp/util/json.cpp index ef569c1cf..7b0145d57 100644 --- a/llarp/util/json.cpp +++ b/llarp/util/json.cpp @@ -11,21 +11,20 @@ namespace llarp { struct NlohmannJSONParser : public IParser { - NlohmannJSONParser(size_t contentSize) - : m_Buf(contentSize + 1), m_Offset(0) + NlohmannJSONParser(size_t contentSize) : m_Buf(contentSize + 1), m_Offset(0) { assert(contentSize != 0); } - std::vector< char > m_Buf; + std::vector m_Buf; size_t m_Offset; bool FeedData(const char* buf, size_t sz) override { - if(sz == 0) + if (sz == 0) return true; - if(m_Offset + sz > m_Buf.size() - 1) + if (m_Offset + sz > m_Buf.size() - 1) return false; std::copy_n(buf, sz, m_Buf.data() + m_Offset); m_Offset += sz; @@ -36,7 +35,7 @@ namespace llarp Result Parse(nlohmann::json& obj) const override { - if(m_Offset < m_Buf.size() - 1) + if (m_Offset < m_Buf.size() - 1) return eNeedData; try @@ -44,7 +43,7 @@ namespace llarp obj = nlohmann::json::parse(m_Buf.data()); return eDone; } - catch(const nlohmann::json::exception&) + catch (const nlohmann::json::exception&) { return eParseError; } diff --git a/llarp/util/logging/android_logger.cpp b/llarp/util/logging/android_logger.cpp index 2757cb746..53c772139 100644 --- a/llarp/util/logging/android_logger.cpp +++ b/llarp/util/logging/android_logger.cpp @@ -7,11 +7,10 @@ namespace llarp { void - AndroidLogStream::PreLog(std::stringstream& ss, LogLevel lvl, - const char* fname, int lineno, - const std::string&) const + AndroidLogStream::PreLog( + std::stringstream& ss, LogLevel lvl, const char* fname, int lineno, const std::string&) const { - switch(lvl) + switch (lvl) { case eLogNone: return; @@ -30,8 +29,8 @@ namespace llarp break; } - ss << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname - << ":" << lineno << "\t"; + ss << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname << ":" << lineno + << "\t"; } void @@ -48,7 +47,7 @@ namespace llarp { std::string str("lokinet|"); str += tag; - switch(lvl) + switch (lvl) { case eLogTrace: __android_log_write(ANDROID_LOG_TRACE, str.c_str(), msg.c_str()); diff --git a/llarp/util/logging/android_logger.hpp b/llarp/util/logging/android_logger.hpp index ddde13b5d..9c9cc87ee 100644 --- a/llarp/util/logging/android_logger.hpp +++ b/llarp/util/logging/android_logger.hpp @@ -10,8 +10,12 @@ namespace llarp struct AndroidLogStream : public ILogStream { void - PreLog(std::stringstream& s, LogLevel lvl, const char* fname, int lineno, - const std::string& nodename) const override; + PreLog( + std::stringstream& s, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const override; void Print(LogLevel lvl, const char* filename, const std::string& msg) override; diff --git a/llarp/util/logging/file_logger.cpp b/llarp/util/logging/file_logger.cpp index 7e055b27d..b41d20553 100644 --- a/llarp/util/logging/file_logger.cpp +++ b/llarp/util/logging/file_logger.cpp @@ -6,27 +6,26 @@ namespace llarp { void - FileLogStream::Flush(Lines_t *lines, FILE *const f) + FileLogStream::Flush(Lines_t* lines, FILE* const f) { bool wrote_stuff = false; do { auto maybe_line = lines->tryPopFront(); - if(not maybe_line.has_value()) + if (not maybe_line.has_value()) break; - const auto &line = maybe_line.value(); - if(fprintf(f, "%s\n", line.c_str()) >= 0) + const auto& line = maybe_line.value(); + if (fprintf(f, "%s\n", line.c_str()) >= 0) wrote_stuff = true; - } while(true); + } while (true); - if(wrote_stuff) + if (wrote_stuff) fflush(f); } // namespace - FileLogStream::FileLogStream(std::shared_ptr< thread::ThreadPool > disk, - FILE *f, llarp_time_t flushInterval, - bool closeFile) + FileLogStream::FileLogStream( + std::shared_ptr disk, FILE* f, llarp_time_t flushInterval, bool closeFile) : m_Lines(1024 * 8) , m_Disk(std::move(disk)) , m_File(f) @@ -42,44 +41,52 @@ namespace llarp do { auto line = m_Lines.tryPopFront(); - if(not line.has_value()) + if (not line.has_value()) break; - } while(true); + } while (true); fflush(m_File); - if(m_Close) + if (m_Close) fclose(m_File); } bool FileLogStream::ShouldFlush(llarp_time_t now) const { - if(m_Lines.full()) + if (m_Lines.full()) return true; - if(m_LastFlush >= now) + if (m_LastFlush >= now) return false; const auto dlt = now - m_LastFlush; return dlt >= m_FlushInterval; } void - FileLogStream::PreLog(std::stringstream &ss, LogLevel lvl, const char *fname, - int lineno, const std::string &nodename) const + FileLogStream::PreLog( + std::stringstream& ss, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const { ss << "[" << LogLevelToString(lvl) << "] "; ss << "[" << nodename << "]" - << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname - << ":" << lineno << "\t"; + << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname << ":" << lineno + << "\t"; } void - FileLogStream::Print(LogLevel, const char *, const std::string &msg) + FileLogStream::Print(LogLevel, const char*, const std::string& msg) { m_Lines.pushBack(msg); } void - FileLogStream::AppendLog(LogLevel lvl, const char *fname, int lineno, - const std::string &nodename, const std::string msg) + FileLogStream::AppendLog( + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename, + const std::string msg) { ILogStream::AppendLog(lvl, fname, lineno, nodename, msg); Tick(llarp::time_now_ms()); @@ -88,15 +95,15 @@ namespace llarp void FileLogStream::Tick(llarp_time_t now) { - if(ShouldFlush(now)) + if (ShouldFlush(now)) FlushLinesToDisk(now); } void FileLogStream::FlushLinesToDisk(llarp_time_t now) { - FILE *const f = m_File; - auto lines = &m_Lines; + FILE* const f = m_File; + auto lines = &m_Lines; m_Disk->addJob([f, lines]() { Flush(lines, f); }); m_LastFlush = now; } diff --git a/llarp/util/logging/file_logger.hpp b/llarp/util/logging/file_logger.hpp index 5d7ab2736..7d30fb646 100644 --- a/llarp/util/logging/file_logger.hpp +++ b/llarp/util/logging/file_logger.hpp @@ -14,14 +14,21 @@ namespace llarp /// flushable file based log stream struct FileLogStream : public ILogStream { - FileLogStream(std::shared_ptr< thread::ThreadPool > disk, FILE* f, - llarp_time_t flushInterval, bool closefile = true); + FileLogStream( + std::shared_ptr disk, + FILE* f, + llarp_time_t flushInterval, + bool closefile = true); ~FileLogStream() override; void - PreLog(std::stringstream& out, LogLevel lvl, const char* fname, int lineno, - const std::string& nodename) const override; + PreLog( + std::stringstream& out, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const override; void Print(LogLevel, const char*, const std::string& msg) override; @@ -33,10 +40,14 @@ namespace llarp PostLog(std::stringstream&) const override{}; void - AppendLog(LogLevel lvl, const char* fname, int lineno, - const std::string& nodename, const std::string msg) override; + AppendLog( + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename, + const std::string msg) override; - using Lines_t = thread::Queue< std::string >; + using Lines_t = thread::Queue; protected: Lines_t m_Lines; @@ -51,7 +62,7 @@ namespace llarp void FlushLinesToDisk(llarp_time_t now); - std::shared_ptr< thread::ThreadPool > m_Disk; + std::shared_ptr m_Disk; FILE* const m_File; const llarp_time_t m_FlushInterval; llarp_time_t m_LastFlush = 0s; diff --git a/llarp/util/logging/json_logger.cpp b/llarp/util/logging/json_logger.cpp index a1c187eba..dbae769a9 100644 --- a/llarp/util/logging/json_logger.cpp +++ b/llarp/util/logging/json_logger.cpp @@ -4,16 +4,20 @@ namespace llarp { void - JSONLogStream::AppendLog(LogLevel lvl, const char* fname, int lineno, - const std::string& nodename, const std::string msg) + JSONLogStream::AppendLog( + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename, + const std::string msg) { json::Object obj; - obj["time"] = to_json(llarp::time_now_ms()); + obj["time"] = to_json(llarp::time_now_ms()); obj["nickname"] = nodename; - obj["file"] = std::string(fname); - obj["line"] = lineno; - obj["level"] = LogLevelToString(lvl); - obj["message"] = msg; + obj["file"] = std::string(fname); + obj["line"] = lineno; + obj["level"] = LogLevelToString(lvl); + obj["message"] = msg; m_Lines.pushBack(obj.dump()); } diff --git a/llarp/util/logging/json_logger.hpp b/llarp/util/logging/json_logger.hpp index 978400df3..cd5526b39 100644 --- a/llarp/util/logging/json_logger.hpp +++ b/llarp/util/logging/json_logger.hpp @@ -7,15 +7,22 @@ namespace llarp { struct JSONLogStream : public FileLogStream { - JSONLogStream(std::shared_ptr< thread::ThreadPool > disk, FILE* f, - llarp_time_t flushInterval, bool closeFile) + JSONLogStream( + std::shared_ptr disk, + FILE* f, + llarp_time_t flushInterval, + bool closeFile) : FileLogStream(disk, f, flushInterval, closeFile) { } void - AppendLog(LogLevel lvl, const char* fname, int lineno, - const std::string& nodename, const std::string msg) override; + AppendLog( + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename, + const std::string msg) override; }; } // namespace llarp diff --git a/llarp/util/logging/logger.cpp b/llarp/util/logging/logger.cpp index a313a304d..7518e790f 100644 --- a/llarp/util/logging/logger.cpp +++ b/llarp/util/logging/logger.cpp @@ -24,8 +24,7 @@ namespace llarp #endif LogContext::LogContext() - : logStream(std::make_unique< Stream_t >(_LOGSTREAM_INIT)) - , started(llarp::time_now_ms()) + : logStream(std::make_unique(_LOGSTREAM_INIT)), started(llarp::time_now_ms()) { } @@ -63,7 +62,7 @@ namespace llarp SetLogLevel(LogLevel lvl) { LogContext::Instance().curLevel = lvl; - if(lvl == eLogDebug) + if (lvl == eLogDebug) { LogContext::Instance().runtimeLevel = lvl; } diff --git a/llarp/util/logging/logger.hpp b/llarp/util/logging/logger.hpp index c0d2b99a5..e7d4f2318 100644 --- a/llarp/util/logging/logger.hpp +++ b/llarp/util/logging/logger.hpp @@ -83,7 +83,7 @@ namespace llarp struct LogContext { LogContext(); - LogLevel curLevel = eLogInfo; + LogLevel curLevel = eLogInfo; LogLevel startupLevel = eLogInfo; LogLevel runtimeLevel = eLogInfo; ILogStream_ptr logStream; @@ -105,7 +105,7 @@ namespace llarp SetLogLevel(LogLevel lvl); /** internal */ - template < typename... TArgs > + template inline static void #ifndef LOKINET_HIVE _Log(LogLevel lvl, const char* fname, int lineno, TArgs&&... args) noexcept @@ -116,10 +116,10 @@ namespace llarp /* nop out logging for hive mode for now */ #ifndef LOKINET_HIVE auto& log = LogContext::Instance(); - if(log.curLevel > lvl) + if (log.curLevel > lvl) return; std::stringstream ss; - LogAppend(ss, std::forward< TArgs >(args)...); + LogAppend(ss, std::forward(args)...); log.logStream->AppendLog(lvl, fname, lineno, log.nodeName, ss.str()); #endif } @@ -262,16 +262,11 @@ namespace llarp #define LogWarnTag(tag, ...) _Log(llarp::eLogWarn, tag, __LINE__, __VA_ARGS__) #define LogErrorTag(tag, ...) _Log(llarp::eLogError, tag, __LINE__, __VA_ARGS__) -#define LogTraceExplicit(tag, line, ...) \ - _Log(llarp::eLogTrace, tag, line, __VA_ARGS__) -#define LogDebugExplicit(tag, line, ...) \ - _Log(llarp::eLogDebug, tag, line, __VA_ARGS__) -#define LogInfoExplicit(tag, line, ...) \ - _Log(llarp::eLogInfo, tag, line __VA_ARGS__) -#define LogWarnExplicit(tag, line, ...) \ - _Log(llarp::eLogWarn, tag, line, __VA_ARGS__) -#define LogErrorExplicit(tag, line, ...) \ - _Log(llarp::eLogError, tag, line, __VA_ARGS__) +#define LogTraceExplicit(tag, line, ...) _Log(llarp::eLogTrace, tag, line, __VA_ARGS__) +#define LogDebugExplicit(tag, line, ...) _Log(llarp::eLogDebug, tag, line, __VA_ARGS__) +#define LogInfoExplicit(tag, line, ...) _Log(llarp::eLogInfo, tag, line __VA_ARGS__) +#define LogWarnExplicit(tag, line, ...) _Log(llarp::eLogWarn, tag, line, __VA_ARGS__) +#define LogErrorExplicit(tag, line, ...) _Log(llarp::eLogError, tag, line, __VA_ARGS__) #ifndef LOG_TAG #define LOG_TAG "default" diff --git a/llarp/util/logging/logger_internal.cpp b/llarp/util/logging/logger_internal.cpp index f53b61d89..9ca21213a 100644 --- a/llarp/util/logging/logger_internal.cpp +++ b/llarp/util/logging/logger_internal.cpp @@ -7,9 +7,8 @@ namespace llarp std::ostream& operator<<(std::ostream& out, const log_timestamp& ts) { - std::chrono::time_point< std::chrono::system_clock, - std::chrono::milliseconds > - now{std::chrono::milliseconds{ts.now}}; + std::chrono::time_point now{ + std::chrono::milliseconds{ts.now}}; return date::operator<<(out, now) << " UTC [+" << ts.delta << "]"; } } // namespace llarp diff --git a/llarp/util/logging/logger_internal.hpp b/llarp/util/logging/logger_internal.hpp index b502d2bc5..53e67ce6a 100644 --- a/llarp/util/logging/logger_internal.hpp +++ b/llarp/util/logging/logger_internal.hpp @@ -15,19 +15,19 @@ namespace llarp { } /** internal */ - template < typename TArg, typename... TArgs > + template void LogAppend(std::stringstream& ss, TArg&& arg, TArgs&&... args) noexcept { - ss << std::forward< TArg >(arg); - LogAppend(ss, std::forward< TArgs >(args)...); + ss << std::forward(arg); + LogAppend(ss, std::forward(args)...); } inline std::string thread_id_string() { auto tid = std::this_thread::get_id(); - std::hash< std::thread::id > h; + std::hash h; uint16_t id = h(tid) % 1000; #if defined(ANDROID) || defined(RPI) char buff[8] = {0}; diff --git a/llarp/util/logging/logger_syslog.hpp b/llarp/util/logging/logger_syslog.hpp index 378b84f1a..bf458bd66 100644 --- a/llarp/util/logging/logger_syslog.hpp +++ b/llarp/util/logging/logger_syslog.hpp @@ -9,8 +9,12 @@ namespace llarp struct SysLogStream : public ILogStream { void - PreLog(std::stringstream& s, LogLevel lvl, const char* fname, int lineno, - const std::string& nodename) const override; + PreLog( + std::stringstream& s, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const override; void Print(LogLevel lvl, const char* tag, const std::string& msg) override; diff --git a/llarp/util/logging/loglevel.cpp b/llarp/util/logging/loglevel.cpp index b55cf233b..5810a1e1e 100644 --- a/llarp/util/logging/loglevel.cpp +++ b/llarp/util/logging/loglevel.cpp @@ -7,7 +7,7 @@ namespace llarp std::string LogLevelToString(LogLevel lvl) { - switch(lvl) + switch (lvl) { case eLogTrace: return "TRC"; @@ -27,7 +27,7 @@ namespace llarp std::string LogLevelToName(LogLevel lvl) { - switch(lvl) + switch (lvl) { case eLogTrace: return "Trace"; @@ -46,18 +46,21 @@ namespace llarp } } - nonstd::optional< LogLevel > + nonstd::optional LogLevelFromString(std::string level) { - std::transform( - level.begin(), level.end(), level.begin(), - [](const unsigned char ch) -> char { return std::tolower(ch); }); - static const std::unordered_map< std::string, LogLevel > levels = { - {"trace", eLogTrace}, {"debug", eLogDebug}, {"info", eLogInfo}, - {"warn", eLogWarn}, {"error", eLogError}, {"none", eLogNone}}; + std::transform(level.begin(), level.end(), level.begin(), [](const unsigned char ch) -> char { + return std::tolower(ch); + }); + static const std::unordered_map levels = {{"trace", eLogTrace}, + {"debug", eLogDebug}, + {"info", eLogInfo}, + {"warn", eLogWarn}, + {"error", eLogError}, + {"none", eLogNone}}; const auto itr = levels.find(level); - if(itr == levels.end()) + if (itr == levels.end()) return {}; return itr->second; } diff --git a/llarp/util/logging/loglevel.hpp b/llarp/util/logging/loglevel.hpp index 75dbcdc39..24e393c4c 100644 --- a/llarp/util/logging/loglevel.hpp +++ b/llarp/util/logging/loglevel.hpp @@ -22,7 +22,7 @@ namespace llarp std::string LogLevelToName(LogLevel lvl); - nonstd::optional< LogLevel > + nonstd::optional LogLevelFromString(std::string level); } // namespace llarp diff --git a/llarp/util/logging/logstream.hpp b/llarp/util/logging/logstream.hpp index 949fd1835..46300d20d 100644 --- a/llarp/util/logging/logstream.hpp +++ b/llarp/util/logging/logstream.hpp @@ -16,8 +16,12 @@ namespace llarp virtual ~ILogStream() = default; virtual void - PreLog(std::stringstream& out, LogLevel lvl, const char* fname, int lineno, - const std::string& nodename) const = 0; + PreLog( + std::stringstream& out, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const = 0; virtual void Print(LogLevel lvl, const char* filename, const std::string& msg) = 0; @@ -26,8 +30,12 @@ namespace llarp PostLog(std::stringstream& out) const = 0; virtual void - AppendLog(LogLevel lvl, const char* fname, int lineno, - const std::string& nodename, const std::string msg) + AppendLog( + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename, + const std::string msg) { std::stringstream ss; PreLog(ss, lvl, fname, lineno, nodename); @@ -41,7 +49,7 @@ namespace llarp Tick(llarp_time_t now) = 0; }; - using ILogStream_ptr = std::unique_ptr< ILogStream >; + using ILogStream_ptr = std::unique_ptr; } // namespace llarp #endif diff --git a/llarp/util/logging/ostream_logger.cpp b/llarp/util/logging/ostream_logger.cpp index ba3b3d19e..d737f9954 100644 --- a/llarp/util/logging/ostream_logger.cpp +++ b/llarp/util/logging/ostream_logger.cpp @@ -9,13 +9,16 @@ namespace llarp } void - OStreamLogStream::PreLog(std::stringstream& ss, LogLevel lvl, - const char* fname, int lineno, - const std::string& nodename) const + OStreamLogStream::PreLog( + std::stringstream& ss, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const { - if(m_withColours) + if (m_withColours) { - switch(lvl) + switch (lvl) { case eLogNone: return; @@ -36,14 +39,14 @@ namespace llarp } ss << "[" << LogLevelToString(lvl) << "] "; ss << "[" << nodename << "]" - << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname - << ":" << lineno << "\t"; + << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname << ":" << lineno + << "\t"; } void OStreamLogStream::PostLog(std::stringstream& ss) const { - if(m_withColours) + if (m_withColours) ss << (char)27 << "[0;0m"; ss << std::endl; } diff --git a/llarp/util/logging/ostream_logger.hpp b/llarp/util/logging/ostream_logger.hpp index 0db9b89fc..ee878c96d 100644 --- a/llarp/util/logging/ostream_logger.hpp +++ b/llarp/util/logging/ostream_logger.hpp @@ -13,8 +13,12 @@ namespace llarp ~OStreamLogStream() override = default; void - PreLog(std::stringstream& s, LogLevel lvl, const char* fname, int lineno, - const std::string& nodename) const override; + PreLog( + std::stringstream& s, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const override; virtual void Print(LogLevel lvl, const char* tag, const std::string& msg) override; diff --git a/llarp/util/logging/syslog_logger.cpp b/llarp/util/logging/syslog_logger.cpp index c9ff0c45b..6bf02966f 100644 --- a/llarp/util/logging/syslog_logger.cpp +++ b/llarp/util/logging/syslog_logger.cpp @@ -7,19 +7,23 @@ namespace llarp { void - SysLogStream::PreLog(std::stringstream& ss, LogLevel lvl, const char* fname, - int lineno, const std::string& nodename) const + SysLogStream::PreLog( + std::stringstream& ss, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const { ss << "[" << LogLevelToString(lvl) << "] "; ss << "[" << nodename << "]" - << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname - << ":" << lineno << "\t"; + << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname << ":" << lineno + << "\t"; } void SysLogStream::Print(LogLevel lvl, const char*, const std::string& msg) { - switch(lvl) + switch (lvl) { case eLogNone: return; diff --git a/llarp/util/logging/win32_logger.cpp b/llarp/util/logging/win32_logger.cpp index 78cc5110b..8ed0d9bc4 100644 --- a/llarp/util/logging/win32_logger.cpp +++ b/llarp/util/logging/win32_logger.cpp @@ -7,8 +7,7 @@ static short old_attrs; namespace llarp { - Win32LogStream::Win32LogStream(std::ostream& out) - : OStreamLogStream(true, out), m_Out(out) + Win32LogStream::Win32LogStream(std::ostream& out) : OStreamLogStream(true, out), m_Out(out) { // Attempt to use ANSI escapes directly // if the modern console is active. @@ -20,17 +19,21 @@ namespace llarp // be able to get any of them individually mode_flags |= 0x0004 | 0x0008; BOOL t = SetConsoleMode(fd1, mode_flags); - if(!t) + if (!t) this->isConsoleModern = false; // fall back to setting colours manually } void - Win32LogStream::PreLog(std::stringstream& ss, LogLevel lvl, const char* fname, - int lineno, const std::string& nodename) const + Win32LogStream::PreLog( + std::stringstream& ss, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const { - if(!isConsoleModern) + if (!isConsoleModern) { - switch(lvl) + switch (lvl) { case eLogNone: break; @@ -51,8 +54,8 @@ namespace llarp break; } ss << "[" << nodename << "]" - << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname - << ":" << lineno << "\t"; + << "(" << thread_id_string() << ") " << log_timestamp() << " " << fname << ":" << lineno + << "\t"; } else OStreamLogStream::PreLog(ss, lvl, fname, lineno, nodename); @@ -61,7 +64,7 @@ namespace llarp void Win32LogStream::PostLog(std::stringstream& ss) const { - if(!isConsoleModern) + if (!isConsoleModern) ss << std::endl; else OStreamLogStream::PostLog(ss); @@ -70,19 +73,19 @@ namespace llarp void Win32LogStream::Print(LogLevel lvl, const char*, const std::string& msg) { - if(!isConsoleModern) + if (!isConsoleModern) { GetConsoleScreenBufferInfo(fd1, &consoleInfo); old_attrs = consoleInfo.wAttributes; - switch(lvl) + switch (lvl) { case eLogNone: break; case eLogTrace: case eLogDebug: - SetConsoleTextAttribute(fd1, - FOREGROUND_RED | FOREGROUND_GREEN - | FOREGROUND_BLUE); // low white on black + SetConsoleTextAttribute( + fd1, + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); // low white on black break; case eLogInfo: SetConsoleTextAttribute( @@ -91,23 +94,21 @@ namespace llarp | FOREGROUND_BLUE); // high white on black break; case eLogWarn: - SetConsoleTextAttribute(fd1, - FOREGROUND_RED | FOREGROUND_GREEN - | FOREGROUND_INTENSITY); // bright yellow + SetConsoleTextAttribute( + fd1, + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY); // bright yellow break; case eLogError: - SetConsoleTextAttribute( - fd1, FOREGROUND_RED | FOREGROUND_INTENSITY); // bright red + SetConsoleTextAttribute(fd1, FOREGROUND_RED | FOREGROUND_INTENSITY); // bright red break; } } m_Out << msg << std::flush; - if(!isConsoleModern) + if (!isConsoleModern) { - SetConsoleTextAttribute( - fd1, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); + SetConsoleTextAttribute(fd1, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } } diff --git a/llarp/util/logging/win32_logger.hpp b/llarp/util/logging/win32_logger.hpp index 852704c77..6a259458d 100644 --- a/llarp/util/logging/win32_logger.hpp +++ b/llarp/util/logging/win32_logger.hpp @@ -12,8 +12,12 @@ namespace llarp Win32LogStream(std::ostream& out); void - PreLog(std::stringstream& s, LogLevel lvl, const char* fname, int lineno, - const std::string& nodename) const override; + PreLog( + std::stringstream& s, + LogLevel lvl, + const char* fname, + int lineno, + const std::string& nodename) const override; void PostLog(std::stringstream& s) const override; @@ -26,8 +30,7 @@ namespace llarp private: std::ostream& m_Out; - bool isConsoleModern = - true; // qol fix so oldfag clients don't see ugly escapes + bool isConsoleModern = true; // qol fix so oldfag clients don't see ugly escapes HANDLE fd1 = GetStdHandle(STD_OUTPUT_HANDLE); }; diff --git a/llarp/util/lokinet_init.c b/llarp/util/lokinet_init.c index 34be28086..ea1892916 100644 --- a/llarp/util/lokinet_init.c +++ b/llarp/util/lokinet_init.c @@ -7,18 +7,18 @@ int Lokinet_INIT(void) { - static const char *(CDECL * pwine_get_version)(void); + static const char*(CDECL * pwine_get_version)(void); HMODULE hntdll = GetModuleHandle("ntdll.dll"); - if(hntdll) + if (hntdll) { - pwine_get_version = (void *)GetProcAddress(hntdll, "wine_get_version"); - if(pwine_get_version) + pwine_get_version = (void*)GetProcAddress(hntdll, "wine_get_version"); + if (pwine_get_version) { - static const char *text = + static const char* text = "dont run lokinet in wine like wtf man we support linux and pretty " "much every flavour of BSD, and even some flavours of unix system " "5.x.\nThis Program Will now crash lmao."; - static const char *title = "srsly fam wtf"; + static const char* title = "srsly fam wtf"; MessageBoxA(NULL, text, title, MB_ICONHAND); abort(); } diff --git a/llarp/util/mem.cpp b/llarp/util/mem.cpp index 12e721c48..e2641226b 100644 --- a/llarp/util/mem.cpp +++ b/llarp/util/mem.cpp @@ -5,10 +5,10 @@ namespace llarp { void - Zero(void *ptr, size_t sz) + Zero(void* ptr, size_t sz) { - auto *p = (uint8_t *)ptr; - while(sz--) + auto* p = (uint8_t*)ptr; + while (sz--) { *p = 0; ++p; @@ -17,19 +17,19 @@ namespace llarp } // namespace llarp void -llarp_mem_slab(struct llarp_alloc * /*mem*/, uint32_t * /*buf*/, size_t /*sz*/) +llarp_mem_slab(struct llarp_alloc* /*mem*/, uint32_t* /*buf*/, size_t /*sz*/) { // not implemented abort(); } bool -llarp_eq(const void *a, const void *b, size_t sz) +llarp_eq(const void* a, const void* b, size_t sz) { - bool result = true; - const auto *a_ptr = (const uint8_t *)a; - const auto *b_ptr = (const uint8_t *)b; - while(sz--) + bool result = true; + const auto* a_ptr = (const uint8_t*)a; + const auto* b_ptr = (const uint8_t*)b; + while (sz--) { result &= a_ptr[sz] == b_ptr[sz]; } diff --git a/llarp/util/mem.h b/llarp/util/mem.h index 313837038..af0918122 100644 --- a/llarp/util/mem.h +++ b/llarp/util/mem.h @@ -6,6 +6,6 @@ /** constant time memcmp */ bool -llarp_eq(const void *a, const void *b, size_t sz); +llarp_eq(const void* a, const void* b, size_t sz); #endif diff --git a/llarp/util/mem.hpp b/llarp/util/mem.hpp index 2944ee4fd..8ab179b8e 100644 --- a/llarp/util/mem.hpp +++ b/llarp/util/mem.hpp @@ -11,65 +11,65 @@ namespace llarp { void - Zero(void *ptr, size_t sz); + Zero(void* ptr, size_t sz); - template < typename T > + template void - dumphex(const uint8_t *t) + dumphex(const uint8_t* t) { size_t idx = 0; - while(idx < sizeof(T)) + while (idx < sizeof(T)) { printf("%.2x ", t[idx++]); - if(idx % 8 == 0) + if (idx % 8 == 0) printf("\n"); } } - template < typename T, size_t align = 128 > + template void - DumpBufferHex(const T &buff) + DumpBufferHex(const T& buff) { size_t idx = 0; printf("buffer of size %zu\n", buff.sz); - while(idx < buff.sz) + while (idx < buff.sz) { - if(buff.base + idx == buff.cur) + if (buff.base + idx == buff.cur) { #ifndef _WIN32 printf("%c[1;31m", 27); #endif } printf("%.2x", buff.base[idx]); - if(buff.base + idx == buff.cur) + if (buff.base + idx == buff.cur) { #ifndef _WIN32 printf("%c[0;0m", 27); #endif } ++idx; - if(idx % align == 0) + if (idx % align == 0) printf("\n"); } printf("\n"); fflush(stdout); } - template < typename T, size_t align = 128 > + template void - DumpBuffer(const T &buff) + DumpBuffer(const T& buff) { size_t idx = 0; printf("buffer of size %zu\n", buff.sz); - while(idx < buff.sz) + while (idx < buff.sz) { - if(buff.base + idx == buff.cur) + if (buff.base + idx == buff.cur) { #ifndef _WIN32 printf("%c[1;31m", 27); #endif } - if(std::isprint(buff.base[idx])) + if (std::isprint(buff.base[idx])) { printf("%c", buff.base[idx]); } @@ -77,14 +77,14 @@ namespace llarp { printf("."); } - if(buff.base + idx == buff.cur) + if (buff.base + idx == buff.cur) { #ifndef _WIN32 printf("%c[0;0m", 27); #endif } ++idx; - if(idx % align == 0) + if (idx % align == 0) printf("\n"); } printf("\n"); diff --git a/llarp/util/meta/memfn.hpp b/llarp/util/meta/memfn.hpp index c27e6cea8..8d9366cf5 100644 --- a/llarp/util/meta/memfn.hpp +++ b/llarp/util/meta/memfn.hpp @@ -12,56 +12,60 @@ namespace llarp // Wraps a member function and instance into a callable object that invokes // the method (non-const overload). template < - typename Return, typename Class, typename Derived, typename... Arg, - typename = - std::enable_if_t< std::is_base_of< Class, Derived >::value > > + typename Return, + typename Class, + typename Derived, + typename... Arg, + typename = std::enable_if_t::value>> auto memFn(Return (Class::*f)(Arg...), Derived* self) { - return [f, self](Arg... args) -> Return { - return (self->*f)(std::forward< Arg >(args)...); - }; + return [f, self](Arg... args) -> Return { return (self->*f)(std::forward(args)...); }; } // Wraps a member function and instance into a lambda that invokes the // method (const overload). template < - typename Return, typename Class, typename Derived, typename... Arg, - typename = - std::enable_if_t< std::is_base_of< Class, Derived >::value > > + typename Return, + typename Class, + typename Derived, + typename... Arg, + typename = std::enable_if_t::value>> auto memFn(Return (Class::*f)(Arg...) const, const Derived* self) { - return [f, self](Arg... args) -> Return { - return (self->*f)(std::forward< Arg >(args)...); - }; + return [f, self](Arg... args) -> Return { return (self->*f)(std::forward(args)...); }; } // Wraps a member function and shared pointer to an instance into a lambda // that invokes the method. template < - typename Return, typename Class, typename Derived, typename... Arg, - typename = - std::enable_if_t< std::is_base_of< Class, Derived >::value > > + typename Return, + typename Class, + typename Derived, + typename... Arg, + typename = std::enable_if_t::value>> auto - memFn(Return (Class::*f)(Arg...), std::shared_ptr< Derived > self) + memFn(Return (Class::*f)(Arg...), std::shared_ptr self) { return [f, self = std::move(self)](Arg... args) -> Return { - return (self.get()->*f)(std::forward< Arg >(args)...); + return (self.get()->*f)(std::forward(args)...); }; } // Wraps a member function and shared pointer to an instance into a lambda // that invokes the method (const method overload). template < - typename Return, typename Class, typename Derived, typename... Arg, - typename = - std::enable_if_t< std::is_base_of< Class, Derived >::value > > + typename Return, + typename Class, + typename Derived, + typename... Arg, + typename = std::enable_if_t::value>> auto - memFn(Return (Class::*f)(Arg...) const, std::shared_ptr< Derived > self) + memFn(Return (Class::*f)(Arg...) const, std::shared_ptr self) { return [f, self = std::move(self)](Arg... args) -> Return { - return (self.get()->*f)(std::forward< Arg >(args)...); + return (self.get()->*f)(std::forward(args)...); }; } diff --git a/llarp/util/meta/traits.hpp b/llarp/util/meta/traits.hpp index af1e28ef6..bfed577f7 100644 --- a/llarp/util/meta/traits.hpp +++ b/llarp/util/meta/traits.hpp @@ -14,13 +14,13 @@ namespace llarp using std::void_t; #else /// C++17 void_t backport - template < typename... Ts > + template struct void_t_impl { using type = void; }; - template < typename... Ts > - using void_t = typename void_t_impl< Ts... >::type; + template + using void_t = typename void_t_impl::type; #endif /// Represents the empty type @@ -29,14 +29,14 @@ namespace llarp }; /// Int tag - template < size_t N > + template struct Tag { char arr[N + 1]; }; /// Type trait representing whether a type is pointer-like - template < typename T, typename _ = void > + template struct is_pointy : public std::false_type { }; @@ -45,16 +45,14 @@ namespace llarp // - has element_type typedef // - has dereference operator // - has arrow operator - template < typename T > - struct is_pointy< - T, - std::conditional_t< false, void_t< decltype(*std::declval< T >()) >, - void > > : public std::true_type + template + struct is_pointy())>, void>> + : public std::true_type { }; /// Type trait representing whether a type is an STL-style container - template < typename T, typename _ = void > + template struct is_container : public std::false_type { }; @@ -83,22 +81,22 @@ namespace llarp namespace Switch { - template < size_t Selector, typename... Types > + template struct Switch { using Type = Bottom; }; - template < typename T, typename... Types > - struct Switch< 0u, T, Types... > + template + struct Switch<0u, T, Types...> { using Type = T; }; - template < size_t Selector, typename Tn, typename... Types > - struct Switch< Selector, Tn, Types... > + template + struct Switch { - using Type = typename Switch< Selector - 1, Types... >::Type; + using Type = typename Switch::Type; }; } // namespace Switch @@ -108,18 +106,18 @@ namespace llarp /// This provides a way to do a compile-type dispatch based on type traits /// meta function which always returns false - template < typename > + template class False : public std::false_type { }; /// a case in the selection - template < template < typename... > class Trait = False > + template